mirror of
https://github.com/SyncrowIOT/backend.git
synced 2025-07-16 18:56:22 +00:00
Merge pull request #24 from SyncrowIOT/SP-171-be-create-groups-to-control-devices-per-group
Sp 171 be create groups to control devices per group
This commit is contained in:
@ -1,6 +1,6 @@
|
||||
import { PassportModule } from '@nestjs/passport';
|
||||
import { JwtModule } from '@nestjs/jwt';
|
||||
import { ConfigModule, ConfigService } from '@nestjs/config';
|
||||
import { ConfigModule } from '@nestjs/config';
|
||||
import { Module } from '@nestjs/common';
|
||||
import { HelperModule } from '../helper/helper.module';
|
||||
import { JwtStrategy } from './strategies/jwt.strategy';
|
||||
|
@ -7,10 +7,16 @@ import { UserSessionEntity } from '../modules/session/entities/session.entity';
|
||||
import { UserOtpEntity } from '../modules/user-otp/entities';
|
||||
import { HomeEntity } from '../modules/home/entities';
|
||||
import { ProductEntity } from '../modules/product/entities';
|
||||
import { DeviceEntity, DeviceUserPermissionEntity } from '../modules/device/entities';
|
||||
import {
|
||||
DeviceEntity,
|
||||
DeviceUserPermissionEntity,
|
||||
} from '../modules/device/entities';
|
||||
import { PermissionTypeEntity } from '../modules/permission/entities';
|
||||
import { SpaceEntity } from '../modules/space/entities';
|
||||
import { SpaceTypeEntity } from '../modules/space-type/entities';
|
||||
import { UserSpaceEntity } from '../modules/user-space/entities';
|
||||
import { GroupEntity } from '../modules/group/entities';
|
||||
import { GroupDeviceEntity } from '../modules/group-device/entities';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
@ -36,6 +42,9 @@ import { SpaceTypeEntity } from '../modules/space-type/entities';
|
||||
PermissionTypeEntity,
|
||||
SpaceEntity,
|
||||
SpaceTypeEntity,
|
||||
UserSpaceEntity,
|
||||
GroupEntity,
|
||||
GroupDeviceEntity,
|
||||
],
|
||||
namingStrategy: new SnakeNamingStrategy(),
|
||||
synchronize: Boolean(JSON.parse(configService.get('DB_SYNC'))),
|
||||
|
@ -1,7 +1,6 @@
|
||||
import { IsNotEmpty, IsString } from "class-validator";
|
||||
import { IsNotEmpty, IsString } from 'class-validator';
|
||||
|
||||
export class DeviceDto {
|
||||
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
public uuid: string;
|
||||
|
@ -2,6 +2,7 @@ import { Column, Entity, OneToMany } from 'typeorm';
|
||||
import { AbstractEntity } from '../../abstract/entities/abstract.entity';
|
||||
import { DeviceDto } from '../dtos/device.dto';
|
||||
import { DeviceUserPermissionEntity } from './device-user-type.entity';
|
||||
import { GroupDeviceEntity } from '../../group-device/entities';
|
||||
|
||||
@Entity({ name: 'device' })
|
||||
export class DeviceEntity extends AbstractEntity<DeviceDto> {
|
||||
@ -37,6 +38,12 @@ export class DeviceEntity extends AbstractEntity<DeviceDto> {
|
||||
)
|
||||
permission: DeviceUserPermissionEntity[];
|
||||
|
||||
@OneToMany(
|
||||
() => GroupDeviceEntity,
|
||||
(userGroupDevices) => userGroupDevices.device,
|
||||
)
|
||||
userGroupDevices: GroupDeviceEntity[];
|
||||
|
||||
constructor(partial: Partial<DeviceEntity>) {
|
||||
super();
|
||||
Object.assign(this, partial);
|
||||
|
@ -0,0 +1,15 @@
|
||||
import { IsNotEmpty, IsString } from 'class-validator';
|
||||
|
||||
export class GroupDeviceDto {
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
public uuid: string;
|
||||
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
public deviceUuid: string;
|
||||
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
public groupUuid: string;
|
||||
}
|
1
libs/common/src/modules/group-device/dtos/index.ts
Normal file
1
libs/common/src/modules/group-device/dtos/index.ts
Normal file
@ -0,0 +1 @@
|
||||
export * from './group.device.dto';
|
@ -0,0 +1,36 @@
|
||||
import { Column, Entity, ManyToOne, Unique } from 'typeorm';
|
||||
import { GroupDeviceDto } from '../dtos';
|
||||
import { AbstractEntity } from '../../abstract/entities/abstract.entity';
|
||||
import { DeviceEntity } from '../../device/entities';
|
||||
import { GroupEntity } from '../../group/entities';
|
||||
|
||||
@Entity({ name: 'group-device' })
|
||||
@Unique(['device', 'group'])
|
||||
export class GroupDeviceEntity extends AbstractEntity<GroupDeviceDto> {
|
||||
@Column({
|
||||
type: 'uuid',
|
||||
default: () => 'gen_random_uuid()', // Use gen_random_uuid() for default value
|
||||
nullable: false,
|
||||
})
|
||||
public uuid: string;
|
||||
|
||||
@ManyToOne(() => DeviceEntity, (device) => device.userGroupDevices, {
|
||||
nullable: false,
|
||||
})
|
||||
device: DeviceEntity;
|
||||
|
||||
@ManyToOne(() => GroupEntity, (group) => group.groupDevices, {
|
||||
nullable: false,
|
||||
})
|
||||
group: GroupEntity;
|
||||
|
||||
@Column({
|
||||
nullable: true,
|
||||
default: true,
|
||||
})
|
||||
public isActive: boolean;
|
||||
constructor(partial: Partial<GroupDeviceEntity>) {
|
||||
super();
|
||||
Object.assign(this, partial);
|
||||
}
|
||||
}
|
1
libs/common/src/modules/group-device/entities/index.ts
Normal file
1
libs/common/src/modules/group-device/entities/index.ts
Normal file
@ -0,0 +1 @@
|
||||
export * from './group.device.entity';
|
@ -0,0 +1,11 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { GroupDeviceEntity } from './entities/group.device.entity';
|
||||
|
||||
@Module({
|
||||
providers: [],
|
||||
exports: [],
|
||||
controllers: [],
|
||||
imports: [TypeOrmModule.forFeature([GroupDeviceEntity])],
|
||||
})
|
||||
export class GroupDeviceRepositoryModule {}
|
@ -0,0 +1,10 @@
|
||||
import { DataSource, Repository } from 'typeorm';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { GroupDeviceEntity } from '../entities/group.device.entity';
|
||||
|
||||
@Injectable()
|
||||
export class GroupDeviceRepository extends Repository<GroupDeviceEntity> {
|
||||
constructor(private dataSource: DataSource) {
|
||||
super(GroupDeviceEntity, dataSource.createEntityManager());
|
||||
}
|
||||
}
|
@ -0,0 +1 @@
|
||||
export * from './group.device.repository';
|
11
libs/common/src/modules/group/dtos/group.dto.ts
Normal file
11
libs/common/src/modules/group/dtos/group.dto.ts
Normal file
@ -0,0 +1,11 @@
|
||||
import { IsNotEmpty, IsString } from 'class-validator';
|
||||
|
||||
export class GroupDto {
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
public uuid: string;
|
||||
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
public groupName: string;
|
||||
}
|
1
libs/common/src/modules/group/dtos/index.ts
Normal file
1
libs/common/src/modules/group/dtos/index.ts
Normal file
@ -0,0 +1 @@
|
||||
export * from './group.dto';
|
35
libs/common/src/modules/group/entities/group.entity.ts
Normal file
35
libs/common/src/modules/group/entities/group.entity.ts
Normal file
@ -0,0 +1,35 @@
|
||||
import { Column, Entity, OneToMany } from 'typeorm';
|
||||
import { GroupDto } from '../dtos';
|
||||
import { AbstractEntity } from '../../abstract/entities/abstract.entity';
|
||||
import { GroupDeviceEntity } from '../../group-device/entities';
|
||||
|
||||
@Entity({ name: 'group' })
|
||||
export class GroupEntity extends AbstractEntity<GroupDto> {
|
||||
@Column({
|
||||
type: 'uuid',
|
||||
default: () => 'gen_random_uuid()', // Use gen_random_uuid() for default value
|
||||
nullable: false,
|
||||
})
|
||||
public uuid: string;
|
||||
|
||||
@Column({
|
||||
nullable: false,
|
||||
})
|
||||
public groupName: string;
|
||||
|
||||
@OneToMany(() => GroupDeviceEntity, (groupDevice) => groupDevice.group, {
|
||||
cascade: true,
|
||||
onDelete: 'CASCADE',
|
||||
})
|
||||
groupDevices: GroupDeviceEntity[];
|
||||
|
||||
@Column({
|
||||
nullable: true,
|
||||
default: true,
|
||||
})
|
||||
public isActive: boolean;
|
||||
constructor(partial: Partial<GroupEntity>) {
|
||||
super();
|
||||
Object.assign(this, partial);
|
||||
}
|
||||
}
|
1
libs/common/src/modules/group/entities/index.ts
Normal file
1
libs/common/src/modules/group/entities/index.ts
Normal file
@ -0,0 +1 @@
|
||||
export * from './group.entity';
|
11
libs/common/src/modules/group/group.repository.module.ts
Normal file
11
libs/common/src/modules/group/group.repository.module.ts
Normal file
@ -0,0 +1,11 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { GroupEntity } from './entities/group.entity';
|
||||
|
||||
@Module({
|
||||
providers: [],
|
||||
exports: [],
|
||||
controllers: [],
|
||||
imports: [TypeOrmModule.forFeature([GroupEntity])],
|
||||
})
|
||||
export class GroupRepositoryModule {}
|
@ -0,0 +1,10 @@
|
||||
import { DataSource, Repository } from 'typeorm';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { GroupEntity } from '../entities/group.entity';
|
||||
|
||||
@Injectable()
|
||||
export class GroupRepository extends Repository<GroupEntity> {
|
||||
constructor(private dataSource: DataSource) {
|
||||
super(GroupEntity, dataSource.createEntityManager());
|
||||
}
|
||||
}
|
1
libs/common/src/modules/group/repositories/index.ts
Normal file
1
libs/common/src/modules/group/repositories/index.ts
Normal file
@ -0,0 +1 @@
|
||||
export * from './group.repository';
|
@ -1 +1 @@
|
||||
export * from './permission.dto'
|
||||
export * from './permission.dto';
|
||||
|
@ -1 +1 @@
|
||||
export * from './permission.entity'
|
||||
export * from './permission.entity';
|
||||
|
@ -1 +1 @@
|
||||
export * from './permission.repository'
|
||||
export * from './permission.repository';
|
||||
|
@ -2,6 +2,7 @@ import { Column, Entity, ManyToOne, OneToMany } from 'typeorm';
|
||||
import { SpaceDto } from '../dtos';
|
||||
import { AbstractEntity } from '../../abstract/entities/abstract.entity';
|
||||
import { SpaceTypeEntity } from '../../space-type/entities';
|
||||
import { UserSpaceEntity } from '../../user-space/entities';
|
||||
|
||||
@Entity({ name: 'space' })
|
||||
export class SpaceEntity extends AbstractEntity<SpaceDto> {
|
||||
@ -26,6 +27,9 @@ export class SpaceEntity extends AbstractEntity<SpaceDto> {
|
||||
})
|
||||
spaceType: SpaceTypeEntity;
|
||||
|
||||
@OneToMany(() => UserSpaceEntity, (userSpace) => userSpace.space)
|
||||
userSpaces: UserSpaceEntity[];
|
||||
|
||||
constructor(partial: Partial<SpaceEntity>) {
|
||||
super();
|
||||
Object.assign(this, partial);
|
||||
|
1
libs/common/src/modules/user-space/dtos/index.ts
Normal file
1
libs/common/src/modules/user-space/dtos/index.ts
Normal file
@ -0,0 +1 @@
|
||||
export * from './user.space.dto';
|
15
libs/common/src/modules/user-space/dtos/user.space.dto.ts
Normal file
15
libs/common/src/modules/user-space/dtos/user.space.dto.ts
Normal file
@ -0,0 +1,15 @@
|
||||
import { IsNotEmpty, IsString } from 'class-validator';
|
||||
|
||||
export class UserSpaceDto {
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
public uuid: string;
|
||||
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
public spaceUuid: string;
|
||||
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
public userUuid: string;
|
||||
}
|
1
libs/common/src/modules/user-space/entities/index.ts
Normal file
1
libs/common/src/modules/user-space/entities/index.ts
Normal file
@ -0,0 +1 @@
|
||||
export * from './user.space.entity';
|
@ -0,0 +1,29 @@
|
||||
import { Column, Entity, ManyToOne, Unique } from 'typeorm';
|
||||
import { UserSpaceDto } from '../dtos';
|
||||
import { AbstractEntity } from '../../abstract/entities/abstract.entity';
|
||||
import { SpaceEntity } from '../../space/entities';
|
||||
import { UserEntity } from '../../user/entities';
|
||||
|
||||
@Entity({ name: 'user-space' })
|
||||
@Unique(['user', 'space'])
|
||||
export class UserSpaceEntity extends AbstractEntity<UserSpaceDto> {
|
||||
@Column({
|
||||
type: 'uuid',
|
||||
default: () => 'gen_random_uuid()', // Use gen_random_uuid() for default value
|
||||
nullable: false,
|
||||
})
|
||||
public uuid: string;
|
||||
|
||||
@ManyToOne(() => UserEntity, (user) => user.userSpaces, { nullable: false })
|
||||
user: UserEntity;
|
||||
|
||||
@ManyToOne(() => SpaceEntity, (space) => space.userSpaces, {
|
||||
nullable: false,
|
||||
})
|
||||
space: SpaceEntity;
|
||||
|
||||
constructor(partial: Partial<UserSpaceEntity>) {
|
||||
super();
|
||||
Object.assign(this, partial);
|
||||
}
|
||||
}
|
1
libs/common/src/modules/user-space/repositories/index.ts
Normal file
1
libs/common/src/modules/user-space/repositories/index.ts
Normal file
@ -0,0 +1 @@
|
||||
export * from './user.space.repository';
|
@ -0,0 +1,10 @@
|
||||
import { DataSource, Repository } from 'typeorm';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { UserSpaceEntity } from '../entities/user.space.entity';
|
||||
|
||||
@Injectable()
|
||||
export class UserSpaceRepository extends Repository<UserSpaceEntity> {
|
||||
constructor(private dataSource: DataSource) {
|
||||
super(UserSpaceEntity, dataSource.createEntityManager());
|
||||
}
|
||||
}
|
@ -0,0 +1,11 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { UserSpaceEntity } from './entities/user.space.entity';
|
||||
|
||||
@Module({
|
||||
providers: [],
|
||||
exports: [],
|
||||
controllers: [],
|
||||
imports: [TypeOrmModule.forFeature([UserSpaceEntity])],
|
||||
})
|
||||
export class UserSpaceRepositoryModule {}
|
@ -0,0 +1 @@
|
||||
export * from './user.entity';
|
||||
|
@ -1,6 +1,7 @@
|
||||
import { Column, Entity } from 'typeorm';
|
||||
import { Column, Entity, OneToMany } from 'typeorm';
|
||||
import { UserDto } from '../dtos';
|
||||
import { AbstractEntity } from '../../abstract/entities/abstract.entity';
|
||||
import { UserSpaceEntity } from '../../user-space/entities';
|
||||
|
||||
@Entity({ name: 'user' })
|
||||
export class UserEntity extends AbstractEntity<UserDto> {
|
||||
@ -47,6 +48,9 @@ export class UserEntity extends AbstractEntity<UserDto> {
|
||||
})
|
||||
public isActive: boolean;
|
||||
|
||||
@OneToMany(() => UserSpaceEntity, (userSpace) => userSpace.user)
|
||||
userSpaces: UserSpaceEntity[];
|
||||
|
||||
constructor(partial: Partial<UserEntity>) {
|
||||
super();
|
||||
Object.assign(this, partial);
|
||||
|
@ -29,7 +29,7 @@ import { UnitModule } from './unit/unit.module';
|
||||
RoomModule,
|
||||
GroupModule,
|
||||
DeviceModule,
|
||||
UserDevicePermissionModule
|
||||
UserDevicePermissionModule,
|
||||
],
|
||||
controllers: [AuthenticationController],
|
||||
})
|
||||
|
@ -16,7 +16,6 @@ import { ResponseMessage } from '../../../libs/common/src/response/response.deco
|
||||
import { UserLoginDto } from '../dtos/user-login.dto';
|
||||
import { JwtAuthGuard } from '../../../libs/common/src/guards/jwt.auth.guard';
|
||||
import { ForgetPasswordDto, UserOtpDto, VerifyOtpDto } from '../dtos';
|
||||
import { Request } from 'express';
|
||||
import { RefreshTokenGuard } from '@app/common/guards/jwt-refresh.auth.guard';
|
||||
|
||||
@Controller({
|
||||
@ -101,7 +100,7 @@ export class UserAuthController {
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@Get('user/list')
|
||||
async userList(@Req() req) {
|
||||
async userList() {
|
||||
const userList = await this.userAuthService.userList();
|
||||
return {
|
||||
statusCode: HttpStatus.OK,
|
||||
|
@ -6,11 +6,27 @@ import { SpaceRepositoryModule } from '@app/common/modules/space/space.repositor
|
||||
import { SpaceRepository } from '@app/common/modules/space/repositories';
|
||||
import { SpaceTypeRepositoryModule } from '@app/common/modules/space-type/space.type.repository.module';
|
||||
import { SpaceTypeRepository } from '@app/common/modules/space-type/repositories';
|
||||
import { UserSpaceRepositoryModule } from '@app/common/modules/user-space/user.space.repository.module';
|
||||
import { UserSpaceRepository } from '@app/common/modules/user-space/repositories';
|
||||
import { UserRepository } from '@app/common/modules/user/repositories';
|
||||
import { UserRepositoryModule } from '@app/common/modules/user/user.repository.module';
|
||||
|
||||
@Module({
|
||||
imports: [ConfigModule, SpaceRepositoryModule, SpaceTypeRepositoryModule],
|
||||
imports: [
|
||||
ConfigModule,
|
||||
SpaceRepositoryModule,
|
||||
SpaceTypeRepositoryModule,
|
||||
UserSpaceRepositoryModule,
|
||||
UserRepositoryModule,
|
||||
],
|
||||
controllers: [BuildingController],
|
||||
providers: [BuildingService, SpaceRepository, SpaceTypeRepository],
|
||||
providers: [
|
||||
BuildingService,
|
||||
SpaceRepository,
|
||||
SpaceTypeRepository,
|
||||
UserSpaceRepository,
|
||||
UserRepository,
|
||||
],
|
||||
exports: [BuildingService],
|
||||
})
|
||||
export class BuildingModule {}
|
||||
|
@ -13,10 +13,11 @@ import {
|
||||
} from '@nestjs/common';
|
||||
import { ApiTags, ApiBearerAuth } from '@nestjs/swagger';
|
||||
import { JwtAuthGuard } from '../../../libs/common/src/guards/jwt.auth.guard';
|
||||
import { AddBuildingDto } from '../dtos/add.building.dto';
|
||||
import { AddBuildingDto, AddUserBuildingDto } from '../dtos/add.building.dto';
|
||||
import { GetBuildingChildDto } from '../dtos/get.building.dto';
|
||||
import { UpdateBuildingNameDto } from '../dtos/update.building.dto';
|
||||
import { CheckCommunityTypeGuard } from 'src/guards/community.type.guard';
|
||||
import { CheckUserBuildingGuard } from 'src/guards/user.building.guard';
|
||||
|
||||
@ApiTags('Building Module')
|
||||
@Controller({
|
||||
@ -92,6 +93,34 @@ export class BuildingController {
|
||||
);
|
||||
}
|
||||
}
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard, CheckUserBuildingGuard)
|
||||
@Post('user')
|
||||
async addUserBuilding(@Body() addUserBuildingDto: AddUserBuildingDto) {
|
||||
try {
|
||||
await this.buildingService.addUserBuilding(addUserBuildingDto);
|
||||
return { message: 'user building added successfully' };
|
||||
} catch (error) {
|
||||
throw new HttpException(
|
||||
error.message || 'Internal server error',
|
||||
error.status || HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
}
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@Get('user/:userUuid')
|
||||
async getBuildingsByUserId(@Param('userUuid') userUuid: string) {
|
||||
try {
|
||||
return await this.buildingService.getBuildingsByUserId(userUuid);
|
||||
} catch (error) {
|
||||
throw new HttpException(
|
||||
error.message || 'Internal server error',
|
||||
error.status || HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@Put('rename/:buildingUuid')
|
||||
|
@ -21,3 +21,22 @@ export class AddBuildingDto {
|
||||
Object.assign(this, dto);
|
||||
}
|
||||
}
|
||||
export class AddUserBuildingDto {
|
||||
@ApiProperty({
|
||||
description: 'buildingUuid',
|
||||
required: true,
|
||||
})
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
public buildingUuid: string;
|
||||
@ApiProperty({
|
||||
description: 'userUuid',
|
||||
required: true,
|
||||
})
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
public userUuid: string;
|
||||
constructor(dto: Partial<AddUserBuildingDto>) {
|
||||
Object.assign(this, dto);
|
||||
}
|
||||
}
|
||||
|
@ -24,3 +24,8 @@ export interface RenameBuildingByUuidInterface {
|
||||
name: string;
|
||||
type: string;
|
||||
}
|
||||
export interface GetBuildingByUserUuidInterface {
|
||||
uuid: string;
|
||||
name: string;
|
||||
type: string;
|
||||
}
|
||||
|
@ -7,21 +7,24 @@ import {
|
||||
BadRequestException,
|
||||
} from '@nestjs/common';
|
||||
import { SpaceRepository } from '@app/common/modules/space/repositories';
|
||||
import { AddBuildingDto } from '../dtos';
|
||||
import { AddBuildingDto, AddUserBuildingDto } from '../dtos';
|
||||
import {
|
||||
BuildingChildInterface,
|
||||
BuildingParentInterface,
|
||||
GetBuildingByUserUuidInterface,
|
||||
GetBuildingByUuidInterface,
|
||||
RenameBuildingByUuidInterface,
|
||||
} from '../interface/building.interface';
|
||||
import { SpaceEntity } from '@app/common/modules/space/entities';
|
||||
import { UpdateBuildingNameDto } from '../dtos/update.building.dto';
|
||||
import { UserSpaceRepository } from '@app/common/modules/user-space/repositories';
|
||||
|
||||
@Injectable()
|
||||
export class BuildingService {
|
||||
constructor(
|
||||
private readonly spaceRepository: SpaceRepository,
|
||||
private readonly spaceTypeRepository: SpaceTypeRepository,
|
||||
private readonly userSpaceRepository: UserSpaceRepository,
|
||||
) {}
|
||||
|
||||
async addBuilding(addBuildingDto: AddBuildingDto) {
|
||||
@ -210,6 +213,58 @@ export class BuildingService {
|
||||
}
|
||||
}
|
||||
|
||||
async getBuildingsByUserId(
|
||||
userUuid: string,
|
||||
): Promise<GetBuildingByUserUuidInterface[]> {
|
||||
try {
|
||||
const buildings = await this.userSpaceRepository.find({
|
||||
relations: ['space', 'space.spaceType'],
|
||||
where: {
|
||||
user: { uuid: userUuid },
|
||||
space: { spaceType: { type: 'building' } },
|
||||
},
|
||||
});
|
||||
|
||||
if (buildings.length === 0) {
|
||||
throw new HttpException(
|
||||
'this user has no buildings',
|
||||
HttpStatus.NOT_FOUND,
|
||||
);
|
||||
}
|
||||
const spaces = buildings.map((building) => ({
|
||||
uuid: building.space.uuid,
|
||||
name: building.space.spaceName,
|
||||
type: building.space.spaceType.type,
|
||||
}));
|
||||
|
||||
return spaces;
|
||||
} catch (err) {
|
||||
if (err instanceof HttpException) {
|
||||
throw err;
|
||||
} else {
|
||||
throw new HttpException('user not found', HttpStatus.NOT_FOUND);
|
||||
}
|
||||
}
|
||||
}
|
||||
async addUserBuilding(addUserBuildingDto: AddUserBuildingDto) {
|
||||
try {
|
||||
await this.userSpaceRepository.save({
|
||||
user: { uuid: addUserBuildingDto.userUuid },
|
||||
space: { uuid: addUserBuildingDto.buildingUuid },
|
||||
});
|
||||
} catch (err) {
|
||||
if (err.code === '23505') {
|
||||
throw new HttpException(
|
||||
'User already belongs to this building',
|
||||
HttpStatus.BAD_REQUEST,
|
||||
);
|
||||
}
|
||||
throw new HttpException(
|
||||
err.message || 'Internal Server Error',
|
||||
HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
}
|
||||
async renameBuildingByUuid(
|
||||
buildingUuid: string,
|
||||
updateBuildingNameDto: UpdateBuildingNameDto,
|
||||
|
@ -6,11 +6,27 @@ import { SpaceRepositoryModule } from '@app/common/modules/space/space.repositor
|
||||
import { SpaceRepository } from '@app/common/modules/space/repositories';
|
||||
import { SpaceTypeRepositoryModule } from '@app/common/modules/space-type/space.type.repository.module';
|
||||
import { SpaceTypeRepository } from '@app/common/modules/space-type/repositories';
|
||||
import { UserSpaceRepositoryModule } from '@app/common/modules/user-space/user.space.repository.module';
|
||||
import { UserSpaceRepository } from '@app/common/modules/user-space/repositories';
|
||||
import { UserRepositoryModule } from '@app/common/modules/user/user.repository.module';
|
||||
import { UserRepository } from '@app/common/modules/user/repositories';
|
||||
|
||||
@Module({
|
||||
imports: [ConfigModule, SpaceRepositoryModule, SpaceTypeRepositoryModule],
|
||||
imports: [
|
||||
ConfigModule,
|
||||
SpaceRepositoryModule,
|
||||
SpaceTypeRepositoryModule,
|
||||
UserSpaceRepositoryModule,
|
||||
UserRepositoryModule,
|
||||
],
|
||||
controllers: [CommunityController],
|
||||
providers: [CommunityService, SpaceRepository, SpaceTypeRepository],
|
||||
providers: [
|
||||
CommunityService,
|
||||
SpaceRepository,
|
||||
SpaceTypeRepository,
|
||||
UserSpaceRepository,
|
||||
UserRepository,
|
||||
],
|
||||
exports: [CommunityService],
|
||||
})
|
||||
export class CommunityModule {}
|
||||
|
@ -13,9 +13,13 @@ import {
|
||||
} from '@nestjs/common';
|
||||
import { ApiTags, ApiBearerAuth } from '@nestjs/swagger';
|
||||
import { JwtAuthGuard } from '../../../libs/common/src/guards/jwt.auth.guard';
|
||||
import { AddCommunityDto } from '../dtos/add.community.dto';
|
||||
import {
|
||||
AddCommunityDto,
|
||||
AddUserCommunityDto,
|
||||
} from '../dtos/add.community.dto';
|
||||
import { GetCommunityChildDto } from '../dtos/get.community.dto';
|
||||
import { UpdateCommunityNameDto } from '../dtos/update.community.dto';
|
||||
import { CheckUserCommunityGuard } from 'src/guards/user.community.guard';
|
||||
|
||||
@ApiTags('Community Module')
|
||||
@Controller({
|
||||
@ -77,6 +81,33 @@ export class CommunityController {
|
||||
}
|
||||
}
|
||||
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@Get('user/:userUuid')
|
||||
async getCommunitiesByUserId(@Param('userUuid') userUuid: string) {
|
||||
try {
|
||||
return await this.communityService.getCommunitiesByUserId(userUuid);
|
||||
} catch (error) {
|
||||
throw new HttpException(
|
||||
error.message || 'Internal server error',
|
||||
error.status || HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
}
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard, CheckUserCommunityGuard)
|
||||
@Post('user')
|
||||
async addUserCommunity(@Body() addUserCommunityDto: AddUserCommunityDto) {
|
||||
try {
|
||||
await this.communityService.addUserCommunity(addUserCommunityDto);
|
||||
return { message: 'user community added successfully' };
|
||||
} catch (error) {
|
||||
throw new HttpException(
|
||||
error.message || 'Internal server error',
|
||||
error.status || HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
}
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@Put('rename/:communityUuid')
|
||||
|
@ -14,3 +14,22 @@ export class AddCommunityDto {
|
||||
Object.assign(this, dto);
|
||||
}
|
||||
}
|
||||
export class AddUserCommunityDto {
|
||||
@ApiProperty({
|
||||
description: 'communityUuid',
|
||||
required: true,
|
||||
})
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
public communityUuid: string;
|
||||
@ApiProperty({
|
||||
description: 'userUuid',
|
||||
required: true,
|
||||
})
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
public userUuid: string;
|
||||
constructor(dto: Partial<AddUserCommunityDto>) {
|
||||
Object.assign(this, dto);
|
||||
}
|
||||
}
|
||||
|
@ -18,3 +18,9 @@ export interface RenameCommunityByUuidInterface {
|
||||
name: string;
|
||||
type: string;
|
||||
}
|
||||
|
||||
export interface GetCommunityByUserUuidInterface {
|
||||
uuid: string;
|
||||
name: string;
|
||||
type: string;
|
||||
}
|
||||
|
@ -7,20 +7,23 @@ import {
|
||||
BadRequestException,
|
||||
} from '@nestjs/common';
|
||||
import { SpaceRepository } from '@app/common/modules/space/repositories';
|
||||
import { AddCommunityDto } from '../dtos';
|
||||
import { AddCommunityDto, AddUserCommunityDto } from '../dtos';
|
||||
import {
|
||||
CommunityChildInterface,
|
||||
GetCommunityByUserUuidInterface,
|
||||
GetCommunityByUuidInterface,
|
||||
RenameCommunityByUuidInterface,
|
||||
} from '../interface/community.interface';
|
||||
import { SpaceEntity } from '@app/common/modules/space/entities';
|
||||
import { UpdateCommunityNameDto } from '../dtos/update.community.dto';
|
||||
import { UserSpaceRepository } from '@app/common/modules/user-space/repositories';
|
||||
|
||||
@Injectable()
|
||||
export class CommunityService {
|
||||
constructor(
|
||||
private readonly spaceRepository: SpaceRepository,
|
||||
private readonly spaceTypeRepository: SpaceTypeRepository,
|
||||
private readonly userSpaceRepository: UserSpaceRepository,
|
||||
) {}
|
||||
|
||||
async addCommunity(addCommunityDto: AddCommunityDto) {
|
||||
@ -151,6 +154,60 @@ export class CommunityService {
|
||||
|
||||
return childHierarchies;
|
||||
}
|
||||
|
||||
async getCommunitiesByUserId(
|
||||
userUuid: string,
|
||||
): Promise<GetCommunityByUserUuidInterface[]> {
|
||||
try {
|
||||
const communities = await this.userSpaceRepository.find({
|
||||
relations: ['space', 'space.spaceType'],
|
||||
where: {
|
||||
user: { uuid: userUuid },
|
||||
space: { spaceType: { type: 'community' } },
|
||||
},
|
||||
});
|
||||
|
||||
if (communities.length === 0) {
|
||||
throw new HttpException(
|
||||
'this user has no communities',
|
||||
HttpStatus.NOT_FOUND,
|
||||
);
|
||||
}
|
||||
const spaces = communities.map((community) => ({
|
||||
uuid: community.space.uuid,
|
||||
name: community.space.spaceName,
|
||||
type: community.space.spaceType.type,
|
||||
}));
|
||||
|
||||
return spaces;
|
||||
} catch (err) {
|
||||
if (err instanceof HttpException) {
|
||||
throw err;
|
||||
} else {
|
||||
throw new HttpException('user not found', HttpStatus.NOT_FOUND);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async addUserCommunity(addUserCommunityDto: AddUserCommunityDto) {
|
||||
try {
|
||||
await this.userSpaceRepository.save({
|
||||
user: { uuid: addUserCommunityDto.userUuid },
|
||||
space: { uuid: addUserCommunityDto.communityUuid },
|
||||
});
|
||||
} catch (err) {
|
||||
if (err.code === '23505') {
|
||||
throw new HttpException(
|
||||
'User already belongs to this community',
|
||||
HttpStatus.BAD_REQUEST,
|
||||
);
|
||||
}
|
||||
throw new HttpException(
|
||||
err.message || 'Internal Server Error',
|
||||
HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
}
|
||||
async renameCommunityByUuid(
|
||||
communityUuid: string,
|
||||
updateCommunityDto: UpdateCommunityNameDto,
|
||||
|
@ -13,10 +13,11 @@ import {
|
||||
} from '@nestjs/common';
|
||||
import { ApiTags, ApiBearerAuth } from '@nestjs/swagger';
|
||||
import { JwtAuthGuard } from '../../../libs/common/src/guards/jwt.auth.guard';
|
||||
import { AddFloorDto } from '../dtos/add.floor.dto';
|
||||
import { AddFloorDto, AddUserFloorDto } from '../dtos/add.floor.dto';
|
||||
import { GetFloorChildDto } from '../dtos/get.floor.dto';
|
||||
import { UpdateFloorNameDto } from '../dtos/update.floor.dto';
|
||||
import { CheckBuildingTypeGuard } from 'src/guards/building.type.guard';
|
||||
import { CheckUserFloorGuard } from 'src/guards/user.floor.guard';
|
||||
|
||||
@ApiTags('Floor Module')
|
||||
@Controller({
|
||||
@ -91,6 +92,35 @@ export class FloorController {
|
||||
}
|
||||
}
|
||||
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard, CheckUserFloorGuard)
|
||||
@Post('user')
|
||||
async addUserFloor(@Body() addUserFloorDto: AddUserFloorDto) {
|
||||
try {
|
||||
await this.floorService.addUserFloor(addUserFloorDto);
|
||||
return { message: 'user floor added successfully' };
|
||||
} catch (error) {
|
||||
throw new HttpException(
|
||||
error.message || 'Internal server error',
|
||||
error.status || HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@Get('user/:userUuid')
|
||||
async getFloorsByUserId(@Param('userUuid') userUuid: string) {
|
||||
try {
|
||||
return await this.floorService.getFloorsByUserId(userUuid);
|
||||
} catch (error) {
|
||||
throw new HttpException(
|
||||
error.message || 'Internal server error',
|
||||
error.status || HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@Put('rename/:floorUuid')
|
||||
|
@ -21,3 +21,22 @@ export class AddFloorDto {
|
||||
Object.assign(this, dto);
|
||||
}
|
||||
}
|
||||
export class AddUserFloorDto {
|
||||
@ApiProperty({
|
||||
description: 'floorUuid',
|
||||
required: true,
|
||||
})
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
public floorUuid: string;
|
||||
@ApiProperty({
|
||||
description: 'userUuid',
|
||||
required: true,
|
||||
})
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
public userUuid: string;
|
||||
constructor(dto: Partial<AddUserFloorDto>) {
|
||||
Object.assign(this, dto);
|
||||
}
|
||||
}
|
||||
|
@ -6,11 +6,27 @@ import { SpaceRepositoryModule } from '@app/common/modules/space/space.repositor
|
||||
import { SpaceRepository } from '@app/common/modules/space/repositories';
|
||||
import { SpaceTypeRepositoryModule } from '@app/common/modules/space-type/space.type.repository.module';
|
||||
import { SpaceTypeRepository } from '@app/common/modules/space-type/repositories';
|
||||
import { UserSpaceRepositoryModule } from '@app/common/modules/user-space/user.space.repository.module';
|
||||
import { UserSpaceRepository } from '@app/common/modules/user-space/repositories';
|
||||
import { UserRepositoryModule } from '@app/common/modules/user/user.repository.module';
|
||||
import { UserRepository } from '@app/common/modules/user/repositories';
|
||||
|
||||
@Module({
|
||||
imports: [ConfigModule, SpaceRepositoryModule, SpaceTypeRepositoryModule],
|
||||
imports: [
|
||||
ConfigModule,
|
||||
SpaceRepositoryModule,
|
||||
SpaceTypeRepositoryModule,
|
||||
UserSpaceRepositoryModule,
|
||||
UserRepositoryModule,
|
||||
],
|
||||
controllers: [FloorController],
|
||||
providers: [FloorService, SpaceRepository, SpaceTypeRepository],
|
||||
providers: [
|
||||
FloorService,
|
||||
SpaceRepository,
|
||||
SpaceTypeRepository,
|
||||
UserSpaceRepository,
|
||||
UserRepository,
|
||||
],
|
||||
exports: [FloorService],
|
||||
})
|
||||
export class FloorModule {}
|
||||
|
@ -24,3 +24,9 @@ export interface RenameFloorByUuidInterface {
|
||||
name: string;
|
||||
type: string;
|
||||
}
|
||||
|
||||
export interface GetFloorByUserUuidInterface {
|
||||
uuid: string;
|
||||
name: string;
|
||||
type: string;
|
||||
}
|
||||
|
@ -7,21 +7,24 @@ import {
|
||||
BadRequestException,
|
||||
} from '@nestjs/common';
|
||||
import { SpaceRepository } from '@app/common/modules/space/repositories';
|
||||
import { AddFloorDto } from '../dtos';
|
||||
import { AddFloorDto, AddUserFloorDto } from '../dtos';
|
||||
import {
|
||||
FloorChildInterface,
|
||||
FloorParentInterface,
|
||||
GetFloorByUserUuidInterface,
|
||||
GetFloorByUuidInterface,
|
||||
RenameFloorByUuidInterface,
|
||||
} from '../interface/floor.interface';
|
||||
import { SpaceEntity } from '@app/common/modules/space/entities';
|
||||
import { UpdateFloorNameDto } from '../dtos/update.floor.dto';
|
||||
import { UserSpaceRepository } from '@app/common/modules/user-space/repositories';
|
||||
|
||||
@Injectable()
|
||||
export class FloorService {
|
||||
constructor(
|
||||
private readonly spaceRepository: SpaceRepository,
|
||||
private readonly spaceTypeRepository: SpaceTypeRepository,
|
||||
private readonly userSpaceRepository: UserSpaceRepository,
|
||||
) {}
|
||||
|
||||
async addFloor(addFloorDto: AddFloorDto) {
|
||||
@ -195,6 +198,58 @@ export class FloorService {
|
||||
}
|
||||
}
|
||||
|
||||
async getFloorsByUserId(
|
||||
userUuid: string,
|
||||
): Promise<GetFloorByUserUuidInterface[]> {
|
||||
try {
|
||||
const floors = await this.userSpaceRepository.find({
|
||||
relations: ['space', 'space.spaceType'],
|
||||
where: {
|
||||
user: { uuid: userUuid },
|
||||
space: { spaceType: { type: 'floor' } },
|
||||
},
|
||||
});
|
||||
|
||||
if (floors.length === 0) {
|
||||
throw new HttpException(
|
||||
'this user has no floors',
|
||||
HttpStatus.NOT_FOUND,
|
||||
);
|
||||
}
|
||||
const spaces = floors.map((floor) => ({
|
||||
uuid: floor.space.uuid,
|
||||
name: floor.space.spaceName,
|
||||
type: floor.space.spaceType.type,
|
||||
}));
|
||||
|
||||
return spaces;
|
||||
} catch (err) {
|
||||
if (err instanceof HttpException) {
|
||||
throw err;
|
||||
} else {
|
||||
throw new HttpException('user not found', HttpStatus.NOT_FOUND);
|
||||
}
|
||||
}
|
||||
}
|
||||
async addUserFloor(addUserFloorDto: AddUserFloorDto) {
|
||||
try {
|
||||
await this.userSpaceRepository.save({
|
||||
user: { uuid: addUserFloorDto.userUuid },
|
||||
space: { uuid: addUserFloorDto.floorUuid },
|
||||
});
|
||||
} catch (err) {
|
||||
if (err.code === '23505') {
|
||||
throw new HttpException(
|
||||
'User already belongs to this floor',
|
||||
HttpStatus.BAD_REQUEST,
|
||||
);
|
||||
}
|
||||
throw new HttpException(
|
||||
err.message || 'Internal Server Error',
|
||||
HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
}
|
||||
async renameFloorByUuid(
|
||||
floorUuid: string,
|
||||
updateFloorDto: UpdateFloorNameDto,
|
||||
|
@ -5,17 +5,18 @@ import {
|
||||
Get,
|
||||
Post,
|
||||
UseGuards,
|
||||
Query,
|
||||
Param,
|
||||
Put,
|
||||
Delete,
|
||||
HttpException,
|
||||
HttpStatus,
|
||||
} from '@nestjs/common';
|
||||
import { ApiTags, ApiBearerAuth } from '@nestjs/swagger';
|
||||
import { JwtAuthGuard } from '../../../libs/common/src/guards/jwt.auth.guard';
|
||||
import { AddGroupDto } from '../dtos/add.group.dto';
|
||||
import { GetGroupDto } from '../dtos/get.group.dto';
|
||||
import { ControlGroupDto } from '../dtos/control.group.dto';
|
||||
import { RenameGroupDto } from '../dtos/rename.group.dto copy';
|
||||
import { CheckProductUuidForAllDevicesGuard } from 'src/guards/device.product.guard';
|
||||
|
||||
@ApiTags('Group Module')
|
||||
@Controller({
|
||||
@ -27,32 +28,41 @@ export class GroupController {
|
||||
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@Get()
|
||||
async getGroupsByHomeId(@Query() getGroupsDto: GetGroupDto) {
|
||||
@Get('space/:spaceUuid')
|
||||
async getGroupsBySpaceUuid(@Param('spaceUuid') spaceUuid: string) {
|
||||
try {
|
||||
return await this.groupService.getGroupsByHomeId(getGroupsDto);
|
||||
} catch (err) {
|
||||
throw new Error(err);
|
||||
return await this.groupService.getGroupsBySpaceUuid(spaceUuid);
|
||||
} catch (error) {
|
||||
throw new HttpException(
|
||||
error.message || 'Internal server error',
|
||||
error.status || HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
}
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@Get(':groupId')
|
||||
async getGroupsByGroupId(@Param('groupId') groupId: number) {
|
||||
@Get(':groupUuid')
|
||||
async getGroupsByGroupId(@Param('groupUuid') groupUuid: string) {
|
||||
try {
|
||||
return await this.groupService.getGroupsByGroupId(groupId);
|
||||
} catch (err) {
|
||||
throw new Error(err);
|
||||
return await this.groupService.getGroupsByGroupUuid(groupUuid);
|
||||
} catch (error) {
|
||||
throw new HttpException(
|
||||
error.message || 'Internal server error',
|
||||
error.status || HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
}
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@UseGuards(JwtAuthGuard, CheckProductUuidForAllDevicesGuard)
|
||||
@Post()
|
||||
async addGroup(@Body() addGroupDto: AddGroupDto) {
|
||||
try {
|
||||
return await this.groupService.addGroup(addGroupDto);
|
||||
} catch (err) {
|
||||
throw new Error(err);
|
||||
} catch (error) {
|
||||
throw new HttpException(
|
||||
error.message || 'Internal server error',
|
||||
error.status || HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@ -62,30 +72,45 @@ export class GroupController {
|
||||
async controlGroup(@Body() controlGroupDto: ControlGroupDto) {
|
||||
try {
|
||||
return await this.groupService.controlGroup(controlGroupDto);
|
||||
} catch (err) {
|
||||
throw new Error(err);
|
||||
} catch (error) {
|
||||
throw new HttpException(
|
||||
error.message || 'Internal server error',
|
||||
error.status || HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@Put('rename')
|
||||
async renameGroup(@Body() renameGroupDto: RenameGroupDto) {
|
||||
@Put('rename/:groupUuid')
|
||||
async renameGroupByUuid(
|
||||
@Param('groupUuid') groupUuid: string,
|
||||
@Body() renameGroupDto: RenameGroupDto,
|
||||
) {
|
||||
try {
|
||||
return await this.groupService.renameGroup(renameGroupDto);
|
||||
} catch (err) {
|
||||
throw new Error(err);
|
||||
return await this.groupService.renameGroupByUuid(
|
||||
groupUuid,
|
||||
renameGroupDto,
|
||||
);
|
||||
} catch (error) {
|
||||
throw new HttpException(
|
||||
error.message || 'Internal server error',
|
||||
error.status || HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@Delete(':groupId')
|
||||
async deleteGroup(@Param('groupId') groupId: number) {
|
||||
@Delete(':groupUuid')
|
||||
async deleteGroup(@Param('groupUuid') groupUuid: string) {
|
||||
try {
|
||||
return await this.groupService.deleteGroup(groupId);
|
||||
} catch (err) {
|
||||
throw new Error(err);
|
||||
return await this.groupService.deleteGroup(groupUuid);
|
||||
} catch (error) {
|
||||
throw new HttpException(
|
||||
error.message || 'Internal server error',
|
||||
error.status || HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -1,5 +1,5 @@
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
import { IsNotEmpty, IsString, IsNumberString } from 'class-validator';
|
||||
import { IsNotEmpty, IsString, IsArray } from 'class-validator';
|
||||
|
||||
export class AddGroupDto {
|
||||
@ApiProperty({
|
||||
@ -11,26 +11,10 @@ export class AddGroupDto {
|
||||
public groupName: string;
|
||||
|
||||
@ApiProperty({
|
||||
description: 'homeId',
|
||||
description: 'deviceUuids',
|
||||
required: true,
|
||||
})
|
||||
@IsNumberString()
|
||||
@IsArray()
|
||||
@IsNotEmpty()
|
||||
public homeId: string;
|
||||
|
||||
@ApiProperty({
|
||||
description: 'productId',
|
||||
required: true,
|
||||
})
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
public productId: string;
|
||||
|
||||
@ApiProperty({
|
||||
description: 'The list of up to 20 device IDs, separated with commas (,)',
|
||||
required: true,
|
||||
})
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
public deviceIds: string;
|
||||
public deviceUuids: [string];
|
||||
}
|
||||
|
@ -1,20 +1,26 @@
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
import { IsNotEmpty, IsObject, IsNumberString } from 'class-validator';
|
||||
import { IsNotEmpty, IsString } from 'class-validator';
|
||||
|
||||
export class ControlGroupDto {
|
||||
@ApiProperty({
|
||||
description: 'groupId',
|
||||
description: 'groupUuid',
|
||||
required: true,
|
||||
})
|
||||
@IsNumberString()
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
public groupId: string;
|
||||
public groupUuid: string;
|
||||
|
||||
@ApiProperty({
|
||||
description: 'example {"switch_1":true,"add_ele":300}',
|
||||
description: 'code',
|
||||
required: true,
|
||||
})
|
||||
@IsObject()
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
public properties: object;
|
||||
public code: string;
|
||||
@ApiProperty({
|
||||
description: 'value',
|
||||
required: true,
|
||||
})
|
||||
@IsNotEmpty()
|
||||
public value: any;
|
||||
}
|
||||
|
@ -1,28 +0,0 @@
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
import { IsNotEmpty, IsNumberString } from 'class-validator';
|
||||
|
||||
export class GetGroupDto {
|
||||
@ApiProperty({
|
||||
description: 'homeId',
|
||||
required: true,
|
||||
})
|
||||
@IsNumberString()
|
||||
@IsNotEmpty()
|
||||
public homeId: string;
|
||||
|
||||
@ApiProperty({
|
||||
description: 'pageSize',
|
||||
required: true,
|
||||
})
|
||||
@IsNumberString()
|
||||
@IsNotEmpty()
|
||||
public pageSize: number;
|
||||
|
||||
@ApiProperty({
|
||||
description: 'pageNo',
|
||||
required: true,
|
||||
})
|
||||
@IsNumberString()
|
||||
@IsNotEmpty()
|
||||
public pageNo: number;
|
||||
}
|
@ -1,15 +1,7 @@
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
import { IsNotEmpty, IsString, IsNumberString } from 'class-validator';
|
||||
import { IsNotEmpty, IsString } from 'class-validator';
|
||||
|
||||
export class RenameGroupDto {
|
||||
@ApiProperty({
|
||||
description: 'groupId',
|
||||
required: true,
|
||||
})
|
||||
@IsNumberString()
|
||||
@IsNotEmpty()
|
||||
public groupId: string;
|
||||
|
||||
@ApiProperty({
|
||||
description: 'groupName',
|
||||
required: true,
|
||||
|
@ -2,10 +2,26 @@ import { Module } from '@nestjs/common';
|
||||
import { GroupService } from './services/group.service';
|
||||
import { GroupController } from './controllers/group.controller';
|
||||
import { ConfigModule } from '@nestjs/config';
|
||||
import { GroupRepositoryModule } from '@app/common/modules/group/group.repository.module';
|
||||
import { GroupRepository } from '@app/common/modules/group/repositories';
|
||||
import { GroupDeviceRepositoryModule } from '@app/common/modules/group-device/group.device.repository.module';
|
||||
import { GroupDeviceRepository } from '@app/common/modules/group-device/repositories';
|
||||
import { DeviceRepositoryModule } from '@app/common/modules/device';
|
||||
import { DeviceRepository } from '@app/common/modules/device/repositories';
|
||||
@Module({
|
||||
imports: [ConfigModule],
|
||||
imports: [
|
||||
ConfigModule,
|
||||
GroupRepositoryModule,
|
||||
GroupDeviceRepositoryModule,
|
||||
DeviceRepositoryModule,
|
||||
],
|
||||
controllers: [GroupController],
|
||||
providers: [GroupService],
|
||||
providers: [
|
||||
GroupService,
|
||||
GroupRepository,
|
||||
GroupDeviceRepository,
|
||||
DeviceRepository,
|
||||
],
|
||||
exports: [GroupService],
|
||||
})
|
||||
export class GroupModule {}
|
||||
|
@ -1,25 +1,15 @@
|
||||
export class GetGroupDetailsInterface {
|
||||
result: {
|
||||
id: string;
|
||||
name: string;
|
||||
};
|
||||
export interface GetGroupDetailsInterface {
|
||||
groupUuid: string;
|
||||
groupName: string;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
}
|
||||
export class GetGroupsInterface {
|
||||
result: {
|
||||
count: number;
|
||||
data_list: [];
|
||||
};
|
||||
export interface GetGroupsBySpaceUuidInterface {
|
||||
groupUuid: string;
|
||||
groupName: string;
|
||||
}
|
||||
|
||||
export class addGroupInterface {
|
||||
success: boolean;
|
||||
msg: string;
|
||||
result: {
|
||||
id: string;
|
||||
};
|
||||
}
|
||||
|
||||
export class controlGroupInterface {
|
||||
export interface controlGroupInterface {
|
||||
success: boolean;
|
||||
result: boolean;
|
||||
msg: string;
|
||||
|
@ -1,21 +1,31 @@
|
||||
import { Injectable, HttpException, HttpStatus } from '@nestjs/common';
|
||||
import {
|
||||
Injectable,
|
||||
HttpException,
|
||||
HttpStatus,
|
||||
BadRequestException,
|
||||
} from '@nestjs/common';
|
||||
import { TuyaContext } from '@tuya/tuya-connector-nodejs';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { AddGroupDto } from '../dtos/add.group.dto';
|
||||
import {
|
||||
GetGroupDetailsInterface,
|
||||
GetGroupsInterface,
|
||||
addGroupInterface,
|
||||
controlGroupInterface,
|
||||
GetGroupsBySpaceUuidInterface,
|
||||
} from '../interfaces/get.group.interface';
|
||||
import { GetGroupDto } from '../dtos/get.group.dto';
|
||||
import { ControlGroupDto } from '../dtos/control.group.dto';
|
||||
import { RenameGroupDto } from '../dtos/rename.group.dto copy';
|
||||
import { GroupRepository } from '@app/common/modules/group/repositories';
|
||||
import { GroupDeviceRepository } from '@app/common/modules/group-device/repositories';
|
||||
import { controlDeviceInterface } from 'src/device/interfaces/get.device.interface';
|
||||
import { ControlDeviceDto } from 'src/device/dtos';
|
||||
|
||||
@Injectable()
|
||||
export class GroupService {
|
||||
private tuya: TuyaContext;
|
||||
constructor(private readonly configService: ConfigService) {
|
||||
constructor(
|
||||
private readonly configService: ConfigService,
|
||||
private readonly groupRepository: GroupRepository,
|
||||
private readonly groupDeviceRepository: GroupDeviceRepository,
|
||||
) {
|
||||
const accessKey = this.configService.get<string>('auth-config.ACCESS_KEY');
|
||||
const secretKey = this.configService.get<string>('auth-config.SECRET_KEY');
|
||||
// const clientId = this.configService.get<string>('auth-config.CLIENT_ID');
|
||||
@ -26,88 +36,100 @@ export class GroupService {
|
||||
});
|
||||
}
|
||||
|
||||
async getGroupsByHomeId(getGroupDto: GetGroupDto) {
|
||||
async getGroupsBySpaceUuid(
|
||||
spaceUuid: string,
|
||||
): Promise<GetGroupsBySpaceUuidInterface[]> {
|
||||
try {
|
||||
const response = await this.getGroupsTuya(getGroupDto);
|
||||
|
||||
const groups = response.result.data_list.map((group: any) => ({
|
||||
groupId: group.id,
|
||||
groupName: group.name,
|
||||
}));
|
||||
|
||||
return {
|
||||
count: response.result.count,
|
||||
groups: groups,
|
||||
};
|
||||
} catch (error) {
|
||||
throw new HttpException(
|
||||
'Error fetching groups',
|
||||
HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async getGroupsTuya(getGroupDto: GetGroupDto): Promise<GetGroupsInterface> {
|
||||
try {
|
||||
const path = `/v2.0/cloud/thing/group`;
|
||||
const response = await this.tuya.request({
|
||||
method: 'GET',
|
||||
path,
|
||||
query: {
|
||||
space_id: getGroupDto.homeId,
|
||||
page_size: getGroupDto.pageSize,
|
||||
page_no: getGroupDto.pageNo,
|
||||
const groupDevices = await this.groupDeviceRepository.find({
|
||||
relations: ['group', 'device'],
|
||||
where: {
|
||||
device: { spaceUuid },
|
||||
isActive: true,
|
||||
},
|
||||
});
|
||||
return response as unknown as GetGroupsInterface;
|
||||
|
||||
// Extract and return only the group entities
|
||||
const groups = groupDevices.map((groupDevice) => {
|
||||
return {
|
||||
groupUuid: groupDevice.uuid,
|
||||
groupName: groupDevice.group.groupName,
|
||||
};
|
||||
});
|
||||
if (groups.length > 0) {
|
||||
return groups;
|
||||
} else {
|
||||
throw new HttpException(
|
||||
'this space has no groups',
|
||||
HttpStatus.NOT_FOUND,
|
||||
);
|
||||
}
|
||||
} catch (error) {
|
||||
throw new HttpException(
|
||||
'Error fetching groups ',
|
||||
HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
error.message || 'Error fetching groups',
|
||||
error.status || HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async addGroup(addGroupDto: AddGroupDto) {
|
||||
const response = await this.addGroupTuya(addGroupDto);
|
||||
try {
|
||||
const group = await this.groupRepository.save({
|
||||
groupName: addGroupDto.groupName,
|
||||
});
|
||||
|
||||
if (response.success) {
|
||||
return {
|
||||
success: true,
|
||||
groupId: response.result.id,
|
||||
};
|
||||
} else {
|
||||
const groupDevicePromises = addGroupDto.deviceUuids.map(
|
||||
async (deviceUuid) => {
|
||||
await this.saveGroupDevice(group.uuid, deviceUuid);
|
||||
},
|
||||
);
|
||||
|
||||
await Promise.all(groupDevicePromises);
|
||||
} catch (err) {
|
||||
if (err.code === '23505') {
|
||||
throw new HttpException(
|
||||
response.msg || 'Unknown error',
|
||||
'User already belongs to this group',
|
||||
HttpStatus.BAD_REQUEST,
|
||||
);
|
||||
}
|
||||
}
|
||||
async addGroupTuya(addGroupDto: AddGroupDto): Promise<addGroupInterface> {
|
||||
try {
|
||||
const path = `/v2.0/cloud/thing/group`;
|
||||
const response = await this.tuya.request({
|
||||
method: 'POST',
|
||||
path,
|
||||
body: {
|
||||
space_id: addGroupDto.homeId,
|
||||
name: addGroupDto.groupName,
|
||||
product_id: addGroupDto.productId,
|
||||
device_ids: addGroupDto.deviceIds,
|
||||
},
|
||||
});
|
||||
|
||||
return response as addGroupInterface;
|
||||
} catch (error) {
|
||||
throw new HttpException(
|
||||
'Error adding group',
|
||||
err.message || 'Internal Server Error',
|
||||
HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async controlGroup(controlGroupDto: ControlGroupDto) {
|
||||
const response = await this.controlGroupTuya(controlGroupDto);
|
||||
private async saveGroupDevice(groupUuid: string, deviceUuid: string) {
|
||||
try {
|
||||
await this.groupDeviceRepository.save({
|
||||
group: {
|
||||
uuid: groupUuid,
|
||||
},
|
||||
device: {
|
||||
uuid: deviceUuid,
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
async getDevicesByGroupUuid(groupUuid: string) {
|
||||
try {
|
||||
const devices = await this.groupDeviceRepository.find({
|
||||
relations: ['device'],
|
||||
where: {
|
||||
group: {
|
||||
uuid: groupUuid,
|
||||
},
|
||||
isActive: true,
|
||||
},
|
||||
});
|
||||
return devices;
|
||||
} catch (error) {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
async controlDevice(controlDeviceDto: ControlDeviceDto) {
|
||||
const response = await this.controlDeviceTuya(controlDeviceDto);
|
||||
|
||||
if (response.success) {
|
||||
return response;
|
||||
@ -118,128 +140,120 @@ export class GroupService {
|
||||
);
|
||||
}
|
||||
}
|
||||
async controlGroupTuya(
|
||||
controlGroupDto: ControlGroupDto,
|
||||
): Promise<controlGroupInterface> {
|
||||
async controlDeviceTuya(
|
||||
controlDeviceDto: ControlDeviceDto,
|
||||
): Promise<controlDeviceInterface> {
|
||||
try {
|
||||
const path = `/v2.0/cloud/thing/group/properties`;
|
||||
const path = `/v1.0/iot-03/devices/${controlDeviceDto.deviceId}/commands`;
|
||||
const response = await this.tuya.request({
|
||||
method: 'POST',
|
||||
path,
|
||||
body: {
|
||||
group_id: controlGroupDto.groupId,
|
||||
properties: controlGroupDto.properties,
|
||||
commands: [
|
||||
{ code: controlDeviceDto.code, value: controlDeviceDto.value },
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
return response as controlGroupInterface;
|
||||
return response as controlDeviceInterface;
|
||||
} catch (error) {
|
||||
throw new HttpException(
|
||||
'Error control group',
|
||||
'Error control device from Tuya',
|
||||
HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
}
|
||||
async controlGroup(controlGroupDto: ControlGroupDto) {
|
||||
const devices = await this.getDevicesByGroupUuid(controlGroupDto.groupUuid);
|
||||
|
||||
try {
|
||||
await Promise.all(
|
||||
devices.map(async (device) => {
|
||||
return this.controlDevice({
|
||||
deviceId: device.device.deviceTuyaUuid,
|
||||
code: controlGroupDto.code,
|
||||
value: controlGroupDto.value,
|
||||
});
|
||||
}),
|
||||
);
|
||||
} catch (error) {
|
||||
throw new HttpException(
|
||||
'Error controlling devices',
|
||||
HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async renameGroup(renameGroupDto: RenameGroupDto) {
|
||||
const response = await this.renameGroupTuya(renameGroupDto);
|
||||
|
||||
if (response.success) {
|
||||
return {
|
||||
success: response.success,
|
||||
result: response.result,
|
||||
msg: response.msg,
|
||||
};
|
||||
} else {
|
||||
throw new HttpException(
|
||||
response.msg || 'Unknown error',
|
||||
HttpStatus.BAD_REQUEST,
|
||||
);
|
||||
}
|
||||
}
|
||||
async renameGroupTuya(
|
||||
async renameGroupByUuid(
|
||||
groupUuid: string,
|
||||
renameGroupDto: RenameGroupDto,
|
||||
): Promise<controlGroupInterface> {
|
||||
): Promise<GetGroupsBySpaceUuidInterface> {
|
||||
try {
|
||||
const path = `/v2.0/cloud/thing/group/${renameGroupDto.groupId}/${renameGroupDto.groupName}`;
|
||||
const response = await this.tuya.request({
|
||||
method: 'PUT',
|
||||
path,
|
||||
await this.groupRepository.update(
|
||||
{ uuid: groupUuid },
|
||||
{ groupName: renameGroupDto.groupName },
|
||||
);
|
||||
|
||||
// Fetch the updated floor
|
||||
const updatedGroup = await this.groupRepository.findOneOrFail({
|
||||
where: { uuid: groupUuid },
|
||||
});
|
||||
|
||||
return response as controlGroupInterface;
|
||||
} catch (error) {
|
||||
throw new HttpException(
|
||||
'Error rename group',
|
||||
HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async deleteGroup(groupId: number) {
|
||||
const response = await this.deleteGroupTuya(groupId);
|
||||
|
||||
if (response.success) {
|
||||
return {
|
||||
success: response.success,
|
||||
result: response.result,
|
||||
msg: response.msg,
|
||||
};
|
||||
} else {
|
||||
throw new HttpException(
|
||||
response.msg || 'Unknown error',
|
||||
HttpStatus.BAD_REQUEST,
|
||||
);
|
||||
}
|
||||
}
|
||||
async deleteGroupTuya(groupId: number): Promise<controlGroupInterface> {
|
||||
try {
|
||||
const path = `/v2.0/cloud/thing/group/${groupId}`;
|
||||
const response = await this.tuya.request({
|
||||
method: 'DELETE',
|
||||
path,
|
||||
});
|
||||
|
||||
return response as controlGroupInterface;
|
||||
} catch (error) {
|
||||
throw new HttpException(
|
||||
'Error delete group',
|
||||
HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async getGroupsByGroupId(groupId: number) {
|
||||
try {
|
||||
const response = await this.getGroupsByGroupIdTuya(groupId);
|
||||
|
||||
return {
|
||||
groupId: response.result.id,
|
||||
groupName: response.result.name,
|
||||
groupUuid: updatedGroup.uuid,
|
||||
groupName: updatedGroup.groupName,
|
||||
};
|
||||
} catch (error) {
|
||||
throw new HttpException('Group not found', HttpStatus.NOT_FOUND);
|
||||
}
|
||||
}
|
||||
|
||||
async deleteGroup(groupUuid: string) {
|
||||
try {
|
||||
const group = await this.getGroupsByGroupUuid(groupUuid);
|
||||
|
||||
if (!group) {
|
||||
throw new HttpException('Group not found', HttpStatus.NOT_FOUND);
|
||||
}
|
||||
|
||||
await this.groupRepository.update(
|
||||
{ uuid: groupUuid },
|
||||
{ isActive: false },
|
||||
);
|
||||
|
||||
return { message: 'Group deleted successfully' };
|
||||
} catch (error) {
|
||||
throw new HttpException(
|
||||
'Error fetching group',
|
||||
HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
error.message || 'Error deleting group',
|
||||
error.status || HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async getGroupsByGroupIdTuya(
|
||||
groupId: number,
|
||||
async getGroupsByGroupUuid(
|
||||
groupUuid: string,
|
||||
): Promise<GetGroupDetailsInterface> {
|
||||
try {
|
||||
const path = `/v2.0/cloud/thing/group/${groupId}`;
|
||||
const response = await this.tuya.request({
|
||||
method: 'GET',
|
||||
path,
|
||||
const group = await this.groupRepository.findOne({
|
||||
where: {
|
||||
uuid: groupUuid,
|
||||
isActive: true,
|
||||
},
|
||||
});
|
||||
return response as GetGroupDetailsInterface;
|
||||
} catch (error) {
|
||||
throw new HttpException(
|
||||
'Error fetching group ',
|
||||
HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
if (!group) {
|
||||
throw new BadRequestException('Invalid group UUID');
|
||||
}
|
||||
return {
|
||||
groupUuid: group.uuid,
|
||||
groupName: group.groupName,
|
||||
createdAt: group.createdAt,
|
||||
updatedAt: group.updatedAt,
|
||||
};
|
||||
} catch (err) {
|
||||
if (err instanceof BadRequestException) {
|
||||
throw err; // Re-throw BadRequestException
|
||||
} else {
|
||||
throw new HttpException('Group not found', HttpStatus.NOT_FOUND);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
71
src/guards/device.product.guard.ts
Normal file
71
src/guards/device.product.guard.ts
Normal file
@ -0,0 +1,71 @@
|
||||
import { DeviceRepository } from '@app/common/modules/device/repositories';
|
||||
import {
|
||||
Injectable,
|
||||
CanActivate,
|
||||
HttpStatus,
|
||||
BadRequestException,
|
||||
ExecutionContext,
|
||||
} from '@nestjs/common';
|
||||
|
||||
@Injectable()
|
||||
export class CheckProductUuidForAllDevicesGuard implements CanActivate {
|
||||
constructor(private readonly deviceRepository: DeviceRepository) {}
|
||||
|
||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
const req = context.switchToHttp().getRequest();
|
||||
|
||||
try {
|
||||
const { deviceUuids } = req.body;
|
||||
console.log(deviceUuids);
|
||||
|
||||
await this.checkAllDevicesHaveSameProductUuid(deviceUuids);
|
||||
|
||||
return true;
|
||||
} catch (error) {
|
||||
this.handleGuardError(error, context);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async checkAllDevicesHaveSameProductUuid(deviceUuids: string[]) {
|
||||
const firstDevice = await this.deviceRepository.findOne({
|
||||
where: { uuid: deviceUuids[0] },
|
||||
});
|
||||
|
||||
if (!firstDevice) {
|
||||
throw new BadRequestException('First device not found');
|
||||
}
|
||||
|
||||
const firstProductUuid = firstDevice.productUuid;
|
||||
|
||||
for (let i = 1; i < deviceUuids.length; i++) {
|
||||
const device = await this.deviceRepository.findOne({
|
||||
where: { uuid: deviceUuids[i] },
|
||||
});
|
||||
|
||||
if (!device) {
|
||||
throw new BadRequestException(`Device ${deviceUuids[i]} not found`);
|
||||
}
|
||||
|
||||
if (device.productUuid !== firstProductUuid) {
|
||||
throw new BadRequestException(`Devices have different product UUIDs`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private handleGuardError(error: Error, context: ExecutionContext) {
|
||||
const response = context.switchToHttp().getResponse();
|
||||
console.error(error);
|
||||
|
||||
if (error instanceof BadRequestException) {
|
||||
response
|
||||
.status(HttpStatus.BAD_REQUEST)
|
||||
.json({ statusCode: HttpStatus.BAD_REQUEST, message: error.message });
|
||||
} else {
|
||||
response.status(HttpStatus.NOT_FOUND).json({
|
||||
statusCode: HttpStatus.NOT_FOUND,
|
||||
message: 'Device not found',
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
70
src/guards/user.building.guard.ts
Normal file
70
src/guards/user.building.guard.ts
Normal file
@ -0,0 +1,70 @@
|
||||
import {
|
||||
CanActivate,
|
||||
ExecutionContext,
|
||||
Injectable,
|
||||
HttpStatus,
|
||||
} from '@nestjs/common';
|
||||
import { SpaceRepository } from '@app/common/modules/space/repositories';
|
||||
import { BadRequestException, NotFoundException } from '@nestjs/common';
|
||||
import { UserRepository } from '@app/common/modules/user/repositories';
|
||||
|
||||
@Injectable()
|
||||
export class CheckUserBuildingGuard implements CanActivate {
|
||||
constructor(
|
||||
private readonly spaceRepository: SpaceRepository,
|
||||
private readonly userRepository: UserRepository,
|
||||
) {}
|
||||
|
||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
const req = context.switchToHttp().getRequest();
|
||||
|
||||
try {
|
||||
const { userUuid, buildingUuid } = req.body;
|
||||
|
||||
await this.checkUserIsFound(userUuid);
|
||||
|
||||
await this.checkBuildingIsFound(buildingUuid);
|
||||
|
||||
return true;
|
||||
} catch (error) {
|
||||
this.handleGuardError(error, context);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private async checkUserIsFound(userUuid: string) {
|
||||
const userData = await this.userRepository.findOne({
|
||||
where: { uuid: userUuid },
|
||||
});
|
||||
if (!userData) {
|
||||
throw new NotFoundException('User not found');
|
||||
}
|
||||
}
|
||||
|
||||
private async checkBuildingIsFound(spaceUuid: string) {
|
||||
const spaceData = await this.spaceRepository.findOne({
|
||||
where: { uuid: spaceUuid, spaceType: { type: 'building' } },
|
||||
relations: ['spaceType'],
|
||||
});
|
||||
if (!spaceData) {
|
||||
throw new NotFoundException('Building not found');
|
||||
}
|
||||
}
|
||||
|
||||
private handleGuardError(error: Error, context: ExecutionContext) {
|
||||
const response = context.switchToHttp().getResponse();
|
||||
if (
|
||||
error instanceof BadRequestException ||
|
||||
error instanceof NotFoundException
|
||||
) {
|
||||
response
|
||||
.status(HttpStatus.NOT_FOUND)
|
||||
.json({ statusCode: HttpStatus.NOT_FOUND, message: error.message });
|
||||
} else {
|
||||
response.status(HttpStatus.BAD_REQUEST).json({
|
||||
statusCode: HttpStatus.BAD_REQUEST,
|
||||
message: 'invalid userUuid or buildingUuid',
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
70
src/guards/user.community.guard.ts
Normal file
70
src/guards/user.community.guard.ts
Normal file
@ -0,0 +1,70 @@
|
||||
import {
|
||||
CanActivate,
|
||||
ExecutionContext,
|
||||
Injectable,
|
||||
HttpStatus,
|
||||
} from '@nestjs/common';
|
||||
import { SpaceRepository } from '@app/common/modules/space/repositories';
|
||||
import { BadRequestException, NotFoundException } from '@nestjs/common';
|
||||
import { UserRepository } from '@app/common/modules/user/repositories';
|
||||
|
||||
@Injectable()
|
||||
export class CheckUserCommunityGuard implements CanActivate {
|
||||
constructor(
|
||||
private readonly spaceRepository: SpaceRepository,
|
||||
private readonly userRepository: UserRepository,
|
||||
) {}
|
||||
|
||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
const req = context.switchToHttp().getRequest();
|
||||
|
||||
try {
|
||||
const { userUuid, communityUuid } = req.body;
|
||||
|
||||
await this.checkUserIsFound(userUuid);
|
||||
|
||||
await this.checkCommunityIsFound(communityUuid);
|
||||
|
||||
return true;
|
||||
} catch (error) {
|
||||
this.handleGuardError(error, context);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private async checkUserIsFound(userUuid: string) {
|
||||
const userData = await this.userRepository.findOne({
|
||||
where: { uuid: userUuid },
|
||||
});
|
||||
if (!userData) {
|
||||
throw new NotFoundException('User not found');
|
||||
}
|
||||
}
|
||||
|
||||
private async checkCommunityIsFound(spaceUuid: string) {
|
||||
const spaceData = await this.spaceRepository.findOne({
|
||||
where: { uuid: spaceUuid, spaceType: { type: 'community' } },
|
||||
relations: ['spaceType'],
|
||||
});
|
||||
if (!spaceData) {
|
||||
throw new NotFoundException('Community not found');
|
||||
}
|
||||
}
|
||||
|
||||
private handleGuardError(error: Error, context: ExecutionContext) {
|
||||
const response = context.switchToHttp().getResponse();
|
||||
if (
|
||||
error instanceof BadRequestException ||
|
||||
error instanceof NotFoundException
|
||||
) {
|
||||
response
|
||||
.status(HttpStatus.NOT_FOUND)
|
||||
.json({ statusCode: HttpStatus.NOT_FOUND, message: error.message });
|
||||
} else {
|
||||
response.status(HttpStatus.BAD_REQUEST).json({
|
||||
statusCode: HttpStatus.BAD_REQUEST,
|
||||
message: 'invalid userUuid or communityUuid',
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
70
src/guards/user.floor.guard.ts
Normal file
70
src/guards/user.floor.guard.ts
Normal file
@ -0,0 +1,70 @@
|
||||
import {
|
||||
CanActivate,
|
||||
ExecutionContext,
|
||||
Injectable,
|
||||
HttpStatus,
|
||||
} from '@nestjs/common';
|
||||
import { SpaceRepository } from '@app/common/modules/space/repositories';
|
||||
import { BadRequestException, NotFoundException } from '@nestjs/common';
|
||||
import { UserRepository } from '@app/common/modules/user/repositories';
|
||||
|
||||
@Injectable()
|
||||
export class CheckUserFloorGuard implements CanActivate {
|
||||
constructor(
|
||||
private readonly spaceRepository: SpaceRepository,
|
||||
private readonly userRepository: UserRepository,
|
||||
) {}
|
||||
|
||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
const req = context.switchToHttp().getRequest();
|
||||
|
||||
try {
|
||||
const { userUuid, floorUuid } = req.body;
|
||||
|
||||
await this.checkUserIsFound(userUuid);
|
||||
|
||||
await this.checkFloorIsFound(floorUuid);
|
||||
|
||||
return true;
|
||||
} catch (error) {
|
||||
this.handleGuardError(error, context);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private async checkUserIsFound(userUuid: string) {
|
||||
const userData = await this.userRepository.findOne({
|
||||
where: { uuid: userUuid },
|
||||
});
|
||||
if (!userData) {
|
||||
throw new NotFoundException('User not found');
|
||||
}
|
||||
}
|
||||
|
||||
private async checkFloorIsFound(spaceUuid: string) {
|
||||
const spaceData = await this.spaceRepository.findOne({
|
||||
where: { uuid: spaceUuid, spaceType: { type: 'floor' } },
|
||||
relations: ['spaceType'],
|
||||
});
|
||||
if (!spaceData) {
|
||||
throw new NotFoundException('Floor not found');
|
||||
}
|
||||
}
|
||||
|
||||
private handleGuardError(error: Error, context: ExecutionContext) {
|
||||
const response = context.switchToHttp().getResponse();
|
||||
if (
|
||||
error instanceof BadRequestException ||
|
||||
error instanceof NotFoundException
|
||||
) {
|
||||
response
|
||||
.status(HttpStatus.NOT_FOUND)
|
||||
.json({ statusCode: HttpStatus.NOT_FOUND, message: error.message });
|
||||
} else {
|
||||
response.status(HttpStatus.BAD_REQUEST).json({
|
||||
statusCode: HttpStatus.BAD_REQUEST,
|
||||
message: 'invalid userUuid or floorUuid',
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
70
src/guards/user.room.guard.ts
Normal file
70
src/guards/user.room.guard.ts
Normal file
@ -0,0 +1,70 @@
|
||||
import {
|
||||
CanActivate,
|
||||
ExecutionContext,
|
||||
Injectable,
|
||||
HttpStatus,
|
||||
} from '@nestjs/common';
|
||||
import { SpaceRepository } from '@app/common/modules/space/repositories';
|
||||
import { BadRequestException, NotFoundException } from '@nestjs/common';
|
||||
import { UserRepository } from '@app/common/modules/user/repositories';
|
||||
|
||||
@Injectable()
|
||||
export class CheckUserRoomGuard implements CanActivate {
|
||||
constructor(
|
||||
private readonly spaceRepository: SpaceRepository,
|
||||
private readonly userRepository: UserRepository,
|
||||
) {}
|
||||
|
||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
const req = context.switchToHttp().getRequest();
|
||||
|
||||
try {
|
||||
const { userUuid, roomUuid } = req.body;
|
||||
|
||||
await this.checkUserIsFound(userUuid);
|
||||
|
||||
await this.checkRoomIsFound(roomUuid);
|
||||
|
||||
return true;
|
||||
} catch (error) {
|
||||
this.handleGuardError(error, context);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private async checkUserIsFound(userUuid: string) {
|
||||
const userData = await this.userRepository.findOne({
|
||||
where: { uuid: userUuid },
|
||||
});
|
||||
if (!userData) {
|
||||
throw new NotFoundException('User not found');
|
||||
}
|
||||
}
|
||||
|
||||
private async checkRoomIsFound(spaceUuid: string) {
|
||||
const spaceData = await this.spaceRepository.findOne({
|
||||
where: { uuid: spaceUuid, spaceType: { type: 'room' } },
|
||||
relations: ['spaceType'],
|
||||
});
|
||||
if (!spaceData) {
|
||||
throw new NotFoundException('Room not found');
|
||||
}
|
||||
}
|
||||
|
||||
private handleGuardError(error: Error, context: ExecutionContext) {
|
||||
const response = context.switchToHttp().getResponse();
|
||||
if (
|
||||
error instanceof BadRequestException ||
|
||||
error instanceof NotFoundException
|
||||
) {
|
||||
response
|
||||
.status(HttpStatus.NOT_FOUND)
|
||||
.json({ statusCode: HttpStatus.NOT_FOUND, message: error.message });
|
||||
} else {
|
||||
response.status(HttpStatus.BAD_REQUEST).json({
|
||||
statusCode: HttpStatus.BAD_REQUEST,
|
||||
message: 'invalid userUuid or roomUuid',
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
70
src/guards/user.unit.guard.ts
Normal file
70
src/guards/user.unit.guard.ts
Normal file
@ -0,0 +1,70 @@
|
||||
import {
|
||||
CanActivate,
|
||||
ExecutionContext,
|
||||
Injectable,
|
||||
HttpStatus,
|
||||
} from '@nestjs/common';
|
||||
import { SpaceRepository } from '@app/common/modules/space/repositories';
|
||||
import { BadRequestException, NotFoundException } from '@nestjs/common';
|
||||
import { UserRepository } from '@app/common/modules/user/repositories';
|
||||
|
||||
@Injectable()
|
||||
export class CheckUserUnitGuard implements CanActivate {
|
||||
constructor(
|
||||
private readonly spaceRepository: SpaceRepository,
|
||||
private readonly userRepository: UserRepository,
|
||||
) {}
|
||||
|
||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
const req = context.switchToHttp().getRequest();
|
||||
|
||||
try {
|
||||
const { userUuid, unitUuid } = req.body;
|
||||
|
||||
await this.checkUserIsFound(userUuid);
|
||||
|
||||
await this.checkUnitIsFound(unitUuid);
|
||||
|
||||
return true;
|
||||
} catch (error) {
|
||||
this.handleGuardError(error, context);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private async checkUserIsFound(userUuid: string) {
|
||||
const userData = await this.userRepository.findOne({
|
||||
where: { uuid: userUuid },
|
||||
});
|
||||
if (!userData) {
|
||||
throw new NotFoundException('User not found');
|
||||
}
|
||||
}
|
||||
|
||||
private async checkUnitIsFound(spaceUuid: string) {
|
||||
const spaceData = await this.spaceRepository.findOne({
|
||||
where: { uuid: spaceUuid, spaceType: { type: 'unit' } },
|
||||
relations: ['spaceType'],
|
||||
});
|
||||
if (!spaceData) {
|
||||
throw new NotFoundException('Unit not found');
|
||||
}
|
||||
}
|
||||
|
||||
private handleGuardError(error: Error, context: ExecutionContext) {
|
||||
const response = context.switchToHttp().getResponse();
|
||||
if (
|
||||
error instanceof BadRequestException ||
|
||||
error instanceof NotFoundException
|
||||
) {
|
||||
response
|
||||
.status(HttpStatus.NOT_FOUND)
|
||||
.json({ statusCode: HttpStatus.NOT_FOUND, message: error.message });
|
||||
} else {
|
||||
response.status(HttpStatus.BAD_REQUEST).json({
|
||||
statusCode: HttpStatus.BAD_REQUEST,
|
||||
message: 'invalid userUuid or unitUuid',
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
@ -12,9 +12,10 @@ import {
|
||||
} from '@nestjs/common';
|
||||
import { ApiTags, ApiBearerAuth } from '@nestjs/swagger';
|
||||
import { JwtAuthGuard } from '../../../libs/common/src/guards/jwt.auth.guard';
|
||||
import { AddRoomDto } from '../dtos/add.room.dto';
|
||||
import { AddRoomDto, AddUserRoomDto } from '../dtos/add.room.dto';
|
||||
import { UpdateRoomNameDto } from '../dtos/update.room.dto';
|
||||
import { CheckUnitTypeGuard } from 'src/guards/unit.type.guard';
|
||||
import { CheckUserRoomGuard } from 'src/guards/user.room.guard';
|
||||
|
||||
@ApiTags('Room Module')
|
||||
@Controller({
|
||||
@ -68,6 +69,33 @@ export class RoomController {
|
||||
);
|
||||
}
|
||||
}
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard, CheckUserRoomGuard)
|
||||
@Post('user')
|
||||
async addUserRoom(@Body() addUserRoomDto: AddUserRoomDto) {
|
||||
try {
|
||||
await this.roomService.addUserRoom(addUserRoomDto);
|
||||
return { message: 'user room added successfully' };
|
||||
} catch (error) {
|
||||
throw new HttpException(
|
||||
error.message || 'Internal server error',
|
||||
error.status || HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
}
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@Get('user/:userUuid')
|
||||
async getRoomsByUserId(@Param('userUuid') userUuid: string) {
|
||||
try {
|
||||
return await this.roomService.getRoomsByUserId(userUuid);
|
||||
} catch (error) {
|
||||
throw new HttpException(
|
||||
error.message || 'Internal server error',
|
||||
error.status || HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard)
|
||||
|
@ -21,3 +21,22 @@ export class AddRoomDto {
|
||||
Object.assign(this, dto);
|
||||
}
|
||||
}
|
||||
export class AddUserRoomDto {
|
||||
@ApiProperty({
|
||||
description: 'roomUuid',
|
||||
required: true,
|
||||
})
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
public roomUuid: string;
|
||||
@ApiProperty({
|
||||
description: 'userUuid',
|
||||
required: true,
|
||||
})
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
public userUuid: string;
|
||||
constructor(dto: Partial<AddUserRoomDto>) {
|
||||
Object.assign(this, dto);
|
||||
}
|
||||
}
|
||||
|
@ -17,3 +17,8 @@ export interface RenameRoomByUuidInterface {
|
||||
name: string;
|
||||
type: string;
|
||||
}
|
||||
export interface GetRoomByUserUuidInterface {
|
||||
uuid: string;
|
||||
name: string;
|
||||
type: string;
|
||||
}
|
||||
|
@ -6,11 +6,27 @@ import { SpaceRepositoryModule } from '@app/common/modules/space/space.repositor
|
||||
import { SpaceRepository } from '@app/common/modules/space/repositories';
|
||||
import { SpaceTypeRepositoryModule } from '@app/common/modules/space-type/space.type.repository.module';
|
||||
import { SpaceTypeRepository } from '@app/common/modules/space-type/repositories';
|
||||
import { UserSpaceRepositoryModule } from '@app/common/modules/user-space/user.space.repository.module';
|
||||
import { UserSpaceRepository } from '@app/common/modules/user-space/repositories';
|
||||
import { UserRepositoryModule } from '@app/common/modules/user/user.repository.module';
|
||||
import { UserRepository } from '@app/common/modules/user/repositories';
|
||||
|
||||
@Module({
|
||||
imports: [ConfigModule, SpaceRepositoryModule, SpaceTypeRepositoryModule],
|
||||
imports: [
|
||||
ConfigModule,
|
||||
SpaceRepositoryModule,
|
||||
SpaceTypeRepositoryModule,
|
||||
UserSpaceRepositoryModule,
|
||||
UserRepositoryModule,
|
||||
],
|
||||
controllers: [RoomController],
|
||||
providers: [RoomService, SpaceRepository, SpaceTypeRepository],
|
||||
providers: [
|
||||
RoomService,
|
||||
SpaceRepository,
|
||||
SpaceTypeRepository,
|
||||
UserSpaceRepository,
|
||||
UserRepository,
|
||||
],
|
||||
exports: [RoomService],
|
||||
})
|
||||
export class RoomModule {}
|
||||
|
@ -6,19 +6,22 @@ import {
|
||||
BadRequestException,
|
||||
} from '@nestjs/common';
|
||||
import { SpaceRepository } from '@app/common/modules/space/repositories';
|
||||
import { AddRoomDto } from '../dtos';
|
||||
import { AddRoomDto, AddUserRoomDto } from '../dtos';
|
||||
import {
|
||||
RoomParentInterface,
|
||||
GetRoomByUuidInterface,
|
||||
RenameRoomByUuidInterface,
|
||||
GetRoomByUserUuidInterface,
|
||||
} from '../interface/room.interface';
|
||||
import { UpdateRoomNameDto } from '../dtos/update.room.dto';
|
||||
import { UserSpaceRepository } from '@app/common/modules/user-space/repositories';
|
||||
|
||||
@Injectable()
|
||||
export class RoomService {
|
||||
constructor(
|
||||
private readonly spaceRepository: SpaceRepository,
|
||||
private readonly spaceTypeRepository: SpaceTypeRepository,
|
||||
private readonly userSpaceRepository: UserSpaceRepository,
|
||||
) {}
|
||||
|
||||
async addRoom(addRoomDto: AddRoomDto) {
|
||||
@ -103,6 +106,56 @@ export class RoomService {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async getRoomsByUserId(
|
||||
userUuid: string,
|
||||
): Promise<GetRoomByUserUuidInterface[]> {
|
||||
try {
|
||||
const rooms = await this.userSpaceRepository.find({
|
||||
relations: ['space', 'space.spaceType'],
|
||||
where: {
|
||||
user: { uuid: userUuid },
|
||||
space: { spaceType: { type: 'room' } },
|
||||
},
|
||||
});
|
||||
|
||||
if (rooms.length === 0) {
|
||||
throw new HttpException('this user has no rooms', HttpStatus.NOT_FOUND);
|
||||
}
|
||||
const spaces = rooms.map((room) => ({
|
||||
uuid: room.space.uuid,
|
||||
name: room.space.spaceName,
|
||||
type: room.space.spaceType.type,
|
||||
}));
|
||||
|
||||
return spaces;
|
||||
} catch (err) {
|
||||
if (err instanceof HttpException) {
|
||||
throw err;
|
||||
} else {
|
||||
throw new HttpException('user not found', HttpStatus.NOT_FOUND);
|
||||
}
|
||||
}
|
||||
}
|
||||
async addUserRoom(addUserRoomDto: AddUserRoomDto) {
|
||||
try {
|
||||
await this.userSpaceRepository.save({
|
||||
user: { uuid: addUserRoomDto.userUuid },
|
||||
space: { uuid: addUserRoomDto.roomUuid },
|
||||
});
|
||||
} catch (err) {
|
||||
if (err.code === '23505') {
|
||||
throw new HttpException(
|
||||
'User already belongs to this room',
|
||||
HttpStatus.BAD_REQUEST,
|
||||
);
|
||||
}
|
||||
throw new HttpException(
|
||||
err.message || 'Internal Server Error',
|
||||
HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
}
|
||||
async renameRoomByUuid(
|
||||
roomUuid: string,
|
||||
updateRoomNameDto: UpdateRoomNameDto,
|
||||
|
@ -13,10 +13,11 @@ import {
|
||||
} from '@nestjs/common';
|
||||
import { ApiTags, ApiBearerAuth } from '@nestjs/swagger';
|
||||
import { JwtAuthGuard } from '../../../libs/common/src/guards/jwt.auth.guard';
|
||||
import { AddUnitDto } from '../dtos/add.unit.dto';
|
||||
import { AddUnitDto, AddUserUnitDto } from '../dtos/add.unit.dto';
|
||||
import { GetUnitChildDto } from '../dtos/get.unit.dto';
|
||||
import { UpdateUnitNameDto } from '../dtos/update.unit.dto';
|
||||
import { CheckFloorTypeGuard } from 'src/guards/floor.type.guard';
|
||||
import { CheckUserUnitGuard } from 'src/guards/user.unit.guard';
|
||||
|
||||
@ApiTags('Unit Module')
|
||||
@Controller({
|
||||
@ -87,6 +88,33 @@ export class UnitController {
|
||||
);
|
||||
}
|
||||
}
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard, CheckUserUnitGuard)
|
||||
@Post('user')
|
||||
async addUserUnit(@Body() addUserUnitDto: AddUserUnitDto) {
|
||||
try {
|
||||
await this.unitService.addUserUnit(addUserUnitDto);
|
||||
return { message: 'user unit added successfully' };
|
||||
} catch (error) {
|
||||
throw new HttpException(
|
||||
error.message || 'Internal server error',
|
||||
error.status || HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
}
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@Get('user/:userUuid')
|
||||
async getUnitsByUserId(@Param('userUuid') userUuid: string) {
|
||||
try {
|
||||
return await this.unitService.getUnitsByUserId(userUuid);
|
||||
} catch (error) {
|
||||
throw new HttpException(
|
||||
error.message || 'Internal server error',
|
||||
error.status || HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard)
|
||||
|
@ -21,3 +21,22 @@ export class AddUnitDto {
|
||||
Object.assign(this, dto);
|
||||
}
|
||||
}
|
||||
export class AddUserUnitDto {
|
||||
@ApiProperty({
|
||||
description: 'unitUuid',
|
||||
required: true,
|
||||
})
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
public unitUuid: string;
|
||||
@ApiProperty({
|
||||
description: 'userUuid',
|
||||
required: true,
|
||||
})
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
public userUuid: string;
|
||||
constructor(dto: Partial<AddUserUnitDto>) {
|
||||
Object.assign(this, dto);
|
||||
}
|
||||
}
|
||||
|
@ -49,3 +49,12 @@ export class GetUnitChildDto {
|
||||
})
|
||||
public includeSubSpaces: boolean = false;
|
||||
}
|
||||
export class GetUnitByUserIdDto {
|
||||
@ApiProperty({
|
||||
description: 'userUuid',
|
||||
required: true,
|
||||
})
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
public userUuid: string;
|
||||
}
|
||||
|
@ -24,3 +24,8 @@ export interface RenameUnitByUuidInterface {
|
||||
name: string;
|
||||
type: string;
|
||||
}
|
||||
export interface GetUnitByUserUuidInterface {
|
||||
uuid: string;
|
||||
name: string;
|
||||
type: string;
|
||||
}
|
||||
|
@ -7,21 +7,24 @@ import {
|
||||
BadRequestException,
|
||||
} from '@nestjs/common';
|
||||
import { SpaceRepository } from '@app/common/modules/space/repositories';
|
||||
import { AddUnitDto } from '../dtos';
|
||||
import { AddUnitDto, AddUserUnitDto } from '../dtos';
|
||||
import {
|
||||
UnitChildInterface,
|
||||
UnitParentInterface,
|
||||
GetUnitByUuidInterface,
|
||||
RenameUnitByUuidInterface,
|
||||
GetUnitByUserUuidInterface,
|
||||
} from '../interface/unit.interface';
|
||||
import { SpaceEntity } from '@app/common/modules/space/entities';
|
||||
import { UpdateUnitNameDto } from '../dtos/update.unit.dto';
|
||||
import { UserSpaceRepository } from '@app/common/modules/user-space/repositories';
|
||||
|
||||
@Injectable()
|
||||
export class UnitService {
|
||||
constructor(
|
||||
private readonly spaceRepository: SpaceRepository,
|
||||
private readonly spaceTypeRepository: SpaceTypeRepository,
|
||||
private readonly userSpaceRepository: UserSpaceRepository,
|
||||
) {}
|
||||
|
||||
async addUnit(addUnitDto: AddUnitDto) {
|
||||
@ -195,7 +198,56 @@ export class UnitService {
|
||||
}
|
||||
}
|
||||
}
|
||||
async getUnitsByUserId(
|
||||
userUuid: string,
|
||||
): Promise<GetUnitByUserUuidInterface[]> {
|
||||
try {
|
||||
const units = await this.userSpaceRepository.find({
|
||||
relations: ['space', 'space.spaceType'],
|
||||
where: {
|
||||
user: { uuid: userUuid },
|
||||
space: { spaceType: { type: 'unit' } },
|
||||
},
|
||||
});
|
||||
|
||||
if (units.length === 0) {
|
||||
throw new HttpException('this user has no units', HttpStatus.NOT_FOUND);
|
||||
}
|
||||
const spaces = units.map((unit) => ({
|
||||
uuid: unit.space.uuid,
|
||||
name: unit.space.spaceName,
|
||||
type: unit.space.spaceType.type,
|
||||
}));
|
||||
|
||||
return spaces;
|
||||
} catch (err) {
|
||||
if (err instanceof HttpException) {
|
||||
throw err;
|
||||
} else {
|
||||
throw new HttpException('user not found', HttpStatus.NOT_FOUND);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async addUserUnit(addUserUnitDto: AddUserUnitDto) {
|
||||
try {
|
||||
await this.userSpaceRepository.save({
|
||||
user: { uuid: addUserUnitDto.userUuid },
|
||||
space: { uuid: addUserUnitDto.unitUuid },
|
||||
});
|
||||
} catch (err) {
|
||||
if (err.code === '23505') {
|
||||
throw new HttpException(
|
||||
'User already belongs to this unit',
|
||||
HttpStatus.BAD_REQUEST,
|
||||
);
|
||||
}
|
||||
throw new HttpException(
|
||||
err.message || 'Internal Server Error',
|
||||
HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
}
|
||||
async renameUnitByUuid(
|
||||
unitUuid: string,
|
||||
updateUnitNameDto: UpdateUnitNameDto,
|
||||
|
@ -6,11 +6,27 @@ import { SpaceRepositoryModule } from '@app/common/modules/space/space.repositor
|
||||
import { SpaceRepository } from '@app/common/modules/space/repositories';
|
||||
import { SpaceTypeRepositoryModule } from '@app/common/modules/space-type/space.type.repository.module';
|
||||
import { SpaceTypeRepository } from '@app/common/modules/space-type/repositories';
|
||||
import { UserSpaceRepositoryModule } from '@app/common/modules/user-space/user.space.repository.module';
|
||||
import { UserSpaceRepository } from '@app/common/modules/user-space/repositories';
|
||||
import { UserRepositoryModule } from '@app/common/modules/user/user.repository.module';
|
||||
import { UserRepository } from '@app/common/modules/user/repositories';
|
||||
|
||||
@Module({
|
||||
imports: [ConfigModule, SpaceRepositoryModule, SpaceTypeRepositoryModule],
|
||||
imports: [
|
||||
ConfigModule,
|
||||
SpaceRepositoryModule,
|
||||
SpaceTypeRepositoryModule,
|
||||
UserSpaceRepositoryModule,
|
||||
UserRepositoryModule,
|
||||
],
|
||||
controllers: [UnitController],
|
||||
providers: [UnitService, SpaceRepository, SpaceTypeRepository],
|
||||
providers: [
|
||||
UnitService,
|
||||
SpaceRepository,
|
||||
SpaceTypeRepository,
|
||||
UserSpaceRepository,
|
||||
UserRepository,
|
||||
],
|
||||
exports: [UnitService],
|
||||
})
|
||||
export class UnitModule {}
|
||||
|
Reference in New Issue
Block a user