Compare commits
2
Commits
97abb808b8
...
715ca585a8
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
715ca585a8 | ||
|
|
2d6bae2ba1 |
+8
-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
|
||||||
@@ -16,8 +18,12 @@ OTP_REQUEST_MAX_PER_HOUR=5
|
|||||||
# Dev/test only: returns OTP code in API response instead of sending SMS
|
# Dev/test only: returns OTP code in API response instead of sending SMS
|
||||||
AUTH_RETURN_OTP=true
|
AUTH_RETURN_OTP=true
|
||||||
|
|
||||||
|
# Local folder for business images (served at /uploads/...)
|
||||||
|
UPLOAD_DIR=uploads
|
||||||
|
|
||||||
# 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)
|
||||||
|
|||||||
@@ -21,3 +21,6 @@ npm-debug.log*
|
|||||||
# Test / coverage
|
# Test / coverage
|
||||||
coverage/
|
coverage/
|
||||||
.nyc_output/
|
.nyc_output/
|
||||||
|
|
||||||
|
# User uploads
|
||||||
|
uploads/
|
||||||
|
|||||||
@@ -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,50 @@
|
|||||||
|
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 { BusinessImageEntity } from '../../entities/business-image.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,
|
||||||
|
onBeforeDeleteBusiness?: (businessId: string) => Promise<void>,
|
||||||
|
): Promise<void> {
|
||||||
|
await manager.delete(BookingEntity, { businessId });
|
||||||
|
await manager.delete(BusinessServiceEntity, { businessId });
|
||||||
|
await manager.delete(BusinessAttributeValueEntity, { businessId });
|
||||||
|
await manager.delete(BusinessImageEntity, { businessId });
|
||||||
|
if (onBeforeDeleteBusiness) {
|
||||||
|
await onBeforeDeleteBusiness(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[],
|
||||||
|
onBeforeDeleteBusiness?: (businessId: string) => Promise<void>,
|
||||||
|
): Promise<void> {
|
||||||
|
for (const businessId of businessIds) {
|
||||||
|
await deleteBusinessCascade(manager, businessId, onBeforeDeleteBusiness);
|
||||||
|
}
|
||||||
|
|
||||||
|
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);
|
||||||
|
}
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
import {
|
||||||
|
Column,
|
||||||
|
CreateDateColumn,
|
||||||
|
Entity,
|
||||||
|
JoinColumn,
|
||||||
|
ManyToOne,
|
||||||
|
PrimaryGeneratedColumn,
|
||||||
|
} from 'typeorm';
|
||||||
|
import { BusinessEntity } from './business.entity';
|
||||||
|
|
||||||
|
@Entity('business_images')
|
||||||
|
export class BusinessImageEntity {
|
||||||
|
@PrimaryGeneratedColumn('uuid')
|
||||||
|
id!: string;
|
||||||
|
|
||||||
|
@ManyToOne(() => BusinessEntity, (business) => business.images, {
|
||||||
|
onDelete: 'CASCADE',
|
||||||
|
})
|
||||||
|
@JoinColumn({ name: 'businessId' })
|
||||||
|
business!: BusinessEntity;
|
||||||
|
|
||||||
|
@Column('uuid')
|
||||||
|
businessId!: string;
|
||||||
|
|
||||||
|
/** Relative path under uploads root, e.g. businesses/{id}/{file}.jpg */
|
||||||
|
@Column({ length: 500 })
|
||||||
|
url!: string;
|
||||||
|
|
||||||
|
@Column({ type: 'varchar', nullable: true, length: 255 })
|
||||||
|
originalName!: string | null;
|
||||||
|
|
||||||
|
@Column({ default: 0 })
|
||||||
|
sortOrder!: number;
|
||||||
|
|
||||||
|
@Column({ default: false })
|
||||||
|
isCover!: boolean;
|
||||||
|
|
||||||
|
@CreateDateColumn()
|
||||||
|
createdAt!: Date;
|
||||||
|
}
|
||||||
@@ -11,6 +11,7 @@ import {
|
|||||||
import { BookingEntity } from './booking.entity';
|
import { BookingEntity } from './booking.entity';
|
||||||
import { BusinessAttributeValueEntity } from './business-attribute-value.entity';
|
import { BusinessAttributeValueEntity } from './business-attribute-value.entity';
|
||||||
import { BusinessCategoryEntity } from './business-category.entity';
|
import { BusinessCategoryEntity } from './business-category.entity';
|
||||||
|
import { BusinessImageEntity } from './business-image.entity';
|
||||||
import { BusinessServiceEntity } from './business-service.entity';
|
import { BusinessServiceEntity } from './business-service.entity';
|
||||||
import { UserEntity } from './user.entity';
|
import { UserEntity } from './user.entity';
|
||||||
|
|
||||||
@@ -62,6 +63,11 @@ export class BusinessEntity {
|
|||||||
@Column({ type: 'uuid', nullable: true })
|
@Column({ type: 'uuid', nullable: true })
|
||||||
ownerId!: string | null;
|
ownerId!: string | null;
|
||||||
|
|
||||||
|
@OneToMany(() => BusinessImageEntity, (image) => image.business, {
|
||||||
|
cascade: true,
|
||||||
|
})
|
||||||
|
images!: BusinessImageEntity[];
|
||||||
|
|
||||||
@OneToMany(() => BusinessServiceEntity, (service) => service.business)
|
@OneToMany(() => BusinessServiceEntity, (service) => service.business)
|
||||||
services!: BusinessServiceEntity[];
|
services!: BusinessServiceEntity[];
|
||||||
|
|
||||||
|
|||||||
+7
-1
@@ -1,7 +1,10 @@
|
|||||||
import 'reflect-metadata';
|
import 'reflect-metadata';
|
||||||
import { ValidationPipe } from '@nestjs/common';
|
import { ValidationPipe } from '@nestjs/common';
|
||||||
import { NestFactory } from '@nestjs/core';
|
import { NestFactory } from '@nestjs/core';
|
||||||
|
import { NestExpressApplication } from '@nestjs/platform-express';
|
||||||
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
|
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
|
||||||
|
import { join } from 'path';
|
||||||
|
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>>) {
|
||||||
@@ -17,7 +20,9 @@ function configureCors(app: Awaited<ReturnType<typeof NestFactory.create>>) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function bootstrap() {
|
async function bootstrap() {
|
||||||
const app = await NestFactory.create(AppModule);
|
const app = await NestFactory.create<NestExpressApplication>(AppModule);
|
||||||
|
const uploadDir = process.env.UPLOAD_DIR ?? 'uploads';
|
||||||
|
app.useStaticAssets(join(process.cwd(), uploadDir), { prefix: '/uploads' });
|
||||||
configureCors(app);
|
configureCors(app);
|
||||||
app.useGlobalPipes(
|
app.useGlobalPipes(
|
||||||
new ValidationPipe({
|
new ValidationPipe({
|
||||||
@@ -26,6 +31,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,18 @@
|
|||||||
import { Module } from '@nestjs/common';
|
import { Module, forwardRef } 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 { BusinessesModule } from '../businesses/businesses.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]),
|
||||||
|
forwardRef(() => BusinessesModule),
|
||||||
|
AuthModule,
|
||||||
|
],
|
||||||
controllers: [BusinessCategoriesController],
|
controllers: [BusinessCategoriesController],
|
||||||
providers: [BusinessCategoriesService],
|
providers: [BusinessCategoriesService],
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -4,8 +4,11 @@ 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 { BusinessImagesService } from '../businesses/business-images.service';
|
||||||
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 +17,10 @@ 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,
|
||||||
|
private readonly images: BusinessImagesService,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
findAll(): Promise<BusinessCategoryEntity[]> {
|
findAll(): Promise<BusinessCategoryEntity[]> {
|
||||||
@@ -62,9 +69,18 @@ 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'],
|
||||||
|
});
|
||||||
|
|
||||||
|
const businessIds = businesses.map((b) => b.id);
|
||||||
|
await this.dataSource.transaction(async (manager) => {
|
||||||
|
await deleteCategoryCascade(manager, id, businessIds, async (businessId) => {
|
||||||
|
await this.images.removeAllForBusiness(businessId);
|
||||||
|
});
|
||||||
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,151 @@
|
|||||||
|
import {
|
||||||
|
BadRequestException,
|
||||||
|
Injectable,
|
||||||
|
NotFoundException,
|
||||||
|
} from '@nestjs/common';
|
||||||
|
import { InjectRepository } from '@nestjs/typeorm';
|
||||||
|
import { randomUUID } from 'crypto';
|
||||||
|
import { existsSync, mkdirSync, unlinkSync } from 'fs';
|
||||||
|
import { extname, join } from 'path';
|
||||||
|
import { Repository } from 'typeorm';
|
||||||
|
import { BusinessImageEntity } from '../../entities/business-image.entity';
|
||||||
|
import { BusinessEntity } from '../../entities/business.entity';
|
||||||
|
|
||||||
|
const ALLOWED_MIME = new Set([
|
||||||
|
'image/jpeg',
|
||||||
|
'image/png',
|
||||||
|
'image/webp',
|
||||||
|
'image/gif',
|
||||||
|
]);
|
||||||
|
const MAX_FILE_BYTES = 5 * 1024 * 1024;
|
||||||
|
const MAX_IMAGES_PER_BUSINESS = 10;
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class BusinessImagesService {
|
||||||
|
private readonly uploadRoot: string;
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
@InjectRepository(BusinessImageEntity)
|
||||||
|
private readonly imageRepo: Repository<BusinessImageEntity>,
|
||||||
|
@InjectRepository(BusinessEntity)
|
||||||
|
private readonly businessRepo: Repository<BusinessEntity>,
|
||||||
|
) {
|
||||||
|
this.uploadRoot = join(process.cwd(), process.env.UPLOAD_DIR ?? 'uploads');
|
||||||
|
}
|
||||||
|
|
||||||
|
async listForBusiness(businessId: string): Promise<BusinessImageEntity[]> {
|
||||||
|
await this.ensureBusiness(businessId);
|
||||||
|
return this.imageRepo.find({
|
||||||
|
where: { businessId },
|
||||||
|
order: { isCover: 'DESC', sortOrder: 'ASC', createdAt: 'ASC' },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async upload(
|
||||||
|
businessId: string,
|
||||||
|
files: Express.Multer.File[],
|
||||||
|
): Promise<BusinessImageEntity[]> {
|
||||||
|
await this.ensureBusiness(businessId);
|
||||||
|
|
||||||
|
if (!files?.length) {
|
||||||
|
throw new BadRequestException('At least one image file is required');
|
||||||
|
}
|
||||||
|
|
||||||
|
const existing = await this.imageRepo.count({ where: { businessId } });
|
||||||
|
if (existing + files.length > MAX_IMAGES_PER_BUSINESS) {
|
||||||
|
throw new BadRequestException(
|
||||||
|
`Maximum ${MAX_IMAGES_PER_BUSINESS} images per business`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const dir = join(this.uploadRoot, 'businesses', businessId);
|
||||||
|
mkdirSync(dir, { recursive: true });
|
||||||
|
|
||||||
|
const hasCover = await this.imageRepo.exists({
|
||||||
|
where: { businessId, isCover: true },
|
||||||
|
});
|
||||||
|
|
||||||
|
const saved: BusinessImageEntity[] = [];
|
||||||
|
let sortOrder = existing;
|
||||||
|
|
||||||
|
for (const file of files) {
|
||||||
|
this.validateFile(file);
|
||||||
|
const ext = extname(file.originalname).toLowerCase() || '.jpg';
|
||||||
|
const filename = `${randomUUID()}${ext}`;
|
||||||
|
const relativeUrl = `businesses/${businessId}/${filename}`;
|
||||||
|
const absolutePath = join(this.uploadRoot, relativeUrl);
|
||||||
|
|
||||||
|
const { writeFileSync } = await import('fs');
|
||||||
|
writeFileSync(absolutePath, file.buffer);
|
||||||
|
|
||||||
|
const entity = this.imageRepo.create({
|
||||||
|
businessId,
|
||||||
|
url: relativeUrl,
|
||||||
|
originalName: file.originalname,
|
||||||
|
sortOrder,
|
||||||
|
isCover: !hasCover && saved.length === 0,
|
||||||
|
});
|
||||||
|
saved.push(await this.imageRepo.save(entity));
|
||||||
|
sortOrder += 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
return saved;
|
||||||
|
}
|
||||||
|
|
||||||
|
async remove(businessId: string, imageId: string): Promise<void> {
|
||||||
|
const image = await this.imageRepo.findOne({
|
||||||
|
where: { id: imageId, businessId },
|
||||||
|
});
|
||||||
|
if (!image) {
|
||||||
|
throw new NotFoundException('Image not found');
|
||||||
|
}
|
||||||
|
|
||||||
|
this.deleteFile(image.url);
|
||||||
|
const wasCover = image.isCover;
|
||||||
|
await this.imageRepo.remove(image);
|
||||||
|
|
||||||
|
if (wasCover) {
|
||||||
|
const next = await this.imageRepo.findOne({
|
||||||
|
where: { businessId },
|
||||||
|
order: { sortOrder: 'ASC', createdAt: 'ASC' },
|
||||||
|
});
|
||||||
|
if (next) {
|
||||||
|
next.isCover = true;
|
||||||
|
await this.imageRepo.save(next);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async removeAllForBusiness(businessId: string): Promise<void> {
|
||||||
|
const images = await this.imageRepo.find({ where: { businessId } });
|
||||||
|
for (const image of images) {
|
||||||
|
this.deleteFile(image.url);
|
||||||
|
}
|
||||||
|
await this.imageRepo.delete({ businessId });
|
||||||
|
}
|
||||||
|
|
||||||
|
private validateFile(file: Express.Multer.File): void {
|
||||||
|
if (!ALLOWED_MIME.has(file.mimetype)) {
|
||||||
|
throw new BadRequestException(
|
||||||
|
'Only JPEG, PNG, WebP and GIF images are allowed',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (file.size > MAX_FILE_BYTES) {
|
||||||
|
throw new BadRequestException('Image must be at most 5 MB');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private deleteFile(relativeUrl: string): void {
|
||||||
|
const absolutePath = join(this.uploadRoot, relativeUrl);
|
||||||
|
if (existsSync(absolutePath)) {
|
||||||
|
unlinkSync(absolutePath);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async ensureBusiness(businessId: string): Promise<void> {
|
||||||
|
const exists = await this.businessRepo.exists({ where: { id: businessId } });
|
||||||
|
if (!exists) {
|
||||||
|
throw new NotFoundException('Business not found');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -7,8 +7,13 @@ import {
|
|||||||
Patch,
|
Patch,
|
||||||
Post,
|
Post,
|
||||||
Query,
|
Query,
|
||||||
|
UploadedFiles,
|
||||||
UseGuards,
|
UseGuards,
|
||||||
|
UseInterceptors,
|
||||||
} from '@nestjs/common';
|
} from '@nestjs/common';
|
||||||
|
import { FilesInterceptor } from '@nestjs/platform-express';
|
||||||
|
import { memoryStorage } from 'multer';
|
||||||
|
import { BusinessImageEntity } from '../../entities/business-image.entity';
|
||||||
import { BusinessEntity } from '../../entities/business.entity';
|
import { BusinessEntity } from '../../entities/business.entity';
|
||||||
import { UserRole } from '../../entities/user.entity';
|
import { UserRole } from '../../entities/user.entity';
|
||||||
import { AuthUser } from '../auth/auth.types';
|
import { AuthUser } from '../auth/auth.types';
|
||||||
@@ -16,6 +21,7 @@ import { CurrentUser } from '../auth/decorators/current-user.decorator';
|
|||||||
import { Roles } from '../auth/decorators/roles.decorator';
|
import { Roles } from '../auth/decorators/roles.decorator';
|
||||||
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
|
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
|
||||||
import { RolesGuard } from '../auth/guards/roles.guard';
|
import { RolesGuard } from '../auth/guards/roles.guard';
|
||||||
|
import { BusinessImagesService } from './business-images.service';
|
||||||
import { BusinessesService } from './businesses.service';
|
import { BusinessesService } from './businesses.service';
|
||||||
import { AssignBusinessOwnerDto } from './dto/assign-business-owner.dto';
|
import { AssignBusinessOwnerDto } from './dto/assign-business-owner.dto';
|
||||||
import { CreateBusinessDto } from './dto/create-business.dto';
|
import { CreateBusinessDto } from './dto/create-business.dto';
|
||||||
@@ -23,7 +29,10 @@ import { UpdateBusinessDto } from './dto/update-business.dto';
|
|||||||
|
|
||||||
@Controller('businesses')
|
@Controller('businesses')
|
||||||
export class BusinessesController {
|
export class BusinessesController {
|
||||||
constructor(private readonly service: BusinessesService) {}
|
constructor(
|
||||||
|
private readonly service: BusinessesService,
|
||||||
|
private readonly images: BusinessImagesService,
|
||||||
|
) {}
|
||||||
|
|
||||||
@Get()
|
@Get()
|
||||||
findAll(
|
findAll(
|
||||||
@@ -51,6 +60,33 @@ export class BusinessesController {
|
|||||||
return this.service.create(payload);
|
return this.service.create(payload);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Post(':id/images')
|
||||||
|
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||||
|
@Roles(UserRole.ADMIN)
|
||||||
|
@UseInterceptors(
|
||||||
|
FilesInterceptor('files', 10, {
|
||||||
|
storage: memoryStorage(),
|
||||||
|
limits: { fileSize: 5 * 1024 * 1024 },
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
uploadImages(
|
||||||
|
@Param('id') id: string,
|
||||||
|
@UploadedFiles() files: Express.Multer.File[],
|
||||||
|
): Promise<BusinessImageEntity[]> {
|
||||||
|
return this.images.upload(id, files);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Delete(':id/images/:imageId')
|
||||||
|
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||||
|
@Roles(UserRole.ADMIN)
|
||||||
|
async removeImage(
|
||||||
|
@Param('id') id: string,
|
||||||
|
@Param('imageId') imageId: string,
|
||||||
|
): Promise<{ success: true }> {
|
||||||
|
await this.images.remove(id, imageId);
|
||||||
|
return { success: true };
|
||||||
|
}
|
||||||
|
|
||||||
@Post(':id/assign-owner')
|
@Post(':id/assign-owner')
|
||||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||||
@Roles(UserRole.ADMIN)
|
@Roles(UserRole.ADMIN)
|
||||||
|
|||||||
@@ -1,18 +1,26 @@
|
|||||||
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 { BusinessImageEntity } from '../../entities/business-image.entity';
|
||||||
import { BusinessEntity } from '../../entities/business.entity';
|
import { BusinessEntity } from '../../entities/business.entity';
|
||||||
import { UserEntity } from '../../entities/user.entity';
|
import { UserEntity } from '../../entities/user.entity';
|
||||||
import { AuthModule } from '../auth/auth.module';
|
import { AuthModule } from '../auth/auth.module';
|
||||||
|
import { BusinessImagesService } from './business-images.service';
|
||||||
import { BusinessesController } from './businesses.controller';
|
import { BusinessesController } from './businesses.controller';
|
||||||
import { BusinessesService } from './businesses.service';
|
import { BusinessesService } from './businesses.service';
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [
|
imports: [
|
||||||
TypeOrmModule.forFeature([BusinessEntity, BusinessCategoryEntity, UserEntity]),
|
TypeOrmModule.forFeature([
|
||||||
|
BusinessEntity,
|
||||||
|
BusinessCategoryEntity,
|
||||||
|
UserEntity,
|
||||||
|
BusinessImageEntity,
|
||||||
|
]),
|
||||||
AuthModule,
|
AuthModule,
|
||||||
],
|
],
|
||||||
controllers: [BusinessesController],
|
controllers: [BusinessesController],
|
||||||
providers: [BusinessesService],
|
providers: [BusinessesService, BusinessImagesService],
|
||||||
|
exports: [BusinessImagesService],
|
||||||
})
|
})
|
||||||
export class BusinessesModule {}
|
export class BusinessesModule {}
|
||||||
|
|||||||
@@ -6,7 +6,9 @@ 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 { BusinessImagesService } from './business-images.service';
|
||||||
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,13 +31,18 @@ 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,
|
||||||
|
private readonly images: BusinessImagesService,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
async findAll(filters: FindAllFilters): Promise<BusinessEntity[]> {
|
async findAll(filters: FindAllFilters): Promise<BusinessEntity[]> {
|
||||||
const query = this.repo
|
const query = this.repo
|
||||||
.createQueryBuilder('business')
|
.createQueryBuilder('business')
|
||||||
.leftJoinAndSelect('business.category', 'category')
|
.leftJoinAndSelect('business.category', 'category')
|
||||||
.orderBy('business.createdAt', 'DESC');
|
.leftJoinAndSelect('business.images', 'images')
|
||||||
|
.orderBy('business.createdAt', 'DESC')
|
||||||
|
.addOrderBy('images.isCover', 'DESC')
|
||||||
|
.addOrderBy('images.sortOrder', 'ASC');
|
||||||
|
|
||||||
if (filters.categoryId) {
|
if (filters.categoryId) {
|
||||||
query.andWhere('business.categoryId = :categoryId', {
|
query.andWhere('business.categoryId = :categoryId', {
|
||||||
@@ -55,7 +62,7 @@ export class BusinessesService {
|
|||||||
async findOne(id: string): Promise<BusinessEntity> {
|
async findOne(id: string): Promise<BusinessEntity> {
|
||||||
const business = await this.repo.findOne({
|
const business = await this.repo.findOne({
|
||||||
where: { id },
|
where: { id },
|
||||||
relations: { category: true },
|
relations: { category: true, images: true },
|
||||||
});
|
});
|
||||||
if (!business) {
|
if (!business) {
|
||||||
throw new NotFoundException('Business not found');
|
throw new NotFoundException('Business not found');
|
||||||
@@ -111,10 +118,13 @@ 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 (businessId) => {
|
||||||
|
await this.images.removeAllForBusiness(businessId);
|
||||||
|
});
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
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 })
|
||||||
|
|||||||
Vendored
+21
@@ -0,0 +1,21 @@
|
|||||||
|
declare namespace Express {
|
||||||
|
namespace Multer {
|
||||||
|
interface File {
|
||||||
|
fieldname: string;
|
||||||
|
originalname: string;
|
||||||
|
encoding: string;
|
||||||
|
mimetype: string;
|
||||||
|
size: number;
|
||||||
|
buffer: Buffer;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
declare module 'multer' {
|
||||||
|
import { RequestHandler } from 'express';
|
||||||
|
export function memoryStorage(): unknown;
|
||||||
|
export interface Options {
|
||||||
|
storage?: unknown;
|
||||||
|
limits?: { fileSize?: number };
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user