Files
serverMontime/src/modules/businesses/businesses.service.ts
T

210 lines
6.2 KiB
TypeScript
Raw Normal View History

2026-05-07 21:22:50 +03:30
import {
2026-05-11 15:30:04 +03:30
BadRequestException,
2026-05-07 21:22:50 +03:30
ConflictException,
2026-05-11 12:40:42 +03:30
ForbiddenException,
2026-05-07 21:22:50 +03:30
Injectable,
NotFoundException,
} from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { DataSource, Repository } from 'typeorm';
import { deleteBusinessCascade } from '../../common/utils/business-cascade.util';
import { BusinessImagesService } from './business-images.service';
2026-05-07 21:22:50 +03:30
import { BusinessCategoryEntity } from '../../entities/business-category.entity';
import { BusinessEntity } from '../../entities/business.entity';
2026-05-11 15:30:04 +03:30
import { UserEntity, UserRole } from '../../entities/user.entity';
2026-05-11 12:40:42 +03:30
import { AuthUser } from '../auth/auth.types';
2026-05-11 15:30:04 +03:30
import { AssignBusinessOwnerDto } from './dto/assign-business-owner.dto';
2026-05-07 21:22:50 +03:30
import { CreateBusinessDto } from './dto/create-business.dto';
import { UpdateBusinessDto } from './dto/update-business.dto';
type FindAllFilters = {
categoryId?: string;
isActive?: boolean;
};
@Injectable()
export class BusinessesService {
constructor(
@InjectRepository(BusinessEntity)
private readonly repo: Repository<BusinessEntity>,
@InjectRepository(BusinessCategoryEntity)
private readonly categoryRepo: Repository<BusinessCategoryEntity>,
2026-05-11 15:30:04 +03:30
@InjectRepository(UserEntity)
private readonly userRepo: Repository<UserEntity>,
private readonly dataSource: DataSource,
private readonly images: BusinessImagesService,
2026-05-07 21:22:50 +03:30
) {}
async findAll(filters: FindAllFilters): Promise<BusinessEntity[]> {
const query = this.repo
.createQueryBuilder('business')
.leftJoinAndSelect('business.category', 'category')
.leftJoinAndSelect('business.images', 'images')
.orderBy('business.createdAt', 'DESC')
.addOrderBy('images.isCover', 'DESC')
.addOrderBy('images.sortOrder', 'ASC');
2026-05-07 21:22:50 +03:30
if (filters.categoryId) {
query.andWhere('business.categoryId = :categoryId', {
categoryId: filters.categoryId,
});
}
if (typeof filters.isActive === 'boolean') {
query.andWhere('business.isActive = :isActive', {
isActive: filters.isActive,
});
}
return query.getMany();
}
async findOne(id: string): Promise<BusinessEntity> {
const business = await this.repo.findOne({
where: { id },
relations: { category: true, images: true },
2026-05-07 21:22:50 +03:30
});
if (!business) {
throw new NotFoundException('Business not found');
}
return business;
}
async findMine(ownerId: string): Promise<BusinessEntity[]> {
return this.repo.find({
where: { ownerId },
relations: { category: true, images: true },
order: { createdAt: 'DESC' },
});
}
2026-05-07 21:22:50 +03:30
async create(payload: CreateBusinessDto): Promise<BusinessEntity> {
const slugTaken = await this.repo.findOne({ where: { slug: payload.slug } });
if (slugTaken) {
throw new ConflictException('Slug already exists');
}
await this.ensureCategoryExists(payload.categoryId);
const entity = this.repo.create({
title: payload.title,
slug: payload.slug,
categoryId: payload.categoryId,
description: payload.description ?? null,
contactPhone: payload.contactPhone ?? null,
address: payload.address ?? null,
latitude: payload.latitude ?? null,
longitude: payload.longitude ?? null,
ownerId: payload.ownerId ?? null,
isActive: payload.isActive ?? true,
});
return this.repo.save(entity);
}
2026-05-11 12:40:42 +03:30
async update(
id: string,
payload: UpdateBusinessDto,
actor?: AuthUser,
): Promise<BusinessEntity> {
2026-05-07 21:22:50 +03:30
const business = await this.findOne(id);
2026-05-11 12:40:42 +03:30
this.assertCanUpdateBusiness(business, payload, actor);
2026-05-07 21:22:50 +03:30
if (payload.slug && payload.slug !== business.slug) {
const slugTaken = await this.repo.findOne({ where: { slug: payload.slug } });
if (slugTaken) {
throw new ConflictException('Slug already exists');
}
}
if (payload.categoryId && payload.categoryId !== business.categoryId) {
await this.ensureCategoryExists(payload.categoryId);
}
Object.assign(business, payload);
return this.repo.save(business);
}
async remove(id: string): Promise<void> {
await this.findOne(id);
await this.dataSource.transaction(async (manager) => {
await deleteBusinessCascade(manager, id, async (businessId) => {
await this.images.removeAllForBusiness(businessId);
});
});
2026-05-07 21:22:50 +03:30
}
2026-05-11 15:30:04 +03:30
async assignOwner(
id: string,
dto: AssignBusinessOwnerDto,
): Promise<BusinessEntity> {
const business = await this.findOne(id);
const mobile = this.normalizeMobile(dto.mobile);
let user = await this.userRepo.findOne({ where: { mobile } });
if (!user) {
user = this.userRepo.create({
mobile,
fullName: dto.fullName ?? null,
role: UserRole.BUSINESS_OWNER,
isActive: true,
});
} else {
if (user.role !== UserRole.ADMIN) {
user.role = UserRole.BUSINESS_OWNER;
}
if (dto.fullName !== undefined) {
user.fullName = dto.fullName;
}
user.isActive = true;
}
const savedUser = await this.userRepo.save(user);
business.ownerId = savedUser.id;
return this.repo.save(business);
}
2026-05-07 21:22:50 +03:30
private async ensureCategoryExists(categoryId: string): Promise<void> {
const category = await this.categoryRepo.findOne({ where: { id: categoryId } });
if (!category) {
throw new NotFoundException('Business category not found');
}
}
2026-05-11 12:40:42 +03:30
2026-05-11 15:30:04 +03:30
private normalizeMobile(mobile: string): string {
const normalized = String(mobile ?? '').trim();
if (!/^(\+?\d{10,15}|09\d{9})$/.test(normalized)) {
throw new BadRequestException('Invalid mobile number');
}
return normalized;
}
2026-05-11 12:40:42 +03:30
private assertCanUpdateBusiness(
business: BusinessEntity,
payload: UpdateBusinessDto,
actor?: AuthUser,
): void {
if (!actor || actor.role === UserRole.ADMIN) {
return;
}
if (
actor.role !== UserRole.BUSINESS_OWNER ||
business.ownerId !== actor.id
) {
throw new ForbiddenException('You can only manage your own business');
}
if (
payload.ownerId !== undefined ||
payload.categoryId !== undefined ||
payload.isActive !== undefined
) {
throw new ForbiddenException(
'Only the super admin can change owner, category, or active status',
);
}
}
2026-05-07 21:22:50 +03:30
}