mirror of
https://github.com/SyncrowIOT/backend.git
synced 2026-10-25 21:57:55 +00:00
Refactor/space management (#404)
* refactor: reducing used queries on get communities (#385) * refactor: fix create space logic (#394) * Remove unique constraint on subspace and product in SubspaceProductAllocationEntity; update product relation to nullable in NewTagEntity * refactor: fix create space logic * device model updated to include the fixes and final columns * updated space models to include suggested fixes, update final logic and column names * task: removing old references of the old tag-product relation * task: remove old use of tags * task: remove old tag & tag model usage * refactor: delete space * task: remove unused functions * fix lint rule
This commit is contained in:
@@ -1,39 +1,46 @@
|
||||
import { ORPHAN_SPACE_NAME } from './../../../libs/common/src/constants/orphan-constant';
|
||||
import { ProductRepository } from './../../../libs/common/src/modules/product/repositories/product.repository';
|
||||
import { AUTOMATION_CONFIG } from '@app/common/constants/automation.enum';
|
||||
import { BatchDeviceTypeEnum } from '@app/common/constants/batch-device.enum';
|
||||
import { BatteryStatus } from '@app/common/constants/battery-status.enum';
|
||||
import { DeviceStatuses } from '@app/common/constants/device-status.enum';
|
||||
import { DeviceTypeEnum } from '@app/common/constants/device-type.enum';
|
||||
import { CommonErrorCodes } from '@app/common/constants/error-codes.enum';
|
||||
import { ProductType } from '@app/common/constants/product-type.enum';
|
||||
import { SceneSwitchesTypeEnum } from '@app/common/constants/scene-switch-type.enum';
|
||||
import { BaseResponseDto } from '@app/common/dto/base.response.dto';
|
||||
import { SuccessResponseDto } from '@app/common/dto/success.response.dto';
|
||||
import { DeviceStatusFirebaseService } from '@app/common/firebase/devices-status/services/devices-status.service';
|
||||
import { convertKeysToCamelCase } from '@app/common/helper/camelCaseConverter';
|
||||
import { TuyaService } from '@app/common/integrations/tuya/services/tuya.service';
|
||||
import { CommunityRepository } from '@app/common/modules/community/repositories';
|
||||
import { DeviceEntity } from '@app/common/modules/device/entities';
|
||||
import { DeviceRepository } from '@app/common/modules/device/repositories';
|
||||
import { ProjectEntity } from '@app/common/modules/project/entities';
|
||||
import { ProjectRepository } from '@app/common/modules/project/repositiories';
|
||||
import { SceneDeviceRepository } from '@app/common/modules/scene-device/repositories';
|
||||
import { SpaceEntity } from '@app/common/modules/space/entities/space.entity';
|
||||
import { SpaceRepository } from '@app/common/modules/space/repositories';
|
||||
import { addSpaceUuidToDevices } from '@app/common/util/device-utils';
|
||||
import {
|
||||
Injectable,
|
||||
HttpException,
|
||||
HttpStatus,
|
||||
NotFoundException,
|
||||
BadRequestException,
|
||||
forwardRef,
|
||||
HttpException,
|
||||
HttpStatus,
|
||||
Inject,
|
||||
Injectable,
|
||||
NotFoundException,
|
||||
} from '@nestjs/common';
|
||||
import { TuyaContext } from '@tuya/tuya-connector-nodejs';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { TuyaContext } from '@tuya/tuya-connector-nodejs';
|
||||
import { AddAutomationDto } from 'src/automation/dtos';
|
||||
import { SceneService } from 'src/scene/services';
|
||||
import { In, Not, QueryRunner } from 'typeorm';
|
||||
import { ProjectParam } from '../dtos';
|
||||
import {
|
||||
AddDeviceDto,
|
||||
AddSceneToFourSceneDeviceDto,
|
||||
UpdateDeviceDto,
|
||||
AssignDeviceToSpaceDto,
|
||||
UpdateDeviceDto,
|
||||
} from '../dtos/add.device.dto';
|
||||
import {
|
||||
DeviceInstructionResponse,
|
||||
GetDeviceDetailsFunctionsInterface,
|
||||
GetDeviceDetailsFunctionsStatusInterface,
|
||||
GetDeviceDetailsInterface,
|
||||
GetMacAddressInterface,
|
||||
GetPowerClampFunctionsStatusInterface,
|
||||
controlDeviceInterface,
|
||||
getDeviceLogsInterface,
|
||||
updateDeviceFirmwareInterface,
|
||||
} from '../interfaces/get.device.interface';
|
||||
import {
|
||||
GetDeviceBySpaceUuidDto,
|
||||
GetDeviceLogsDto,
|
||||
GetDevicesBySpaceOrCommunityDto,
|
||||
GetDoorLockDevices,
|
||||
} from '../dtos/get.device.dto';
|
||||
import {
|
||||
BatchControlDevicesDto,
|
||||
BatchFactoryResetDevicesDto,
|
||||
@@ -41,33 +48,29 @@ import {
|
||||
ControlDeviceDto,
|
||||
GetSceneFourSceneDeviceDto,
|
||||
} from '../dtos/control.device.dto';
|
||||
import { convertKeysToCamelCase } from '@app/common/helper/camelCaseConverter';
|
||||
import { DeviceRepository } from '@app/common/modules/device/repositories';
|
||||
import { In, Not, QueryRunner } from 'typeorm';
|
||||
import { ProductType } from '@app/common/constants/product-type.enum';
|
||||
import { SpaceRepository } from '@app/common/modules/space/repositories';
|
||||
import { DeviceStatusFirebaseService } from '@app/common/firebase/devices-status/services/devices-status.service';
|
||||
import { DeviceStatuses } from '@app/common/constants/device-status.enum';
|
||||
import { CommonErrorCodes } from '@app/common/constants/error-codes.enum';
|
||||
import { BatteryStatus } from '@app/common/constants/battery-status.enum';
|
||||
import { SceneService } from 'src/scene/services';
|
||||
import { AddAutomationDto } from 'src/automation/dtos';
|
||||
import { TuyaService } from '@app/common/integrations/tuya/services/tuya.service';
|
||||
import { SceneDeviceRepository } from '@app/common/modules/scene-device/repositories';
|
||||
import { SceneSwitchesTypeEnum } from '@app/common/constants/scene-switch-type.enum';
|
||||
import { AUTOMATION_CONFIG } from '@app/common/constants/automation.enum';
|
||||
import { DeviceSceneParamDto } from '../dtos/device.param.dto';
|
||||
import { BaseResponseDto } from '@app/common/dto/base.response.dto';
|
||||
import { SuccessResponseDto } from '@app/common/dto/success.response.dto';
|
||||
import { DeleteSceneFromSceneDeviceDto } from '../dtos/delete.device.dto';
|
||||
import { DeviceEntity } from '@app/common/modules/device/entities';
|
||||
import { SpaceEntity } from '@app/common/modules/space/entities/space.entity';
|
||||
import { ProjectRepository } from '@app/common/modules/project/repositiories';
|
||||
import { ProjectParam } from '../dtos';
|
||||
import { BatchDeviceTypeEnum } from '@app/common/constants/batch-device.enum';
|
||||
import { DeviceTypeEnum } from '@app/common/constants/device-type.enum';
|
||||
import { CommunityRepository } from '@app/common/modules/community/repositories';
|
||||
import { addSpaceUuidToDevices } from '@app/common/util/device-utils';
|
||||
import { DeviceSceneParamDto } from '../dtos/device.param.dto';
|
||||
import {
|
||||
GetDeviceLogsDto,
|
||||
GetDevicesBySpaceOrCommunityDto,
|
||||
GetDoorLockDevices,
|
||||
} from '../dtos/get.device.dto';
|
||||
import {
|
||||
controlDeviceInterface,
|
||||
DeviceInstructionResponse,
|
||||
GetDeviceDetailsFunctionsInterface,
|
||||
GetDeviceDetailsFunctionsStatusInterface,
|
||||
GetDeviceDetailsInterface,
|
||||
getDeviceLogsInterface,
|
||||
GetMacAddressInterface,
|
||||
GetPowerClampFunctionsStatusInterface,
|
||||
updateDeviceFirmwareInterface,
|
||||
} from '../interfaces/get.device.interface';
|
||||
import {
|
||||
ORPHAN_COMMUNITY_NAME,
|
||||
ORPHAN_SPACE_NAME,
|
||||
} from './../../../libs/common/src/constants/orphan-constant';
|
||||
import { ProductRepository } from './../../../libs/common/src/modules/product/repositories/product.repository';
|
||||
|
||||
@Injectable()
|
||||
export class DeviceService {
|
||||
@@ -198,46 +201,6 @@ export class DeviceService {
|
||||
}
|
||||
}
|
||||
|
||||
async getDevicesBySpaceId(
|
||||
getDeviceBySpaceUuidDto: GetDeviceBySpaceUuidDto,
|
||||
): Promise<GetDeviceDetailsInterface[]> {
|
||||
try {
|
||||
const devices = await this.deviceRepository.find({
|
||||
where: {
|
||||
spaceDevice: { uuid: getDeviceBySpaceUuidDto.spaceUuid },
|
||||
isActive: true,
|
||||
},
|
||||
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(
|
||||
'Error fetching devices by space',
|
||||
HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
}
|
||||
async transferDeviceInSpaces(
|
||||
assignDeviceToSpaceDto: AssignDeviceToSpaceDto,
|
||||
projectUuid: string,
|
||||
@@ -1199,39 +1162,6 @@ export class DeviceService {
|
||||
}
|
||||
}
|
||||
|
||||
async getFullSpaceHierarchy(
|
||||
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 },
|
||||
relations: ['parent', 'children'],
|
||||
});
|
||||
|
||||
// Fetch only the ancestors of the target space
|
||||
const ancestors = await this.fetchAncestors(targetSpace);
|
||||
|
||||
// Optionally, fetch descendants if required
|
||||
const descendants = await this.fetchDescendants(targetSpace);
|
||||
|
||||
const fullHierarchy = [...ancestors, targetSpace, ...descendants].map(
|
||||
(space) => ({
|
||||
uuid: space.uuid,
|
||||
spaceName: space.spaceName,
|
||||
}),
|
||||
);
|
||||
|
||||
return fullHierarchy;
|
||||
} catch (error) {
|
||||
console.error('Error fetching space hierarchy:', error.message);
|
||||
throw new HttpException(
|
||||
'Error fetching space hierarchy',
|
||||
HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async getPowerClampInstructionStatus(deviceDetails: any) {
|
||||
try {
|
||||
const deviceStatus = await this.getPowerClampInstructionStatusTuya(
|
||||
@@ -1331,27 +1261,6 @@ export class DeviceService {
|
||||
return ancestors.reverse();
|
||||
}
|
||||
|
||||
private async fetchDescendants(space: SpaceEntity): Promise<SpaceEntity[]> {
|
||||
const descendants: SpaceEntity[] = [];
|
||||
|
||||
// Fetch the immediate children of the current space
|
||||
const children = await this.spaceRepository.find({
|
||||
where: { parent: { uuid: space.uuid } },
|
||||
relations: ['children'], // To continue fetching downwards
|
||||
});
|
||||
|
||||
for (const child of children) {
|
||||
// Add the child to the descendants list
|
||||
descendants.push(child);
|
||||
|
||||
// Recursively fetch the child's descendants
|
||||
const childDescendants = await this.fetchDescendants(child);
|
||||
descendants.push(...childDescendants);
|
||||
}
|
||||
|
||||
return descendants;
|
||||
}
|
||||
|
||||
async addSceneToSceneDevice(
|
||||
deviceUuid: string,
|
||||
addSceneToFourSceneDeviceDto: AddSceneToFourSceneDeviceDto,
|
||||
@@ -1654,22 +1563,6 @@ export class DeviceService {
|
||||
}
|
||||
}
|
||||
|
||||
async moveDevicesToSpace(
|
||||
targetSpace: SpaceEntity,
|
||||
deviceIds: string[],
|
||||
): Promise<void> {
|
||||
if (!deviceIds || deviceIds.length === 0) {
|
||||
throw new HttpException(
|
||||
'No device IDs provided for transfer',
|
||||
HttpStatus.BAD_REQUEST,
|
||||
);
|
||||
}
|
||||
|
||||
await this.deviceRepository.update(
|
||||
{ uuid: In(deviceIds) },
|
||||
{ spaceDevice: targetSpace },
|
||||
);
|
||||
}
|
||||
async getDoorLockDevices(projectUuid: string) {
|
||||
await this.validateProject(projectUuid);
|
||||
|
||||
@@ -1860,4 +1753,39 @@ export class DeviceService {
|
||||
|
||||
return allDevices;
|
||||
}
|
||||
|
||||
async addDevicesToOrphanSpace(
|
||||
space: SpaceEntity,
|
||||
project: ProjectEntity,
|
||||
queryRunner: QueryRunner,
|
||||
) {
|
||||
const spaceRepository = queryRunner.manager.getRepository(SpaceEntity);
|
||||
const deviceRepository = queryRunner.manager.getRepository(DeviceEntity);
|
||||
try {
|
||||
const orphanSpace = await spaceRepository.findOne({
|
||||
where: {
|
||||
community: {
|
||||
name: `${ORPHAN_COMMUNITY_NAME}-${project.name}`,
|
||||
},
|
||||
spaceName: ORPHAN_SPACE_NAME,
|
||||
},
|
||||
});
|
||||
|
||||
if (!orphanSpace) {
|
||||
throw new HttpException(
|
||||
`Orphan space not found in community ${project.name}`,
|
||||
HttpStatus.NOT_FOUND,
|
||||
);
|
||||
}
|
||||
|
||||
await deviceRepository.update(
|
||||
{ uuid: In(space.devices.map((device) => device.uuid)) },
|
||||
{ spaceDevice: orphanSpace },
|
||||
);
|
||||
} catch (error) {
|
||||
throw new Error(
|
||||
`Failed to add devices to orphan spaces: ${error.message}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user