unit(D3): slot materialization (headcount, call time)
Slot materialization (ARCHITECTURE §5.2): for each non-published instance, plan the seats planSlots() computes and upsert them on (service_instance_id, role_id, slot_index). onConflictDoNothing makes it idempotent; published weeks are skipped (owned by the publish flow). - src/domain/slots.ts: pure planSlots()/planSlotsForRole(); headcount fills slotIndex 1..N, call_time = start + offset (null if no offset). - src/domain/slots.test.ts: 5 tests (Audio headcount 2 -> 2 slots with correct call_time, clamp to 1, null offset, multi-role flatten). - src/db/slots.ts: materializeSlotsForInstance() + materializeSlots(). - src/app/api/dev/cron/slots/route.ts: GET drives the daily job. No schema change (slots unique index predates this unit; position_skills stays deferred to D5). Verified: draft instance + Audio headcount 2 -> 4 seats (Audio x2 + Livestream + Slides), Audio call_time 09:30 EST; re-run creates 0 rows. Seed restored to canonical 4 instances / 12 slots after testing.
This commit is contained in:
@@ -475,6 +475,33 @@ Build log for Media Team Hub. One unit per commit, top to bottom. Append after e
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
## D3 — Slot materialization (headcount, call time) — DONE 2026-11-18
|
||||||
|
|
||||||
|
**Scope (from BUILD-PLAN.md):** slot materialization from role requirements (headcount, call time). Done when: Audio headcount 2 creates 2 slots with correct call_time. ARCHITECTURE §5.2.
|
||||||
|
|
||||||
|
**Delivered:**
|
||||||
|
- `src/domain/slots.ts` — pure `planSlotsForRole(instanceStartsAt, role)` + `planSlots(instanceStartsAt, roles)`. A role with headcount N fills N seats (slotIndex 1..N); each seat's call_time is `instanceStartsAt + call_time_offset_minutes` (null when the role has no offset); headcount clamped to >= 1. No DB imports.
|
||||||
|
- `src/domain/slots.test.ts` — 5 tests named after the rule: Audio headcount 2 → 2 slots with correct call_time (11:00 EST − 90 min = 09:30 EST = 14:30 UTC), headcount clamped to 1, null call_time when offset null, multi-role flattening in role order.
|
||||||
|
- `src/db/slots.ts` — `materializeSlotsForInstance(serviceInstanceId, instanceStartsAt, roles)` upserts seats on `(service_instance_id, role_id, slot_index)` via `onConflictDoNothing`; `materializeSlots(now)` processes every non-published instance at/after `now` (published weeks are owned by the publish flow, so their slot set is left untouched per §5.1).
|
||||||
|
- `src/app/api/dev/cron/slots/route.ts` — GET `/api/dev/cron/slots` drives `materializeSlots()`; idempotent on re-run.
|
||||||
|
|
||||||
|
**No schema change, no migration.** The `slots` table already exists (A2) with the `(service_instance_id, role_id, slot_index)` unique index that makes materialization idempotent. `position_skills` (which drives conflict detection in D5) stays deferred.
|
||||||
|
|
||||||
|
**Verification (all exit 0):**
|
||||||
|
- `tsc --noEmit` ✓ · `eslint .` ✓ (0 problems) · `vitest run` ✓ (**129** total; D3 = 5) · `next build` ✓
|
||||||
|
- Runtime smoke test: draft instance + Audio headcount 2 → 4 seats (Audio×2 + Livestream×1 + Slides×1); Audio slots slot_index 1,2 with call_time 09:30 EST (14:30 UTC); re-run creates 0 rows (idempotent). Seed state restored to canonical 4 instances / 12 slots after testing.
|
||||||
|
|
||||||
|
**Decisions:**
|
||||||
|
- **Idempotency is one primitive again.** `onConflictDoNothing({ target: [service_instance_id, role_id, slot_index] })` returns only rows this run inserted, so `created` counts genuine additions and a re-run is a no-op that never disturbs an admin's assignment on an existing seat.
|
||||||
|
- **Published instances are skipped, not upserted.** §5.1 says slots are created for *new* instances and a published week's slot set is owned by the publish flow. `materializeSlots` filters `status != 'published'`, so re-running generation never rewrites a published week's seats.
|
||||||
|
- **call_time is a zoned offset, not a naive add.** `instanceStartsAt + offset` operates on the UTC instant, so a −90 min offset applied to a DST-safe start stays DST-safe (the stored UTC shifts with the wall clock, exactly as the seed does).
|
||||||
|
- **Headcount clamped to >= 1.** A role always produces at least one seat, so a zero/missing headcount can never silently drop a role from an instance.
|
||||||
|
- **Seed is date-dependent, not fully idempotent.** The seed materializes `nextSundaysInTz(2)` (rolling window), so re-running it across dates creates new instances. After testing I reset instances/slots/assignments and re-ran the seed once to restore the canonical 4-instance / 12-slot state.
|
||||||
|
|
||||||
|
**Next: D4 — blackout CRUD + `isUnavailable(user, date)` pure function, ranges + rrule.**
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
## D1 — Service CRUD + `expandRRULE()` — DONE 2026-11-18
|
## D1 — Service CRUD + `expandRRULE()` — DONE 2026-11-18
|
||||||
|
|
||||||
**Scope (from BUILD-PLAN.md):** service CRUD + `expandRRULE()` (weekly / biweekly / monthly-nth). Done when: `pnpm test recurrence` green on 5 named cases — spring-forward Sunday, fall-back Sunday, monthly-nth across a year boundary, cancelled instance not regenerated, biweekly phase stable. ARCHITECTURE §4.3 / §5.1 / §5.8.3.
|
**Scope (from BUILD-PLAN.md):** service CRUD + `expandRRULE()` (weekly / biweekly / monthly-nth). Done when: `pnpm test recurrence` green on 5 named cases — spring-forward Sunday, fall-back Sunday, monthly-nth across a year boundary, cancelled instance not regenerated, biweekly phase stable. ARCHITECTURE §4.3 / §5.1 / §5.8.3.
|
||||||
|
|||||||
@@ -0,0 +1,15 @@
|
|||||||
|
import { materializeSlots } from "@/db/slots";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Slot materialization (ARCHITECTURE §5.2). Drives `materializeSlots()` —
|
||||||
|
* idempotent on (instance, role, seat). Re-runs create 0 rows.
|
||||||
|
*
|
||||||
|
* GET /api/dev/cron/slots
|
||||||
|
*/
|
||||||
|
export const GET = async () => {
|
||||||
|
const result = await materializeSlots();
|
||||||
|
return new Response(JSON.stringify({ result }), {
|
||||||
|
status: 200,
|
||||||
|
headers: { "content-type": "application/json" },
|
||||||
|
});
|
||||||
|
};
|
||||||
@@ -0,0 +1,88 @@
|
|||||||
|
/**
|
||||||
|
* Slot materialization — unit D3 (ARCHITECTURE §5.2).
|
||||||
|
*
|
||||||
|
* `materializeSlots()` turns the seats `planSlots()` computes into `slots`
|
||||||
|
* rows. Idempotent on `(service_instance_id, role_id, slot_index)` via
|
||||||
|
* `onConflictDoNothing`, so re-runs are no-ops and never disturb an admin's
|
||||||
|
* assignments on an existing seat.
|
||||||
|
*
|
||||||
|
* Per §5.1, slots are created only for non-published instances: a published
|
||||||
|
* week's slot set is owned by the publish flow, not the generator.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { and, gte, ne } from "drizzle-orm";
|
||||||
|
import { db } from "@/db";
|
||||||
|
import { roles, serviceInstances, slots } from "@/db/schema";
|
||||||
|
import { uuidv7 } from "@/lib/uuid";
|
||||||
|
import { planSlots, type RolePlanInput } from "@/domain/slots";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Materialize the seats for one instance. Returns the number of seats created
|
||||||
|
* this run (0 on a clean re-run).
|
||||||
|
*/
|
||||||
|
export async function materializeSlotsForInstance(
|
||||||
|
serviceInstanceId: string,
|
||||||
|
instanceStartsAt: Date,
|
||||||
|
rolesInput: RolePlanInput[],
|
||||||
|
): Promise<number> {
|
||||||
|
const plan = planSlots(instanceStartsAt, rolesInput);
|
||||||
|
let created = 0;
|
||||||
|
|
||||||
|
for (const seat of plan) {
|
||||||
|
const [row] = await db
|
||||||
|
.insert(slots)
|
||||||
|
.values({
|
||||||
|
id: uuidv7(),
|
||||||
|
serviceInstanceId,
|
||||||
|
eventId: null,
|
||||||
|
roleId: seat.roleId,
|
||||||
|
slotIndex: seat.slotIndex,
|
||||||
|
callTime: seat.callTime,
|
||||||
|
status: "open",
|
||||||
|
})
|
||||||
|
.onConflictDoNothing({
|
||||||
|
target: [
|
||||||
|
slots.serviceInstanceId,
|
||||||
|
slots.roleId,
|
||||||
|
slots.slotIndex,
|
||||||
|
],
|
||||||
|
})
|
||||||
|
.returning();
|
||||||
|
if (row) created++;
|
||||||
|
}
|
||||||
|
|
||||||
|
return created;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Materialize slots for every non-published instance at or after `now`.
|
||||||
|
* Published instances are left untouched (their slot set is owned by the
|
||||||
|
* publish flow).
|
||||||
|
*/
|
||||||
|
export async function materializeSlots(now?: Date): Promise<{ created: number; instances: number }> {
|
||||||
|
const reference = now ?? new Date();
|
||||||
|
const instances = await db
|
||||||
|
.select()
|
||||||
|
.from(serviceInstances)
|
||||||
|
.where(
|
||||||
|
and(
|
||||||
|
gte(serviceInstances.startsAt, reference),
|
||||||
|
ne(serviceInstances.status, "published"),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
const roleRows = await db.select().from(roles).orderBy(roles.sortOrder);
|
||||||
|
const rolesInput: RolePlanInput[] = roleRows.map((r) => ({
|
||||||
|
id: r.id,
|
||||||
|
callTimeOffsetMinutes: r.callTimeOffsetMinutes,
|
||||||
|
defaultHeadcount: r.defaultHeadcount,
|
||||||
|
}));
|
||||||
|
|
||||||
|
let created = 0;
|
||||||
|
for (const inst of instances) {
|
||||||
|
if (!inst.startsAt) continue;
|
||||||
|
created += await materializeSlotsForInstance(inst.id, inst.startsAt, rolesInput);
|
||||||
|
}
|
||||||
|
|
||||||
|
return { created, instances: instances.length };
|
||||||
|
}
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
import { describe, expect, it } from "vitest";
|
||||||
|
import { planSlots, planSlotsForRole } from "./slots";
|
||||||
|
|
||||||
|
const audioRole = {
|
||||||
|
id: "audio",
|
||||||
|
callTimeOffsetMinutes: -90,
|
||||||
|
defaultHeadcount: 2,
|
||||||
|
};
|
||||||
|
|
||||||
|
describe("planSlotsForRole — headcount", () => {
|
||||||
|
it("Audio headcount 2 creates 2 slots with correct call_time", () => {
|
||||||
|
const startsAt = new Date(Date.UTC(2026, 10, 22, 16, 0, 0)); // 11:00 EST
|
||||||
|
const seats = planSlotsForRole(startsAt, audioRole);
|
||||||
|
expect(seats.map((s) => s.slotIndex)).toEqual([1, 2]);
|
||||||
|
expect(seats).toHaveLength(2);
|
||||||
|
// call_time = start + (-90 min) = 09:30 EST = 14:30 UTC.
|
||||||
|
expect(seats.every((s) => s.callTime !== null)).toBe(true);
|
||||||
|
expect(seats.map((s) => s.callTime!.getUTCHours())).toEqual([14, 14]);
|
||||||
|
expect(seats.map((s) => s.callTime!.getUTCMinutes())).toEqual([30, 30]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("clamps headcount to at least 1", () => {
|
||||||
|
const seats = planSlotsForRole(new Date(), {
|
||||||
|
id: "coffee",
|
||||||
|
callTimeOffsetMinutes: null,
|
||||||
|
defaultHeadcount: 0,
|
||||||
|
});
|
||||||
|
expect(seats).toHaveLength(1);
|
||||||
|
expect(seats[0].slotIndex).toBe(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("call_time is null when the role has no offset", () => {
|
||||||
|
const seats = planSlotsForRole(new Date(Date.UTC(2026, 10, 22, 16, 0, 0)), {
|
||||||
|
id: "welcome",
|
||||||
|
callTimeOffsetMinutes: null,
|
||||||
|
defaultHeadcount: 1,
|
||||||
|
});
|
||||||
|
expect(seats[0].callTime).toBeNull();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("planSlots — multiple roles", () => {
|
||||||
|
it("flattens every role's seats in role order", () => {
|
||||||
|
const startsAt = new Date(Date.UTC(2026, 10, 22, 16, 0, 0));
|
||||||
|
const seats = planSlots(startsAt, [
|
||||||
|
{ id: "audio", callTimeOffsetMinutes: -90, defaultHeadcount: 2 },
|
||||||
|
{ id: "livestream", callTimeOffsetMinutes: -60, defaultHeadcount: 1 },
|
||||||
|
]);
|
||||||
|
expect(seats.map((s) => s.slotIndex)).toEqual([1, 2, 1]);
|
||||||
|
expect(seats.map((s) => s.roleId)).toEqual(["audio", "audio", "livestream"]);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
/**
|
||||||
|
* Slot planning — unit D3 (ARCHITECTURE §5.2).
|
||||||
|
*
|
||||||
|
* Pure: no DB, no `src/db` imports. `planSlots()` turns an instance's start
|
||||||
|
* instant plus the role requirements into the seats that role fills. The data
|
||||||
|
* layer (`src/db/slots.ts`) upserts these; the cron route drives it.
|
||||||
|
*
|
||||||
|
* A role with headcount N fills N seats (slotIndex 1..N). Each seat's call time
|
||||||
|
* is the instance start plus the role's call-time offset (null when the role
|
||||||
|
* has no offset), matching the seed.
|
||||||
|
*/
|
||||||
|
|
||||||
|
export interface RolePlanInput {
|
||||||
|
id: string;
|
||||||
|
callTimeOffsetMinutes: number | null;
|
||||||
|
defaultHeadcount: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface SlotPlan {
|
||||||
|
roleId: string;
|
||||||
|
/** 1..headcount, for labels like "Audio 2". */
|
||||||
|
slotIndex: number;
|
||||||
|
/** instance.startsAt + offset; null when the role has no offset. */
|
||||||
|
callTime: Date | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The seats a single role fills for an instance. Headcount is clamped to >= 1
|
||||||
|
* so a role always produces at least one seat.
|
||||||
|
*/
|
||||||
|
export function planSlotsForRole(
|
||||||
|
instanceStartsAt: Date,
|
||||||
|
role: RolePlanInput,
|
||||||
|
): SlotPlan[] {
|
||||||
|
const headcount = Math.max(1, role.defaultHeadcount);
|
||||||
|
const offsetMs = role.callTimeOffsetMinutes != null
|
||||||
|
? role.callTimeOffsetMinutes * 60_000
|
||||||
|
: 0;
|
||||||
|
return Array.from({ length: headcount }, (_, i) => ({
|
||||||
|
roleId: role.id,
|
||||||
|
slotIndex: i + 1,
|
||||||
|
callTime: role.callTimeOffsetMinutes != null
|
||||||
|
? new Date(instanceStartsAt.getTime() + offsetMs)
|
||||||
|
: null,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Every seat for every role in an instance. */
|
||||||
|
export function planSlots(
|
||||||
|
instanceStartsAt: Date,
|
||||||
|
roles: RolePlanInput[],
|
||||||
|
): SlotPlan[] {
|
||||||
|
return roles.flatMap((role) => planSlotsForRole(instanceStartsAt, role));
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user