mirror of
https://github.com/SyncrowIOT/backend.git
synced 2025-07-10 15:17:41 +00:00
Compare commits
3 Commits
add-queue-
...
DATA-occup
Author | SHA1 | Date | |
---|---|---|---|
6282f402db | |||
76f3d6369a | |||
14b7f4ab6b |
@ -21,7 +21,6 @@ module.exports = {
|
||||
'@typescript-eslint/explicit-function-return-type': 'off',
|
||||
'@typescript-eslint/explicit-module-boundary-types': 'off',
|
||||
'@typescript-eslint/no-explicit-any': 'off',
|
||||
"@typescript-eslint/no-unused-vars": 'warn',
|
||||
},
|
||||
settings: {
|
||||
'import/resolver': {
|
||||
|
@ -524,20 +524,6 @@ export class ControllerRoute {
|
||||
'This endpoint retrieves the occupancy heat map data based on the provided parameters.';
|
||||
};
|
||||
};
|
||||
static AQI = class {
|
||||
public static readonly ROUTE = 'aqi';
|
||||
|
||||
static ACTIONS = class {
|
||||
public static readonly GET_AQI_RANGE_DATA_SUMMARY = 'Get AQI range data';
|
||||
public static readonly GET_AQI_RANGE_DATA_DESCRIPTION =
|
||||
'This endpoint retrieves the AQI (Air Quality Index) range data based on the provided parameters.';
|
||||
|
||||
public static readonly GET_AQI_DISTRIBUTION_DATA_SUMMARY =
|
||||
'Get AQI distribution data';
|
||||
public static readonly GET_AQI_DISTRIBUTION_DATA_DESCRIPTION =
|
||||
'This endpoint retrieves the AQI (Air Quality Index) distribution data based on the provided parameters.';
|
||||
};
|
||||
};
|
||||
static DEVICE = class {
|
||||
public static readonly ROUTE = 'devices';
|
||||
|
||||
|
@ -1,8 +0,0 @@
|
||||
export enum PollutantType {
|
||||
AQI = 'aqi',
|
||||
PM25 = 'pm25',
|
||||
PM10 = 'pm10',
|
||||
VOC = 'voc',
|
||||
CO2 = 'co2',
|
||||
CH2O = 'ch2o',
|
||||
}
|
@ -19,5 +19,4 @@ export enum ProductType {
|
||||
FOUR_S = '4S',
|
||||
SIX_S = '6S',
|
||||
SOS = 'SOS',
|
||||
AQI = 'AQI',
|
||||
}
|
||||
|
@ -1,31 +1,51 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { ConfigModule, ConfigService } from '@nestjs/config';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { DeviceEntity } from '../modules/device/entities';
|
||||
import { PermissionTypeEntity } from '../modules/permission/entities';
|
||||
import { ProductEntity } from '../modules/product/entities';
|
||||
import { SnakeNamingStrategy } from './strategies';
|
||||
import { UserEntity } from '../modules/user/entities/user.entity';
|
||||
import { UserSessionEntity } from '../modules/session/entities/session.entity';
|
||||
import { UserOtpEntity } from '../modules/user/entities';
|
||||
import { UserEntity } from '../modules/user/entities/user.entity';
|
||||
import { SnakeNamingStrategy } from './strategies';
|
||||
import { ProductEntity } from '../modules/product/entities';
|
||||
import { DeviceEntity } from '../modules/device/entities';
|
||||
import { PermissionTypeEntity } from '../modules/permission/entities';
|
||||
|
||||
import { TypeOrmWinstonLogger } from '@app/common/logger/services/typeorm.logger';
|
||||
import { createLogger } from 'winston';
|
||||
import { winstonLoggerOptions } from '../logger/services/winston.logger';
|
||||
import { AqiSpaceDailyPollutantStatsEntity } from '../modules/aqi/entities';
|
||||
import { AutomationEntity } from '../modules/automation/entities';
|
||||
import { ClientEntity } from '../modules/client/entities';
|
||||
import { UserSpaceEntity } from '../modules/user/entities';
|
||||
import { DeviceUserPermissionEntity } from '../modules/device/entities';
|
||||
import { RoleTypeEntity } from '../modules/role-type/entities';
|
||||
import { UserNotificationEntity } from '../modules/user/entities';
|
||||
import { DeviceNotificationEntity } from '../modules/device/entities';
|
||||
import { RegionEntity } from '../modules/region/entities';
|
||||
import { TimeZoneEntity } from '../modules/timezone/entities';
|
||||
import { VisitorPasswordEntity } from '../modules/visitor-password/entities';
|
||||
import { CommunityEntity } from '../modules/community/entities';
|
||||
import { DeviceStatusLogEntity } from '../modules/device-status-log/entities';
|
||||
import { SceneEntity, SceneIconEntity } from '../modules/scene/entities';
|
||||
import { SceneDeviceEntity } from '../modules/scene-device/entities';
|
||||
import { ProjectEntity } from '../modules/project/entities';
|
||||
import {
|
||||
DeviceNotificationEntity,
|
||||
DeviceUserPermissionEntity,
|
||||
} from '../modules/device/entities';
|
||||
SpaceModelEntity,
|
||||
SubspaceModelEntity,
|
||||
TagModel,
|
||||
SpaceModelProductAllocationEntity,
|
||||
SubspaceModelProductAllocationEntity,
|
||||
} from '../modules/space-model/entities';
|
||||
import {
|
||||
InviteUserEntity,
|
||||
InviteUserSpaceEntity,
|
||||
} from '../modules/Invite-user/entities';
|
||||
import { SpaceDailyOccupancyDurationEntity } from '../modules/occupancy/entities';
|
||||
import { InviteSpaceEntity } from '../modules/space/entities/invite-space.entity';
|
||||
import { AutomationEntity } from '../modules/automation/entities';
|
||||
import { SpaceProductAllocationEntity } from '../modules/space/entities/space-product-allocation.entity';
|
||||
import { NewTagEntity } from '../modules/tag/entities/tag.entity';
|
||||
import { SpaceEntity } from '../modules/space/entities/space.entity';
|
||||
import { SpaceLinkEntity } from '../modules/space/entities/space-link.entity';
|
||||
import { SubspaceProductAllocationEntity } from '../modules/space/entities/subspace/subspace-product-allocation.entity';
|
||||
import { SubspaceEntity } from '../modules/space/entities/subspace/subspace.entity';
|
||||
import { TagEntity } from '../modules/space/entities/tag.entity';
|
||||
import { ClientEntity } from '../modules/client/entities';
|
||||
import { TypeOrmWinstonLogger } from '@app/common/logger/services/typeorm.logger';
|
||||
import { createLogger } from 'winston';
|
||||
import { winstonLoggerOptions } from '../logger/services/winston.logger';
|
||||
import {
|
||||
PowerClampDailyEntity,
|
||||
PowerClampHourlyEntity,
|
||||
@ -35,29 +55,6 @@ import {
|
||||
PresenceSensorDailyDeviceEntity,
|
||||
PresenceSensorDailySpaceEntity,
|
||||
} from '../modules/presence-sensor/entities';
|
||||
import { ProjectEntity } from '../modules/project/entities';
|
||||
import { RegionEntity } from '../modules/region/entities';
|
||||
import { RoleTypeEntity } from '../modules/role-type/entities';
|
||||
import { SceneDeviceEntity } from '../modules/scene-device/entities';
|
||||
import { SceneEntity, SceneIconEntity } from '../modules/scene/entities';
|
||||
import {
|
||||
SpaceModelEntity,
|
||||
SpaceModelProductAllocationEntity,
|
||||
SubspaceModelEntity,
|
||||
SubspaceModelProductAllocationEntity,
|
||||
} from '../modules/space-model/entities';
|
||||
import { InviteSpaceEntity } from '../modules/space/entities/invite-space.entity';
|
||||
import { SpaceProductAllocationEntity } from '../modules/space/entities/space-product-allocation.entity';
|
||||
import { SpaceEntity } from '../modules/space/entities/space.entity';
|
||||
import { SubspaceProductAllocationEntity } from '../modules/space/entities/subspace/subspace-product-allocation.entity';
|
||||
import { SubspaceEntity } from '../modules/space/entities/subspace/subspace.entity';
|
||||
import { NewTagEntity } from '../modules/tag/entities/tag.entity';
|
||||
import { TimeZoneEntity } from '../modules/timezone/entities';
|
||||
import {
|
||||
UserNotificationEntity,
|
||||
UserSpaceEntity,
|
||||
} from '../modules/user/entities';
|
||||
import { VisitorPasswordEntity } from '../modules/visitor-password/entities';
|
||||
@Module({
|
||||
imports: [
|
||||
TypeOrmModule.forRootAsync({
|
||||
@ -86,7 +83,9 @@ import { VisitorPasswordEntity } from '../modules/visitor-password/entities';
|
||||
PermissionTypeEntity,
|
||||
CommunityEntity,
|
||||
SpaceEntity,
|
||||
SpaceLinkEntity,
|
||||
SubspaceEntity,
|
||||
TagEntity,
|
||||
UserSpaceEntity,
|
||||
DeviceUserPermissionEntity,
|
||||
RoleTypeEntity,
|
||||
@ -101,6 +100,7 @@ import { VisitorPasswordEntity } from '../modules/visitor-password/entities';
|
||||
SceneDeviceEntity,
|
||||
SpaceModelEntity,
|
||||
SubspaceModelEntity,
|
||||
TagModel,
|
||||
InviteUserEntity,
|
||||
InviteUserSpaceEntity,
|
||||
InviteSpaceEntity,
|
||||
@ -115,8 +115,6 @@ import { VisitorPasswordEntity } from '../modules/visitor-password/entities';
|
||||
PowerClampMonthlyEntity,
|
||||
PresenceSensorDailyDeviceEntity,
|
||||
PresenceSensorDailySpaceEntity,
|
||||
AqiSpaceDailyPollutantStatsEntity,
|
||||
SpaceDailyOccupancyDurationEntity,
|
||||
],
|
||||
namingStrategy: new SnakeNamingStrategy(),
|
||||
synchronize: Boolean(JSON.parse(configService.get('DB_SYNC'))),
|
||||
@ -125,7 +123,7 @@ import { VisitorPasswordEntity } from '../modules/visitor-password/entities';
|
||||
logger: typeOrmLogger,
|
||||
extra: {
|
||||
charset: 'utf8mb4',
|
||||
max: 100, // set pool max size
|
||||
max: 20, // set pool max size
|
||||
idleTimeoutMillis: 5000, // close idle clients after 5 second
|
||||
connectionTimeoutMillis: 12_000, // return an error after 11 second if connection could not be established
|
||||
maxUses: 7500, // close (and replace) a connection after it has been used 7500 times (see below for discussion)
|
||||
|
@ -1,9 +1,10 @@
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
import { Transform } from 'class-transformer';
|
||||
import { IsBoolean, IsOptional } from 'class-validator';
|
||||
import { BooleanValues } from '../constants/boolean-values.enum';
|
||||
import { IsBoolean, IsDate, IsOptional } from 'class-validator';
|
||||
import { IsPageRequestParam } from '../validators/is-page-request-param.validator';
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
import { IsSizeRequestParam } from '../validators/is-size-request-param.validator';
|
||||
import { Transform } from 'class-transformer';
|
||||
import { parseToDate } from '../util/parseToDate';
|
||||
import { BooleanValues } from '../constants/boolean-values.enum';
|
||||
|
||||
export class PaginationRequestGetListDto {
|
||||
@ApiProperty({
|
||||
@ -18,7 +19,6 @@ export class PaginationRequestGetListDto {
|
||||
return value.obj.includeSpaces === BooleanValues.TRUE;
|
||||
})
|
||||
public includeSpaces?: boolean = false;
|
||||
|
||||
@IsOptional()
|
||||
@IsPageRequestParam({
|
||||
message: 'Page must be bigger than 0',
|
||||
@ -40,4 +40,40 @@ export class PaginationRequestGetListDto {
|
||||
description: 'Size request',
|
||||
})
|
||||
size?: number;
|
||||
|
||||
@IsOptional()
|
||||
@ApiProperty({
|
||||
name: 'name',
|
||||
required: false,
|
||||
description: 'Name to be filtered',
|
||||
})
|
||||
name?: string;
|
||||
|
||||
@ApiProperty({
|
||||
name: 'from',
|
||||
required: false,
|
||||
type: Number,
|
||||
description: `Start time in UNIX timestamp format to filter`,
|
||||
example: 1674172800000,
|
||||
})
|
||||
@IsOptional()
|
||||
@Transform(({ value }) => parseToDate(value))
|
||||
@IsDate({
|
||||
message: `From must be in UNIX timestamp format in order to parse to Date instance`,
|
||||
})
|
||||
from?: Date;
|
||||
|
||||
@ApiProperty({
|
||||
name: 'to',
|
||||
required: false,
|
||||
type: Number,
|
||||
description: `End time in UNIX timestamp format to filter`,
|
||||
example: 1674259200000,
|
||||
})
|
||||
@IsOptional()
|
||||
@Transform(({ value }) => parseToDate(value))
|
||||
@IsDate({
|
||||
message: `To must be in UNIX timestamp format in order to parse to Date instance`,
|
||||
})
|
||||
to?: Date;
|
||||
}
|
||||
|
@ -11,7 +11,6 @@ import {
|
||||
} from '@app/common/modules/power-clamp/repositories';
|
||||
import { SqlLoaderService } from '@app/common/helper/services/sql-loader.service';
|
||||
import { OccupancyService } from '@app/common/helper/services/occupancy.service';
|
||||
import { AqiDataService } from '@app/common/helper/services/aqi.data.service';
|
||||
|
||||
@Module({
|
||||
providers: [
|
||||
@ -24,7 +23,6 @@ import { AqiDataService } from '@app/common/helper/services/aqi.data.service';
|
||||
PowerClampMonthlyRepository,
|
||||
SqlLoaderService,
|
||||
OccupancyService,
|
||||
AqiDataService,
|
||||
],
|
||||
controllers: [DeviceStatusFirebaseController],
|
||||
exports: [DeviceStatusFirebaseService, DeviceStatusLogRepository],
|
||||
|
@ -23,7 +23,6 @@ import { PowerClampService } from '@app/common/helper/services/power.clamp.servi
|
||||
import { PowerClampEnergyEnum } from '@app/common/constants/power.clamp.enargy.enum';
|
||||
import { PresenceSensorEnum } from '@app/common/constants/presence.sensor.enum';
|
||||
import { OccupancyService } from '@app/common/helper/services/occupancy.service';
|
||||
import { AqiDataService } from '@app/common/helper/services/aqi.data.service';
|
||||
@Injectable()
|
||||
export class DeviceStatusFirebaseService {
|
||||
private tuya: TuyaContext;
|
||||
@ -33,7 +32,6 @@ export class DeviceStatusFirebaseService {
|
||||
private readonly deviceRepository: DeviceRepository,
|
||||
private readonly powerClampService: PowerClampService,
|
||||
private readonly occupancyService: OccupancyService,
|
||||
private readonly aqiDataService: AqiDataService,
|
||||
private deviceStatusLogRepository: DeviceStatusLogRepository,
|
||||
) {
|
||||
const accessKey = this.configService.get<string>('auth-config.ACCESS_KEY');
|
||||
@ -76,28 +74,6 @@ export class DeviceStatusFirebaseService {
|
||||
);
|
||||
}
|
||||
}
|
||||
async addDeviceStatusToOurDb(
|
||||
addDeviceStatusDto: AddDeviceStatusDto,
|
||||
): Promise<AddDeviceStatusDto | null> {
|
||||
try {
|
||||
const device = await this.getDeviceByDeviceTuyaUuid(
|
||||
addDeviceStatusDto.deviceTuyaUuid,
|
||||
);
|
||||
|
||||
if (device?.uuid) {
|
||||
return await this.createDeviceStatusInOurDb({
|
||||
deviceUuid: device.uuid,
|
||||
...addDeviceStatusDto,
|
||||
productType: device.productDevice.prodType,
|
||||
});
|
||||
}
|
||||
// Return null if device not found or no UUID
|
||||
return null;
|
||||
} catch (error) {
|
||||
// Handle the error silently, perhaps log it internally or ignore it
|
||||
return null;
|
||||
}
|
||||
}
|
||||
async addDeviceStatusToFirebase(
|
||||
addDeviceStatusDto: AddDeviceStatusDto,
|
||||
): Promise<AddDeviceStatusDto | null> {
|
||||
@ -233,13 +209,6 @@ export class DeviceStatusFirebaseService {
|
||||
return existingData;
|
||||
});
|
||||
|
||||
// Return the updated data
|
||||
const snapshot: DataSnapshot = await get(dataRef);
|
||||
return snapshot.val();
|
||||
}
|
||||
async createDeviceStatusInOurDb(
|
||||
addDeviceStatusDto: AddDeviceStatusDto,
|
||||
): Promise<any> {
|
||||
// Save logs to your repository
|
||||
const newLogs = addDeviceStatusDto.log.properties.map((property) => {
|
||||
return this.deviceStatusLogRepository.create({
|
||||
@ -293,10 +262,9 @@ export class DeviceStatusFirebaseService {
|
||||
);
|
||||
}
|
||||
}
|
||||
if (addDeviceStatusDto.productType === ProductType.AQI) {
|
||||
await this.aqiDataService.updateAQISensorHistoricalData(
|
||||
addDeviceStatusDto.deviceUuid,
|
||||
);
|
||||
}
|
||||
|
||||
// Return the updated data
|
||||
const snapshot: DataSnapshot = await get(dataRef);
|
||||
return snapshot.val();
|
||||
}
|
||||
}
|
||||
|
@ -1,47 +0,0 @@
|
||||
import { DeviceRepository } from '@app/common/modules/device/repositories';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { SqlLoaderService } from './sql-loader.service';
|
||||
import { DataSource } from 'typeorm';
|
||||
import { SQL_PROCEDURES_PATH } from '@app/common/constants/sql-query-path';
|
||||
|
||||
@Injectable()
|
||||
export class AqiDataService {
|
||||
constructor(
|
||||
private readonly sqlLoader: SqlLoaderService,
|
||||
private readonly dataSource: DataSource,
|
||||
private readonly deviceRepository: DeviceRepository,
|
||||
) {}
|
||||
async updateAQISensorHistoricalData(deviceUuid: string): Promise<void> {
|
||||
try {
|
||||
const now = new Date();
|
||||
const dateStr = now.toLocaleDateString('en-CA'); // YYYY-MM-DD
|
||||
const device = await this.deviceRepository.findOne({
|
||||
where: { uuid: deviceUuid },
|
||||
relations: ['spaceDevice'],
|
||||
});
|
||||
|
||||
await this.executeProcedure(
|
||||
'fact_daily_space_aqi',
|
||||
'proceduce_update_daily_space_aqi',
|
||||
[dateStr, device.spaceDevice?.uuid],
|
||||
);
|
||||
} catch (err) {
|
||||
console.error('Failed to insert or update aqi data:', err);
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
private async executeProcedure(
|
||||
procedureFolderName: string,
|
||||
procedureFileName: string,
|
||||
params: (string | number | null)[],
|
||||
): Promise<void> {
|
||||
const query = this.loadQuery(procedureFolderName, procedureFileName);
|
||||
await this.dataSource.query(query, params);
|
||||
console.log(`Procedure ${procedureFileName} executed successfully.`);
|
||||
}
|
||||
|
||||
private loadQuery(folderName: string, fileName: string): string {
|
||||
return this.sqlLoader.loadQuery(folderName, fileName, SQL_PROCEDURES_PATH);
|
||||
}
|
||||
}
|
@ -16,7 +16,7 @@ export class SosHandlerService {
|
||||
);
|
||||
}
|
||||
|
||||
async handleSosEventFirebase(devId: string, logData: any): Promise<void> {
|
||||
async handleSosEvent(devId: string, logData: any): Promise<void> {
|
||||
try {
|
||||
await this.deviceStatusFirebaseService.addDeviceStatusToFirebase({
|
||||
deviceTuyaUuid: devId,
|
||||
@ -39,28 +39,4 @@ export class SosHandlerService {
|
||||
this.logger.error('Failed to send SOS true value', err);
|
||||
}
|
||||
}
|
||||
|
||||
async handleSosEventOurDb(devId: string, logData: any): Promise<void> {
|
||||
try {
|
||||
await this.deviceStatusFirebaseService.addDeviceStatusToOurDb({
|
||||
deviceTuyaUuid: devId,
|
||||
status: [{ code: 'sos', value: true }],
|
||||
log: logData,
|
||||
});
|
||||
|
||||
setTimeout(async () => {
|
||||
try {
|
||||
await this.deviceStatusFirebaseService.addDeviceStatusToOurDb({
|
||||
deviceTuyaUuid: devId,
|
||||
status: [{ code: 'sos', value: false }],
|
||||
log: logData,
|
||||
});
|
||||
} catch (err) {
|
||||
this.logger.error('Failed to send SOS false value', err);
|
||||
}
|
||||
}, 2000);
|
||||
} catch (err) {
|
||||
this.logger.error('Failed to send SOS true value', err);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -9,14 +9,6 @@ export class TuyaWebSocketService {
|
||||
private client: any;
|
||||
private readonly isDevEnv: boolean;
|
||||
|
||||
private messageQueue: {
|
||||
devId: string;
|
||||
status: any;
|
||||
logData: any;
|
||||
}[] = [];
|
||||
|
||||
private isProcessing = false;
|
||||
|
||||
constructor(
|
||||
private readonly configService: ConfigService,
|
||||
private readonly deviceStatusFirebaseService: DeviceStatusFirebaseService,
|
||||
@ -34,12 +26,12 @@ export class TuyaWebSocketService {
|
||||
});
|
||||
|
||||
if (this.configService.get<string>('tuya-config.TRUN_ON_TUYA_SOCKET')) {
|
||||
// Set up event handlers
|
||||
this.setupEventHandlers();
|
||||
|
||||
// Start receiving messages
|
||||
this.client.start();
|
||||
}
|
||||
|
||||
// Trigger the queue processor every 2 seconds
|
||||
setInterval(() => this.processQueue(), 10000);
|
||||
}
|
||||
|
||||
private setupEventHandlers() {
|
||||
@ -51,10 +43,10 @@ export class TuyaWebSocketService {
|
||||
this.client.message(async (ws: WebSocket, message: any) => {
|
||||
try {
|
||||
const { devId, status, logData } = this.extractMessageData(message);
|
||||
|
||||
if (this.sosHandlerService.isSosTriggered(status)) {
|
||||
await this.sosHandlerService.handleSosEventFirebase(devId, logData);
|
||||
await this.sosHandlerService.handleSosEvent(devId, logData);
|
||||
} else {
|
||||
// Firebase real-time update
|
||||
await this.deviceStatusFirebaseService.addDeviceStatusToFirebase({
|
||||
deviceTuyaUuid: devId,
|
||||
status: status,
|
||||
@ -62,13 +54,9 @@ export class TuyaWebSocketService {
|
||||
});
|
||||
}
|
||||
|
||||
// Push to internal queue
|
||||
this.messageQueue.push({ devId, status, logData });
|
||||
|
||||
// Acknowledge the message
|
||||
this.client.ackMessage(message.messageId);
|
||||
} catch (error) {
|
||||
console.error('Error receiving message:', error);
|
||||
console.error('Error processing message:', error);
|
||||
}
|
||||
});
|
||||
|
||||
@ -92,38 +80,6 @@ export class TuyaWebSocketService {
|
||||
console.error('WebSocket error:', error);
|
||||
});
|
||||
}
|
||||
private async processQueue() {
|
||||
if (this.isProcessing || this.messageQueue.length === 0) return;
|
||||
|
||||
this.isProcessing = true;
|
||||
|
||||
const batch = [...this.messageQueue];
|
||||
this.messageQueue = [];
|
||||
|
||||
try {
|
||||
for (const item of batch) {
|
||||
if (this.sosHandlerService.isSosTriggered(item.status)) {
|
||||
await this.sosHandlerService.handleSosEventOurDb(
|
||||
item.devId,
|
||||
item.logData,
|
||||
);
|
||||
} else {
|
||||
await this.deviceStatusFirebaseService.addDeviceStatusToOurDb({
|
||||
deviceTuyaUuid: item.devId,
|
||||
status: item.status,
|
||||
log: item.logData,
|
||||
});
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error processing batch:', error);
|
||||
// Re-add the batch to the queue for retry
|
||||
this.messageQueue.unshift(...batch);
|
||||
} finally {
|
||||
this.isProcessing = false;
|
||||
}
|
||||
}
|
||||
|
||||
private extractMessageData(message: any): {
|
||||
devId: string;
|
||||
status: any;
|
||||
|
@ -1,11 +0,0 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { AqiSpaceDailyPollutantStatsEntity } from './entities/aqi.entity';
|
||||
|
||||
@Module({
|
||||
providers: [],
|
||||
exports: [],
|
||||
controllers: [],
|
||||
imports: [TypeOrmModule.forFeature([AqiSpaceDailyPollutantStatsEntity])],
|
||||
})
|
||||
export class AqiRepositoryModule {}
|
@ -1,82 +0,0 @@
|
||||
import { IsNotEmpty, IsNumber, IsString } from 'class-validator';
|
||||
|
||||
export class AqiSpaceDailyPollutantStatsDto {
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
public uuid: string;
|
||||
|
||||
@IsNotEmpty()
|
||||
@IsString()
|
||||
spaceUuid: string;
|
||||
|
||||
@IsNotEmpty()
|
||||
@IsString()
|
||||
eventDay: string;
|
||||
|
||||
@IsNotEmpty()
|
||||
@IsNumber()
|
||||
eventHour: number;
|
||||
|
||||
@IsNumber()
|
||||
pm1Min: number;
|
||||
|
||||
@IsNumber()
|
||||
pm1Avg: number;
|
||||
|
||||
@IsNumber()
|
||||
pm1Max: number;
|
||||
|
||||
@IsNumber()
|
||||
pm10Min: number;
|
||||
|
||||
@IsNumber()
|
||||
pm10Avg: number;
|
||||
|
||||
@IsNumber()
|
||||
pm10Max: number;
|
||||
|
||||
@IsNumber()
|
||||
pm25Min: number;
|
||||
|
||||
@IsNumber()
|
||||
pm25Avg: number;
|
||||
|
||||
@IsNumber()
|
||||
pm25Max: number;
|
||||
|
||||
@IsNumber()
|
||||
ch2oMin: number;
|
||||
|
||||
@IsNumber()
|
||||
ch2oAvg: number;
|
||||
|
||||
@IsNumber()
|
||||
ch2oMax: number;
|
||||
|
||||
@IsNumber()
|
||||
vocMin: number;
|
||||
|
||||
@IsNumber()
|
||||
vocAvg: number;
|
||||
|
||||
@IsNumber()
|
||||
vocMax: number;
|
||||
|
||||
@IsNumber()
|
||||
co2Min: number;
|
||||
|
||||
@IsNumber()
|
||||
co2Avg: number;
|
||||
|
||||
@IsNumber()
|
||||
co2Max: number;
|
||||
|
||||
@IsNumber()
|
||||
aqiMin: number;
|
||||
|
||||
@IsNumber()
|
||||
aqiAvg: number;
|
||||
|
||||
@IsNumber()
|
||||
aqiMax: number;
|
||||
}
|
@ -1 +0,0 @@
|
||||
export * from './aqi.dto';
|
@ -1,184 +0,0 @@
|
||||
import { Column, Entity, ManyToOne, Unique } from 'typeorm';
|
||||
import { AbstractEntity } from '../../abstract/entities/abstract.entity';
|
||||
import { SpaceEntity } from '../../space/entities/space.entity';
|
||||
import { AqiSpaceDailyPollutantStatsDto } from '../dtos';
|
||||
|
||||
@Entity({ name: 'space-daily-pollutant-stats' })
|
||||
@Unique(['spaceUuid', 'eventDate'])
|
||||
export class AqiSpaceDailyPollutantStatsEntity extends AbstractEntity<AqiSpaceDailyPollutantStatsDto> {
|
||||
@Column({ nullable: false })
|
||||
public spaceUuid: string;
|
||||
|
||||
@ManyToOne(() => SpaceEntity, (space) => space.aqiSensorDaily)
|
||||
space: SpaceEntity;
|
||||
|
||||
@Column({ type: 'date', nullable: false })
|
||||
public eventDate: Date;
|
||||
|
||||
@Column('float', { nullable: true })
|
||||
public goodAqiPercentage?: number;
|
||||
|
||||
@Column('float', { nullable: true })
|
||||
public moderateAqiPercentage?: number;
|
||||
|
||||
@Column('float', { nullable: true })
|
||||
public unhealthySensitiveAqiPercentage?: number;
|
||||
|
||||
@Column('float', { nullable: true })
|
||||
public unhealthyAqiPercentage?: number;
|
||||
|
||||
@Column('float', { nullable: true })
|
||||
public veryUnhealthyAqiPercentage?: number;
|
||||
|
||||
@Column('float', { nullable: true })
|
||||
public hazardousAqiPercentage?: number;
|
||||
|
||||
@Column('float', { nullable: true })
|
||||
public dailyAvgAqi?: number;
|
||||
|
||||
@Column('float', { nullable: true })
|
||||
public dailyMaxAqi?: number;
|
||||
|
||||
@Column('float', { nullable: true })
|
||||
public dailyMinAqi?: number;
|
||||
|
||||
@Column('float', { nullable: true })
|
||||
public goodPm25Percentage?: number;
|
||||
|
||||
@Column('float', { nullable: true })
|
||||
public moderatePm25Percentage?: number;
|
||||
|
||||
@Column('float', { nullable: true })
|
||||
public unhealthySensitivePm25Percentage?: number;
|
||||
|
||||
@Column('float', { nullable: true })
|
||||
public unhealthyPm25Percentage?: number;
|
||||
|
||||
@Column('float', { nullable: true })
|
||||
public veryUnhealthyPm25Percentage?: number;
|
||||
|
||||
@Column('float', { nullable: true })
|
||||
public hazardousPm25Percentage?: number;
|
||||
|
||||
@Column('float', { nullable: true })
|
||||
public dailyAvgPm25?: number;
|
||||
|
||||
@Column('float', { nullable: true })
|
||||
public dailyMaxPm25?: number;
|
||||
|
||||
@Column('float', { nullable: true })
|
||||
public dailyMinPm25?: number;
|
||||
|
||||
@Column('float', { nullable: true })
|
||||
public goodPm10Percentage?: number;
|
||||
|
||||
@Column('float', { nullable: true })
|
||||
public moderatePm10Percentage?: number;
|
||||
|
||||
@Column('float', { nullable: true })
|
||||
public unhealthySensitivePm10Percentage?: number;
|
||||
|
||||
@Column('float', { nullable: true })
|
||||
public unhealthyPm10Percentage?: number;
|
||||
|
||||
@Column('float', { nullable: true })
|
||||
public veryUnhealthyPm10Percentage?: number;
|
||||
|
||||
@Column('float', { nullable: true })
|
||||
public hazardousPm10Percentage?: number;
|
||||
|
||||
@Column('float', { nullable: true })
|
||||
public dailyAvgPm10?: number;
|
||||
|
||||
@Column('float', { nullable: true })
|
||||
public dailyMaxPm10?: number;
|
||||
|
||||
@Column('float', { nullable: true })
|
||||
public dailyMinPm10?: number;
|
||||
|
||||
@Column('float', { nullable: true })
|
||||
public goodVocPercentage?: number;
|
||||
|
||||
@Column('float', { nullable: true })
|
||||
public moderateVocPercentage?: number;
|
||||
|
||||
@Column('float', { nullable: true })
|
||||
public unhealthySensitiveVocPercentage?: number;
|
||||
|
||||
@Column('float', { nullable: true })
|
||||
public unhealthyVocPercentage?: number;
|
||||
|
||||
@Column('float', { nullable: true })
|
||||
public veryUnhealthyVocPercentage?: number;
|
||||
|
||||
@Column('float', { nullable: true })
|
||||
public hazardousVocPercentage?: number;
|
||||
|
||||
@Column('float', { nullable: true })
|
||||
public dailyAvgVoc?: number;
|
||||
|
||||
@Column('float', { nullable: true })
|
||||
public dailyMaxVoc?: number;
|
||||
|
||||
@Column('float', { nullable: true })
|
||||
public dailyMinVoc?: number;
|
||||
|
||||
@Column('float', { nullable: true })
|
||||
public goodCo2Percentage?: number;
|
||||
|
||||
@Column('float', { nullable: true })
|
||||
public moderateCo2Percentage?: number;
|
||||
|
||||
@Column('float', { nullable: true })
|
||||
public unhealthySensitiveCo2Percentage?: number;
|
||||
|
||||
@Column('float', { nullable: true })
|
||||
public unhealthyCo2Percentage?: number;
|
||||
|
||||
@Column('float', { nullable: true })
|
||||
public veryUnhealthyCo2Percentage?: number;
|
||||
|
||||
@Column('float', { nullable: true })
|
||||
public hazardousCo2Percentage?: number;
|
||||
|
||||
@Column('float', { nullable: true })
|
||||
public dailyAvgCo2?: number;
|
||||
|
||||
@Column('float', { nullable: true })
|
||||
public dailyMaxCo2?: number;
|
||||
|
||||
@Column('float', { nullable: true })
|
||||
public dailyMinCo2?: number;
|
||||
|
||||
@Column('float', { nullable: true })
|
||||
public goodCh2oPercentage?: number;
|
||||
|
||||
@Column('float', { nullable: true })
|
||||
public moderateCh2oPercentage?: number;
|
||||
|
||||
@Column('float', { nullable: true })
|
||||
public unhealthySensitiveCh2oPercentage?: number;
|
||||
|
||||
@Column('float', { nullable: true })
|
||||
public unhealthyCh2oPercentage?: number;
|
||||
|
||||
@Column('float', { nullable: true })
|
||||
public veryUnhealthyCh2oPercentage?: number;
|
||||
|
||||
@Column('float', { nullable: true })
|
||||
public hazardousCh2oPercentage?: number;
|
||||
|
||||
@Column('float', { nullable: true })
|
||||
public dailyAvgCh2o?: number;
|
||||
|
||||
@Column('float', { nullable: true })
|
||||
public dailyMaxCh2o?: number;
|
||||
|
||||
@Column('float', { nullable: true })
|
||||
public dailyMinCh2o?: number;
|
||||
|
||||
constructor(partial: Partial<AqiSpaceDailyPollutantStatsEntity>) {
|
||||
super();
|
||||
Object.assign(this, partial);
|
||||
}
|
||||
}
|
@ -1 +0,0 @@
|
||||
export * from './aqi.entity';
|
@ -1,10 +0,0 @@
|
||||
import { DataSource, Repository } from 'typeorm';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { AqiSpaceDailyPollutantStatsEntity } from '../entities';
|
||||
|
||||
@Injectable()
|
||||
export class AqiSpaceDailyPollutantStatsRepository extends Repository<AqiSpaceDailyPollutantStatsEntity> {
|
||||
constructor(private dataSource: DataSource) {
|
||||
super(AqiSpaceDailyPollutantStatsEntity, dataSource.createEntityManager());
|
||||
}
|
||||
}
|
@ -1 +0,0 @@
|
||||
export * from './aqi.repository';
|
@ -2,15 +2,15 @@ import { SourceType } from '@app/common/constants/source-type.enum';
|
||||
import { Entity, Column, PrimaryColumn, Unique } from 'typeorm';
|
||||
|
||||
@Entity('device-status-log')
|
||||
@Unique('event_time_idx', ['eventTime', 'deviceId', 'code', 'value'])
|
||||
@Unique('event_time_idx', ['eventTime'])
|
||||
export class DeviceStatusLogEntity {
|
||||
@PrimaryColumn({ type: 'int', generated: true, unsigned: true })
|
||||
@Column({ type: 'int', generated: true, unsigned: true })
|
||||
id: number;
|
||||
|
||||
@Column({ type: 'text' })
|
||||
eventId: string;
|
||||
|
||||
@Column({ type: 'timestamptz' })
|
||||
@PrimaryColumn({ type: 'timestamptz' })
|
||||
eventTime: Date;
|
||||
|
||||
@Column({
|
||||
|
@ -78,8 +78,8 @@ export class DeviceEntity extends AbstractEntity<DeviceDto> {
|
||||
@OneToMany(() => SceneDeviceEntity, (sceneDevice) => sceneDevice.device, {})
|
||||
sceneDevices: SceneDeviceEntity[];
|
||||
|
||||
@ManyToOne(() => NewTagEntity, (tag) => tag.devices)
|
||||
@JoinColumn({ name: 'tag_uuid' })
|
||||
@OneToMany(() => NewTagEntity, (tag) => tag.devices)
|
||||
// @JoinTable({ name: 'device_tags' })
|
||||
public tag: NewTagEntity;
|
||||
@OneToMany(() => PowerClampHourlyEntity, (powerClamp) => powerClamp.device)
|
||||
powerClampHourly: PowerClampHourlyEntity[];
|
||||
|
@ -1 +0,0 @@
|
||||
export * from './occupancy.dto';
|
@ -1,23 +0,0 @@
|
||||
import { IsNotEmpty, IsNumber, IsString } from 'class-validator';
|
||||
|
||||
export class SpaceDailyOccupancyDurationDto {
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
public uuid: string;
|
||||
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
public spaceUuid: string;
|
||||
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
public eventDate: string;
|
||||
|
||||
@IsNumber()
|
||||
@IsNotEmpty()
|
||||
public occupancyPercentage: number;
|
||||
|
||||
@IsNumber()
|
||||
@IsNotEmpty()
|
||||
public occupiedSeconds: number;
|
||||
}
|
@ -1 +0,0 @@
|
||||
export * from './occupancy.entity';
|
@ -1,32 +0,0 @@
|
||||
import { Column, Entity, ManyToOne, Unique } from 'typeorm';
|
||||
import { AbstractEntity } from '../../abstract/entities/abstract.entity';
|
||||
import { SpaceEntity } from '../../space/entities/space.entity';
|
||||
import { SpaceDailyOccupancyDurationDto } from '../dtos';
|
||||
|
||||
@Entity({ name: 'space-daily-occupancy-duration' })
|
||||
@Unique(['spaceUuid', 'eventDate'])
|
||||
export class SpaceDailyOccupancyDurationEntity extends AbstractEntity<SpaceDailyOccupancyDurationDto> {
|
||||
@Column({ nullable: false })
|
||||
public spaceUuid: string;
|
||||
|
||||
@Column({ nullable: false, type: 'date' })
|
||||
public eventDate: string;
|
||||
|
||||
public CountTotalPresenceDetected: number;
|
||||
|
||||
@ManyToOne(() => SpaceEntity, (space) => space.presenceSensorDaily)
|
||||
space: SpaceEntity;
|
||||
|
||||
@Column({ type: 'int' })
|
||||
occupancyPercentage: number;
|
||||
|
||||
@Column({ type: 'int', nullable: true })
|
||||
occupiedSeconds?: number;
|
||||
|
||||
@Column({ type: 'int', nullable: true })
|
||||
deviceCount?: number;
|
||||
constructor(partial: Partial<SpaceDailyOccupancyDurationEntity>) {
|
||||
super();
|
||||
Object.assign(this, partial);
|
||||
}
|
||||
}
|
@ -1,11 +0,0 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { SpaceDailyOccupancyDurationEntity } from './entities/occupancy.entity';
|
||||
|
||||
@Module({
|
||||
providers: [],
|
||||
exports: [],
|
||||
controllers: [],
|
||||
imports: [TypeOrmModule.forFeature([SpaceDailyOccupancyDurationEntity])],
|
||||
})
|
||||
export class SpaceDailyOccupancyDurationRepositoryModule {}
|
@ -1 +0,0 @@
|
||||
export * from './occupancy.repository';
|
@ -1,10 +0,0 @@
|
||||
import { DataSource, Repository } from 'typeorm';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { SpaceDailyOccupancyDurationEntity } from '../entities/occupancy.entity';
|
||||
|
||||
@Injectable()
|
||||
export class SpaceDailyOccupancyDurationEntityRepository extends Repository<SpaceDailyOccupancyDurationEntity> {
|
||||
constructor(private dataSource: DataSource) {
|
||||
super(SpaceDailyOccupancyDurationEntity, dataSource.createEntityManager());
|
||||
}
|
||||
}
|
@ -1,7 +1,10 @@
|
||||
import { Column, Entity, OneToMany } from 'typeorm';
|
||||
import { ProductDto } from '../dtos';
|
||||
import { AbstractEntity } from '../../abstract/entities/abstract.entity';
|
||||
import { DeviceEntity } from '../../device/entities';
|
||||
import { ProductDto } from '../dtos';
|
||||
import { TagModel } from '../../space-model';
|
||||
import { TagEntity } from '../../space/entities/tag.entity';
|
||||
import { NewTagEntity } from '../../tag/entities';
|
||||
@Entity({ name: 'product' })
|
||||
export class ProductEntity extends AbstractEntity<ProductDto> {
|
||||
@Column({
|
||||
@ -25,6 +28,15 @@ export class ProductEntity extends AbstractEntity<ProductDto> {
|
||||
})
|
||||
public prodType: string;
|
||||
|
||||
@OneToMany(() => NewTagEntity, (tag) => tag.product, { cascade: true })
|
||||
public newTags: NewTagEntity[];
|
||||
|
||||
@OneToMany(() => TagModel, (tag) => tag.product)
|
||||
tagModels: TagModel[];
|
||||
|
||||
@OneToMany(() => TagEntity, (tag) => tag.product)
|
||||
tags: TagEntity[];
|
||||
|
||||
@OneToMany(
|
||||
() => DeviceEntity,
|
||||
(devicesProductEntity) => devicesProductEntity.productDevice,
|
||||
|
21
libs/common/src/modules/space-model/dtos/tag-model.dto.ts
Normal file
21
libs/common/src/modules/space-model/dtos/tag-model.dto.ts
Normal file
@ -0,0 +1,21 @@
|
||||
import { IsNotEmpty, IsString } from 'class-validator';
|
||||
|
||||
export class TagModelDto {
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
public uuid: string;
|
||||
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
public name: string;
|
||||
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
public productUuid: string;
|
||||
|
||||
@IsString()
|
||||
spaceModelUuid: string;
|
||||
|
||||
@IsString()
|
||||
subspaceModelUuid: string;
|
||||
}
|
@ -1,3 +1,4 @@
|
||||
export * from './space-model-product-allocation.entity';
|
||||
export * from './space-model.entity';
|
||||
export * from './subspace-model';
|
||||
export * from './tag-model.entity';
|
||||
export * from './space-model-product-allocation.entity';
|
||||
|
@ -1,12 +1,18 @@
|
||||
import { Column, Entity, ManyToOne, OneToMany, Unique } from 'typeorm';
|
||||
import { AbstractEntity } from '../../abstract/entities/abstract.entity';
|
||||
import {
|
||||
Entity,
|
||||
Column,
|
||||
ManyToOne,
|
||||
ManyToMany,
|
||||
JoinTable,
|
||||
OneToMany,
|
||||
} from 'typeorm';
|
||||
import { SpaceModelEntity } from './space-model.entity';
|
||||
import { NewTagEntity } from '../../tag/entities/tag.entity';
|
||||
import { ProductEntity } from '../../product/entities/product.entity';
|
||||
import { SpaceProductAllocationEntity } from '../../space/entities/space-product-allocation.entity';
|
||||
import { NewTagEntity } from '../../tag/entities/tag.entity';
|
||||
import { SpaceModelEntity } from './space-model.entity';
|
||||
import { AbstractEntity } from '../../abstract/entities/abstract.entity';
|
||||
|
||||
@Entity({ name: 'space_model_product_allocation' })
|
||||
@Unique(['spaceModel', 'product', 'tag'])
|
||||
export class SpaceModelProductAllocationEntity extends AbstractEntity<SpaceModelProductAllocationEntity> {
|
||||
@Column({
|
||||
type: 'uuid',
|
||||
@ -25,8 +31,9 @@ export class SpaceModelProductAllocationEntity extends AbstractEntity<SpaceModel
|
||||
@ManyToOne(() => ProductEntity, { nullable: false, onDelete: 'CASCADE' })
|
||||
public product: ProductEntity;
|
||||
|
||||
@ManyToOne(() => NewTagEntity, { nullable: true, onDelete: 'CASCADE' })
|
||||
public tag: NewTagEntity;
|
||||
@ManyToMany(() => NewTagEntity, { cascade: true, onDelete: 'CASCADE' })
|
||||
@JoinTable({ name: 'space_model_product_tags' })
|
||||
public tags: NewTagEntity[];
|
||||
|
||||
@OneToMany(
|
||||
() => SpaceProductAllocationEntity,
|
||||
|
@ -1,10 +1,11 @@
|
||||
import { Column, Entity, JoinColumn, ManyToOne, OneToMany } from 'typeorm';
|
||||
import { Entity, Column, OneToMany, ManyToOne, JoinColumn } from 'typeorm';
|
||||
import { AbstractEntity } from '../../abstract/entities/abstract.entity';
|
||||
import { ProjectEntity } from '../../project/entities';
|
||||
import { SpaceEntity } from '../../space/entities/space.entity';
|
||||
import { SpaceModelDto } from '../dtos';
|
||||
import { SpaceModelProductAllocationEntity } from './space-model-product-allocation.entity';
|
||||
import { SubspaceModelEntity } from './subspace-model';
|
||||
import { ProjectEntity } from '../../project/entities';
|
||||
import { TagModel } from './tag-model.entity';
|
||||
import { SpaceModelProductAllocationEntity } from './space-model-product-allocation.entity';
|
||||
import { SpaceEntity } from '../../space/entities/space.entity';
|
||||
|
||||
@Entity({ name: 'space-model' })
|
||||
export class SpaceModelEntity extends AbstractEntity<SpaceModelDto> {
|
||||
@ -48,6 +49,9 @@ export class SpaceModelEntity extends AbstractEntity<SpaceModelDto> {
|
||||
})
|
||||
public spaces: SpaceEntity[];
|
||||
|
||||
@OneToMany(() => TagModel, (tag) => tag.spaceModel)
|
||||
tags: TagModel[];
|
||||
|
||||
@OneToMany(
|
||||
() => SpaceModelProductAllocationEntity,
|
||||
(allocation) => allocation.spaceModel,
|
||||
|
@ -1,12 +1,11 @@
|
||||
import { AbstractEntity } from '@app/common/modules/abstract/entities/abstract.entity';
|
||||
import { Entity, Column, ManyToOne, ManyToMany, JoinTable } from 'typeorm';
|
||||
import { SubspaceModelEntity } from './subspace-model.entity';
|
||||
import { ProductEntity } from '@app/common/modules/product/entities/product.entity';
|
||||
import { NewTagEntity } from '@app/common/modules/tag/entities/tag.entity';
|
||||
import { Column, Entity, ManyToOne, Unique } from 'typeorm';
|
||||
import { SubspaceModelProductAllocationDto } from '../../dtos/subspace-model/subspace-model-product-allocation.dto';
|
||||
import { SubspaceModelEntity } from './subspace-model.entity';
|
||||
import { AbstractEntity } from '@app/common/modules/abstract/entities/abstract.entity';
|
||||
|
||||
@Entity({ name: 'subspace_model_product_allocation' })
|
||||
@Unique(['subspaceModel', 'product', 'tag'])
|
||||
export class SubspaceModelProductAllocationEntity extends AbstractEntity<SubspaceModelProductAllocationDto> {
|
||||
@Column({
|
||||
type: 'uuid',
|
||||
@ -28,8 +27,12 @@ export class SubspaceModelProductAllocationEntity extends AbstractEntity<Subspac
|
||||
@ManyToOne(() => ProductEntity, { nullable: false, onDelete: 'CASCADE' })
|
||||
public product: ProductEntity;
|
||||
|
||||
@ManyToOne(() => NewTagEntity, { nullable: true, onDelete: 'CASCADE' })
|
||||
public tag: NewTagEntity;
|
||||
@ManyToMany(() => NewTagEntity, (tag) => tag.subspaceModelAllocations, {
|
||||
cascade: true,
|
||||
onDelete: 'CASCADE',
|
||||
})
|
||||
@JoinTable({ name: 'subspace_model_product_tags' })
|
||||
public tags: NewTagEntity[];
|
||||
|
||||
constructor(partial: Partial<SubspaceModelProductAllocationEntity>) {
|
||||
super();
|
||||
|
@ -1,9 +1,10 @@
|
||||
import { AbstractEntity } from '@app/common/modules/abstract/entities/abstract.entity';
|
||||
import { SubspaceEntity } from '@app/common/modules/space/entities/subspace/subspace.entity';
|
||||
import { Column, Entity, ManyToOne, OneToMany } from 'typeorm';
|
||||
import { SubSpaceModelDto } from '../../dtos';
|
||||
import { SpaceModelEntity } from '../space-model.entity';
|
||||
import { TagModel } from '../tag-model.entity';
|
||||
import { SubspaceModelProductAllocationEntity } from './subspace-model-product-allocation.entity';
|
||||
import { SubspaceEntity } from '@app/common/modules/space/entities/subspace/subspace.entity';
|
||||
|
||||
@Entity({ name: 'subspace-model' })
|
||||
export class SubspaceModelEntity extends AbstractEntity<SubSpaceModelDto> {
|
||||
@ -40,6 +41,9 @@ export class SubspaceModelEntity extends AbstractEntity<SubSpaceModelDto> {
|
||||
})
|
||||
public disabled: boolean;
|
||||
|
||||
@OneToMany(() => TagModel, (tag) => tag.subspaceModel)
|
||||
tags: TagModel[];
|
||||
|
||||
@OneToMany(
|
||||
() => SubspaceModelProductAllocationEntity,
|
||||
(allocation) => allocation.subspaceModel,
|
||||
|
@ -0,0 +1,38 @@
|
||||
import { Column, Entity, JoinColumn, ManyToOne, OneToMany } from 'typeorm';
|
||||
import { AbstractEntity } from '../../abstract/entities/abstract.entity';
|
||||
import { TagModelDto } from '../dtos/tag-model.dto';
|
||||
import { SpaceModelEntity } from './space-model.entity';
|
||||
import { SubspaceModelEntity } from './subspace-model';
|
||||
import { ProductEntity } from '../../product/entities';
|
||||
import { TagEntity } from '../../space/entities/tag.entity';
|
||||
|
||||
@Entity({ name: 'tag_model' })
|
||||
export class TagModel extends AbstractEntity<TagModelDto> {
|
||||
@Column({ type: 'varchar', length: 255 })
|
||||
tag: string;
|
||||
|
||||
@ManyToOne(() => ProductEntity, (product) => product.tagModels, {
|
||||
nullable: false,
|
||||
})
|
||||
@JoinColumn({ name: 'product_id' })
|
||||
product: ProductEntity;
|
||||
|
||||
@ManyToOne(() => SpaceModelEntity, (space) => space.tags, { nullable: true })
|
||||
@JoinColumn({ name: 'space_model_id' })
|
||||
spaceModel: SpaceModelEntity;
|
||||
|
||||
@ManyToOne(() => SubspaceModelEntity, (subspace) => subspace.tags, {
|
||||
nullable: true,
|
||||
})
|
||||
@JoinColumn({ name: 'subspace_model_id' })
|
||||
subspaceModel: SubspaceModelEntity;
|
||||
|
||||
@Column({
|
||||
nullable: false,
|
||||
default: false,
|
||||
})
|
||||
public disabled: boolean;
|
||||
|
||||
@OneToMany(() => TagEntity, (tag) => tag.model)
|
||||
tags: TagEntity[];
|
||||
}
|
@ -1,10 +1,11 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { DataSource, Repository } from 'typeorm';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import {
|
||||
SpaceModelEntity,
|
||||
SpaceModelProductAllocationEntity,
|
||||
SubspaceModelEntity,
|
||||
SubspaceModelProductAllocationEntity,
|
||||
TagModel,
|
||||
} from '../entities';
|
||||
|
||||
@Injectable()
|
||||
@ -20,6 +21,13 @@ export class SubspaceModelRepository extends Repository<SubspaceModelEntity> {
|
||||
}
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class TagModelRepository extends Repository<TagModel> {
|
||||
constructor(private dataSource: DataSource) {
|
||||
super(TagModel, dataSource.createEntityManager());
|
||||
}
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class SpaceModelProductAllocationRepoitory extends Repository<SpaceModelProductAllocationEntity> {
|
||||
constructor(private dataSource: DataSource) {
|
||||
|
@ -1,11 +1,13 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { SpaceModelEntity, SubspaceModelEntity } from './entities';
|
||||
import { SpaceModelEntity, SubspaceModelEntity, TagModel } from './entities';
|
||||
import { Module } from '@nestjs/common';
|
||||
|
||||
@Module({
|
||||
providers: [],
|
||||
exports: [],
|
||||
controllers: [],
|
||||
imports: [TypeOrmModule.forFeature([SpaceModelEntity, SubspaceModelEntity])],
|
||||
imports: [
|
||||
TypeOrmModule.forFeature([SpaceModelEntity, SubspaceModelEntity, TagModel]),
|
||||
],
|
||||
})
|
||||
export class SpaceModelRepositoryModule {}
|
||||
|
@ -1,3 +1,32 @@
|
||||
import { Column, Entity, JoinColumn, ManyToOne } from 'typeorm';
|
||||
import { AbstractEntity } from '../../abstract/entities/abstract.entity';
|
||||
import { SpaceEntity } from './space.entity';
|
||||
import { Direction } from '@app/common/constants/direction.enum';
|
||||
|
||||
export class SpaceLinkEntity extends AbstractEntity {}
|
||||
@Entity({ name: 'space-link' })
|
||||
export class SpaceLinkEntity extends AbstractEntity {
|
||||
@ManyToOne(() => SpaceEntity, { nullable: false, onDelete: 'CASCADE' })
|
||||
@JoinColumn({ name: 'start_space_id' })
|
||||
public startSpace: SpaceEntity;
|
||||
|
||||
@ManyToOne(() => SpaceEntity, { nullable: false, onDelete: 'CASCADE' })
|
||||
@JoinColumn({ name: 'end_space_id' })
|
||||
public endSpace: SpaceEntity;
|
||||
|
||||
@Column({
|
||||
nullable: false,
|
||||
default: false,
|
||||
})
|
||||
public disabled: boolean;
|
||||
|
||||
@Column({
|
||||
nullable: false,
|
||||
enum: Object.values(Direction),
|
||||
})
|
||||
direction: string;
|
||||
|
||||
constructor(partial: Partial<SpaceLinkEntity>) {
|
||||
super();
|
||||
Object.assign(this, partial);
|
||||
}
|
||||
}
|
||||
|
@ -1,13 +1,12 @@
|
||||
import { Column, Entity, ManyToOne, Unique } from 'typeorm';
|
||||
import { AbstractEntity } from '../../abstract/entities/abstract.entity';
|
||||
import { ProductEntity } from '../../product/entities/product.entity';
|
||||
import { SpaceModelProductAllocationEntity } from '../../space-model/entities/space-model-product-allocation.entity';
|
||||
import { NewTagEntity } from '../../tag/entities/tag.entity';
|
||||
import { SpaceProductAllocationDto } from '../dtos/space-product-allocation.dto';
|
||||
import { Entity, Column, ManyToOne, ManyToMany, JoinTable } from 'typeorm';
|
||||
import { SpaceEntity } from './space.entity';
|
||||
import { SpaceModelProductAllocationEntity } from '../../space-model/entities/space-model-product-allocation.entity';
|
||||
import { ProductEntity } from '../../product/entities/product.entity';
|
||||
import { NewTagEntity } from '../../tag/entities/tag.entity';
|
||||
import { AbstractEntity } from '../../abstract/entities/abstract.entity';
|
||||
import { SpaceProductAllocationDto } from '../dtos/space-product-allocation.dto';
|
||||
|
||||
@Entity({ name: 'space_product_allocation' })
|
||||
@Unique(['space', 'product', 'tag'], {})
|
||||
export class SpaceProductAllocationEntity extends AbstractEntity<SpaceProductAllocationDto> {
|
||||
@Column({
|
||||
type: 'uuid',
|
||||
@ -31,8 +30,9 @@ export class SpaceProductAllocationEntity extends AbstractEntity<SpaceProductAll
|
||||
@ManyToOne(() => ProductEntity, { nullable: false, onDelete: 'CASCADE' })
|
||||
public product: ProductEntity;
|
||||
|
||||
@ManyToOne(() => NewTagEntity, { nullable: true, onDelete: 'CASCADE' })
|
||||
public tag: NewTagEntity;
|
||||
@ManyToMany(() => NewTagEntity)
|
||||
@JoinTable({ name: 'space_product_tags' })
|
||||
public tags: NewTagEntity[];
|
||||
|
||||
constructor(partial: Partial<SpaceProductAllocationEntity>) {
|
||||
super();
|
||||
|
@ -1,17 +1,16 @@
|
||||
import { Column, Entity, JoinColumn, ManyToOne, OneToMany } from 'typeorm';
|
||||
import { SpaceDto } from '../dtos';
|
||||
import { AbstractEntity } from '../../abstract/entities/abstract.entity';
|
||||
import { AqiSpaceDailyPollutantStatsEntity } from '../../aqi/entities';
|
||||
import { CommunityEntity } from '../../community/entities';
|
||||
import { UserSpaceEntity } from '../../user/entities';
|
||||
import { DeviceEntity } from '../../device/entities';
|
||||
import { InviteUserSpaceEntity } from '../../Invite-user/entities';
|
||||
import { SpaceDailyOccupancyDurationEntity } from '../../occupancy/entities';
|
||||
import { PresenceSensorDailySpaceEntity } from '../../presence-sensor/entities';
|
||||
import { CommunityEntity } from '../../community/entities';
|
||||
import { SpaceLinkEntity } from './space-link.entity';
|
||||
import { SceneEntity } from '../../scene/entities';
|
||||
import { SpaceModelEntity } from '../../space-model';
|
||||
import { UserSpaceEntity } from '../../user/entities';
|
||||
import { SpaceDto } from '../dtos';
|
||||
import { InviteUserSpaceEntity } from '../../Invite-user/entities';
|
||||
import { SpaceProductAllocationEntity } from './space-product-allocation.entity';
|
||||
import { SubspaceEntity } from './subspace/subspace.entity';
|
||||
import { PresenceSensorDailySpaceEntity } from '../../presence-sensor/entities';
|
||||
|
||||
@Entity({ name: 'space' })
|
||||
export class SpaceEntity extends AbstractEntity<SpaceDto> {
|
||||
@ -74,6 +73,16 @@ export class SpaceEntity extends AbstractEntity<SpaceDto> {
|
||||
)
|
||||
devices: DeviceEntity[];
|
||||
|
||||
@OneToMany(() => SpaceLinkEntity, (connection) => connection.startSpace, {
|
||||
nullable: true,
|
||||
})
|
||||
public outgoingConnections: SpaceLinkEntity[];
|
||||
|
||||
@OneToMany(() => SpaceLinkEntity, (connection) => connection.endSpace, {
|
||||
nullable: true,
|
||||
})
|
||||
public incomingConnections: SpaceLinkEntity[];
|
||||
|
||||
@Column({
|
||||
nullable: true,
|
||||
type: 'text',
|
||||
@ -106,15 +115,6 @@ export class SpaceEntity extends AbstractEntity<SpaceDto> {
|
||||
@OneToMany(() => PresenceSensorDailySpaceEntity, (sensor) => sensor.space)
|
||||
presenceSensorDaily: PresenceSensorDailySpaceEntity[];
|
||||
|
||||
@OneToMany(() => AqiSpaceDailyPollutantStatsEntity, (aqi) => aqi.space)
|
||||
aqiSensorDaily: AqiSpaceDailyPollutantStatsEntity[];
|
||||
|
||||
@OneToMany(
|
||||
() => SpaceDailyOccupancyDurationEntity,
|
||||
(occupancy) => occupancy.space,
|
||||
)
|
||||
occupancyDaily: SpaceDailyOccupancyDurationEntity[];
|
||||
|
||||
constructor(partial: Partial<SpaceEntity>) {
|
||||
super();
|
||||
Object.assign(this, partial);
|
||||
|
@ -1,13 +1,20 @@
|
||||
import { AbstractEntity } from '@app/common/modules/abstract/entities/abstract.entity';
|
||||
import {
|
||||
Entity,
|
||||
Column,
|
||||
ManyToOne,
|
||||
ManyToMany,
|
||||
JoinTable,
|
||||
Unique,
|
||||
} from 'typeorm';
|
||||
import { SubspaceEntity } from './subspace.entity';
|
||||
import { ProductEntity } from '@app/common/modules/product/entities';
|
||||
import { SubspaceModelProductAllocationEntity } from '@app/common/modules/space-model';
|
||||
import { NewTagEntity } from '@app/common/modules/tag/entities/tag.entity';
|
||||
import { Column, Entity, ManyToOne, Unique } from 'typeorm';
|
||||
import { AbstractEntity } from '@app/common/modules/abstract/entities/abstract.entity';
|
||||
import { SubspaceProductAllocationDto } from '../../dtos/subspace-product-allocation.dto';
|
||||
import { SubspaceEntity } from './subspace.entity';
|
||||
|
||||
@Entity({ name: 'subspace_product_allocation' })
|
||||
@Unique(['subspace', 'product', 'tag'])
|
||||
// @Unique(['subspace', 'product'])
|
||||
export class SubspaceProductAllocationEntity extends AbstractEntity<SubspaceProductAllocationDto> {
|
||||
@Column({
|
||||
type: 'uuid',
|
||||
@ -31,8 +38,9 @@ export class SubspaceProductAllocationEntity extends AbstractEntity<SubspaceProd
|
||||
@ManyToOne(() => ProductEntity, { nullable: false, onDelete: 'CASCADE' })
|
||||
public product: ProductEntity;
|
||||
|
||||
@ManyToOne(() => NewTagEntity, { nullable: true, onDelete: 'CASCADE' })
|
||||
public tag: NewTagEntity;
|
||||
@ManyToMany(() => NewTagEntity)
|
||||
@JoinTable({ name: 'subspace_product_tags' })
|
||||
public tags: NewTagEntity[];
|
||||
|
||||
constructor(partial: Partial<SubspaceProductAllocationEntity>) {
|
||||
super();
|
||||
|
@ -4,6 +4,7 @@ import { SubspaceModelEntity } from '@app/common/modules/space-model';
|
||||
import { Column, Entity, JoinColumn, ManyToOne, OneToMany } from 'typeorm';
|
||||
import { SubspaceDto } from '../../dtos';
|
||||
import { SpaceEntity } from '../space.entity';
|
||||
import { TagEntity } from '../tag.entity';
|
||||
import { SubspaceProductAllocationEntity } from './subspace-product-allocation.entity';
|
||||
|
||||
@Entity({ name: 'subspace' })
|
||||
@ -42,6 +43,9 @@ export class SubspaceEntity extends AbstractEntity<SubspaceDto> {
|
||||
})
|
||||
subSpaceModel?: SubspaceModelEntity;
|
||||
|
||||
@OneToMany(() => TagEntity, (tag) => tag.subspace)
|
||||
tags: TagEntity[];
|
||||
|
||||
@OneToMany(
|
||||
() => SubspaceProductAllocationEntity,
|
||||
(allocation) => allocation.subspace,
|
||||
|
41
libs/common/src/modules/space/entities/tag.entity.ts
Normal file
41
libs/common/src/modules/space/entities/tag.entity.ts
Normal file
@ -0,0 +1,41 @@
|
||||
import { Entity, Column, ManyToOne, JoinColumn, OneToOne } from 'typeorm';
|
||||
import { AbstractEntity } from '../../abstract/entities/abstract.entity';
|
||||
import { ProductEntity } from '../../product/entities';
|
||||
import { TagDto } from '../dtos';
|
||||
import { TagModel } from '../../space-model/entities/tag-model.entity';
|
||||
import { DeviceEntity } from '../../device/entities';
|
||||
import { SubspaceEntity } from './subspace/subspace.entity';
|
||||
|
||||
@Entity({ name: 'tag' })
|
||||
export class TagEntity extends AbstractEntity<TagDto> {
|
||||
@Column({ type: 'varchar', length: 255, nullable: true })
|
||||
tag: string;
|
||||
|
||||
@ManyToOne(() => TagModel, (model) => model.tags, {
|
||||
nullable: true,
|
||||
})
|
||||
model: TagModel;
|
||||
|
||||
@ManyToOne(() => ProductEntity, (product) => product.tags, {
|
||||
nullable: false,
|
||||
})
|
||||
product: ProductEntity;
|
||||
|
||||
@ManyToOne(() => SubspaceEntity, (subspace) => subspace.tags, {
|
||||
nullable: true,
|
||||
})
|
||||
@JoinColumn({ name: 'subspace_id' })
|
||||
subspace: SubspaceEntity;
|
||||
|
||||
@Column({
|
||||
nullable: false,
|
||||
default: false,
|
||||
})
|
||||
public disabled: boolean;
|
||||
|
||||
@OneToOne(() => DeviceEntity, (device) => device.tag, {
|
||||
nullable: true,
|
||||
})
|
||||
@JoinColumn({ name: 'device_id' })
|
||||
device: DeviceEntity;
|
||||
}
|
@ -1,8 +1,10 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { DataSource, Repository } from 'typeorm';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { InviteSpaceEntity } from '../entities/invite-space.entity';
|
||||
import { SpaceProductAllocationEntity } from '../entities/space-product-allocation.entity';
|
||||
import { SpaceLinkEntity } from '../entities/space-link.entity';
|
||||
import { SpaceEntity } from '../entities/space.entity';
|
||||
import { TagEntity } from '../entities/tag.entity';
|
||||
import { SpaceProductAllocationEntity } from '../entities/space-product-allocation.entity';
|
||||
|
||||
@Injectable()
|
||||
export class SpaceRepository extends Repository<SpaceEntity> {
|
||||
@ -12,7 +14,18 @@ export class SpaceRepository extends Repository<SpaceEntity> {
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class SpaceLinkRepository {}
|
||||
export class SpaceLinkRepository extends Repository<SpaceLinkEntity> {
|
||||
constructor(private dataSource: DataSource) {
|
||||
super(SpaceLinkEntity, dataSource.createEntityManager());
|
||||
}
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class TagRepository extends Repository<TagEntity> {
|
||||
constructor(private dataSource: DataSource) {
|
||||
super(TagEntity, dataSource.createEntityManager());
|
||||
}
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class InviteSpaceRepository extends Repository<InviteSpaceEntity> {
|
||||
|
@ -6,6 +6,7 @@ import { SpaceProductAllocationEntity } from './entities/space-product-allocatio
|
||||
import { SpaceEntity } from './entities/space.entity';
|
||||
import { SubspaceProductAllocationEntity } from './entities/subspace/subspace-product-allocation.entity';
|
||||
import { SubspaceEntity } from './entities/subspace/subspace.entity';
|
||||
import { TagEntity } from './entities/tag.entity';
|
||||
|
||||
@Module({
|
||||
providers: [],
|
||||
@ -15,6 +16,7 @@ import { SubspaceEntity } from './entities/subspace/subspace.entity';
|
||||
TypeOrmModule.forFeature([
|
||||
SpaceEntity,
|
||||
SubspaceEntity,
|
||||
TagEntity,
|
||||
InviteSpaceEntity,
|
||||
SpaceProductAllocationEntity,
|
||||
SubspaceProductAllocationEntity,
|
||||
|
@ -1,10 +1,11 @@
|
||||
import { Column, Entity, ManyToOne, OneToMany, Unique } from 'typeorm';
|
||||
import { AbstractEntity } from '../../abstract/entities/abstract.entity';
|
||||
import { DeviceEntity } from '../../device/entities/device.entity';
|
||||
import { Entity, Column, ManyToOne, Unique, ManyToMany } from 'typeorm';
|
||||
import { ProductEntity } from '../../product/entities';
|
||||
import { ProjectEntity } from '../../project/entities';
|
||||
import { AbstractEntity } from '../../abstract/entities/abstract.entity';
|
||||
import { NewTagDto } from '../dtos/tag.dto';
|
||||
import { SpaceModelProductAllocationEntity } from '../../space-model/entities/space-model-product-allocation.entity';
|
||||
import { SubspaceModelProductAllocationEntity } from '../../space-model/entities/subspace-model/subspace-model-product-allocation.entity';
|
||||
import { NewTagDto } from '../dtos/tag.dto';
|
||||
import { DeviceEntity } from '../../device/entities/device.entity';
|
||||
|
||||
@Entity({ name: 'new_tag' })
|
||||
@Unique(['name', 'project'])
|
||||
@ -23,25 +24,31 @@ export class NewTagEntity extends AbstractEntity<NewTagDto> {
|
||||
})
|
||||
name: string;
|
||||
|
||||
@ManyToOne(() => ProductEntity, (product) => product.newTags, {
|
||||
nullable: true,
|
||||
onDelete: 'CASCADE',
|
||||
})
|
||||
public product: ProductEntity;
|
||||
|
||||
@ManyToOne(() => ProjectEntity, (project) => project.tags, {
|
||||
nullable: false,
|
||||
onDelete: 'CASCADE',
|
||||
})
|
||||
public project: ProjectEntity;
|
||||
|
||||
@OneToMany(
|
||||
@ManyToMany(
|
||||
() => SpaceModelProductAllocationEntity,
|
||||
(allocation) => allocation.tag,
|
||||
(allocation) => allocation.tags,
|
||||
)
|
||||
public spaceModelAllocations: SpaceModelProductAllocationEntity[];
|
||||
|
||||
@OneToMany(
|
||||
@ManyToMany(
|
||||
() => SubspaceModelProductAllocationEntity,
|
||||
(allocation) => allocation.tag,
|
||||
(allocation) => allocation.tags,
|
||||
)
|
||||
public subspaceModelAllocations: SubspaceModelProductAllocationEntity[];
|
||||
|
||||
@OneToMany(() => DeviceEntity, (device) => device.tag)
|
||||
@ManyToOne(() => DeviceEntity, (device) => device.tag)
|
||||
public devices: DeviceEntity[];
|
||||
|
||||
constructor(partial: Partial<NewTagEntity>) {
|
||||
|
@ -13,81 +13,142 @@ WITH presence_logs AS (
|
||||
AND p.cat_name = 'hps'
|
||||
),
|
||||
|
||||
-- Intervals when device was in 'presence' (between prev_time and event_time when value='none')
|
||||
presence_intervals AS (
|
||||
raw_absence_intervals AS (
|
||||
SELECT
|
||||
space_id,
|
||||
device_id,
|
||||
prev_time AS start_time,
|
||||
event_time AS end_time
|
||||
FROM presence_logs
|
||||
WHERE value = 'none'
|
||||
AND prev_value = 'presence'
|
||||
AND prev_time IS NOT NULL
|
||||
WHERE prev_value = 'none' AND prev_time IS NOT NULL
|
||||
),
|
||||
|
||||
-- Split intervals across days
|
||||
split_intervals AS (
|
||||
absence_intervals AS (
|
||||
SELECT
|
||||
r.space_id,
|
||||
r.device_id,
|
||||
gs.day,
|
||||
GREATEST(r.start_time, gs.day) AS start_time,
|
||||
LEAST(r.end_time, gs.day + INTERVAL '1 day') AS end_time
|
||||
FROM raw_absence_intervals r
|
||||
CROSS JOIN LATERAL (
|
||||
SELECT generate_series(
|
||||
date_trunc('day', r.start_time),
|
||||
date_trunc('day', r.end_time),
|
||||
INTERVAL '1 day'
|
||||
) AS day
|
||||
) gs
|
||||
WHERE GREATEST(r.start_time, gs.day) < LEAST(r.end_time, gs.day + INTERVAL '1 day')
|
||||
),
|
||||
|
||||
device_counts AS (
|
||||
SELECT space_id, day, COUNT(DISTINCT device_id) AS device_count
|
||||
FROM absence_intervals
|
||||
GROUP BY 1, 2
|
||||
),
|
||||
|
||||
timeline AS (
|
||||
SELECT
|
||||
a.space_id,
|
||||
a.day,
|
||||
a.device_id,
|
||||
a.start_time AS ts,
|
||||
1 AS is_start
|
||||
FROM absence_intervals a
|
||||
UNION ALL
|
||||
SELECT
|
||||
a.space_id,
|
||||
a.day,
|
||||
a.device_id,
|
||||
a.end_time AS ts,
|
||||
0 AS is_start
|
||||
FROM absence_intervals a
|
||||
),
|
||||
|
||||
ordered_events AS (
|
||||
SELECT
|
||||
space_id,
|
||||
generate_series(
|
||||
date_trunc('day', start_time),
|
||||
date_trunc('day', end_time),
|
||||
interval '1 day'
|
||||
)::date AS event_date,
|
||||
GREATEST(start_time, date_trunc('day', start_time)) AS interval_start,
|
||||
LEAST(end_time, date_trunc('day', end_time) + interval '1 day') AS interval_end
|
||||
FROM presence_intervals
|
||||
day,
|
||||
ts,
|
||||
is_start,
|
||||
device_id,
|
||||
SUM(CASE WHEN is_start = 1 THEN 1 ELSE -1 END)
|
||||
OVER (PARTITION BY space_id, day, device_id ORDER BY ts) AS device_active
|
||||
FROM timeline
|
||||
),
|
||||
|
||||
-- Mark and group overlapping intervals per space per day
|
||||
ordered_intervals AS (
|
||||
SELECT
|
||||
space_id,
|
||||
event_date,
|
||||
interval_start,
|
||||
interval_end,
|
||||
LAG(interval_end) OVER (PARTITION BY space_id, event_date ORDER BY interval_start) AS prev_end
|
||||
FROM split_intervals
|
||||
),
|
||||
|
||||
grouped_intervals AS (
|
||||
SELECT *,
|
||||
SUM(CASE
|
||||
WHEN prev_end IS NULL OR interval_start > prev_end THEN 1
|
||||
ELSE 0
|
||||
END) OVER (PARTITION BY space_id, event_date ORDER BY interval_start) AS grp
|
||||
FROM ordered_intervals
|
||||
),
|
||||
|
||||
-- Merge overlapping intervals per group
|
||||
merged_intervals AS (
|
||||
SELECT
|
||||
space_id,
|
||||
event_date,
|
||||
MIN(interval_start) AS merged_start,
|
||||
MAX(interval_end) AS merged_end
|
||||
FROM grouped_intervals
|
||||
GROUP BY space_id, event_date, grp
|
||||
),
|
||||
|
||||
-- Sum durations of merged intervals
|
||||
summed_intervals AS (
|
||||
device_state_changes AS (
|
||||
SELECT
|
||||
space_id,
|
||||
event_date,
|
||||
SUM(EXTRACT(EPOCH FROM (merged_end - merged_start))) AS raw_occupied_seconds
|
||||
FROM merged_intervals
|
||||
GROUP BY space_id, event_date
|
||||
),
|
||||
day,
|
||||
ts,
|
||||
SUM(CASE WHEN is_start = 1 THEN 1 ELSE -1 END)
|
||||
OVER (PARTITION BY space_id, day ORDER BY ts) AS net_active_devices
|
||||
FROM (
|
||||
SELECT DISTINCT space_id, day, ts, is_start
|
||||
FROM timeline
|
||||
) t
|
||||
),
|
||||
|
||||
final_data AS (
|
||||
absence_windows AS (
|
||||
SELECT
|
||||
dc.space_id,
|
||||
dc.day,
|
||||
ts AS start_time,
|
||||
LEAD(ts) OVER (PARTITION BY dc.space_id, dc.day ORDER BY ts) AS end_time
|
||||
FROM device_state_changes dsc
|
||||
JOIN device_counts dc ON dc.space_id = dsc.space_id AND dc.day = dsc.day
|
||||
WHERE net_active_devices = 0
|
||||
),
|
||||
|
||||
empty_periods AS (
|
||||
SELECT
|
||||
space_id,
|
||||
day,
|
||||
EXTRACT(EPOCH FROM (end_time - start_time)) AS unoccupied_seconds
|
||||
FROM absence_windows
|
||||
WHERE end_time IS NOT NULL
|
||||
),
|
||||
|
||||
unoccupied_summary AS (
|
||||
SELECT
|
||||
space_id,
|
||||
day,
|
||||
SUM(unoccupied_seconds) AS total_unoccupied_seconds
|
||||
FROM empty_periods
|
||||
GROUP BY space_id, day
|
||||
),
|
||||
|
||||
-- Include device count even for days with 0 unoccupied time
|
||||
all_days_with_devices AS (
|
||||
SELECT
|
||||
space_id,
|
||||
DATE(event_time) AS day,
|
||||
COUNT(DISTINCT device_id) AS device_count
|
||||
FROM presence_logs
|
||||
GROUP BY 1, 2
|
||||
),
|
||||
|
||||
final_occupancy AS (
|
||||
SELECT
|
||||
d.space_id,
|
||||
d.day,
|
||||
d.device_count,
|
||||
COALESCE(u.total_unoccupied_seconds, 0) AS unoccupied_seconds,
|
||||
86400 - COALESCE(u.total_unoccupied_seconds, 0) AS occupied_seconds
|
||||
FROM all_days_with_devices d
|
||||
LEFT JOIN unoccupied_summary u
|
||||
ON d.space_id = u.space_id AND d.day = u.day
|
||||
)
|
||||
, final_data as (
|
||||
SELECT
|
||||
space_id,
|
||||
event_date,
|
||||
LEAST(raw_occupied_seconds, 86400) AS occupied_seconds,
|
||||
ROUND(LEAST(raw_occupied_seconds, 86400) / 86400.0 * 100, 2) AS occupancy_percentage
|
||||
FROM summed_intervals
|
||||
ORDER BY space_id, event_date)
|
||||
day,
|
||||
device_count,
|
||||
occupied_seconds,
|
||||
ROUND(occupied_seconds / 86400.0 * 100, 2) AS occupancy_percentage
|
||||
FROM final_occupancy
|
||||
ORDER BY space_id, day)
|
||||
|
||||
|
||||
INSERT INTO public."space-daily-occupancy-duration" (
|
||||
|
@ -10,7 +10,8 @@ presence_logs AS (
|
||||
l.device_id,
|
||||
l.event_time,
|
||||
l.value,
|
||||
LAG(l.event_time) OVER (PARTITION BY l.device_id ORDER BY l.event_time) AS prev_time
|
||||
LAG(l.event_time) OVER (PARTITION BY l.device_id ORDER BY l.event_time) AS prev_time,
|
||||
LAG(l.value) OVER (PARTITION BY l.device_id ORDER BY l.event_time) AS prev_value
|
||||
FROM device d
|
||||
JOIN "device-status-log" l ON d.uuid = l.device_id
|
||||
JOIN product p ON p.uuid = d.product_device_uuid
|
||||
@ -18,77 +19,147 @@ presence_logs AS (
|
||||
AND p.cat_name = 'hps'
|
||||
),
|
||||
|
||||
presence_intervals AS (
|
||||
raw_absence_intervals AS (
|
||||
SELECT
|
||||
space_id,
|
||||
device_id,
|
||||
prev_time AS start_time,
|
||||
event_time AS end_time
|
||||
FROM presence_logs
|
||||
WHERE value = 'none' AND prev_time IS NOT NULL
|
||||
WHERE prev_value = 'none' AND prev_time IS NOT NULL
|
||||
),
|
||||
|
||||
split_intervals AS (
|
||||
absence_intervals AS (
|
||||
SELECT
|
||||
r.space_id,
|
||||
r.device_id,
|
||||
gs.day,
|
||||
GREATEST(r.start_time, gs.day) AS start_time,
|
||||
LEAST(r.end_time, gs.day + INTERVAL '1 day') AS end_time
|
||||
FROM raw_absence_intervals r
|
||||
CROSS JOIN LATERAL (
|
||||
SELECT generate_series(
|
||||
date_trunc('day', r.start_time),
|
||||
date_trunc('day', r.end_time),
|
||||
INTERVAL '1 day'
|
||||
) AS day
|
||||
) gs
|
||||
WHERE GREATEST(r.start_time, gs.day) < LEAST(r.end_time, gs.day + INTERVAL '1 day')
|
||||
),
|
||||
|
||||
device_counts AS (
|
||||
SELECT space_id, day, COUNT(DISTINCT device_id) AS device_count
|
||||
FROM absence_intervals
|
||||
GROUP BY 1, 2
|
||||
),
|
||||
|
||||
timeline AS (
|
||||
SELECT
|
||||
a.space_id,
|
||||
a.day,
|
||||
a.device_id,
|
||||
a.start_time AS ts,
|
||||
1 AS is_start
|
||||
FROM absence_intervals a
|
||||
UNION ALL
|
||||
SELECT
|
||||
a.space_id,
|
||||
a.day,
|
||||
a.device_id,
|
||||
a.end_time AS ts,
|
||||
0 AS is_start
|
||||
FROM absence_intervals a
|
||||
),
|
||||
|
||||
ordered_events AS (
|
||||
SELECT
|
||||
space_id,
|
||||
generate_series(
|
||||
date_trunc('day', start_time),
|
||||
date_trunc('day', end_time),
|
||||
interval '1 day'
|
||||
)::date AS event_date,
|
||||
GREATEST(start_time, date_trunc('day', start_time)) AS interval_start,
|
||||
LEAST(end_time, date_trunc('day', end_time) + INTERVAL '1 day') AS interval_end
|
||||
FROM presence_intervals
|
||||
day,
|
||||
ts,
|
||||
is_start,
|
||||
device_id,
|
||||
SUM(CASE WHEN is_start = 1 THEN 1 ELSE -1 END)
|
||||
OVER (PARTITION BY space_id, day, device_id ORDER BY ts) AS device_active
|
||||
FROM timeline
|
||||
),
|
||||
|
||||
ordered_intervals AS (
|
||||
SELECT
|
||||
space_id,
|
||||
event_date,
|
||||
interval_start,
|
||||
interval_end,
|
||||
LAG(interval_end) OVER (PARTITION BY space_id, event_date ORDER BY interval_start) AS prev_end
|
||||
FROM split_intervals
|
||||
),
|
||||
|
||||
grouped_intervals AS (
|
||||
SELECT *,
|
||||
SUM(CASE
|
||||
WHEN prev_end IS NULL OR interval_start > prev_end THEN 1
|
||||
ELSE 0
|
||||
END) OVER (PARTITION BY space_id, event_date ORDER BY interval_start) AS grp
|
||||
FROM ordered_intervals
|
||||
),
|
||||
|
||||
merged_intervals AS (
|
||||
SELECT
|
||||
space_id,
|
||||
event_date,
|
||||
MIN(interval_start) AS merged_start,
|
||||
MAX(interval_end) AS merged_end
|
||||
FROM grouped_intervals
|
||||
GROUP BY space_id, event_date, grp
|
||||
),
|
||||
|
||||
summed_intervals AS (
|
||||
device_state_changes AS (
|
||||
SELECT
|
||||
space_id,
|
||||
event_date,
|
||||
SUM(EXTRACT(EPOCH FROM (merged_end - merged_start))) AS raw_occupied_seconds
|
||||
FROM merged_intervals
|
||||
GROUP BY space_id, event_date
|
||||
day,
|
||||
ts,
|
||||
SUM(CASE WHEN is_start = 1 THEN 1 ELSE -1 END)
|
||||
OVER (PARTITION BY space_id, day ORDER BY ts) AS net_active_devices
|
||||
FROM (
|
||||
SELECT DISTINCT space_id, day, ts, is_start
|
||||
FROM timeline
|
||||
) t
|
||||
),
|
||||
|
||||
final_data AS (
|
||||
absence_windows AS (
|
||||
SELECT
|
||||
s.space_id,
|
||||
s.event_date,
|
||||
LEAST(raw_occupied_seconds, 86400) AS occupied_seconds,
|
||||
ROUND(LEAST(raw_occupied_seconds, 86400) / 86400.0 * 100, 2) AS occupancy_percentage
|
||||
FROM summed_intervals s
|
||||
JOIN params p
|
||||
dc.space_id,
|
||||
dc.day,
|
||||
ts AS start_time,
|
||||
LEAD(ts) OVER (PARTITION BY dc.space_id, dc.day ORDER BY ts) AS end_time
|
||||
FROM device_state_changes dsc
|
||||
JOIN device_counts dc ON dc.space_id = dsc.space_id AND dc.day = dsc.day
|
||||
WHERE net_active_devices = 0
|
||||
),
|
||||
|
||||
empty_periods AS (
|
||||
SELECT
|
||||
space_id,
|
||||
day,
|
||||
EXTRACT(EPOCH FROM (end_time - start_time)) AS unoccupied_seconds
|
||||
FROM absence_windows
|
||||
WHERE end_time IS NOT NULL
|
||||
),
|
||||
|
||||
unoccupied_summary AS (
|
||||
SELECT
|
||||
space_id,
|
||||
day,
|
||||
SUM(unoccupied_seconds) AS total_unoccupied_seconds
|
||||
FROM empty_periods
|
||||
GROUP BY space_id, day
|
||||
),
|
||||
|
||||
-- Include device count even for days with 0 unoccupied time
|
||||
all_days_with_devices AS (
|
||||
SELECT
|
||||
space_id,
|
||||
DATE(event_time) AS day,
|
||||
COUNT(DISTINCT device_id) AS device_count
|
||||
FROM presence_logs
|
||||
GROUP BY 1, 2
|
||||
),
|
||||
|
||||
final_occupancy AS (
|
||||
SELECT
|
||||
d.space_id,
|
||||
d.day,
|
||||
d.device_count,
|
||||
COALESCE(u.total_unoccupied_seconds, 0) AS unoccupied_seconds,
|
||||
86400 - COALESCE(u.total_unoccupied_seconds, 0) AS occupied_seconds
|
||||
FROM all_days_with_devices d
|
||||
LEFT JOIN unoccupied_summary u
|
||||
ON d.space_id = u.space_id AND d.day = u.day
|
||||
),
|
||||
|
||||
final_data as(
|
||||
SELECT
|
||||
space_id,
|
||||
day,
|
||||
device_count,
|
||||
occupied_seconds,
|
||||
ROUND(occupied_seconds / 86400.0 * 100, 2) AS occupancy_percentage
|
||||
FROM final_occupancy s
|
||||
JOIN params p
|
||||
ON p.space_id = s.space_id
|
||||
AND p.event_date = s.event_date
|
||||
)
|
||||
ORDER BY space_id, DAY)
|
||||
|
||||
|
||||
INSERT INTO public."space-daily-occupancy-duration" (
|
||||
space_uuid,
|
||||
|
@ -12,4 +12,8 @@ AND (
|
||||
P.event_year IS NULL
|
||||
OR TO_CHAR(psdsd.event_date, 'YYYY') = TO_CHAR(P.event_year, 'YYYY')
|
||||
)
|
||||
ORDER BY space_uuid, event_date
|
||||
ORDER BY space_uuid, event_date
|
||||
|
||||
|
||||
|
||||
|
||||
|
@ -13,78 +13,156 @@ WITH presence_logs AS (
|
||||
AND p.cat_name = 'hps'
|
||||
),
|
||||
|
||||
-- Intervals when device was in 'presence' (between prev_time and event_time when value='none')
|
||||
presence_intervals AS (
|
||||
-- Intervals when device was in 'absence' (between prev_time and event_time when value='none')
|
||||
raw_absence_intervals AS (
|
||||
SELECT
|
||||
space_id,
|
||||
device_id,
|
||||
prev_time AS start_time,
|
||||
event_time AS end_time
|
||||
FROM presence_logs
|
||||
WHERE value = 'none'
|
||||
AND prev_value = 'presence'
|
||||
WHERE value <> 'none'
|
||||
AND prev_value = 'none'
|
||||
AND prev_time IS NOT NULL
|
||||
),
|
||||
|
||||
-- Split intervals across days
|
||||
split_intervals AS (
|
||||
-- Split intervals that span multiple days into day-specific chunks
|
||||
absence_intervals AS (
|
||||
SELECT
|
||||
r.space_id,
|
||||
r.device_id,
|
||||
GREATEST(r.start_time, gs.day::timestamp) AS start_time,
|
||||
LEAST(r.end_time, (gs.day + INTERVAL '1 day' - INTERVAL '1 second')::timestamp) AS end_time
|
||||
FROM raw_absence_intervals r
|
||||
CROSS JOIN LATERAL (
|
||||
SELECT generate_series(
|
||||
date_trunc('day', r.start_time),
|
||||
date_trunc('day', r.end_time),
|
||||
INTERVAL '1 day'
|
||||
) AS day
|
||||
) gs
|
||||
WHERE GREATEST(r.start_time, gs.day::timestamp) < LEAST(r.end_time, (gs.day + INTERVAL '1 day')::timestamp)
|
||||
),
|
||||
|
||||
-- FIXED: Count devices based on presence_logs OR absence_intervals
|
||||
devices_per_day AS (
|
||||
SELECT
|
||||
space_id,
|
||||
generate_series(
|
||||
date_trunc('day', start_time),
|
||||
date_trunc('day', end_time),
|
||||
interval '1 day'
|
||||
)::date AS event_date,
|
||||
GREATEST(start_time, date_trunc('day', start_time)) AS interval_start,
|
||||
LEAST(end_time, date_trunc('day', end_time) + interval '1 day') AS interval_end
|
||||
FROM presence_intervals
|
||||
day,
|
||||
COUNT(DISTINCT device_id) AS device_count
|
||||
FROM (
|
||||
-- Devices that logged events on that day
|
||||
SELECT space_id, DATE(event_time) AS day, device_id
|
||||
FROM presence_logs
|
||||
|
||||
UNION
|
||||
|
||||
-- Devices that had absence intervals on that day
|
||||
SELECT space_id, DATE(start_time) AS day, device_id
|
||||
FROM absence_intervals
|
||||
) combined
|
||||
GROUP BY space_id, day
|
||||
),
|
||||
|
||||
-- Mark and group overlapping intervals per space per day
|
||||
ordered_intervals AS (
|
||||
SELECT
|
||||
space_id,
|
||||
event_date,
|
||||
interval_start,
|
||||
interval_end,
|
||||
LAG(interval_end) OVER (PARTITION BY space_id, event_date ORDER BY interval_start) AS prev_end
|
||||
FROM split_intervals
|
||||
),
|
||||
|
||||
grouped_intervals AS (
|
||||
SELECT *,
|
||||
SUM(CASE
|
||||
WHEN prev_end IS NULL OR interval_start > prev_end THEN 1
|
||||
ELSE 0
|
||||
END) OVER (PARTITION BY space_id, event_date ORDER BY interval_start) AS grp
|
||||
FROM ordered_intervals
|
||||
),
|
||||
|
||||
-- Merge overlapping intervals per group
|
||||
merged_intervals AS (
|
||||
SELECT
|
||||
space_id,
|
||||
event_date,
|
||||
MIN(interval_start) AS merged_start,
|
||||
MAX(interval_end) AS merged_end
|
||||
FROM grouped_intervals
|
||||
GROUP BY space_id, event_date, grp
|
||||
),
|
||||
|
||||
-- Sum durations of merged intervals
|
||||
summed_intervals AS (
|
||||
-- For multi-device spaces, find all time periods when ALL devices were absent
|
||||
multi_device_unoccupied AS (
|
||||
WITH device_absence_per_day AS (
|
||||
SELECT
|
||||
a.space_id,
|
||||
DATE(a.start_time) AS day,
|
||||
a.device_id,
|
||||
a.start_time,
|
||||
a.end_time,
|
||||
d.device_count
|
||||
FROM absence_intervals a
|
||||
JOIN devices_per_day d ON a.space_id = d.space_id AND DATE(a.start_time) = d.day
|
||||
WHERE d.device_count > 1
|
||||
),
|
||||
-- Generate time slots for each day with multiple devices
|
||||
time_ranges AS (
|
||||
SELECT
|
||||
space_id,
|
||||
day,
|
||||
day::timestamp AS range_start,
|
||||
(day + INTERVAL '1 day')::timestamp AS range_end,
|
||||
device_count
|
||||
FROM devices_per_day
|
||||
WHERE device_count > 1
|
||||
),
|
||||
|
||||
-- Find all time periods when all devices were absent
|
||||
all_devices_absent AS (
|
||||
SELECT
|
||||
t.space_id,
|
||||
t.day,
|
||||
t.range_start,
|
||||
t.range_end,
|
||||
t.device_count,
|
||||
-- Find the latest start time of all devices' absence intervals
|
||||
MAX(a.start_time) OVER (PARTITION BY t.space_id, t.day) AS max_start_time,
|
||||
-- Find the earliest end time of all devices' absence intervals
|
||||
MIN(a.end_time) OVER (PARTITION BY t.space_id, t.day) AS min_end_time
|
||||
FROM time_ranges t
|
||||
LEFT JOIN device_absence_per_day a ON
|
||||
t.space_id = a.space_id AND
|
||||
t.day = a.day
|
||||
GROUP BY t.space_id, t.day, t.range_start, t.range_end, t.device_count, a.start_time, a.end_time
|
||||
)
|
||||
|
||||
-- Calculate total unoccupied seconds when all devices were absent
|
||||
SELECT
|
||||
space_id,
|
||||
event_date,
|
||||
SUM(EXTRACT(EPOCH FROM (merged_end - merged_start))) AS raw_occupied_seconds
|
||||
FROM merged_intervals
|
||||
GROUP BY space_id, event_date
|
||||
day,
|
||||
CASE
|
||||
WHEN max_start_time IS NULL OR min_end_time IS NULL THEN 0
|
||||
WHEN max_start_time >= min_end_time THEN 0
|
||||
ELSE EXTRACT(EPOCH FROM (LEAST(min_end_time, range_end) - GREATEST(max_start_time, range_start)))
|
||||
END AS unoccupied_seconds
|
||||
FROM all_devices_absent
|
||||
GROUP BY space_id, day, range_start, range_end, device_count, max_start_time, min_end_time
|
||||
HAVING COUNT(*) = device_count -- Only include periods when all devices were absent
|
||||
)
|
||||
,
|
||||
|
||||
-- Calculate unoccupied time for spaces with single device reporting
|
||||
single_device_unoccupied AS (
|
||||
SELECT
|
||||
a.space_id,
|
||||
DATE(a.start_time) AS day,
|
||||
SUM(EXTRACT(EPOCH FROM (a.end_time - a.start_time))) AS unoccupied_seconds
|
||||
FROM absence_intervals a
|
||||
JOIN devices_per_day d ON a.space_id = d.space_id AND DATE(a.start_time) = d.day
|
||||
WHERE d.device_count = 1
|
||||
GROUP BY a.space_id, DATE(a.start_time)
|
||||
)
|
||||
,
|
||||
|
||||
-- Combine results from both single and multi-device cases
|
||||
combined_unoccupied AS (
|
||||
SELECT space_id, day, unoccupied_seconds FROM single_device_unoccupied
|
||||
UNION ALL
|
||||
SELECT space_id, day, unoccupied_seconds FROM multi_device_unoccupied
|
||||
),
|
||||
|
||||
-- Calculate total occupied time per space per day
|
||||
daily_occupancy AS (
|
||||
SELECT
|
||||
space_id,
|
||||
day,
|
||||
-- Total seconds in day (86400) minus unoccupied seconds
|
||||
86400 - COALESCE(SUM(unoccupied_seconds), 0) AS occupied_seconds
|
||||
FROM combined_unoccupied
|
||||
GROUP BY space_id, day
|
||||
)
|
||||
|
||||
-- Final output with capped seconds and percentage
|
||||
-- Final result
|
||||
SELECT
|
||||
space_id,
|
||||
event_date,
|
||||
LEAST(raw_occupied_seconds, 86400) AS occupied_seconds,
|
||||
ROUND(LEAST(raw_occupied_seconds, 86400) / 86400.0 * 100, 2) AS occupancy_percentage
|
||||
FROM summed_intervals
|
||||
ORDER BY space_id, event_date;
|
||||
day,
|
||||
occupied_seconds,
|
||||
-- Also include percentage for convenience
|
||||
ROUND((occupied_seconds / 86400.0) * 100, 2) AS occupancy_percentage
|
||||
FROM daily_occupancy
|
||||
ORDER BY space_id, day;
|
||||
|
||||
|
@ -1,7 +1,7 @@
|
||||
import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import axios from 'axios';
|
||||
import * as nodemailer from 'nodemailer';
|
||||
import axios from 'axios';
|
||||
import {
|
||||
SEND_EMAIL_API_URL_DEV,
|
||||
SEND_EMAIL_API_URL_PROD,
|
||||
@ -83,17 +83,12 @@ export class EmailService {
|
||||
);
|
||||
}
|
||||
}
|
||||
async sendEmailWithTemplate({
|
||||
email,
|
||||
name,
|
||||
isEnable,
|
||||
isDelete,
|
||||
}: {
|
||||
email: string;
|
||||
name: string;
|
||||
isEnable: boolean;
|
||||
isDelete: boolean;
|
||||
}): Promise<void> {
|
||||
async sendEmailWithTemplate(
|
||||
email: string,
|
||||
name: string,
|
||||
isEnable: boolean,
|
||||
isDelete: boolean,
|
||||
): Promise<void> {
|
||||
const isProduction = process.env.NODE_ENV === 'production';
|
||||
const API_TOKEN = this.configService.get<string>(
|
||||
'email-config.MAILTRAP_API_TOKEN',
|
||||
|
@ -10,7 +10,6 @@
|
||||
"format": "prettier --write \"apps/**/*.ts\" \"libs/**/*.ts\"",
|
||||
"start": "npm run test && node dist/main",
|
||||
"start:dev": "npm run test && npx nest start --watch",
|
||||
"dev": "npx nest start --watch",
|
||||
"start:debug": "npm run test && npx nest start --debug --watch",
|
||||
"start:prod": "npm run test && node dist/main",
|
||||
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
|
||||
|
@ -1,42 +1,42 @@
|
||||
import { SeederModule } from '@app/common/seed/seeder.module';
|
||||
import { Module } from '@nestjs/common';
|
||||
import { ConfigModule } from '@nestjs/config';
|
||||
import { APP_INTERCEPTOR } from '@nestjs/core';
|
||||
import { WinstonModule } from 'nest-winston';
|
||||
import { AuthenticationModule } from './auth/auth.module';
|
||||
import { AutomationModule } from './automation/automation.module';
|
||||
import { ClientModule } from './client/client.module';
|
||||
import { DeviceCommissionModule } from './commission-device/commission-device.module';
|
||||
import { CommunityModule } from './community/community.module';
|
||||
import config from './config';
|
||||
import { DeviceMessagesSubscriptionModule } from './device-messages/device-messages.module';
|
||||
import { DeviceModule } from './device/device.module';
|
||||
import { DoorLockModule } from './door-lock/door.lock.module';
|
||||
import { AuthenticationModule } from './auth/auth.module';
|
||||
import { UserModule } from './users/user.module';
|
||||
import { GroupModule } from './group/group.module';
|
||||
import { HealthModule } from './health/health.module';
|
||||
import { DeviceModule } from './device/device.module';
|
||||
import { UserDevicePermissionModule } from './user-device-permission/user-device-permission.module';
|
||||
import { CommunityModule } from './community/community.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';
|
||||
import { SceneModule } from './scene/scene.module';
|
||||
import { DoorLockModule } from './door-lock/door.lock.module';
|
||||
import { APP_GUARD, APP_INTERCEPTOR } from '@nestjs/core';
|
||||
import { LoggingInterceptor } from './interceptors/logging.interceptor';
|
||||
import { InviteUserModule } from './invite-user/invite-user.module';
|
||||
import { PermissionModule } from './permission/permission.module';
|
||||
import { PowerClampModule } from './power-clamp/power-clamp.module';
|
||||
import { PrivacyPolicyModule } from './privacy-policy/privacy-policy.module';
|
||||
import { AutomationModule } from './automation/automation.module';
|
||||
import { RegionModule } from './region/region.module';
|
||||
import { TimeZoneModule } from './timezone/timezone.module';
|
||||
import { VisitorPasswordModule } from './vistor-password/visitor-password.module';
|
||||
import { ScheduleModule } from './schedule/schedule.module';
|
||||
import { SpaceModule } from './space/space.module';
|
||||
import { ProductModule } from './product';
|
||||
import { ProjectModule } from './project';
|
||||
import { RegionModule } from './region/region.module';
|
||||
import { RoleModule } from './role/role.module';
|
||||
import { SceneModule } from './scene/scene.module';
|
||||
import { ScheduleModule } from './schedule/schedule.module';
|
||||
import { SpaceModelModule } from './space-model';
|
||||
import { SpaceModule } from './space/space.module';
|
||||
import { TagModule } from './tags/tags.module';
|
||||
import { InviteUserModule } from './invite-user/invite-user.module';
|
||||
import { PermissionModule } from './permission/permission.module';
|
||||
import { RoleModule } from './role/role.module';
|
||||
import { TermsConditionsModule } from './terms-conditions/terms-conditions.module';
|
||||
import { TimeZoneModule } from './timezone/timezone.module';
|
||||
import { UserDevicePermissionModule } from './user-device-permission/user-device-permission.module';
|
||||
import { UserNotificationModule } from './user-notification/user-notification.module';
|
||||
import { UserModule } from './users/user.module';
|
||||
import { VisitorPasswordModule } from './vistor-password/visitor-password.module';
|
||||
import { PrivacyPolicyModule } from './privacy-policy/privacy-policy.module';
|
||||
import { TagModule } from './tags/tags.module';
|
||||
import { ClientModule } from './client/client.module';
|
||||
import { DeviceCommissionModule } from './commission-device/commission-device.module';
|
||||
import { PowerClampModule } from './power-clamp/power-clamp.module';
|
||||
import { WinstonModule } from 'nest-winston';
|
||||
import { ThrottlerGuard, ThrottlerModule } from '@nestjs/throttler';
|
||||
import { HealthModule } from './health/health.module';
|
||||
|
||||
import { winstonLoggerOptions } from '../libs/common/src/logger/services/winston.logger';
|
||||
import { AqiModule } from './aqi/aqi.module';
|
||||
import { OccupancyModule } from './occupancy/occupancy.module';
|
||||
import { WeatherModule } from './weather/weather.module';
|
||||
@Module({
|
||||
@ -81,7 +81,6 @@ import { WeatherModule } from './weather/weather.module';
|
||||
HealthModule,
|
||||
OccupancyModule,
|
||||
WeatherModule,
|
||||
AqiModule,
|
||||
],
|
||||
providers: [
|
||||
{
|
||||
|
@ -1,11 +0,0 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { ConfigModule } from '@nestjs/config';
|
||||
import { SqlLoaderService } from '@app/common/helper/services/sql-loader.service';
|
||||
import { AqiService } from './services';
|
||||
import { AqiController } from './controllers';
|
||||
@Module({
|
||||
imports: [ConfigModule],
|
||||
controllers: [AqiController],
|
||||
providers: [AqiService, SqlLoaderService],
|
||||
})
|
||||
export class AqiModule {}
|
@ -1,64 +0,0 @@
|
||||
import { Controller, Get, Param, Query, UseGuards } from '@nestjs/common';
|
||||
import {
|
||||
ApiTags,
|
||||
ApiBearerAuth,
|
||||
ApiOperation,
|
||||
ApiParam,
|
||||
} from '@nestjs/swagger';
|
||||
import { EnableDisableStatusEnum } from '@app/common/constants/days.enum';
|
||||
import { ControllerRoute } from '@app/common/constants/controller-route';
|
||||
import { JwtAuthGuard } from '@app/common/guards/jwt.auth.guard';
|
||||
import { AqiService } from '../services/aqi.service';
|
||||
import {
|
||||
GetAqiDailyBySpaceDto,
|
||||
GetAqiPollutantBySpaceDto,
|
||||
} from '../dto/get-aqi.dto';
|
||||
import { BaseResponseDto } from '@app/common/dto/base.response.dto';
|
||||
import { SpaceParamsDto } from '../dto/aqi-params.dto';
|
||||
|
||||
@ApiTags('AQI Module')
|
||||
@Controller({
|
||||
version: EnableDisableStatusEnum.ENABLED,
|
||||
path: ControllerRoute.AQI.ROUTE,
|
||||
})
|
||||
export class AqiController {
|
||||
constructor(private readonly aqiService: AqiService) {}
|
||||
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@Get('range/space/:spaceUuid')
|
||||
@ApiOperation({
|
||||
summary: ControllerRoute.AQI.ACTIONS.GET_AQI_RANGE_DATA_SUMMARY,
|
||||
description: ControllerRoute.AQI.ACTIONS.GET_AQI_RANGE_DATA_DESCRIPTION,
|
||||
})
|
||||
@ApiParam({
|
||||
name: 'spaceUuid',
|
||||
description: 'UUID of the Space',
|
||||
required: true,
|
||||
})
|
||||
async getAQIRangeDataBySpace(
|
||||
@Param() params: SpaceParamsDto,
|
||||
@Query() query: GetAqiDailyBySpaceDto,
|
||||
): Promise<BaseResponseDto> {
|
||||
return await this.aqiService.getAQIRangeDataBySpace(params, query);
|
||||
}
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@Get('distribution/space/:spaceUuid')
|
||||
@ApiOperation({
|
||||
summary: ControllerRoute.AQI.ACTIONS.GET_AQI_DISTRIBUTION_DATA_SUMMARY,
|
||||
description:
|
||||
ControllerRoute.AQI.ACTIONS.GET_AQI_DISTRIBUTION_DATA_DESCRIPTION,
|
||||
})
|
||||
@ApiParam({
|
||||
name: 'spaceUuid',
|
||||
description: 'UUID of the Space',
|
||||
required: true,
|
||||
})
|
||||
async getAQIDistributionDataBySpace(
|
||||
@Param() params: SpaceParamsDto,
|
||||
@Query() query: GetAqiPollutantBySpaceDto,
|
||||
): Promise<BaseResponseDto> {
|
||||
return await this.aqiService.getAQIDistributionDataBySpace(params, query);
|
||||
}
|
||||
}
|
@ -1 +0,0 @@
|
||||
export * from './aqi.controller';
|
@ -1,7 +0,0 @@
|
||||
import { IsNotEmpty, IsUUID } from 'class-validator';
|
||||
|
||||
export class SpaceParamsDto {
|
||||
@IsUUID('4', { message: 'Invalid UUID format' })
|
||||
@IsNotEmpty()
|
||||
spaceUuid: string;
|
||||
}
|
@ -1,37 +0,0 @@
|
||||
import { PollutantType } from '@app/common/constants/pollutants.enum';
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
import { Matches, IsNotEmpty, IsString } from 'class-validator';
|
||||
|
||||
export class GetAqiDailyBySpaceDto {
|
||||
@ApiProperty({
|
||||
description: 'Month and year in format YYYY-MM',
|
||||
example: '2025-03',
|
||||
required: true,
|
||||
})
|
||||
@Matches(/^\d{4}-(0[1-9]|1[0-2])$/, {
|
||||
message: 'monthDate must be in YYYY-MM format',
|
||||
})
|
||||
@IsNotEmpty()
|
||||
monthDate: string;
|
||||
}
|
||||
export class GetAqiPollutantBySpaceDto {
|
||||
@ApiProperty({
|
||||
description: 'Pollutant Type',
|
||||
enum: PollutantType,
|
||||
example: PollutantType.AQI,
|
||||
required: true,
|
||||
})
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
public pollutantType: string;
|
||||
@ApiProperty({
|
||||
description: 'Month and year in format YYYY-MM',
|
||||
example: '2025-03',
|
||||
required: true,
|
||||
})
|
||||
@Matches(/^\d{4}-(0[1-9]|1[0-2])$/, {
|
||||
message: 'monthDate must be in YYYY-MM format',
|
||||
})
|
||||
@IsNotEmpty()
|
||||
monthDate: string;
|
||||
}
|
@ -1,138 +0,0 @@
|
||||
import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
|
||||
import {
|
||||
GetAqiDailyBySpaceDto,
|
||||
GetAqiPollutantBySpaceDto,
|
||||
} from '../dto/get-aqi.dto';
|
||||
import { SuccessResponseDto } from '@app/common/dto/success.response.dto';
|
||||
import { SpaceParamsDto } from '../dto/aqi-params.dto';
|
||||
import { SqlLoaderService } from '@app/common/helper/services/sql-loader.service';
|
||||
import { DataSource } from 'typeorm';
|
||||
import { SQL_PROCEDURES_PATH } from '@app/common/constants/sql-query-path';
|
||||
import { BaseResponseDto } from '@app/common/dto/base.response.dto';
|
||||
import { convertKeysToCamelCase } from '@app/common/helper/camelCaseConverter';
|
||||
import { PollutantType } from '@app/common/constants/pollutants.enum';
|
||||
|
||||
@Injectable()
|
||||
export class AqiService {
|
||||
constructor(
|
||||
private readonly sqlLoader: SqlLoaderService,
|
||||
private readonly dataSource: DataSource,
|
||||
) {}
|
||||
async getAQIDistributionDataBySpace(
|
||||
params: SpaceParamsDto,
|
||||
query: GetAqiPollutantBySpaceDto,
|
||||
): Promise<BaseResponseDto> {
|
||||
const { monthDate, pollutantType } = query;
|
||||
const { spaceUuid } = params;
|
||||
|
||||
try {
|
||||
const data = await this.executeProcedure(
|
||||
'fact_daily_space_aqi',
|
||||
'proceduce_select_daily_space_aqi',
|
||||
[spaceUuid, monthDate],
|
||||
);
|
||||
|
||||
const categories = [
|
||||
'good',
|
||||
'moderate',
|
||||
'unhealthy_sensitive',
|
||||
'unhealthy',
|
||||
'very_unhealthy',
|
||||
'hazardous',
|
||||
];
|
||||
|
||||
const transformedData = data.map((item) => {
|
||||
const date = new Date(item.event_date).toLocaleDateString('en-CA'); // YYYY-MM-DD
|
||||
|
||||
const categoryData = categories.map((category) => {
|
||||
const key = `${category}_${pollutantType.toLowerCase()}_percentage`;
|
||||
return {
|
||||
type: category,
|
||||
percentage: item[key] ?? 0,
|
||||
};
|
||||
});
|
||||
|
||||
return { date, data: categoryData };
|
||||
});
|
||||
|
||||
const response = this.buildResponse(
|
||||
`AQI distribution data fetched successfully for ${spaceUuid} space and pollutant ${pollutantType}`,
|
||||
transformedData,
|
||||
);
|
||||
return response;
|
||||
} catch (error) {
|
||||
console.error('Failed to fetch AQI distribution data', {
|
||||
error,
|
||||
spaceUuid,
|
||||
});
|
||||
throw new HttpException(
|
||||
error.response?.message || 'Failed to fetch AQI distribution data',
|
||||
error.status || HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async getAQIRangeDataBySpace(
|
||||
params: SpaceParamsDto,
|
||||
query: GetAqiDailyBySpaceDto,
|
||||
): Promise<BaseResponseDto> {
|
||||
const { monthDate } = query;
|
||||
const { spaceUuid } = params;
|
||||
|
||||
try {
|
||||
const data = await this.executeProcedure(
|
||||
'fact_daily_space_aqi',
|
||||
'proceduce_select_daily_space_aqi',
|
||||
[spaceUuid, monthDate],
|
||||
);
|
||||
|
||||
// Define pollutants dynamically
|
||||
const pollutants = Object.values(PollutantType);
|
||||
|
||||
const transformedData = data.map((item) => {
|
||||
const date = new Date(item.event_date).toLocaleDateString('en-CA'); // YYYY-MM-DD
|
||||
const dailyData = pollutants.map((type) => ({
|
||||
type,
|
||||
min: item[`daily_min_${type}`],
|
||||
max: item[`daily_max_${type}`],
|
||||
average: item[`daily_avg_${type}`],
|
||||
}));
|
||||
return { date, data: dailyData };
|
||||
});
|
||||
|
||||
const response = this.buildResponse(
|
||||
`AQI data fetched successfully for ${spaceUuid} space`,
|
||||
transformedData,
|
||||
);
|
||||
return convertKeysToCamelCase(response);
|
||||
} catch (error) {
|
||||
console.error('Failed to fetch AQI data', {
|
||||
error,
|
||||
spaceUuid,
|
||||
});
|
||||
throw new HttpException(
|
||||
error.response?.message || 'Failed to fetch AQI data',
|
||||
error.status || HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private buildResponse(message: string, data: any[]) {
|
||||
return new SuccessResponseDto({
|
||||
message,
|
||||
data,
|
||||
statusCode: HttpStatus.OK,
|
||||
});
|
||||
}
|
||||
private async executeProcedure(
|
||||
procedureFolderName: string,
|
||||
procedureFileName: string,
|
||||
params: (string | number | null)[],
|
||||
): Promise<any[]> {
|
||||
const query = this.loadQuery(procedureFolderName, procedureFileName);
|
||||
return await this.dataSource.query(query, params);
|
||||
}
|
||||
private loadQuery(folderName: string, fileName: string): string {
|
||||
return this.sqlLoader.loadQuery(folderName, fileName, SQL_PROCEDURES_PATH);
|
||||
}
|
||||
}
|
@ -1 +0,0 @@
|
||||
export * from './aqi.service';
|
@ -29,7 +29,6 @@ import {
|
||||
import { PowerClampService } from '@app/common/helper/services/power.clamp.service';
|
||||
import { SqlLoaderService } from '@app/common/helper/services/sql-loader.service';
|
||||
import { OccupancyService } from '@app/common/helper/services/occupancy.service';
|
||||
import { AqiDataService } from '@app/common/helper/services/aqi.data.service';
|
||||
|
||||
@Module({
|
||||
imports: [ConfigModule, SpaceRepositoryModule],
|
||||
@ -58,7 +57,6 @@ import { AqiDataService } from '@app/common/helper/services/aqi.data.service';
|
||||
PowerClampMonthlyRepository,
|
||||
SqlLoaderService,
|
||||
OccupancyService,
|
||||
AqiDataService,
|
||||
],
|
||||
exports: [],
|
||||
})
|
||||
|
@ -1,19 +1,17 @@
|
||||
import * as csv from 'csv-parser';
|
||||
import * as fs from 'fs';
|
||||
import * as csv from 'csv-parser';
|
||||
|
||||
import { ProjectParam } from '@app/common/dto/project-param.dto';
|
||||
import { SuccessResponseDto } from '@app/common/dto/success.response.dto';
|
||||
import { TuyaService } from '@app/common/integrations/tuya/services/tuya.service';
|
||||
import { CommunityRepository } from '@app/common/modules/community/repositories';
|
||||
import { DeviceRepository } from '@app/common/modules/device/repositories';
|
||||
import { ProjectRepository } from '@app/common/modules/project/repositiories';
|
||||
import { SpaceRepository } from '@app/common/modules/space';
|
||||
import { SpaceProductAllocationEntity } from '@app/common/modules/space/entities/space-product-allocation.entity';
|
||||
import { SubspaceProductAllocationEntity } from '@app/common/modules/space/entities/subspace/subspace-product-allocation.entity';
|
||||
import { SubspaceEntity } from '@app/common/modules/space/entities/subspace/subspace.entity';
|
||||
import { SubspaceRepository } from '@app/common/modules/space/repositories/subspace.repository';
|
||||
import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
|
||||
import { DeviceService } from 'src/device/services';
|
||||
import { CommunityRepository } from '@app/common/modules/community/repositories';
|
||||
import { SpaceRepository } from '@app/common/modules/space';
|
||||
import { SubspaceRepository } from '@app/common/modules/space/repositories/subspace.repository';
|
||||
import { SubspaceEntity } from '@app/common/modules/space/entities/subspace/subspace.entity';
|
||||
import { DeviceRepository } from '@app/common/modules/device/repositories';
|
||||
import { SuccessResponseDto } from '@app/common/dto/success.response.dto';
|
||||
import { ProjectParam } from '@app/common/dto/project-param.dto';
|
||||
import { ProjectRepository } from '@app/common/modules/project/repositiories';
|
||||
|
||||
@Injectable()
|
||||
export class DeviceCommissionService {
|
||||
@ -120,7 +118,7 @@ export class DeviceCommissionService {
|
||||
where: { uuid: spaceId },
|
||||
relations: [
|
||||
'productAllocations',
|
||||
'productAllocations.tag',
|
||||
'productAllocations.tags',
|
||||
'productAllocations.product',
|
||||
],
|
||||
});
|
||||
@ -137,7 +135,7 @@ export class DeviceCommissionService {
|
||||
where: { uuid: subspaceId },
|
||||
relations: [
|
||||
'productAllocations',
|
||||
'productAllocations.tag',
|
||||
'productAllocations.tags',
|
||||
'productAllocations.product',
|
||||
],
|
||||
});
|
||||
@ -153,23 +151,19 @@ export class DeviceCommissionService {
|
||||
subspace?.productAllocations || space.productAllocations;
|
||||
|
||||
const match = allocations
|
||||
.map(
|
||||
({
|
||||
product,
|
||||
tag,
|
||||
}:
|
||||
| SpaceProductAllocationEntity
|
||||
| SubspaceProductAllocationEntity) => ({ product, tag }),
|
||||
.flatMap((pa) =>
|
||||
(pa.tags || []).map((tag) => ({ product: pa.product, tag })),
|
||||
)
|
||||
.find(
|
||||
({ tag, product }) =>
|
||||
tag.name === tagName && product.name === productName,
|
||||
);
|
||||
.find(({ tag }) => tag.name === tagName);
|
||||
|
||||
if (!match) {
|
||||
console.error(
|
||||
`No matching tag-product combination found for Device ID: ${rawDeviceId}`,
|
||||
);
|
||||
console.error(`No matching tag found for Device ID: ${rawDeviceId}`);
|
||||
failureCount.value++;
|
||||
return;
|
||||
}
|
||||
|
||||
if (match.product.name !== productName) {
|
||||
console.error(`Product name mismatch for Device ID: ${rawDeviceId}`);
|
||||
failureCount.value++;
|
||||
return;
|
||||
}
|
||||
|
@ -8,6 +8,7 @@ import {
|
||||
SpaceLinkRepository,
|
||||
SpaceProductAllocationRepository,
|
||||
SpaceRepository,
|
||||
TagRepository,
|
||||
} from '@app/common/modules/space/repositories';
|
||||
import { UserSpaceRepository } from '@app/common/modules/user/repositories';
|
||||
import { UserRepositoryModule } from '@app/common/modules/user/user.repository.module';
|
||||
@ -63,7 +64,6 @@ import {
|
||||
} from '@app/common/modules/power-clamp/repositories';
|
||||
import { SqlLoaderService } from '@app/common/helper/services/sql-loader.service';
|
||||
import { OccupancyService } from '@app/common/helper/services/occupancy.service';
|
||||
import { AqiDataService } from '@app/common/helper/services/aqi.data.service';
|
||||
|
||||
@Module({
|
||||
imports: [ConfigModule, SpaceRepositoryModule, UserRepositoryModule],
|
||||
@ -78,7 +78,6 @@ import { AqiDataService } from '@app/common/helper/services/aqi.data.service';
|
||||
ProjectRepository,
|
||||
SpaceService,
|
||||
InviteSpaceRepository,
|
||||
// Todo: find out why this is needed
|
||||
SpaceLinkService,
|
||||
SubSpaceService,
|
||||
ValidationService,
|
||||
@ -87,7 +86,6 @@ import { AqiDataService } from '@app/common/helper/services/aqi.data.service';
|
||||
SpaceProductAllocationService,
|
||||
SpaceLinkRepository,
|
||||
SubspaceRepository,
|
||||
// Todo: find out why this is needed
|
||||
TagService,
|
||||
SubspaceDeviceService,
|
||||
SubspaceProductAllocationService,
|
||||
@ -99,6 +97,7 @@ import { AqiDataService } from '@app/common/helper/services/aqi.data.service';
|
||||
SpaceModelProductAllocationService,
|
||||
SpaceProductAllocationRepository,
|
||||
SubspaceProductAllocationRepository,
|
||||
TagRepository,
|
||||
SubspaceModelRepository,
|
||||
SubspaceModelProductAllocationService,
|
||||
SpaceModelProductAllocationRepoitory,
|
||||
@ -117,7 +116,6 @@ import { AqiDataService } from '@app/common/helper/services/aqi.data.service';
|
||||
PowerClampMonthlyRepository,
|
||||
SqlLoaderService,
|
||||
OccupancyService,
|
||||
AqiDataService,
|
||||
],
|
||||
exports: [CommunityService, SpacePermissionService],
|
||||
})
|
||||
|
@ -1,3 +1,4 @@
|
||||
import { CommunityService } from '../services/community.service';
|
||||
import {
|
||||
Body,
|
||||
Controller,
|
||||
@ -9,18 +10,17 @@ import {
|
||||
Query,
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import { ApiBearerAuth, ApiOperation, ApiTags } from '@nestjs/swagger';
|
||||
import { ApiTags, ApiBearerAuth, ApiOperation } from '@nestjs/swagger';
|
||||
import { AddCommunityDto } from '../dtos/add.community.dto';
|
||||
import { GetCommunityParams } from '../dtos/get.community.dto';
|
||||
import { UpdateCommunityNameDto } from '../dtos/update.community.dto';
|
||||
import { CommunityService } from '../services/community.service';
|
||||
// import { CheckUserCommunityGuard } from 'src/guards/user.community.guard';
|
||||
import { ControllerRoute } from '@app/common/constants/controller-route';
|
||||
import { BaseResponseDto } from '@app/common/dto/base.response.dto';
|
||||
import { PaginationRequestWithSearchGetListDto } from '@app/common/dto/pagination-with-search.request.dto';
|
||||
import { Permissions } from 'src/decorators/permissions.decorator';
|
||||
import { PermissionsGuard } from 'src/guards/permissions.guard';
|
||||
import { ProjectParam } from '../dtos';
|
||||
import { PermissionsGuard } from 'src/guards/permissions.guard';
|
||||
import { Permissions } from 'src/decorators/permissions.decorator';
|
||||
import { PaginationRequestWithSearchGetListDto } from '@app/common/dto/pagination-with-search.request.dto';
|
||||
|
||||
@ApiTags('Community Module')
|
||||
@Controller({
|
||||
@ -45,21 +45,6 @@ export class CommunityController {
|
||||
return await this.communityService.createCommunity(param, addCommunityDto);
|
||||
}
|
||||
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(PermissionsGuard)
|
||||
@Permissions('COMMUNITY_VIEW')
|
||||
@ApiOperation({
|
||||
summary: ControllerRoute.COMMUNITY.ACTIONS.LIST_COMMUNITY_SUMMARY,
|
||||
description: ControllerRoute.COMMUNITY.ACTIONS.LIST_COMMUNITY_DESCRIPTION,
|
||||
})
|
||||
@Get('v2')
|
||||
async getCommunitiesV2(
|
||||
@Param() param: ProjectParam,
|
||||
@Query() query: PaginationRequestWithSearchGetListDto,
|
||||
): Promise<any> {
|
||||
return this.communityService.getCommunitiesV2(param, query);
|
||||
}
|
||||
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(PermissionsGuard)
|
||||
@Permissions('COMMUNITY_VIEW')
|
||||
|
@ -1,33 +1,29 @@
|
||||
import {
|
||||
ORPHAN_COMMUNITY_NAME,
|
||||
ORPHAN_SPACE_NAME,
|
||||
} from '@app/common/constants/orphan-constant';
|
||||
Injectable,
|
||||
HttpException,
|
||||
HttpStatus,
|
||||
NotFoundException,
|
||||
} from '@nestjs/common';
|
||||
import { AddCommunityDto, GetCommunityParams, ProjectParam } from '../dtos';
|
||||
import { UpdateCommunityNameDto } from '../dtos/update.community.dto';
|
||||
import { BaseResponseDto } from '@app/common/dto/base.response.dto';
|
||||
import { PageResponse } from '@app/common/dto/pagination.response.dto';
|
||||
import { SuccessResponseDto } from '@app/common/dto/success.response.dto';
|
||||
import { TuyaService } from '@app/common/integrations/tuya/services/tuya.service';
|
||||
import {
|
||||
ExtendedTypeORMCustomModelFindAllQuery,
|
||||
TypeORMCustomModel,
|
||||
} from '@app/common/models/typeOrmCustom.model';
|
||||
import { CommunityDto } from '@app/common/modules/community/dtos';
|
||||
import { CommunityEntity } from '@app/common/modules/community/entities';
|
||||
import { PageResponse } from '@app/common/dto/pagination.response.dto';
|
||||
import { CommunityRepository } from '@app/common/modules/community/repositories';
|
||||
import { DeviceEntity } from '@app/common/modules/device/entities';
|
||||
import { CommunityDto } from '@app/common/modules/community/dtos';
|
||||
import { SuccessResponseDto } from '@app/common/dto/success.response.dto';
|
||||
import { TuyaService } from '@app/common/integrations/tuya/services/tuya.service';
|
||||
import { ProjectRepository } from '@app/common/modules/project/repositiories';
|
||||
import { ORPHAN_COMMUNITY_NAME } from '@app/common/constants/orphan-constant';
|
||||
import { ILike, In, Not } from 'typeorm';
|
||||
import { SpaceService } from 'src/space/services';
|
||||
import { SpaceRepository } from '@app/common/modules/space';
|
||||
import { DeviceEntity } from '@app/common/modules/device/entities';
|
||||
import { SpaceEntity } from '@app/common/modules/space/entities/space.entity';
|
||||
import { addSpaceUuidToDevices } from '@app/common/util/device-utils';
|
||||
import {
|
||||
HttpException,
|
||||
HttpStatus,
|
||||
Injectable,
|
||||
NotFoundException,
|
||||
} from '@nestjs/common';
|
||||
import { SpaceService } from 'src/space/services';
|
||||
import { QueryRunner, SelectQueryBuilder } from 'typeorm';
|
||||
import { AddCommunityDto, GetCommunityParams, ProjectParam } from '../dtos';
|
||||
import { UpdateCommunityNameDto } from '../dtos/update.community.dto';
|
||||
|
||||
@Injectable()
|
||||
export class CommunityService {
|
||||
@ -72,18 +68,12 @@ export class CommunityService {
|
||||
}
|
||||
}
|
||||
|
||||
async getCommunityById(
|
||||
params: GetCommunityParams,
|
||||
queryRunner?: QueryRunner,
|
||||
): Promise<BaseResponseDto> {
|
||||
async getCommunityById(params: GetCommunityParams): Promise<BaseResponseDto> {
|
||||
const { communityUuid, projectUuid } = params;
|
||||
|
||||
await this.validateProject(projectUuid);
|
||||
|
||||
const communityRepository =
|
||||
queryRunner?.manager.getRepository(CommunityEntity) ||
|
||||
this.communityRepository;
|
||||
const community = await communityRepository.findOneBy({
|
||||
const community = await this.communityRepository.findOneBy({
|
||||
uuid: communityUuid,
|
||||
});
|
||||
|
||||
@ -103,36 +93,56 @@ export class CommunityService {
|
||||
}
|
||||
|
||||
async getCommunities(
|
||||
{ projectUuid }: ProjectParam,
|
||||
param: ProjectParam,
|
||||
pageable: Partial<ExtendedTypeORMCustomModelFindAllQuery>,
|
||||
): Promise<BaseResponseDto> {
|
||||
try {
|
||||
const project = await this.validateProject(projectUuid);
|
||||
const project = await this.validateProject(param.projectUuid);
|
||||
|
||||
/**
|
||||
* TODO: removing this breaks the code (should be fixed when refactoring @see TypeORMCustomModel
|
||||
*/
|
||||
pageable.where = {};
|
||||
let qb: undefined | SelectQueryBuilder<CommunityEntity> = undefined;
|
||||
pageable.modelName = 'community';
|
||||
pageable.where = {
|
||||
project: { uuid: param.projectUuid },
|
||||
name: Not(`${ORPHAN_COMMUNITY_NAME}-${project.name}`),
|
||||
};
|
||||
|
||||
qb = this.communityRepository
|
||||
.createQueryBuilder('c')
|
||||
.leftJoin('c.spaces', 's', 's.disabled = false')
|
||||
.where('c.project = :projectUuid', { projectUuid })
|
||||
.andWhere(`c.name != '${ORPHAN_COMMUNITY_NAME}-${project.name}'`)
|
||||
.distinct(true);
|
||||
if (pageable.search) {
|
||||
qb.andWhere(
|
||||
`c.name ILIKE '%${pageable.search}%' OR s.space_name ILIKE '%${pageable.search}%'`,
|
||||
);
|
||||
}
|
||||
const matchingCommunities = await this.communityRepository.find({
|
||||
where: {
|
||||
project: { uuid: param.projectUuid },
|
||||
name: ILike(`%${pageable.search}%`),
|
||||
},
|
||||
});
|
||||
|
||||
const matchingSpaces = await this.spaceRepository.find({
|
||||
where: {
|
||||
spaceName: ILike(`%${pageable.search}%`),
|
||||
disabled: false,
|
||||
community: { project: { uuid: param.projectUuid } },
|
||||
},
|
||||
relations: ['community'],
|
||||
});
|
||||
|
||||
const spaceCommunityUuids = [
|
||||
...new Set(matchingSpaces.map((space) => space.community.uuid)),
|
||||
];
|
||||
|
||||
const allMatchedCommunityUuids = [
|
||||
...new Set([
|
||||
...matchingCommunities.map((c) => c.uuid),
|
||||
...spaceCommunityUuids,
|
||||
]),
|
||||
];
|
||||
|
||||
pageable.where = {
|
||||
...pageable.where,
|
||||
uuid: In(allMatchedCommunityUuids),
|
||||
};
|
||||
}
|
||||
const customModel = TypeORMCustomModel(this.communityRepository);
|
||||
|
||||
const { baseResponseDto, paginationResponseDto } =
|
||||
await customModel.findAll({ ...pageable, modelName: 'community' }, qb);
|
||||
await customModel.findAll(pageable);
|
||||
|
||||
// todo: refactor this to minimize the number of queries
|
||||
if (pageable.includeSpaces) {
|
||||
const communitiesWithSpaces = await Promise.all(
|
||||
baseResponseDto.data.map(async (community: CommunityDto) => {
|
||||
@ -140,7 +150,7 @@ export class CommunityService {
|
||||
await this.spaceService.getSpacesHierarchyForCommunity(
|
||||
{
|
||||
communityUuid: community.uuid,
|
||||
projectUuid: projectUuid,
|
||||
projectUuid: param.projectUuid,
|
||||
},
|
||||
{
|
||||
onlyWithDevices: false,
|
||||
@ -170,75 +180,6 @@ export class CommunityService {
|
||||
}
|
||||
}
|
||||
|
||||
async getCommunitiesV2(
|
||||
{ projectUuid }: ProjectParam,
|
||||
{
|
||||
search,
|
||||
includeSpaces,
|
||||
...pageable
|
||||
}: Partial<ExtendedTypeORMCustomModelFindAllQuery>,
|
||||
) {
|
||||
try {
|
||||
const project = await this.validateProject(projectUuid);
|
||||
|
||||
let qb: undefined | SelectQueryBuilder<CommunityEntity> = undefined;
|
||||
|
||||
qb = this.communityRepository
|
||||
.createQueryBuilder('c')
|
||||
.where('c.project = :projectUuid', { projectUuid })
|
||||
.andWhere(`c.name != '${ORPHAN_COMMUNITY_NAME}-${project.name}'`)
|
||||
.distinct(true);
|
||||
|
||||
if (includeSpaces) {
|
||||
qb.leftJoinAndSelect(
|
||||
'c.spaces',
|
||||
'space',
|
||||
'space.disabled = :disabled AND space.spaceName != :orphanSpaceName',
|
||||
{ disabled: false, orphanSpaceName: ORPHAN_SPACE_NAME },
|
||||
)
|
||||
.leftJoinAndSelect('space.parent', 'parent')
|
||||
.leftJoinAndSelect(
|
||||
'space.children',
|
||||
'children',
|
||||
'children.disabled = :disabled',
|
||||
{ disabled: false },
|
||||
);
|
||||
// .leftJoinAndSelect('space.spaceModel', 'spaceModel')
|
||||
}
|
||||
|
||||
if (search) {
|
||||
qb.andWhere(
|
||||
`c.name ILIKE :search ${includeSpaces ? 'OR space.space_name ILIKE :search' : ''}`,
|
||||
{ search },
|
||||
);
|
||||
}
|
||||
|
||||
const customModel = TypeORMCustomModel(this.communityRepository);
|
||||
|
||||
const { baseResponseDto, paginationResponseDto } =
|
||||
await customModel.findAll({ ...pageable, modelName: 'community' }, qb);
|
||||
if (includeSpaces) {
|
||||
baseResponseDto.data = baseResponseDto.data.map((community) => ({
|
||||
...community,
|
||||
spaces: this.spaceService.buildSpaceHierarchy(community.spaces || []),
|
||||
}));
|
||||
}
|
||||
return new PageResponse<CommunityDto>(
|
||||
baseResponseDto,
|
||||
paginationResponseDto,
|
||||
);
|
||||
} catch (error) {
|
||||
// Generic error handling
|
||||
if (error instanceof HttpException) {
|
||||
throw error;
|
||||
}
|
||||
throw new HttpException(
|
||||
error.message || 'An error occurred while fetching communities.',
|
||||
HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async updateCommunity(
|
||||
params: GetCommunityParams,
|
||||
updateCommunityDto: UpdateCommunityNameDto,
|
||||
|
@ -1,11 +1,11 @@
|
||||
import { ControllerRoute } from '@app/common/constants/controller-route';
|
||||
import { EnableDisableStatusEnum } from '@app/common/constants/days.enum';
|
||||
import { Controller, Get, Param, Query, UseGuards } from '@nestjs/common';
|
||||
import { ApiBearerAuth, ApiOperation, ApiTags } from '@nestjs/swagger';
|
||||
import { Permissions } from 'src/decorators/permissions.decorator';
|
||||
import { PermissionsGuard } from 'src/guards/permissions.guard';
|
||||
import { GetDevicesFilterDto, ProjectParam } from '../dtos';
|
||||
import { DeviceService } from '../services/device.service';
|
||||
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 { GetDoorLockDevices, ProjectParam } from '../dtos';
|
||||
|
||||
@ApiTags('Device Module')
|
||||
@Controller({
|
||||
@ -25,7 +25,7 @@ export class DeviceProjectController {
|
||||
})
|
||||
async getAllDevices(
|
||||
@Param() param: ProjectParam,
|
||||
@Query() query: GetDevicesFilterDto,
|
||||
@Query() query: GetDoorLockDevices,
|
||||
) {
|
||||
return await this.deviceService.getAllDevices(param, query);
|
||||
}
|
||||
|
@ -1,7 +1,6 @@
|
||||
import { DeviceTypeEnum } from '@app/common/constants/device-type.enum';
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
import {
|
||||
IsArray,
|
||||
IsEnum,
|
||||
IsNotEmpty,
|
||||
IsOptional,
|
||||
@ -42,7 +41,16 @@ export class GetDeviceLogsDto {
|
||||
@IsOptional()
|
||||
public endTime: string;
|
||||
}
|
||||
|
||||
export class GetDoorLockDevices {
|
||||
@ApiProperty({
|
||||
description: 'Device Type',
|
||||
enum: DeviceTypeEnum,
|
||||
required: false,
|
||||
})
|
||||
@IsEnum(DeviceTypeEnum)
|
||||
@IsOptional()
|
||||
public deviceType: DeviceTypeEnum;
|
||||
}
|
||||
export class GetDevicesBySpaceOrCommunityDto {
|
||||
@ApiProperty({
|
||||
description: 'Device Product Type',
|
||||
@ -64,23 +72,3 @@ export class GetDevicesBySpaceOrCommunityDto {
|
||||
@IsNotEmpty({ message: 'Either spaceUuid or communityUuid must be provided' })
|
||||
requireEither?: never; // This ensures at least one of them is provided
|
||||
}
|
||||
|
||||
export class GetDevicesFilterDto {
|
||||
@ApiProperty({
|
||||
description: 'Device Type',
|
||||
enum: DeviceTypeEnum,
|
||||
required: false,
|
||||
})
|
||||
@IsEnum(DeviceTypeEnum)
|
||||
@IsOptional()
|
||||
public deviceType: DeviceTypeEnum;
|
||||
@ApiProperty({
|
||||
description: 'List of Space IDs to filter devices',
|
||||
required: false,
|
||||
example: ['60d21b4667d0d8992e610c85', '60d21b4967d0d8992e610c86'],
|
||||
})
|
||||
@IsOptional()
|
||||
@IsArray()
|
||||
@IsUUID('4', { each: true })
|
||||
public spaces?: string[];
|
||||
}
|
||||
|
@ -1,46 +1,39 @@
|
||||
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 { ORPHAN_SPACE_NAME } from './../../../libs/common/src/constants/orphan-constant';
|
||||
import { ProductRepository } from './../../../libs/common/src/modules/product/repositories/product.repository';
|
||||
import {
|
||||
BadRequestException,
|
||||
forwardRef,
|
||||
Injectable,
|
||||
HttpException,
|
||||
HttpStatus,
|
||||
Inject,
|
||||
Injectable,
|
||||
NotFoundException,
|
||||
BadRequestException,
|
||||
forwardRef,
|
||||
Inject,
|
||||
} from '@nestjs/common';
|
||||
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 { ConfigService } from '@nestjs/config';
|
||||
import {
|
||||
AddDeviceDto,
|
||||
AddSceneToFourSceneDeviceDto,
|
||||
AssignDeviceToSpaceDto,
|
||||
UpdateDeviceDto,
|
||||
AssignDeviceToSpaceDto,
|
||||
} 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,
|
||||
@ -48,29 +41,33 @@ import {
|
||||
ControlDeviceDto,
|
||||
GetSceneFourSceneDeviceDto,
|
||||
} from '../dtos/control.device.dto';
|
||||
import { DeleteSceneFromSceneDeviceDto } from '../dtos/delete.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 {
|
||||
GetDeviceLogsDto,
|
||||
GetDevicesBySpaceOrCommunityDto,
|
||||
GetDevicesFilterDto,
|
||||
} 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';
|
||||
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';
|
||||
|
||||
@Injectable()
|
||||
export class DeviceService {
|
||||
@ -201,6 +198,46 @@ 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,
|
||||
@ -955,20 +992,19 @@ export class DeviceService {
|
||||
|
||||
async getAllDevices(
|
||||
param: ProjectParam,
|
||||
{ deviceType, spaces }: GetDevicesFilterDto,
|
||||
query: GetDoorLockDevices,
|
||||
): Promise<BaseResponseDto> {
|
||||
try {
|
||||
await this.validateProject(param.projectUuid);
|
||||
if (deviceType === DeviceTypeEnum.DOOR_LOCK) {
|
||||
return await this.getDoorLockDevices(param.projectUuid, spaces);
|
||||
} else if (!deviceType) {
|
||||
if (query.deviceType === DeviceTypeEnum.DOOR_LOCK) {
|
||||
return await this.getDoorLockDevices(param.projectUuid);
|
||||
} else if (!query.deviceType) {
|
||||
const devices = await this.deviceRepository.find({
|
||||
where: {
|
||||
isActive: true,
|
||||
spaceDevice: {
|
||||
uuid: spaces && spaces.length ? In(spaces) : undefined,
|
||||
spaceName: Not(ORPHAN_SPACE_NAME),
|
||||
community: { project: { uuid: param.projectUuid } },
|
||||
spaceName: Not(ORPHAN_SPACE_NAME),
|
||||
},
|
||||
},
|
||||
relations: [
|
||||
@ -1163,6 +1199,39 @@ 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(
|
||||
@ -1262,6 +1331,27 @@ 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,
|
||||
@ -1564,7 +1654,23 @@ export class DeviceService {
|
||||
}
|
||||
}
|
||||
|
||||
async getDoorLockDevices(projectUuid: string, spaces?: string[]) {
|
||||
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);
|
||||
|
||||
const devices = await this.deviceRepository.find({
|
||||
@ -1574,7 +1680,6 @@ export class DeviceService {
|
||||
},
|
||||
spaceDevice: {
|
||||
spaceName: Not(ORPHAN_SPACE_NAME),
|
||||
uuid: spaces && spaces.length ? In(spaces) : undefined,
|
||||
community: {
|
||||
project: {
|
||||
uuid: projectUuid,
|
||||
@ -1755,39 +1860,4 @@ 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}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -29,7 +29,6 @@ import {
|
||||
import { SqlLoaderService } from '@app/common/helper/services/sql-loader.service';
|
||||
import { OccupancyService } from '@app/common/helper/services/occupancy.service';
|
||||
import { CommunityRepository } from '@app/common/modules/community/repositories';
|
||||
import { AqiDataService } from '@app/common/helper/services/aqi.data.service';
|
||||
@Module({
|
||||
imports: [ConfigModule, DeviceRepositoryModule],
|
||||
controllers: [DoorLockController],
|
||||
@ -57,7 +56,6 @@ import { AqiDataService } from '@app/common/helper/services/aqi.data.service';
|
||||
SqlLoaderService,
|
||||
OccupancyService,
|
||||
CommunityRepository,
|
||||
AqiDataService,
|
||||
],
|
||||
exports: [DoorLockService],
|
||||
})
|
||||
|
@ -27,7 +27,6 @@ import {
|
||||
import { SqlLoaderService } from '@app/common/helper/services/sql-loader.service';
|
||||
import { OccupancyService } from '@app/common/helper/services/occupancy.service';
|
||||
import { CommunityRepository } from '@app/common/modules/community/repositories';
|
||||
import { AqiDataService } from '@app/common/helper/services/aqi.data.service';
|
||||
@Module({
|
||||
imports: [ConfigModule, DeviceRepositoryModule],
|
||||
controllers: [GroupController],
|
||||
@ -54,7 +53,6 @@ import { AqiDataService } from '@app/common/helper/services/aqi.data.service';
|
||||
SqlLoaderService,
|
||||
OccupancyService,
|
||||
CommunityRepository,
|
||||
AqiDataService,
|
||||
],
|
||||
exports: [GroupService],
|
||||
})
|
||||
|
@ -1,87 +1,89 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { ConfigModule } from '@nestjs/config';
|
||||
import { InviteUserController } from './controllers/invite-user.controller';
|
||||
import { InviteUserService } from './services/invite-user.service';
|
||||
import { InviteUserController } from './controllers/invite-user.controller';
|
||||
import { ConfigModule } from '@nestjs/config';
|
||||
|
||||
import { DeviceStatusFirebaseService } from '@app/common/firebase/devices-status/services/devices-status.service';
|
||||
import { AqiDataService } from '@app/common/helper/services/aqi.data.service';
|
||||
import { OccupancyService } from '@app/common/helper/services/occupancy.service';
|
||||
import { PowerClampService } from '@app/common/helper/services/power.clamp.service';
|
||||
import { SqlLoaderService } from '@app/common/helper/services/sql-loader.service';
|
||||
import { TuyaService } from '@app/common/integrations/tuya/services/tuya.service';
|
||||
import { AutomationRepository } from '@app/common/modules/automation/repositories';
|
||||
import { CommunityRepository } from '@app/common/modules/community/repositories';
|
||||
import { DeviceStatusLogRepository } from '@app/common/modules/device-status-log/repositories';
|
||||
import {
|
||||
DeviceRepository,
|
||||
DeviceUserPermissionRepository,
|
||||
} from '@app/common/modules/device/repositories';
|
||||
UserRepository,
|
||||
UserSpaceRepository,
|
||||
} from '@app/common/modules/user/repositories';
|
||||
import { InviteUserRepositoryModule } from '@app/common/modules/Invite-user/Invite-user.repository.module';
|
||||
import {
|
||||
InviteUserRepository,
|
||||
InviteUserSpaceRepository,
|
||||
} from '@app/common/modules/Invite-user/repositiories';
|
||||
import { PermissionTypeRepository } from '@app/common/modules/permission/repositories';
|
||||
import {
|
||||
PowerClampDailyRepository,
|
||||
PowerClampHourlyRepository,
|
||||
PowerClampMonthlyRepository,
|
||||
} from '@app/common/modules/power-clamp/repositories';
|
||||
import { ProductRepository } from '@app/common/modules/product/repositories';
|
||||
import { ProjectRepository } from '@app/common/modules/project/repositiories';
|
||||
import { RegionRepository } from '@app/common/modules/region/repositories';
|
||||
import { RoleTypeRepository } from '@app/common/modules/role-type/repositories';
|
||||
import { SceneDeviceRepository } from '@app/common/modules/scene-device/repositories';
|
||||
import {
|
||||
SceneIconRepository,
|
||||
SceneRepository,
|
||||
} from '@app/common/modules/scene/repositories';
|
||||
import {
|
||||
InviteSpaceRepository,
|
||||
SpaceLinkRepository,
|
||||
SpaceProductAllocationRepository,
|
||||
SpaceRepository,
|
||||
} from '@app/common/modules/space';
|
||||
import {
|
||||
SpaceModelProductAllocationRepoitory,
|
||||
SpaceModelRepository,
|
||||
SubspaceModelProductAllocationRepoitory,
|
||||
SubspaceModelRepository,
|
||||
} from '@app/common/modules/space-model';
|
||||
import {
|
||||
SubspaceProductAllocationRepository,
|
||||
SubspaceRepository,
|
||||
} from '@app/common/modules/space/repositories/subspace.repository';
|
||||
import { NewTagRepository } from '@app/common/modules/tag/repositories/tag-repository';
|
||||
import { TimeZoneRepository } from '@app/common/modules/timezone/repositories';
|
||||
import {
|
||||
UserRepository,
|
||||
UserSpaceRepository,
|
||||
} from '@app/common/modules/user/repositories';
|
||||
import { EmailService } from '@app/common/util/email.service';
|
||||
import { CommunityModule } from 'src/community/community.module';
|
||||
import { CommunityService } from 'src/community/services';
|
||||
import { DeviceService } from 'src/device/services';
|
||||
import { ProjectUserService } from 'src/project/services/project-user.service';
|
||||
import { SceneService } from 'src/scene/services';
|
||||
import {
|
||||
SpaceModelService,
|
||||
SubSpaceModelService,
|
||||
} from 'src/space-model/services';
|
||||
import { SpaceModelProductAllocationService } from 'src/space-model/services/space-model-product-allocation.service';
|
||||
import { SubspaceModelProductAllocationService } from 'src/space-model/services/subspace/subspace-model-product-allocation.service';
|
||||
import {
|
||||
SpaceLinkService,
|
||||
SpaceService,
|
||||
SpaceUserService,
|
||||
SubspaceDeviceService,
|
||||
SubSpaceService,
|
||||
ValidationService,
|
||||
} from 'src/space/services';
|
||||
import { SpaceProductAllocationService } from 'src/space/services/space-product-allocation.service';
|
||||
import { SubspaceProductAllocationService } from 'src/space/services/subspace/subspace-product-allocation.service';
|
||||
import { TagService as NewTagService } from 'src/tags/services';
|
||||
import { UserDevicePermissionService } from 'src/user-device-permission/services';
|
||||
import { CommunityService } from 'src/community/services';
|
||||
import {
|
||||
InviteSpaceRepository,
|
||||
SpaceLinkRepository,
|
||||
SpaceProductAllocationRepository,
|
||||
SpaceRepository,
|
||||
TagRepository,
|
||||
} from '@app/common/modules/space';
|
||||
import { SpaceModelRepository } from '@app/common/modules/space-model';
|
||||
import { CommunityRepository } from '@app/common/modules/community/repositories';
|
||||
import { ProjectRepository } from '@app/common/modules/project/repositiories';
|
||||
import { TuyaService } from '@app/common/integrations/tuya/services/tuya.service';
|
||||
import { UserService, UserSpaceService } from 'src/users/services';
|
||||
import { UserDevicePermissionService } from 'src/user-device-permission/services';
|
||||
import {
|
||||
DeviceRepository,
|
||||
DeviceUserPermissionRepository,
|
||||
} from '@app/common/modules/device/repositories';
|
||||
import { PermissionTypeRepository } from '@app/common/modules/permission/repositories';
|
||||
import { ProjectUserService } from 'src/project/services/project-user.service';
|
||||
import { RoleTypeRepository } from '@app/common/modules/role-type/repositories';
|
||||
import { RegionRepository } from '@app/common/modules/region/repositories';
|
||||
import { TimeZoneRepository } from '@app/common/modules/timezone/repositories';
|
||||
import { CommunityModule } from 'src/community/community.module';
|
||||
import { TagService as NewTagService } from 'src/tags/services';
|
||||
import { TagService } from 'src/space/services/tag';
|
||||
import {
|
||||
SpaceModelService,
|
||||
SubSpaceModelService,
|
||||
} from 'src/space-model/services';
|
||||
import { SpaceProductAllocationService } from 'src/space/services/space-product-allocation.service';
|
||||
import {
|
||||
SubspaceProductAllocationRepository,
|
||||
SubspaceRepository,
|
||||
} from '@app/common/modules/space/repositories/subspace.repository';
|
||||
import { SubspaceProductAllocationService } from 'src/space/services/subspace/subspace-product-allocation.service';
|
||||
import {
|
||||
SpaceModelProductAllocationRepoitory,
|
||||
SubspaceModelProductAllocationRepoitory,
|
||||
SubspaceModelRepository,
|
||||
} from '@app/common/modules/space-model';
|
||||
import { NewTagRepository } from '@app/common/modules/tag/repositories/tag-repository';
|
||||
import { ProductRepository } from '@app/common/modules/product/repositories';
|
||||
import { SpaceModelProductAllocationService } from 'src/space-model/services/space-model-product-allocation.service';
|
||||
import { SubspaceModelProductAllocationService } from 'src/space-model/services/subspace/subspace-model-product-allocation.service';
|
||||
import { DeviceService } from 'src/device/services';
|
||||
import { SceneDeviceRepository } from '@app/common/modules/scene-device/repositories';
|
||||
import { DeviceStatusFirebaseService } from '@app/common/firebase/devices-status/services/devices-status.service';
|
||||
import { SceneService } from 'src/scene/services';
|
||||
import { DeviceStatusLogRepository } from '@app/common/modules/device-status-log/repositories';
|
||||
import {
|
||||
SceneIconRepository,
|
||||
SceneRepository,
|
||||
} from '@app/common/modules/scene/repositories';
|
||||
import { AutomationRepository } from '@app/common/modules/automation/repositories';
|
||||
import {
|
||||
PowerClampHourlyRepository,
|
||||
PowerClampDailyRepository,
|
||||
PowerClampMonthlyRepository,
|
||||
} from '@app/common/modules/power-clamp/repositories';
|
||||
import { PowerClampService } from '@app/common/helper/services/power.clamp.service';
|
||||
import { SqlLoaderService } from '@app/common/helper/services/sql-loader.service';
|
||||
import { OccupancyService } from '@app/common/helper/services/occupancy.service';
|
||||
|
||||
@Module({
|
||||
imports: [ConfigModule, InviteUserRepositoryModule, CommunityModule],
|
||||
@ -114,6 +116,7 @@ import { UserService, UserSpaceService } from 'src/users/services';
|
||||
TimeZoneRepository,
|
||||
SpaceService,
|
||||
InviteSpaceRepository,
|
||||
SpaceLinkService,
|
||||
SubSpaceService,
|
||||
ValidationService,
|
||||
NewTagService,
|
||||
@ -121,6 +124,7 @@ import { UserService, UserSpaceService } from 'src/users/services';
|
||||
SpaceProductAllocationService,
|
||||
SpaceLinkRepository,
|
||||
SubspaceRepository,
|
||||
TagService,
|
||||
SubspaceDeviceService,
|
||||
SubspaceProductAllocationService,
|
||||
SpaceModelRepository,
|
||||
@ -131,6 +135,7 @@ import { UserService, UserSpaceService } from 'src/users/services';
|
||||
SpaceModelProductAllocationService,
|
||||
SpaceProductAllocationRepository,
|
||||
SubspaceProductAllocationRepository,
|
||||
TagRepository,
|
||||
SubspaceModelRepository,
|
||||
SubspaceModelProductAllocationService,
|
||||
SpaceModelProductAllocationRepoitory,
|
||||
@ -149,7 +154,6 @@ import { UserService, UserSpaceService } from 'src/users/services';
|
||||
PowerClampMonthlyRepository,
|
||||
SqlLoaderService,
|
||||
OccupancyService,
|
||||
AqiDataService,
|
||||
],
|
||||
exports: [InviteUserService],
|
||||
})
|
||||
|
@ -1,42 +1,36 @@
|
||||
import { RoleType } from '@app/common/constants/role.type.enum';
|
||||
import { UserStatusEnum } from '@app/common/constants/user-status.enum';
|
||||
import {
|
||||
Injectable,
|
||||
HttpException,
|
||||
HttpStatus,
|
||||
BadRequestException,
|
||||
} from '@nestjs/common';
|
||||
import { AddUserInvitationDto } from '../dtos';
|
||||
import { BaseResponseDto } from '@app/common/dto/base.response.dto';
|
||||
import { UserStatusEnum } from '@app/common/constants/user-status.enum';
|
||||
import { SuccessResponseDto } from '@app/common/dto/success.response.dto';
|
||||
import { generateRandomString } from '@app/common/helper/randomString';
|
||||
import { InviteUserEntity } from '@app/common/modules/Invite-user/entities';
|
||||
import { EntityManager, In, IsNull, Not, QueryRunner } from 'typeorm';
|
||||
import { DataSource } from 'typeorm';
|
||||
import { UserEntity } from '@app/common/modules/user/entities';
|
||||
import { RoleType } from '@app/common/constants/role.type.enum';
|
||||
import {
|
||||
InviteUserRepository,
|
||||
InviteUserSpaceRepository,
|
||||
} from '@app/common/modules/Invite-user/repositiories';
|
||||
import { RoleTypeRepository } from '@app/common/modules/role-type/repositories';
|
||||
import { SpaceRepository } from '@app/common/modules/space';
|
||||
import { SpaceEntity } from '@app/common/modules/space/entities/space.entity';
|
||||
import { UserEntity } from '@app/common/modules/user/entities';
|
||||
import { CheckEmailDto } from '../dtos/check-email.dto';
|
||||
import { UserRepository } from '@app/common/modules/user/repositories';
|
||||
import { EmailService } from '@app/common/util/email.service';
|
||||
import {
|
||||
BadRequestException,
|
||||
HttpException,
|
||||
HttpStatus,
|
||||
Injectable,
|
||||
} from '@nestjs/common';
|
||||
import { SpaceUserService } from 'src/space/services';
|
||||
import { UserSpaceService } from 'src/users/services';
|
||||
import {
|
||||
DataSource,
|
||||
EntityManager,
|
||||
In,
|
||||
IsNull,
|
||||
Not,
|
||||
QueryRunner,
|
||||
} from 'typeorm';
|
||||
import { AddUserInvitationDto } from '../dtos';
|
||||
import { SpaceRepository } from '@app/common/modules/space';
|
||||
import { ActivateCodeDto } from '../dtos/active-code.dto';
|
||||
import { CheckEmailDto } from '../dtos/check-email.dto';
|
||||
import { UserSpaceService } from 'src/users/services';
|
||||
import { SpaceUserService } from 'src/space/services';
|
||||
import {
|
||||
DisableUserInvitationDto,
|
||||
UpdateUserInvitationDto,
|
||||
} from '../dtos/update.invite-user.dto';
|
||||
import { RoleTypeRepository } from '@app/common/modules/role-type/repositories';
|
||||
import { InviteUserEntity } from '@app/common/modules/Invite-user/entities';
|
||||
import { SpaceEntity } from '@app/common/modules/space/entities/space.entity';
|
||||
|
||||
@Injectable()
|
||||
export class InviteUserService {
|
||||
@ -664,12 +658,12 @@ export class InviteUserService {
|
||||
HttpStatus.BAD_REQUEST,
|
||||
);
|
||||
}
|
||||
await this.emailService.sendEmailWithTemplate({
|
||||
email: userData.email,
|
||||
name: userData.firstName,
|
||||
isEnable: !disable,
|
||||
isDelete: false,
|
||||
});
|
||||
await this.emailService.sendEmailWithTemplate(
|
||||
userData.email,
|
||||
userData.firstName,
|
||||
disable,
|
||||
false,
|
||||
);
|
||||
await queryRunner.commitTransaction();
|
||||
|
||||
return new SuccessResponseDto({
|
||||
@ -803,12 +797,12 @@ export class InviteUserService {
|
||||
{ isActive: false },
|
||||
);
|
||||
}
|
||||
await this.emailService.sendEmailWithTemplate({
|
||||
email: userData.email,
|
||||
name: userData.firstName,
|
||||
isEnable: false,
|
||||
isDelete: true,
|
||||
});
|
||||
await this.emailService.sendEmailWithTemplate(
|
||||
userData.email,
|
||||
userData.firstName,
|
||||
false,
|
||||
true,
|
||||
);
|
||||
await queryRunner.commitTransaction();
|
||||
|
||||
return new SuccessResponseDto({
|
||||
|
20
src/main.ts
20
src/main.ts
@ -1,14 +1,15 @@
|
||||
import { RequestContextMiddleware } from '@app/common/middleware/request-context.middleware';
|
||||
import { SeederService } from '@app/common/seed/services/seeder.service';
|
||||
import { Logger, ValidationPipe } from '@nestjs/common';
|
||||
import { NestFactory } from '@nestjs/core';
|
||||
import { json, urlencoded } from 'body-parser';
|
||||
import { AppModule } from './app.module';
|
||||
import rateLimit from 'express-rate-limit';
|
||||
import helmet from 'helmet';
|
||||
import { WINSTON_MODULE_NEST_PROVIDER } from 'nest-winston';
|
||||
import { setupSwaggerAuthentication } from '../libs/common/src/util/user-auth.swagger.utils';
|
||||
import { AppModule } from './app.module';
|
||||
import { ValidationPipe } from '@nestjs/common';
|
||||
import { json, urlencoded } from 'body-parser';
|
||||
import { SeederService } from '@app/common/seed/services/seeder.service';
|
||||
import { HttpExceptionFilter } from './common/filters/http-exception/http-exception.filter';
|
||||
import { Logger } from '@nestjs/common';
|
||||
import { WINSTON_MODULE_NEST_PROVIDER } from 'nest-winston';
|
||||
import { RequestContextMiddleware } from '@app/common/middleware/request-context.middleware';
|
||||
|
||||
async function bootstrap() {
|
||||
const app = await NestFactory.create(AppModule);
|
||||
@ -29,13 +30,6 @@ async function bootstrap() {
|
||||
}),
|
||||
);
|
||||
|
||||
app.use((req, res, next) => {
|
||||
console.log('Real IP:', req.ip);
|
||||
next();
|
||||
});
|
||||
|
||||
// app.getHttpAdapter().getInstance().set('trust proxy', 1);
|
||||
|
||||
app.use(
|
||||
helmet({
|
||||
contentSecurityPolicy: false,
|
||||
|
@ -1,65 +1,66 @@
|
||||
import { DeviceStatusFirebaseService } from '@app/common/firebase/devices-status/services/devices-status.service';
|
||||
import { AqiDataService } from '@app/common/helper/services/aqi.data.service';
|
||||
import { OccupancyService } from '@app/common/helper/services/occupancy.service';
|
||||
import { PowerClampService } from '@app/common/helper/services/power.clamp.service';
|
||||
import { SqlLoaderService } from '@app/common/helper/services/sql-loader.service';
|
||||
import { TuyaService } from '@app/common/integrations/tuya/services/tuya.service';
|
||||
import { AutomationRepository } from '@app/common/modules/automation/repositories';
|
||||
import { CommunityRepository } from '@app/common/modules/community/repositories';
|
||||
import { DeviceStatusLogRepository } from '@app/common/modules/device-status-log/repositories';
|
||||
import { DeviceRepository } from '@app/common/modules/device/repositories';
|
||||
import { Module } from '@nestjs/common';
|
||||
import { ConfigModule } from '@nestjs/config';
|
||||
import { PowerClampService as PowerClamp } from './services/power-clamp.service';
|
||||
import { PowerClampController } from './controllers';
|
||||
import {
|
||||
PowerClampDailyRepository,
|
||||
PowerClampHourlyRepository,
|
||||
PowerClampMonthlyRepository,
|
||||
} from '@app/common/modules/power-clamp/repositories';
|
||||
import { ProductRepository } from '@app/common/modules/product/repositories';
|
||||
import { ProjectRepository } from '@app/common/modules/project/repositiories';
|
||||
import { SceneDeviceRepository } from '@app/common/modules/scene-device/repositories';
|
||||
import { DeviceRepository } from '@app/common/modules/device/repositories';
|
||||
import {
|
||||
SceneIconRepository,
|
||||
SceneRepository,
|
||||
} from '@app/common/modules/scene/repositories';
|
||||
SpaceDeviceService,
|
||||
SpaceLinkService,
|
||||
SpaceService,
|
||||
SubspaceDeviceService,
|
||||
SubSpaceService,
|
||||
ValidationService,
|
||||
} from 'src/space/services';
|
||||
import { TuyaService } from '@app/common/integrations/tuya/services/tuya.service';
|
||||
import { DeviceService } from 'src/device/services';
|
||||
import {
|
||||
InviteSpaceRepository,
|
||||
SpaceLinkRepository,
|
||||
SpaceProductAllocationRepository,
|
||||
SpaceRepository,
|
||||
TagRepository,
|
||||
} from '@app/common/modules/space';
|
||||
import { CommunityService } from 'src/community/services';
|
||||
import { ProjectRepository } from '@app/common/modules/project/repositiories';
|
||||
import { CommunityRepository } from '@app/common/modules/community/repositories';
|
||||
import {
|
||||
SpaceModelProductAllocationRepoitory,
|
||||
SpaceModelRepository,
|
||||
SubspaceModelProductAllocationRepoitory,
|
||||
SubspaceModelRepository,
|
||||
} from '@app/common/modules/space-model';
|
||||
import {
|
||||
SubspaceProductAllocationRepository,
|
||||
SubspaceRepository,
|
||||
} from '@app/common/modules/space/repositories/subspace.repository';
|
||||
import { NewTagRepository } from '@app/common/modules/tag/repositories/tag-repository';
|
||||
import { Module } from '@nestjs/common';
|
||||
import { ConfigModule } from '@nestjs/config';
|
||||
import { CommunityService } from 'src/community/services';
|
||||
import { DeviceService } from 'src/device/services';
|
||||
import { SceneDeviceRepository } from '@app/common/modules/scene-device/repositories';
|
||||
import { ProductRepository } from '@app/common/modules/product/repositories';
|
||||
import { DeviceStatusFirebaseService } from '@app/common/firebase/devices-status/services/devices-status.service';
|
||||
import { SceneService } from 'src/scene/services';
|
||||
import { PowerClampService } from '@app/common/helper/services/power.clamp.service';
|
||||
import { DeviceStatusLogRepository } from '@app/common/modules/device-status-log/repositories';
|
||||
import {
|
||||
SceneIconRepository,
|
||||
SceneRepository,
|
||||
} from '@app/common/modules/scene/repositories';
|
||||
import { AutomationRepository } from '@app/common/modules/automation/repositories';
|
||||
import { TagService } from 'src/tags/services';
|
||||
import {
|
||||
SpaceModelService,
|
||||
SubSpaceModelService,
|
||||
} from 'src/space-model/services';
|
||||
import { SpaceProductAllocationService } from 'src/space/services/space-product-allocation.service';
|
||||
import { SqlLoaderService } from '@app/common/helper/services/sql-loader.service';
|
||||
import {
|
||||
SubspaceProductAllocationRepository,
|
||||
SubspaceRepository,
|
||||
} from '@app/common/modules/space/repositories/subspace.repository';
|
||||
import { SubspaceProductAllocationService } from 'src/space/services/subspace/subspace-product-allocation.service';
|
||||
import { NewTagRepository } from '@app/common/modules/tag/repositories/tag-repository';
|
||||
import { SpaceModelProductAllocationService } from 'src/space-model/services/space-model-product-allocation.service';
|
||||
import { SubspaceModelProductAllocationService } from 'src/space-model/services/subspace/subspace-model-product-allocation.service';
|
||||
import {
|
||||
SpaceDeviceService,
|
||||
SpaceService,
|
||||
SubspaceDeviceService,
|
||||
SubSpaceService,
|
||||
ValidationService,
|
||||
} from 'src/space/services';
|
||||
import { SpaceProductAllocationService } from 'src/space/services/space-product-allocation.service';
|
||||
import { SubspaceProductAllocationService } from 'src/space/services/subspace/subspace-product-allocation.service';
|
||||
import { TagService } from 'src/tags/services';
|
||||
import { PowerClampController } from './controllers';
|
||||
import { PowerClampService as PowerClamp } from './services/power-clamp.service';
|
||||
import { OccupancyService } from '@app/common/helper/services/occupancy.service';
|
||||
@Module({
|
||||
imports: [ConfigModule],
|
||||
controllers: [PowerClampController],
|
||||
@ -89,6 +90,7 @@ import { PowerClampService as PowerClamp } from './services/power-clamp.service'
|
||||
SceneRepository,
|
||||
AutomationRepository,
|
||||
InviteSpaceRepository,
|
||||
SpaceLinkService,
|
||||
SubSpaceService,
|
||||
TagService,
|
||||
SpaceModelService,
|
||||
@ -103,12 +105,12 @@ import { PowerClampService as PowerClamp } from './services/power-clamp.service'
|
||||
SpaceModelProductAllocationService,
|
||||
SpaceProductAllocationRepository,
|
||||
SubspaceProductAllocationRepository,
|
||||
TagRepository,
|
||||
SubspaceModelRepository,
|
||||
SubspaceModelProductAllocationService,
|
||||
SpaceModelProductAllocationRepoitory,
|
||||
SubspaceModelProductAllocationRepoitory,
|
||||
OccupancyService,
|
||||
AqiDataService,
|
||||
],
|
||||
exports: [PowerClamp],
|
||||
})
|
||||
|
@ -1,72 +1,73 @@
|
||||
import { DeviceStatusFirebaseService } from '@app/common/firebase/devices-status/services/devices-status.service';
|
||||
import { AqiDataService } from '@app/common/helper/services/aqi.data.service';
|
||||
import { OccupancyService } from '@app/common/helper/services/occupancy.service';
|
||||
import { PowerClampService } from '@app/common/helper/services/power.clamp.service';
|
||||
import { SqlLoaderService } from '@app/common/helper/services/sql-loader.service';
|
||||
import { TuyaService } from '@app/common/integrations/tuya/services/tuya.service';
|
||||
import { AutomationRepository } from '@app/common/modules/automation/repositories';
|
||||
import { CommunityRepository } from '@app/common/modules/community/repositories';
|
||||
import { DeviceStatusLogRepository } from '@app/common/modules/device-status-log/repositories';
|
||||
import { DeviceRepository } from '@app/common/modules/device/repositories';
|
||||
import { InviteUserRepository } from '@app/common/modules/Invite-user/repositiories';
|
||||
import {
|
||||
PowerClampDailyRepository,
|
||||
PowerClampHourlyRepository,
|
||||
PowerClampMonthlyRepository,
|
||||
} from '@app/common/modules/power-clamp/repositories';
|
||||
import { ProductRepository } from '@app/common/modules/product/repositories';
|
||||
import { Global, Module } from '@nestjs/common';
|
||||
import { CqrsModule } from '@nestjs/cqrs';
|
||||
import { ProjectController } from './controllers';
|
||||
import { ProjectService } from './services';
|
||||
import { ProjectRepository } from '@app/common/modules/project/repositiories';
|
||||
import { SceneDeviceRepository } from '@app/common/modules/scene-device/repositories';
|
||||
import {
|
||||
SceneIconRepository,
|
||||
SceneRepository,
|
||||
} from '@app/common/modules/scene/repositories';
|
||||
import { CreateOrphanSpaceHandler } from './handler';
|
||||
import {
|
||||
InviteSpaceRepository,
|
||||
SpaceLinkRepository,
|
||||
SpaceProductAllocationRepository,
|
||||
SpaceRepository,
|
||||
TagRepository,
|
||||
} from '@app/common/modules/space';
|
||||
import { CommunityRepository } from '@app/common/modules/community/repositories';
|
||||
import { InviteUserRepository } from '@app/common/modules/Invite-user/repositiories';
|
||||
import { ProjectUserController } from './controllers/project-user.controller';
|
||||
import { ProjectUserService } from './services/project-user.service';
|
||||
import {
|
||||
UserRepository,
|
||||
UserSpaceRepository,
|
||||
} from '@app/common/modules/user/repositories';
|
||||
import {
|
||||
SpaceLinkService,
|
||||
SpaceService,
|
||||
SubspaceDeviceService,
|
||||
SubSpaceService,
|
||||
ValidationService,
|
||||
} from 'src/space/services';
|
||||
import { TagService } from 'src/tags/services';
|
||||
import {
|
||||
SpaceModelService,
|
||||
SubSpaceModelService,
|
||||
} from 'src/space-model/services';
|
||||
import { DeviceService } from 'src/device/services';
|
||||
import { SpaceProductAllocationService } from 'src/space/services/space-product-allocation.service';
|
||||
import {
|
||||
SubspaceProductAllocationRepository,
|
||||
SubspaceRepository,
|
||||
} from '@app/common/modules/space/repositories/subspace.repository';
|
||||
import { SubspaceProductAllocationService } from 'src/space/services/subspace/subspace-product-allocation.service';
|
||||
import { CommunityService } from 'src/community/services';
|
||||
import {
|
||||
SpaceModelProductAllocationRepoitory,
|
||||
SpaceModelRepository,
|
||||
SubspaceModelProductAllocationRepoitory,
|
||||
SubspaceModelRepository,
|
||||
} from '@app/common/modules/space-model';
|
||||
import {
|
||||
SubspaceProductAllocationRepository,
|
||||
SubspaceRepository,
|
||||
} from '@app/common/modules/space/repositories/subspace.repository';
|
||||
import { DeviceRepository } from '@app/common/modules/device/repositories';
|
||||
import { NewTagRepository } from '@app/common/modules/tag/repositories/tag-repository';
|
||||
import {
|
||||
UserRepository,
|
||||
UserSpaceRepository,
|
||||
} from '@app/common/modules/user/repositories';
|
||||
import { Global, Module } from '@nestjs/common';
|
||||
import { CqrsModule } from '@nestjs/cqrs';
|
||||
import { CommunityService } from 'src/community/services';
|
||||
import { DeviceService } from 'src/device/services';
|
||||
import { SceneService } from 'src/scene/services';
|
||||
import {
|
||||
SpaceModelService,
|
||||
SubSpaceModelService,
|
||||
} from 'src/space-model/services';
|
||||
import { ProductRepository } from '@app/common/modules/product/repositories';
|
||||
import { SpaceModelProductAllocationService } from 'src/space-model/services/space-model-product-allocation.service';
|
||||
import { SceneDeviceRepository } from '@app/common/modules/scene-device/repositories';
|
||||
import { DeviceStatusFirebaseService } from '@app/common/firebase/devices-status/services/devices-status.service';
|
||||
import { SceneService } from 'src/scene/services';
|
||||
import { TuyaService } from '@app/common/integrations/tuya/services/tuya.service';
|
||||
import { SubspaceModelProductAllocationService } from 'src/space-model/services/subspace/subspace-model-product-allocation.service';
|
||||
import { DeviceStatusLogRepository } from '@app/common/modules/device-status-log/repositories';
|
||||
import {
|
||||
SpaceService,
|
||||
SubspaceDeviceService,
|
||||
SubSpaceService,
|
||||
ValidationService,
|
||||
} from 'src/space/services';
|
||||
import { SpaceProductAllocationService } from 'src/space/services/space-product-allocation.service';
|
||||
import { SubspaceProductAllocationService } from 'src/space/services/subspace/subspace-product-allocation.service';
|
||||
import { TagService } from 'src/tags/services';
|
||||
import { ProjectController } from './controllers';
|
||||
import { ProjectUserController } from './controllers/project-user.controller';
|
||||
import { CreateOrphanSpaceHandler } from './handler';
|
||||
import { ProjectService } from './services';
|
||||
import { ProjectUserService } from './services/project-user.service';
|
||||
SceneIconRepository,
|
||||
SceneRepository,
|
||||
} from '@app/common/modules/scene/repositories';
|
||||
import { AutomationRepository } from '@app/common/modules/automation/repositories';
|
||||
import { PowerClampService } from '@app/common/helper/services/power.clamp.service';
|
||||
import {
|
||||
PowerClampDailyRepository,
|
||||
PowerClampHourlyRepository,
|
||||
PowerClampMonthlyRepository,
|
||||
} from '@app/common/modules/power-clamp/repositories';
|
||||
import { SqlLoaderService } from '@app/common/helper/services/sql-loader.service';
|
||||
import { OccupancyService } from '@app/common/helper/services/occupancy.service';
|
||||
|
||||
const CommandHandlers = [CreateOrphanSpaceHandler];
|
||||
|
||||
@ -86,6 +87,7 @@ const CommandHandlers = [CreateOrphanSpaceHandler];
|
||||
UserRepository,
|
||||
SpaceService,
|
||||
InviteSpaceRepository,
|
||||
SpaceLinkService,
|
||||
SubSpaceService,
|
||||
ValidationService,
|
||||
TagService,
|
||||
@ -109,6 +111,7 @@ const CommandHandlers = [CreateOrphanSpaceHandler];
|
||||
DeviceStatusFirebaseService,
|
||||
SceneService,
|
||||
TuyaService,
|
||||
TagRepository,
|
||||
SubspaceModelRepository,
|
||||
SubspaceModelProductAllocationService,
|
||||
SpaceModelProductAllocationRepoitory,
|
||||
@ -123,7 +126,6 @@ const CommandHandlers = [CreateOrphanSpaceHandler];
|
||||
PowerClampMonthlyRepository,
|
||||
SqlLoaderService,
|
||||
OccupancyService,
|
||||
AqiDataService,
|
||||
],
|
||||
exports: [ProjectService, CqrsModule],
|
||||
})
|
||||
|
@ -1,17 +1,4 @@
|
||||
import { ORPHAN_COMMUNITY_NAME } from '@app/common/constants/orphan-constant';
|
||||
import { BaseResponseDto } from '@app/common/dto/base.response.dto';
|
||||
import { PageResponse } from '@app/common/dto/pagination.response.dto';
|
||||
import { SuccessResponseDto } from '@app/common/dto/success.response.dto';
|
||||
import {
|
||||
TypeORMCustomModel,
|
||||
TypeORMCustomModelFindAllQuery,
|
||||
} from '@app/common/models/typeOrmCustom.model';
|
||||
import { ProjectDto } from '@app/common/modules/project/dtos';
|
||||
import { ProjectEntity } from '@app/common/modules/project/entities';
|
||||
import { ProjectRepository } from '@app/common/modules/project/repositiories';
|
||||
import { SpaceEntity } from '@app/common/modules/space/entities/space.entity';
|
||||
import { UserRepository } from '@app/common/modules/user/repositories';
|
||||
import { format } from '@fast-csv/format';
|
||||
import {
|
||||
forwardRef,
|
||||
HttpException,
|
||||
@ -19,12 +6,24 @@ import {
|
||||
Inject,
|
||||
Injectable,
|
||||
} from '@nestjs/common';
|
||||
import { CommandBus } from '@nestjs/cqrs';
|
||||
import { SpaceService } from 'src/space/services';
|
||||
import { PassThrough } from 'stream';
|
||||
import { CreateOrphanSpaceCommand } from '../command/create-orphan-space-command';
|
||||
import { CreateProjectDto, GetProjectParam } from '../dto';
|
||||
import { QueryRunner } from 'typeorm';
|
||||
import { BaseResponseDto } from '@app/common/dto/base.response.dto';
|
||||
import { SuccessResponseDto } from '@app/common/dto/success.response.dto';
|
||||
import { ProjectEntity } from '@app/common/modules/project/entities';
|
||||
import {
|
||||
TypeORMCustomModel,
|
||||
TypeORMCustomModelFindAllQuery,
|
||||
} from '@app/common/models/typeOrmCustom.model';
|
||||
import { ProjectDto } from '@app/common/modules/project/dtos';
|
||||
import { PageResponse } from '@app/common/dto/pagination.response.dto';
|
||||
import { CommandBus } from '@nestjs/cqrs';
|
||||
import { CreateOrphanSpaceCommand } from '../command/create-orphan-space-command';
|
||||
import { UserRepository } from '@app/common/modules/user/repositories';
|
||||
import { format } from '@fast-csv/format';
|
||||
import { PassThrough } from 'stream';
|
||||
import { SpaceEntity } from '@app/common/modules/space/entities/space.entity';
|
||||
import { SpaceService } from 'src/space/services';
|
||||
import { ORPHAN_COMMUNITY_NAME } from '@app/common/constants/orphan-constant';
|
||||
|
||||
@Injectable()
|
||||
export class ProjectService {
|
||||
@ -213,14 +212,8 @@ export class ProjectService {
|
||||
}
|
||||
}
|
||||
|
||||
async findOne(
|
||||
uuid: string,
|
||||
queryRunner?: QueryRunner,
|
||||
): Promise<ProjectEntity> {
|
||||
const projectRepository = queryRunner
|
||||
? queryRunner.manager.getRepository(ProjectEntity)
|
||||
: this.projectRepository;
|
||||
const project = await projectRepository.findOne({ where: { uuid } });
|
||||
async findOne(uuid: string): Promise<ProjectEntity> {
|
||||
const project = await this.projectRepository.findOne({ where: { uuid } });
|
||||
if (!project) {
|
||||
throw new HttpException(
|
||||
`Invalid project with uuid ${uuid}`,
|
||||
@ -243,11 +236,11 @@ export class ProjectService {
|
||||
'communities.spaces.parent',
|
||||
'communities.spaces.productAllocations',
|
||||
'communities.spaces.productAllocations.product',
|
||||
'communities.spaces.productAllocations.tag',
|
||||
'communities.spaces.productAllocations.tags',
|
||||
'communities.spaces.subspaces',
|
||||
'communities.spaces.subspaces.productAllocations',
|
||||
'communities.spaces.subspaces.productAllocations.product',
|
||||
'communities.spaces.subspaces.productAllocations.tag',
|
||||
'communities.spaces.subspaces.productAllocations.tags',
|
||||
],
|
||||
});
|
||||
|
||||
@ -310,38 +303,52 @@ export class ProjectService {
|
||||
if (subspace.disabled) continue;
|
||||
|
||||
for (const productAllocation of subspace.productAllocations || []) {
|
||||
for (const tag of productAllocation.tags || []) {
|
||||
csvStream.write({
|
||||
'Device ID': '',
|
||||
'Community Name': space.community?.name || '',
|
||||
'Space Name': space.spaceName,
|
||||
'Space Location': spaceLocation,
|
||||
'Subspace Name': subspace.subspaceName || '',
|
||||
Tag: tag.name,
|
||||
'Product Name': productAllocation.product.name || '',
|
||||
'Community UUID': space.community?.uuid || '',
|
||||
'Space UUID': space.uuid,
|
||||
'Subspace UUID': subspace.uuid,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (const productAllocation of space.productAllocations || []) {
|
||||
for (const tag of productAllocation.tags || []) {
|
||||
csvStream.write({
|
||||
'Device ID': '',
|
||||
'Community Name': space.community?.name || '',
|
||||
'Space Name': space.spaceName,
|
||||
'Space Location': spaceLocation,
|
||||
'Subspace Name': subspace.subspaceName || '',
|
||||
Tag: productAllocation.tag.name,
|
||||
'Subspace Name': '',
|
||||
Tag: tag.name,
|
||||
'Product Name': productAllocation.product.name || '',
|
||||
'Community UUID': space.community?.uuid || '',
|
||||
'Space UUID': space.uuid,
|
||||
'Subspace UUID': subspace.uuid,
|
||||
'Subspace UUID': '',
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
for (const productAllocation of space.productAllocations || []) {
|
||||
csvStream.write({
|
||||
'Device ID': '',
|
||||
'Community Name': space.community?.name || '',
|
||||
'Space Name': space.spaceName,
|
||||
'Space Location': spaceLocation,
|
||||
'Subspace Name': '',
|
||||
Tag: productAllocation.tag.name,
|
||||
'Product Name': productAllocation.product.name || '',
|
||||
'Community UUID': space.community?.uuid || '',
|
||||
'Space UUID': space.uuid,
|
||||
'Subspace UUID': '',
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
csvStream.end();
|
||||
return stream;
|
||||
}
|
||||
|
||||
getSpaceLocation(space: SpaceEntity): string {
|
||||
const names = [];
|
||||
let current = space.parent;
|
||||
while (current) {
|
||||
names.unshift(current.spaceName);
|
||||
current = current.parent;
|
||||
}
|
||||
return names.join(' > ');
|
||||
}
|
||||
}
|
||||
|
@ -1,6 +1,7 @@
|
||||
export * from './create-space-model.dto';
|
||||
export * from './link-space-model.dto';
|
||||
export * from './project-param.dto';
|
||||
export * from './update-space-model.dto';
|
||||
export * from './space-model-param';
|
||||
export * from './subspaces-model-dtos';
|
||||
export * from './update-space-model.dto';
|
||||
export * from './tag-model-dtos';
|
||||
export * from './link-space-model.dto';
|
||||
|
@ -1,14 +1,14 @@
|
||||
import { ModifyAction } from '@app/common/constants/modify-action.enum';
|
||||
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||
import { Type } from 'class-transformer';
|
||||
import {
|
||||
IsArray,
|
||||
IsEnum,
|
||||
IsOptional,
|
||||
IsString,
|
||||
IsOptional,
|
||||
IsArray,
|
||||
ValidateNested,
|
||||
IsEnum,
|
||||
} from 'class-validator';
|
||||
import { ModifyTagDto } from 'src/space/dtos/tag/modify-tag.dto';
|
||||
import { ModifyTagModelDto } from '../tag-model-dtos';
|
||||
import { ModifyAction } from '@app/common/constants/modify-action.enum';
|
||||
|
||||
export class ModifySubspaceModelDto {
|
||||
@ApiProperty({
|
||||
@ -37,11 +37,11 @@ export class ModifySubspaceModelDto {
|
||||
@ApiPropertyOptional({
|
||||
description:
|
||||
'List of tag modifications (add/update/delete) for the subspace',
|
||||
type: [ModifyTagDto],
|
||||
type: [ModifyTagModelDto],
|
||||
})
|
||||
@IsOptional()
|
||||
@IsArray()
|
||||
@ValidateNested({ each: true })
|
||||
@Type(() => ModifyTagDto)
|
||||
tags?: ModifyTagDto[];
|
||||
@Type(() => ModifyTagModelDto)
|
||||
tags?: ModifyTagModelDto[];
|
||||
}
|
||||
|
28
src/space-model/dtos/tag-model-dtos/create-tag-model.dto.ts
Normal file
28
src/space-model/dtos/tag-model-dtos/create-tag-model.dto.ts
Normal file
@ -0,0 +1,28 @@
|
||||
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||
import { IsNotEmpty, IsOptional, IsString } from 'class-validator';
|
||||
|
||||
export class CreateTagModelDto {
|
||||
@ApiProperty({
|
||||
description: 'Tag associated with the space or subspace models',
|
||||
example: 'Temperature Control',
|
||||
})
|
||||
@IsNotEmpty()
|
||||
@IsString()
|
||||
tag: string;
|
||||
|
||||
@ApiPropertyOptional({
|
||||
description: 'UUID of the tag model (required for update/delete)',
|
||||
example: '123e4567-e89b-12d3-a456-426614174000',
|
||||
})
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
uuid?: string;
|
||||
|
||||
@ApiProperty({
|
||||
description: 'ID of the product associated with the tag',
|
||||
example: '123e4567-e89b-12d3-a456-426614174000',
|
||||
})
|
||||
@IsNotEmpty()
|
||||
@IsString()
|
||||
productUuid: string;
|
||||
}
|
3
src/space-model/dtos/tag-model-dtos/index.ts
Normal file
3
src/space-model/dtos/tag-model-dtos/index.ts
Normal file
@ -0,0 +1,3 @@
|
||||
export * from './create-tag-model.dto';
|
||||
export * from './update-tag-model.dto';
|
||||
export * from './modify-tag-model.dto';
|
46
src/space-model/dtos/tag-model-dtos/modify-tag-model.dto.ts
Normal file
46
src/space-model/dtos/tag-model-dtos/modify-tag-model.dto.ts
Normal file
@ -0,0 +1,46 @@
|
||||
import { ModifyAction } from '@app/common/constants/modify-action.enum';
|
||||
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||
import { IsString, IsOptional, IsEnum, IsUUID } from 'class-validator';
|
||||
|
||||
export class ModifyTagModelDto {
|
||||
@ApiProperty({
|
||||
description: 'Action to perform: add, update, or delete',
|
||||
example: ModifyAction.ADD,
|
||||
})
|
||||
@IsEnum(ModifyAction)
|
||||
action: ModifyAction;
|
||||
|
||||
@ApiPropertyOptional({
|
||||
description: 'UUID of the new tag',
|
||||
example: '123e4567-e89b-12d3-a456-426614174000',
|
||||
})
|
||||
@IsOptional()
|
||||
@IsUUID()
|
||||
newTagUuid: string;
|
||||
|
||||
@ApiPropertyOptional({
|
||||
description:
|
||||
'UUID of an existing tag (required for update/delete, optional for add)',
|
||||
example: 'a1b2c3d4-5678-90ef-abcd-1234567890ef',
|
||||
})
|
||||
@IsOptional()
|
||||
@IsUUID()
|
||||
tagUuid?: string;
|
||||
|
||||
@ApiPropertyOptional({
|
||||
description: 'Name of the tag (required for add/update)',
|
||||
example: 'Temperature Sensor',
|
||||
})
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
name?: string;
|
||||
|
||||
@ApiPropertyOptional({
|
||||
description:
|
||||
'UUID of the product associated with the tag (required for add)',
|
||||
example: 'c789a91e-549a-4753-9006-02f89e8170e0',
|
||||
})
|
||||
@IsOptional()
|
||||
@IsUUID()
|
||||
productUuid?: string;
|
||||
}
|
21
src/space-model/dtos/tag-model-dtos/update-tag-model.dto.ts
Normal file
21
src/space-model/dtos/tag-model-dtos/update-tag-model.dto.ts
Normal file
@ -0,0 +1,21 @@
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
import { IsNotEmpty, IsOptional, IsString, IsUUID } from 'class-validator';
|
||||
|
||||
export class UpdateTagModelDto {
|
||||
@ApiProperty({
|
||||
description: 'UUID of the tag to be updated',
|
||||
example: '123e4567-e89b-12d3-a456-426614174000',
|
||||
})
|
||||
@IsNotEmpty()
|
||||
@IsUUID()
|
||||
uuid: string;
|
||||
|
||||
@ApiProperty({
|
||||
description: 'Updated name of the tag',
|
||||
example: 'Updated Tag Name',
|
||||
required: false,
|
||||
})
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
tag?: string;
|
||||
}
|
@ -1,13 +1,48 @@
|
||||
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||
import { Type } from 'class-transformer';
|
||||
import { IsArray, IsOptional, IsString, ValidateNested } from 'class-validator';
|
||||
import { CreateSubspaceModelDto } from './subspaces-model-dtos/create-subspace-model.dto';
|
||||
import { Type } from 'class-transformer';
|
||||
import {
|
||||
DeleteSubspaceModelDto,
|
||||
ModifySubspaceModelDto,
|
||||
UpdateSubspaceModelDto,
|
||||
} from './subspaces-model-dtos';
|
||||
import { CreateSubspaceModelDto } from './subspaces-model-dtos/create-subspace-model.dto';
|
||||
import { ModifyTagDto } from 'src/space/dtos/tag/modify-tag.dto';
|
||||
import { ModifyTagModelDto } from './tag-model-dtos';
|
||||
|
||||
export class ModifySubspacesModelDto {
|
||||
@ApiProperty({
|
||||
description: 'List of subspaces to add',
|
||||
type: [CreateSubspaceModelDto],
|
||||
required: false,
|
||||
})
|
||||
@IsOptional()
|
||||
@IsArray()
|
||||
@ValidateNested({ each: true })
|
||||
@Type(() => CreateSubspaceModelDto)
|
||||
add?: CreateSubspaceModelDto[];
|
||||
|
||||
@ApiProperty({
|
||||
description: 'List of subspaces to add',
|
||||
type: [CreateSubspaceModelDto],
|
||||
required: false,
|
||||
})
|
||||
@IsOptional()
|
||||
@IsArray()
|
||||
@ValidateNested({ each: true })
|
||||
@Type(() => UpdateSubspaceModelDto)
|
||||
update?: UpdateSubspaceModelDto[];
|
||||
|
||||
@ApiProperty({
|
||||
description: 'List of subspaces to delete',
|
||||
type: [DeleteSubspaceModelDto],
|
||||
required: false,
|
||||
})
|
||||
@IsOptional()
|
||||
@IsArray()
|
||||
@ValidateNested({ each: true })
|
||||
@Type(() => DeleteSubspaceModelDto)
|
||||
delete?: DeleteSubspaceModelDto[];
|
||||
}
|
||||
|
||||
export class UpdateSpaceModelDto {
|
||||
@ApiProperty({
|
||||
@ -31,11 +66,11 @@ export class UpdateSpaceModelDto {
|
||||
@ApiPropertyOptional({
|
||||
description:
|
||||
'List of tag modifications (add/update/delete) for the space model',
|
||||
type: [ModifyTagDto],
|
||||
type: [ModifyTagModelDto],
|
||||
})
|
||||
@IsOptional()
|
||||
@IsArray()
|
||||
@ValidateNested({ each: true })
|
||||
@Type(() => ModifyTagDto)
|
||||
tags?: ModifyTagDto[];
|
||||
@Type(() => ModifyTagModelDto)
|
||||
tags?: ModifyTagModelDto[];
|
||||
}
|
||||
|
@ -1,11 +1,11 @@
|
||||
import { CommandHandler, ICommandHandler } from '@nestjs/cqrs';
|
||||
import { PropogateUpdateSpaceModelProductAllocationCommand } from '../commands';
|
||||
import { SpaceProductAllocationRepository } from '@app/common/modules/space';
|
||||
import { SubspaceModelProductAllocationRepoitory } from '@app/common/modules/space-model';
|
||||
import {
|
||||
SubspaceProductAllocationRepository,
|
||||
SubspaceRepository,
|
||||
SubspaceProductAllocationRepository,
|
||||
} from '@app/common/modules/space/repositories/subspace.repository';
|
||||
import { CommandHandler, ICommandHandler } from '@nestjs/cqrs';
|
||||
import { PropogateUpdateSpaceModelProductAllocationCommand } from '../commands';
|
||||
|
||||
@CommandHandler(PropogateUpdateSpaceModelProductAllocationCommand)
|
||||
export class PropogateUpdateSpaceModelProductAllocationHandler
|
||||
@ -31,89 +31,89 @@ export class PropogateUpdateSpaceModelProductAllocationHandler
|
||||
|
||||
console.log(`Processing ${updatedAllocations.length} allocations...`);
|
||||
|
||||
// for (const allocation of updatedAllocations) {
|
||||
// try {
|
||||
// if (allocation.allocation) {
|
||||
// const spaceAllocations = await this.spaceProductRepository.find({
|
||||
// where: { uuid: allocation.allocation.uuid },
|
||||
// relations: ['tags'],
|
||||
// });
|
||||
for (const allocation of updatedAllocations) {
|
||||
try {
|
||||
if (allocation.allocation) {
|
||||
const spaceAllocations = await this.spaceProductRepository.find({
|
||||
where: { uuid: allocation.allocation.uuid },
|
||||
relations: ['tags'],
|
||||
});
|
||||
|
||||
// if (!spaceAllocations || spaceAllocations.length === 0) {
|
||||
// console.warn(
|
||||
// `No space allocations found for UUID: ${allocation.allocation.uuid}`,
|
||||
// );
|
||||
// continue;
|
||||
// }
|
||||
if (!spaceAllocations || spaceAllocations.length === 0) {
|
||||
console.warn(
|
||||
`No space allocations found for UUID: ${allocation.allocation.uuid}`,
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
// if (allocation.tagsAdded?.length) {
|
||||
// for (const spaceAllocation of spaceAllocations) {
|
||||
// spaceAllocation.tags.push(...allocation.tagsAdded);
|
||||
// }
|
||||
// await this.spaceProductRepository.save(spaceAllocations);
|
||||
// console.log(
|
||||
// `Added tags to ${spaceAllocations.length} space allocations.`,
|
||||
// );
|
||||
// }
|
||||
if (allocation.tagsAdded?.length) {
|
||||
for (const spaceAllocation of spaceAllocations) {
|
||||
spaceAllocation.tags.push(...allocation.tagsAdded);
|
||||
}
|
||||
await this.spaceProductRepository.save(spaceAllocations);
|
||||
console.log(
|
||||
`Added tags to ${spaceAllocations.length} space allocations.`,
|
||||
);
|
||||
}
|
||||
|
||||
// if (allocation.tagsRemoved?.length) {
|
||||
// const tagsToRemoveUUIDs = new Set(
|
||||
// allocation.tagsRemoved.map((tag) => tag.uuid),
|
||||
// );
|
||||
if (allocation.tagsRemoved?.length) {
|
||||
const tagsToRemoveUUIDs = new Set(
|
||||
allocation.tagsRemoved.map((tag) => tag.uuid),
|
||||
);
|
||||
|
||||
// for (const spaceAllocation of spaceAllocations) {
|
||||
// spaceAllocation.tags = spaceAllocation.tags.filter(
|
||||
// (tag) => !tagsToRemoveUUIDs.has(tag.uuid),
|
||||
// );
|
||||
// }
|
||||
// await this.spaceProductRepository.save(spaceAllocations);
|
||||
// console.log(
|
||||
// `Removed tags from ${spaceAllocations.length} space allocations.`,
|
||||
// );
|
||||
// }
|
||||
// }
|
||||
for (const spaceAllocation of spaceAllocations) {
|
||||
spaceAllocation.tags = spaceAllocation.tags.filter(
|
||||
(tag) => !tagsToRemoveUUIDs.has(tag.uuid),
|
||||
);
|
||||
}
|
||||
await this.spaceProductRepository.save(spaceAllocations);
|
||||
console.log(
|
||||
`Removed tags from ${spaceAllocations.length} space allocations.`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// if (allocation.deletedAllocation) {
|
||||
// const spaceAllocations = await this.spaceProductRepository.find({
|
||||
// where: { uuid: allocation.deletedAllocation.uuid },
|
||||
// relations: ['tags'],
|
||||
// });
|
||||
if (allocation.deletedAllocation) {
|
||||
const spaceAllocations = await this.spaceProductRepository.find({
|
||||
where: { uuid: allocation.deletedAllocation.uuid },
|
||||
relations: ['tags'],
|
||||
});
|
||||
|
||||
// if (!spaceAllocations || spaceAllocations.length === 0) {
|
||||
// console.warn(
|
||||
// `No space allocations found to delete for UUID: ${allocation.deletedAllocation.uuid}`,
|
||||
// );
|
||||
// continue;
|
||||
// }
|
||||
if (!spaceAllocations || spaceAllocations.length === 0) {
|
||||
console.warn(
|
||||
`No space allocations found to delete for UUID: ${allocation.deletedAllocation.uuid}`,
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
// await this.spaceProductRepository.remove(spaceAllocations);
|
||||
// console.log(
|
||||
// `Deleted ${spaceAllocations.length} space allocations.`,
|
||||
// );
|
||||
// }
|
||||
await this.spaceProductRepository.remove(spaceAllocations);
|
||||
console.log(
|
||||
`Deleted ${spaceAllocations.length} space allocations.`,
|
||||
);
|
||||
}
|
||||
|
||||
// if (allocation.newAllocation) {
|
||||
// const newAllocations = spaces.map((space) =>
|
||||
// this.spaceProductRepository.create({
|
||||
// space,
|
||||
// product: allocation.newAllocation.product,
|
||||
// tag: allocation.newAllocation.tag,
|
||||
// inheritedFromModel: allocation.newAllocation,
|
||||
// }),
|
||||
// );
|
||||
if (allocation.newAllocation) {
|
||||
const newAllocations = spaces.map((space) =>
|
||||
this.spaceProductRepository.create({
|
||||
space,
|
||||
product: allocation.newAllocation.product,
|
||||
tags: allocation.newAllocation.tags,
|
||||
inheritedFromModel: allocation.newAllocation,
|
||||
}),
|
||||
);
|
||||
|
||||
// await this.spaceProductRepository.save(newAllocations);
|
||||
// console.log(
|
||||
// `Created ${newAllocations.length} new space allocations.`,
|
||||
// );
|
||||
// }
|
||||
// } catch (error) {
|
||||
// console.error(
|
||||
// `Error processing allocation update: ${JSON.stringify(allocation)}`,
|
||||
// error,
|
||||
// );
|
||||
// }
|
||||
// }
|
||||
await this.spaceProductRepository.save(newAllocations);
|
||||
console.log(
|
||||
`Created ${newAllocations.length} new space allocations.`,
|
||||
);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(
|
||||
`Error processing allocation update: ${JSON.stringify(allocation)}`,
|
||||
error,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
console.log('Finished processing all allocations.');
|
||||
} catch (error) {
|
||||
|
@ -1,14 +1,15 @@
|
||||
import { ModifyAction } from '@app/common/constants/modify-action.enum';
|
||||
import { CommandHandler, ICommandHandler } from '@nestjs/cqrs';
|
||||
import { PropogateUpdateSpaceModelCommand } from '../commands';
|
||||
import { SpaceProductAllocationRepository } from '@app/common/modules/space';
|
||||
import { SubspaceModelProductAllocationRepoitory } from '@app/common/modules/space-model';
|
||||
import { SpaceEntity } from '@app/common/modules/space/entities/space.entity';
|
||||
import {
|
||||
SubspaceProductAllocationRepository,
|
||||
SubspaceRepository,
|
||||
} from '@app/common/modules/space/repositories/subspace.repository';
|
||||
import { CommandHandler, ICommandHandler } from '@nestjs/cqrs';
|
||||
import { PropogateUpdateSpaceModelCommand } from '../commands';
|
||||
import { SubspaceModelProductAllocationRepoitory } from '@app/common/modules/space-model';
|
||||
import { In } from 'typeorm';
|
||||
import { ISingleSubspaceModel } from '../interfaces';
|
||||
import { SpaceEntity } from '@app/common/modules/space/entities/space.entity';
|
||||
import { ModifyAction } from '@app/common/constants/modify-action.enum';
|
||||
import { IUpdatedAllocations } from '../interfaces/subspace-product-allocation-update-result.interface';
|
||||
|
||||
@CommandHandler(PropogateUpdateSpaceModelCommand)
|
||||
@ -71,48 +72,48 @@ export class PropogateUpdateSpaceModelHandler
|
||||
for (const allocation of allocations) {
|
||||
if (!allocation) continue;
|
||||
|
||||
// if (allocation.allocation) {
|
||||
// try {
|
||||
// const subspaceAllocations =
|
||||
// await this.subspaceProductRepository.find({
|
||||
// where: {
|
||||
// inheritedFromModel: { uuid: allocation.allocation.uuid },
|
||||
// },
|
||||
// relations: ['tags'],
|
||||
// });
|
||||
if (allocation.allocation) {
|
||||
try {
|
||||
const subspaceAllocations =
|
||||
await this.subspaceProductRepository.find({
|
||||
where: {
|
||||
inheritedFromModel: { uuid: allocation.allocation.uuid },
|
||||
},
|
||||
relations: ['tags'],
|
||||
});
|
||||
|
||||
// if (!subspaceAllocations || subspaceAllocations.length === 0)
|
||||
// continue;
|
||||
if (!subspaceAllocations || subspaceAllocations.length === 0)
|
||||
continue;
|
||||
|
||||
// if (allocation.tagsAdded?.length) {
|
||||
// for (const subspaceAllocation of subspaceAllocations) {
|
||||
// subspaceAllocation.tags.push(...allocation.tagsAdded);
|
||||
// }
|
||||
// await this.subspaceProductRepository.save(subspaceAllocations);
|
||||
// console.log(
|
||||
// `Added tags to ${subspaceAllocations.length} subspace allocations.`,
|
||||
// );
|
||||
// }
|
||||
if (allocation.tagsAdded?.length) {
|
||||
for (const subspaceAllocation of subspaceAllocations) {
|
||||
subspaceAllocation.tags.push(...allocation.tagsAdded);
|
||||
}
|
||||
await this.subspaceProductRepository.save(subspaceAllocations);
|
||||
console.log(
|
||||
`Added tags to ${subspaceAllocations.length} subspace allocations.`,
|
||||
);
|
||||
}
|
||||
|
||||
// if (allocation.tagsRemoved?.length) {
|
||||
// const tagsToRemoveUUIDs = allocation.tagsRemoved.map(
|
||||
// (tag) => tag.uuid,
|
||||
// );
|
||||
if (allocation.tagsRemoved?.length) {
|
||||
const tagsToRemoveUUIDs = allocation.tagsRemoved.map(
|
||||
(tag) => tag.uuid,
|
||||
);
|
||||
|
||||
// for (const subspaceAllocation of subspaceAllocations) {
|
||||
// subspaceAllocation.tags = subspaceAllocation.tags.filter(
|
||||
// (tag) => !tagsToRemoveUUIDs.includes(tag.uuid),
|
||||
// );
|
||||
// }
|
||||
// await this.subspaceProductRepository.save(subspaceAllocations);
|
||||
// console.log(
|
||||
// `Removed tags from ${subspaceAllocations.length} subspace allocations.`,
|
||||
// );
|
||||
// }
|
||||
// } catch (error) {
|
||||
// console.error('Error processing allocation update:', error);
|
||||
// }
|
||||
// }
|
||||
for (const subspaceAllocation of subspaceAllocations) {
|
||||
subspaceAllocation.tags = subspaceAllocation.tags.filter(
|
||||
(tag) => !tagsToRemoveUUIDs.includes(tag.uuid),
|
||||
);
|
||||
}
|
||||
await this.subspaceProductRepository.save(subspaceAllocations);
|
||||
console.log(
|
||||
`Removed tags from ${subspaceAllocations.length} subspace allocations.`,
|
||||
);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error processing allocation update:', error);
|
||||
}
|
||||
}
|
||||
|
||||
if (allocation.newAllocation) {
|
||||
try {
|
||||
@ -126,7 +127,7 @@ export class PropogateUpdateSpaceModelHandler
|
||||
const newAllocations = subspaces.map((subspace) =>
|
||||
this.subspaceProductRepository.create({
|
||||
product: allocation.newAllocation.product,
|
||||
tag: allocation.newAllocation.tag,
|
||||
tags: allocation.newAllocation.tags,
|
||||
subspace,
|
||||
inheritedFromModel: allocation.newAllocation,
|
||||
}),
|
||||
@ -197,7 +198,7 @@ export class PropogateUpdateSpaceModelHandler
|
||||
const subspaceAllocation = this.subspaceProductRepository.create({
|
||||
subspace: subspace,
|
||||
product: allocation.product,
|
||||
tag: allocation.tag,
|
||||
tags: allocation.tags,
|
||||
inheritedFromModel: allocation,
|
||||
});
|
||||
await this.subspaceProductRepository.save(subspaceAllocation);
|
||||
@ -210,59 +211,67 @@ export class PropogateUpdateSpaceModelHandler
|
||||
subspaceModel: ISingleSubspaceModel,
|
||||
spaces: SpaceEntity[],
|
||||
) {
|
||||
// const subspaces = await this.subspaceRepository.find({
|
||||
// where: {
|
||||
// subSpaceModel: { uuid: subspaceModel.subspaceModel.uuid },
|
||||
// disabled: false,
|
||||
// },
|
||||
// relations: [
|
||||
// 'productAllocations',
|
||||
// 'productAllocations.product',
|
||||
// 'productAllocations.tags',
|
||||
// ],
|
||||
// });
|
||||
// if (!subspaces.length) {
|
||||
// return;
|
||||
// }
|
||||
// const allocationUuidsToRemove = subspaces.flatMap((subspace) =>
|
||||
// subspace.productAllocations.map((allocation) => allocation.uuid),
|
||||
// );
|
||||
// if (allocationUuidsToRemove.length) {
|
||||
// await this.subspaceProductRepository.delete(allocationUuidsToRemove);
|
||||
// }
|
||||
// await this.subspaceRepository.update(
|
||||
// { uuid: In(subspaces.map((s) => s.uuid)) },
|
||||
// { disabled: true },
|
||||
// );
|
||||
// const relocatedAllocations = subspaceModel.relocatedAllocations || [];
|
||||
// if (!relocatedAllocations.length) {
|
||||
// return;
|
||||
// }
|
||||
// for (const space of spaces) {
|
||||
// for (const { allocation, tags = [] } of relocatedAllocations) {
|
||||
// const spaceAllocation = await this.spaceProductRepository.findOne({
|
||||
// where: {
|
||||
// inheritedFromModel: { uuid: allocation.uuid },
|
||||
// space: { uuid: space.uuid },
|
||||
// },
|
||||
// relations: ['tags'],
|
||||
// });
|
||||
// if (spaceAllocation) {
|
||||
// if (tags.length) {
|
||||
// spaceAllocation.tags.push(...tags);
|
||||
// await this.spaceProductRepository.save(spaceAllocation);
|
||||
// }
|
||||
// } else {
|
||||
// const newSpaceAllocation = this.spaceProductRepository.create({
|
||||
// space,
|
||||
// inheritedFromModel: allocation,
|
||||
// tag: allocation.tag,
|
||||
// product: allocation.product,
|
||||
// });
|
||||
// await this.spaceProductRepository.save(newSpaceAllocation);
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
const subspaces = await this.subspaceRepository.find({
|
||||
where: {
|
||||
subSpaceModel: { uuid: subspaceModel.subspaceModel.uuid },
|
||||
disabled: false,
|
||||
},
|
||||
relations: [
|
||||
'productAllocations',
|
||||
'productAllocations.product',
|
||||
'productAllocations.tags',
|
||||
],
|
||||
});
|
||||
|
||||
if (!subspaces.length) {
|
||||
return;
|
||||
}
|
||||
|
||||
const allocationUuidsToRemove = subspaces.flatMap((subspace) =>
|
||||
subspace.productAllocations.map((allocation) => allocation.uuid),
|
||||
);
|
||||
|
||||
if (allocationUuidsToRemove.length) {
|
||||
await this.subspaceProductRepository.delete(allocationUuidsToRemove);
|
||||
}
|
||||
|
||||
await this.subspaceRepository.update(
|
||||
{ uuid: In(subspaces.map((s) => s.uuid)) },
|
||||
{ disabled: true },
|
||||
);
|
||||
|
||||
const relocatedAllocations = subspaceModel.relocatedAllocations || [];
|
||||
|
||||
if (!relocatedAllocations.length) {
|
||||
return;
|
||||
}
|
||||
|
||||
for (const space of spaces) {
|
||||
for (const { allocation, tags = [] } of relocatedAllocations) {
|
||||
const spaceAllocation = await this.spaceProductRepository.findOne({
|
||||
where: {
|
||||
inheritedFromModel: { uuid: allocation.uuid },
|
||||
space: { uuid: space.uuid },
|
||||
},
|
||||
relations: ['tags'],
|
||||
});
|
||||
|
||||
if (spaceAllocation) {
|
||||
if (tags.length) {
|
||||
spaceAllocation.tags.push(...tags);
|
||||
await this.spaceProductRepository.save(spaceAllocation);
|
||||
}
|
||||
} else {
|
||||
const newSpaceAllocation = this.spaceProductRepository.create({
|
||||
space,
|
||||
inheritedFromModel: allocation,
|
||||
tags: allocation.tags,
|
||||
product: allocation.product,
|
||||
});
|
||||
await this.spaceProductRepository.save(newSpaceAllocation);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async updateSubspaceModel(subspaceModel: ISingleSubspaceModel) {
|
||||
|
@ -1,3 +1,4 @@
|
||||
export * from './update-subspace.interface';
|
||||
export * from './modify-subspace.interface';
|
||||
export * from './single-subspace.interface';
|
||||
export * from './space-product-allocation.interface';
|
||||
export * from './update-subspace.interface';
|
||||
|
24
src/space-model/interfaces/modify-subspace.interface.ts
Normal file
24
src/space-model/interfaces/modify-subspace.interface.ts
Normal file
@ -0,0 +1,24 @@
|
||||
import { SubspaceModelEntity, TagModel } from '@app/common/modules/space-model';
|
||||
|
||||
export interface ModifyspaceModelPayload {
|
||||
modifiedSubspaceModels?: ModifySubspaceModelPayload;
|
||||
modifiedTags?: ModifiedTagsModelPayload;
|
||||
}
|
||||
|
||||
export interface ModifySubspaceModelPayload {
|
||||
addedSubspaceModels?: SubspaceModelEntity[];
|
||||
updatedSubspaceModels?: UpdatedSubspaceModelPayload[];
|
||||
deletedSubspaceModels?: string[];
|
||||
}
|
||||
|
||||
export interface UpdatedSubspaceModelPayload {
|
||||
subspaceName?: string;
|
||||
modifiedTags?: ModifiedTagsModelPayload;
|
||||
subspaceModelUuid: string;
|
||||
}
|
||||
|
||||
export interface ModifiedTagsModelPayload {
|
||||
added?: TagModel[];
|
||||
updated?: TagModel[];
|
||||
deleted?: string[];
|
||||
}
|
@ -1,11 +1,11 @@
|
||||
import { ModifyAction } from '@app/common/constants/modify-action.enum';
|
||||
import {
|
||||
SpaceModelProductAllocationEntity,
|
||||
SubspaceModelEntity,
|
||||
} from '@app/common/modules/space-model';
|
||||
import { ModifyTagModelDto } from '../dtos';
|
||||
import { ModifyAction } from '@app/common/constants/modify-action.enum';
|
||||
import { NewTagEntity } from '@app/common/modules/tag';
|
||||
import { IUpdatedAllocations } from './subspace-product-allocation-update-result.interface';
|
||||
import { ModifyTagDto } from 'src/space/dtos/tag/modify-tag.dto';
|
||||
|
||||
export interface IRelocatedAllocation {
|
||||
allocation: SpaceModelProductAllocationEntity;
|
||||
@ -14,7 +14,7 @@ export interface IRelocatedAllocation {
|
||||
export interface ISingleSubspaceModel {
|
||||
subspaceModel: SubspaceModelEntity;
|
||||
action: ModifyAction;
|
||||
tags?: ModifyTagDto[];
|
||||
tags?: ModifyTagModelDto[];
|
||||
relocatedAllocations?: IRelocatedAllocation[];
|
||||
}
|
||||
|
||||
|
@ -1,19 +1,20 @@
|
||||
import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
|
||||
import { In, QueryRunner } from 'typeorm';
|
||||
import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
|
||||
|
||||
import { ProductEntity } from '@app/common/modules/product/entities';
|
||||
import { ProjectEntity } from '@app/common/modules/project/entities';
|
||||
import { SpaceRepository } from '@app/common/modules/space';
|
||||
import {
|
||||
SpaceModelEntity,
|
||||
SpaceModelProductAllocationEntity,
|
||||
SpaceModelProductAllocationRepoitory,
|
||||
SubspaceModelProductAllocationEntity,
|
||||
} from '@app/common/modules/space-model';
|
||||
import { NewTagEntity } from '@app/common/modules/tag';
|
||||
import { ModifyTagDto } from 'src/space/dtos/tag/modify-tag.dto';
|
||||
import { ProcessTagDto } from 'src/tags/dtos';
|
||||
import { TagService as NewTagService } from 'src/tags/services';
|
||||
import { ModifySubspaceModelDto } from '../dtos';
|
||||
import { ProcessTagDto } from 'src/tags/dtos';
|
||||
import { ModifySubspaceModelDto, ModifyTagModelDto } from '../dtos';
|
||||
import { ModifyAction } from '@app/common/constants/modify-action.enum';
|
||||
import { NewTagEntity } from '@app/common/modules/tag';
|
||||
import { ProductEntity } from '@app/common/modules/product/entities';
|
||||
import { SpaceRepository } from '@app/common/modules/space';
|
||||
import { ProjectEntity } from '@app/common/modules/project/entities';
|
||||
import { IUpdatedSpaceAllocations } from '../interfaces';
|
||||
|
||||
@Injectable()
|
||||
@ -31,220 +32,225 @@ export class SpaceModelProductAllocationService {
|
||||
queryRunner?: QueryRunner,
|
||||
modifySubspaceModels?: ModifySubspaceModelDto[],
|
||||
): Promise<IUpdatedSpaceAllocations[]> {
|
||||
// try {
|
||||
if (!tags.length) return [];
|
||||
try {
|
||||
if (!tags.length) return [];
|
||||
|
||||
const allocationUpdates: IUpdatedSpaceAllocations[] = [];
|
||||
return allocationUpdates;
|
||||
// const processedTags = await this.tagService.processTags(
|
||||
// tags,
|
||||
// projectUuid,
|
||||
// queryRunner,
|
||||
// );
|
||||
const allocationUpdates: IUpdatedSpaceAllocations[] = [];
|
||||
|
||||
// const productAllocations: SpaceModelProductAllocationEntity[] = [];
|
||||
// const existingAllocations = new Map<
|
||||
// string,
|
||||
// SpaceModelProductAllocationEntity
|
||||
// >();
|
||||
const processedTags = await this.tagService.processTags(
|
||||
tags,
|
||||
projectUuid,
|
||||
queryRunner,
|
||||
);
|
||||
|
||||
// for (const tag of processedTags) {
|
||||
// let isTagNeeded = true;
|
||||
const productAllocations: SpaceModelProductAllocationEntity[] = [];
|
||||
const existingAllocations = new Map<
|
||||
string,
|
||||
SpaceModelProductAllocationEntity
|
||||
>();
|
||||
|
||||
// if (modifySubspaceModels) {
|
||||
// const relatedSubspaces = await queryRunner.manager.find(
|
||||
// SubspaceModelProductAllocationEntity,
|
||||
// {
|
||||
// where: {
|
||||
// product: { uuid: tag.product.uuid },
|
||||
// subspaceModel: { spaceModel: { uuid: spaceModel.uuid } },
|
||||
// tags: { uuid: tag.uuid },
|
||||
// },
|
||||
// relations: ['subspaceModel', 'tags'],
|
||||
// },
|
||||
// );
|
||||
for (const tag of processedTags) {
|
||||
let isTagNeeded = true;
|
||||
|
||||
// for (const subspaceWithTag of relatedSubspaces) {
|
||||
// const modifyingSubspace = modifySubspaceModels.find(
|
||||
// (subspace) =>
|
||||
// subspace.action === ModifyAction.UPDATE &&
|
||||
// subspace.uuid === subspaceWithTag.subspaceModel.uuid,
|
||||
// );
|
||||
if (modifySubspaceModels) {
|
||||
const relatedSubspaces = await queryRunner.manager.find(
|
||||
SubspaceModelProductAllocationEntity,
|
||||
{
|
||||
where: {
|
||||
product: { uuid: tag.product.uuid },
|
||||
subspaceModel: { spaceModel: { uuid: spaceModel.uuid } },
|
||||
tags: { uuid: tag.uuid },
|
||||
},
|
||||
relations: ['subspaceModel', 'tags'],
|
||||
},
|
||||
);
|
||||
|
||||
// if (
|
||||
// modifyingSubspace &&
|
||||
// modifyingSubspace.tags &&
|
||||
// modifyingSubspace.tags.some(
|
||||
// (subspaceTag) =>
|
||||
// subspaceTag.action === ModifyAction.DELETE &&
|
||||
// subspaceTag.tagUuid === tag.uuid,
|
||||
// )
|
||||
// ) {
|
||||
// isTagNeeded = true;
|
||||
// break;
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
for (const subspaceWithTag of relatedSubspaces) {
|
||||
const modifyingSubspace = modifySubspaceModels.find(
|
||||
(subspace) =>
|
||||
subspace.action === ModifyAction.UPDATE &&
|
||||
subspace.uuid === subspaceWithTag.subspaceModel.uuid,
|
||||
);
|
||||
|
||||
// if (isTagNeeded) {
|
||||
// const hasTags = await this.validateTagWithinSpaceModel(
|
||||
// queryRunner,
|
||||
// tag,
|
||||
// spaceModel,
|
||||
// );
|
||||
if (
|
||||
modifyingSubspace &&
|
||||
modifyingSubspace.tags &&
|
||||
modifyingSubspace.tags.some(
|
||||
(subspaceTag) =>
|
||||
subspaceTag.action === ModifyAction.DELETE &&
|
||||
subspaceTag.tagUuid === tag.uuid,
|
||||
)
|
||||
) {
|
||||
isTagNeeded = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// if (hasTags) continue;
|
||||
if (isTagNeeded) {
|
||||
const hasTags = await this.validateTagWithinSpaceModel(
|
||||
queryRunner,
|
||||
tag,
|
||||
spaceModel,
|
||||
);
|
||||
|
||||
// let allocation = existingAllocations.get(tag.product.uuid);
|
||||
// if (!allocation) {
|
||||
// allocation = await this.getAllocationByProduct(
|
||||
// tag.product,
|
||||
// spaceModel,
|
||||
// queryRunner,
|
||||
// );
|
||||
// if (allocation) {
|
||||
// existingAllocations.set(tag.product.uuid, allocation);
|
||||
// }
|
||||
// }
|
||||
if (hasTags) continue;
|
||||
|
||||
// if (!allocation) {
|
||||
// allocation = this.createNewAllocation(spaceModel, tag, queryRunner);
|
||||
// productAllocations.push(allocation);
|
||||
// allocationUpdates.push({
|
||||
// newAllocation: allocation,
|
||||
// });
|
||||
// } else if (!allocation.tags.some((t) => t.uuid === tag.uuid)) {
|
||||
// allocation.tags.push(tag);
|
||||
// allocationUpdates.push({
|
||||
// allocation: allocation,
|
||||
// tagsAdded: [tag],
|
||||
// });
|
||||
// await this.saveAllocation(allocation, queryRunner);
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
let allocation = existingAllocations.get(tag.product.uuid);
|
||||
if (!allocation) {
|
||||
allocation = await this.getAllocationByProduct(
|
||||
tag.product,
|
||||
spaceModel,
|
||||
queryRunner,
|
||||
);
|
||||
if (allocation) {
|
||||
existingAllocations.set(tag.product.uuid, allocation);
|
||||
}
|
||||
}
|
||||
|
||||
// if (productAllocations.length > 0) {
|
||||
// await this.saveAllocations(productAllocations, queryRunner);
|
||||
// }
|
||||
if (!allocation) {
|
||||
allocation = this.createNewAllocation(spaceModel, tag, queryRunner);
|
||||
productAllocations.push(allocation);
|
||||
allocationUpdates.push({
|
||||
newAllocation: allocation,
|
||||
});
|
||||
} else if (!allocation.tags.some((t) => t.uuid === tag.uuid)) {
|
||||
allocation.tags.push(tag);
|
||||
allocationUpdates.push({
|
||||
allocation: allocation,
|
||||
tagsAdded: [tag],
|
||||
});
|
||||
await this.saveAllocation(allocation, queryRunner);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// return allocationUpdates;
|
||||
// } catch (error) {
|
||||
// throw this.handleError(error, 'Failed to create product allocations');
|
||||
// }
|
||||
if (productAllocations.length > 0) {
|
||||
await this.saveAllocations(productAllocations, queryRunner);
|
||||
}
|
||||
|
||||
return allocationUpdates;
|
||||
} catch (error) {
|
||||
throw this.handleError(error, 'Failed to create product allocations');
|
||||
}
|
||||
}
|
||||
|
||||
async updateProductAllocations(
|
||||
dtos: ModifyTagDto[],
|
||||
dtos: ModifyTagModelDto[],
|
||||
project: ProjectEntity,
|
||||
spaceModel: SpaceModelEntity,
|
||||
queryRunner: QueryRunner,
|
||||
modifySubspaceModels?: ModifySubspaceModelDto[],
|
||||
): Promise<IUpdatedSpaceAllocations[]> {
|
||||
const allocationUpdates: IUpdatedSpaceAllocations[] = [];
|
||||
return allocationUpdates;
|
||||
// try {
|
||||
// const addDtos = dtos.filter((dto) => dto.action === ModifyAction.ADD);
|
||||
// const deleteDtos = dtos.filter(
|
||||
// (dto) => dto.action === ModifyAction.DELETE,
|
||||
// );
|
||||
// const addTagDtos: ProcessTagDto[] = addDtos.map((dto) => ({
|
||||
// name: dto.name,
|
||||
// productUuid: dto.productUuid,
|
||||
// uuid: dto.newTagUuid,
|
||||
// }));
|
||||
// // Process added tags
|
||||
// const processedTags = await this.tagService.processTags(
|
||||
// addTagDtos,
|
||||
// project.uuid,
|
||||
// queryRunner,
|
||||
// );
|
||||
// const addTagUuidMap = new Map<string, ModifyTagModelDto>();
|
||||
// processedTags.forEach((tag, index) => {
|
||||
// addTagUuidMap.set(tag.uuid, addDtos[index]);
|
||||
// });
|
||||
// const addTagUuids = new Set(processedTags.map((tag) => tag.uuid));
|
||||
// const deleteTagUuids = new Set(deleteDtos.map((dto) => dto.tagUuid));
|
||||
// const tagsToIgnore = new Set(
|
||||
// [...addTagUuids].filter((uuid) => deleteTagUuids.has(uuid)),
|
||||
// );
|
||||
// // Filter out tags that are added and deleted in the same request
|
||||
// const filteredDtos = dtos.filter(
|
||||
// (dto) =>
|
||||
// !(
|
||||
// tagsToIgnore.has(dto.tagUuid) ||
|
||||
// (dto.action === ModifyAction.ADD &&
|
||||
// tagsToIgnore.has(
|
||||
// [...addTagUuidMap.keys()].find(
|
||||
// (uuid) => addTagUuidMap.get(uuid) === dto,
|
||||
// ),
|
||||
// ))
|
||||
// ),
|
||||
// );
|
||||
// // Process add and delete actions concurrently
|
||||
// const [updatedAllocations, deletedAllocations] = await Promise.all([
|
||||
// this.processAddActions(
|
||||
// filteredDtos,
|
||||
// project.uuid,
|
||||
// spaceModel,
|
||||
// queryRunner,
|
||||
// modifySubspaceModels,
|
||||
// ),
|
||||
// this.processDeleteActions(filteredDtos, queryRunner, spaceModel),
|
||||
// ]);
|
||||
// // Combine results and return
|
||||
// return [...updatedAllocations, ...deletedAllocations];
|
||||
// } catch (error) {
|
||||
// throw this.handleError(error, 'Error while updating product allocations');
|
||||
// }
|
||||
try {
|
||||
const addDtos = dtos.filter((dto) => dto.action === ModifyAction.ADD);
|
||||
const deleteDtos = dtos.filter(
|
||||
(dto) => dto.action === ModifyAction.DELETE,
|
||||
);
|
||||
|
||||
const addTagDtos: ProcessTagDto[] = addDtos.map((dto) => ({
|
||||
name: dto.name,
|
||||
productUuid: dto.productUuid,
|
||||
uuid: dto.newTagUuid,
|
||||
}));
|
||||
|
||||
// Process added tags
|
||||
const processedTags = await this.tagService.processTags(
|
||||
addTagDtos,
|
||||
project.uuid,
|
||||
queryRunner,
|
||||
);
|
||||
|
||||
const addTagUuidMap = new Map<string, ModifyTagModelDto>();
|
||||
processedTags.forEach((tag, index) => {
|
||||
addTagUuidMap.set(tag.uuid, addDtos[index]);
|
||||
});
|
||||
|
||||
const addTagUuids = new Set(processedTags.map((tag) => tag.uuid));
|
||||
const deleteTagUuids = new Set(deleteDtos.map((dto) => dto.tagUuid));
|
||||
|
||||
const tagsToIgnore = new Set(
|
||||
[...addTagUuids].filter((uuid) => deleteTagUuids.has(uuid)),
|
||||
);
|
||||
|
||||
// Filter out tags that are added and deleted in the same request
|
||||
const filteredDtos = dtos.filter(
|
||||
(dto) =>
|
||||
!(
|
||||
tagsToIgnore.has(dto.tagUuid) ||
|
||||
(dto.action === ModifyAction.ADD &&
|
||||
tagsToIgnore.has(
|
||||
[...addTagUuidMap.keys()].find(
|
||||
(uuid) => addTagUuidMap.get(uuid) === dto,
|
||||
),
|
||||
))
|
||||
),
|
||||
);
|
||||
|
||||
// Process add and delete actions concurrently
|
||||
const [updatedAllocations, deletedAllocations] = await Promise.all([
|
||||
this.processAddActions(
|
||||
filteredDtos,
|
||||
project.uuid,
|
||||
spaceModel,
|
||||
queryRunner,
|
||||
modifySubspaceModels,
|
||||
),
|
||||
this.processDeleteActions(filteredDtos, queryRunner, spaceModel),
|
||||
]);
|
||||
|
||||
// Combine results and return
|
||||
return [...updatedAllocations, ...deletedAllocations];
|
||||
} catch (error) {
|
||||
throw this.handleError(error, 'Error while updating product allocations');
|
||||
}
|
||||
}
|
||||
|
||||
private async processAddActions(
|
||||
dtos: ModifyTagDto[],
|
||||
dtos: ModifyTagModelDto[],
|
||||
projectUuid: string,
|
||||
spaceModel: SpaceModelEntity,
|
||||
queryRunner: QueryRunner,
|
||||
modifySubspaceModels?: ModifySubspaceModelDto[],
|
||||
): Promise<IUpdatedSpaceAllocations[]> {
|
||||
const allocationUpdates: IUpdatedSpaceAllocations[] = [];
|
||||
return allocationUpdates;
|
||||
// const addDtos: ProcessTagDto[] = dtos
|
||||
// .filter((dto) => dto.action === ModifyAction.ADD)
|
||||
// .map((dto) => ({
|
||||
// name: dto.name,
|
||||
// productUuid: dto.productUuid,
|
||||
// uuid: dto.newTagUuid,
|
||||
// }));
|
||||
let allocationUpdates: IUpdatedSpaceAllocations[] = [];
|
||||
|
||||
// if (addDtos.length > 0) {
|
||||
// allocationUpdates = await this.createProductAllocations(
|
||||
// projectUuid,
|
||||
// spaceModel,
|
||||
// addDtos,
|
||||
// queryRunner,
|
||||
// modifySubspaceModels,
|
||||
// );
|
||||
// }
|
||||
// return allocationUpdates;
|
||||
const addDtos: ProcessTagDto[] = dtos
|
||||
.filter((dto) => dto.action === ModifyAction.ADD)
|
||||
.map((dto) => ({
|
||||
name: dto.name,
|
||||
productUuid: dto.productUuid,
|
||||
uuid: dto.newTagUuid,
|
||||
}));
|
||||
|
||||
if (addDtos.length > 0) {
|
||||
allocationUpdates = await this.createProductAllocations(
|
||||
projectUuid,
|
||||
spaceModel,
|
||||
addDtos,
|
||||
queryRunner,
|
||||
modifySubspaceModels,
|
||||
);
|
||||
}
|
||||
return allocationUpdates;
|
||||
}
|
||||
|
||||
private createNewAllocation(
|
||||
spaceModel: SpaceModelEntity,
|
||||
tag: NewTagEntity,
|
||||
queryRunner?: QueryRunner,
|
||||
) {
|
||||
// : SpaceModelProductAllocationEntity
|
||||
// return queryRunner
|
||||
// ? queryRunner.manager.create(SpaceModelProductAllocationEntity, {
|
||||
// spaceModel,
|
||||
// product: tag.product,
|
||||
// tags: [tag],
|
||||
// })
|
||||
// : this.spaceModelProductAllocationRepository.create({
|
||||
// spaceModel,
|
||||
// product: tag.product,
|
||||
// tags: [tag],
|
||||
// });
|
||||
): SpaceModelProductAllocationEntity {
|
||||
return queryRunner
|
||||
? queryRunner.manager.create(SpaceModelProductAllocationEntity, {
|
||||
spaceModel,
|
||||
product: tag.product,
|
||||
tags: [tag],
|
||||
})
|
||||
: this.spaceModelProductAllocationRepository.create({
|
||||
spaceModel,
|
||||
product: tag.product,
|
||||
tags: [tag],
|
||||
});
|
||||
}
|
||||
|
||||
private async getAllocationByProduct(
|
||||
@ -303,7 +309,7 @@ export class SpaceModelProductAllocationService {
|
||||
}
|
||||
|
||||
private async processDeleteActions(
|
||||
dtos: ModifyTagDto[],
|
||||
dtos: ModifyTagModelDto[],
|
||||
queryRunner: QueryRunner,
|
||||
spaceModel: SpaceModelEntity,
|
||||
): Promise<IUpdatedSpaceAllocations[]> {
|
||||
@ -311,10 +317,10 @@ export class SpaceModelProductAllocationService {
|
||||
if (!dtos || dtos.length === 0) {
|
||||
return;
|
||||
}
|
||||
const allocationUpdateToPropagate: IUpdatedSpaceAllocations[] = [];
|
||||
let allocationUpdateToPropagate: IUpdatedSpaceAllocations[] = [];
|
||||
|
||||
const tagUuidsToDelete = dtos
|
||||
// .filter((dto) => dto.action === ModifyAction.DELETE && dto.tagUuid)
|
||||
.filter((dto) => dto.action === ModifyAction.DELETE && dto.tagUuid)
|
||||
.map((dto) => dto.tagUuid);
|
||||
|
||||
if (tagUuidsToDelete.length === 0) return [];
|
||||
@ -323,7 +329,7 @@ export class SpaceModelProductAllocationService {
|
||||
SpaceModelProductAllocationEntity,
|
||||
{
|
||||
where: {
|
||||
tag: In(tagUuidsToDelete),
|
||||
tags: { uuid: In(tagUuidsToDelete) },
|
||||
spaceModel: {
|
||||
uuid: spaceModel.uuid,
|
||||
},
|
||||
@ -342,28 +348,31 @@ export class SpaceModelProductAllocationService {
|
||||
const allocationUpdates: SpaceModelProductAllocationEntity[] = [];
|
||||
|
||||
for (const allocation of allocationsToUpdate) {
|
||||
// const updatedTags = allocation.tags.filter(
|
||||
// (tag) => !tagUuidsToDelete.includes(tag.uuid),
|
||||
// );
|
||||
// const deletedTags = allocation.tags.filter((tag) =>
|
||||
// tagUuidsToDelete.includes(tag.uuid),
|
||||
// );
|
||||
// if (updatedTags.length === allocation.tags.length) {
|
||||
// continue;
|
||||
// }
|
||||
// if (updatedTags.length === 0) {
|
||||
// deletedAllocations.push(allocation);
|
||||
// allocationUpdateToPropagate.push({
|
||||
// deletedAllocation: allocation,
|
||||
// });
|
||||
// } else {
|
||||
// allocation.tags = updatedTags;
|
||||
// allocationUpdates.push(allocation);
|
||||
// allocationUpdateToPropagate.push({
|
||||
// allocation: allocation,
|
||||
// tagsRemoved: deletedTags,
|
||||
// });
|
||||
// }
|
||||
const updatedTags = allocation.tags.filter(
|
||||
(tag) => !tagUuidsToDelete.includes(tag.uuid),
|
||||
);
|
||||
|
||||
const deletedTags = allocation.tags.filter((tag) =>
|
||||
tagUuidsToDelete.includes(tag.uuid),
|
||||
);
|
||||
|
||||
if (updatedTags.length === allocation.tags.length) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (updatedTags.length === 0) {
|
||||
deletedAllocations.push(allocation);
|
||||
allocationUpdateToPropagate.push({
|
||||
deletedAllocation: allocation,
|
||||
});
|
||||
} else {
|
||||
allocation.tags = updatedTags;
|
||||
allocationUpdates.push(allocation);
|
||||
allocationUpdateToPropagate.push({
|
||||
allocation: allocation,
|
||||
tagsRemoved: deletedTags,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (allocationUpdates.length > 0) {
|
||||
@ -406,34 +415,33 @@ export class SpaceModelProductAllocationService {
|
||||
tag: NewTagEntity,
|
||||
spaceModel: SpaceModelEntity,
|
||||
): Promise<boolean> {
|
||||
return true;
|
||||
// const existingAllocationsForProduct = await queryRunner.manager.find(
|
||||
// SpaceModelProductAllocationEntity,
|
||||
// {
|
||||
// where: {
|
||||
// spaceModel: {
|
||||
// uuid: spaceModel.uuid,
|
||||
// },
|
||||
// product: {
|
||||
// uuid: tag.product.uuid,
|
||||
// },
|
||||
// },
|
||||
// relations: ['tags'],
|
||||
// },
|
||||
// );
|
||||
const existingAllocationsForProduct = await queryRunner.manager.find(
|
||||
SpaceModelProductAllocationEntity,
|
||||
{
|
||||
where: {
|
||||
spaceModel: {
|
||||
uuid: spaceModel.uuid,
|
||||
},
|
||||
product: {
|
||||
uuid: tag.product.uuid,
|
||||
},
|
||||
},
|
||||
relations: ['tags'],
|
||||
},
|
||||
);
|
||||
|
||||
// const existingTagsForProduct = existingAllocationsForProduct.flatMap(
|
||||
// (allocation) => allocation.tags,
|
||||
// );
|
||||
const existingTagsForProduct = existingAllocationsForProduct.flatMap(
|
||||
(allocation) => allocation.tags,
|
||||
);
|
||||
|
||||
// const isDuplicateTag = existingTagsForProduct.some(
|
||||
// (existingTag) => existingTag.uuid === tag.uuid,
|
||||
// );
|
||||
const isDuplicateTag = existingTagsForProduct.some(
|
||||
(existingTag) => existingTag.uuid === tag.uuid,
|
||||
);
|
||||
|
||||
// if (isDuplicateTag) {
|
||||
// return true;
|
||||
// }
|
||||
// return false;
|
||||
if (isDuplicateTag) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
async clearAllAllocations(spaceModelUuid: string, queryRunner: QueryRunner) {
|
||||
|
@ -1,47 +1,58 @@
|
||||
import { BaseResponseDto } from '@app/common/dto/base.response.dto';
|
||||
import {
|
||||
SpaceModelEntity,
|
||||
SpaceModelProductAllocationEntity,
|
||||
SpaceModelRepository,
|
||||
SubspaceModelProductAllocationEntity,
|
||||
} from '@app/common/modules/space-model';
|
||||
import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
|
||||
import {
|
||||
CreateSpaceModelDto,
|
||||
LinkSpacesToModelDto,
|
||||
UpdateSpaceModelDto,
|
||||
} from '../dtos';
|
||||
import { ProjectParam } from 'src/community/dtos';
|
||||
import { SuccessResponseDto } from '@app/common/dto/success.response.dto';
|
||||
import { SubSpaceModelService } from './subspace/subspace-model.service';
|
||||
import { DataSource, In, QueryRunner, SelectQueryBuilder } from 'typeorm';
|
||||
import {
|
||||
TypeORMCustomModel,
|
||||
TypeORMCustomModelFindAllQuery,
|
||||
} from '@app/common/models/typeOrmCustom.model';
|
||||
import { ProjectEntity } from '@app/common/modules/project/entities';
|
||||
import {
|
||||
SpaceProductAllocationRepository,
|
||||
SpaceRepository,
|
||||
} from '@app/common/modules/space';
|
||||
import {
|
||||
SpaceModelEntity,
|
||||
SpaceModelRepository,
|
||||
} from '@app/common/modules/space-model';
|
||||
import { SpaceProductAllocationEntity } from '@app/common/modules/space/entities/space-product-allocation.entity';
|
||||
import { SpaceEntity } from '@app/common/modules/space/entities/space.entity';
|
||||
import { SubspaceProductAllocationEntity } from '@app/common/modules/space/entities/subspace/subspace-product-allocation.entity';
|
||||
import { SubspaceEntity } from '@app/common/modules/space/entities/subspace/subspace.entity';
|
||||
import {
|
||||
SubspaceProductAllocationRepository,
|
||||
SubspaceRepository,
|
||||
} from '@app/common/modules/space/repositories/subspace.repository';
|
||||
import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
|
||||
import { CommandBus } from '@nestjs/cqrs';
|
||||
import { ProjectParam } from 'src/community/dtos';
|
||||
import { DeviceService } from 'src/device/services';
|
||||
import { SpaceModelParam } from '../dtos/space-model-param';
|
||||
import { ProjectService } from 'src/project/services';
|
||||
import { ProjectEntity } from '@app/common/modules/project/entities';
|
||||
import { BaseResponseDto } from '@app/common/dto/base.response.dto';
|
||||
import { CommandBus } from '@nestjs/cqrs';
|
||||
import { ProcessTagDto } from 'src/tags/dtos';
|
||||
import { DataSource, In, QueryRunner, SelectQueryBuilder } from 'typeorm';
|
||||
import { SpaceModelProductAllocationService } from './space-model-product-allocation.service';
|
||||
import {
|
||||
PropogateDeleteSpaceModelCommand,
|
||||
PropogateUpdateSpaceModelCommand,
|
||||
PropogateUpdateSpaceModelProductAllocationCommand,
|
||||
} from '../commands';
|
||||
import {
|
||||
CreateSpaceModelDto,
|
||||
LinkSpacesToModelDto,
|
||||
UpdateSpaceModelDto,
|
||||
} from '../dtos';
|
||||
import { SpaceModelParam } from '../dtos/space-model-param';
|
||||
import { ISubspaceModelUpdates, IUpdatedSpaceAllocations } from '../interfaces';
|
||||
import { SpaceModelProductAllocationService } from './space-model-product-allocation.service';
|
||||
import { SubSpaceModelService } from './subspace';
|
||||
SpaceProductAllocationRepository,
|
||||
SpaceRepository,
|
||||
} from '@app/common/modules/space';
|
||||
import { SpaceEntity } from '@app/common/modules/space/entities/space.entity';
|
||||
import {
|
||||
SubspaceProductAllocationRepository,
|
||||
SubspaceRepository,
|
||||
} from '@app/common/modules/space/repositories/subspace.repository';
|
||||
import {
|
||||
ORPHAN_COMMUNITY_NAME,
|
||||
ORPHAN_SPACE_NAME,
|
||||
} from '@app/common/constants/orphan-constant';
|
||||
import { DeviceRepository } from '@app/common/modules/device/repositories';
|
||||
import { SpaceProductAllocationEntity } from '@app/common/modules/space/entities/space-product-allocation.entity';
|
||||
import { SubspaceEntity } from '@app/common/modules/space/entities/subspace/subspace.entity';
|
||||
import { SubspaceProductAllocationEntity } from '@app/common/modules/space/entities/subspace/subspace-product-allocation.entity';
|
||||
import { DeviceEntity } from '@app/common/modules/device/entities';
|
||||
import {
|
||||
ISingleSubspaceModel,
|
||||
ISubspaceModelUpdates,
|
||||
IUpdatedSpaceAllocations,
|
||||
} from '../interfaces';
|
||||
|
||||
@Injectable()
|
||||
export class SpaceModelService {
|
||||
@ -49,7 +60,6 @@ export class SpaceModelService {
|
||||
private readonly dataSource: DataSource,
|
||||
private readonly spaceModelRepository: SpaceModelRepository,
|
||||
private readonly projectService: ProjectService,
|
||||
private readonly deviceService: DeviceService,
|
||||
private readonly subSpaceModelService: SubSpaceModelService,
|
||||
private commandBus: CommandBus,
|
||||
private readonly spaceModelProductAllocationService: SpaceModelProductAllocationService,
|
||||
@ -57,6 +67,7 @@ export class SpaceModelService {
|
||||
private readonly spaceProductAllocationRepository: SpaceProductAllocationRepository,
|
||||
private readonly subspaceRepository: SubspaceRepository,
|
||||
private readonly subspaceProductAllocationRepository: SubspaceProductAllocationRepository,
|
||||
private readonly deviceRepository: DeviceRepository,
|
||||
) {}
|
||||
|
||||
async createSpaceModel(
|
||||
@ -150,7 +161,7 @@ export class SpaceModelService {
|
||||
disabled: false,
|
||||
};
|
||||
pageable.include =
|
||||
'subspaceModels.productAllocations,subspaceModelProductAllocations.tag,subspaceModelProductAllocations.product,subspaceModels, productAllocations, productAllocations.tag,productAllocations.product';
|
||||
'subspaceModels.productAllocations,subspaceModelProductAllocations.tags,subspaceModels, productAllocations, productAllocations.tags';
|
||||
|
||||
const queryBuilder = this.buildSpaceModelQuery(param.projectUuid);
|
||||
|
||||
@ -220,7 +231,7 @@ export class SpaceModelService {
|
||||
spaceModel,
|
||||
queryRunner,
|
||||
param.projectUuid,
|
||||
// dto.tags,
|
||||
dto.tags,
|
||||
);
|
||||
}
|
||||
|
||||
@ -375,10 +386,10 @@ export class SpaceModelService {
|
||||
'productAllocations',
|
||||
'subspaceModels',
|
||||
'productAllocations.product',
|
||||
'productAllocations.tag',
|
||||
'productAllocations.tags',
|
||||
'subspaceModels.productAllocations',
|
||||
'subspaceModels.productAllocations.product',
|
||||
'subspaceModels.productAllocations.tag',
|
||||
'subspaceModels.productAllocations.tags',
|
||||
],
|
||||
});
|
||||
|
||||
@ -397,10 +408,10 @@ export class SpaceModelService {
|
||||
'subspaces',
|
||||
'productAllocations',
|
||||
'productAllocations.product',
|
||||
'productAllocations.tag',
|
||||
'productAllocations.tags',
|
||||
'subspaces.productAllocations',
|
||||
'subspaces.productAllocations.product',
|
||||
'subspaces.productAllocations.product.tag',
|
||||
'subspaces.productAllocations.product.tags',
|
||||
'community',
|
||||
],
|
||||
});
|
||||
@ -422,7 +433,7 @@ export class SpaceModelService {
|
||||
if (!hasDependencies && !space.spaceModel) {
|
||||
await this.linkToSpace(space, spaceModel);
|
||||
} else if (dto.overwrite) {
|
||||
await this.removeSpaceOldSubspacesAndAllocations(space, project);
|
||||
await this.overwriteSpace(space, project);
|
||||
await this.linkToSpace(space, spaceModel);
|
||||
}
|
||||
}),
|
||||
@ -459,9 +470,10 @@ export class SpaceModelService {
|
||||
space,
|
||||
inheritedFromModel: modelAllocation,
|
||||
product: modelAllocation.product,
|
||||
tag: modelAllocation.tag,
|
||||
tags: modelAllocation.tags,
|
||||
}),
|
||||
);
|
||||
|
||||
if (queryRunner) {
|
||||
await queryRunner.manager.save(
|
||||
SpaceProductAllocationEntity,
|
||||
@ -479,20 +491,23 @@ export class SpaceModelService {
|
||||
subSpaceModel: subspaceModel,
|
||||
space: space,
|
||||
});
|
||||
|
||||
if (queryRunner) {
|
||||
await queryRunner.manager.save(SubspaceEntity, subspace);
|
||||
} else {
|
||||
await this.subspaceRepository.save(subspace);
|
||||
}
|
||||
|
||||
const subspaceAllocations = subspaceModel.productAllocations.map(
|
||||
(modelAllocation) =>
|
||||
this.subspaceProductAllocationRepository.create({
|
||||
subspace,
|
||||
inheritedFromModel: modelAllocation,
|
||||
product: modelAllocation.product,
|
||||
tag: modelAllocation.tag,
|
||||
tags: modelAllocation.tags,
|
||||
}),
|
||||
);
|
||||
|
||||
if (subspaceAllocations.length) {
|
||||
if (queryRunner) {
|
||||
await queryRunner.manager.save(
|
||||
@ -515,7 +530,7 @@ export class SpaceModelService {
|
||||
}
|
||||
}
|
||||
|
||||
async removeSpaceOldSubspacesAndAllocations(
|
||||
async overwriteSpace(
|
||||
space: SpaceEntity,
|
||||
project: ProjectEntity,
|
||||
queryRunner?: QueryRunner,
|
||||
@ -533,6 +548,14 @@ export class SpaceModelService {
|
||||
? queryRunner.manager.getRepository(SubspaceProductAllocationEntity)
|
||||
: this.subspaceProductAllocationRepository;
|
||||
|
||||
const spaceRepository = queryRunner
|
||||
? queryRunner.manager.getRepository(SpaceEntity)
|
||||
: this.spaceRepository;
|
||||
|
||||
const deviceRepository = queryRunner
|
||||
? queryRunner.manager.getRepository(DeviceEntity)
|
||||
: this.deviceRepository;
|
||||
|
||||
if (space.productAllocations.length) {
|
||||
await spaceProductAllocationRepository.delete({
|
||||
uuid: In(
|
||||
@ -561,7 +584,26 @@ export class SpaceModelService {
|
||||
);
|
||||
|
||||
if (space.devices.length > 0) {
|
||||
this.deviceService.addDevicesToOrphanSpace(space, project, queryRunner);
|
||||
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(
|
||||
@ -570,6 +612,19 @@ export class SpaceModelService {
|
||||
}
|
||||
}
|
||||
|
||||
async validateName(modelName: string, projectUuid: string): Promise<void> {
|
||||
const isModelExist = await this.spaceModelRepository.findOne({
|
||||
where: { modelName, project: { uuid: projectUuid }, disabled: false },
|
||||
});
|
||||
|
||||
if (isModelExist) {
|
||||
throw new HttpException(
|
||||
`Model name ${modelName} already exists in the project with UUID ${projectUuid}.`,
|
||||
HttpStatus.CONFLICT,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async validateNameUsingQueryRunner(
|
||||
modelName: string,
|
||||
projectUuid: string,
|
||||
@ -671,20 +726,14 @@ export class SpaceModelService {
|
||||
'subspaceModelProductAllocations',
|
||||
)
|
||||
.leftJoinAndSelect(
|
||||
'subspaceModelProductAllocations.tag',
|
||||
'subspaceModelTag',
|
||||
)
|
||||
.leftJoinAndSelect(
|
||||
'subspaceModelProductAllocations.product',
|
||||
'subspaceModelProduct',
|
||||
'subspaceModelProductAllocations.tags',
|
||||
'subspaceModelTags',
|
||||
)
|
||||
.leftJoinAndSelect('subspaceModelTags.product', 'subspaceModelTagProduct')
|
||||
.leftJoinAndSelect('spaceModel.productAllocations', 'productAllocations')
|
||||
.leftJoinAndSelect('productAllocations.product', 'allocatedProduct')
|
||||
.leftJoinAndSelect('productAllocations.tag', 'spaceModelTag')
|
||||
.leftJoinAndSelect(
|
||||
'productAllocations.product',
|
||||
'productAllocationsProduct',
|
||||
)
|
||||
.leftJoinAndSelect('productAllocations.tags', 'productTags')
|
||||
.leftJoinAndSelect('productTags.product', 'productTagProduct')
|
||||
.where('spaceModel.disabled = false')
|
||||
.andWhere('spaceModel.project = :projectUuid', { projectUuid });
|
||||
}
|
||||
@ -704,12 +753,42 @@ export class SpaceModelService {
|
||||
updatedAt: subspace.updatedAt,
|
||||
subspaceName: subspace.subspaceName,
|
||||
disabled: subspace.disabled,
|
||||
productAllocations: subspace.productAllocations,
|
||||
tags: this.extractTags(subspace.productAllocations),
|
||||
})),
|
||||
productAllocations: spaceModel.productAllocations,
|
||||
tags: this.extractTags(spaceModel.productAllocations),
|
||||
}));
|
||||
}
|
||||
|
||||
private extractTags(
|
||||
productAllocations:
|
||||
| SpaceModelProductAllocationEntity[]
|
||||
| SubspaceModelProductAllocationEntity[]
|
||||
| undefined,
|
||||
): any[] {
|
||||
if (!productAllocations) return [];
|
||||
|
||||
return productAllocations
|
||||
.flatMap((allocation) => allocation.tags ?? [])
|
||||
.map((tag) => ({
|
||||
uuid: tag.uuid,
|
||||
createdAt: tag.createdAt,
|
||||
updatedAt: tag.updatedAt,
|
||||
name: tag.name,
|
||||
disabled: tag.disabled,
|
||||
product: tag.product
|
||||
? {
|
||||
uuid: tag.product.uuid,
|
||||
createdAt: tag.product.createdAt,
|
||||
updatedAt: tag.product.updatedAt,
|
||||
catName: tag.product.catName,
|
||||
prodId: tag.product.prodId,
|
||||
name: tag.product.name,
|
||||
prodType: tag.product.prodType,
|
||||
}
|
||||
: null,
|
||||
}));
|
||||
}
|
||||
|
||||
private formatSpaceModelResponse(spaceModel: SpaceModelEntity): any {
|
||||
return {
|
||||
uuid: spaceModel.uuid,
|
||||
@ -724,9 +803,9 @@ export class SpaceModelService {
|
||||
updatedAt: subspace.updatedAt,
|
||||
subspaceName: subspace.subspaceName,
|
||||
disabled: subspace.disabled,
|
||||
productAllocations: subspace.productAllocations,
|
||||
tags: this.extractTags(subspace.productAllocations),
|
||||
})) ?? [],
|
||||
productAllocations: spaceModel.productAllocations,
|
||||
tags: this.extractTags(spaceModel.productAllocations),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
@ -9,9 +9,10 @@ import {
|
||||
} from '@app/common/modules/space-model';
|
||||
import { NewTagEntity } from '@app/common/modules/tag';
|
||||
import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
|
||||
import { ModifyTagModelDto } from 'src/space-model/dtos';
|
||||
import { ISingleSubspaceModel } from 'src/space-model/interfaces';
|
||||
import { IUpdatedAllocations } from 'src/space-model/interfaces/subspace-product-allocation-update-result.interface';
|
||||
import { ModifyTagDto } from 'src/space/dtos/tag/modify-tag.dto';
|
||||
import { ProcessTagDto } from 'src/tags/dtos';
|
||||
import { TagService as NewTagService } from 'src/tags/services';
|
||||
import { In, QueryRunner } from 'typeorm';
|
||||
|
||||
@ -30,159 +31,172 @@ export class SubspaceModelProductAllocationService {
|
||||
queryRunner?: QueryRunner,
|
||||
spaceAllocationsToExclude?: SpaceModelProductAllocationEntity[],
|
||||
): Promise<IUpdatedAllocations[]> {
|
||||
// try {
|
||||
const updatedAllocations: IUpdatedAllocations[] = [];
|
||||
return updatedAllocations;
|
||||
// const allocations: SubspaceModelProductAllocationEntity[] = [];
|
||||
// for (const tag of tags) {
|
||||
// // Step 1: Check if this specific tag is already allocated at the space level
|
||||
// const existingTagInSpaceModel = await (queryRunner
|
||||
// ? queryRunner.manager.findOne(SpaceModelProductAllocationEntity, {
|
||||
// where: {
|
||||
// spaceModel: {
|
||||
// uuid: spaceModel.uuid,
|
||||
// }, // Check at the space level
|
||||
// tags: { uuid: tag.uuid }, // Check for the specific tag
|
||||
// },
|
||||
// relations: ['tags'],
|
||||
// })
|
||||
// : this.spaceModelAllocationRepository.findOne({
|
||||
// where: {
|
||||
// spaceModel: {
|
||||
// uuid: spaceModel.uuid,
|
||||
// },
|
||||
// tags: { uuid: tag.uuid },
|
||||
// },
|
||||
// relations: ['tags', 'product'],
|
||||
// }));
|
||||
// const isExcluded = spaceAllocationsToExclude?.some(
|
||||
// (excludedAllocation) =>
|
||||
// excludedAllocation.product.uuid === tag.product.uuid &&
|
||||
// excludedAllocation.tags.some((t) => t.uuid === tag.uuid),
|
||||
// );
|
||||
// // If tag is found at the space level, prevent allocation at the subspace level
|
||||
// if (!isExcluded && existingTagInSpaceModel) {
|
||||
// throw new HttpException(
|
||||
// `Tag ${tag.uuid} (Product: ${tag.product.uuid}) is already allocated at the space level (${subspaceModel.spaceModel.uuid}). Cannot allocate the same tag in a subspace.`,
|
||||
// HttpStatus.BAD_REQUEST,
|
||||
// );
|
||||
// }
|
||||
// // Check if this specific tag is already allocated within another subspace of the same space
|
||||
// const existingTagInSameSpace = await (queryRunner
|
||||
// ? queryRunner.manager.findOne(SubspaceModelProductAllocationEntity, {
|
||||
// where: {
|
||||
// product: { uuid: tag.product.uuid },
|
||||
// subspaceModel: { spaceModel: subspaceModel.spaceModel },
|
||||
// tags: { uuid: tag.uuid }, // Ensure the exact tag is checked
|
||||
// },
|
||||
// relations: ['subspaceModel', 'tags'],
|
||||
// })
|
||||
// : this.subspaceModelProductAllocationRepository.findOne({
|
||||
// where: {
|
||||
// product: { uuid: tag.product.uuid },
|
||||
// subspaceModel: { spaceModel: subspaceModel.spaceModel },
|
||||
// tags: { uuid: tag.uuid },
|
||||
// },
|
||||
// relations: ['subspaceModel', 'tags'],
|
||||
// }));
|
||||
// // Prevent duplicate allocation if tag exists in another subspace of the same space
|
||||
// if (
|
||||
// existingTagInSameSpace &&
|
||||
// existingTagInSameSpace.subspaceModel.uuid !== subspaceModel.uuid
|
||||
// ) {
|
||||
// throw new HttpException(
|
||||
// `Tag ${tag.uuid} (Product: ${tag.product.uuid}) is already allocated in another subspace (${existingTagInSameSpace.subspaceModel.uuid}) within the same space (${subspaceModel.spaceModel.uuid}).`,
|
||||
// HttpStatus.BAD_REQUEST,
|
||||
// );
|
||||
// }
|
||||
// //Check if there are existing allocations for this product in the subspace
|
||||
// const existingAllocationsForProduct = await (queryRunner
|
||||
// ? queryRunner.manager.find(SubspaceModelProductAllocationEntity, {
|
||||
// where: {
|
||||
// subspaceModel: { uuid: subspaceModel.uuid },
|
||||
// product: { uuid: tag.product.uuid },
|
||||
// },
|
||||
// relations: ['tags'],
|
||||
// })
|
||||
// : this.subspaceModelProductAllocationRepository.find({
|
||||
// where: {
|
||||
// subspaceModel: { uuid: subspaceModel.uuid },
|
||||
// product: { uuid: tag.product.uuid },
|
||||
// },
|
||||
// relations: ['tags'],
|
||||
// }));
|
||||
// //Flatten all existing tags for this product in the subspace
|
||||
// const existingTagsForProduct = existingAllocationsForProduct.flatMap(
|
||||
// (allocation) => allocation.tags,
|
||||
// );
|
||||
// // Check if the tag is already assigned to the same product in this subspace
|
||||
// const isDuplicateTag = existingTagsForProduct.some(
|
||||
// (existingTag) => existingTag.uuid === tag.uuid,
|
||||
// );
|
||||
// if (isDuplicateTag) {
|
||||
// throw new HttpException(
|
||||
// `Tag ${tag.uuid} is already allocated to product ${tag.product.uuid} within this subspace (${subspaceModel.uuid}).`,
|
||||
// HttpStatus.BAD_REQUEST,
|
||||
// );
|
||||
// }
|
||||
// // If no existing allocation, create a new one
|
||||
// if (existingAllocationsForProduct.length === 0) {
|
||||
// const allocation = queryRunner
|
||||
// ? queryRunner.manager.create(SubspaceModelProductAllocationEntity, {
|
||||
// subspaceModel,
|
||||
// product: tag.product,
|
||||
// tags: [tag],
|
||||
// })
|
||||
// : this.subspaceModelProductAllocationRepository.create({
|
||||
// subspaceModel,
|
||||
// product: tag.product,
|
||||
// tags: [tag],
|
||||
// });
|
||||
// allocations.push(allocation);
|
||||
// } else {
|
||||
// //If allocation exists, add the tag to it
|
||||
// existingAllocationsForProduct[0].tags.push(tag);
|
||||
// if (queryRunner) {
|
||||
// await queryRunner.manager.save(
|
||||
// SubspaceModelProductAllocationEntity,
|
||||
// existingAllocationsForProduct[0],
|
||||
// );
|
||||
// } else {
|
||||
// await this.subspaceModelProductAllocationRepository.save(
|
||||
// existingAllocationsForProduct[0],
|
||||
// );
|
||||
// }
|
||||
// updatedAllocations.push({
|
||||
// allocation: existingAllocationsForProduct[0],
|
||||
// tagsAdded: [tag],
|
||||
// });
|
||||
// }
|
||||
// }
|
||||
// // Save newly created allocations
|
||||
// if (allocations.length > 0) {
|
||||
// if (queryRunner) {
|
||||
// await queryRunner.manager.save(
|
||||
// SubspaceModelProductAllocationEntity,
|
||||
// allocations,
|
||||
// );
|
||||
// } else {
|
||||
// await this.subspaceModelProductAllocationRepository.save(allocations);
|
||||
// }
|
||||
// allocations.forEach((allocation) => {
|
||||
// updatedAllocations.push({ newAllocation: allocation });
|
||||
// });
|
||||
// }
|
||||
// return updatedAllocations;
|
||||
// } catch (error) {
|
||||
// throw new HttpException(
|
||||
// `An unexpected error occurred while creating subspace product allocations ${error}`,
|
||||
// HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
// );
|
||||
// }
|
||||
try {
|
||||
const updatedAllocations: IUpdatedAllocations[] = [];
|
||||
|
||||
const allocations: SubspaceModelProductAllocationEntity[] = [];
|
||||
|
||||
for (const tag of tags) {
|
||||
// Step 1: Check if this specific tag is already allocated at the space level
|
||||
const existingTagInSpaceModel = await (queryRunner
|
||||
? queryRunner.manager.findOne(SpaceModelProductAllocationEntity, {
|
||||
where: {
|
||||
spaceModel: {
|
||||
uuid: spaceModel.uuid,
|
||||
}, // Check at the space level
|
||||
tags: { uuid: tag.uuid }, // Check for the specific tag
|
||||
},
|
||||
relations: ['tags'],
|
||||
})
|
||||
: this.spaceModelAllocationRepository.findOne({
|
||||
where: {
|
||||
spaceModel: {
|
||||
uuid: spaceModel.uuid,
|
||||
},
|
||||
tags: { uuid: tag.uuid },
|
||||
},
|
||||
relations: ['tags', 'product'],
|
||||
}));
|
||||
|
||||
const isExcluded = spaceAllocationsToExclude?.some(
|
||||
(excludedAllocation) =>
|
||||
excludedAllocation.product.uuid === tag.product.uuid &&
|
||||
excludedAllocation.tags.some((t) => t.uuid === tag.uuid),
|
||||
);
|
||||
|
||||
// If tag is found at the space level, prevent allocation at the subspace level
|
||||
if (!isExcluded && existingTagInSpaceModel) {
|
||||
throw new HttpException(
|
||||
`Tag ${tag.uuid} (Product: ${tag.product.uuid}) is already allocated at the space level (${subspaceModel.spaceModel.uuid}). Cannot allocate the same tag in a subspace.`,
|
||||
HttpStatus.BAD_REQUEST,
|
||||
);
|
||||
}
|
||||
|
||||
// Check if this specific tag is already allocated within another subspace of the same space
|
||||
const existingTagInSameSpace = await (queryRunner
|
||||
? queryRunner.manager.findOne(SubspaceModelProductAllocationEntity, {
|
||||
where: {
|
||||
product: { uuid: tag.product.uuid },
|
||||
subspaceModel: { spaceModel: subspaceModel.spaceModel },
|
||||
tags: { uuid: tag.uuid }, // Ensure the exact tag is checked
|
||||
},
|
||||
relations: ['subspaceModel', 'tags'],
|
||||
})
|
||||
: this.subspaceModelProductAllocationRepository.findOne({
|
||||
where: {
|
||||
product: { uuid: tag.product.uuid },
|
||||
subspaceModel: { spaceModel: subspaceModel.spaceModel },
|
||||
tags: { uuid: tag.uuid },
|
||||
},
|
||||
relations: ['subspaceModel', 'tags'],
|
||||
}));
|
||||
|
||||
// Prevent duplicate allocation if tag exists in another subspace of the same space
|
||||
if (
|
||||
existingTagInSameSpace &&
|
||||
existingTagInSameSpace.subspaceModel.uuid !== subspaceModel.uuid
|
||||
) {
|
||||
throw new HttpException(
|
||||
`Tag ${tag.uuid} (Product: ${tag.product.uuid}) is already allocated in another subspace (${existingTagInSameSpace.subspaceModel.uuid}) within the same space (${subspaceModel.spaceModel.uuid}).`,
|
||||
HttpStatus.BAD_REQUEST,
|
||||
);
|
||||
}
|
||||
|
||||
//Check if there are existing allocations for this product in the subspace
|
||||
const existingAllocationsForProduct = await (queryRunner
|
||||
? queryRunner.manager.find(SubspaceModelProductAllocationEntity, {
|
||||
where: {
|
||||
subspaceModel: { uuid: subspaceModel.uuid },
|
||||
product: { uuid: tag.product.uuid },
|
||||
},
|
||||
relations: ['tags'],
|
||||
})
|
||||
: this.subspaceModelProductAllocationRepository.find({
|
||||
where: {
|
||||
subspaceModel: { uuid: subspaceModel.uuid },
|
||||
product: { uuid: tag.product.uuid },
|
||||
},
|
||||
relations: ['tags'],
|
||||
}));
|
||||
|
||||
//Flatten all existing tags for this product in the subspace
|
||||
const existingTagsForProduct = existingAllocationsForProduct.flatMap(
|
||||
(allocation) => allocation.tags,
|
||||
);
|
||||
|
||||
// Check if the tag is already assigned to the same product in this subspace
|
||||
const isDuplicateTag = existingTagsForProduct.some(
|
||||
(existingTag) => existingTag.uuid === tag.uuid,
|
||||
);
|
||||
|
||||
if (isDuplicateTag) {
|
||||
throw new HttpException(
|
||||
`Tag ${tag.uuid} is already allocated to product ${tag.product.uuid} within this subspace (${subspaceModel.uuid}).`,
|
||||
HttpStatus.BAD_REQUEST,
|
||||
);
|
||||
}
|
||||
|
||||
// If no existing allocation, create a new one
|
||||
if (existingAllocationsForProduct.length === 0) {
|
||||
const allocation = queryRunner
|
||||
? queryRunner.manager.create(SubspaceModelProductAllocationEntity, {
|
||||
subspaceModel,
|
||||
product: tag.product,
|
||||
tags: [tag],
|
||||
})
|
||||
: this.subspaceModelProductAllocationRepository.create({
|
||||
subspaceModel,
|
||||
product: tag.product,
|
||||
tags: [tag],
|
||||
});
|
||||
allocations.push(allocation);
|
||||
} else {
|
||||
//If allocation exists, add the tag to it
|
||||
existingAllocationsForProduct[0].tags.push(tag);
|
||||
if (queryRunner) {
|
||||
await queryRunner.manager.save(
|
||||
SubspaceModelProductAllocationEntity,
|
||||
existingAllocationsForProduct[0],
|
||||
);
|
||||
} else {
|
||||
await this.subspaceModelProductAllocationRepository.save(
|
||||
existingAllocationsForProduct[0],
|
||||
);
|
||||
}
|
||||
updatedAllocations.push({
|
||||
allocation: existingAllocationsForProduct[0],
|
||||
tagsAdded: [tag],
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Save newly created allocations
|
||||
if (allocations.length > 0) {
|
||||
if (queryRunner) {
|
||||
await queryRunner.manager.save(
|
||||
SubspaceModelProductAllocationEntity,
|
||||
allocations,
|
||||
);
|
||||
} else {
|
||||
await this.subspaceModelProductAllocationRepository.save(allocations);
|
||||
}
|
||||
|
||||
allocations.forEach((allocation) => {
|
||||
updatedAllocations.push({ newAllocation: allocation });
|
||||
});
|
||||
}
|
||||
|
||||
return updatedAllocations;
|
||||
} catch (error) {
|
||||
throw new HttpException(
|
||||
`An unexpected error occurred while creating subspace product allocations ${error}`,
|
||||
HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async processDeleteActions(
|
||||
dtos: ModifyTagDto[],
|
||||
dtos: ModifyTagModelDto[],
|
||||
queryRunner: QueryRunner,
|
||||
): Promise<SubspaceModelProductAllocationEntity[]> {
|
||||
try {
|
||||
@ -191,7 +205,7 @@ export class SubspaceModelProductAllocationService {
|
||||
}
|
||||
|
||||
const tagUuidsToDelete = dtos
|
||||
// .filter((dto) => dto.action === ModifyAction.DELETE && dto.tagUuid)
|
||||
.filter((dto) => dto.action === ModifyAction.DELETE && dto.tagUuid)
|
||||
.map((dto) => dto.tagUuid);
|
||||
|
||||
if (tagUuidsToDelete.length === 0) return [];
|
||||
@ -199,7 +213,8 @@ export class SubspaceModelProductAllocationService {
|
||||
const allocationsToUpdate = await queryRunner.manager.find(
|
||||
SubspaceModelProductAllocationEntity,
|
||||
{
|
||||
where: { tag: In(tagUuidsToDelete) },
|
||||
where: { tags: { uuid: In(tagUuidsToDelete) } },
|
||||
relations: ['tags'],
|
||||
},
|
||||
);
|
||||
|
||||
@ -209,18 +224,20 @@ export class SubspaceModelProductAllocationService {
|
||||
const allocationUpdates: SubspaceModelProductAllocationEntity[] = [];
|
||||
|
||||
for (const allocation of allocationsToUpdate) {
|
||||
// const updatedTags = allocation.tags.filter(
|
||||
// (tag) => !tagUuidsToDelete.includes(tag.uuid),
|
||||
// );
|
||||
// if (updatedTags.length === allocation.tags.length) {
|
||||
// continue;
|
||||
// }
|
||||
// if (updatedTags.length === 0) {
|
||||
// deletedAllocations.push(allocation);
|
||||
// } else {
|
||||
// allocation.tags = updatedTags;
|
||||
// allocationUpdates.push(allocation);
|
||||
// }
|
||||
const updatedTags = allocation.tags.filter(
|
||||
(tag) => !tagUuidsToDelete.includes(tag.uuid),
|
||||
);
|
||||
|
||||
if (updatedTags.length === allocation.tags.length) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (updatedTags.length === 0) {
|
||||
deletedAllocations.push(allocation);
|
||||
} else {
|
||||
allocation.tags = updatedTags;
|
||||
allocationUpdates.push(allocation);
|
||||
}
|
||||
}
|
||||
|
||||
if (allocationUpdates.length > 0) {
|
||||
@ -263,255 +280,254 @@ export class SubspaceModelProductAllocationService {
|
||||
projectUuid: string,
|
||||
queryRunner: QueryRunner,
|
||||
spaceModel: SpaceModelEntity,
|
||||
spaceTagUpdateDtos?: ModifyTagDto[],
|
||||
) {
|
||||
// : Promise<IUpdatedAllocations[]>
|
||||
spaceTagUpdateDtos?: ModifyTagModelDto[],
|
||||
): Promise<IUpdatedAllocations[]> {
|
||||
const spaceAllocationToExclude: SpaceModelProductAllocationEntity[] = [];
|
||||
const updatedAllocations: IUpdatedAllocations[] = [];
|
||||
return updatedAllocations;
|
||||
// for (const subspaceModel of subspaceModels) {
|
||||
// const tagDtos = subspaceModel.tags;
|
||||
// if (tagDtos.length > 0) {
|
||||
// const tagsToAddDto: ProcessTagDto[] = tagDtos
|
||||
// .filter((dto) => dto.action === ModifyAction.ADD)
|
||||
// .map((dto) => ({
|
||||
// name: dto.name,
|
||||
// productUuid: dto.productUuid,
|
||||
// uuid: dto.newTagUuid,
|
||||
// }));
|
||||
|
||||
// const tagsToDeleteDto = tagDtos.filter(
|
||||
// (dto) => dto.action === ModifyAction.DELETE,
|
||||
// );
|
||||
for (const subspaceModel of subspaceModels) {
|
||||
const tagDtos = subspaceModel.tags;
|
||||
if (tagDtos.length > 0) {
|
||||
const tagsToAddDto: ProcessTagDto[] = tagDtos
|
||||
.filter((dto) => dto.action === ModifyAction.ADD)
|
||||
.map((dto) => ({
|
||||
name: dto.name,
|
||||
productUuid: dto.productUuid,
|
||||
uuid: dto.newTagUuid,
|
||||
}));
|
||||
|
||||
// if (tagsToAddDto.length > 0) {
|
||||
// let processedTags = await this.tagService.processTags(
|
||||
// tagsToAddDto,
|
||||
// projectUuid,
|
||||
// queryRunner,
|
||||
// );
|
||||
const tagsToDeleteDto = tagDtos.filter(
|
||||
(dto) => dto.action === ModifyAction.DELETE,
|
||||
);
|
||||
|
||||
// for (const subspaceDto of subspaceModels) {
|
||||
// if (
|
||||
// subspaceDto !== subspaceModel &&
|
||||
// subspaceDto.action === ModifyAction.UPDATE &&
|
||||
// subspaceDto.tags
|
||||
// ) {
|
||||
// // Tag is deleted from one subspace and added in another subspace
|
||||
// const deletedTags = subspaceDto.tags.filter(
|
||||
// (tagDto) =>
|
||||
// tagDto.action === ModifyAction.DELETE &&
|
||||
// processedTags.some((tag) => tag.uuid === tagDto.tagUuid),
|
||||
// );
|
||||
if (tagsToAddDto.length > 0) {
|
||||
let processedTags = await this.tagService.processTags(
|
||||
tagsToAddDto,
|
||||
projectUuid,
|
||||
queryRunner,
|
||||
);
|
||||
|
||||
// for (const deletedTag of deletedTags) {
|
||||
// const allocation = await queryRunner.manager.findOne(
|
||||
// SubspaceModelProductAllocationEntity,
|
||||
// {
|
||||
// where: {
|
||||
// tags: {
|
||||
// uuid: deletedTag.tagUuid,
|
||||
// },
|
||||
// subspaceModel: {
|
||||
// uuid: subspaceDto.subspaceModel.uuid,
|
||||
// },
|
||||
// },
|
||||
// relations: ['tags', 'product', 'subspaceModel'],
|
||||
// },
|
||||
// );
|
||||
// if (allocation) {
|
||||
// const isCommonTag = allocation.tags.some(
|
||||
// (tag) => tag.uuid === deletedTag.tagUuid,
|
||||
// );
|
||||
for (const subspaceDto of subspaceModels) {
|
||||
if (
|
||||
subspaceDto !== subspaceModel &&
|
||||
subspaceDto.action === ModifyAction.UPDATE &&
|
||||
subspaceDto.tags
|
||||
) {
|
||||
// Tag is deleted from one subspace and added in another subspace
|
||||
const deletedTags = subspaceDto.tags.filter(
|
||||
(tagDto) =>
|
||||
tagDto.action === ModifyAction.DELETE &&
|
||||
processedTags.some((tag) => tag.uuid === tagDto.tagUuid),
|
||||
);
|
||||
|
||||
// if (allocation && isCommonTag) {
|
||||
// const tagEntity = allocation.tags.find(
|
||||
// (tag) => tag.uuid === deletedTag.tagUuid,
|
||||
// );
|
||||
for (const deletedTag of deletedTags) {
|
||||
const allocation = await queryRunner.manager.findOne(
|
||||
SubspaceModelProductAllocationEntity,
|
||||
{
|
||||
where: {
|
||||
tags: {
|
||||
uuid: deletedTag.tagUuid,
|
||||
},
|
||||
subspaceModel: {
|
||||
uuid: subspaceDto.subspaceModel.uuid,
|
||||
},
|
||||
},
|
||||
relations: ['tags', 'product', 'subspaceModel'],
|
||||
},
|
||||
);
|
||||
if (allocation) {
|
||||
const isCommonTag = allocation.tags.some(
|
||||
(tag) => tag.uuid === deletedTag.tagUuid,
|
||||
);
|
||||
|
||||
// allocation.tags = allocation.tags.filter(
|
||||
// (tag) => tag.uuid !== deletedTag.tagUuid,
|
||||
// );
|
||||
if (allocation && isCommonTag) {
|
||||
const tagEntity = allocation.tags.find(
|
||||
(tag) => tag.uuid === deletedTag.tagUuid,
|
||||
);
|
||||
|
||||
// updatedAllocations.push({
|
||||
// allocation,
|
||||
// tagsRemoved: [tagEntity],
|
||||
// });
|
||||
allocation.tags = allocation.tags.filter(
|
||||
(tag) => tag.uuid !== deletedTag.tagUuid,
|
||||
);
|
||||
|
||||
// await queryRunner.manager.save(allocation);
|
||||
updatedAllocations.push({
|
||||
allocation,
|
||||
tagsRemoved: [tagEntity],
|
||||
});
|
||||
|
||||
// const productAllocationExistInSubspace =
|
||||
// await queryRunner.manager.findOne(
|
||||
// SubspaceModelProductAllocationEntity,
|
||||
// {
|
||||
// where: {
|
||||
// subspaceModel: {
|
||||
// uuid: subspaceDto.subspaceModel.uuid,
|
||||
// },
|
||||
// product: { uuid: allocation.product.uuid },
|
||||
// },
|
||||
// relations: ['tags'],
|
||||
// },
|
||||
// );
|
||||
await queryRunner.manager.save(allocation);
|
||||
|
||||
// if (productAllocationExistInSubspace) {
|
||||
// productAllocationExistInSubspace.tags.push(tagEntity);
|
||||
const productAllocationExistInSubspace =
|
||||
await queryRunner.manager.findOne(
|
||||
SubspaceModelProductAllocationEntity,
|
||||
{
|
||||
where: {
|
||||
subspaceModel: {
|
||||
uuid: subspaceDto.subspaceModel.uuid,
|
||||
},
|
||||
product: { uuid: allocation.product.uuid },
|
||||
},
|
||||
relations: ['tags'],
|
||||
},
|
||||
);
|
||||
|
||||
// updatedAllocations.push({
|
||||
// allocation: productAllocationExistInSubspace,
|
||||
// tagsAdded: [tagEntity],
|
||||
// });
|
||||
if (productAllocationExistInSubspace) {
|
||||
productAllocationExistInSubspace.tags.push(tagEntity);
|
||||
|
||||
// await queryRunner.manager.save(
|
||||
// productAllocationExistInSubspace,
|
||||
// );
|
||||
// } else {
|
||||
// const newProductAllocation = queryRunner.manager.create(
|
||||
// SubspaceModelProductAllocationEntity,
|
||||
// {
|
||||
// subspaceModel: subspaceModel.subspaceModel,
|
||||
// product: allocation.product,
|
||||
// tags: [tagEntity],
|
||||
// },
|
||||
// );
|
||||
updatedAllocations.push({
|
||||
allocation: productAllocationExistInSubspace,
|
||||
tagsAdded: [tagEntity],
|
||||
});
|
||||
|
||||
// updatedAllocations.push({
|
||||
// allocation: newProductAllocation,
|
||||
// });
|
||||
await queryRunner.manager.save(
|
||||
productAllocationExistInSubspace,
|
||||
);
|
||||
} else {
|
||||
const newProductAllocation = queryRunner.manager.create(
|
||||
SubspaceModelProductAllocationEntity,
|
||||
{
|
||||
subspaceModel: subspaceModel.subspaceModel,
|
||||
product: allocation.product,
|
||||
tags: [tagEntity],
|
||||
},
|
||||
);
|
||||
|
||||
// await queryRunner.manager.save(newProductAllocation);
|
||||
// }
|
||||
updatedAllocations.push({
|
||||
allocation: newProductAllocation,
|
||||
});
|
||||
|
||||
// // Remove the tag from processedTags to prevent duplication
|
||||
// processedTags = processedTags.filter(
|
||||
// (tag) => tag.uuid !== deletedTag.tagUuid,
|
||||
// );
|
||||
await queryRunner.manager.save(newProductAllocation);
|
||||
}
|
||||
|
||||
// // Remove the tag from subspaceDto.tags to ensure it's not processed again while processing other dtos.
|
||||
// subspaceDto.tags = subspaceDto.tags.filter(
|
||||
// (tagDto) => tagDto.tagUuid !== deletedTag.tagUuid,
|
||||
// );
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// if (
|
||||
// subspaceDto !== subspaceModel &&
|
||||
// subspaceDto.action === ModifyAction.DELETE
|
||||
// ) {
|
||||
// const allocation = await queryRunner.manager.findOne(
|
||||
// SubspaceModelProductAllocationEntity,
|
||||
// {
|
||||
// where: {
|
||||
// subspaceModel: { uuid: subspaceDto.subspaceModel.uuid },
|
||||
// },
|
||||
// relations: ['tags'],
|
||||
// },
|
||||
// );
|
||||
// Remove the tag from processedTags to prevent duplication
|
||||
processedTags = processedTags.filter(
|
||||
(tag) => tag.uuid !== deletedTag.tagUuid,
|
||||
);
|
||||
|
||||
// const repeatedTags = allocation?.tags.filter((tag) =>
|
||||
// processedTags.some(
|
||||
// (processedTag) => processedTag.uuid === tag.uuid,
|
||||
// ),
|
||||
// );
|
||||
// if (repeatedTags.length > 0) {
|
||||
// allocation.tags = allocation.tags.filter(
|
||||
// (tag) =>
|
||||
// !repeatedTags.some(
|
||||
// (repeatedTag) => repeatedTag.uuid === tag.uuid,
|
||||
// ),
|
||||
// );
|
||||
// Remove the tag from subspaceDto.tags to ensure it's not processed again while processing other dtos.
|
||||
subspaceDto.tags = subspaceDto.tags.filter(
|
||||
(tagDto) => tagDto.tagUuid !== deletedTag.tagUuid,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (
|
||||
subspaceDto !== subspaceModel &&
|
||||
subspaceDto.action === ModifyAction.DELETE
|
||||
) {
|
||||
const allocation = await queryRunner.manager.findOne(
|
||||
SubspaceModelProductAllocationEntity,
|
||||
{
|
||||
where: {
|
||||
subspaceModel: { uuid: subspaceDto.subspaceModel.uuid },
|
||||
},
|
||||
relations: ['tags'],
|
||||
},
|
||||
);
|
||||
|
||||
// updatedAllocations.push({
|
||||
// allocation: allocation,
|
||||
// tagsRemoved: repeatedTags,
|
||||
// });
|
||||
const repeatedTags = allocation?.tags.filter((tag) =>
|
||||
processedTags.some(
|
||||
(processedTag) => processedTag.uuid === tag.uuid,
|
||||
),
|
||||
);
|
||||
if (repeatedTags.length > 0) {
|
||||
allocation.tags = allocation.tags.filter(
|
||||
(tag) =>
|
||||
!repeatedTags.some(
|
||||
(repeatedTag) => repeatedTag.uuid === tag.uuid,
|
||||
),
|
||||
);
|
||||
|
||||
// await queryRunner.manager.save(allocation);
|
||||
updatedAllocations.push({
|
||||
allocation: allocation,
|
||||
tagsRemoved: repeatedTags,
|
||||
});
|
||||
|
||||
// const productAllocationExistInSubspace =
|
||||
// await queryRunner.manager.findOne(
|
||||
// SubspaceModelProductAllocationEntity,
|
||||
// {
|
||||
// where: {
|
||||
// subspaceModel: { uuid: subspaceDto.subspaceModel.uuid },
|
||||
// product: { uuid: allocation.product.uuid },
|
||||
// },
|
||||
// relations: ['tags'],
|
||||
// },
|
||||
// );
|
||||
await queryRunner.manager.save(allocation);
|
||||
|
||||
// if (productAllocationExistInSubspace) {
|
||||
// updatedAllocations.push({
|
||||
// allocation: productAllocationExistInSubspace,
|
||||
// tagsAdded: repeatedTags,
|
||||
// });
|
||||
const productAllocationExistInSubspace =
|
||||
await queryRunner.manager.findOne(
|
||||
SubspaceModelProductAllocationEntity,
|
||||
{
|
||||
where: {
|
||||
subspaceModel: { uuid: subspaceDto.subspaceModel.uuid },
|
||||
product: { uuid: allocation.product.uuid },
|
||||
},
|
||||
relations: ['tags'],
|
||||
},
|
||||
);
|
||||
|
||||
// productAllocationExistInSubspace.tags.push(...repeatedTags);
|
||||
// await queryRunner.manager.save(
|
||||
// productAllocationExistInSubspace,
|
||||
// );
|
||||
// } else {
|
||||
// const newProductAllocation = queryRunner.manager.create(
|
||||
// SubspaceModelProductAllocationEntity,
|
||||
// {
|
||||
// subspaceModel: subspaceModel.subspaceModel,
|
||||
// product: allocation.product,
|
||||
// tags: repeatedTags,
|
||||
// },
|
||||
// );
|
||||
if (productAllocationExistInSubspace) {
|
||||
updatedAllocations.push({
|
||||
allocation: productAllocationExistInSubspace,
|
||||
tagsAdded: repeatedTags,
|
||||
});
|
||||
|
||||
// updatedAllocations.push({
|
||||
// newAllocation: newProductAllocation,
|
||||
// });
|
||||
productAllocationExistInSubspace.tags.push(...repeatedTags);
|
||||
await queryRunner.manager.save(
|
||||
productAllocationExistInSubspace,
|
||||
);
|
||||
} else {
|
||||
const newProductAllocation = queryRunner.manager.create(
|
||||
SubspaceModelProductAllocationEntity,
|
||||
{
|
||||
subspaceModel: subspaceModel.subspaceModel,
|
||||
product: allocation.product,
|
||||
tags: repeatedTags,
|
||||
},
|
||||
);
|
||||
|
||||
// await queryRunner.manager.save(newProductAllocation);
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// if (spaceTagUpdateDtos) {
|
||||
// const deletedSpaceTags = spaceTagUpdateDtos.filter(
|
||||
// (tagDto) =>
|
||||
// tagDto.action === ModifyAction.DELETE &&
|
||||
// processedTags.some((tag) => tag.uuid === tagDto.tagUuid),
|
||||
// );
|
||||
// for (const deletedTag of deletedSpaceTags) {
|
||||
// const allocation = await queryRunner.manager.findOne(
|
||||
// SpaceModelProductAllocationEntity,
|
||||
// {
|
||||
// where: {
|
||||
// spaceModel: { uuid: spaceModel.uuid },
|
||||
// tags: { uuid: deletedTag.tagUuid },
|
||||
// },
|
||||
// relations: ['tags', 'product'],
|
||||
// },
|
||||
// );
|
||||
updatedAllocations.push({
|
||||
newAllocation: newProductAllocation,
|
||||
});
|
||||
|
||||
// if (
|
||||
// allocation &&
|
||||
// allocation.tags.some((tag) => tag.uuid === deletedTag.tagUuid)
|
||||
// ) {
|
||||
// spaceAllocationToExclude.push(allocation);
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
await queryRunner.manager.save(newProductAllocation);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (spaceTagUpdateDtos) {
|
||||
const deletedSpaceTags = spaceTagUpdateDtos.filter(
|
||||
(tagDto) =>
|
||||
tagDto.action === ModifyAction.DELETE &&
|
||||
processedTags.some((tag) => tag.uuid === tagDto.tagUuid),
|
||||
);
|
||||
for (const deletedTag of deletedSpaceTags) {
|
||||
const allocation = await queryRunner.manager.findOne(
|
||||
SpaceModelProductAllocationEntity,
|
||||
{
|
||||
where: {
|
||||
spaceModel: { uuid: spaceModel.uuid },
|
||||
tags: { uuid: deletedTag.tagUuid },
|
||||
},
|
||||
relations: ['tags', 'product'],
|
||||
},
|
||||
);
|
||||
|
||||
// // Create new product allocations
|
||||
// const newAllocations = await this.createProductAllocations(
|
||||
// subspaceModel.subspaceModel,
|
||||
// spaceModel,
|
||||
// processedTags,
|
||||
// queryRunner,
|
||||
// spaceAllocationToExclude,
|
||||
// );
|
||||
// return [...updatedAllocations, ...newAllocations];
|
||||
// }
|
||||
// if (tagsToDeleteDto.length > 0) {
|
||||
// await this.processDeleteActions(tagsToDeleteDto, queryRunner);
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
if (
|
||||
allocation &&
|
||||
allocation.tags.some((tag) => tag.uuid === deletedTag.tagUuid)
|
||||
) {
|
||||
spaceAllocationToExclude.push(allocation);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Create new product allocations
|
||||
const newAllocations = await this.createProductAllocations(
|
||||
subspaceModel.subspaceModel,
|
||||
spaceModel,
|
||||
processedTags,
|
||||
queryRunner,
|
||||
spaceAllocationToExclude,
|
||||
);
|
||||
return [...updatedAllocations, ...newAllocations];
|
||||
}
|
||||
if (tagsToDeleteDto.length > 0) {
|
||||
await this.processDeleteActions(tagsToDeleteDto, queryRunner);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async clearAllAllocations(subspaceIds: string[], queryRunner: QueryRunner) {
|
||||
|
@ -1,4 +1,3 @@
|
||||
import { ModifyAction } from '@app/common/constants/modify-action.enum';
|
||||
import {
|
||||
SpaceModelEntity,
|
||||
SpaceModelProductAllocationEntity,
|
||||
@ -6,21 +5,21 @@ import {
|
||||
SubspaceModelProductAllocationEntity,
|
||||
SubspaceModelRepository,
|
||||
} from '@app/common/modules/space-model';
|
||||
import { SpaceEntity } from '@app/common/modules/space/entities/space.entity';
|
||||
import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
|
||||
import { CreateSubspaceModelDto, ModifyTagModelDto } from '../../dtos';
|
||||
import { In, Not, QueryFailedError, QueryRunner } from 'typeorm';
|
||||
import { ModifySubspaceModelDto } from 'src/space-model/dtos/subspaces-model-dtos';
|
||||
import { ModifyAction } from '@app/common/constants/modify-action.enum';
|
||||
import { ProcessTagDto } from 'src/tags/dtos';
|
||||
import { TagService } from 'src/tags/services';
|
||||
import { SubspaceModelProductAllocationService } from './subspace-model-product-allocation.service';
|
||||
import {
|
||||
IRelocatedAllocation,
|
||||
ISingleSubspaceModel,
|
||||
ISubspaceModelUpdates,
|
||||
} from 'src/space-model/interfaces';
|
||||
import { ModifyTagDto } from 'src/space/dtos/tag/modify-tag.dto';
|
||||
import { SpaceEntity } from '@app/common/modules/space/entities/space.entity';
|
||||
import { SubSpaceService } from 'src/space/services/subspace';
|
||||
import { ProcessTagDto } from 'src/tags/dtos';
|
||||
import { TagService } from 'src/tags/services';
|
||||
import { In, Not, QueryFailedError, QueryRunner } from 'typeorm';
|
||||
import { CreateSubspaceModelDto } from '../../dtos';
|
||||
import { SubspaceModelProductAllocationService } from './subspace-model-product-allocation.service';
|
||||
|
||||
@Injectable()
|
||||
export class SubSpaceModelService {
|
||||
@ -51,12 +50,8 @@ export class SubSpaceModelService {
|
||||
for (const [index, dto] of dtos.entries()) {
|
||||
const subspaceModel = savedSubspaces[index];
|
||||
|
||||
const processedTags = await this.tagService.upsertTags(
|
||||
dto.tags.map((tag) => ({
|
||||
tagName: tag.name,
|
||||
productUuid: tag.productUuid,
|
||||
tagUuid: tag.uuid,
|
||||
})),
|
||||
const processedTags = await this.tagService.processTags(
|
||||
dto.tags,
|
||||
spaceModel.project.uuid,
|
||||
queryRunner,
|
||||
);
|
||||
@ -122,7 +117,7 @@ export class SubSpaceModelService {
|
||||
spaceModel: SpaceModelEntity,
|
||||
queryRunner: QueryRunner,
|
||||
projectUuid: string,
|
||||
spaceTagUpdateDtos?: ModifyTagDto[],
|
||||
spaceTagUpdateDtos?: ModifyTagModelDto[],
|
||||
spaces?: SpaceEntity[],
|
||||
): Promise<ISubspaceModelUpdates> {
|
||||
try {
|
||||
@ -157,7 +152,7 @@ export class SubSpaceModelService {
|
||||
projectUuid,
|
||||
queryRunner,
|
||||
spaceModel,
|
||||
// spaceTagUpdateDtos,
|
||||
spaceTagUpdateDtos,
|
||||
);
|
||||
|
||||
const deletedSubspaces = await this.deleteSubspaceModels(
|
||||
@ -193,7 +188,7 @@ export class SubSpaceModelService {
|
||||
deleteDtos: ModifySubspaceModelDto[],
|
||||
queryRunner: QueryRunner,
|
||||
spaceModel: SpaceModelEntity,
|
||||
spaceTagUpdateDtos?: ModifyTagDto[],
|
||||
spaceTagUpdateDtos?: ModifyTagModelDto[],
|
||||
): Promise<ISingleSubspaceModel[]> {
|
||||
try {
|
||||
if (!deleteDtos || deleteDtos.length === 0) {
|
||||
@ -235,82 +230,92 @@ export class SubSpaceModelService {
|
||||
>();
|
||||
|
||||
for (const allocation of allocationsToRemove) {
|
||||
// const product = allocation.product;
|
||||
// const tags = allocation.tags;
|
||||
// const subspaceUuid = allocation.subspaceModel.uuid;
|
||||
// const spaceAllocationKey = `${spaceModel.uuid}-${product.uuid}`;
|
||||
// if (!spaceAllocationsMap.has(spaceAllocationKey)) {
|
||||
// const spaceAllocation = await queryRunner.manager.findOne(
|
||||
// SpaceModelProductAllocationEntity,
|
||||
// {
|
||||
// where: {
|
||||
// spaceModel: { uuid: spaceModel.uuid },
|
||||
// product: { uuid: product.uuid },
|
||||
// },
|
||||
// relations: ['tags'],
|
||||
// },
|
||||
// );
|
||||
// if (spaceAllocation) {
|
||||
// spaceAllocationsMap.set(spaceAllocationKey, spaceAllocation);
|
||||
// }
|
||||
// }
|
||||
// const movedToAlreadyExistingSpaceAllocations: IRelocatedAllocation[] =
|
||||
// [];
|
||||
// const spaceAllocation = spaceAllocationsMap.get(spaceAllocationKey);
|
||||
// if (spaceAllocation) {
|
||||
// const existingTagUuids = new Set(
|
||||
// spaceAllocation.tags.map((tag) => tag.uuid),
|
||||
// );
|
||||
// const newTags = tags.filter(
|
||||
// (tag) => !existingTagUuids.has(tag.uuid),
|
||||
// );
|
||||
// if (newTags.length > 0) {
|
||||
// movedToAlreadyExistingSpaceAllocations.push({
|
||||
// tags: newTags,
|
||||
// allocation: spaceAllocation,
|
||||
// });
|
||||
// spaceAllocation.tags.push(...newTags);
|
||||
// await queryRunner.manager.save(spaceAllocation);
|
||||
// }
|
||||
// } else {
|
||||
// let tagsToAdd = [...tags];
|
||||
// if (spaceTagUpdateDtos && spaceTagUpdateDtos.length > 0) {
|
||||
// const spaceTagDtosToAdd = spaceTagUpdateDtos.filter(
|
||||
// (dto) => dto.action === ModifyAction.ADD,
|
||||
// );
|
||||
// tagsToAdd = tagsToAdd.filter(
|
||||
// (tag) =>
|
||||
// !spaceTagDtosToAdd.some(
|
||||
// (addDto) =>
|
||||
// (addDto.name && addDto.name === tag.name) ||
|
||||
// (addDto.newTagUuid && addDto.newTagUuid === tag.uuid),
|
||||
// ),
|
||||
// );
|
||||
// }
|
||||
// if (tagsToAdd.length > 0) {
|
||||
// const newSpaceAllocation = queryRunner.manager.create(
|
||||
// SpaceModelProductAllocationEntity,
|
||||
// {
|
||||
// spaceModel: spaceModel,
|
||||
// product: product,
|
||||
// tags: tags,
|
||||
// },
|
||||
// );
|
||||
// movedToAlreadyExistingSpaceAllocations.push({
|
||||
// allocation: newSpaceAllocation,
|
||||
// tags: tags,
|
||||
// });
|
||||
// await queryRunner.manager.save(newSpaceAllocation);
|
||||
// }
|
||||
// }
|
||||
// if (movedToAlreadyExistingSpaceAllocations.length > 0) {
|
||||
// if (!relocatedAllocationsMap.has(subspaceUuid)) {
|
||||
// relocatedAllocationsMap.set(subspaceUuid, []);
|
||||
// }
|
||||
// relocatedAllocationsMap
|
||||
// .get(subspaceUuid)
|
||||
// .push(...movedToAlreadyExistingSpaceAllocations);
|
||||
// }
|
||||
const product = allocation.product;
|
||||
const tags = allocation.tags;
|
||||
const subspaceUuid = allocation.subspaceModel.uuid;
|
||||
const spaceAllocationKey = `${spaceModel.uuid}-${product.uuid}`;
|
||||
|
||||
if (!spaceAllocationsMap.has(spaceAllocationKey)) {
|
||||
const spaceAllocation = await queryRunner.manager.findOne(
|
||||
SpaceModelProductAllocationEntity,
|
||||
{
|
||||
where: {
|
||||
spaceModel: { uuid: spaceModel.uuid },
|
||||
product: { uuid: product.uuid },
|
||||
},
|
||||
relations: ['tags'],
|
||||
},
|
||||
);
|
||||
if (spaceAllocation) {
|
||||
spaceAllocationsMap.set(spaceAllocationKey, spaceAllocation);
|
||||
}
|
||||
}
|
||||
|
||||
const movedToAlreadyExistingSpaceAllocations: IRelocatedAllocation[] =
|
||||
[];
|
||||
const spaceAllocation = spaceAllocationsMap.get(spaceAllocationKey);
|
||||
|
||||
if (spaceAllocation) {
|
||||
const existingTagUuids = new Set(
|
||||
spaceAllocation.tags.map((tag) => tag.uuid),
|
||||
);
|
||||
const newTags = tags.filter(
|
||||
(tag) => !existingTagUuids.has(tag.uuid),
|
||||
);
|
||||
|
||||
if (newTags.length > 0) {
|
||||
movedToAlreadyExistingSpaceAllocations.push({
|
||||
tags: newTags,
|
||||
allocation: spaceAllocation,
|
||||
});
|
||||
spaceAllocation.tags.push(...newTags);
|
||||
|
||||
await queryRunner.manager.save(spaceAllocation);
|
||||
}
|
||||
} else {
|
||||
let tagsToAdd = [...tags];
|
||||
|
||||
if (spaceTagUpdateDtos && spaceTagUpdateDtos.length > 0) {
|
||||
const spaceTagDtosToAdd = spaceTagUpdateDtos.filter(
|
||||
(dto) => dto.action === ModifyAction.ADD,
|
||||
);
|
||||
|
||||
tagsToAdd = tagsToAdd.filter(
|
||||
(tag) =>
|
||||
!spaceTagDtosToAdd.some(
|
||||
(addDto) =>
|
||||
(addDto.name && addDto.name === tag.name) ||
|
||||
(addDto.newTagUuid && addDto.newTagUuid === tag.uuid),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
if (tagsToAdd.length > 0) {
|
||||
const newSpaceAllocation = queryRunner.manager.create(
|
||||
SpaceModelProductAllocationEntity,
|
||||
{
|
||||
spaceModel: spaceModel,
|
||||
product: product,
|
||||
tags: tags,
|
||||
},
|
||||
);
|
||||
|
||||
movedToAlreadyExistingSpaceAllocations.push({
|
||||
allocation: newSpaceAllocation,
|
||||
tags: tags,
|
||||
});
|
||||
await queryRunner.manager.save(newSpaceAllocation);
|
||||
}
|
||||
}
|
||||
|
||||
if (movedToAlreadyExistingSpaceAllocations.length > 0) {
|
||||
if (!relocatedAllocationsMap.has(subspaceUuid)) {
|
||||
relocatedAllocationsMap.set(subspaceUuid, []);
|
||||
}
|
||||
relocatedAllocationsMap
|
||||
.get(subspaceUuid)
|
||||
.push(...movedToAlreadyExistingSpaceAllocations);
|
||||
}
|
||||
}
|
||||
|
||||
await queryRunner.manager.remove(
|
||||
@ -399,7 +404,7 @@ export class SubSpaceModelService {
|
||||
|
||||
const updatedSubspaces: {
|
||||
subspaceModel: SubspaceModelEntity;
|
||||
tags: ModifyTagDto[];
|
||||
tags: ModifyTagModelDto[];
|
||||
action: ModifyAction.UPDATE;
|
||||
}[] = [];
|
||||
|
||||
@ -503,6 +508,12 @@ export class SubSpaceModelService {
|
||||
return subspaceModels.flatMap((subspace) => subspace.tags || []);
|
||||
}
|
||||
|
||||
extractTagsFromModifiedSubspaceModels(
|
||||
subspaceModels: ModifySubspaceModelDto[],
|
||||
): ModifyTagModelDto[] {
|
||||
return subspaceModels.flatMap((subspace) => subspace.tags || []);
|
||||
}
|
||||
|
||||
private async getSubspacesByUuids(
|
||||
queryRunner: QueryRunner,
|
||||
subspaceUuids: string[],
|
||||
|
@ -1,68 +1,71 @@
|
||||
import { DeviceStatusFirebaseService } from '@app/common/firebase/devices-status/services/devices-status.service';
|
||||
import { AqiDataService } from '@app/common/helper/services/aqi.data.service';
|
||||
import { OccupancyService } from '@app/common/helper/services/occupancy.service';
|
||||
import { PowerClampService } from '@app/common/helper/services/power.clamp.service';
|
||||
import { SqlLoaderService } from '@app/common/helper/services/sql-loader.service';
|
||||
import { TuyaService } from '@app/common/integrations/tuya/services/tuya.service';
|
||||
import { AutomationRepository } from '@app/common/modules/automation/repositories';
|
||||
import { CommunityRepository } from '@app/common/modules/community/repositories';
|
||||
import { DeviceStatusLogRepository } from '@app/common/modules/device-status-log/repositories';
|
||||
import { DeviceRepository } from '@app/common/modules/device/repositories';
|
||||
import {
|
||||
PowerClampDailyRepository,
|
||||
PowerClampHourlyRepository,
|
||||
PowerClampMonthlyRepository,
|
||||
} from '@app/common/modules/power-clamp/repositories';
|
||||
import { ProductRepository } from '@app/common/modules/product/repositories';
|
||||
import { ProjectRepository } from '@app/common/modules/project/repositiories';
|
||||
import { SceneDeviceRepository } from '@app/common/modules/scene-device/repositories';
|
||||
import {
|
||||
SceneIconRepository,
|
||||
SceneRepository,
|
||||
} from '@app/common/modules/scene/repositories';
|
||||
import {
|
||||
InviteSpaceRepository,
|
||||
SpaceLinkRepository,
|
||||
SpaceProductAllocationRepository,
|
||||
SpaceRepository,
|
||||
} from '@app/common/modules/space';
|
||||
import { SpaceRepositoryModule } from '@app/common/modules/space/space.repository.module';
|
||||
import { Module } from '@nestjs/common';
|
||||
import { ConfigModule } from '@nestjs/config';
|
||||
import { SpaceModelController } from './controllers';
|
||||
import { SpaceModelService, SubSpaceModelService } from './services';
|
||||
import {
|
||||
SpaceModelProductAllocationRepoitory,
|
||||
SpaceModelRepository,
|
||||
SubspaceModelProductAllocationRepoitory,
|
||||
SubspaceModelRepository,
|
||||
TagModelRepository,
|
||||
} from '@app/common/modules/space-model';
|
||||
import {
|
||||
SubspaceProductAllocationRepository,
|
||||
SubspaceRepository,
|
||||
} from '@app/common/modules/space/repositories/subspace.repository';
|
||||
import { SpaceRepositoryModule } from '@app/common/modules/space/space.repository.module';
|
||||
import { NewTagRepository } from '@app/common/modules/tag/repositories/tag-repository';
|
||||
import { Module } from '@nestjs/common';
|
||||
import { ConfigModule } from '@nestjs/config';
|
||||
import { CqrsModule } from '@nestjs/cqrs';
|
||||
import { CommunityModule } from 'src/community/community.module';
|
||||
import { CommunityService } from 'src/community/services';
|
||||
import { DeviceService } from 'src/device/services';
|
||||
import { SceneService } from 'src/scene/services';
|
||||
import {
|
||||
SpaceService,
|
||||
SubspaceDeviceService,
|
||||
SubSpaceService,
|
||||
ValidationService,
|
||||
} from 'src/space/services';
|
||||
import { SpaceProductAllocationService } from 'src/space/services/space-product-allocation.service';
|
||||
import { SubspaceProductAllocationService } from 'src/space/services/subspace/subspace-product-allocation.service';
|
||||
import { TagService as NewTagService } from 'src/tags/services/tags.service';
|
||||
import { SpaceModelController } from './controllers';
|
||||
import { ProjectRepository } from '@app/common/modules/project/repositiories';
|
||||
import { ProductRepository } from '@app/common/modules/product/repositories';
|
||||
import {
|
||||
PropogateDeleteSpaceModelHandler,
|
||||
PropogateUpdateSpaceModelHandler,
|
||||
PropogateUpdateSpaceModelProductAllocationHandler,
|
||||
} from './handlers';
|
||||
import { SpaceModelService, SubSpaceModelService } from './services';
|
||||
import { CqrsModule } from '@nestjs/cqrs';
|
||||
import {
|
||||
InviteSpaceRepository,
|
||||
SpaceLinkRepository,
|
||||
SpaceProductAllocationRepository,
|
||||
SpaceRepository,
|
||||
TagRepository,
|
||||
} from '@app/common/modules/space';
|
||||
import {
|
||||
SubspaceProductAllocationRepository,
|
||||
SubspaceRepository,
|
||||
} from '@app/common/modules/space/repositories/subspace.repository';
|
||||
import {
|
||||
SpaceLinkService,
|
||||
SpaceService,
|
||||
SubspaceDeviceService,
|
||||
SubSpaceService,
|
||||
ValidationService,
|
||||
} from 'src/space/services';
|
||||
import { TagService } from 'src/space/services/tag';
|
||||
import { CommunityService } from 'src/community/services';
|
||||
import { DeviceRepository } from '@app/common/modules/device/repositories';
|
||||
import { TuyaService } from '@app/common/integrations/tuya/services/tuya.service';
|
||||
import { CommunityRepository } from '@app/common/modules/community/repositories';
|
||||
import { TagService as NewTagService } from 'src/tags/services/tags.service';
|
||||
import { NewTagRepository } from '@app/common/modules/tag/repositories/tag-repository';
|
||||
import { SpaceModelProductAllocationService } from './services/space-model-product-allocation.service';
|
||||
import { SubspaceModelProductAllocationService } from './services/subspace/subspace-model-product-allocation.service';
|
||||
import { SpaceProductAllocationService } from 'src/space/services/space-product-allocation.service';
|
||||
import { SubspaceProductAllocationService } from 'src/space/services/subspace/subspace-product-allocation.service';
|
||||
import { DeviceService } from 'src/device/services';
|
||||
import { SceneDeviceRepository } from '@app/common/modules/scene-device/repositories';
|
||||
import { DeviceStatusFirebaseService } from '@app/common/firebase/devices-status/services/devices-status.service';
|
||||
import { SceneService } from 'src/scene/services';
|
||||
import { DeviceStatusLogRepository } from '@app/common/modules/device-status-log/repositories';
|
||||
import {
|
||||
SceneIconRepository,
|
||||
SceneRepository,
|
||||
} from '@app/common/modules/scene/repositories';
|
||||
import { AutomationRepository } from '@app/common/modules/automation/repositories';
|
||||
import { CommunityModule } from 'src/community/community.module';
|
||||
import { PowerClampService } from '@app/common/helper/services/power.clamp.service';
|
||||
import {
|
||||
PowerClampHourlyRepository,
|
||||
PowerClampDailyRepository,
|
||||
PowerClampMonthlyRepository,
|
||||
} from '@app/common/modules/power-clamp/repositories';
|
||||
import { SqlLoaderService } from '@app/common/helper/services/sql-loader.service';
|
||||
import { OccupancyService } from '@app/common/helper/services/occupancy.service';
|
||||
|
||||
const CommandHandlers = [
|
||||
PropogateUpdateSpaceModelHandler,
|
||||
@ -84,13 +87,17 @@ const CommandHandlers = [
|
||||
SubspaceModelRepository,
|
||||
ProductRepository,
|
||||
SubspaceRepository,
|
||||
TagModelRepository,
|
||||
SubSpaceService,
|
||||
ValidationService,
|
||||
TagService,
|
||||
SubspaceDeviceService,
|
||||
CommunityService,
|
||||
TagRepository,
|
||||
DeviceRepository,
|
||||
TuyaService,
|
||||
CommunityRepository,
|
||||
SpaceLinkService,
|
||||
SpaceLinkRepository,
|
||||
InviteSpaceRepository,
|
||||
NewTagService,
|
||||
@ -119,7 +126,6 @@ const CommandHandlers = [
|
||||
PowerClampMonthlyRepository,
|
||||
SqlLoaderService,
|
||||
OccupancyService,
|
||||
AqiDataService,
|
||||
],
|
||||
exports: [CqrsModule, SpaceModelService],
|
||||
})
|
||||
|
@ -1,20 +1,16 @@
|
||||
import { ORPHAN_SPACE_NAME } from '@app/common/constants/orphan-constant';
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
import { Type } from 'class-transformer';
|
||||
import {
|
||||
ArrayUnique,
|
||||
IsArray,
|
||||
IsMongoId,
|
||||
IsBoolean,
|
||||
IsNotEmpty,
|
||||
IsNumber,
|
||||
IsOptional,
|
||||
IsString,
|
||||
IsUUID,
|
||||
NotEquals,
|
||||
ValidateNested,
|
||||
} from 'class-validator';
|
||||
import { CreateProductAllocationDto } from './create-product-allocation.dto';
|
||||
import { AddSubspaceDto } from './subspace';
|
||||
import { ProcessTagDto } from 'src/tags/dtos';
|
||||
|
||||
export class AddSpaceDto {
|
||||
@ApiProperty({
|
||||
@ -23,11 +19,6 @@ export class AddSpaceDto {
|
||||
})
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
@NotEquals(ORPHAN_SPACE_NAME, {
|
||||
message() {
|
||||
return `Space name cannot be "${ORPHAN_SPACE_NAME}". Please choose a different name.`;
|
||||
},
|
||||
})
|
||||
spaceName: string;
|
||||
|
||||
@ApiProperty({
|
||||
@ -48,6 +39,14 @@ export class AddSpaceDto {
|
||||
@IsOptional()
|
||||
public icon?: string;
|
||||
|
||||
@ApiProperty({
|
||||
description: 'Indicates whether the space is private or public',
|
||||
example: false,
|
||||
default: false,
|
||||
})
|
||||
@IsBoolean()
|
||||
isPrivate: boolean;
|
||||
|
||||
@ApiProperty({ description: 'X position on canvas', example: 120 })
|
||||
@IsNumber()
|
||||
x: number;
|
||||
@ -57,53 +56,73 @@ export class AddSpaceDto {
|
||||
y: number;
|
||||
|
||||
@ApiProperty({
|
||||
description: 'UUID of the Space Model',
|
||||
description: 'UUID of the Space',
|
||||
example: 'd290f1ee-6c54-4b01-90e6-d701748f0851',
|
||||
})
|
||||
@IsMongoId()
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
spaceModelUuid?: string;
|
||||
|
||||
@ApiProperty({ description: 'Y position on canvas', example: 200 })
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
direction?: string;
|
||||
|
||||
@ApiProperty({
|
||||
description: 'List of subspaces included in the model',
|
||||
type: [AddSubspaceDto],
|
||||
})
|
||||
@IsOptional()
|
||||
@IsArray()
|
||||
@ValidateNested({ each: true })
|
||||
@ArrayUnique((subspace) => subspace.subspaceName, {
|
||||
message(validationArguments) {
|
||||
const subspaces = validationArguments.value;
|
||||
const nameCounts = subspaces.reduce((acc, curr) => {
|
||||
acc[curr.subspaceName] = (acc[curr.subspaceName] || 0) + 1;
|
||||
return acc;
|
||||
}, {});
|
||||
// Find duplicates
|
||||
const duplicates = Object.keys(nameCounts).filter(
|
||||
(name) => nameCounts[name] > 1,
|
||||
);
|
||||
return `Duplicate subspace names found: ${duplicates.join(', ')}`;
|
||||
},
|
||||
})
|
||||
@Type(() => AddSubspaceDto)
|
||||
subspaces?: AddSubspaceDto[];
|
||||
|
||||
@ApiProperty({
|
||||
description: 'List of allocations associated with the space',
|
||||
type: [CreateProductAllocationDto],
|
||||
description: 'List of tags associated with the space model',
|
||||
type: [ProcessTagDto],
|
||||
})
|
||||
@IsOptional()
|
||||
@IsArray()
|
||||
@ValidateNested({ each: true })
|
||||
@Type(() => CreateProductAllocationDto)
|
||||
productAllocations?: CreateProductAllocationDto[];
|
||||
|
||||
@ApiProperty({
|
||||
description: 'List of children spaces associated with the space',
|
||||
type: [AddSpaceDto],
|
||||
})
|
||||
@IsOptional()
|
||||
@ValidateNested({ each: true })
|
||||
@Type(() => AddSpaceDto)
|
||||
children?: AddSpaceDto[];
|
||||
@Type(() => ProcessTagDto)
|
||||
tags?: ProcessTagDto[];
|
||||
}
|
||||
|
||||
export class AddUserSpaceDto {
|
||||
@ApiProperty({
|
||||
description: 'spaceUuid',
|
||||
required: true,
|
||||
})
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
public spaceUuid: string;
|
||||
@ApiProperty({
|
||||
description: 'userUuid',
|
||||
required: true,
|
||||
})
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
public userUuid: string;
|
||||
constructor(dto: Partial<AddUserSpaceDto>) {
|
||||
Object.assign(this, dto);
|
||||
}
|
||||
}
|
||||
|
||||
export class AddUserSpaceUsingCodeDto {
|
||||
@ApiProperty({
|
||||
description: 'userUuid',
|
||||
required: true,
|
||||
})
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
public userUuid: string;
|
||||
@ApiProperty({
|
||||
description: 'inviteCode',
|
||||
required: true,
|
||||
})
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
public inviteCode: string;
|
||||
|
||||
constructor(dto: Partial<AddUserSpaceDto>) {
|
||||
Object.assign(this, dto);
|
||||
}
|
||||
}
|
||||
|
@ -1,29 +0,0 @@
|
||||
import { SpaceEntity } from '@app/common/modules/space/entities/space.entity';
|
||||
import { SubspaceEntity } from '@app/common/modules/space/entities/subspace/subspace.entity';
|
||||
import { QueryRunner } from 'typeorm';
|
||||
import { CreateProductAllocationDto } from './create-product-allocation.dto';
|
||||
|
||||
export enum AllocationsOwnerType {
|
||||
SPACE = 'space',
|
||||
SUBSPACE = 'subspace',
|
||||
}
|
||||
export class BaseCreateAllocationsDto {
|
||||
productAllocations: CreateProductAllocationDto[];
|
||||
projectUuid: string;
|
||||
queryRunner: QueryRunner;
|
||||
type: AllocationsOwnerType;
|
||||
}
|
||||
|
||||
export class CreateSpaceAllocationsDto extends BaseCreateAllocationsDto {
|
||||
space: SpaceEntity;
|
||||
type: AllocationsOwnerType.SPACE;
|
||||
}
|
||||
|
||||
export class CreateSubspaceAllocationsDto extends BaseCreateAllocationsDto {
|
||||
subspace: SubspaceEntity;
|
||||
type: AllocationsOwnerType.SUBSPACE;
|
||||
}
|
||||
|
||||
export type CreateAllocationsDto =
|
||||
| CreateSpaceAllocationsDto
|
||||
| CreateSubspaceAllocationsDto;
|
@ -1,36 +0,0 @@
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
import {
|
||||
IsNotEmpty,
|
||||
IsOptional,
|
||||
IsString,
|
||||
IsUUID,
|
||||
ValidateIf,
|
||||
} from 'class-validator';
|
||||
|
||||
export class CreateProductAllocationDto {
|
||||
@ApiProperty({
|
||||
description: 'The name of the tag (if creating a new tag)',
|
||||
example: 'New Tag',
|
||||
})
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
@ValidateIf((o) => !o.tagUuid)
|
||||
tagName: string;
|
||||
|
||||
@ApiProperty({
|
||||
description: 'UUID of the tag (if selecting an existing tag)',
|
||||
example: '123e4567-e89b-12d3-a456-426614174000',
|
||||
})
|
||||
@IsUUID()
|
||||
@IsNotEmpty()
|
||||
@ValidateIf((o) => !o.tagName)
|
||||
tagUuid: string;
|
||||
|
||||
@ApiProperty({
|
||||
description: 'UUID of the product',
|
||||
example: '550e8400-e29b-41d4-a716-446655440000',
|
||||
})
|
||||
@IsUUID()
|
||||
@IsOptional()
|
||||
productUuid: string;
|
||||
}
|
@ -1,10 +1,8 @@
|
||||
export * from './add.space.dto';
|
||||
export * from './community-space.param';
|
||||
export * from './create-allocations.dto';
|
||||
export * from './create-product-allocation.dto';
|
||||
export * from './get.space.param';
|
||||
export * from './project.param.dto';
|
||||
export * from './subspace';
|
||||
export * from './tag';
|
||||
export * from './update.space.dto';
|
||||
export * from './user-space.param';
|
||||
export * from './subspace';
|
||||
export * from './project.param.dto';
|
||||
export * from './update.space.dto';
|
||||
export * from './tag';
|
||||
|
@ -1,5 +1,4 @@
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
import { Type } from 'class-transformer';
|
||||
import {
|
||||
IsArray,
|
||||
IsNotEmpty,
|
||||
@ -7,8 +6,8 @@ import {
|
||||
IsString,
|
||||
ValidateNested,
|
||||
} from 'class-validator';
|
||||
import { Type } from 'class-transformer';
|
||||
import { ProcessTagDto } from 'src/tags/dtos';
|
||||
import { CreateProductAllocationDto } from '../create-product-allocation.dto';
|
||||
|
||||
export class AddSubspaceDto {
|
||||
@ApiProperty({
|
||||
@ -25,7 +24,7 @@ export class AddSubspaceDto {
|
||||
})
|
||||
@IsArray()
|
||||
@ValidateNested({ each: true })
|
||||
@Type(() => CreateProductAllocationDto)
|
||||
@Type(() => ProcessTagDto)
|
||||
@IsOptional()
|
||||
productAllocations?: CreateProductAllocationDto[];
|
||||
tags?: ProcessTagDto[];
|
||||
}
|
||||
|
@ -1,5 +1,6 @@
|
||||
export * from './add.subspace-device.param';
|
||||
export * from './add.subspace.dto';
|
||||
export * from './delete.subspace.dto';
|
||||
export * from './get.subspace.param';
|
||||
export * from './add.subspace-device.param';
|
||||
export * from './update.subspace.dto';
|
||||
export * from './delete.subspace.dto';
|
||||
export * from './modify.subspace.dto';
|
||||
|
47
src/space/dtos/subspace/modify.subspace.dto.ts
Normal file
47
src/space/dtos/subspace/modify.subspace.dto.ts
Normal file
@ -0,0 +1,47 @@
|
||||
import { ModifyAction } from '@app/common/constants/modify-action.enum';
|
||||
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||
import { Type } from 'class-transformer';
|
||||
import {
|
||||
IsEnum,
|
||||
IsOptional,
|
||||
IsString,
|
||||
IsArray,
|
||||
ValidateNested,
|
||||
} from 'class-validator';
|
||||
import { ModifyTagDto } from '../tag/modify-tag.dto';
|
||||
|
||||
export class ModifySubspaceDto {
|
||||
@ApiProperty({
|
||||
description: 'Action to perform: add, update, or delete',
|
||||
example: ModifyAction.ADD,
|
||||
})
|
||||
@IsEnum(ModifyAction)
|
||||
action: ModifyAction;
|
||||
|
||||
@ApiPropertyOptional({
|
||||
description: 'UUID of the subspace (required for update/delete)',
|
||||
example: '123e4567-e89b-12d3-a456-426614174000',
|
||||
})
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
uuid?: string;
|
||||
|
||||
@ApiPropertyOptional({
|
||||
description: 'Name of the subspace (required for add/update)',
|
||||
example: 'Living Room',
|
||||
})
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
subspaceName?: string;
|
||||
|
||||
@ApiPropertyOptional({
|
||||
description:
|
||||
'List of tag modifications (add/update/delete) for the subspace',
|
||||
type: [ModifyTagDto],
|
||||
})
|
||||
@IsOptional()
|
||||
@IsArray()
|
||||
@ValidateNested({ each: true })
|
||||
@Type(() => ModifyTagDto)
|
||||
tags?: ModifyTagDto[];
|
||||
}
|
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user