API: strukturalny adres silowni (ulica/kod/miasto/kraj); location derivowane, adres wymagany przy tworzeniu REAL
This commit is contained in:
36
api/src/lib/address.ts
Normal file
36
api/src/lib/address.ts
Normal file
@@ -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;
|
||||
}
|
||||
@@ -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}$/),
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -915,18 +915,26 @@ export const openapi: Record<string, unknown> = {
|
||||
},
|
||||
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<string, unknown> = {
|
||||
'/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'],
|
||||
|
||||
Reference in New Issue
Block a user