From ba17fb1d6a944716fdf838d7da49dd53b2e2fc59 Mon Sep 17 00:00:00 2001 From: tisachi Date: Sat, 17 Oct 2026 11:16:54 +0200 Subject: [PATCH] Cialo: typeId+side zamiast nazwy PL w pomiarach obwodow (migracja z backfillem, kontrakt API: z.enum typow, grupowanie serii po type+side, legacy name nullable, swagger, testy) --- .../migration.sql | 26 ++++ api/prisma/schema.prisma | 7 +- api/src/routes/admin.ts | 15 ++- api/src/routes/me.ts | 15 ++- api/src/services/me.ts | 65 ++++++++-- api/src/swagger.ts | 16 ++- api/test/integration/admin-user-data.test.ts | 10 +- api/test/integration/audit.test.ts | 22 +++- api/test/integration/me.test.ts | 111 +++++++++++++++--- 9 files changed, 235 insertions(+), 52 deletions(-) create mode 100644 api/prisma/migrations/20261017085515_circumference_type_side/migration.sql diff --git a/api/prisma/migrations/20261017085515_circumference_type_side/migration.sql b/api/prisma/migrations/20261017085515_circumference_type_side/migration.sql new file mode 100644 index 0000000..1157598 --- /dev/null +++ b/api/prisma/migrations/20261017085515_circumference_type_side/migration.sql @@ -0,0 +1,26 @@ +-- AlterTable +ALTER TABLE "CircumferenceMeasurement" ADD COLUMN "side" TEXT, +ADD COLUMN "typeId" TEXT, +ALTER COLUMN "name" DROP NOT NULL; + +-- Backfill: map legacy Polish series names to typeId + side. +-- Unknown / free-text names (typos, custom labels) stay as legacy (typeId NULL, name preserved). +UPDATE "CircumferenceMeasurement" +SET + side = CASE + WHEN lower("name") LIKE '% lewy' THEN 'left' + WHEN lower("name") LIKE '% prawy' THEN 'right' + ELSE NULL + END, + "typeId" = CASE lower(regexp_replace("name", '\s+(lewy|prawy)$', '', 'i')) + WHEN 'klatka piersiowa' THEN 'chest' + WHEN 'talia' THEN 'waist' + WHEN 'biodra' THEN 'hips' + WHEN 'kark' THEN 'neck' + WHEN 'biceps' THEN 'biceps' + WHEN 'przedramię' THEN 'forearm' + WHEN 'udo' THEN 'thigh' + WHEN 'łydka' THEN 'calf' + ELSE NULL + END +WHERE "typeId" IS NULL AND "name" IS NOT NULL; diff --git a/api/prisma/schema.prisma b/api/prisma/schema.prisma index 3f9543f..e594091 100644 --- a/api/prisma/schema.prisma +++ b/api/prisma/schema.prisma @@ -517,7 +517,12 @@ model BodyMeasurement { model CircumferenceMeasurement { id String @id @default(cuid()) userId String - name String + /// Identyfikator typu pomiaru z listy (chest/waist/...); null dla starszych pomiarów zapisanych jako swobodna nazwa. + typeId String? + /// Strona pomiaru w parach (left/right); null dla pomiarów niesymetrycznych i starszych. + side String? + /// Etykieta seryjna: null dla nowych pomiarów (etykieta wynika z typeId+side), zachowana dla starszych. + name String? value Float date DateTime @default(now()) diff --git a/api/src/routes/admin.ts b/api/src/routes/admin.ts index 55949e0..7e4e3b5 100644 --- a/api/src/routes/admin.ts +++ b/api/src/routes/admin.ts @@ -851,7 +851,12 @@ export function createAdminRoutes({ prisma }: AppDeps) { action: 'circumference.added', entityType: 'user', entityId: req.params.id, - details: { name: data.name, value: data.value, byAdmin: true }, + details: { + typeId: data.typeId, + side: data.side ?? null, + value: data.value, + byAdmin: true, + }, }); res.status(201).json(result); }), @@ -877,7 +882,13 @@ export function createAdminRoutes({ prisma }: AppDeps) { action: 'circumference.removed', entityType: 'user', entityId: req.params.id, - details: { name: result.name, value: result.value, byAdmin: true }, + details: { + typeId: result.typeId, + side: result.side, + name: result.name, + value: result.value, + byAdmin: true, + }, }); res.status(204).end(); }), diff --git a/api/src/routes/me.ts b/api/src/routes/me.ts index 3753414..37ae3cd 100644 --- a/api/src/routes/me.ts +++ b/api/src/routes/me.ts @@ -6,6 +6,7 @@ import { validate } from '../middleware/validate.js'; import { addCircumference, addWeight, + CIRCUMFERENCE_TYPE_IDS, deleteCircumference, deleteWeight, getBodyParameters, @@ -59,7 +60,8 @@ export const weightSchema = z.object({ }); export const circumferenceSchema = z.object({ - name: z.string().min(1).max(100), + typeId: z.enum(CIRCUMFERENCE_TYPE_IDS), + side: z.enum(['left', 'right']).nullish(), value: z.number().positive().max(300), date: z.string().datetime({ offset: true }).optional(), }); @@ -303,7 +305,7 @@ export function createMeRoutes({ prisma }: AppDeps) { * @openapi * /me/body-parameters/circumference: * post: - * summary: Add circumference measurement (name + value) + * summary: Add circumference measurement (type + side + value) * tags: [Profile] * responses: * 201: { description: Created } @@ -319,7 +321,7 @@ export function createMeRoutes({ prisma }: AppDeps) { action: 'circumference.added', entityType: 'user', entityId: req.user!.id, - details: { name: data.name, value: data.value }, + details: { typeId: data.typeId, side: data.side ?? null, value: data.value }, }); res.status(201).json(result); }), @@ -369,7 +371,12 @@ export function createMeRoutes({ prisma }: AppDeps) { action: 'circumference.removed', entityType: 'user', entityId: req.user!.id, - details: { name: result.name, value: result.value }, + details: { + typeId: result.typeId, + side: result.side, + name: result.name, + value: result.value, + }, }); res.status(204).end(); }), diff --git a/api/src/services/me.ts b/api/src/services/me.ts index 9af7315..10bcc9b 100644 --- a/api/src/services/me.ts +++ b/api/src/services/me.ts @@ -53,8 +53,23 @@ export interface WeightInput { date?: string; } +export type CircumferenceSide = 'left' | 'right'; + +/** Znane typy pomiarów obwodu (kolejność zgodna z listą na froncie). */ +export const CIRCUMFERENCE_TYPE_IDS = [ + 'chest', + 'waist', + 'hips', + 'neck', + 'biceps', + 'forearm', + 'thigh', + 'calf', +] as const; + export interface CircumferenceInput { - name: string; + typeId: string; + side?: CircumferenceSide | null; value: number; date?: string; } @@ -180,18 +195,32 @@ export async function getBodyParameters(prisma: PrismaClient, userId: string) { orderBy: { date: 'asc' }, }), ]); - const byName = new Map< - string, - { name: string; points: { id: string; value: number; date: string }[] } - >(); + interface Series { + typeId: string | null; + side: string | null; + /** Znacząca tylko dla starszych pomiarów (typeId = null) — zachowana swobodna nazwa. */ + name: string | null; + points: { id: string; value: number; date: string }[]; + } + const byKey = new Map(); for (const c of circumferences) { - const entry = byName.get(c.name) ?? { name: c.name, points: [] }; + // Nowe: grupujemy po (typeId, side). Starsze bez typeId: po zachowanej nazwie. + const key = c.typeId ? `t:${c.typeId}:${c.side ?? ''}` : `n:${c.name ?? ''}`; + let entry = byKey.get(key); + if (!entry) { + entry = { + typeId: c.typeId, + side: c.typeId ? c.side : null, + name: c.typeId ? null : c.name, + points: [], + }; + byKey.set(key, entry); + } entry.points.push({ id: c.id, value: c.value, date: c.date.toISOString() }); - byName.set(c.name, entry); } return { weight: weight.map((w) => ({ id: w.id, value: w.value, date: w.date.toISOString() })), - circumferences: [...byName.values()], + circumferences: [...byKey.values()], }; } @@ -210,12 +239,19 @@ export async function addCircumference( const entry = await prisma.circumferenceMeasurement.create({ data: { userId, - name: input.name, + typeId: input.typeId, + side: input.side ?? null, value: input.value, date: input.date ? new Date(input.date) : new Date(), }, }); - return { id: entry.id, name: entry.name, value: entry.value, date: entry.date }; + return { + id: entry.id, + typeId: entry.typeId, + side: entry.side, + value: entry.value, + date: entry.date, + }; } export async function deleteWeight(prisma: PrismaClient, userId: string, id: string) { @@ -229,7 +265,14 @@ export async function deleteCircumference(prisma: PrismaClient, userId: string, const entry = await prisma.circumferenceMeasurement.findFirst({ where: { id, userId } }); if (!entry) throw notFound('Measurement not found'); await prisma.circumferenceMeasurement.delete({ where: { id: entry.id } }); - return { id: entry.id, name: entry.name, value: entry.value, date: entry.date }; + return { + id: entry.id, + typeId: entry.typeId, + side: entry.side, + name: entry.name, + value: entry.value, + date: entry.date, + }; } export async function getHistory(prisma: PrismaClient, userId: string, month?: string) { diff --git a/api/src/swagger.ts b/api/src/swagger.ts index dd0e532..32e187b 100644 --- a/api/src/swagger.ts +++ b/api/src/swagger.ts @@ -177,9 +177,13 @@ export const openapi: Record = { 'application/json': { schema: { type: 'object', - required: ['name', 'value'], + required: ['typeId', 'value'], properties: { - name: { type: 'string' }, + typeId: { + type: 'string', + enum: ['chest', 'waist', 'hips', 'neck', 'biceps', 'forearm', 'thigh', 'calf'], + }, + side: { type: 'string', enum: ['left', 'right'], nullable: true }, value: { type: 'number' }, date: { type: 'string' }, }, @@ -1516,9 +1520,13 @@ export const openapi: Record = { 'application/json': { schema: { type: 'object', - required: ['name', 'value'], + required: ['typeId', 'value'], properties: { - name: { type: 'string' }, + typeId: { + type: 'string', + enum: ['chest', 'waist', 'hips', 'neck', 'biceps', 'forearm', 'thigh', 'calf'], + }, + side: { type: 'string', enum: ['left', 'right'], nullable: true }, value: { type: 'number' }, date: { type: 'string', format: 'date-time' }, }, diff --git a/api/test/integration/admin-user-data.test.ts b/api/test/integration/admin-user-data.test.ts index a02a1ae..e04ca0c 100644 --- a/api/test/integration/admin-user-data.test.ts +++ b/api/test/integration/admin-user-data.test.ts @@ -98,17 +98,17 @@ describe('admin per-user data routes', () => { const create = await app .post(`/api/v1/admin/users/${targetUserId}/body-parameters/circumference`) .set('Authorization', `Bearer ${adminToken}`) - .send({ name: 'Biceps (prawa)', value: 36.2 }); + .send({ typeId: 'biceps', side: 'right', value: 36.2 }); expect(create.status).toBe(201); const list = await adminGet(`/users/${targetUserId}/body-parameters`); - const series = list.body.circumferences.find((s: { name: string }) => s.name === 'Biceps (prawa)'); + const series = list.body.circumferences.find( + (s: { typeId: string; side: string }) => s.typeId === 'biceps' && s.side === 'right', + ); expect(series?.points[0]).toMatchObject({ value: 36.2 }); const del = await app - .delete( - `/api/v1/admin/users/${targetUserId}/body-parameters/circumference/${create.body.id}`, - ) + .delete(`/api/v1/admin/users/${targetUserId}/body-parameters/circumference/${create.body.id}`) .set('Authorization', `Bearer ${adminToken}`); expect(del.status).toBe(204); }); diff --git a/api/test/integration/audit.test.ts b/api/test/integration/audit.test.ts index c07fa2f..dd67d57 100644 --- a/api/test/integration/audit.test.ts +++ b/api/test/integration/audit.test.ts @@ -72,7 +72,11 @@ describe('activity logs (audit trail)', () => { }); expect(logs.map((l) => l.action)).toEqual(['plan.created', 'plan.activated', 'plan.abandoned']); expect(logs[0].details).toMatchObject({ actorId: user.id, title: 'Audit plan' }); - expect(logs[1].details).toMatchObject({ actorId: user.id, title: 'Audit plan', startDate: MONDAY }); + expect(logs[1].details).toMatchObject({ + actorId: user.id, + title: 'Audit plan', + startDate: MONDAY, + }); expect(logs[2].entityId).toBe(planId); }); @@ -115,14 +119,20 @@ describe('activity logs (audit trail)', () => { const app = buildApp(); const auth = { Authorization: `Bearer ${token}` }; - const weight = await app.post('/api/v1/me/body-parameters/weight').set(auth).send({ value: 82.5 }); + const weight = await app + .post('/api/v1/me/body-parameters/weight') + .set(auth) + .send({ value: 82.5 }); const circ = await app .post('/api/v1/me/body-parameters/circumference') .set(auth) - .send({ name: 'biceps', value: 40 }); - expect((await app.delete(`/api/v1/me/body-parameters/weight/${weight.body.id}`).set(auth)).status).toBe(204); + .send({ typeId: 'biceps', value: 40 }); expect( - (await app.delete(`/api/v1/me/body-parameters/circumference/${circ.body.id}`).set(auth)).status, + (await app.delete(`/api/v1/me/body-parameters/weight/${weight.body.id}`).set(auth)).status, + ).toBe(204); + expect( + (await app.delete(`/api/v1/me/body-parameters/circumference/${circ.body.id}`).set(auth)) + .status, ).toBe(204); const logs = await prisma.activityLog.findMany({ @@ -135,7 +145,7 @@ describe('activity logs (audit trail)', () => { }); expect(logs.find((l) => l.action === 'circumference.removed')?.details).toMatchObject({ actorId: user.id, - name: 'biceps', + typeId: 'biceps', value: 40, }); }); diff --git a/api/test/integration/me.test.ts b/api/test/integration/me.test.ts index d508d90..a63338f 100644 --- a/api/test/integration/me.test.ts +++ b/api/test/integration/me.test.ts @@ -1,5 +1,13 @@ import { describe, it, expect } from 'vitest'; -import { buildApp, registerViaApi, rand, createExercise, seedPlan, seedSession } from '../helpers.js'; +import { prisma } from '../../src/lib/prisma.js'; +import { + buildApp, + registerViaApi, + rand, + createExercise, + seedPlan, + seedSession, +} from '../helpers.js'; describe('me routes', () => { it('rejects /me without a token with 401', async () => { @@ -157,9 +165,9 @@ describe('me routes', () => { const circ = await app .post('/api/v1/me/body-parameters/circumference') .set(auth) - .send({ name: 'biceps', value: 40, date: '2026-08-01T08:00:00.000Z' }); + .send({ typeId: 'biceps', side: 'left', value: 40, date: '2026-08-01T08:00:00.000Z' }); expect(circ.status).toBe(201); - expect(circ.body.name).toBe('biceps'); + expect(circ.body).toMatchObject({ typeId: 'biceps', side: 'left' }); const list = await app.get('/api/v1/me/body-parameters').set(auth); expect(list.status).toBe(200); @@ -168,28 +176,45 @@ describe('me routes', () => { expect(list.body.weight[0].id).toBeTruthy(); expect(list.body.circumferences).toHaveLength(1); expect(list.body.circumferences[0]).toMatchObject({ - name: 'biceps', + typeId: 'biceps', + side: 'left', + name: null, points: [{ value: 40, date: '2026-08-01T08:00:00.000Z' }], }); expect(list.body.circumferences[0].points[0].id).toBeTruthy(); }); + it('rejects an unknown circumference type with 400', async () => { + const app = buildApp(); + const { token } = await registerViaApi(`badtype-${rand()}@test.local`); + const res = await app + .post('/api/v1/me/body-parameters/circumference') + .set('Authorization', `Bearer ${token}`) + .send({ typeId: 'ogon', value: 40 }); + expect(res.status).toBe(400); + }); + it('deletes weight and circumference measurements (own only)', async () => { const app = buildApp(); const { token } = await registerViaApi(`del-${rand()}@test.local`); const other = await registerViaApi(`del-other-${rand()}@test.local`); const auth = { Authorization: `Bearer ${token}` }; - const weight = await app.post('/api/v1/me/body-parameters/weight').set(auth).send({ value: 80 }); + const weight = await app + .post('/api/v1/me/body-parameters/weight') + .set(auth) + .send({ value: 80 }); const circ = await app .post('/api/v1/me/body-parameters/circumference') .set(auth) - .send({ name: 'biceps', value: 40 }); + .send({ typeId: 'biceps', side: 'left', value: 40 }); const weightId = weight.body.id; const circId = circ.body.id; // usunięcie własnych pomiarów - expect((await app.delete(`/api/v1/me/body-parameters/weight/${weightId}`).set(auth)).status).toBe(204); + expect( + (await app.delete(`/api/v1/me/body-parameters/weight/${weightId}`).set(auth)).status, + ).toBe(204); expect( (await app.delete(`/api/v1/me/body-parameters/circumference/${circId}`).set(auth)).status, ).toBe(204); @@ -199,26 +224,70 @@ describe('me routes', () => { expect(list.body.circumferences).toHaveLength(0); // cudzy pomiar -> 404, nieistniejący -> 404 - const otherWeight = await app.post('/api/v1/me/body-parameters/weight').set(auth).send({ value: 81 }); + const otherWeight = await app + .post('/api/v1/me/body-parameters/weight') + .set(auth) + .send({ value: 81 }); expect( - (await app - .delete(`/api/v1/me/body-parameters/weight/${otherWeight.body.id}`) - .set('Authorization', `Bearer ${other.token}`)).status, + ( + await app + .delete(`/api/v1/me/body-parameters/weight/${otherWeight.body.id}`) + .set('Authorization', `Bearer ${other.token}`) + ).status, ).toBe(404); expect((await app.delete('/api/v1/me/body-parameters/weight/none').set(auth)).status).toBe(404); }); - it('groups circumference series by name', async () => { + it('groups circumference series by type and side', async () => { const app = buildApp(); const { token } = await registerViaApi(`circ-${rand()}@test.local`); const auth = { Authorization: `Bearer ${token}` }; - await app.post('/api/v1/me/body-parameters/circumference').set(auth).send({ name: 'biceps', value: 40 }); - await app.post('/api/v1/me/body-parameters/circumference').set(auth).send({ name: 'biceps', value: 41 }); - await app.post('/api/v1/me/body-parameters/circumference').set(auth).send({ name: 'waist', value: 85 }); + await app + .post('/api/v1/me/body-parameters/circumference') + .set(auth) + .send({ typeId: 'biceps', side: 'left', value: 40 }); + await app + .post('/api/v1/me/body-parameters/circumference') + .set(auth) + .send({ typeId: 'biceps', side: 'left', value: 41 }); + await app + .post('/api/v1/me/body-parameters/circumference') + .set(auth) + .send({ typeId: 'biceps', side: 'right', value: 38 }); + await app + .post('/api/v1/me/body-parameters/circumference') + .set(auth) + .send({ typeId: 'waist', value: 85 }); const list = await app.get('/api/v1/me/body-parameters').set(auth); - const byName = Object.fromEntries(list.body.circumferences.map((c: { name: string; points: unknown[] }) => [c.name, c.points.length])); - expect(byName).toEqual({ biceps: 2, waist: 1 }); + const bySeries = Object.fromEntries( + list.body.circumferences.map( + (c: { typeId: string; side: string | null; points: unknown[] }) => [ + `${c.typeId}/${c.side ?? '-'}`, + c.points.length, + ], + ), + ); + expect(bySeries).toEqual({ 'biceps/left': 2, 'biceps/right': 1, 'waist/-': 1 }); + }); + + it('exposes legacy free-text series as-is (typeId/side null, name preserved)', async () => { + const app = buildApp(); + const { token, user } = await registerViaApi(`legacy-${rand()}@test.local`); + const auth = { Authorization: `Bearer ${token}` }; + // historyczny wiersz sprzed migracji — swobodna nazwa bez typeId (backfill jej nie rozpoznał) + await prisma.circumferenceMeasurement.create({ + data: { userId: user.id, name: 'Stary biceps', value: 33 }, + }); + + const list = await app.get('/api/v1/me/body-parameters').set(auth); + expect(list.body.circumferences).toHaveLength(1); + expect(list.body.circumferences[0]).toMatchObject({ + typeId: null, + side: null, + name: 'Stary biceps', + points: [{ value: 33 }], + }); }); it('weight measurement rejects a non-positive value with 400', async () => { @@ -326,7 +395,9 @@ describe('me routes', () => { exerciseId: exercise.id, planExerciseId: planExercise.id, order: 0, - sets: [{ planSetId: planExercise.sets[0].id, reps: 10, note: 'plecy bolały przy tej serii' }], + sets: [ + { planSetId: planExercise.sets[0].id, reps: 10, note: 'plecy bolały przy tej serii' }, + ], }, ], }); @@ -439,7 +510,9 @@ describe('me routes', () => { it('rejects an invalid month format in /me/history with 400', async () => { const app = buildApp(); const { token } = await registerViaApi(`histbad-${rand()}@test.local`); - const res = await app.get('/api/v1/me/history?month=2026-1').set('Authorization', `Bearer ${token}`); + const res = await app + .get('/api/v1/me/history?month=2026-1') + .set('Authorization', `Bearer ${token}`); expect(res.status).toBe(400); }); });