Skip to content

Commit feef161

Browse files
fix: resolve Prisma alunoId for ALUNO role to avoid FK violation
getAuthRole() returns role=null for ALUNO (no funcionarios record). Previous code used auth user.id as alunoId, but Prisma aluno.id may differ from Supabase Auth UUID. Added resolveAlunoId() helper that looks up the correct aluno.id by email before create. Fixes: foreign key constraint violation on treinos_alunoId_fkey when ALUNO saves AI-generated workout.
1 parent 26cc77a commit feef161

1 file changed

Lines changed: 18 additions & 3 deletions

File tree

src/lib/actions/treinos.ts

Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -43,14 +43,24 @@ async function getAuthRole() {
4343
};
4444
}
4545

46+
/**
47+
* ALUNO role has no funcionarios record, so role === null.
48+
* Their Prisma `aluno.id` may differ from Supabase Auth `user.id`.
49+
* Resolve the correct alunoId from Prisma by email to avoid FK violation.
50+
*/
51+
async function resolveAlunoId(user: { id: string; email?: string | null }): Promise<string> {
52+
const aluno = await prisma.aluno.findUnique({ where: { email: user.email ?? '' } });
53+
return aluno?.id ?? user.id;
54+
}
55+
4656
async function performTreinoUpsert(
4757
validatedData: TreinoBase & { id?: string },
4858
user: { id: string },
4959
role: string | null,
5060
derivedInstrutorId: string | null
5161
) {
5262
const { objetivo, exercicios, diaSemana } = validatedData;
53-
const alunoId = role === null ? user.id : validatedData.alunoId;
63+
const alunoId = role === null ? await resolveAlunoId(user) : validatedData.alunoId;
5464
const id = 'id' in validatedData ? (validatedData as TreinoBase & { id: string }).id : undefined;
5565

5666
if (id) {
@@ -172,15 +182,20 @@ export async function batchUpsertTreinoAction(
172182
if ('error' in auth) return { success: false, error: auth.error };
173183
const { user, role, derivedInstrutorId } = auth;
174184

175-
const validated = treinos.map((t) => TreinoBaseSchema.parse({ ...t, alunoId: t.alunoId }));
185+
const validated = await Promise.all(
186+
treinos.map(async (t) => ({
187+
...TreinoBaseSchema.parse({ ...t, alunoId: t.alunoId }),
188+
alunoId: role === null ? await resolveAlunoId(user) : t.alunoId,
189+
}))
190+
);
176191

177192
await prisma.$transaction(
178193
validated.map((data) =>
179194
prisma.treino.create({
180195
data: {
181196
objetivo: data.objetivo,
182197
diaSemana: data.diaSemana,
183-
alunoId: role === null ? user.id : data.alunoId,
198+
alunoId: data.alunoId,
184199
instrutorId: derivedInstrutorId,
185200
Exercicios: {
186201
create: data.exercicios.map((ex) => ({

0 commit comments

Comments
 (0)