Merge pull request #323 from SyncrowIOT/SP-1241-be-refactor-device-module

Sp 1241 be refactor device module
This commit is contained in:
hannathkadher
2025-03-24 11:20:58 +04:00
committed by GitHub
16 changed files with 793 additions and 620 deletions

View File

@ -0,0 +1,4 @@
export enum BatchDeviceTypeEnum {
RESET = 'RESET',
COMMAND = 'COMMAND',
}

View File

@ -473,14 +473,9 @@ export class ControllerRoute {
public static readonly ROUTE = 'device';
static ACTIONS = class {
public static readonly ADD_DEVICE_TO_USER_SUMMARY = 'Add device to user';
public static readonly ADD_DEVICE_TO_USER_DESCRIPTION =
'This endpoint adds a device to a user in the system.';
public static readonly GET_DEVICES_BY_USER_SUMMARY =
'Get devices by user UUID';
public static readonly GET_DEVICES_BY_USER_DESCRIPTION =
'This endpoint retrieves all devices associated with a specific user.';
public static readonly ADD_DEVICE_SUMMARY = 'Add new device';
public static readonly ADD_DEVICE_DESCRIPTION =
'This endpoint adds a new device in the system.';
public static readonly GET_DEVICES_BY_SPACE_UUID_SUMMARY =
'Get devices by space UUID';
@ -552,16 +547,16 @@ export class ControllerRoute {
'This endpoint retrieves the status of a specific power clamp device.';
public static readonly ADD_SCENE_TO_DEVICE_SUMMARY =
'Add scene to device (4 Scene and 6 Scene devices only)';
'Add scene to device';
public static readonly ADD_SCENE_TO_DEVICE_DESCRIPTION =
'This endpoint adds a scene to a specific switch device.';
public static readonly GET_SCENES_BY_DEVICE_SUMMARY =
'Get scenes by device (4 Scene and 6 Scene devices only)';
'Get scenes by device';
public static readonly GET_SCENES_BY_DEVICE_DESCRIPTION =
'This endpoint retrieves all scenes associated with a specific switch device.';
public static readonly DELETE_SCENES_BY_SWITCH_NAME_SUMMARY =
'Delete scenes by device uuid and switch name (4 Scene and 6 Scene devices only)';
'Delete scenes by device uuid and switch name';
public static readonly DELETE_SCENES_BY_SWITCH_NAME_DESCRIPTION =
'This endpoint deletes all scenes associated with a specific switch device.';
};

View File

@ -0,0 +1,3 @@
export enum DeviceTypeEnum {
DOOR_LOCK = 'DOOR_LOCK',
}

View File

@ -123,6 +123,7 @@ export class AutomationService {
);
const formattedCondition = await this.prepareConditions(
params.conditions,
projectUuid,
);
const response = await this.tuyaService.createAutomation(
@ -585,7 +586,10 @@ export class AutomationService {
updateAutomationDto;
try {
const formattedActions = await this.prepareActions(actions, projectUuid);
const formattedCondition = await this.prepareConditions(conditions);
const formattedCondition = await this.prepareConditions(
conditions,
projectUuid,
);
const response = await this.tuyaService.updateAutomation(
automationUuid,
spaceTuyaUuid,
@ -722,6 +726,7 @@ export class AutomationService {
const device = await this.deviceService.getDeviceByDeviceUuid(
action.entity_id,
false,
projectUuid,
);
if (device) {
action.entity_id = device.deviceTuyaUuid;
@ -759,7 +764,10 @@ export class AutomationService {
return convertedData;
}
private async prepareConditions(conditions: Condition[]) {
private async prepareConditions(
conditions: Condition[],
projectUuid: string,
) {
const convertedData = convertKeysToSnakeCase(conditions);
await Promise.all(
convertedData.map(async (condition) => {
@ -767,6 +775,7 @@ export class AutomationService {
const device = await this.deviceService.getDeviceByDeviceUuid(
condition.entity_id,
false,
projectUuid,
);
if (device) {
condition.entity_id = device.deviceTuyaUuid;

View File

@ -1,11 +1,11 @@
import { DeviceService } from '../services/device.service';
import { Controller, Get, Param, UseGuards } from '@nestjs/common';
import { Controller, Get, Param, Query, UseGuards } from '@nestjs/common';
import { ApiTags, ApiBearerAuth, ApiOperation } from '@nestjs/swagger';
import { EnableDisableStatusEnum } from '@app/common/constants/days.enum';
import { ControllerRoute } from '@app/common/constants/controller-route';
import { PermissionsGuard } from 'src/guards/permissions.guard';
import { Permissions } from 'src/decorators/permissions.decorator';
import { ProjectParam } from '../dtos';
import { GetDoorLockDevices, ProjectParam } from '../dtos';
@ApiTags('Device Module')
@Controller({
@ -23,7 +23,10 @@ export class DeviceProjectController {
summary: ControllerRoute.DEVICE.ACTIONS.GET_ALL_DEVICES_SUMMARY,
description: ControllerRoute.DEVICE.ACTIONS.GET_ALL_DEVICES_DESCRIPTION,
})
async getAllDevices(@Param() param: ProjectParam) {
return await this.deviceService.getAllDevices(param);
async getAllDevices(
@Param() param: ProjectParam,
@Query() query: GetDoorLockDevices,
) {
return await this.deviceService.getAllDevices(param, query);
}
}

View File

@ -6,25 +6,23 @@ import {
Post,
Query,
Param,
HttpStatus,
UseGuards,
Req,
Put,
Delete,
Req,
} from '@nestjs/common';
import { ApiTags, ApiBearerAuth, ApiOperation } from '@nestjs/swagger';
import {
AddDeviceDto,
AddSceneToFourSceneDeviceDto,
AssignDeviceToSpaceDto,
UpdateDeviceDto,
UpdateDeviceInSpaceDto,
} from '../dtos/add.device.dto';
import { GetDeviceLogsDto } from '../dtos/get.device.dto';
import {
ControlDeviceDto,
BatchControlDevicesDto,
BatchStatusDevicesDto,
BatchFactoryResetDevicesDto,
GetSceneFourSceneDeviceDto,
} from '../dtos/control.device.dto';
import { CheckRoomGuard } from 'src/guards/room.guard';
@ -50,65 +48,35 @@ export class DeviceController {
@Permissions('SPACE_DEVICE_ASSIGN_DEVICE_TO_SPACE')
@Post()
@ApiOperation({
summary: ControllerRoute.DEVICE.ACTIONS.ADD_DEVICE_TO_USER_SUMMARY,
description: ControllerRoute.DEVICE.ACTIONS.ADD_DEVICE_TO_USER_DESCRIPTION,
summary: ControllerRoute.DEVICE.ACTIONS.ADD_DEVICE_SUMMARY,
description: ControllerRoute.DEVICE.ACTIONS.ADD_DEVICE_DESCRIPTION,
})
async addDeviceUser(@Body() addDeviceDto: AddDeviceDto) {
const device = await this.deviceService.addDeviceUser(addDeviceDto);
return {
statusCode: HttpStatus.CREATED,
success: true,
message: 'device added successfully',
data: device,
};
}
@ApiBearerAuth()
@UseGuards(PermissionsGuard)
@Permissions('DEVICE_VIEW')
@Get('user/:userUuid')
@ApiOperation({
summary: ControllerRoute.DEVICE.ACTIONS.GET_DEVICES_BY_USER_SUMMARY,
description: ControllerRoute.DEVICE.ACTIONS.GET_DEVICES_BY_USER_DESCRIPTION,
})
async getDevicesByUser(@Param('userUuid') userUuid: string) {
return await this.deviceService.getDevicesByUser(userUuid);
async addNewDevice(
@Body() addDeviceDto: AddDeviceDto,
@Req() req: any,
): Promise<BaseResponseDto> {
const projectUuid = req.user.project.uuid;
return await this.deviceService.addNewDevice(addDeviceDto, projectUuid);
}
@ApiBearerAuth()
@UseGuards(PermissionsGuard)
@Permissions('SPACE_DEVICE_VIEW_DEVICE_IN_SPACE')
@Get('space/:spaceUuid')
@ApiOperation({
summary: ControllerRoute.DEVICE.ACTIONS.GET_DEVICES_BY_SPACE_UUID_SUMMARY,
description:
ControllerRoute.DEVICE.ACTIONS.GET_DEVICES_BY_SPACE_UUID_DESCRIPTION,
})
async getDevicesByUnitId(@Param('spaceUuid') spaceUuid: string) {
return await this.deviceService.getDevicesBySpaceUuid(spaceUuid);
}
@ApiBearerAuth()
@UseGuards(PermissionsGuard, CheckRoomGuard)
@Permissions('SUBSPACE_DEVICE_UPDATE_DEVICE_IN_SUBSPACE')
@Put('space')
@Post(':deviceUuid/space/:spaceUuid')
@ApiOperation({
summary: ControllerRoute.DEVICE.ACTIONS.UPDATE_DEVICE_IN_ROOM_SUMMARY,
description:
ControllerRoute.DEVICE.ACTIONS.UPDATE_DEVICE_IN_ROOM_DESCRIPTION,
})
async updateDeviceInRoom(
@Body() updateDeviceInSpaceDto: UpdateDeviceInSpaceDto,
) {
const device = await this.deviceService.updateDeviceInSpace(
async transferDeviceInSpaces(
@Param() updateDeviceInSpaceDto: AssignDeviceToSpaceDto,
@Req() req: any,
): Promise<BaseResponseDto> {
const projectUuid = req.user.project.uuid;
return await this.deviceService.transferDeviceInSpaces(
updateDeviceInSpaceDto,
projectUuid,
);
return {
statusCode: HttpStatus.CREATED,
success: true,
message: 'device updated in room successfully',
data: device,
};
}
@ApiBearerAuth()
@ -122,11 +90,11 @@ export class DeviceController {
async getDeviceDetailsByDeviceId(
@Param('deviceUuid') deviceUuid: string,
@Req() req: any,
) {
const userUuid = req.user.uuid;
): Promise<BaseResponseDto> {
const projectUuid = req.user.project.uuid;
return await this.deviceService.getDeviceDetailsByDeviceId(
deviceUuid,
userUuid,
projectUuid,
);
}
@ApiBearerAuth()
@ -140,18 +108,14 @@ export class DeviceController {
async updateDevice(
@Param('deviceUuid') deviceUuid: string,
@Body() updateDeviceDto: UpdateDeviceDto,
) {
const device = await this.deviceService.updateDevice(
@Req() req: any,
): Promise<BaseResponseDto> {
const projectUuid = req.user.project.uuid;
return await this.deviceService.updateDevice(
deviceUuid,
updateDeviceDto,
projectUuid,
);
return {
statusCode: HttpStatus.CREATED,
success: true,
message: 'device updated successfully',
data: device,
};
}
@ApiBearerAuth()
@ -165,8 +129,13 @@ export class DeviceController {
})
async getDeviceInstructionByDeviceId(
@Param('deviceUuid') deviceUuid: string,
@Req() req: any,
) {
return await this.deviceService.getDeviceInstructionByDeviceId(deviceUuid);
const projectUuid = req.user.project.uuid;
return await this.deviceService.getDeviceInstructionByDeviceId(
deviceUuid,
projectUuid,
);
}
@ApiBearerAuth()
@UseGuards(PermissionsGuard)
@ -176,14 +145,18 @@ export class DeviceController {
summary: ControllerRoute.DEVICE.ACTIONS.GET_DEVICE_STATUS_SUMMARY,
description: ControllerRoute.DEVICE.ACTIONS.GET_DEVICE_STATUS_DESCRIPTION,
})
async getDevicesInstructionStatus(@Param('deviceUuid') deviceUuid: string) {
return await this.deviceService.getDevicesInstructionStatus(deviceUuid);
async getDevicesInstructionStatus(
@Param('deviceUuid') deviceUuid: string,
@Req() req: any,
): Promise<BaseResponseDto> {
const projectUuid = req.user.project.uuid;
return await this.deviceService.getDevicesStatus(deviceUuid, projectUuid);
}
@ApiBearerAuth()
@UseGuards(PermissionsGuard)
@Permissions('DEVICE_SINGLE_CONTROL')
@Post(':deviceUuid/control')
@Post(':deviceUuid/command')
@ApiOperation({
summary: ControllerRoute.DEVICE.ACTIONS.CONTROL_DEVICE_SUMMARY,
description: ControllerRoute.DEVICE.ACTIONS.CONTROL_DEVICE_DESCRIPTION,
@ -191,8 +164,14 @@ export class DeviceController {
async controlDevice(
@Body() controlDeviceDto: ControlDeviceDto,
@Param('deviceUuid') deviceUuid: string,
) {
return await this.deviceService.controlDevice(controlDeviceDto, deviceUuid);
@Req() req: any,
): Promise<BaseResponseDto> {
const projectUuid = req.user.project.uuid;
return await this.deviceService.controlDevice(
controlDeviceDto,
deviceUuid,
projectUuid,
);
}
@ApiBearerAuth()
@UseGuards(PermissionsGuard)
@ -206,10 +185,13 @@ export class DeviceController {
async updateDeviceFirmware(
@Param('deviceUuid') deviceUuid: string,
@Param('firmwareVersion') firmwareVersion: number,
) {
@Req() req: any,
): Promise<BaseResponseDto> {
const projectUuid = req.user.project.uuid;
return await this.deviceService.updateDeviceFirmware(
deviceUuid,
firmwareVersion,
projectUuid,
);
}
@ApiBearerAuth()
@ -221,14 +203,21 @@ export class DeviceController {
description:
ControllerRoute.DEVICE.ACTIONS.GET_DEVICES_IN_GATEWAY_DESCRIPTION,
})
async getDevicesInGateway(@Param('gatewayUuid') gatewayUuid: string) {
return await this.deviceService.getDevicesInGateway(gatewayUuid);
async getDevicesInGateway(
@Param('gatewayUuid') gatewayUuid: string,
@Req() req: any,
): Promise<BaseResponseDto> {
const projectUuid = req.user.project.uuid;
return await this.deviceService.getDevicesInGateway(
gatewayUuid,
projectUuid,
);
}
@ApiBearerAuth()
@UseGuards(PermissionsGuard)
@Permissions('DEVICE_VIEW')
@Get('report-logs/:deviceUuid')
@Get(':deviceUuid/report-logs')
@ApiOperation({
summary: ControllerRoute.DEVICE.ACTIONS.GET_DEVICE_LOGS_SUMMARY,
description: ControllerRoute.DEVICE.ACTIONS.GET_DEVICE_LOGS_DESCRIPTION,
@ -236,13 +225,19 @@ export class DeviceController {
async getBuildingChildByUuid(
@Param('deviceUuid') deviceUuid: string,
@Query() query: GetDeviceLogsDto,
) {
return await this.deviceService.getDeviceLogs(deviceUuid, query);
@Req() req: any,
): Promise<BaseResponseDto> {
const projectUuid = req.user.project.uuid;
return await this.deviceService.getDeviceLogs(
deviceUuid,
query,
projectUuid,
);
}
@ApiBearerAuth()
@UseGuards(PermissionsGuard)
@Permissions('DEVICE_BATCH_CONTROL')
@Post('control/batch')
@Post('batch')
@ApiOperation({
summary: ControllerRoute.DEVICE.ACTIONS.BATCH_CONTROL_DEVICES_SUMMARY,
description:
@ -250,13 +245,18 @@ export class DeviceController {
})
async batchControlDevices(
@Body() batchControlDevicesDto: BatchControlDevicesDto,
@Req() req: any,
) {
return await this.deviceService.batchControlDevices(batchControlDevicesDto);
const projectUuid = req.user.project.uuid;
return await this.deviceService.batchControlDevices(
batchControlDevicesDto,
projectUuid,
);
}
@ApiBearerAuth()
@UseGuards(PermissionsGuard)
@Permissions('DEVICE_BATCH_CONTROL')
@Get('status/batch')
@Get('batch')
@ApiOperation({
summary: ControllerRoute.DEVICE.ACTIONS.BATCH_STATUS_DEVICES_SUMMARY,
description:
@ -264,41 +264,15 @@ export class DeviceController {
})
async batchStatusDevices(
@Query() batchStatusDevicesDto: BatchStatusDevicesDto,
) {
return await this.deviceService.batchStatusDevices(batchStatusDevicesDto);
}
@ApiBearerAuth()
@UseGuards(PermissionsGuard)
@Permissions('DEVICE_DELETE')
@Post('factory/reset/:deviceUuid')
@ApiOperation({
summary: ControllerRoute.DEVICE.ACTIONS.BATCH_FACTORY_RESET_DEVICES_SUMMARY,
description:
ControllerRoute.DEVICE.ACTIONS.BATCH_FACTORY_RESET_DEVICES_DESCRIPTION,
})
async batchFactoryResetDevices(
@Body() batchFactoryResetDevicesDto: BatchFactoryResetDevicesDto,
) {
return await this.deviceService.batchFactoryResetDevices(
batchFactoryResetDevicesDto,
);
}
@ApiBearerAuth()
@UseGuards(PermissionsGuard)
@Permissions('DEVICE_VIEW')
@Get(':powerClampUuid/power-clamp/status')
@ApiOperation({
summary: ControllerRoute.DEVICE.ACTIONS.GET_POWER_CLAMP_STATUS_SUMMARY,
description:
ControllerRoute.DEVICE.ACTIONS.GET_POWER_CLAMP_STATUS_DESCRIPTION,
})
async getPowerClampInstructionStatus(
@Param('powerClampUuid') powerClampUuid: string,
) {
return await this.deviceService.getPowerClampInstructionStatus(
powerClampUuid,
@Req() req: any,
): Promise<BaseResponseDto> {
const projectUuid = req.user.project.uuid;
return await this.deviceService.batchStatusDevices(
batchStatusDevicesDto,
projectUuid,
);
}
@ApiBearerAuth()
@UseGuards(PermissionsGuard, CheckFourAndSixSceneDeviceTypeGuard)
@Permissions('DEVICE_SINGLE_CONTROL')
@ -310,18 +284,14 @@ export class DeviceController {
async addSceneToSceneDevice(
@Param('deviceUuid') deviceUuid: string,
@Body() addSceneToFourSceneDeviceDto: AddSceneToFourSceneDeviceDto,
) {
const device = await this.deviceService.addSceneToSceneDevice(
@Req() req: any,
): Promise<BaseResponseDto> {
const projectUuid = req.user.project.uuid;
return await this.deviceService.addSceneToSceneDevice(
deviceUuid,
addSceneToFourSceneDeviceDto,
projectUuid,
);
return {
statusCode: HttpStatus.CREATED,
success: true,
message: `scene added successfully to device ${deviceUuid}`,
data: device,
};
}
@ApiBearerAuth()
@UseGuards(PermissionsGuard, CheckFourAndSixSceneDeviceTypeGuard)
@ -335,10 +305,13 @@ export class DeviceController {
async getScenesBySceneDevice(
@Param('deviceUuid') deviceUuid: string,
@Query() getSceneFourSceneDeviceDto: GetSceneFourSceneDeviceDto,
) {
@Req() req: any,
): Promise<BaseResponseDto> {
const projectUuid = req.user.project.uuid;
return await this.deviceService.getScenesBySceneDevice(
deviceUuid,
getSceneFourSceneDeviceDto,
projectUuid,
);
}
@ApiBearerAuth()
@ -354,7 +327,13 @@ export class DeviceController {
async deleteSceneFromSceneDevice(
@Param() param: DeviceSceneParamDto,
@Query() query: DeleteSceneFromSceneDeviceDto,
@Req() req: any,
): Promise<BaseResponseDto> {
return await this.deviceService.deleteSceneFromSceneDevice(param, query);
const projectUuid = req.user.project.uuid;
return await this.deviceService.deleteSceneFromSceneDevice(
param,
query,
projectUuid,
);
}
}

View File

@ -10,16 +10,8 @@ export class AddDeviceDto {
@IsString()
@IsNotEmpty()
public deviceTuyaUuid: string;
@ApiProperty({
description: 'userUuid',
required: true,
})
@IsString()
@IsNotEmpty()
public userUuid: string;
}
export class UpdateDeviceInSpaceDto {
export class AssignDeviceToSpaceDto {
@ApiProperty({
description: 'deviceUuid',
required: true,

View File

@ -1,5 +1,12 @@
import { BatchDeviceTypeEnum } from '@app/common/constants/batch-device.enum';
import { ApiProperty } from '@nestjs/swagger';
import { IsArray, IsNotEmpty, IsOptional, IsString } from 'class-validator';
import {
IsArray,
IsEnum,
IsNotEmpty,
IsOptional,
IsString,
} from 'class-validator';
export class ControlDeviceDto {
@ApiProperty({
@ -17,6 +24,15 @@ export class ControlDeviceDto {
public value: any;
}
export class BatchControlDevicesDto {
@ApiProperty({
description: 'Operation type',
enum: BatchDeviceTypeEnum,
required: true,
})
@IsEnum(BatchDeviceTypeEnum)
@IsNotEmpty()
public operationType: BatchDeviceTypeEnum;
@ApiProperty({
description: 'devicesUuid',
required: true,

View File

@ -1,5 +1,6 @@
import { DeviceTypeEnum } from '@app/common/constants/device-type.enum';
import { ApiProperty } from '@nestjs/swagger';
import { IsNotEmpty, IsOptional, IsString } from 'class-validator';
import { IsEnum, IsNotEmpty, IsOptional, IsString } from 'class-validator';
export class GetDeviceBySpaceUuidDto {
@ApiProperty({
@ -33,3 +34,13 @@ export class GetDeviceLogsDto {
@IsOptional()
public endTime: string;
}
export class GetDoorLockDevices {
@ApiProperty({
description: 'Device Type',
enum: DeviceTypeEnum,
required: false,
})
@IsEnum(DeviceTypeEnum)
@IsOptional()
public deviceType: DeviceTypeEnum;
}

View File

@ -64,13 +64,15 @@ export interface GetDeviceDetailsFunctionsStatusInterface {
}
export interface DeviceInstructionResponse {
productUuid: string;
productType: string;
functions: {
code: string;
values: any[];
dataType: string;
}[];
data: {
productUuid: string;
productType: string;
functions: {
code: string;
values: any[];
dataType: string;
}[];
};
}
export interface updateDeviceFirmwareInterface {
success: boolean;

File diff suppressed because it is too large Load Diff

View File

@ -15,14 +15,17 @@ export class CheckFourAndSixSceneDeviceTypeGuard implements CanActivate {
async canActivate(context: ExecutionContext): Promise<boolean> {
const request = context.switchToHttp().getRequest();
const deviceUuid = request.params.deviceUuid;
const projectUuid = request.user.project.uuid;
if (!deviceUuid) {
throw new BadRequestException('Device UUID is required');
}
try {
const deviceDetails =
await this.deviceService.getDeviceByDeviceUuid(deviceUuid);
const deviceDetails = await this.deviceService.getDeviceByDeviceUuid(
deviceUuid,
true,
projectUuid,
);
if (
deviceDetails.productDevice.prodType !== ProductType.FOUR_S &&

View File

@ -8,6 +8,7 @@ import {
Param,
Post,
Put,
Req,
UseGuards,
} from '@nestjs/common';
import { ApiTags, ApiBearerAuth, ApiOperation } from '@nestjs/swagger';
@ -42,8 +43,13 @@ export class SceneController {
})
async addTapToRunScene(
@Body() addSceneTapToRunDto: AddSceneTapToRunDto,
@Req() req: any,
): Promise<BaseResponseDto> {
return await this.sceneService.createScene(addSceneTapToRunDto);
const projectUuid = req.user.project.uuid;
return await this.sceneService.createScene(
addSceneTapToRunDto,
projectUuid,
);
}
@ApiBearerAuth()
@ -100,10 +106,13 @@ export class SceneController {
async updateTapToRunScene(
@Body() updateSceneTapToRunDto: UpdateSceneTapToRunDto,
@Param() param: SceneParamDto,
@Req() req: any,
) {
const projectUuid = req.user.project.uuid;
return await this.sceneService.updateTapToRunScene(
updateSceneTapToRunDto,
param.sceneUuid,
projectUuid,
);
}

View File

@ -60,13 +60,18 @@ export class SceneService {
async createScene(
addSceneTapToRunDto: AddSceneTapToRunDto,
projectUuid: string,
): Promise<BaseResponseDto> {
try {
const { spaceUuid } = addSceneTapToRunDto;
const space = await this.getSpaceByUuid(spaceUuid);
const scene = await this.create(space.spaceTuyaUuid, addSceneTapToRunDto);
const scene = await this.create(
space.spaceTuyaUuid,
addSceneTapToRunDto,
projectUuid,
);
return new SuccessResponseDto({
message: `Successfully created new scene with uuid ${scene.uuid}`,
@ -90,6 +95,7 @@ export class SceneService {
async create(
spaceTuyaUuid: string,
addSceneTapToRunDto: AddSceneTapToRunDto,
projectUuid: string,
): Promise<SceneEntity> {
const { iconUuid, showInHomePage, spaceUuid } = addSceneTapToRunDto;
@ -107,6 +113,7 @@ export class SceneService {
const response = await this.createSceneExternalService(
spaceTuyaUuid,
addSceneTapToRunDto,
projectUuid,
);
const scene = await this.sceneRepository.save({
@ -137,10 +144,11 @@ export class SceneService {
spaceTuyaUuid: string,
sceneTuyaUuid: string,
updateSceneTapToRunDto: UpdateSceneTapToRunDto,
projectUuid: string,
) {
const { sceneName, decisionExpr, actions } = updateSceneTapToRunDto;
try {
const formattedActions = await this.prepareActions(actions);
const formattedActions = await this.prepareActions(actions, projectUuid);
const response = (await this.tuyaService.updateTapToRunScene(
sceneTuyaUuid,
@ -178,10 +186,11 @@ export class SceneService {
async createSceneExternalService(
spaceTuyaUuid: string,
addSceneTapToRunDto: AddSceneTapToRunDto,
projectUuid: string,
) {
const { sceneName, decisionExpr, actions } = addSceneTapToRunDto;
try {
const formattedActions = await this.prepareActions(actions);
const formattedActions = await this.prepareActions(actions, projectUuid);
const response = (await this.tuyaService.addTapToRunScene(
spaceTuyaUuid,
@ -324,6 +333,7 @@ export class SceneService {
async updateTapToRunScene(
updateSceneTapToRunDto: UpdateSceneTapToRunDto,
sceneUuid: string,
projectUuid: string,
) {
try {
const scene = await this.findScene(sceneUuid);
@ -340,6 +350,7 @@ export class SceneService {
space.spaceTuyaUuid,
scene.sceneTuyaUuid,
addSceneTapToRunDto,
projectUuid,
);
if (!updateTuyaSceneResponse.success) {
@ -573,7 +584,10 @@ export class SceneService {
}
}
private async prepareActions(actions: Action[]): Promise<ConvertedAction[]> {
private async prepareActions(
actions: Action[],
projectUuid: string,
): Promise<ConvertedAction[]> {
const convertedData = convertKeysToSnakeCase(actions) as ConvertedAction[];
await Promise.all(
@ -582,6 +596,7 @@ export class SceneService {
const device = await this.deviceService.getDeviceByDeviceUuid(
action.entity_id,
false,
projectUuid,
);
if (device) {
action.entity_id = device.deviceTuyaUuid;

View File

@ -1,13 +1,5 @@
import { VisitorPasswordService } from '../services/visitor-password.service';
import {
Body,
Controller,
Post,
HttpStatus,
UseGuards,
Req,
Get,
} from '@nestjs/common';
import { Body, Controller, Post, UseGuards, Req, Get } from '@nestjs/common';
import { ApiTags, ApiBearerAuth, ApiOperation } from '@nestjs/swagger';
import { AddDoorLockTemporaryPasswordDto } from '../dtos/temp-pass.dto';
import { EnableDisableStatusEnum } from '@app/common/constants/days.enum';
@ -40,16 +32,12 @@ export class VisitorPasswordController {
@Req() req: any,
) {
const userUuid = req.user.uuid;
const temporaryPasswords =
await this.visitorPasswordService.handleTemporaryPassword(
addDoorLockTemporaryPasswordDto,
userUuid,
);
return {
statusCode: HttpStatus.CREATED,
data: temporaryPasswords,
};
const projectUuid = req.user.project.uuid;
return await this.visitorPasswordService.handleTemporaryPassword(
addDoorLockTemporaryPasswordDto,
userUuid,
projectUuid,
);
}
@ApiBearerAuth()
@UseGuards(PermissionsGuard)
@ -65,19 +53,4 @@ export class VisitorPasswordController {
const projectUuid = req.user.project.uuid;
return await this.visitorPasswordService.getPasswords(projectUuid);
}
@ApiBearerAuth()
@UseGuards(PermissionsGuard)
@Permissions('VISITOR_PASSWORD_VIEW')
@Get('/devices')
@ApiOperation({
summary:
ControllerRoute.VISITOR_PASSWORD.ACTIONS.GET_VISITOR_DEVICES_SUMMARY,
description:
ControllerRoute.VISITOR_PASSWORD.ACTIONS.GET_VISITOR_DEVICES_DESCRIPTION,
})
async GetVisitorDevices(@Req() req: any) {
const projectUuid = req.user.project.uuid;
return await this.visitorPasswordService.getAllPassDevices(projectUuid);
}
}

View File

@ -18,7 +18,6 @@ import { AddDoorLockTemporaryPasswordDto } from '../dtos';
import { EmailService } from '@app/common/util/email.service';
import { PasswordEncryptionService } from 'src/door-lock/services/encryption.services';
import { DoorLockService } from 'src/door-lock/services';
import { GetDeviceDetailsInterface } from 'src/device/interfaces/get.device.interface';
import { DeviceService } from 'src/device/services';
import { DeviceStatuses } from '@app/common/constants/device-status.enum';
import {
@ -32,6 +31,9 @@ import {
} from '@app/common/constants/hours-minutes.enum';
import { ProjectRepository } from '@app/common/modules/project/repositiories';
import { VisitorPasswordEnum } from '@app/common/constants/visitor-password.enum';
import { SuccessResponseDto } from '@app/common/dto/success.response.dto';
import { Not } from 'typeorm';
import { ORPHAN_SPACE_NAME } from '@app/common/constants/orphan-constant';
@Injectable()
export class VisitorPasswordService {
@ -58,43 +60,65 @@ export class VisitorPasswordService {
async handleTemporaryPassword(
addDoorLockTemporaryPasswordDto: AddDoorLockTemporaryPasswordDto,
userUuid: string,
projectUuid: string,
) {
const { operationType } = addDoorLockTemporaryPasswordDto;
let result;
switch (operationType) {
case VisitorPasswordEnum.ONLINE_ONE_TIME:
return this.addOnlineTemporaryPasswordOneTime(
result = await this.addOnlineTemporaryPasswordOneTime(
addDoorLockTemporaryPasswordDto,
userUuid,
projectUuid,
);
break;
case VisitorPasswordEnum.ONLINE_MULTIPLE_TIME:
return this.addOnlineTemporaryPasswordMultipleTime(
result = await this.addOnlineTemporaryPasswordMultipleTime(
addDoorLockTemporaryPasswordDto,
userUuid,
projectUuid,
);
break;
case VisitorPasswordEnum.OFFLINE_ONE_TIME:
return this.addOfflineOneTimeTemporaryPassword(
result = await this.addOfflineOneTimeTemporaryPassword(
addDoorLockTemporaryPasswordDto,
userUuid,
projectUuid,
);
break;
case VisitorPasswordEnum.OFFLINE_MULTIPLE_TIME:
return this.addOfflineMultipleTimeTemporaryPassword(
result = await this.addOfflineMultipleTimeTemporaryPassword(
addDoorLockTemporaryPasswordDto,
userUuid,
projectUuid,
);
break;
default:
throw new BadRequestException('Invalid operation type');
}
return new SuccessResponseDto({
message: `Successfully created new ${operationType.toLowerCase()} visitor password`,
data: result,
statusCode: HttpStatus.CREATED,
});
}
async addOfflineMultipleTimeTemporaryPassword(
addDoorLockOfflineMultipleDto: AddDoorLockTemporaryPasswordDto,
userUuid: string,
projectUuid: string,
) {
try {
const deviceResults = await Promise.allSettled(
addDoorLockOfflineMultipleDto.devicesUuid.map(async (deviceUuid) => {
try {
const deviceDetails = await this.getDeviceByDeviceUuid(deviceUuid);
const deviceDetails = await this.getDeviceByDeviceUuid(
deviceUuid,
true,
projectUuid,
);
if (!deviceDetails || !deviceDetails.deviceTuyaUuid) {
throw new HttpException('Device Not Found', HttpStatus.NOT_FOUND);
@ -210,12 +234,17 @@ export class VisitorPasswordService {
async addOfflineOneTimeTemporaryPassword(
addDoorLockOfflineOneTimeDto: AddDoorLockTemporaryPasswordDto,
userUuid: string,
projectUuid: string,
) {
try {
const deviceResults = await Promise.allSettled(
addDoorLockOfflineOneTimeDto.devicesUuid.map(async (deviceUuid) => {
try {
const deviceDetails = await this.getDeviceByDeviceUuid(deviceUuid);
const deviceDetails = await this.getDeviceByDeviceUuid(
deviceUuid,
true,
projectUuid,
);
if (!deviceDetails || !deviceDetails.deviceTuyaUuid) {
throw new HttpException('Device Not Found', HttpStatus.NOT_FOUND);
@ -361,6 +390,7 @@ export class VisitorPasswordService {
async addOnlineTemporaryPasswordMultipleTime(
addDoorLockOnlineMultipleDto: AddDoorLockTemporaryPasswordDto,
userUuid: string,
projectUuid: string,
) {
try {
const deviceResults = await Promise.allSettled(
@ -369,6 +399,7 @@ export class VisitorPasswordService {
const passwordData = await this.getTicketAndEncryptedPassword(
deviceUuid,
addDoorLockOnlineMultipleDto.password,
projectUuid,
);
if (
@ -486,6 +517,7 @@ export class VisitorPasswordService {
prodType: ProductType.DL,
},
spaceDevice: {
spaceName: Not(ORPHAN_SPACE_NAME),
community: {
project: {
uuid: projectUuid,
@ -495,6 +527,7 @@ export class VisitorPasswordService {
isActive: true,
},
});
const data = [];
deviceIds.forEach((deviceId) => {
data.push(
@ -524,62 +557,21 @@ export class VisitorPasswordService {
.catch(() => {}),
);
});
return (await Promise.all(data)).flat().filter((datum) => {
const result = (await Promise.all(data)).flat().filter((datum) => {
return datum != null;
});
}
async getAllPassDevices(projectUuid: string) {
await this.validateProject(projectUuid);
const devices = await this.deviceRepository.find({
where: {
productDevice: {
prodType: ProductType.DL,
},
spaceDevice: {
community: {
project: {
uuid: projectUuid,
},
},
},
isActive: true,
},
relations: ['productDevice', 'spaceDevice'],
return new SuccessResponseDto({
message: 'Successfully retrieved temporary passwords',
data: result,
statusCode: HttpStatus.OK,
});
const devicesData = await Promise.all(
devices?.map(async (device) => {
try {
const deviceDetails =
await this.deviceService.getDeviceDetailsByDeviceIdTuya(
device.deviceTuyaUuid,
);
return {
productUuid: device.productDevice.uuid,
productType: device.productDevice.prodType,
...deviceDetails,
uuid: device.uuid,
spaceName: device.spaceDevice.spaceName,
} as GetDeviceDetailsInterface;
} catch (error) {
console.error(
`Error fetching details for device ${device.deviceTuyaUuid}:`,
error,
);
// Return null or a specific value to indicate the error
return null;
}
}),
);
// Filter out null values to only include successful device data
return devicesData.filter((deviceData) => deviceData !== null);
}
async addOnlineTemporaryPasswordOneTime(
addDoorLockOnlineOneTimeDto: AddDoorLockTemporaryPasswordDto,
userUuid: string,
projectUuid: string,
) {
try {
const deviceResults = await Promise.allSettled(
@ -588,6 +580,7 @@ export class VisitorPasswordService {
const passwordData = await this.getTicketAndEncryptedPassword(
deviceUuid,
addDoorLockOnlineOneTimeDto.password,
projectUuid,
);
if (
@ -698,9 +691,14 @@ export class VisitorPasswordService {
async getTicketAndEncryptedPassword(
doorLockUuid: string,
passwordPlan: string,
projectUuid: string,
) {
try {
const deviceDetails = await this.getDeviceByDeviceUuid(doorLockUuid);
const deviceDetails = await this.getDeviceByDeviceUuid(
doorLockUuid,
true,
projectUuid,
);
if (!deviceDetails || !deviceDetails.deviceTuyaUuid) {
throw new HttpException('Device Not Found', HttpStatus.NOT_FOUND);
@ -919,10 +917,19 @@ export class VisitorPasswordService {
async getDeviceByDeviceUuid(
deviceUuid: string,
withProductDevice: boolean = true,
projectUuid: string,
) {
try {
return await this.deviceRepository.findOne({
where: {
spaceDevice: {
spaceName: Not(ORPHAN_SPACE_NAME),
community: {
project: {
uuid: projectUuid,
},
},
},
uuid: deviceUuid,
isActive: true,
},