Fix mobile validation, cascade delete for businesses/categories, and DB error handling.
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
+5
-2
@@ -1,7 +1,9 @@
|
|||||||
DB_HOST=127.0.0.1
|
DB_HOST=127.0.0.1
|
||||||
|
# Local Docker (docker compose up -d): 5432
|
||||||
|
# Remote DB via SSH tunnel (-L 5433:127.0.0.1:5432): 5433
|
||||||
POSTGRES_PORT=5432
|
POSTGRES_PORT=5432
|
||||||
POSTGRES_USER=montime
|
POSTGRES_USER=montime
|
||||||
POSTGRES_PASSWORD=change_me
|
POSTGRES_PASSWORD=montime
|
||||||
POSTGRES_DB=montime
|
POSTGRES_DB=montime
|
||||||
# Dev only: auto-sync schema from entities (do not use true in production)
|
# Dev only: auto-sync schema from entities (do not use true in production)
|
||||||
DB_SYNC=true
|
DB_SYNC=true
|
||||||
@@ -17,7 +19,8 @@ OTP_REQUEST_MAX_PER_HOUR=5
|
|||||||
AUTH_RETURN_OTP=true
|
AUTH_RETURN_OTP=true
|
||||||
|
|
||||||
# Comma-separated frontend origins (required in production for browser clients)
|
# Comma-separated frontend origins (required in production for browser clients)
|
||||||
# CORS_ORIGINS=https://app.example.com,http://localhost:5173
|
# Include both dev ports if calling API directly (without Vite /api proxy)
|
||||||
|
CORS_ORIGINS=https://montime.ir,https://adm.montime.ir,http://localhost:5173,http://localhost:5174
|
||||||
|
|
||||||
# 0098sms.com — used when AUTH_RETURN_OTP is not true
|
# 0098sms.com — used when AUTH_RETURN_OTP is not true
|
||||||
# From panel: account username, password (or web service password), approved sender line (FROM)
|
# From panel: account username, password (or web service password), approved sender line (FROM)
|
||||||
|
|||||||
@@ -0,0 +1,23 @@
|
|||||||
|
# PostgreSQL for local development (no SSH tunnel).
|
||||||
|
# Start: docker compose up -d
|
||||||
|
# Stop: docker compose down
|
||||||
|
services:
|
||||||
|
postgres:
|
||||||
|
image: postgres:16-alpine
|
||||||
|
restart: unless-stopped
|
||||||
|
ports:
|
||||||
|
- '5432:5432'
|
||||||
|
environment:
|
||||||
|
POSTGRES_USER: montime
|
||||||
|
POSTGRES_PASSWORD: montime
|
||||||
|
POSTGRES_DB: montime
|
||||||
|
volumes:
|
||||||
|
- montime_pg_data:/var/lib/postgresql/data
|
||||||
|
healthcheck:
|
||||||
|
test: ['CMD-SHELL', 'pg_isready -U montime -d montime']
|
||||||
|
interval: 5s
|
||||||
|
timeout: 5s
|
||||||
|
retries: 5
|
||||||
|
|
||||||
|
volumes:
|
||||||
|
montime_pg_data:
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
import {
|
||||||
|
registerDecorator,
|
||||||
|
ValidationOptions,
|
||||||
|
ValidationArguments,
|
||||||
|
} from 'class-validator';
|
||||||
|
import {
|
||||||
|
isValidIranMobile,
|
||||||
|
normalizeIranMobile,
|
||||||
|
} from '../utils/iran-mobile.util';
|
||||||
|
|
||||||
|
export function IsIranMobile(validationOptions?: ValidationOptions) {
|
||||||
|
return function (object: object, propertyName: string) {
|
||||||
|
registerDecorator({
|
||||||
|
name: 'isIranMobile',
|
||||||
|
target: object.constructor,
|
||||||
|
propertyName,
|
||||||
|
options: {
|
||||||
|
message: 'mobile must be a valid mobile number',
|
||||||
|
...validationOptions,
|
||||||
|
},
|
||||||
|
validator: {
|
||||||
|
validate(value: unknown, args: ValidationArguments) {
|
||||||
|
if (value === undefined || value === null || value === '') {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
const normalized = normalizeIranMobile(String(value));
|
||||||
|
(args.object as Record<string, unknown>)[propertyName] = normalized;
|
||||||
|
return isValidIranMobile(normalized);
|
||||||
|
},
|
||||||
|
defaultMessage() {
|
||||||
|
return 'mobile must be a valid mobile number';
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
import {
|
||||||
|
ArgumentsHost,
|
||||||
|
Catch,
|
||||||
|
ConflictException,
|
||||||
|
ExceptionFilter,
|
||||||
|
HttpStatus,
|
||||||
|
InternalServerErrorException,
|
||||||
|
Logger,
|
||||||
|
} from '@nestjs/common';
|
||||||
|
import { QueryFailedError } from 'typeorm';
|
||||||
|
|
||||||
|
@Catch(QueryFailedError)
|
||||||
|
export class TypeOrmExceptionFilter implements ExceptionFilter {
|
||||||
|
private readonly logger = new Logger(TypeOrmExceptionFilter.name);
|
||||||
|
|
||||||
|
catch(exception: QueryFailedError, host: ArgumentsHost) {
|
||||||
|
const ctx = host.switchToHttp();
|
||||||
|
const response = ctx.getResponse();
|
||||||
|
const driver = exception.driverError as { code?: string; detail?: string };
|
||||||
|
|
||||||
|
if (driver?.code === '23503') {
|
||||||
|
response.status(HttpStatus.CONFLICT).json({
|
||||||
|
statusCode: HttpStatus.CONFLICT,
|
||||||
|
message:
|
||||||
|
'Cannot delete: related records still exist. Remove bookings and linked data first.',
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (driver?.code === '23505') {
|
||||||
|
response.status(HttpStatus.CONFLICT).json({
|
||||||
|
statusCode: HttpStatus.CONFLICT,
|
||||||
|
message: 'A record with the same unique value already exists.',
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.logger.error(exception.message, exception.stack);
|
||||||
|
const internal = new InternalServerErrorException();
|
||||||
|
response.status(internal.getStatus()).json(internal.getResponse());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
import { NotFoundException } from '@nestjs/common';
|
||||||
|
import { EntityManager } from 'typeorm';
|
||||||
|
import { AttributeDefinitionEntity } from '../../entities/attribute-definition.entity';
|
||||||
|
import { BookingEntity } from '../../entities/booking.entity';
|
||||||
|
import { BusinessAttributeValueEntity } from '../../entities/business-attribute-value.entity';
|
||||||
|
import { BusinessCategoryEntity } from '../../entities/business-category.entity';
|
||||||
|
import { BusinessServiceEntity } from '../../entities/business-service.entity';
|
||||||
|
import { BusinessEntity } from '../../entities/business.entity';
|
||||||
|
import { ServiceTemplateEntity } from '../../entities/service-template.entity';
|
||||||
|
|
||||||
|
/** Remove a business and all rows that block FK deletes in production DB. */
|
||||||
|
export async function deleteBusinessCascade(
|
||||||
|
manager: EntityManager,
|
||||||
|
businessId: string,
|
||||||
|
): Promise<void> {
|
||||||
|
await manager.delete(BookingEntity, { businessId });
|
||||||
|
await manager.delete(BusinessServiceEntity, { businessId });
|
||||||
|
await manager.delete(BusinessAttributeValueEntity, { businessId });
|
||||||
|
|
||||||
|
const result = await manager.delete(BusinessEntity, businessId);
|
||||||
|
if (!result.affected) {
|
||||||
|
throw new NotFoundException('Business not found');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Remove a category after all its businesses and catalog rows are cleared. */
|
||||||
|
export async function deleteCategoryCascade(
|
||||||
|
manager: EntityManager,
|
||||||
|
categoryId: string,
|
||||||
|
businessIds: string[],
|
||||||
|
): Promise<void> {
|
||||||
|
for (const businessId of businessIds) {
|
||||||
|
await deleteBusinessCascade(manager, businessId);
|
||||||
|
}
|
||||||
|
|
||||||
|
await manager.delete(ServiceTemplateEntity, { categoryId });
|
||||||
|
await manager.delete(AttributeDefinitionEntity, { categoryId });
|
||||||
|
|
||||||
|
const result = await manager.delete(BusinessCategoryEntity, categoryId);
|
||||||
|
if (!result.affected) {
|
||||||
|
throw new NotFoundException('Business category not found');
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
const PERSIAN_DIGITS = '۰۱۲۳۴۵۶۷۸۹';
|
||||||
|
const ARABIC_DIGITS = '٠١٢٣٤٥٦٧٨٩';
|
||||||
|
const INVISIBLE_CHARS = /[\u200c\u200d\u202a-\u202e\ufeff]/g;
|
||||||
|
|
||||||
|
export const IRAN_MOBILE_REGEX = /^09\d{9}$/;
|
||||||
|
|
||||||
|
function toAsciiDigits(value: string): string {
|
||||||
|
return value.replace(/[۰-۹٠-٩]/g, (ch) => {
|
||||||
|
const persian = PERSIAN_DIGITS.indexOf(ch);
|
||||||
|
if (persian >= 0) return String(persian);
|
||||||
|
const arabic = ARABIC_DIGITS.indexOf(ch);
|
||||||
|
if (arabic >= 0) return String(arabic);
|
||||||
|
return ch;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Normalize Iranian mobile to 09xxxxxxxxx (11 digits). */
|
||||||
|
export function normalizeIranMobile(raw: string): string {
|
||||||
|
let mobile = toAsciiDigits(String(raw ?? '').trim());
|
||||||
|
mobile = mobile.replace(INVISIBLE_CHARS, '');
|
||||||
|
|
||||||
|
let digits = mobile.replace(/\D/g, '');
|
||||||
|
if (!digits) return '';
|
||||||
|
|
||||||
|
if (digits.startsWith('0098')) {
|
||||||
|
digits = digits.slice(2);
|
||||||
|
}
|
||||||
|
if (digits.startsWith('98') && digits.length >= 12) {
|
||||||
|
digits = `0${digits.slice(2)}`;
|
||||||
|
} else if (digits.startsWith('9') && digits.length === 10) {
|
||||||
|
digits = `0${digits}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
return digits;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isValidIranMobile(mobile: string): boolean {
|
||||||
|
return IRAN_MOBILE_REGEX.test(mobile);
|
||||||
|
}
|
||||||
@@ -2,6 +2,7 @@ import 'reflect-metadata';
|
|||||||
import { ValidationPipe } from '@nestjs/common';
|
import { ValidationPipe } from '@nestjs/common';
|
||||||
import { NestFactory } from '@nestjs/core';
|
import { NestFactory } from '@nestjs/core';
|
||||||
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
|
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
|
||||||
|
import { TypeOrmExceptionFilter } from './common/filters/typeorm-exception.filter';
|
||||||
import { AppModule } from './app.module';
|
import { AppModule } from './app.module';
|
||||||
|
|
||||||
function configureCors(app: Awaited<ReturnType<typeof NestFactory.create>>) {
|
function configureCors(app: Awaited<ReturnType<typeof NestFactory.create>>) {
|
||||||
@@ -26,6 +27,7 @@ async function bootstrap() {
|
|||||||
whitelist: true,
|
whitelist: true,
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
app.useGlobalFilters(new TypeOrmExceptionFilter());
|
||||||
|
|
||||||
const swaggerConfig = new DocumentBuilder()
|
const swaggerConfig = new DocumentBuilder()
|
||||||
.setTitle('Montime API')
|
.setTitle('Montime API')
|
||||||
|
|||||||
@@ -12,6 +12,10 @@ import { JwtService } from '@nestjs/jwt';
|
|||||||
import { InjectRepository } from '@nestjs/typeorm';
|
import { InjectRepository } from '@nestjs/typeorm';
|
||||||
import { createHash, randomInt } from 'crypto';
|
import { createHash, randomInt } from 'crypto';
|
||||||
import { IsNull, MoreThan, Repository } from 'typeorm';
|
import { IsNull, MoreThan, Repository } from 'typeorm';
|
||||||
|
import {
|
||||||
|
isValidIranMobile,
|
||||||
|
normalizeIranMobile,
|
||||||
|
} from '../../common/utils/iran-mobile.util';
|
||||||
import { AuthOtpEntity } from '../../entities/auth-otp.entity';
|
import { AuthOtpEntity } from '../../entities/auth-otp.entity';
|
||||||
import { UserEntity, UserRole } from '../../entities/user.entity';
|
import { UserEntity, UserRole } from '../../entities/user.entity';
|
||||||
import { JwtPayload } from './auth.types';
|
import { JwtPayload } from './auth.types';
|
||||||
@@ -200,8 +204,8 @@ export class AuthService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private normalizeMobile(mobile: string): string {
|
private normalizeMobile(mobile: string): string {
|
||||||
const normalized = String(mobile ?? '').trim();
|
const normalized = normalizeIranMobile(mobile);
|
||||||
if (!/^(\+?\d{10,15}|09\d{9})$/.test(normalized)) {
|
if (!isValidIranMobile(normalized)) {
|
||||||
throw new BadRequestException('Invalid mobile number');
|
throw new BadRequestException('Invalid mobile number');
|
||||||
}
|
}
|
||||||
return normalized;
|
return normalized;
|
||||||
|
|||||||
@@ -1,11 +1,10 @@
|
|||||||
import { ApiProperty } from '@nestjs/swagger';
|
import { ApiProperty } from '@nestjs/swagger';
|
||||||
import { IsString, Matches } from 'class-validator';
|
import { IsString } from 'class-validator';
|
||||||
|
import { IsIranMobile } from '../../../common/decorators/is-iran-mobile.decorator';
|
||||||
|
|
||||||
export class RequestOtpDto {
|
export class RequestOtpDto {
|
||||||
@ApiProperty({ example: '09122222222' })
|
@ApiProperty({ example: '09122222222' })
|
||||||
@IsString()
|
@IsString()
|
||||||
@Matches(/^(\+?\d{10,15}|09\d{9})$/, {
|
@IsIranMobile()
|
||||||
message: 'mobile must be a valid mobile number',
|
|
||||||
})
|
|
||||||
mobile!: string;
|
mobile!: string;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,12 +1,11 @@
|
|||||||
import { ApiProperty } from '@nestjs/swagger';
|
import { ApiProperty } from '@nestjs/swagger';
|
||||||
import { IsString, Matches } from 'class-validator';
|
import { IsString, Matches } from 'class-validator';
|
||||||
|
import { IsIranMobile } from '../../../common/decorators/is-iran-mobile.decorator';
|
||||||
|
|
||||||
export class VerifyOtpDto {
|
export class VerifyOtpDto {
|
||||||
@ApiProperty({ example: '09122222222' })
|
@ApiProperty({ example: '09122222222' })
|
||||||
@IsString()
|
@IsString()
|
||||||
@Matches(/^(\+?\d{10,15}|09\d{9})$/, {
|
@IsIranMobile()
|
||||||
message: 'mobile must be a valid mobile number',
|
|
||||||
})
|
|
||||||
mobile!: string;
|
mobile!: string;
|
||||||
|
|
||||||
@ApiProperty({ example: '123456' })
|
@ApiProperty({ example: '123456' })
|
||||||
|
|||||||
@@ -1,12 +1,16 @@
|
|||||||
import { Module } from '@nestjs/common';
|
import { Module } from '@nestjs/common';
|
||||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||||
import { BusinessCategoryEntity } from '../../entities/business-category.entity';
|
import { BusinessCategoryEntity } from '../../entities/business-category.entity';
|
||||||
|
import { BusinessEntity } from '../../entities/business.entity';
|
||||||
import { AuthModule } from '../auth/auth.module';
|
import { AuthModule } from '../auth/auth.module';
|
||||||
import { BusinessCategoriesController } from './business-categories.controller';
|
import { BusinessCategoriesController } from './business-categories.controller';
|
||||||
import { BusinessCategoriesService } from './business-categories.service';
|
import { BusinessCategoriesService } from './business-categories.service';
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [TypeOrmModule.forFeature([BusinessCategoryEntity]), AuthModule],
|
imports: [
|
||||||
|
TypeOrmModule.forFeature([BusinessCategoryEntity, BusinessEntity]),
|
||||||
|
AuthModule,
|
||||||
|
],
|
||||||
controllers: [BusinessCategoriesController],
|
controllers: [BusinessCategoriesController],
|
||||||
providers: [BusinessCategoriesService],
|
providers: [BusinessCategoriesService],
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -4,8 +4,10 @@ import {
|
|||||||
NotFoundException,
|
NotFoundException,
|
||||||
} from '@nestjs/common';
|
} from '@nestjs/common';
|
||||||
import { InjectRepository } from '@nestjs/typeorm';
|
import { InjectRepository } from '@nestjs/typeorm';
|
||||||
import { Repository } from 'typeorm';
|
import { DataSource, Repository } from 'typeorm';
|
||||||
|
import { deleteCategoryCascade } from '../../common/utils/business-cascade.util';
|
||||||
import { BusinessCategoryEntity } from '../../entities/business-category.entity';
|
import { BusinessCategoryEntity } from '../../entities/business-category.entity';
|
||||||
|
import { BusinessEntity } from '../../entities/business.entity';
|
||||||
import { CreateBusinessCategoryDto } from './dto/create-business-category.dto';
|
import { CreateBusinessCategoryDto } from './dto/create-business-category.dto';
|
||||||
import { UpdateBusinessCategoryDto } from './dto/update-business-category.dto';
|
import { UpdateBusinessCategoryDto } from './dto/update-business-category.dto';
|
||||||
|
|
||||||
@@ -14,6 +16,9 @@ export class BusinessCategoriesService {
|
|||||||
constructor(
|
constructor(
|
||||||
@InjectRepository(BusinessCategoryEntity)
|
@InjectRepository(BusinessCategoryEntity)
|
||||||
private readonly repo: Repository<BusinessCategoryEntity>,
|
private readonly repo: Repository<BusinessCategoryEntity>,
|
||||||
|
@InjectRepository(BusinessEntity)
|
||||||
|
private readonly businessRepo: Repository<BusinessEntity>,
|
||||||
|
private readonly dataSource: DataSource,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
findAll(): Promise<BusinessCategoryEntity[]> {
|
findAll(): Promise<BusinessCategoryEntity[]> {
|
||||||
@@ -62,9 +67,19 @@ export class BusinessCategoriesService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async remove(id: string): Promise<void> {
|
async remove(id: string): Promise<void> {
|
||||||
const result = await this.repo.delete(id);
|
await this.findOne(id);
|
||||||
if (!result.affected) {
|
|
||||||
throw new NotFoundException('Business category not found');
|
const businesses = await this.businessRepo.find({
|
||||||
}
|
where: { categoryId: id },
|
||||||
|
select: ['id'],
|
||||||
|
});
|
||||||
|
|
||||||
|
await this.dataSource.transaction(async (manager) => {
|
||||||
|
await deleteCategoryCascade(
|
||||||
|
manager,
|
||||||
|
id,
|
||||||
|
businesses.map((b) => b.id),
|
||||||
|
);
|
||||||
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,7 +6,8 @@ import {
|
|||||||
NotFoundException,
|
NotFoundException,
|
||||||
} from '@nestjs/common';
|
} from '@nestjs/common';
|
||||||
import { InjectRepository } from '@nestjs/typeorm';
|
import { InjectRepository } from '@nestjs/typeorm';
|
||||||
import { Repository } from 'typeorm';
|
import { DataSource, Repository } from 'typeorm';
|
||||||
|
import { deleteBusinessCascade } from '../../common/utils/business-cascade.util';
|
||||||
import { BusinessCategoryEntity } from '../../entities/business-category.entity';
|
import { BusinessCategoryEntity } from '../../entities/business-category.entity';
|
||||||
import { BusinessEntity } from '../../entities/business.entity';
|
import { BusinessEntity } from '../../entities/business.entity';
|
||||||
import { UserEntity, UserRole } from '../../entities/user.entity';
|
import { UserEntity, UserRole } from '../../entities/user.entity';
|
||||||
@@ -29,6 +30,7 @@ export class BusinessesService {
|
|||||||
private readonly categoryRepo: Repository<BusinessCategoryEntity>,
|
private readonly categoryRepo: Repository<BusinessCategoryEntity>,
|
||||||
@InjectRepository(UserEntity)
|
@InjectRepository(UserEntity)
|
||||||
private readonly userRepo: Repository<UserEntity>,
|
private readonly userRepo: Repository<UserEntity>,
|
||||||
|
private readonly dataSource: DataSource,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
async findAll(filters: FindAllFilters): Promise<BusinessEntity[]> {
|
async findAll(filters: FindAllFilters): Promise<BusinessEntity[]> {
|
||||||
@@ -111,10 +113,11 @@ export class BusinessesService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async remove(id: string): Promise<void> {
|
async remove(id: string): Promise<void> {
|
||||||
const result = await this.repo.delete(id);
|
await this.findOne(id);
|
||||||
if (!result.affected) {
|
|
||||||
throw new NotFoundException('Business not found');
|
await this.dataSource.transaction(async (manager) => {
|
||||||
}
|
await deleteBusinessCascade(manager, id);
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
async assignOwner(
|
async assignOwner(
|
||||||
|
|||||||
@@ -1,12 +1,11 @@
|
|||||||
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||||
import { IsOptional, IsString, Matches, MaxLength } from 'class-validator';
|
import { IsOptional, IsString, MaxLength } from 'class-validator';
|
||||||
|
import { IsIranMobile } from '../../../common/decorators/is-iran-mobile.decorator';
|
||||||
|
|
||||||
export class AssignBusinessOwnerDto {
|
export class AssignBusinessOwnerDto {
|
||||||
@ApiProperty({ example: '09111111111' })
|
@ApiProperty({ example: '09111111111' })
|
||||||
@IsString()
|
@IsString()
|
||||||
@Matches(/^(\+?\d{10,15}|09\d{9})$/, {
|
@IsIranMobile()
|
||||||
message: 'mobile must be a valid mobile number',
|
|
||||||
})
|
|
||||||
mobile!: string;
|
mobile!: string;
|
||||||
|
|
||||||
@ApiPropertyOptional({ example: 'Business Admin', nullable: true })
|
@ApiPropertyOptional({ example: 'Business Admin', nullable: true })
|
||||||
|
|||||||
Reference in New Issue
Block a user