mirror of
https://github.com/SyncrowIOT/backend.git
synced 2026-10-25 11:37:55 +00:00
Merge branch 'dev' into SP-197-be-retrieve-devices-in-the-gateway
This commit is contained in:
@@ -14,6 +14,8 @@ import { FloorModule } from './floor/floor.module';
|
||||
import { UnitModule } from './unit/unit.module';
|
||||
import { RoleModule } from './role/role.module';
|
||||
import { SeederModule } from '@app/common/seed/seeder.module';
|
||||
import { UserNotificationModule } from './user-notification/user-notification.module';
|
||||
import { DeviceMessagesSubscriptionModule } from './device-messages/device-messages.module';
|
||||
@Module({
|
||||
imports: [
|
||||
ConfigModule.forRoot({
|
||||
@@ -30,7 +32,9 @@ import { SeederModule } from '@app/common/seed/seeder.module';
|
||||
RoomModule,
|
||||
GroupModule,
|
||||
DeviceModule,
|
||||
DeviceMessagesSubscriptionModule,
|
||||
UserDevicePermissionModule,
|
||||
UserNotificationModule,
|
||||
SeederModule,
|
||||
],
|
||||
controllers: [AuthenticationController],
|
||||
|
||||
@@ -30,7 +30,7 @@ export class BuildingController {
|
||||
constructor(private readonly buildingService: BuildingService) {}
|
||||
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(AdminRoleGuard, CheckCommunityTypeGuard)
|
||||
@UseGuards(JwtAuthGuard, CheckCommunityTypeGuard)
|
||||
@Post()
|
||||
async addBuilding(@Body() addBuildingDto: AddBuildingDto) {
|
||||
try {
|
||||
|
||||
@@ -32,7 +32,7 @@ export class CommunityController {
|
||||
constructor(private readonly communityService: CommunityService) {}
|
||||
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(AdminRoleGuard)
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@Post()
|
||||
async addCommunity(@Body() addCommunityDto: AddCommunityDto) {
|
||||
try {
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
import {
|
||||
Body,
|
||||
Controller,
|
||||
Delete,
|
||||
Get,
|
||||
HttpException,
|
||||
HttpStatus,
|
||||
Param,
|
||||
Post,
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import { ApiBearerAuth, ApiTags } from '@nestjs/swagger';
|
||||
import { DeviceMessagesSubscriptionService } from '../services/device-messages.service';
|
||||
import { DeviceMessagesAddDto } from '../dtos/device-messages.dto';
|
||||
|
||||
import { JwtAuthGuard } from '@app/common/guards/jwt.auth.guard';
|
||||
|
||||
@ApiTags('Device Messages Status Module')
|
||||
@Controller({
|
||||
version: '1',
|
||||
path: 'device-messages/subscription',
|
||||
})
|
||||
export class DeviceMessagesSubscriptionController {
|
||||
constructor(
|
||||
private readonly deviceMessagesSubscriptionService: DeviceMessagesSubscriptionService,
|
||||
) {}
|
||||
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@Post()
|
||||
async addDeviceMessagesSubscription(
|
||||
@Body() deviceMessagesAddDto: DeviceMessagesAddDto,
|
||||
) {
|
||||
try {
|
||||
const addDetails =
|
||||
await this.deviceMessagesSubscriptionService.addDeviceMessagesSubscription(
|
||||
deviceMessagesAddDto,
|
||||
);
|
||||
return {
|
||||
statusCode: HttpStatus.CREATED,
|
||||
message: 'Device Messages Subscription Added Successfully',
|
||||
data: addDetails,
|
||||
};
|
||||
} catch (error) {
|
||||
throw new HttpException(
|
||||
error.message || 'Internal server error',
|
||||
error.status || HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@Get(':deviceUuid/user/:userUuid')
|
||||
async getDeviceMessagesSubscription(
|
||||
@Param('deviceUuid') deviceUuid: string,
|
||||
@Param('userUuid') userUuid: string,
|
||||
) {
|
||||
try {
|
||||
const deviceDetails =
|
||||
await this.deviceMessagesSubscriptionService.getDeviceMessagesSubscription(
|
||||
userUuid,
|
||||
deviceUuid,
|
||||
);
|
||||
return {
|
||||
statusCode: HttpStatus.OK,
|
||||
message: 'User Device Subscription fetched Successfully',
|
||||
data: deviceDetails,
|
||||
};
|
||||
} catch (error) {
|
||||
throw new HttpException(
|
||||
error.message || 'Internal server error',
|
||||
error.status || HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
}
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@Delete()
|
||||
async deleteDeviceMessagesSubscription(
|
||||
@Body() deviceMessagesAddDto: DeviceMessagesAddDto,
|
||||
) {
|
||||
try {
|
||||
await this.deviceMessagesSubscriptionService.deleteDeviceMessagesSubscription(
|
||||
deviceMessagesAddDto,
|
||||
);
|
||||
return {
|
||||
statusCode: HttpStatus.OK,
|
||||
message: 'User subscription deleted Successfully',
|
||||
};
|
||||
} catch (error) {
|
||||
throw new HttpException(
|
||||
error.message || 'Internal server error',
|
||||
error.status || HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export * from './device-messages.controller';
|
||||
@@ -0,0 +1,14 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { ConfigModule } from '@nestjs/config';
|
||||
import { DeviceMessagesSubscriptionController } from './controllers';
|
||||
import { DeviceMessagesSubscriptionService } from './services';
|
||||
import { DeviceNotificationRepositoryModule } from '@app/common/modules/device-notification/device.notification.module';
|
||||
import { DeviceNotificationRepository } from '@app/common/modules/device-notification/repositories';
|
||||
|
||||
@Module({
|
||||
imports: [ConfigModule, DeviceNotificationRepositoryModule],
|
||||
controllers: [DeviceMessagesSubscriptionController],
|
||||
providers: [DeviceNotificationRepository, DeviceMessagesSubscriptionService],
|
||||
exports: [DeviceMessagesSubscriptionService],
|
||||
})
|
||||
export class DeviceMessagesSubscriptionModule {}
|
||||
+5
-11
@@ -1,26 +1,20 @@
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
import { IsNotEmpty, IsString } from 'class-validator';
|
||||
|
||||
export class ControlGroupDto {
|
||||
export class DeviceMessagesAddDto {
|
||||
@ApiProperty({
|
||||
description: 'groupUuid',
|
||||
description: 'user uuid',
|
||||
required: true,
|
||||
})
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
public groupUuid: string;
|
||||
userUuid: string;
|
||||
|
||||
@ApiProperty({
|
||||
description: 'code',
|
||||
description: 'device uuid',
|
||||
required: true,
|
||||
})
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
public code: string;
|
||||
@ApiProperty({
|
||||
description: 'value',
|
||||
required: true,
|
||||
})
|
||||
@IsNotEmpty()
|
||||
public value: any;
|
||||
deviceUuid: string;
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export * from './device-messages.dto';
|
||||
@@ -0,0 +1,75 @@
|
||||
import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
|
||||
import { DeviceMessagesAddDto } from '../dtos/device-messages.dto';
|
||||
import { DeviceNotificationRepository } from '@app/common/modules/device-notification/repositories';
|
||||
|
||||
@Injectable()
|
||||
export class DeviceMessagesSubscriptionService {
|
||||
constructor(
|
||||
private readonly deviceNotificationRepository: DeviceNotificationRepository,
|
||||
) {}
|
||||
|
||||
async addDeviceMessagesSubscription(
|
||||
deviceMessagesAddDto: DeviceMessagesAddDto,
|
||||
) {
|
||||
try {
|
||||
return await this.deviceNotificationRepository.save({
|
||||
user: {
|
||||
uuid: deviceMessagesAddDto.userUuid,
|
||||
},
|
||||
device: {
|
||||
uuid: deviceMessagesAddDto.deviceUuid,
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
if (error.code === '23505') {
|
||||
throw new HttpException(
|
||||
'This User already belongs to this device',
|
||||
HttpStatus.BAD_REQUEST,
|
||||
);
|
||||
}
|
||||
throw new HttpException(
|
||||
error.message || 'Internal Server Error',
|
||||
HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
}
|
||||
async getDeviceMessagesSubscription(userUuid: string, deviceUuid: string) {
|
||||
try {
|
||||
const deviceUserSubscription =
|
||||
await this.deviceNotificationRepository.findOne({
|
||||
where: {
|
||||
user: { uuid: userUuid },
|
||||
device: { uuid: deviceUuid },
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
uuid: deviceUserSubscription.uuid,
|
||||
deviceUuid: deviceUserSubscription.deviceUuid,
|
||||
userUuid: deviceUserSubscription.userUuid,
|
||||
};
|
||||
} catch (error) {
|
||||
throw new HttpException(
|
||||
'User device subscription not found',
|
||||
HttpStatus.NOT_FOUND,
|
||||
);
|
||||
}
|
||||
}
|
||||
async deleteDeviceMessagesSubscription(
|
||||
deviceMessagesAddDto: DeviceMessagesAddDto,
|
||||
) {
|
||||
try {
|
||||
const result = await this.deviceNotificationRepository.delete({
|
||||
user: { uuid: deviceMessagesAddDto.userUuid },
|
||||
device: { uuid: deviceMessagesAddDto.deviceUuid },
|
||||
});
|
||||
|
||||
return result;
|
||||
} catch (error) {
|
||||
throw new HttpException(
|
||||
error.message || 'device not found',
|
||||
HttpStatus.NOT_FOUND,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export * from './device-messages.service';
|
||||
@@ -10,22 +10,18 @@ import {
|
||||
HttpStatus,
|
||||
UseGuards,
|
||||
Req,
|
||||
Put,
|
||||
} from '@nestjs/common';
|
||||
import { ApiTags, ApiBearerAuth } from '@nestjs/swagger';
|
||||
import {
|
||||
AddDeviceInGroupDto,
|
||||
AddDeviceInRoomDto,
|
||||
} from '../dtos/add.device.dto';
|
||||
import {
|
||||
GetDeviceByGroupIdDto,
|
||||
GetDeviceByRoomUuidDto,
|
||||
} from '../dtos/get.device.dto';
|
||||
import { AddDeviceDto, UpdateDeviceInRoomDto } from '../dtos/add.device.dto';
|
||||
import { GetDeviceByRoomUuidDto } from '../dtos/get.device.dto';
|
||||
import { ControlDeviceDto } from '../dtos/control.device.dto';
|
||||
import { CheckRoomGuard } from 'src/guards/room.guard';
|
||||
import { CheckGroupGuard } from 'src/guards/group.guard';
|
||||
import { CheckUserHavePermission } from 'src/guards/user.device.permission.guard';
|
||||
import { CheckUserHaveControllablePermission } from 'src/guards/user.device.controllable.permission.guard';
|
||||
import { JwtAuthGuard } from '@app/common/guards/jwt.auth.guard';
|
||||
import { CheckDeviceGuard } from 'src/guards/device.guard';
|
||||
import { SuperAdminRoleGuard } from 'src/guards/super.admin.role.guard';
|
||||
|
||||
@ApiTags('Device Module')
|
||||
@Controller({
|
||||
@@ -34,7 +30,39 @@ import { JwtAuthGuard } from '@app/common/guards/jwt.auth.guard';
|
||||
})
|
||||
export class DeviceController {
|
||||
constructor(private readonly deviceService: DeviceService) {}
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(SuperAdminRoleGuard, CheckDeviceGuard)
|
||||
@Post()
|
||||
async addDeviceUser(@Body() addDeviceDto: AddDeviceDto) {
|
||||
try {
|
||||
const device = await this.deviceService.addDeviceUser(addDeviceDto);
|
||||
|
||||
return {
|
||||
statusCode: HttpStatus.CREATED,
|
||||
success: true,
|
||||
message: 'device added successfully',
|
||||
data: device,
|
||||
};
|
||||
} catch (error) {
|
||||
throw new HttpException(
|
||||
error.message || 'Internal server error',
|
||||
error.status || HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
}
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@Get('user/:userUuid')
|
||||
async getDevicesByUser(@Param('userUuid') userUuid: string) {
|
||||
try {
|
||||
return await this.deviceService.getDevicesByUser(userUuid);
|
||||
} catch (error) {
|
||||
throw new HttpException(
|
||||
error.message || 'Internal server error',
|
||||
error.status || HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
}
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard, CheckRoomGuard)
|
||||
@Get('room')
|
||||
@@ -58,16 +86,19 @@ export class DeviceController {
|
||||
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard, CheckRoomGuard)
|
||||
@Post('room')
|
||||
async addDeviceInRoom(@Body() addDeviceInRoomDto: AddDeviceInRoomDto) {
|
||||
@Put('room')
|
||||
async updateDeviceInRoom(
|
||||
@Body() updateDeviceInRoomDto: UpdateDeviceInRoomDto,
|
||||
) {
|
||||
try {
|
||||
const device =
|
||||
await this.deviceService.addDeviceInRoom(addDeviceInRoomDto);
|
||||
const device = await this.deviceService.updateDeviceInRoom(
|
||||
updateDeviceInRoomDto,
|
||||
);
|
||||
|
||||
return {
|
||||
statusCode: HttpStatus.CREATED,
|
||||
success: true,
|
||||
message: 'device added in room successfully',
|
||||
message: 'device updated in room successfully',
|
||||
data: device,
|
||||
};
|
||||
} catch (error) {
|
||||
@@ -77,39 +108,7 @@ export class DeviceController {
|
||||
);
|
||||
}
|
||||
}
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard, CheckGroupGuard)
|
||||
@Get('group')
|
||||
async getDevicesByGroupId(
|
||||
@Query() getDeviceByGroupIdDto: GetDeviceByGroupIdDto,
|
||||
@Req() req: any,
|
||||
) {
|
||||
try {
|
||||
const userUuid = req.user.uuid;
|
||||
return await this.deviceService.getDevicesByGroupId(
|
||||
getDeviceByGroupIdDto,
|
||||
userUuid,
|
||||
);
|
||||
} catch (error) {
|
||||
throw new HttpException(
|
||||
error.message || 'Internal server error',
|
||||
error.status || HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
}
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard, CheckGroupGuard)
|
||||
@Post('group')
|
||||
async addDeviceInGroup(@Body() addDeviceInGroupDto: AddDeviceInGroupDto) {
|
||||
try {
|
||||
return await this.deviceService.addDeviceInGroup(addDeviceInGroupDto);
|
||||
} catch (error) {
|
||||
throw new HttpException(
|
||||
error.message || 'Internal server error',
|
||||
error.status || HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard, CheckUserHavePermission)
|
||||
@Get(':deviceUuid')
|
||||
|
||||
@@ -8,18 +8,10 @@ import { DeviceRepositoryModule } from '@app/common/modules/device';
|
||||
import { DeviceRepository } from '@app/common/modules/device/repositories';
|
||||
import { PermissionTypeRepository } from '@app/common/modules/permission/repositories';
|
||||
import { SpaceRepository } from '@app/common/modules/space/repositories';
|
||||
import { GroupDeviceRepository } from '@app/common/modules/group-device/repositories';
|
||||
import { GroupRepository } from '@app/common/modules/group/repositories';
|
||||
import { GroupRepositoryModule } from '@app/common/modules/group/group.repository.module';
|
||||
import { DeviceUserPermissionRepository } from '@app/common/modules/device-user-permission/repositories';
|
||||
import { UserRepository } from '@app/common/modules/user/repositories';
|
||||
@Module({
|
||||
imports: [
|
||||
ConfigModule,
|
||||
ProductRepositoryModule,
|
||||
DeviceRepositoryModule,
|
||||
GroupRepositoryModule,
|
||||
],
|
||||
imports: [ConfigModule, ProductRepositoryModule, DeviceRepositoryModule],
|
||||
controllers: [DeviceController],
|
||||
providers: [
|
||||
DeviceService,
|
||||
@@ -28,8 +20,6 @@ import { UserRepository } from '@app/common/modules/user/repositories';
|
||||
PermissionTypeRepository,
|
||||
SpaceRepository,
|
||||
DeviceRepository,
|
||||
GroupDeviceRepository,
|
||||
GroupRepository,
|
||||
UserRepository,
|
||||
],
|
||||
exports: [DeviceService],
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
import { IsNotEmpty, IsString } from 'class-validator';
|
||||
|
||||
export class AddDeviceInRoomDto {
|
||||
export class AddDeviceDto {
|
||||
@ApiProperty({
|
||||
description: 'deviceTuyaUuid',
|
||||
required: true,
|
||||
@@ -11,14 +11,14 @@ export class AddDeviceInRoomDto {
|
||||
public deviceTuyaUuid: string;
|
||||
|
||||
@ApiProperty({
|
||||
description: 'roomUuid',
|
||||
description: 'userUuid',
|
||||
required: true,
|
||||
})
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
public roomUuid: string;
|
||||
public userUuid: string;
|
||||
}
|
||||
export class AddDeviceInGroupDto {
|
||||
export class UpdateDeviceInRoomDto {
|
||||
@ApiProperty({
|
||||
description: 'deviceUuid',
|
||||
required: true,
|
||||
@@ -28,10 +28,10 @@ export class AddDeviceInGroupDto {
|
||||
public deviceUuid: string;
|
||||
|
||||
@ApiProperty({
|
||||
description: 'groupUuid',
|
||||
description: 'roomUuid',
|
||||
required: true,
|
||||
})
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
public groupUuid: string;
|
||||
public roomUuid: string;
|
||||
}
|
||||
|
||||
@@ -10,12 +10,3 @@ export class GetDeviceByRoomUuidDto {
|
||||
@IsNotEmpty()
|
||||
public roomUuid: string;
|
||||
}
|
||||
export class GetDeviceByGroupIdDto {
|
||||
@ApiProperty({
|
||||
description: 'groupUuid',
|
||||
required: true,
|
||||
})
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
public groupUuid: string;
|
||||
}
|
||||
|
||||
@@ -8,10 +8,7 @@ import {
|
||||
} from '@nestjs/common';
|
||||
import { TuyaContext } from '@tuya/tuya-connector-nodejs';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import {
|
||||
AddDeviceInGroupDto,
|
||||
AddDeviceInRoomDto,
|
||||
} from '../dtos/add.device.dto';
|
||||
import { AddDeviceDto, UpdateDeviceInRoomDto } from '../dtos/add.device.dto';
|
||||
import {
|
||||
DeviceInstructionResponse,
|
||||
GetDeviceDetailsFunctionsInterface,
|
||||
@@ -20,14 +17,10 @@ import {
|
||||
controlDeviceInterface,
|
||||
updateDeviceFirmwareInterface,
|
||||
} from '../interfaces/get.device.interface';
|
||||
import {
|
||||
GetDeviceByGroupIdDto,
|
||||
GetDeviceByRoomUuidDto,
|
||||
} from '../dtos/get.device.dto';
|
||||
import { GetDeviceByRoomUuidDto } from '../dtos/get.device.dto';
|
||||
import { ControlDeviceDto } from '../dtos/control.device.dto';
|
||||
import { convertKeysToCamelCase } from '@app/common/helper/camelCaseConverter';
|
||||
import { DeviceRepository } from '@app/common/modules/device/repositories';
|
||||
import { GroupDeviceRepository } from '@app/common/modules/group-device/repositories';
|
||||
import { PermissionType } from '@app/common/constants/permission-type.enum';
|
||||
import { In } from 'typeorm';
|
||||
import { ProductType } from '@app/common/constants/product-type.enum';
|
||||
@@ -38,7 +31,6 @@ export class DeviceService {
|
||||
constructor(
|
||||
private readonly configService: ConfigService,
|
||||
private readonly deviceRepository: DeviceRepository,
|
||||
private readonly groupDeviceRepository: GroupDeviceRepository,
|
||||
private readonly productRepository: ProductRepository,
|
||||
) {
|
||||
const accessKey = this.configService.get<string>('auth-config.ACCESS_KEY');
|
||||
@@ -60,6 +52,82 @@ export class DeviceService {
|
||||
...(withProductDevice && { relations: ['productDevice'] }),
|
||||
});
|
||||
}
|
||||
async addDeviceUser(addDeviceDto: AddDeviceDto) {
|
||||
try {
|
||||
const device = await this.getDeviceDetailsByDeviceIdTuya(
|
||||
addDeviceDto.deviceTuyaUuid,
|
||||
);
|
||||
|
||||
if (!device.productUuid) {
|
||||
throw new Error('Product UUID is missing for the device.');
|
||||
}
|
||||
|
||||
return await this.deviceRepository.save({
|
||||
deviceTuyaUuid: addDeviceDto.deviceTuyaUuid,
|
||||
productDevice: { uuid: device.productUuid },
|
||||
user: {
|
||||
uuid: addDeviceDto.userUuid,
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
if (error.code === '23505') {
|
||||
throw new HttpException(
|
||||
'Device already exists',
|
||||
HttpStatus.BAD_REQUEST,
|
||||
);
|
||||
} else {
|
||||
throw new HttpException(
|
||||
error.message || 'Failed to add device in room',
|
||||
error.status || HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
async getDevicesByUser(
|
||||
userUuid: string,
|
||||
): Promise<GetDeviceDetailsInterface[]> {
|
||||
try {
|
||||
const devices = await this.deviceRepository.find({
|
||||
where: {
|
||||
user: { uuid: userUuid },
|
||||
permission: {
|
||||
userUuid,
|
||||
permissionType: {
|
||||
type: In([PermissionType.READ, PermissionType.CONTROLLABLE]),
|
||||
},
|
||||
},
|
||||
},
|
||||
relations: [
|
||||
'spaceDevice',
|
||||
'productDevice',
|
||||
'permission',
|
||||
'permission.permissionType',
|
||||
],
|
||||
});
|
||||
const devicesData = await Promise.all(
|
||||
devices.map(async (device) => {
|
||||
return {
|
||||
haveRoom: device.spaceDevice ? true : false,
|
||||
productUuid: device.productDevice.uuid,
|
||||
productType: device.productDevice.prodType,
|
||||
permissionType: device.permission[0].permissionType.type,
|
||||
...(await this.getDeviceDetailsByDeviceIdTuya(
|
||||
device.deviceTuyaUuid,
|
||||
)),
|
||||
uuid: device.uuid,
|
||||
} as GetDeviceDetailsInterface;
|
||||
}),
|
||||
);
|
||||
|
||||
return devicesData;
|
||||
} catch (error) {
|
||||
// Handle the error here
|
||||
throw new HttpException(
|
||||
'User does not have any devices',
|
||||
HttpStatus.NOT_FOUND,
|
||||
);
|
||||
}
|
||||
}
|
||||
async getDevicesByRoomId(
|
||||
getDeviceByRoomUuidDto: GetDeviceByRoomUuidDto,
|
||||
userUuid: string,
|
||||
@@ -85,13 +153,14 @@ export class DeviceService {
|
||||
const devicesData = await Promise.all(
|
||||
devices.map(async (device) => {
|
||||
return {
|
||||
haveRoom: device.spaceDevice ? true : false,
|
||||
productUuid: device.productDevice.uuid,
|
||||
productType: device.productDevice.prodType,
|
||||
permissionType: device.permission[0].permissionType.type,
|
||||
...(await this.getDeviceDetailsByDeviceIdTuya(
|
||||
device.deviceTuyaUuid,
|
||||
)),
|
||||
uuid: device.uuid,
|
||||
productUuid: device.productDevice.uuid,
|
||||
productType: device.productDevice.prodType,
|
||||
permissionType: device.permission[0].permissionType.type,
|
||||
} as GetDeviceDetailsInterface;
|
||||
}),
|
||||
);
|
||||
@@ -105,104 +174,31 @@ export class DeviceService {
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async getDevicesByGroupId(
|
||||
getDeviceByGroupIdDto: GetDeviceByGroupIdDto,
|
||||
userUuid: string,
|
||||
) {
|
||||
async updateDeviceInRoom(updateDeviceInRoomDto: UpdateDeviceInRoomDto) {
|
||||
try {
|
||||
const groupDevices = await this.groupDeviceRepository.find({
|
||||
where: {
|
||||
group: { uuid: getDeviceByGroupIdDto.groupUuid },
|
||||
device: {
|
||||
permission: {
|
||||
userUuid,
|
||||
permissionType: {
|
||||
type: PermissionType.READ || PermissionType.CONTROLLABLE,
|
||||
},
|
||||
},
|
||||
},
|
||||
await this.deviceRepository.update(
|
||||
{ uuid: updateDeviceInRoomDto.deviceUuid },
|
||||
{
|
||||
spaceDevice: { uuid: updateDeviceInRoomDto.roomUuid },
|
||||
},
|
||||
relations: [
|
||||
'device',
|
||||
'device.productDevice',
|
||||
'device.permission',
|
||||
'device.permission.permissionType',
|
||||
],
|
||||
});
|
||||
const devicesData = await Promise.all(
|
||||
groupDevices.map(async (device) => {
|
||||
return {
|
||||
...(await this.getDeviceDetailsByDeviceIdTuya(
|
||||
device.device.deviceTuyaUuid,
|
||||
)),
|
||||
uuid: device.device.uuid,
|
||||
productUuid: device.device.productDevice.uuid,
|
||||
productType: device.device.productDevice.prodType,
|
||||
permissionType: device.device.permission[0].permissionType.type,
|
||||
} as GetDeviceDetailsInterface;
|
||||
}),
|
||||
);
|
||||
|
||||
return devicesData;
|
||||
const device = await this.deviceRepository.findOne({
|
||||
where: {
|
||||
uuid: updateDeviceInRoomDto.deviceUuid,
|
||||
},
|
||||
relations: ['spaceDevice'],
|
||||
});
|
||||
return {
|
||||
uuid: device.uuid,
|
||||
roomUuid: device.spaceDevice.uuid,
|
||||
};
|
||||
} catch (error) {
|
||||
throw new HttpException(
|
||||
'Error fetching devices by group',
|
||||
'Failed to add device in room',
|
||||
HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
}
|
||||
async addDeviceInRoom(addDeviceInRoomDto: AddDeviceInRoomDto) {
|
||||
try {
|
||||
const device = await this.getDeviceDetailsByDeviceIdTuya(
|
||||
addDeviceInRoomDto.deviceTuyaUuid,
|
||||
);
|
||||
|
||||
if (!device.productUuid) {
|
||||
throw new Error('Product UUID is missing for the device.');
|
||||
}
|
||||
|
||||
return await this.deviceRepository.save({
|
||||
deviceTuyaUuid: addDeviceInRoomDto.deviceTuyaUuid,
|
||||
spaceDevice: { uuid: addDeviceInRoomDto.roomUuid },
|
||||
productDevice: { uuid: device.productUuid },
|
||||
});
|
||||
} catch (error) {
|
||||
if (error.code === '23505') {
|
||||
throw new HttpException(
|
||||
'Device already exists in the room',
|
||||
HttpStatus.BAD_REQUEST,
|
||||
);
|
||||
} else {
|
||||
throw new HttpException(
|
||||
'Failed to add device in room',
|
||||
HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async addDeviceInGroup(addDeviceInGroupDto: AddDeviceInGroupDto) {
|
||||
try {
|
||||
await this.groupDeviceRepository.save({
|
||||
device: { uuid: addDeviceInGroupDto.deviceUuid },
|
||||
group: { uuid: addDeviceInGroupDto.groupUuid },
|
||||
});
|
||||
return { message: 'device added in group successfully' };
|
||||
} catch (error) {
|
||||
if (error.code === '23505') {
|
||||
throw new HttpException(
|
||||
'Device already exists in the group',
|
||||
HttpStatus.BAD_REQUEST,
|
||||
);
|
||||
} else {
|
||||
throw new HttpException(
|
||||
'Failed to add device in group',
|
||||
HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async controlDevice(controlDeviceDto: ControlDeviceDto, deviceUuid: string) {
|
||||
try {
|
||||
|
||||
@@ -30,7 +30,7 @@ export class FloorController {
|
||||
constructor(private readonly floorService: FloorService) {}
|
||||
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(AdminRoleGuard, CheckBuildingTypeGuard)
|
||||
@UseGuards(JwtAuthGuard, CheckBuildingTypeGuard)
|
||||
@Post()
|
||||
async addFloor(@Body() addFloorDto: AddFloorDto) {
|
||||
try {
|
||||
|
||||
@@ -1,22 +1,16 @@
|
||||
import { GroupService } from '../services/group.service';
|
||||
import {
|
||||
Body,
|
||||
Controller,
|
||||
Get,
|
||||
Post,
|
||||
UseGuards,
|
||||
Param,
|
||||
Put,
|
||||
Delete,
|
||||
HttpException,
|
||||
HttpStatus,
|
||||
Req,
|
||||
} from '@nestjs/common';
|
||||
import { ApiTags, ApiBearerAuth } from '@nestjs/swagger';
|
||||
import { AddGroupDto } from '../dtos/add.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';
|
||||
import { JwtAuthGuard } from '@app/common/guards/jwt.auth.guard';
|
||||
import { UnitPermissionGuard } from 'src/guards/unit.permission.guard';
|
||||
|
||||
@ApiTags('Group Module')
|
||||
@Controller({
|
||||
@@ -27,11 +21,11 @@ export class GroupController {
|
||||
constructor(private readonly groupService: GroupService) {}
|
||||
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@Get('space/:spaceUuid')
|
||||
async getGroupsBySpaceUuid(@Param('spaceUuid') spaceUuid: string) {
|
||||
@UseGuards(JwtAuthGuard, UnitPermissionGuard)
|
||||
@Get(':unitUuid')
|
||||
async getGroupsBySpaceUuid(@Param('unitUuid') unitUuid: string) {
|
||||
try {
|
||||
return await this.groupService.getGroupsBySpaceUuid(spaceUuid);
|
||||
return await this.groupService.getGroupsByUnitUuid(unitUuid);
|
||||
} catch (error) {
|
||||
throw new HttpException(
|
||||
error.message || 'Internal server error',
|
||||
@@ -40,72 +34,21 @@ export class GroupController {
|
||||
}
|
||||
}
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@Get(':groupUuid')
|
||||
async getGroupsByGroupId(@Param('groupUuid') groupUuid: string) {
|
||||
try {
|
||||
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, CheckProductUuidForAllDevicesGuard)
|
||||
@Post()
|
||||
async addGroup(@Body() addGroupDto: AddGroupDto) {
|
||||
try {
|
||||
return await this.groupService.addGroup(addGroupDto);
|
||||
} catch (error) {
|
||||
throw new HttpException(
|
||||
error.message || 'Internal server error',
|
||||
error.status || HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@Post('control')
|
||||
async controlGroup(@Body() controlGroupDto: ControlGroupDto) {
|
||||
try {
|
||||
return await this.groupService.controlGroup(controlGroupDto);
|
||||
} catch (error) {
|
||||
throw new HttpException(
|
||||
error.message || 'Internal server error',
|
||||
error.status || HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@Put('rename/:groupUuid')
|
||||
async renameGroupByUuid(
|
||||
@Param('groupUuid') groupUuid: string,
|
||||
@Body() renameGroupDto: RenameGroupDto,
|
||||
@UseGuards(JwtAuthGuard, UnitPermissionGuard)
|
||||
@Get(':unitUuid/devices/:groupName')
|
||||
async getUnitDevicesByGroupName(
|
||||
@Param('unitUuid') unitUuid: string,
|
||||
@Param('groupName') groupName: string,
|
||||
@Req() req: any,
|
||||
) {
|
||||
try {
|
||||
return await this.groupService.renameGroupByUuid(
|
||||
groupUuid,
|
||||
renameGroupDto,
|
||||
);
|
||||
} catch (error) {
|
||||
throw new HttpException(
|
||||
error.message || 'Internal server error',
|
||||
error.status || HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
}
|
||||
const userUuid = req.user.uuid;
|
||||
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@Delete(':groupUuid')
|
||||
async deleteGroup(@Param('groupUuid') groupUuid: string) {
|
||||
try {
|
||||
return await this.groupService.deleteGroup(groupUuid);
|
||||
return await this.groupService.getUnitDevicesByGroupName(
|
||||
unitUuid,
|
||||
groupName,
|
||||
userUuid,
|
||||
);
|
||||
} catch (error) {
|
||||
throw new HttpException(
|
||||
error.message || 'Internal server error',
|
||||
|
||||
@@ -1,20 +0,0 @@
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
import { IsNotEmpty, IsString, IsArray } from 'class-validator';
|
||||
|
||||
export class AddGroupDto {
|
||||
@ApiProperty({
|
||||
description: 'groupName',
|
||||
required: true,
|
||||
})
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
public groupName: string;
|
||||
|
||||
@ApiProperty({
|
||||
description: 'deviceUuids',
|
||||
required: true,
|
||||
})
|
||||
@IsArray()
|
||||
@IsNotEmpty()
|
||||
public deviceUuids: [string];
|
||||
}
|
||||
@@ -1 +0,0 @@
|
||||
export * from './add.group.dto';
|
||||
@@ -1,12 +0,0 @@
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
import { IsNotEmpty, IsString } from 'class-validator';
|
||||
|
||||
export class RenameGroupDto {
|
||||
@ApiProperty({
|
||||
description: 'groupName',
|
||||
required: true,
|
||||
})
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
public groupName: string;
|
||||
}
|
||||
@@ -1,26 +1,20 @@
|
||||
import { DeviceRepository } from './../../libs/common/src/modules/device/repositories/device.repository';
|
||||
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';
|
||||
import { SpaceRepository } from '@app/common/modules/space/repositories';
|
||||
import { ProductRepository } from '@app/common/modules/product/repositories';
|
||||
@Module({
|
||||
imports: [
|
||||
ConfigModule,
|
||||
GroupRepositoryModule,
|
||||
GroupDeviceRepositoryModule,
|
||||
DeviceRepositoryModule,
|
||||
],
|
||||
imports: [ConfigModule, DeviceRepositoryModule],
|
||||
controllers: [GroupController],
|
||||
providers: [
|
||||
GroupService,
|
||||
GroupRepository,
|
||||
GroupDeviceRepository,
|
||||
DeviceRepository,
|
||||
SpaceRepository,
|
||||
DeviceRepository,
|
||||
ProductRepository,
|
||||
],
|
||||
exports: [GroupService],
|
||||
})
|
||||
|
||||
@@ -1,16 +0,0 @@
|
||||
export interface GetGroupDetailsInterface {
|
||||
groupUuid: string;
|
||||
groupName: string;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
}
|
||||
export interface GetGroupsBySpaceUuidInterface {
|
||||
groupUuid: string;
|
||||
groupName: string;
|
||||
}
|
||||
|
||||
export interface controlGroupInterface {
|
||||
success: boolean;
|
||||
result: boolean;
|
||||
msg: string;
|
||||
}
|
||||
+106
-220
@@ -1,33 +1,23 @@
|
||||
import {
|
||||
Injectable,
|
||||
HttpException,
|
||||
HttpStatus,
|
||||
BadRequestException,
|
||||
} from '@nestjs/common';
|
||||
import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
|
||||
import { TuyaContext } from '@tuya/tuya-connector-nodejs';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { AddGroupDto } from '../dtos/add.group.dto';
|
||||
import {
|
||||
GetGroupDetailsInterface,
|
||||
GetGroupsBySpaceUuidInterface,
|
||||
} from '../interfaces/get.group.interface';
|
||||
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 { SpaceRepository } from '@app/common/modules/space/repositories';
|
||||
import { GetDeviceDetailsInterface } from 'src/device/interfaces/get.device.interface';
|
||||
import { convertKeysToCamelCase } from '@app/common/helper/camelCaseConverter';
|
||||
import { ProductRepository } from '@app/common/modules/product/repositories';
|
||||
import { PermissionType } from '@app/common/constants/permission-type.enum';
|
||||
import { In } from 'typeorm';
|
||||
|
||||
@Injectable()
|
||||
export class GroupService {
|
||||
private tuya: TuyaContext;
|
||||
constructor(
|
||||
private readonly configService: ConfigService,
|
||||
private readonly groupRepository: GroupRepository,
|
||||
private readonly groupDeviceRepository: GroupDeviceRepository,
|
||||
private readonly productRepository: ProductRepository,
|
||||
private readonly spaceRepository: SpaceRepository,
|
||||
) {
|
||||
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');
|
||||
this.tuya = new TuyaContext({
|
||||
baseUrl: 'https://openapi.tuyaeu.com',
|
||||
accessKey,
|
||||
@@ -35,230 +25,126 @@ export class GroupService {
|
||||
});
|
||||
}
|
||||
|
||||
async getGroupsBySpaceUuid(
|
||||
spaceUuid: string,
|
||||
): Promise<GetGroupsBySpaceUuidInterface[]> {
|
||||
async getGroupsByUnitUuid(unitUuid: string) {
|
||||
try {
|
||||
const groupDevices = await this.groupDeviceRepository.find({
|
||||
relations: ['group', 'device'],
|
||||
const spaces = await this.spaceRepository.find({
|
||||
where: {
|
||||
device: { spaceDevice: { uuid: spaceUuid } },
|
||||
isActive: true,
|
||||
},
|
||||
});
|
||||
|
||||
// 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.message || 'Error fetching groups',
|
||||
error.status || HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async addGroup(addGroupDto: AddGroupDto) {
|
||||
try {
|
||||
const group = await this.groupRepository.save({
|
||||
groupName: addGroupDto.groupName,
|
||||
});
|
||||
|
||||
const groupDevicePromises = addGroupDto.deviceUuids.map(
|
||||
async (deviceUuid) => {
|
||||
await this.saveGroupDevice(group.uuid, deviceUuid);
|
||||
},
|
||||
);
|
||||
|
||||
await Promise.all(groupDevicePromises);
|
||||
return { message: 'Group added successfully' };
|
||||
} catch (err) {
|
||||
if (err.code === '23505') {
|
||||
throw new HttpException(
|
||||
'User already belongs to this group',
|
||||
HttpStatus.BAD_REQUEST,
|
||||
);
|
||||
}
|
||||
throw new HttpException(
|
||||
err.message || 'Internal Server Error',
|
||||
HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
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,
|
||||
parent: {
|
||||
uuid: unitUuid,
|
||||
},
|
||||
isActive: true,
|
||||
},
|
||||
relations: ['devicesSpaceEntity', 'devicesSpaceEntity.productDevice'],
|
||||
});
|
||||
return devices;
|
||||
} catch (error) {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
async controlDevice(deviceUuid: string, code: string, value: any) {
|
||||
try {
|
||||
const response = await this.controlDeviceTuya(deviceUuid, code, value);
|
||||
|
||||
if (response.success) {
|
||||
return response;
|
||||
} else {
|
||||
throw new HttpException(
|
||||
response.msg || 'Unknown error',
|
||||
HttpStatus.BAD_REQUEST,
|
||||
const groupNames = spaces.flatMap((space) => {
|
||||
return space.devicesSpaceEntity.map(
|
||||
(device) => device.productDevice.prodType,
|
||||
);
|
||||
}
|
||||
} catch (error) {
|
||||
throw new HttpException('Device Not Found', HttpStatus.NOT_FOUND);
|
||||
}
|
||||
}
|
||||
async controlDeviceTuya(
|
||||
deviceUuid: string,
|
||||
code: string,
|
||||
value: any,
|
||||
): Promise<controlDeviceInterface> {
|
||||
try {
|
||||
const path = `/v1.0/iot-03/devices/${deviceUuid}/commands`;
|
||||
const response = await this.tuya.request({
|
||||
method: 'POST',
|
||||
path,
|
||||
body: {
|
||||
commands: [{ code, value: value }],
|
||||
},
|
||||
});
|
||||
|
||||
return response as controlDeviceInterface;
|
||||
const uniqueGroupNames = [...new Set(groupNames)];
|
||||
|
||||
return uniqueGroupNames.map((groupName) => ({ groupName }));
|
||||
} catch (error) {
|
||||
throw new HttpException(
|
||||
'Error control device from Tuya',
|
||||
HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
'This unit does not have any groups',
|
||||
HttpStatus.NOT_FOUND,
|
||||
);
|
||||
}
|
||||
}
|
||||
async controlGroup(controlGroupDto: ControlGroupDto) {
|
||||
const devices = await this.getDevicesByGroupUuid(controlGroupDto.groupUuid);
|
||||
|
||||
async getUnitDevicesByGroupName(
|
||||
unitUuid: string,
|
||||
groupName: string,
|
||||
userUuid: string,
|
||||
) {
|
||||
try {
|
||||
await Promise.all(
|
||||
devices.map(async (device) => {
|
||||
return this.controlDevice(
|
||||
device.device.deviceTuyaUuid,
|
||||
controlGroupDto.code,
|
||||
controlGroupDto.value,
|
||||
const spaces = await this.spaceRepository.find({
|
||||
where: {
|
||||
parent: {
|
||||
uuid: unitUuid,
|
||||
},
|
||||
devicesSpaceEntity: {
|
||||
productDevice: {
|
||||
prodType: groupName,
|
||||
},
|
||||
permission: {
|
||||
userUuid,
|
||||
permissionType: {
|
||||
type: In([PermissionType.READ, PermissionType.CONTROLLABLE]),
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
relations: [
|
||||
'devicesSpaceEntity',
|
||||
'devicesSpaceEntity.productDevice',
|
||||
'devicesSpaceEntity.spaceDevice',
|
||||
'devicesSpaceEntity.permission',
|
||||
'devicesSpaceEntity.permission.permissionType',
|
||||
],
|
||||
});
|
||||
|
||||
const devices = await Promise.all(
|
||||
spaces.flatMap(async (space) => {
|
||||
return await Promise.all(
|
||||
space.devicesSpaceEntity.map(async (device) => {
|
||||
const deviceDetails = await this.getDeviceDetailsByDeviceIdTuya(
|
||||
device.deviceTuyaUuid,
|
||||
);
|
||||
return {
|
||||
haveRoom: !!device.spaceDevice,
|
||||
productUuid: device.productDevice.uuid,
|
||||
productType: device.productDevice.prodType,
|
||||
permissionType: device.permission[0]?.permissionType?.type,
|
||||
...deviceDetails,
|
||||
uuid: device.uuid,
|
||||
};
|
||||
}),
|
||||
);
|
||||
}),
|
||||
);
|
||||
return { message: 'Group controlled successfully', success: true };
|
||||
if (devices.length === 0)
|
||||
throw new HttpException('No devices found', HttpStatus.NOT_FOUND);
|
||||
return devices.flat(); // Flatten the array since flatMap was used
|
||||
} catch (error) {
|
||||
throw new HttpException(
|
||||
'Error controlling devices',
|
||||
'This unit does not have any devices for the specified group name',
|
||||
HttpStatus.NOT_FOUND,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async getDeviceDetailsByDeviceIdTuya(
|
||||
deviceId: string,
|
||||
): Promise<GetDeviceDetailsInterface> {
|
||||
try {
|
||||
const path = `/v1.1/iot-03/devices/${deviceId}`;
|
||||
const response = await this.tuya.request({
|
||||
method: 'GET',
|
||||
path,
|
||||
});
|
||||
|
||||
// Convert keys to camel case
|
||||
const camelCaseResponse = convertKeysToCamelCase(response);
|
||||
const product = await this.productRepository.findOne({
|
||||
where: {
|
||||
prodId: camelCaseResponse.result.productId,
|
||||
},
|
||||
});
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
const { productName, productId, ...rest } = camelCaseResponse.result;
|
||||
|
||||
return {
|
||||
...rest,
|
||||
productUuid: product.uuid,
|
||||
} as GetDeviceDetailsInterface;
|
||||
} catch (error) {
|
||||
throw new HttpException(
|
||||
'Error fetching device details from Tuya',
|
||||
HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async renameGroupByUuid(
|
||||
groupUuid: string,
|
||||
renameGroupDto: RenameGroupDto,
|
||||
): Promise<GetGroupsBySpaceUuidInterface> {
|
||||
try {
|
||||
await this.groupRepository.update(
|
||||
{ uuid: groupUuid },
|
||||
{ groupName: renameGroupDto.groupName },
|
||||
);
|
||||
|
||||
// Fetch the updated floor
|
||||
const updatedGroup = await this.groupRepository.findOneOrFail({
|
||||
where: { uuid: groupUuid },
|
||||
});
|
||||
return {
|
||||
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.message || 'Error deleting group',
|
||||
error.status || HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async getGroupsByGroupUuid(
|
||||
groupUuid: string,
|
||||
): Promise<GetGroupDetailsInterface> {
|
||||
try {
|
||||
const group = await this.groupRepository.findOne({
|
||||
where: {
|
||||
uuid: groupUuid,
|
||||
isActive: true,
|
||||
},
|
||||
});
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
import {
|
||||
CanActivate,
|
||||
ExecutionContext,
|
||||
Injectable,
|
||||
HttpStatus,
|
||||
} from '@nestjs/common';
|
||||
import { TuyaContext } from '@tuya/tuya-connector-nodejs';
|
||||
|
||||
import { BadRequestException, NotFoundException } from '@nestjs/common';
|
||||
import { DeviceRepository } from '@app/common/modules/device/repositories';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { UserRepository } from '@app/common/modules/user/repositories';
|
||||
|
||||
@Injectable()
|
||||
export class CheckDeviceGuard implements CanActivate {
|
||||
private tuya: TuyaContext;
|
||||
constructor(
|
||||
private readonly configService: ConfigService,
|
||||
private readonly userRepository: UserRepository,
|
||||
private readonly deviceRepository: DeviceRepository,
|
||||
) {
|
||||
const accessKey = this.configService.get<string>('auth-config.ACCESS_KEY');
|
||||
const secretKey = this.configService.get<string>('auth-config.SECRET_KEY');
|
||||
this.tuya = new TuyaContext({
|
||||
baseUrl: 'https://openapi.tuyaeu.com',
|
||||
accessKey,
|
||||
secretKey,
|
||||
});
|
||||
}
|
||||
|
||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
const req = context.switchToHttp().getRequest();
|
||||
|
||||
try {
|
||||
if (req.body && req.body.userUuid && req.body.deviceTuyaUuid) {
|
||||
const { userUuid, deviceTuyaUuid } = req.body;
|
||||
await this.checkUserIsFound(userUuid);
|
||||
await this.checkDeviceIsFoundFromTuya(deviceTuyaUuid);
|
||||
} else {
|
||||
throw new BadRequestException('Invalid request parameters');
|
||||
}
|
||||
|
||||
return true;
|
||||
} catch (error) {
|
||||
this.handleGuardError(error, context);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private async checkUserIsFound(userUuid: string) {
|
||||
const user = await this.userRepository.findOne({
|
||||
where: {
|
||||
uuid: userUuid,
|
||||
},
|
||||
});
|
||||
if (!user) {
|
||||
throw new NotFoundException('User not found');
|
||||
}
|
||||
}
|
||||
async checkDeviceIsFoundFromTuya(deviceTuyaUuid: string) {
|
||||
const path = `/v1.1/iot-03/devices/${deviceTuyaUuid}`;
|
||||
const response = await this.tuya.request({
|
||||
method: 'GET',
|
||||
path,
|
||||
});
|
||||
|
||||
if (!response.success) {
|
||||
throw new NotFoundException('Device not found from Tuya');
|
||||
}
|
||||
}
|
||||
|
||||
private handleGuardError(error: Error, context: ExecutionContext) {
|
||||
const response = context.switchToHttp().getResponse();
|
||||
if (error instanceof NotFoundException) {
|
||||
response
|
||||
.status(HttpStatus.NOT_FOUND)
|
||||
.json({ statusCode: HttpStatus.NOT_FOUND, message: error.message });
|
||||
} else if (error instanceof BadRequestException) {
|
||||
response
|
||||
.status(HttpStatus.BAD_REQUEST)
|
||||
.json({ statusCode: HttpStatus.BAD_REQUEST, message: error.message });
|
||||
} else {
|
||||
response.status(HttpStatus.BAD_REQUEST).json({
|
||||
statusCode: HttpStatus.BAD_REQUEST,
|
||||
message: error.message || 'Invalid UUID',
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,81 +0,0 @@
|
||||
import {
|
||||
CanActivate,
|
||||
ExecutionContext,
|
||||
Injectable,
|
||||
HttpStatus,
|
||||
} from '@nestjs/common';
|
||||
|
||||
import { BadRequestException, NotFoundException } from '@nestjs/common';
|
||||
import { DeviceRepository } from '@app/common/modules/device/repositories';
|
||||
import { GroupRepository } from '@app/common/modules/group/repositories';
|
||||
|
||||
@Injectable()
|
||||
export class CheckGroupGuard implements CanActivate {
|
||||
constructor(
|
||||
private readonly groupRepository: GroupRepository,
|
||||
private readonly deviceRepository: DeviceRepository,
|
||||
) {}
|
||||
|
||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
const req = context.switchToHttp().getRequest();
|
||||
|
||||
try {
|
||||
if (req.query && req.query.groupUuid) {
|
||||
const { groupUuid } = req.query;
|
||||
await this.checkGroupIsFound(groupUuid);
|
||||
} else if (req.body && req.body.groupUuid && req.body.deviceUuid) {
|
||||
const { groupUuid, deviceUuid } = req.body;
|
||||
await this.checkGroupIsFound(groupUuid);
|
||||
await this.checkDeviceIsFound(deviceUuid);
|
||||
} else {
|
||||
throw new BadRequestException('Invalid request parameters');
|
||||
}
|
||||
|
||||
return true;
|
||||
} catch (error) {
|
||||
this.handleGuardError(error, context);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private async checkGroupIsFound(groupUuid: string) {
|
||||
const group = await this.groupRepository.findOne({
|
||||
where: {
|
||||
uuid: groupUuid,
|
||||
},
|
||||
});
|
||||
|
||||
if (!group) {
|
||||
throw new NotFoundException('Group not found');
|
||||
}
|
||||
}
|
||||
async checkDeviceIsFound(deviceUuid: string) {
|
||||
const device = await this.deviceRepository.findOne({
|
||||
where: {
|
||||
uuid: deviceUuid,
|
||||
},
|
||||
});
|
||||
|
||||
if (!device) {
|
||||
throw new NotFoundException('Device not found');
|
||||
}
|
||||
}
|
||||
|
||||
private handleGuardError(error: Error, context: ExecutionContext) {
|
||||
const response = context.switchToHttp().getResponse();
|
||||
if (error instanceof NotFoundException) {
|
||||
response
|
||||
.status(HttpStatus.NOT_FOUND)
|
||||
.json({ statusCode: HttpStatus.NOT_FOUND, message: error.message });
|
||||
} else if (error instanceof BadRequestException) {
|
||||
response
|
||||
.status(HttpStatus.BAD_REQUEST)
|
||||
.json({ statusCode: HttpStatus.BAD_REQUEST, message: error.message });
|
||||
} else {
|
||||
response.status(HttpStatus.BAD_REQUEST).json({
|
||||
statusCode: HttpStatus.BAD_REQUEST,
|
||||
message: 'Invalid UUID',
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
+11
-23
@@ -4,29 +4,17 @@ import {
|
||||
Injectable,
|
||||
HttpStatus,
|
||||
} from '@nestjs/common';
|
||||
import { TuyaContext } from '@tuya/tuya-connector-nodejs';
|
||||
|
||||
import { SpaceRepository } from '@app/common/modules/space/repositories';
|
||||
import { BadRequestException, NotFoundException } from '@nestjs/common';
|
||||
import { DeviceRepository } from '@app/common/modules/device/repositories';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
|
||||
@Injectable()
|
||||
export class CheckRoomGuard implements CanActivate {
|
||||
private tuya: TuyaContext;
|
||||
constructor(
|
||||
private readonly configService: ConfigService,
|
||||
private readonly spaceRepository: SpaceRepository,
|
||||
private readonly deviceRepository: DeviceRepository,
|
||||
) {
|
||||
const accessKey = this.configService.get<string>('auth-config.ACCESS_KEY');
|
||||
const secretKey = this.configService.get<string>('auth-config.SECRET_KEY');
|
||||
this.tuya = new TuyaContext({
|
||||
baseUrl: 'https://openapi.tuyaeu.com',
|
||||
accessKey,
|
||||
secretKey,
|
||||
});
|
||||
}
|
||||
) {}
|
||||
|
||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
const req = context.switchToHttp().getRequest();
|
||||
@@ -35,10 +23,10 @@ export class CheckRoomGuard implements CanActivate {
|
||||
if (req.query && req.query.roomUuid) {
|
||||
const { roomUuid } = req.query;
|
||||
await this.checkRoomIsFound(roomUuid);
|
||||
} else if (req.body && req.body.roomUuid && req.body.deviceTuyaUuid) {
|
||||
const { roomUuid, deviceTuyaUuid } = req.body;
|
||||
} else if (req.body && req.body.roomUuid && req.body.deviceUuid) {
|
||||
const { roomUuid, deviceUuid } = req.body;
|
||||
await this.checkRoomIsFound(roomUuid);
|
||||
await this.checkDeviceIsFoundFromTuya(deviceTuyaUuid);
|
||||
await this.checkDeviceIsFound(deviceUuid);
|
||||
} else {
|
||||
throw new BadRequestException('Invalid request parameters');
|
||||
}
|
||||
@@ -63,14 +51,14 @@ export class CheckRoomGuard implements CanActivate {
|
||||
throw new NotFoundException('Room not found');
|
||||
}
|
||||
}
|
||||
async checkDeviceIsFoundFromTuya(deviceTuyaUuid: string) {
|
||||
const path = `/v1.1/iot-03/devices/${deviceTuyaUuid}`;
|
||||
const response = await this.tuya.request({
|
||||
method: 'GET',
|
||||
path,
|
||||
async checkDeviceIsFound(deviceUuid: string) {
|
||||
const response = await this.deviceRepository.findOne({
|
||||
where: {
|
||||
uuid: deviceUuid,
|
||||
},
|
||||
});
|
||||
|
||||
if (!response.success) {
|
||||
if (!response.uuid) {
|
||||
throw new NotFoundException('Device not found');
|
||||
}
|
||||
}
|
||||
@@ -88,7 +76,7 @@ export class CheckRoomGuard implements CanActivate {
|
||||
} else {
|
||||
response.status(HttpStatus.BAD_REQUEST).json({
|
||||
statusCode: HttpStatus.BAD_REQUEST,
|
||||
message: 'Invalid UUID',
|
||||
message: error.message || 'Invalid UUID',
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -28,7 +28,7 @@ export class RoomController {
|
||||
constructor(private readonly roomService: RoomService) {}
|
||||
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(AdminRoleGuard, CheckUnitTypeGuard)
|
||||
@UseGuards(JwtAuthGuard, CheckUnitTypeGuard)
|
||||
@Post()
|
||||
async addRoom(@Body() addRoomDto: AddRoomDto) {
|
||||
try {
|
||||
|
||||
@@ -12,12 +12,15 @@ import {
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import { ApiTags, ApiBearerAuth } from '@nestjs/swagger';
|
||||
import { AddUnitDto, AddUserUnitDto } from '../dtos/add.unit.dto';
|
||||
import {
|
||||
AddUnitDto,
|
||||
AddUserUnitDto,
|
||||
AddUserUnitUsingCodeDto,
|
||||
} 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';
|
||||
import { AdminRoleGuard } from 'src/guards/admin.role.guard';
|
||||
import { JwtAuthGuard } from '@app/common/guards/jwt.auth.guard';
|
||||
import { UnitPermissionGuard } from 'src/guards/unit.permission.guard';
|
||||
|
||||
@@ -30,7 +33,7 @@ export class UnitController {
|
||||
constructor(private readonly unitService: UnitService) {}
|
||||
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(AdminRoleGuard, CheckFloorTypeGuard)
|
||||
@UseGuards(JwtAuthGuard, CheckFloorTypeGuard)
|
||||
@Post()
|
||||
async addUnit(@Body() addUnitDto: AddUnitDto) {
|
||||
try {
|
||||
@@ -96,7 +99,7 @@ export class UnitController {
|
||||
}
|
||||
}
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(AdminRoleGuard, CheckUserUnitGuard)
|
||||
@UseGuards(JwtAuthGuard, CheckUserUnitGuard)
|
||||
@Post('user')
|
||||
async addUserUnit(@Body() addUserUnitDto: AddUserUnitDto) {
|
||||
try {
|
||||
@@ -147,4 +150,39 @@ export class UnitController {
|
||||
);
|
||||
}
|
||||
}
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard, UnitPermissionGuard)
|
||||
@Get(':unitUuid/invitation-code')
|
||||
async getUnitInvitationCode(@Param('unitUuid') unitUuid: string) {
|
||||
try {
|
||||
const unit = await this.unitService.getUnitInvitationCode(unitUuid);
|
||||
return unit;
|
||||
} catch (error) {
|
||||
throw new HttpException(
|
||||
error.message || 'Internal server error',
|
||||
error.status || HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@Post('user/verify-code')
|
||||
async verifyCodeAndAddUserUnit(
|
||||
@Body() addUserUnitUsingCodeDto: AddUserUnitUsingCodeDto,
|
||||
) {
|
||||
try {
|
||||
await this.unitService.verifyCodeAndAddUserUnit(addUserUnitUsingCodeDto);
|
||||
return {
|
||||
statusCode: HttpStatus.CREATED,
|
||||
success: true,
|
||||
message: 'user unit added successfully',
|
||||
};
|
||||
} catch (error) {
|
||||
throw new HttpException(
|
||||
error.message || 'Internal server error',
|
||||
error.status || HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -40,3 +40,22 @@ export class AddUserUnitDto {
|
||||
Object.assign(this, dto);
|
||||
}
|
||||
}
|
||||
export class AddUserUnitUsingCodeDto {
|
||||
@ApiProperty({
|
||||
description: 'userUuid',
|
||||
required: true,
|
||||
})
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
public userUuid: string;
|
||||
@ApiProperty({
|
||||
description: 'inviteCode',
|
||||
required: true,
|
||||
})
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
public inviteCode: string;
|
||||
constructor(dto: Partial<AddUserUnitDto>) {
|
||||
Object.assign(this, dto);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,7 +7,7 @@ import {
|
||||
BadRequestException,
|
||||
} from '@nestjs/common';
|
||||
import { SpaceRepository } from '@app/common/modules/space/repositories';
|
||||
import { AddUnitDto, AddUserUnitDto } from '../dtos';
|
||||
import { AddUnitDto, AddUserUnitDto, AddUserUnitUsingCodeDto } from '../dtos';
|
||||
import {
|
||||
UnitChildInterface,
|
||||
UnitParentInterface,
|
||||
@@ -18,6 +18,9 @@ import {
|
||||
import { SpaceEntity } from '@app/common/modules/space/entities';
|
||||
import { UpdateUnitNameDto } from '../dtos/update.unit.dto';
|
||||
import { UserSpaceRepository } from '@app/common/modules/user-space/repositories';
|
||||
import { generateRandomString } from '@app/common/helper/randomString';
|
||||
import { UserDevicePermissionService } from 'src/user-device-permission/services';
|
||||
import { PermissionType } from '@app/common/constants/permission-type.enum';
|
||||
|
||||
@Injectable()
|
||||
export class UnitService {
|
||||
@@ -25,6 +28,7 @@ export class UnitService {
|
||||
private readonly spaceRepository: SpaceRepository,
|
||||
private readonly spaceTypeRepository: SpaceTypeRepository,
|
||||
private readonly userSpaceRepository: UserSpaceRepository,
|
||||
private readonly userDevicePermissionService: UserDevicePermissionService,
|
||||
) {}
|
||||
|
||||
async addUnit(addUnitDto: AddUnitDto) {
|
||||
@@ -227,7 +231,7 @@ export class UnitService {
|
||||
|
||||
async addUserUnit(addUserUnitDto: AddUserUnitDto) {
|
||||
try {
|
||||
await this.userSpaceRepository.save({
|
||||
return await this.userSpaceRepository.save({
|
||||
user: { uuid: addUserUnitDto.userUuid },
|
||||
space: { uuid: addUserUnitDto.unitUuid },
|
||||
});
|
||||
@@ -282,4 +286,122 @@ export class UnitService {
|
||||
}
|
||||
}
|
||||
}
|
||||
async getUnitInvitationCode(unitUuid: string): Promise<any> {
|
||||
try {
|
||||
// Generate a 6-character random invitation code
|
||||
const invitationCode = generateRandomString(6);
|
||||
|
||||
// Update the unit with the new invitation code
|
||||
await this.spaceRepository.update({ uuid: unitUuid }, { invitationCode });
|
||||
|
||||
// Fetch the updated unit
|
||||
const updatedUnit = await this.spaceRepository.findOneOrFail({
|
||||
where: { uuid: unitUuid },
|
||||
relations: ['spaceType'],
|
||||
});
|
||||
|
||||
return {
|
||||
uuid: updatedUnit.uuid,
|
||||
invitationCode: updatedUnit.invitationCode,
|
||||
type: updatedUnit.spaceType.type,
|
||||
};
|
||||
} catch (err) {
|
||||
if (err instanceof BadRequestException) {
|
||||
throw err;
|
||||
} else {
|
||||
throw new HttpException('Unit not found', HttpStatus.NOT_FOUND);
|
||||
}
|
||||
}
|
||||
}
|
||||
async verifyCodeAndAddUserUnit(
|
||||
addUserUnitUsingCodeDto: AddUserUnitUsingCodeDto,
|
||||
) {
|
||||
try {
|
||||
const unit = await this.findUnitByInviteCode(
|
||||
addUserUnitUsingCodeDto.inviteCode,
|
||||
);
|
||||
|
||||
await this.addUserToUnit(addUserUnitUsingCodeDto.userUuid, unit.uuid);
|
||||
|
||||
await this.clearUnitInvitationCode(unit.uuid);
|
||||
|
||||
const deviceUUIDs = await this.getDeviceUUIDsForUnit(unit.uuid);
|
||||
|
||||
await this.addUserPermissionsToDevices(
|
||||
addUserUnitUsingCodeDto.userUuid,
|
||||
deviceUUIDs,
|
||||
);
|
||||
} catch (err) {
|
||||
throw new HttpException(
|
||||
'Invalid invitation code',
|
||||
HttpStatus.BAD_REQUEST,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private async findUnitByInviteCode(inviteCode: string): Promise<SpaceEntity> {
|
||||
const unit = await this.spaceRepository.findOneOrFail({
|
||||
where: {
|
||||
invitationCode: inviteCode,
|
||||
spaceType: { type: 'unit' },
|
||||
},
|
||||
relations: ['spaceType'],
|
||||
});
|
||||
|
||||
return unit;
|
||||
}
|
||||
|
||||
private async addUserToUnit(userUuid: string, unitUuid: string) {
|
||||
const user = await this.addUserUnit({ userUuid, unitUuid });
|
||||
|
||||
if (user.uuid) {
|
||||
return user;
|
||||
} else {
|
||||
throw new HttpException(
|
||||
'Failed to add user to unit',
|
||||
HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private async clearUnitInvitationCode(unitUuid: string) {
|
||||
await this.spaceRepository.update(
|
||||
{ uuid: unitUuid },
|
||||
{ invitationCode: null },
|
||||
);
|
||||
}
|
||||
|
||||
private async getDeviceUUIDsForUnit(
|
||||
unitUuid: string,
|
||||
): Promise<{ uuid: string }[]> {
|
||||
const devices = await this.spaceRepository.find({
|
||||
where: { parent: { uuid: unitUuid } },
|
||||
relations: ['devicesSpaceEntity', 'devicesSpaceEntity.productDevice'],
|
||||
});
|
||||
|
||||
const allDevices = devices.flatMap((space) => space.devicesSpaceEntity);
|
||||
|
||||
return allDevices.map((device) => ({ uuid: device.uuid }));
|
||||
}
|
||||
|
||||
private async addUserPermissionsToDevices(
|
||||
userUuid: string,
|
||||
deviceUUIDs: { uuid: string }[],
|
||||
): Promise<void> {
|
||||
const permissionPromises = deviceUUIDs.map(async (device) => {
|
||||
try {
|
||||
await this.userDevicePermissionService.addUserPermission({
|
||||
userUuid,
|
||||
deviceUuid: device.uuid,
|
||||
permissionType: PermissionType.CONTROLLABLE,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error(
|
||||
`Failed to add permission for device ${device.uuid}: ${error.message}`,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
await Promise.all(permissionPromises);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,6 +10,9 @@ import { UserSpaceRepositoryModule } from '@app/common/modules/user-space/user.s
|
||||
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';
|
||||
import { UserDevicePermissionService } from 'src/user-device-permission/services';
|
||||
import { DeviceUserPermissionRepository } from '@app/common/modules/device-user-permission/repositories';
|
||||
import { PermissionTypeRepository } from '@app/common/modules/permission/repositories';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
@@ -26,6 +29,9 @@ import { UserRepository } from '@app/common/modules/user/repositories';
|
||||
SpaceTypeRepository,
|
||||
UserSpaceRepository,
|
||||
UserRepository,
|
||||
UserDevicePermissionService,
|
||||
DeviceUserPermissionRepository,
|
||||
PermissionTypeRepository,
|
||||
],
|
||||
exports: [UnitService],
|
||||
})
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
export * from './user-notification.controller';
|
||||
@@ -0,0 +1,94 @@
|
||||
import {
|
||||
Body,
|
||||
Controller,
|
||||
Get,
|
||||
HttpException,
|
||||
HttpStatus,
|
||||
Param,
|
||||
Post,
|
||||
Put,
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import { ApiBearerAuth, ApiTags } from '@nestjs/swagger';
|
||||
import { UserNotificationService } from '../services/user-notification.service';
|
||||
import {
|
||||
UserNotificationAddDto,
|
||||
UserNotificationUpdateDto,
|
||||
} from '../dtos/user-notification.dto';
|
||||
|
||||
import { JwtAuthGuard } from '@app/common/guards/jwt.auth.guard';
|
||||
|
||||
@ApiTags('User Notification Module')
|
||||
@Controller({
|
||||
version: '1',
|
||||
path: 'user-notification/subscription',
|
||||
})
|
||||
export class UserNotificationController {
|
||||
constructor(
|
||||
private readonly userNotificationService: UserNotificationService,
|
||||
) {}
|
||||
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@Post()
|
||||
async addUserSubscription(
|
||||
@Body() userNotificationAddDto: UserNotificationAddDto,
|
||||
) {
|
||||
try {
|
||||
const addDetails = await this.userNotificationService.addUserSubscription(
|
||||
userNotificationAddDto,
|
||||
);
|
||||
return {
|
||||
statusCode: HttpStatus.CREATED,
|
||||
message: 'User Notification Added Successfully',
|
||||
data: addDetails,
|
||||
};
|
||||
} catch (error) {
|
||||
throw new HttpException(
|
||||
error.message || 'Internal server error',
|
||||
error.status || HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@Get(':userUuid')
|
||||
async fetchUserSubscriptions(@Param('userUuid') userUuid: string) {
|
||||
try {
|
||||
const userDetails =
|
||||
await this.userNotificationService.fetchUserSubscriptions(userUuid);
|
||||
return {
|
||||
statusCode: HttpStatus.OK,
|
||||
message: 'User Notification fetched Successfully',
|
||||
data: { ...userDetails },
|
||||
};
|
||||
} catch (error) {
|
||||
throw new HttpException(
|
||||
error.message || 'Internal server error',
|
||||
error.status || HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
}
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@Put()
|
||||
async updateUserSubscription(
|
||||
@Body() userNotificationUpdateDto: UserNotificationUpdateDto,
|
||||
) {
|
||||
try {
|
||||
await this.userNotificationService.updateUserSubscription(
|
||||
userNotificationUpdateDto,
|
||||
);
|
||||
return {
|
||||
statusCode: HttpStatus.OK,
|
||||
message: 'User subscription updated Successfully',
|
||||
};
|
||||
} catch (error) {
|
||||
throw new HttpException(
|
||||
error.message || 'Internal server error',
|
||||
error.status || HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export * from './user-notification.dto';
|
||||
@@ -0,0 +1,44 @@
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
import { IsBoolean, IsNotEmpty, IsString } from 'class-validator';
|
||||
|
||||
export class UserNotificationAddDto {
|
||||
@ApiProperty({
|
||||
description: 'user uuid',
|
||||
required: true,
|
||||
})
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
userUuid: string;
|
||||
|
||||
@ApiProperty({
|
||||
description: 'subscription uuid',
|
||||
required: true,
|
||||
})
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
subscriptionUuid: string;
|
||||
}
|
||||
export class UserNotificationUpdateDto {
|
||||
@ApiProperty({
|
||||
description: 'user uuid',
|
||||
required: true,
|
||||
})
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
userUuid: string;
|
||||
|
||||
@ApiProperty({
|
||||
description: 'subscription uuid',
|
||||
required: true,
|
||||
})
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
subscriptionUuid: string;
|
||||
@ApiProperty({
|
||||
description: 'active',
|
||||
required: true,
|
||||
})
|
||||
@IsBoolean()
|
||||
@IsNotEmpty()
|
||||
active: boolean;
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export * from './user-notification.service';
|
||||
@@ -0,0 +1,83 @@
|
||||
import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
|
||||
import {
|
||||
UserNotificationAddDto,
|
||||
UserNotificationUpdateDto,
|
||||
} from '../dtos/user-notification.dto';
|
||||
import { UserNotificationRepository } from '@app/common/modules/user-notification/repositories';
|
||||
|
||||
@Injectable()
|
||||
export class UserNotificationService {
|
||||
constructor(
|
||||
private readonly userNotificationRepository: UserNotificationRepository,
|
||||
) {}
|
||||
|
||||
async addUserSubscription(userNotificationAddDto: UserNotificationAddDto) {
|
||||
try {
|
||||
return await this.userNotificationRepository.save({
|
||||
user: {
|
||||
uuid: userNotificationAddDto.userUuid,
|
||||
},
|
||||
subscriptionUuid: userNotificationAddDto.subscriptionUuid,
|
||||
});
|
||||
} catch (error) {
|
||||
if (error.code === '23505') {
|
||||
throw new HttpException(
|
||||
'This User already has this subscription uuid',
|
||||
HttpStatus.BAD_REQUEST,
|
||||
);
|
||||
}
|
||||
throw new HttpException(
|
||||
error.message || 'Internal Server Error',
|
||||
HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
}
|
||||
async fetchUserSubscriptions(userUuid: string) {
|
||||
try {
|
||||
const userNotifications = await this.userNotificationRepository.find({
|
||||
where: {
|
||||
user: { uuid: userUuid },
|
||||
active: true,
|
||||
},
|
||||
});
|
||||
return {
|
||||
userUuid,
|
||||
subscriptionUuids: [
|
||||
...userNotifications.map((sub) => sub.subscriptionUuid),
|
||||
],
|
||||
};
|
||||
} catch (error) {
|
||||
throw new HttpException(
|
||||
'User subscription not found',
|
||||
HttpStatus.NOT_FOUND,
|
||||
);
|
||||
}
|
||||
}
|
||||
async updateUserSubscription(
|
||||
userNotificationUpdateDto: UserNotificationUpdateDto,
|
||||
) {
|
||||
try {
|
||||
const result = await this.userNotificationRepository.update(
|
||||
{
|
||||
user: { uuid: userNotificationUpdateDto.userUuid },
|
||||
subscriptionUuid: userNotificationUpdateDto.subscriptionUuid,
|
||||
},
|
||||
{ active: userNotificationUpdateDto.active },
|
||||
);
|
||||
|
||||
if (result.affected === 0) {
|
||||
throw new HttpException(
|
||||
'Subscription uuid not found',
|
||||
HttpStatus.NOT_FOUND,
|
||||
);
|
||||
}
|
||||
|
||||
return result;
|
||||
} catch (error) {
|
||||
throw new HttpException(
|
||||
error.message || 'Internal Server Error',
|
||||
HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { ConfigModule } from '@nestjs/config';
|
||||
import { UserNotificationRepositoryModule } from '@app/common/modules/user-notification/user.notification.repository.module';
|
||||
import { UserNotificationRepository } from '@app/common/modules/user-notification/repositories';
|
||||
import { UserNotificationService } from 'src/user-notification/services';
|
||||
import { UserNotificationController } from 'src/user-notification/controllers';
|
||||
|
||||
@Module({
|
||||
imports: [ConfigModule, UserNotificationRepositoryModule],
|
||||
controllers: [UserNotificationController],
|
||||
providers: [UserNotificationRepository, UserNotificationService],
|
||||
exports: [UserNotificationService],
|
||||
})
|
||||
export class UserNotificationModule {}
|
||||
Reference in New Issue
Block a user