From d734a5e41165172efe442a08a17c04a5f44d55cd Mon Sep 17 00:00:00 2001 From: Tilumca Date: Thu, 15 Oct 2026 00:24:14 +0200 Subject: [PATCH] API: strukturalny adres silowni (ulica/kod/miasto/kraj); location derivowane, adres wymagany przy tworzeniu REAL --- .../migration.sql | 6 ++ api/prisma/schema.prisma | 8 ++ api/src/lib/address.ts | 36 ++++++++ api/src/routes/admin.ts | 33 +++++++- api/src/services/admin.ts | 62 ++++++++++++-- api/src/swagger.ts | 35 +++++++- api/test/integration/admin.test.ts | 82 +++++++++++++++++-- 7 files changed, 237 insertions(+), 25 deletions(-) create mode 100644 api/prisma/migrations/20261014221818_gym_structured_address/migration.sql create mode 100644 api/src/lib/address.ts diff --git a/api/prisma/migrations/20261014221818_gym_structured_address/migration.sql b/api/prisma/migrations/20261014221818_gym_structured_address/migration.sql new file mode 100644 index 0000000..f46db66 --- /dev/null +++ b/api/prisma/migrations/20261014221818_gym_structured_address/migration.sql @@ -0,0 +1,6 @@ +-- AlterTable +ALTER TABLE "Gym" ADD COLUMN "addressLine1" TEXT, +ADD COLUMN "addressLine2" TEXT, +ADD COLUMN "city" TEXT, +ADD COLUMN "countryCode" TEXT DEFAULT 'PL', +ADD COLUMN "postalCode" TEXT; diff --git a/api/prisma/schema.prisma b/api/prisma/schema.prisma index 87c6e8d..9390032 100644 --- a/api/prisma/schema.prisma +++ b/api/prisma/schema.prisma @@ -220,7 +220,15 @@ model ConversationRead { model Gym { id String @id @default(cuid()) name String + /// Display string wyliczany z adresu (fallback dla starszych, swobodnych lokalizacji). location String? + /// Strukturyzowany adres (wzorzec Google/UPU) — `location` składa się z tych pol. + addressLine1 String? + addressLine2 String? + postalCode String? + city String? + /// ISO 3166-1 alpha-2; default PL, przy innym kraju dopisywany do display-stringa. + countryCode String? @default("PL") availability Json? capacity Int? /// Existing rows default to REAL; VIRTUAL gyms are created by users. diff --git a/api/src/lib/address.ts b/api/src/lib/address.ts new file mode 100644 index 0000000..d53e432 --- /dev/null +++ b/api/src/lib/address.ts @@ -0,0 +1,36 @@ +/** + * Adres siłowni — strukturalne pola (wzorzec Google/UPU) + display string. + * `location` (String w bazie) jest zawsze derivowany z pól adresowych; + * stare rekordy ze swobodną lokalizacją zostają bez adresu i displayują `location` 1:1. + */ + +export interface AddressParts { + addressLine1?: string | null; + addressLine2?: string | null; + postalCode?: string | null; + city?: string | null; + countryCode?: string | null; +} + +/** Polskie kody pocztowe: 00-001. */ +export const PL_POSTAL_CODE = /^\d{2}-\d{3}$/; + +/** + * Wyświetlowy adres jednolinijkowy: "Mokotowska 12A, lokal 5, 00-900 Warszawa". + * Kraj ukryty dla PL, inne kraje dopisywane kodem ISO ("..., DE"). + * Zwraca null, gdy brak jakichkolwiek części adresu. + */ +export function formatAddress(parts: AddressParts): string | null { + const street = [parts.addressLine1, parts.addressLine2] + .map((p) => p?.trim()) + .filter(Boolean) + .join(', '); + const city = [parts.postalCode, parts.city] + .map((p) => p?.trim()) + .filter(Boolean) + .join(' '); + const line = [street, city].filter(Boolean).join(', '); + if (!line) return null; + const country = parts.countryCode?.trim().toUpperCase(); + return country && country !== 'PL' ? `${line}, ${country}` : line; +} diff --git a/api/src/routes/admin.ts b/api/src/routes/admin.ts index 5618435..f6b6e2b 100644 --- a/api/src/routes/admin.ts +++ b/api/src/routes/admin.ts @@ -61,14 +61,39 @@ import { asyncHandler } from '../lib/asyncHandler.js'; const gymSchema = z.object({ name: z.string().min(1).max(200), - location: z.string().max(500).nullable().optional(), availability: availabilitySchema, capacity: z.number().int().positive().max(100000).nullable().optional(), }); -// Admin tworząc siłownię zawsze wyznacza jej właściciela (ownerId → członkostwo OWNER). -const createGymSchema = gymSchema.extend({ ownerId: z.string().min(1) }); -const updateGymSchema = gymSchema.partial(); +// Adres strukturalny (wzorzec Google/UPU) — display string `location` liczony po stronie serwera. +const postalCodeSchema = z + .string() + .trim() + .regex(/^\d{2}-\d{3}$/, 'Format kodu pocztowego: 00-001'); +const countryCodeSchema = z + .string() + .trim() + .regex(/^[a-zA-Z]{2}$/, 'Kod kraju ISO 3166-1 alpha-2'); + +// Admin tworząc siłownię REAL zawsze wyznacza właściciela i podaje adres (ulica, kod, miasto). +const createGymSchema = gymSchema.extend({ + ownerId: z.string().min(1), + addressLine1: z.string().trim().min(1).max(200), + addressLine2: z.string().trim().max(200).nullable().optional(), + postalCode: postalCodeSchema, + city: z.string().trim().min(1).max(100), + countryCode: countryCodeSchema.default('PL'), +}); +const updateGymSchema = z.object({ + name: gymSchema.shape.name.optional(), + availability: gymSchema.shape.availability, + capacity: gymSchema.shape.capacity, + addressLine1: z.string().trim().min(1).max(200).nullable().optional(), + addressLine2: z.string().trim().max(200).nullable().optional(), + postalCode: postalCodeSchema.nullable().optional(), + city: z.string().trim().min(1).max(100).nullable().optional(), + countryCode: countryCodeSchema.nullable().optional(), +}); const gymExceptionSchema = z.object({ date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/), diff --git a/api/src/services/admin.ts b/api/src/services/admin.ts index 0fd8e49..fbc56ce 100644 --- a/api/src/services/admin.ts +++ b/api/src/services/admin.ts @@ -5,6 +5,7 @@ import { publicUser } from '../lib/publicUser.js'; import { badRequest, conflict, forbidden, notFound } from '../lib/errors.js'; import { removeGymClaimFiles, removeGymPhotoFiles } from '../lib/uploads.js'; import { gymPhotoUrl, listGymClaimIds } from './gyms.js'; +import { formatAddress, type AddressParts } from '../lib/address.js'; import { resolveMuscleConflicts, toPrismaAvailability, @@ -15,16 +16,25 @@ import { export interface CreateGymInput { name: string; - location?: string | null; - availability?: Availability | null; - capacity?: number | null; /** Administrator wyznacza właściciela nowej siłowni (rola OWNER). */ ownerId: string; + /** Strukturalny adres (REAL); `location` jest z niego derivowany. */ + addressLine1: string; + addressLine2?: string | null; + postalCode: string; + city: string; + countryCode?: string; + availability?: Availability | null; + capacity?: number | null; } export interface UpdateGymInput { name?: string; - location?: string | null; + addressLine1?: string | null; + addressLine2?: string | null; + postalCode?: string | null; + city?: string | null; + countryCode?: string | null; availability?: Availability | null; capacity?: number | null; } @@ -144,13 +154,19 @@ export async function removeGymOwner(prisma: PrismaClient, gymId: string, userId } } -/** Tworzy siłownię; wyznaczony przez admina `ownerId` otrzymuje członkostwo z rolą OWNER. */ +/** Tworzy siłownię REAL z adresem; `location` derivowany, wyznaczony `ownerId` dostaje rolę OWNER. */ export async function createGym(prisma: PrismaClient, data: CreateGymInput) { const { availability, ownerId, ...rest } = data; await ensureUser(prisma, ownerId); + const location = formatAddress(rest); const gym = await prisma.$transaction(async (tx) => { const created = await tx.gym.create({ - data: { ...rest, availability: toPrismaAvailability(availability) }, + data: { + ...rest, + countryCode: (data.countryCode ?? 'PL').toUpperCase(), + location, + availability: toPrismaAvailability(availability), + }, }); await tx.gymMembership.create({ data: { userId: ownerId, gymId: created.id, roles: ['OWNER'] }, @@ -160,12 +176,42 @@ export async function createGym(prisma: PrismaClient, data: CreateGymInput) { return { gym }; } +/** + * Aktualizacja siłowni; przy zmianie któregokolwiek pola adresu reszta jest + * scalana ze stanem w bazie, a display string `location` liczony od nowa. + */ export async function updateGym(prisma: PrismaClient, id: string, data: UpdateGymInput) { try { - const { availability, ...rest } = data; + const { + availability, + addressLine1, + addressLine2, + postalCode, + city, + countryCode, + ...rest + } = data; + let addressData: Prisma.GymUpdateInput = {}; + const hasAddress = [addressLine1, addressLine2, postalCode, city, countryCode].some( + (v) => v !== undefined, + ); + if (hasAddress) { + const existing = await prisma.gym.findUniqueOrThrow({ where: { id } }); + const merged: AddressParts = { + addressLine1: addressLine1 !== undefined ? addressLine1 : existing.addressLine1, + addressLine2: addressLine2 !== undefined ? addressLine2 : existing.addressLine2, + postalCode: postalCode !== undefined ? postalCode : existing.postalCode, + city: city !== undefined ? city : existing.city, + countryCode: + countryCode !== undefined + ? countryCode ? countryCode.trim().toUpperCase() : null + : existing.countryCode, + }; + addressData = { ...merged, location: formatAddress(merged) }; + } const gym = await prisma.gym.update({ where: { id }, - data: { ...rest, availability: toPrismaAvailability(availability) }, + data: { ...rest, ...addressData, availability: toPrismaAvailability(availability) }, }); return { gym }; } catch (e) { diff --git a/api/src/swagger.ts b/api/src/swagger.ts index 1590ec5..33c3843 100644 --- a/api/src/swagger.ts +++ b/api/src/swagger.ts @@ -915,18 +915,26 @@ export const openapi: Record = { }, post: { tags: ['Admin'], - summary: 'Create gym (admin; ownerId becomes OWNER member)', + summary: 'Create REAL gym (admin; ownerId becomes OWNER member, address required)', security: [{ bearerAuth: [] }], requestBody: { content: { 'application/json': { schema: { type: 'object', - required: ['name', 'ownerId'], + required: ['name', 'ownerId', 'addressLine1', 'postalCode', 'city'], properties: { name: { type: 'string' }, ownerId: { type: 'string', description: 'User mianowany właścicielem (OWNER)' }, - location: { type: 'string' }, + addressLine1: { type: 'string', description: 'Ulica i numer, np. Mokotowska 12A' }, + addressLine2: { type: 'string', nullable: true, description: 'Lokal/piętro itp.' }, + postalCode: { type: 'string', description: 'Kod pocztowy 00-001' }, + city: { type: 'string' }, + countryCode: { type: 'string', default: 'PL', description: 'ISO 3166-1 alpha-2' }, + location: { + type: 'string', + description: 'Pole derivowane z adresu (ulica, kod miasto[, kraj]) — nie do zapisu', + }, availability: { type: 'array', description: '7 dni (Pon-Niedz), każdy null lub { start, end }', @@ -977,9 +985,28 @@ export const openapi: Record = { '/admin/gyms/{id}': { patch: { tags: ['Admin'], - summary: 'Update gym (admin)', + summary: 'Update gym (admin; address fields recompute derived location)', security: [{ bearerAuth: [] }], parameters: [{ name: 'id', in: 'path', required: true, schema: { type: 'string' } }], + requestBody: { + content: { + 'application/json': { + schema: { + type: 'object', + properties: { + name: { type: 'string' }, + addressLine1: { type: 'string', nullable: true }, + addressLine2: { type: 'string', nullable: true }, + postalCode: { type: 'string', nullable: true, description: 'Kod pocztowy 00-001' }, + city: { type: 'string', nullable: true }, + countryCode: { type: 'string', nullable: true, description: 'ISO 3166-1 alpha-2' }, + availability: { type: 'array', nullable: true, items: { type: 'object', nullable: true } }, + capacity: { type: 'integer', nullable: true }, + }, + }, + }, + }, + }, }, delete: { tags: ['Admin'], diff --git a/api/test/integration/admin.test.ts b/api/test/integration/admin.test.ts index dbd60dc..1036e50 100644 --- a/api/test/integration/admin.test.ts +++ b/api/test/integration/admin.test.ts @@ -58,10 +58,23 @@ describe('admin routes', () => { const res = await app .post('/api/v1/admin/gyms') .set('Authorization', `Bearer ${adminToken}`) - .send({ name: 'Nowa siłownia', location: 'Kraków', capacity: 50, ownerId }); + .send({ + name: 'Nowa siłownia', + addressLine1: 'Mokotowska 12', + postalCode: '00-900', + city: 'Warszawa', + capacity: 50, + ownerId, + }); expect(res.status).toBe(201); const newGymId = res.body.gym.id as string; - expect(res.body.gym).toMatchObject({ name: 'Nowa siłownia', location: 'Kraków', capacity: 50 }); + expect(res.body.gym).toMatchObject({ + name: 'Nowa siłownia', + // display string derivowany z adresu strukturalnego + location: 'Mokotowska 12, 00-900 Warszawa', + countryCode: 'PL', + capacity: 50, + }); const membership = await prisma.gymMembership.findUnique({ where: { userId_gymId: { userId: ownerId, gymId: newGymId } }, }); @@ -86,7 +99,36 @@ describe('admin routes', () => { const res = await app .post('/api/v1/admin/gyms') .set('Authorization', `Bearer ${adminToken}`) - .send({ name: 'Bez właściciela' }); + .send({ + name: 'Bez właściciela', + addressLine1: 'Polna 1', + postalCode: '00-001', + city: 'Warszawa', + }); + expect(res.status).toBe(400); + }); + + it('rejects creating a REAL gym without a structured address with 400', async () => { + const app = buildApp(); + const res = await app + .post('/api/v1/admin/gyms') + .set('Authorization', `Bearer ${adminToken}`) + .send({ name: 'Bez adresu', ownerId }); + expect(res.status).toBe(400); + }); + + it('rejects an invalid postal code with 400', async () => { + const app = buildApp(); + const res = await app + .post('/api/v1/admin/gyms') + .set('Authorization', `Bearer ${adminToken}`) + .send({ + name: 'Zły kod', + addressLine1: 'Polna 1', + postalCode: '00001', + city: 'Warszawa', + ownerId, + }); expect(res.status).toBe(400); }); @@ -95,7 +137,13 @@ describe('admin routes', () => { const res = await app .post('/api/v1/admin/gyms') .set('Authorization', `Bearer ${adminToken}`) - .send({ name: 'Nieistniejący właściciel', ownerId: 'no-such-user' }); + .send({ + name: 'Nieistniejący właściciel', + addressLine1: 'Polna 1', + postalCode: '00-001', + city: 'Warszawa', + ownerId: 'no-such-user', + }); expect(res.status).toBe(404); }); @@ -136,19 +184,29 @@ describe('admin routes', () => { expect(delAgain.status).toBe(404); }); - it('updates a gym', async () => { + it('updates a gym and recomputes location from partial address changes', async () => { const app = buildApp(); const created = await app .post('/api/v1/admin/gyms') .set('Authorization', `Bearer ${adminToken}`) - .send({ name: 'Do edycji', ownerId: ownerId2 }); + .send({ + name: 'Do edycji', + addressLine1: 'Długa 1', + postalCode: '80-001', + city: 'Gdańsk', + ownerId: ownerId2, + }); const id = created.body.gym.id; const res = await app .patch(`/api/v1/admin/gyms/${id}`) .set('Authorization', `Bearer ${adminToken}`) - .send({ location: 'Gdańsk', capacity: null }); + .send({ postalCode: '80-100', capacity: null }); expect(res.status).toBe(200); - expect(res.body.gym).toMatchObject({ location: 'Gdańsk', capacity: null }); + expect(res.body.gym).toMatchObject({ + // scalenie z resztą adresu w bazie + przeliczenie display stringa + location: 'Długa 1, 80-100 Gdańsk', + capacity: null, + }); }); it('returns 404 when updating an unknown gym', async () => { @@ -165,7 +223,13 @@ describe('admin routes', () => { const created = await app .post('/api/v1/admin/gyms') .set('Authorization', `Bearer ${adminToken}`) - .send({ name: 'Do usunięcia', ownerId: ownerId2 }); + .send({ + name: 'Do usunięcia', + addressLine1: 'Krótka 3', + postalCode: '02-001', + city: 'Warszawa', + ownerId: ownerId2, + }); const id = created.body.gym.id; const res = await app.delete(`/api/v1/admin/gyms/${id}`).set('Authorization', `Bearer ${adminToken}`); expect(res.status).toBe(204);