add business owner assignment

This commit is contained in:
2026-05-11 15:30:04 +03:30
parent d8f71efdd5
commit 8056503078
4 changed files with 60 additions and 2 deletions
+43 -1
View File
@@ -1,4 +1,5 @@
import {
BadRequestException,
ConflictException,
ForbiddenException,
Injectable,
@@ -8,8 +9,9 @@ import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { BusinessCategoryEntity } from '../../entities/business-category.entity';
import { BusinessEntity } from '../../entities/business.entity';
import { UserRole } from '../../entities/user.entity';
import { UserEntity, UserRole } from '../../entities/user.entity';
import { AuthUser } from '../auth/auth.types';
import { AssignBusinessOwnerDto } from './dto/assign-business-owner.dto';
import { CreateBusinessDto } from './dto/create-business.dto';
import { UpdateBusinessDto } from './dto/update-business.dto';
@@ -25,6 +27,8 @@ export class BusinessesService {
private readonly repo: Repository<BusinessEntity>,
@InjectRepository(BusinessCategoryEntity)
private readonly categoryRepo: Repository<BusinessCategoryEntity>,
@InjectRepository(UserEntity)
private readonly userRepo: Repository<UserEntity>,
) {}
async findAll(filters: FindAllFilters): Promise<BusinessEntity[]> {
@@ -113,6 +117,36 @@ export class BusinessesService {
}
}
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);
}
private async ensureCategoryExists(categoryId: string): Promise<void> {
const category = await this.categoryRepo.findOne({ where: { id: categoryId } });
if (!category) {
@@ -120,6 +154,14 @@ export class BusinessesService {
}
}
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;
}
private assertCanUpdateBusiness(
business: BusinessEntity,
payload: UpdateBusinessDto,