/** * Crew employee-number generator. Format: CRW-, e.g. CRW-1000. * * Sequential, floored at 1000, scanning existing CrewMember.employeeId values. * Assigned at onboarding (Phase 3c). Call inside the onboarding transaction to * minimise the race window (the unique constraint is the backstop). */ import { db } from "@/lib/db"; import type { Prisma } from "@prisma/client"; const PREFIX = "CRW-"; const FLOOR = 999; // first generated id is 1000 export async function generateEmployeeId( client: Prisma.TransactionClient | typeof db = db ): Promise { const rows = await client.crewMember.findMany({ where: { employeeId: { startsWith: PREFIX } }, select: { employeeId: true }, }); let maxId = FLOOR; for (const { employeeId } of rows) { if (!employeeId) continue; const n = parseInt(employeeId.slice(PREFIX.length), 10); if (!isNaN(n) && n > maxId) maxId = n; } return `${PREFIX}${maxId + 1}`; }