Merge branch 'dev' of https://github.com/SyncrowIOT/backend into feature/space-management

This commit is contained in:
hannathkadher
2024-10-30 23:08:51 +04:00
35 changed files with 611 additions and 42 deletions

View File

@ -1,4 +1,5 @@
import {
BadRequestException,
Body,
Controller,
Get,
@ -16,6 +17,7 @@ import { ForgetPasswordDto, UserOtpDto, VerifyOtpDto } from '../dtos';
import { RefreshTokenGuard } from '@app/common/guards/jwt-refresh.auth.guard';
import { SuperAdminRoleGuard } from 'src/guards/super.admin.role.guard';
import { EnableDisableStatusEnum } from '@app/common/constants/days.enum';
import { OtpType } from '@app/common/constants/otp-type.enum';
@Controller({
version: EnableDisableStatusEnum.ENABLED,
@ -74,12 +76,27 @@ export class UserAuthController {
@Post('user/forget-password')
async forgetPassword(@Body() forgetPasswordDto: ForgetPasswordDto) {
await this.userAuthService.forgetPassword(forgetPasswordDto);
return {
statusCode: HttpStatus.OK,
const otpResult = await this.userAuthService.verifyOTP(
{
otpCode: forgetPasswordDto.otpCode,
email: forgetPasswordDto.email,
type: OtpType.PASSWORD,
},
true,
);
if (otpResult) {
await this.userAuthService.forgetPassword(forgetPasswordDto);
return {
statusCode: HttpStatus.OK,
data: {},
message: 'Password changed successfully',
};
}
throw new BadRequestException({
statusCode: HttpStatus.BAD_REQUEST,
data: {},
message: 'Password changed successfully',
};
message: 'Otp is incorrect',
});
}
@ApiBearerAuth()

View File

@ -22,4 +22,9 @@ export class ForgetPasswordDto {
'password must be at least 8 characters long and include at least one uppercase letter, one lowercase letter, one numeric digit, and one special character.',
})
public password: string;
@ApiProperty()
@IsString()
@IsNotEmpty()
public otpCode: string;
}

View File

@ -18,7 +18,6 @@ import * as argon2 from 'argon2';
import { differenceInSeconds } from '@app/common/helper/differenceInSeconds';
import { LessThan, MoreThan } from 'typeorm';
import { ConfigService } from '@nestjs/config';
import { UUID } from 'typeorm/driver/mongodb/bson.typings';
@Injectable()
export class UserAuthService {
@ -211,7 +210,7 @@ export class UserAuthService {
}
const otpCode = Math.floor(100000 + Math.random() * 900000).toString();
const expiryTime = new Date();
expiryTime.setMinutes(expiryTime.getMinutes() + 1);
expiryTime.setMinutes(expiryTime.getMinutes() + 10);
await this.otpRepository.save({
email: data.email,
otpCode,
@ -233,7 +232,10 @@ export class UserAuthService {
return { otpCode, cooldown };
}
async verifyOTP(data: VerifyOtpDto): Promise<boolean> {
async verifyOTP(
data: VerifyOtpDto,
fromNewPassword: boolean = false,
): Promise<boolean> {
const otp = await this.otpRepository.findOne({
where: { email: data.email, type: data.type },
});
@ -258,7 +260,9 @@ export class UserAuthService {
await this.otpRepository.delete(otp.uuid);
throw new BadRequestException('OTP expired');
}
if (fromNewPassword) {
await this.otpRepository.delete(otp.uuid);
}
if (data.type == OtpType.VERIFICATION) {
await this.userRepository.update(
{ email: data.email },

View File

@ -173,4 +173,14 @@ export class DeviceController {
batchFactoryResetDevicesDto,
);
}
@ApiBearerAuth()
@UseGuards(JwtAuthGuard)
@Get(':powerClampUuid/power-clamp/status')
async getPowerClampInstructionStatus(
@Param('powerClampUuid') powerClampUuid: string,
) {
return await this.deviceService.getPowerClampInstructionStatus(
powerClampUuid,
);
}
}

View File

@ -70,3 +70,10 @@ export interface getDeviceLogsInterface {
endTime: string;
deviceUuid?: string;
}
export interface GetPowerClampFunctionsStatusInterface {
result: {
properties: [];
};
success: boolean;
msg: string;
}

View File

@ -14,6 +14,7 @@ import {
GetDeviceDetailsFunctionsInterface,
GetDeviceDetailsFunctionsStatusInterface,
GetDeviceDetailsInterface,
GetPowerClampFunctionsStatusInterface,
controlDeviceInterface,
getDeviceLogsInterface,
updateDeviceFirmwareInterface,
@ -985,7 +986,6 @@ export class DeviceService {
space: SpaceEntity,
): Promise<{ uuid: string; spaceName: string }[]> {
try {
// Fetch only the relevant spaces, starting with the target space
const targetSpace = await this.spaceRepository.findOne({
where: { uuid: space.uuid },
@ -1015,6 +1015,84 @@ export class DeviceService {
}
}
async getPowerClampInstructionStatus(powerClampUuid: string) {
try {
const deviceDetails = await this.getDeviceByDeviceUuid(powerClampUuid);
if (!deviceDetails) {
throw new NotFoundException('Device Not Found');
} else if (deviceDetails.productDevice.prodType !== ProductType.PC) {
throw new BadRequestException('This is not a power clamp device');
}
const deviceStatus = await this.getPowerClampInstructionStatusTuya(
deviceDetails.deviceTuyaUuid,
);
const statusList = deviceStatus.result.properties as {
code: string;
value: any;
}[];
const groupedStatus = statusList.reduce(
(acc, currentStatus) => {
const { code } = currentStatus;
if (code.endsWith('A')) {
acc.phaseA.push(currentStatus);
} else if (code.endsWith('B')) {
acc.phaseB.push(currentStatus);
} else if (code.endsWith('C')) {
acc.phaseC.push(currentStatus);
} else {
acc.general.push(currentStatus);
}
return acc;
},
{
phaseA: [] as { code: string; value: any }[],
phaseB: [] as { code: string; value: any }[],
phaseC: [] as { code: string; value: any }[],
general: [] as { code: string; value: any }[],
},
);
return {
productUuid: deviceDetails.productDevice.uuid,
productType: deviceDetails.productDevice.prodType,
status: {
phaseA: groupedStatus.phaseA,
phaseB: groupedStatus.phaseB,
phaseC: groupedStatus.phaseC,
general: groupedStatus.general,
},
};
} catch (error) {
throw new HttpException(
error.message || 'Error fetching power clamp functions status',
error.status || HttpStatus.INTERNAL_SERVER_ERROR,
);
}
}
async getPowerClampInstructionStatusTuya(
deviceUuid: string,
): Promise<GetPowerClampFunctionsStatusInterface> {
try {
const path = `/v2.0/cloud/thing/${deviceUuid}/shadow/properties`;
const response = await this.tuya.request({
method: 'GET',
path,
query: {
device_ids: deviceUuid,
},
});
const camelCaseResponse = convertKeysToCamelCase(response);
return camelCaseResponse as GetPowerClampFunctionsStatusInterface;
} catch (error) {
throw new HttpException(
'Error fetching power clamp functions status from Tuya',
HttpStatus.INTERNAL_SERVER_ERROR,
);
}
}
private async fetchAncestors(space: SpaceEntity): Promise<SpaceEntity[]> {
const ancestors: SpaceEntity[] = [];

View File

@ -10,6 +10,7 @@ import { DeviceService } from 'src/device/services';
import { ProductRepository } from '@app/common/modules/product/repositories';
import { DeviceStatusFirebaseService } from '@app/common/firebase/devices-status/services/devices-status.service';
import { SpaceRepository } from '@app/common/modules/space/repositories';
import { DeviceStatusLogRepository } from '@app/common/modules/device-status-log/repositories';
@Module({
imports: [ConfigModule, DeviceRepositoryModule],
controllers: [DoorLockController],
@ -22,6 +23,7 @@ import { SpaceRepository } from '@app/common/modules/space/repositories';
ProductRepository,
DeviceStatusFirebaseService,
SpaceRepository,
DeviceStatusLogRepository,
],
exports: [DoorLockService],
})

View File

@ -8,10 +8,16 @@ import {
Param,
Post,
Put,
Query,
UseGuards,
} from '@nestjs/common';
import { ApiTags, ApiBearerAuth } from '@nestjs/swagger';
import { AddSceneTapToRunDto, UpdateSceneTapToRunDto } from '../dtos/scene.dto';
import {
AddSceneIconDto,
AddSceneTapToRunDto,
GetSceneDto,
UpdateSceneTapToRunDto,
} from '../dtos/scene.dto';
import { JwtAuthGuard } from '@app/common/guards/jwt.auth.guard';
import { EnableDisableStatusEnum } from '@app/common/constants/days.enum';
import { DeleteSceneParamDto, SceneParamDto, SpaceParamDto } from '../dtos';
@ -41,9 +47,13 @@ export class SceneController {
@ApiBearerAuth()
@UseGuards(JwtAuthGuard)
@Get('tap-to-run/:spaceUuid')
async getTapToRunSceneByUnit(@Param() param: SpaceParamDto) {
async getTapToRunSceneByUnit(
@Param() param: SpaceParamDto,
@Query() inHomePage: GetSceneDto,
) {
const tapToRunScenes = await this.sceneService.getTapToRunSceneByUnit(
param.spaceUuid,
inHomePage,
);
return tapToRunScenes;
}
@ -98,4 +108,23 @@ export class SceneController {
data: tapToRunScene,
};
}
@ApiBearerAuth()
@UseGuards(JwtAuthGuard)
@Post('icon')
async addSceneIcon(@Body() addSceneIconDto: AddSceneIconDto) {
const tapToRunScene = await this.sceneService.addSceneIcon(addSceneIconDto);
return {
statusCode: HttpStatus.CREATED,
success: true,
message: 'Icon added successfully',
data: tapToRunScene,
};
}
@ApiBearerAuth()
@UseGuards(JwtAuthGuard)
@Get('icon')
async getAllIcons() {
const icons = await this.sceneService.getAllIcons();
return icons;
}
}

View File

@ -6,8 +6,10 @@ import {
ValidateNested,
IsOptional,
IsNumber,
IsBoolean,
} from 'class-validator';
import { Type } from 'class-transformer';
import { Transform, Type } from 'class-transformer';
import { BooleanValues } from '@app/common/constants/boolean-values.enum';
class ExecutorProperty {
@ApiProperty({
@ -71,6 +73,20 @@ export class AddSceneTapToRunDto {
@IsNotEmpty()
public spaceUuid: string;
@ApiProperty({
description: 'Icon UUID',
required: false,
})
@IsString()
@IsOptional()
public iconUuid: string;
@ApiProperty({
description: 'show in home page',
required: true,
})
@IsBoolean()
@IsNotEmpty()
public showInHomePage: boolean;
@ApiProperty({
description: 'Scene name',
required: true,
@ -109,7 +125,20 @@ export class UpdateSceneTapToRunDto {
@IsString()
@IsNotEmpty()
public sceneName: string;
@ApiProperty({
description: 'Icon UUID',
required: true,
})
@IsString()
@IsNotEmpty()
public iconUuid: string;
@ApiProperty({
description: 'show in home page',
required: true,
})
@IsBoolean()
@IsNotEmpty()
public showInHomePage: boolean;
@ApiProperty({
description: 'Decision expression',
required: true,
@ -132,3 +161,30 @@ export class UpdateSceneTapToRunDto {
Object.assign(this, dto);
}
}
export class AddSceneIconDto {
@ApiProperty({
description: 'Icon',
required: true,
})
@IsString()
@IsNotEmpty()
public icon: string;
constructor(dto: Partial<AddSceneIconDto>) {
Object.assign(this, dto);
}
}
export class GetSceneDto {
@ApiProperty({
example: true,
description: 'showInHomePage',
required: true,
default: false,
})
@IsNotEmpty()
@IsBoolean()
@Transform((value) => {
return value.obj.showInHomePage === BooleanValues.TRUE;
})
public showInHomePage: boolean = false;
}

View File

@ -8,6 +8,10 @@ import { DeviceService } from 'src/device/services';
import { DeviceRepository } from '@app/common/modules/device/repositories';
import { ProductRepository } from '@app/common/modules/product/repositories';
import { DeviceStatusFirebaseModule } from '@app/common/firebase/devices-status/devices-status.module';
import {
SceneIconRepository,
SceneRepository,
} from '@app/common/modules/scene/repositories';
@Module({
imports: [ConfigModule, SpaceRepositoryModule, DeviceStatusFirebaseModule],
@ -18,6 +22,8 @@ import { DeviceStatusFirebaseModule } from '@app/common/firebase/devices-status/
DeviceService,
DeviceRepository,
ProductRepository,
SceneIconRepository,
SceneRepository,
],
exports: [SceneService],
})

View File

@ -6,8 +6,10 @@ import {
} from '@nestjs/common';
import { SpaceRepository } from '@app/common/modules/space/repositories';
import {
AddSceneIconDto,
AddSceneTapToRunDto,
DeleteSceneParamDto,
GetSceneDto,
UpdateSceneTapToRunDto,
} from '../dtos';
import { ConfigService } from '@nestjs/config';
@ -17,11 +19,15 @@ import { DeviceService } from 'src/device/services';
import {
AddTapToRunSceneInterface,
DeleteTapToRunSceneInterface,
GetTapToRunSceneByUnitInterface,
SceneDetailsResult,
} from '../interface/scene.interface';
import { convertKeysToCamelCase } from '@app/common/helper/camelCaseConverter';
import { ActionExecutorEnum } from '@app/common/constants/automation.enum';
import {
SceneIconRepository,
SceneRepository,
} from '@app/common/modules/scene/repositories';
import { SceneIconType } from '@app/common/constants/secne-icon-type.enum';
@Injectable()
export class SceneService {
@ -29,6 +35,8 @@ export class SceneService {
constructor(
private readonly configService: ConfigService,
private readonly spaceRepository: SpaceRepository,
private readonly sceneIconRepository: SceneIconRepository,
private readonly sceneRepository: SceneRepository,
private readonly deviceService: DeviceService,
) {
const accessKey = this.configService.get<string>('auth-config.ACCESS_KEY');
@ -44,6 +52,7 @@ export class SceneService {
async addTapToRunScene(
addSceneTapToRunDto: AddSceneTapToRunDto,
spaceTuyaId = null,
spaceUuid?: string,
) {
try {
let unitSpaceTuyaId;
@ -91,6 +100,21 @@ export class SceneService {
});
if (!response.success) {
throw new HttpException(response.msg, HttpStatus.BAD_REQUEST);
} else {
const defaultSceneIcon = await this.sceneIconRepository.findOne({
where: { iconType: SceneIconType.Default },
});
await this.sceneRepository.save({
sceneTuyaUuid: response.result.id,
sceneIcon: {
uuid: addSceneTapToRunDto.iconUuid
? addSceneTapToRunDto.iconUuid
: defaultSceneIcon.uuid,
},
showInHomePage: addSceneTapToRunDto.showInHomePage,
unitUuid: spaceUuid ? spaceUuid : addSceneTapToRunDto.spaceUuid,
});
}
return {
id: response.result.id,
@ -136,33 +160,32 @@ export class SceneService {
}
}
}
async getTapToRunSceneByUnit(spaceUuid: string) {
async getTapToRunSceneByUnit(unitUuid: string, inHomePage: GetSceneDto) {
try {
const space = await this.getSpaceByUuid(spaceUuid);
if (!space.spaceTuyaUuid) {
throw new BadRequestException(`Invalid space UUID ${spaceUuid}`);
}
const showInHomePage = inHomePage?.showInHomePage;
const path = `/v2.0/cloud/scene/rule?space_id=${space.spaceTuyaUuid}&type=scene`;
const response: GetTapToRunSceneByUnitInterface = await this.tuya.request(
{
method: 'GET',
path,
const scenesData = await this.sceneRepository.find({
where: {
unitUuid,
...(showInHomePage ? { showInHomePage } : {}),
},
});
const scenes = await Promise.all(
scenesData.map(async (scene) => {
const sceneData = await this.getTapToRunSceneDetails(
scene.sceneTuyaUuid,
false,
);
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const { actions, ...rest } = sceneData;
return {
...rest,
};
}),
);
if (!response.success) {
throw new HttpException(response.msg, HttpStatus.BAD_REQUEST);
}
return response.result.list.map((item) => {
return {
id: item.id,
name: item.name,
status: item.status,
type: 'tap_to_run',
};
});
return scenes;
} catch (err) {
if (err instanceof BadRequestException) {
throw err; // Re-throw BadRequestException
@ -196,6 +219,8 @@ export class SceneService {
if (!response.success) {
throw new HttpException('Scene not found', HttpStatus.NOT_FOUND);
} else {
await this.sceneRepository.delete({ sceneTuyaUuid: sceneUuid });
}
return response;
@ -273,11 +298,17 @@ export class SceneService {
}
}
}
const scene = await this.sceneRepository.findOne({
where: { sceneTuyaUuid: sceneId },
relations: ['sceneIcon'],
});
return {
id: responseData.id,
name: responseData.name,
status: responseData.status,
icon: scene.sceneIcon?.icon,
iconUuid: scene.sceneIcon?.uuid,
showInHome: scene.showInHomePage,
type: 'tap_to_run',
actions: actions,
...(withSpaceId && { spaceId: responseData.spaceId }),
@ -334,10 +365,17 @@ export class SceneService {
const addSceneTapToRunDto: AddSceneTapToRunDto = {
...updateSceneTapToRunDto,
spaceUuid: null,
iconUuid: updateSceneTapToRunDto.iconUuid,
showInHomePage: updateSceneTapToRunDto.showInHomePage,
};
const scene = await this.sceneRepository.findOne({
where: { sceneTuyaUuid: sceneUuid },
});
const newTapToRunScene = await this.addTapToRunScene(
addSceneTapToRunDto,
spaceTuyaId.spaceId,
scene.unitUuid,
);
const param: DeleteSceneParamDto = {
@ -347,6 +385,18 @@ export class SceneService {
if (newTapToRunScene.id) {
await this.deleteTapToRunScene(null, param);
await this.sceneRepository.update(
{ sceneTuyaUuid: sceneUuid },
{
sceneTuyaUuid: newTapToRunScene.id,
showInHomePage: addSceneTapToRunDto.showInHomePage,
sceneIcon: {
uuid: addSceneTapToRunDto.iconUuid,
},
unitUuid: scene.unitUuid,
},
);
return newTapToRunScene;
}
} catch (err) {
@ -360,4 +410,38 @@ export class SceneService {
}
}
}
async addSceneIcon(addSceneIconDto: AddSceneIconDto) {
try {
const icon = await this.sceneIconRepository.save({
icon: addSceneIconDto.icon,
});
return icon;
} catch (err) {
throw new HttpException(
{
status: HttpStatus.INTERNAL_SERVER_ERROR,
error: 'Failed to add scene icon',
message: err.message || 'Unexpected error occurred',
},
HttpStatus.INTERNAL_SERVER_ERROR,
);
}
}
async getAllIcons() {
try {
const icons = await this.sceneIconRepository.find();
return icons;
} catch (err) {
// Improved error handling
throw new HttpException(
{
statusCode: HttpStatus.INTERNAL_SERVER_ERROR,
message: 'Failed to fetch icons',
error:
err.message || 'An unexpected error occurred while fetching icons',
},
HttpStatus.INTERNAL_SERVER_ERROR,
);
}
}
}

View File

@ -12,6 +12,7 @@ import { ProductRepository } from '@app/common/modules/product/repositories';
import { DeviceStatusFirebaseService } from '@app/common/firebase/devices-status/services/devices-status.service';
import { SpaceRepository } from '@app/common/modules/space/repositories';
import { VisitorPasswordRepository } from '@app/common/modules/visitor-password/repositories';
import { DeviceStatusLogRepository } from '@app/common/modules/device-status-log/repositories';
@Module({
imports: [ConfigModule, DeviceRepositoryModule, DoorLockModule],
controllers: [VisitorPasswordController],
@ -25,6 +26,7 @@ import { VisitorPasswordRepository } from '@app/common/modules/visitor-password/
SpaceRepository,
DeviceRepository,
VisitorPasswordRepository,
DeviceStatusLogRepository,
],
exports: [VisitorPasswordService],
})