mirror of
https://github.com/SyncrowIOT/backend.git
synced 2025-07-11 15:48:09 +00:00
Compare commits
1 Commits
dev
...
task/curat
Author | SHA1 | Date | |
---|---|---|---|
f0b472d7b0 |
@ -21,7 +21,6 @@ module.exports = {
|
|||||||
'@typescript-eslint/explicit-function-return-type': 'off',
|
'@typescript-eslint/explicit-function-return-type': 'off',
|
||||||
'@typescript-eslint/explicit-module-boundary-types': 'off',
|
'@typescript-eslint/explicit-module-boundary-types': 'off',
|
||||||
'@typescript-eslint/no-explicit-any': 'off',
|
'@typescript-eslint/no-explicit-any': 'off',
|
||||||
"@typescript-eslint/no-unused-vars": 'warn',
|
|
||||||
},
|
},
|
||||||
settings: {
|
settings: {
|
||||||
'import/resolver': {
|
'import/resolver': {
|
||||||
|
17
.github/pull_request_template.md
vendored
17
.github/pull_request_template.md
vendored
@ -1,17 +0,0 @@
|
|||||||
<!--
|
|
||||||
Thanks for contributing!
|
|
||||||
|
|
||||||
Provide a description of your changes below and a general summary in the title.
|
|
||||||
-->
|
|
||||||
|
|
||||||
## Jira Ticket
|
|
||||||
|
|
||||||
[SP-0000](https://syncrow.atlassian.net/browse/SP-0000)
|
|
||||||
|
|
||||||
## Description
|
|
||||||
|
|
||||||
<!--- Describe your changes in detail -->
|
|
||||||
|
|
||||||
## How to Test
|
|
||||||
|
|
||||||
<!--- Describe the created APIs / Logic -->
|
|
2
.gitignore
vendored
2
.gitignore
vendored
@ -4,7 +4,7 @@
|
|||||||
/build
|
/build
|
||||||
|
|
||||||
#github
|
#github
|
||||||
/.github/workflows
|
/.github
|
||||||
|
|
||||||
# Logs
|
# Logs
|
||||||
logs
|
logs
|
||||||
|
@ -1,6 +1,5 @@
|
|||||||
import { PlatformType } from '@app/common/constants/platform-type.enum';
|
import { PlatformType } from '@app/common/constants/platform-type.enum';
|
||||||
import { RoleType } from '@app/common/constants/role.type.enum';
|
import { RoleType } from '@app/common/constants/role.type.enum';
|
||||||
import { UserEntity } from '@app/common/modules/user/entities';
|
|
||||||
import {
|
import {
|
||||||
BadRequestException,
|
BadRequestException,
|
||||||
Injectable,
|
Injectable,
|
||||||
@ -33,7 +32,7 @@ export class AuthService {
|
|||||||
pass: string,
|
pass: string,
|
||||||
regionUuid?: string,
|
regionUuid?: string,
|
||||||
platform?: PlatformType,
|
platform?: PlatformType,
|
||||||
): Promise<Omit<UserEntity, 'password'>> {
|
): Promise<any> {
|
||||||
const user = await this.userRepository.findOne({
|
const user = await this.userRepository.findOne({
|
||||||
where: {
|
where: {
|
||||||
email,
|
email,
|
||||||
@ -71,9 +70,8 @@ export class AuthService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||||
// const { password, ...result } = user;
|
const { password, ...result } = user;
|
||||||
delete user.password;
|
return result;
|
||||||
return user;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async createSession(data): Promise<UserSessionEntity> {
|
async createSession(data): Promise<UserSessionEntity> {
|
||||||
@ -116,7 +114,6 @@ export class AuthService {
|
|||||||
hasAcceptedWebAgreement: user.hasAcceptedWebAgreement,
|
hasAcceptedWebAgreement: user.hasAcceptedWebAgreement,
|
||||||
hasAcceptedAppAgreement: user.hasAcceptedAppAgreement,
|
hasAcceptedAppAgreement: user.hasAcceptedAppAgreement,
|
||||||
project: user?.project,
|
project: user?.project,
|
||||||
bookingPoints: user?.bookingPoints,
|
|
||||||
};
|
};
|
||||||
if (payload.googleCode) {
|
if (payload.googleCode) {
|
||||||
const profile = await this.getProfile(payload.googleCode);
|
const profile = await this.getProfile(payload.googleCode);
|
||||||
|
@ -69,28 +69,7 @@ export class ControllerRoute {
|
|||||||
'Retrieve the list of all regions registered in Syncrow.';
|
'Retrieve the list of all regions registered in Syncrow.';
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
static BOOKABLE_SPACES = class {
|
|
||||||
public static readonly ROUTE = 'bookable-spaces';
|
|
||||||
static ACTIONS = class {
|
|
||||||
public static readonly ADD_BOOKABLE_SPACES_SUMMARY =
|
|
||||||
'Add new bookable spaces';
|
|
||||||
|
|
||||||
public static readonly ADD_BOOKABLE_SPACES_DESCRIPTION =
|
|
||||||
'This endpoint allows you to add new bookable spaces by providing the required details.';
|
|
||||||
|
|
||||||
public static readonly GET_ALL_BOOKABLE_SPACES_SUMMARY =
|
|
||||||
'Get all bookable spaces';
|
|
||||||
|
|
||||||
public static readonly GET_ALL_BOOKABLE_SPACES_DESCRIPTION =
|
|
||||||
'This endpoint retrieves all bookable spaces.';
|
|
||||||
|
|
||||||
public static readonly UPDATE_BOOKABLE_SPACES_SUMMARY =
|
|
||||||
'Update existing bookable spaces';
|
|
||||||
|
|
||||||
public static readonly UPDATE_BOOKABLE_SPACES_DESCRIPTION =
|
|
||||||
'This endpoint allows you to update existing bookable spaces by providing the required details.';
|
|
||||||
};
|
|
||||||
};
|
|
||||||
static COMMUNITY = class {
|
static COMMUNITY = class {
|
||||||
public static readonly ROUTE = '/projects/:projectUuid/communities';
|
public static readonly ROUTE = '/projects/:projectUuid/communities';
|
||||||
static ACTIONS = class {
|
static ACTIONS = class {
|
||||||
@ -220,11 +199,6 @@ export class ControllerRoute {
|
|||||||
public static readonly UPDATE_SPACE_DESCRIPTION =
|
public static readonly UPDATE_SPACE_DESCRIPTION =
|
||||||
'Updates a space by its UUID and community ID. You can update the name, parent space, and other properties. If a parent space is provided and not already a parent, its `isParent` flag will be set to true.';
|
'Updates a space by its UUID and community ID. You can update the name, parent space, and other properties. If a parent space is provided and not already a parent, its `isParent` flag will be set to true.';
|
||||||
|
|
||||||
public static readonly UPDATE_CHILDREN_SPACES_ORDER_OF_A_SPACE_SUMMARY =
|
|
||||||
'Update the order of child spaces under a specific parent space';
|
|
||||||
public static readonly UPDATE_CHILDREN_SPACES_ORDER_OF_A_SPACE_DESCRIPTION =
|
|
||||||
'Updates the order of child spaces under a specific parent space. You can provide a new order for the child spaces.';
|
|
||||||
|
|
||||||
public static readonly GET_HEIRARCHY_SUMMARY = 'Get space hierarchy';
|
public static readonly GET_HEIRARCHY_SUMMARY = 'Get space hierarchy';
|
||||||
public static readonly GET_HEIRARCHY_DESCRIPTION =
|
public static readonly GET_HEIRARCHY_DESCRIPTION =
|
||||||
'This endpoint retrieves the hierarchical structure of spaces under a given space ID. It returns all the child spaces nested within the specified space, organized by their parent-child relationships. ';
|
'This endpoint retrieves the hierarchical structure of spaces under a given space ID. It returns all the child spaces nested within the specified space, organized by their parent-child relationships. ';
|
||||||
@ -658,11 +632,6 @@ export class ControllerRoute {
|
|||||||
'Delete scenes by device uuid and switch name';
|
'Delete scenes by device uuid and switch name';
|
||||||
public static readonly DELETE_SCENES_BY_SWITCH_NAME_DESCRIPTION =
|
public static readonly DELETE_SCENES_BY_SWITCH_NAME_DESCRIPTION =
|
||||||
'This endpoint deletes all scenes associated with a specific switch device.';
|
'This endpoint deletes all scenes associated with a specific switch device.';
|
||||||
|
|
||||||
public static readonly POPULATE_TUYA_CONST_UUID_SUMMARY =
|
|
||||||
'Populate Tuya const UUID';
|
|
||||||
public static readonly POPULATE_TUYA_CONST_UUID_DESCRIPTION =
|
|
||||||
'This endpoint populates the Tuya const UUID for all devices.';
|
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
static DEVICE_COMMISSION = class {
|
static DEVICE_COMMISSION = class {
|
||||||
|
@ -25,7 +25,6 @@ import {
|
|||||||
InviteUserEntity,
|
InviteUserEntity,
|
||||||
InviteUserSpaceEntity,
|
InviteUserSpaceEntity,
|
||||||
} from '../modules/Invite-user/entities';
|
} from '../modules/Invite-user/entities';
|
||||||
import { SpaceDailyOccupancyDurationEntity } from '../modules/occupancy/entities';
|
|
||||||
import {
|
import {
|
||||||
PowerClampDailyEntity,
|
PowerClampDailyEntity,
|
||||||
PowerClampHourlyEntity,
|
PowerClampHourlyEntity,
|
||||||
@ -47,6 +46,7 @@ import {
|
|||||||
SubspaceModelProductAllocationEntity,
|
SubspaceModelProductAllocationEntity,
|
||||||
} from '../modules/space-model/entities';
|
} from '../modules/space-model/entities';
|
||||||
import { InviteSpaceEntity } from '../modules/space/entities/invite-space.entity';
|
import { InviteSpaceEntity } from '../modules/space/entities/invite-space.entity';
|
||||||
|
import { SpaceLinkEntity } from '../modules/space/entities/space-link.entity';
|
||||||
import { SpaceProductAllocationEntity } from '../modules/space/entities/space-product-allocation.entity';
|
import { SpaceProductAllocationEntity } from '../modules/space/entities/space-product-allocation.entity';
|
||||||
import { SpaceEntity } from '../modules/space/entities/space.entity';
|
import { SpaceEntity } from '../modules/space/entities/space.entity';
|
||||||
import { SubspaceProductAllocationEntity } from '../modules/space/entities/subspace/subspace-product-allocation.entity';
|
import { SubspaceProductAllocationEntity } from '../modules/space/entities/subspace/subspace-product-allocation.entity';
|
||||||
@ -58,7 +58,7 @@ import {
|
|||||||
UserSpaceEntity,
|
UserSpaceEntity,
|
||||||
} from '../modules/user/entities';
|
} from '../modules/user/entities';
|
||||||
import { VisitorPasswordEntity } from '../modules/visitor-password/entities';
|
import { VisitorPasswordEntity } from '../modules/visitor-password/entities';
|
||||||
import { BookableSpaceEntity } from '../modules/booking/entities';
|
import { SpaceDailyOccupancyDurationEntity } from '../modules/occupancy/entities';
|
||||||
@Module({
|
@Module({
|
||||||
imports: [
|
imports: [
|
||||||
TypeOrmModule.forRootAsync({
|
TypeOrmModule.forRootAsync({
|
||||||
@ -87,6 +87,7 @@ import { BookableSpaceEntity } from '../modules/booking/entities';
|
|||||||
PermissionTypeEntity,
|
PermissionTypeEntity,
|
||||||
CommunityEntity,
|
CommunityEntity,
|
||||||
SpaceEntity,
|
SpaceEntity,
|
||||||
|
SpaceLinkEntity,
|
||||||
SubspaceEntity,
|
SubspaceEntity,
|
||||||
UserSpaceEntity,
|
UserSpaceEntity,
|
||||||
DeviceUserPermissionEntity,
|
DeviceUserPermissionEntity,
|
||||||
@ -118,7 +119,6 @@ import { BookableSpaceEntity } from '../modules/booking/entities';
|
|||||||
PresenceSensorDailySpaceEntity,
|
PresenceSensorDailySpaceEntity,
|
||||||
AqiSpaceDailyPollutantStatsEntity,
|
AqiSpaceDailyPollutantStatsEntity,
|
||||||
SpaceDailyOccupancyDurationEntity,
|
SpaceDailyOccupancyDurationEntity,
|
||||||
BookableSpaceEntity,
|
|
||||||
],
|
],
|
||||||
namingStrategy: new SnakeNamingStrategy(),
|
namingStrategy: new SnakeNamingStrategy(),
|
||||||
synchronize: Boolean(JSON.parse(configService.get('DB_SYNC'))),
|
synchronize: Boolean(JSON.parse(configService.get('DB_SYNC'))),
|
||||||
@ -127,8 +127,8 @@ import { BookableSpaceEntity } from '../modules/booking/entities';
|
|||||||
logger: typeOrmLogger,
|
logger: typeOrmLogger,
|
||||||
extra: {
|
extra: {
|
||||||
charset: 'utf8mb4',
|
charset: 'utf8mb4',
|
||||||
max: 100, // set pool max size
|
max: 20, // set pool max size
|
||||||
idleTimeoutMillis: 3000, // close idle clients after 5 second
|
idleTimeoutMillis: 5000, // close idle clients after 5 second
|
||||||
connectionTimeoutMillis: 12_000, // return an error after 11 second if connection could not be established
|
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)
|
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 { IsBoolean, IsDate, IsOptional } from 'class-validator';
|
||||||
import { Transform } from 'class-transformer';
|
|
||||||
import { IsBoolean, IsOptional } from 'class-validator';
|
|
||||||
import { BooleanValues } from '../constants/boolean-values.enum';
|
|
||||||
import { IsPageRequestParam } from '../validators/is-page-request-param.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 { 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 {
|
export class PaginationRequestGetListDto {
|
||||||
@ApiProperty({
|
@ApiProperty({
|
||||||
@ -18,7 +19,6 @@ export class PaginationRequestGetListDto {
|
|||||||
return value.obj.includeSpaces === BooleanValues.TRUE;
|
return value.obj.includeSpaces === BooleanValues.TRUE;
|
||||||
})
|
})
|
||||||
public includeSpaces?: boolean = false;
|
public includeSpaces?: boolean = false;
|
||||||
|
|
||||||
@IsOptional()
|
@IsOptional()
|
||||||
@IsPageRequestParam({
|
@IsPageRequestParam({
|
||||||
message: 'Page must be bigger than 0',
|
message: 'Page must be bigger than 0',
|
||||||
@ -40,4 +40,40 @@ export class PaginationRequestGetListDto {
|
|||||||
description: 'Size request',
|
description: 'Size request',
|
||||||
})
|
})
|
||||||
size?: number;
|
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;
|
||||||
}
|
}
|
||||||
|
@ -3,12 +3,28 @@ import { DeviceStatusFirebaseController } from './controllers/devices-status.con
|
|||||||
import { DeviceStatusFirebaseService } from './services/devices-status.service';
|
import { DeviceStatusFirebaseService } from './services/devices-status.service';
|
||||||
import { DeviceRepository } from '@app/common/modules/device/repositories';
|
import { DeviceRepository } from '@app/common/modules/device/repositories';
|
||||||
import { DeviceStatusLogRepository } from '@app/common/modules/device-status-log/repositories/device-status.repository';
|
import { DeviceStatusLogRepository } from '@app/common/modules/device-status-log/repositories/device-status.repository';
|
||||||
|
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';
|
||||||
|
import { AqiDataService } from '@app/common/helper/services/aqi.data.service';
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
providers: [
|
providers: [
|
||||||
DeviceStatusFirebaseService,
|
DeviceStatusFirebaseService,
|
||||||
DeviceRepository,
|
DeviceRepository,
|
||||||
DeviceStatusLogRepository,
|
DeviceStatusLogRepository,
|
||||||
|
PowerClampService,
|
||||||
|
PowerClampHourlyRepository,
|
||||||
|
PowerClampDailyRepository,
|
||||||
|
PowerClampMonthlyRepository,
|
||||||
|
SqlLoaderService,
|
||||||
|
OccupancyService,
|
||||||
|
AqiDataService,
|
||||||
],
|
],
|
||||||
controllers: [DeviceStatusFirebaseController],
|
controllers: [DeviceStatusFirebaseController],
|
||||||
exports: [DeviceStatusFirebaseService, DeviceStatusLogRepository],
|
exports: [DeviceStatusFirebaseService, DeviceStatusLogRepository],
|
||||||
|
@ -18,6 +18,12 @@ import {
|
|||||||
runTransaction,
|
runTransaction,
|
||||||
} from 'firebase/database';
|
} from 'firebase/database';
|
||||||
import { DeviceStatusLogRepository } from '@app/common/modules/device-status-log/repositories';
|
import { DeviceStatusLogRepository } from '@app/common/modules/device-status-log/repositories';
|
||||||
|
import { ProductType } from '@app/common/constants/product-type.enum';
|
||||||
|
import { PowerClampService } from '@app/common/helper/services/power.clamp.service';
|
||||||
|
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()
|
@Injectable()
|
||||||
export class DeviceStatusFirebaseService {
|
export class DeviceStatusFirebaseService {
|
||||||
private tuya: TuyaContext;
|
private tuya: TuyaContext;
|
||||||
@ -27,6 +33,9 @@ export class DeviceStatusFirebaseService {
|
|||||||
constructor(
|
constructor(
|
||||||
private readonly configService: ConfigService,
|
private readonly configService: ConfigService,
|
||||||
private readonly deviceRepository: DeviceRepository,
|
private readonly deviceRepository: DeviceRepository,
|
||||||
|
private readonly powerClampService: PowerClampService,
|
||||||
|
private readonly occupancyService: OccupancyService,
|
||||||
|
private readonly aqiDataService: AqiDataService,
|
||||||
private deviceStatusLogRepository: DeviceStatusLogRepository,
|
private deviceStatusLogRepository: DeviceStatusLogRepository,
|
||||||
) {
|
) {
|
||||||
const accessKey = this.configService.get<string>('auth-config.ACCESS_KEY');
|
const accessKey = this.configService.get<string>('auth-config.ACCESS_KEY');
|
||||||
@ -71,94 +80,25 @@ export class DeviceStatusFirebaseService {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
async addBatchDeviceStatusToOurDb(
|
|
||||||
batch: {
|
|
||||||
deviceTuyaUuid: string;
|
|
||||||
status: any;
|
|
||||||
log: any;
|
|
||||||
device: any;
|
|
||||||
}[],
|
|
||||||
): Promise<void> {
|
|
||||||
const allLogs = [];
|
|
||||||
|
|
||||||
console.log(`🔁 Preparing logs from batch of ${batch.length} items...`);
|
|
||||||
|
|
||||||
for (const item of batch) {
|
|
||||||
const device = item.device;
|
|
||||||
if (!device?.uuid) {
|
|
||||||
console.log(`⛔ Skipped unknown device: ${item.deviceTuyaUuid}`);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
const logs = item.log.properties.map((property) =>
|
|
||||||
this.deviceStatusLogRepository.create({
|
|
||||||
deviceId: device.uuid,
|
|
||||||
deviceTuyaId: item.deviceTuyaUuid,
|
|
||||||
productId: item.log.productId,
|
|
||||||
log: item.log,
|
|
||||||
code: property.code,
|
|
||||||
value: property.value,
|
|
||||||
eventId: item.log.dataId,
|
|
||||||
eventTime: new Date(property.time).toISOString(),
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
allLogs.push(...logs);
|
|
||||||
}
|
|
||||||
|
|
||||||
console.log(`📝 Total logs to insert: ${allLogs.length}`);
|
|
||||||
|
|
||||||
const insertLogsPromise = (async () => {
|
|
||||||
const chunkSize = 300;
|
|
||||||
let insertedCount = 0;
|
|
||||||
|
|
||||||
for (let i = 0; i < allLogs.length; i += chunkSize) {
|
|
||||||
const chunk = allLogs.slice(i, i + chunkSize);
|
|
||||||
try {
|
|
||||||
const result = await this.deviceStatusLogRepository
|
|
||||||
.createQueryBuilder()
|
|
||||||
.insert()
|
|
||||||
.into('device-status-log') // or use DeviceStatusLogEntity
|
|
||||||
.values(chunk)
|
|
||||||
.orIgnore() // skip duplicates
|
|
||||||
.execute();
|
|
||||||
|
|
||||||
insertedCount += result.identifiers.length;
|
|
||||||
console.log(
|
|
||||||
`✅ Inserted ${result.identifiers.length} / ${chunk.length} logs (chunk)`,
|
|
||||||
);
|
|
||||||
} catch (error) {
|
|
||||||
console.error('❌ Insert error (skipped chunk):', error.message);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
console.log(
|
|
||||||
`✅ Total logs inserted: ${insertedCount} / ${allLogs.length}`,
|
|
||||||
);
|
|
||||||
})();
|
|
||||||
|
|
||||||
await insertLogsPromise;
|
|
||||||
}
|
|
||||||
|
|
||||||
async addDeviceStatusToFirebase(
|
async addDeviceStatusToFirebase(
|
||||||
addDeviceStatusDto: AddDeviceStatusDto & { device?: any },
|
addDeviceStatusDto: AddDeviceStatusDto,
|
||||||
): Promise<AddDeviceStatusDto | null> {
|
): Promise<AddDeviceStatusDto | null> {
|
||||||
try {
|
try {
|
||||||
let device = addDeviceStatusDto.device;
|
const device = await this.getDeviceByDeviceTuyaUuid(
|
||||||
if (!device) {
|
addDeviceStatusDto.deviceTuyaUuid,
|
||||||
device = await this.getDeviceByDeviceTuyaUuid(
|
);
|
||||||
addDeviceStatusDto.deviceTuyaUuid,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
if (device?.uuid) {
|
if (device?.uuid) {
|
||||||
return await this.createDeviceStatusFirebase({
|
return await this.createDeviceStatusFirebase({
|
||||||
deviceUuid: device.uuid,
|
deviceUuid: device.uuid,
|
||||||
...addDeviceStatusDto,
|
...addDeviceStatusDto,
|
||||||
productType: device.productDevice?.prodType,
|
productType: device.productDevice.prodType,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
// Return null if device not found or no UUID
|
// Return null if device not found or no UUID
|
||||||
return null;
|
return null;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
// Handle the error silently, perhaps log it internally or ignore it
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -172,15 +112,6 @@ export class DeviceStatusFirebaseService {
|
|||||||
relations: ['productDevice'],
|
relations: ['productDevice'],
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
async getAllDevices() {
|
|
||||||
return await this.deviceRepository.find({
|
|
||||||
where: {
|
|
||||||
isActive: true,
|
|
||||||
},
|
|
||||||
relations: ['productDevice'],
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
async getDevicesInstructionStatus(deviceUuid: string) {
|
async getDevicesInstructionStatus(deviceUuid: string) {
|
||||||
try {
|
try {
|
||||||
const deviceDetails = await this.getDeviceByDeviceUuid(deviceUuid);
|
const deviceDetails = await this.getDeviceByDeviceUuid(deviceUuid);
|
||||||
@ -284,6 +215,126 @@ export class DeviceStatusFirebaseService {
|
|||||||
return existingData;
|
return existingData;
|
||||||
});
|
});
|
||||||
|
|
||||||
|
if (this.isDevEnv) {
|
||||||
|
// Save logs to your repository
|
||||||
|
const newLogs = addDeviceStatusDto.log.properties.map((property) => {
|
||||||
|
return this.deviceStatusLogRepository.create({
|
||||||
|
deviceId: addDeviceStatusDto.deviceUuid,
|
||||||
|
deviceTuyaId: addDeviceStatusDto.deviceTuyaUuid,
|
||||||
|
productId: addDeviceStatusDto.log.productId,
|
||||||
|
log: addDeviceStatusDto.log,
|
||||||
|
code: property.code,
|
||||||
|
value: property.value,
|
||||||
|
eventId: addDeviceStatusDto.log.dataId,
|
||||||
|
eventTime: new Date(property.time).toISOString(),
|
||||||
|
});
|
||||||
|
});
|
||||||
|
await this.deviceStatusLogRepository.save(newLogs);
|
||||||
|
|
||||||
|
if (addDeviceStatusDto.productType === ProductType.PC) {
|
||||||
|
const energyCodes = new Set([
|
||||||
|
PowerClampEnergyEnum.ENERGY_CONSUMED,
|
||||||
|
PowerClampEnergyEnum.ENERGY_CONSUMED_A,
|
||||||
|
PowerClampEnergyEnum.ENERGY_CONSUMED_B,
|
||||||
|
PowerClampEnergyEnum.ENERGY_CONSUMED_C,
|
||||||
|
]);
|
||||||
|
|
||||||
|
const energyStatus = addDeviceStatusDto?.log?.properties?.find(
|
||||||
|
(status) => energyCodes.has(status.code),
|
||||||
|
);
|
||||||
|
|
||||||
|
if (energyStatus) {
|
||||||
|
await this.powerClampService.updateEnergyConsumedHistoricalData(
|
||||||
|
addDeviceStatusDto.deviceUuid,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (
|
||||||
|
addDeviceStatusDto.productType === ProductType.CPS ||
|
||||||
|
addDeviceStatusDto.productType === ProductType.WPS
|
||||||
|
) {
|
||||||
|
const occupancyCodes = new Set([PresenceSensorEnum.PRESENCE_STATE]);
|
||||||
|
|
||||||
|
const occupancyStatus = addDeviceStatusDto?.log?.properties?.find(
|
||||||
|
(status) => occupancyCodes.has(status.code),
|
||||||
|
);
|
||||||
|
|
||||||
|
if (occupancyStatus) {
|
||||||
|
await this.occupancyService.updateOccupancySensorHistoricalData(
|
||||||
|
addDeviceStatusDto.deviceUuid,
|
||||||
|
);
|
||||||
|
await this.occupancyService.updateOccupancySensorHistoricalDurationData(
|
||||||
|
addDeviceStatusDto.deviceUuid,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (addDeviceStatusDto.productType === ProductType.AQI) {
|
||||||
|
await this.aqiDataService.updateAQISensorHistoricalData(
|
||||||
|
addDeviceStatusDto.deviceUuid,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// Save logs to your repository
|
||||||
|
const newLogs = addDeviceStatusDto?.status.map((property) => {
|
||||||
|
return this.deviceStatusLogRepository.create({
|
||||||
|
deviceId: addDeviceStatusDto.deviceUuid,
|
||||||
|
deviceTuyaId: addDeviceStatusDto.deviceTuyaUuid,
|
||||||
|
productId: addDeviceStatusDto.log.productKey,
|
||||||
|
log: addDeviceStatusDto.log,
|
||||||
|
code: property.code,
|
||||||
|
value: property.value,
|
||||||
|
eventId: addDeviceStatusDto.log.dataId,
|
||||||
|
eventTime: new Date(property.t).toISOString(),
|
||||||
|
});
|
||||||
|
});
|
||||||
|
await this.deviceStatusLogRepository.save(newLogs);
|
||||||
|
|
||||||
|
if (addDeviceStatusDto.productType === ProductType.PC) {
|
||||||
|
const energyCodes = new Set([
|
||||||
|
PowerClampEnergyEnum.ENERGY_CONSUMED,
|
||||||
|
PowerClampEnergyEnum.ENERGY_CONSUMED_A,
|
||||||
|
PowerClampEnergyEnum.ENERGY_CONSUMED_B,
|
||||||
|
PowerClampEnergyEnum.ENERGY_CONSUMED_C,
|
||||||
|
]);
|
||||||
|
|
||||||
|
const energyStatus = addDeviceStatusDto?.status?.find((status) => {
|
||||||
|
return energyCodes.has(status.code as PowerClampEnergyEnum);
|
||||||
|
});
|
||||||
|
|
||||||
|
if (energyStatus) {
|
||||||
|
await this.powerClampService.updateEnergyConsumedHistoricalData(
|
||||||
|
addDeviceStatusDto.deviceUuid,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (
|
||||||
|
addDeviceStatusDto.productType === ProductType.CPS ||
|
||||||
|
addDeviceStatusDto.productType === ProductType.WPS
|
||||||
|
) {
|
||||||
|
const occupancyCodes = new Set([PresenceSensorEnum.PRESENCE_STATE]);
|
||||||
|
|
||||||
|
const occupancyStatus = addDeviceStatusDto?.status?.find((status) => {
|
||||||
|
return occupancyCodes.has(status.code as PresenceSensorEnum);
|
||||||
|
});
|
||||||
|
|
||||||
|
if (occupancyStatus) {
|
||||||
|
await this.occupancyService.updateOccupancySensorHistoricalData(
|
||||||
|
addDeviceStatusDto.deviceUuid,
|
||||||
|
);
|
||||||
|
await this.occupancyService.updateOccupancySensorHistoricalDurationData(
|
||||||
|
addDeviceStatusDto.deviceUuid,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (addDeviceStatusDto.productType === ProductType.AQI) {
|
||||||
|
await this.aqiDataService.updateAQISensorHistoricalData(
|
||||||
|
addDeviceStatusDto.deviceUuid,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
// Return the updated data
|
// Return the updated data
|
||||||
const snapshot: DataSnapshot = await get(dataRef);
|
const snapshot: DataSnapshot = await get(dataRef);
|
||||||
return snapshot.val();
|
return snapshot.val();
|
||||||
|
@ -8,10 +8,7 @@ import { TuyaWebSocketService } from './services/tuya.web.socket.service';
|
|||||||
import { OneSignalService } from './services/onesignal.service';
|
import { OneSignalService } from './services/onesignal.service';
|
||||||
import { DeviceMessagesService } from './services/device.messages.service';
|
import { DeviceMessagesService } from './services/device.messages.service';
|
||||||
import { DeviceRepositoryModule } from '../modules/device/device.repository.module';
|
import { DeviceRepositoryModule } from '../modules/device/device.repository.module';
|
||||||
import {
|
import { DeviceNotificationRepository } from '../modules/device/repositories';
|
||||||
DeviceNotificationRepository,
|
|
||||||
DeviceRepository,
|
|
||||||
} from '../modules/device/repositories';
|
|
||||||
import { DeviceStatusFirebaseModule } from '../firebase/devices-status/devices-status.module';
|
import { DeviceStatusFirebaseModule } from '../firebase/devices-status/devices-status.module';
|
||||||
import { CommunityPermissionService } from './services/community.permission.service';
|
import { CommunityPermissionService } from './services/community.permission.service';
|
||||||
import { CommunityRepository } from '../modules/community/repositories';
|
import { CommunityRepository } from '../modules/community/repositories';
|
||||||
@ -30,7 +27,6 @@ import { SosHandlerService } from './services/sos.handler.service';
|
|||||||
DeviceNotificationRepository,
|
DeviceNotificationRepository,
|
||||||
CommunityRepository,
|
CommunityRepository,
|
||||||
SosHandlerService,
|
SosHandlerService,
|
||||||
DeviceRepository,
|
|
||||||
],
|
],
|
||||||
exports: [
|
exports: [
|
||||||
HelperHashService,
|
HelperHashService,
|
||||||
|
@ -1,63 +1,44 @@
|
|||||||
|
import { DeviceRepository } from '@app/common/modules/device/repositories';
|
||||||
import { Injectable } from '@nestjs/common';
|
import { Injectable } from '@nestjs/common';
|
||||||
|
import { SqlLoaderService } from './sql-loader.service';
|
||||||
import { DataSource } from 'typeorm';
|
import { DataSource } from 'typeorm';
|
||||||
import { SQL_PROCEDURES_PATH } from '@app/common/constants/sql-query-path';
|
import { SQL_PROCEDURES_PATH } from '@app/common/constants/sql-query-path';
|
||||||
import { SqlLoaderService } from './sql-loader.service';
|
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class AqiDataService {
|
export class AqiDataService {
|
||||||
constructor(
|
constructor(
|
||||||
private readonly sqlLoader: SqlLoaderService,
|
private readonly sqlLoader: SqlLoaderService,
|
||||||
private readonly dataSource: DataSource,
|
private readonly dataSource: DataSource,
|
||||||
|
private readonly deviceRepository: DeviceRepository,
|
||||||
) {}
|
) {}
|
||||||
|
async updateAQISensorHistoricalData(deviceUuid: string): Promise<void> {
|
||||||
async updateAQISensorHistoricalData(): Promise<void> {
|
|
||||||
try {
|
try {
|
||||||
const { dateStr } = this.getFormattedDates();
|
const now = new Date();
|
||||||
|
const dateStr = now.toLocaleDateString('en-CA'); // YYYY-MM-DD
|
||||||
|
const device = await this.deviceRepository.findOne({
|
||||||
|
where: { uuid: deviceUuid },
|
||||||
|
relations: ['spaceDevice'],
|
||||||
|
});
|
||||||
|
|
||||||
// Execute all procedures in parallel
|
await this.executeProcedure(
|
||||||
await Promise.all([
|
'fact_daily_space_aqi',
|
||||||
this.executeProcedureWithRetry(
|
'proceduce_update_daily_space_aqi',
|
||||||
'proceduce_update_daily_space_aqi',
|
[dateStr, device.spaceDevice?.uuid],
|
||||||
[dateStr],
|
);
|
||||||
'fact_daily_space_aqi',
|
|
||||||
),
|
|
||||||
]);
|
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error('Failed to update AQI sensor historical data:', err);
|
console.error('Failed to insert or update aqi data:', err);
|
||||||
throw err;
|
throw err;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
private getFormattedDates(): { dateStr: string } {
|
|
||||||
const now = new Date();
|
private async executeProcedure(
|
||||||
return {
|
procedureFolderName: string,
|
||||||
dateStr: now.toLocaleDateString('en-CA'), // YYYY-MM-DD
|
|
||||||
};
|
|
||||||
}
|
|
||||||
private async executeProcedureWithRetry(
|
|
||||||
procedureFileName: string,
|
procedureFileName: string,
|
||||||
params: (string | number | null)[],
|
params: (string | number | null)[],
|
||||||
folderName: string,
|
|
||||||
retries = 3,
|
|
||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
try {
|
const query = this.loadQuery(procedureFolderName, procedureFileName);
|
||||||
const query = this.loadQuery(folderName, procedureFileName);
|
await this.dataSource.query(query, params);
|
||||||
await this.dataSource.query(query, params);
|
console.log(`Procedure ${procedureFileName} executed successfully.`);
|
||||||
console.log(`Procedure ${procedureFileName} executed successfully.`);
|
|
||||||
} catch (err) {
|
|
||||||
if (retries > 0) {
|
|
||||||
const delayMs = 1000 * (4 - retries); // Exponential backoff
|
|
||||||
console.warn(`Retrying ${procedureFileName} (${retries} retries left)`);
|
|
||||||
await new Promise((resolve) => setTimeout(resolve, delayMs));
|
|
||||||
return this.executeProcedureWithRetry(
|
|
||||||
procedureFileName,
|
|
||||||
params,
|
|
||||||
folderName,
|
|
||||||
retries - 1,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
console.error(`Failed to execute ${procedureFileName}:`, err);
|
|
||||||
throw err;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private loadQuery(folderName: string, fileName: string): string {
|
private loadQuery(folderName: string, fileName: string): string {
|
||||||
|
@ -1,69 +1,66 @@
|
|||||||
|
import { DeviceRepository } from '@app/common/modules/device/repositories';
|
||||||
import { Injectable } from '@nestjs/common';
|
import { Injectable } from '@nestjs/common';
|
||||||
|
import { SqlLoaderService } from './sql-loader.service';
|
||||||
import { DataSource } from 'typeorm';
|
import { DataSource } from 'typeorm';
|
||||||
import { SQL_PROCEDURES_PATH } from '@app/common/constants/sql-query-path';
|
import { SQL_PROCEDURES_PATH } from '@app/common/constants/sql-query-path';
|
||||||
import { SqlLoaderService } from './sql-loader.service';
|
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class OccupancyService {
|
export class OccupancyService {
|
||||||
constructor(
|
constructor(
|
||||||
private readonly sqlLoader: SqlLoaderService,
|
private readonly sqlLoader: SqlLoaderService,
|
||||||
private readonly dataSource: DataSource,
|
private readonly dataSource: DataSource,
|
||||||
|
private readonly deviceRepository: DeviceRepository,
|
||||||
) {}
|
) {}
|
||||||
|
async updateOccupancySensorHistoricalDurationData(
|
||||||
async updateOccupancyDataProcedures(): Promise<void> {
|
deviceUuid: string,
|
||||||
try {
|
|
||||||
const { dateStr } = this.getFormattedDates();
|
|
||||||
|
|
||||||
// Execute all procedures in parallel
|
|
||||||
await Promise.all([
|
|
||||||
this.executeProcedureWithRetry(
|
|
||||||
'procedure_update_fact_space_occupancy',
|
|
||||||
[dateStr],
|
|
||||||
'fact_space_occupancy_count',
|
|
||||||
),
|
|
||||||
this.executeProcedureWithRetry(
|
|
||||||
'procedure_update_daily_space_occupancy_duration',
|
|
||||||
[dateStr],
|
|
||||||
'fact_daily_space_occupancy_duration',
|
|
||||||
),
|
|
||||||
]);
|
|
||||||
} catch (err) {
|
|
||||||
console.error('Failed to update occupancy data:', err);
|
|
||||||
throw err;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
private getFormattedDates(): { dateStr: string } {
|
|
||||||
const now = new Date();
|
|
||||||
return {
|
|
||||||
dateStr: now.toLocaleDateString('en-CA'), // YYYY-MM-DD
|
|
||||||
};
|
|
||||||
}
|
|
||||||
private async executeProcedureWithRetry(
|
|
||||||
procedureFileName: string,
|
|
||||||
params: (string | number | null)[],
|
|
||||||
folderName: string,
|
|
||||||
retries = 3,
|
|
||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
try {
|
try {
|
||||||
const query = this.loadQuery(folderName, procedureFileName);
|
const now = new Date();
|
||||||
await this.dataSource.query(query, params);
|
const dateStr = now.toLocaleDateString('en-CA'); // YYYY-MM-DD
|
||||||
console.log(`Procedure ${procedureFileName} executed successfully.`);
|
const device = await this.deviceRepository.findOne({
|
||||||
|
where: { uuid: deviceUuid },
|
||||||
|
relations: ['spaceDevice'],
|
||||||
|
});
|
||||||
|
|
||||||
|
await this.executeProcedure(
|
||||||
|
'fact_daily_space_occupancy_duration',
|
||||||
|
'procedure_update_daily_space_occupancy_duration',
|
||||||
|
[dateStr, device.spaceDevice?.uuid],
|
||||||
|
);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
if (retries > 0) {
|
console.error('Failed to insert or update occupancy duration data:', err);
|
||||||
const delayMs = 1000 * (4 - retries); // Exponential backoff
|
|
||||||
console.warn(`Retrying ${procedureFileName} (${retries} retries left)`);
|
|
||||||
await new Promise((resolve) => setTimeout(resolve, delayMs));
|
|
||||||
return this.executeProcedureWithRetry(
|
|
||||||
procedureFileName,
|
|
||||||
params,
|
|
||||||
folderName,
|
|
||||||
retries - 1,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
console.error(`Failed to execute ${procedureFileName}:`, err);
|
|
||||||
throw err;
|
throw err;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
async updateOccupancySensorHistoricalData(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_space_occupancy_count',
|
||||||
|
'procedure_update_fact_space_occupancy',
|
||||||
|
[dateStr, device.spaceDevice?.uuid],
|
||||||
|
);
|
||||||
|
} catch (err) {
|
||||||
|
console.error('Failed to insert or update occupancy 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 {
|
private loadQuery(folderName: string, fileName: string): string {
|
||||||
return this.sqlLoader.loadQuery(folderName, fileName, SQL_PROCEDURES_PATH);
|
return this.sqlLoader.loadQuery(folderName, fileName, SQL_PROCEDURES_PATH);
|
||||||
|
@ -1,7 +1,7 @@
|
|||||||
import { Injectable } from '@nestjs/common';
|
import { Injectable } from '@nestjs/common';
|
||||||
|
import { SqlLoaderService } from './sql-loader.service';
|
||||||
import { DataSource } from 'typeorm';
|
import { DataSource } from 'typeorm';
|
||||||
import { SQL_PROCEDURES_PATH } from '@app/common/constants/sql-query-path';
|
import { SQL_PROCEDURES_PATH } from '@app/common/constants/sql-query-path';
|
||||||
import { SqlLoaderService } from './sql-loader.service';
|
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class PowerClampService {
|
export class PowerClampService {
|
||||||
@ -10,74 +10,50 @@ export class PowerClampService {
|
|||||||
private readonly dataSource: DataSource,
|
private readonly dataSource: DataSource,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
async updateEnergyConsumedHistoricalData(): Promise<void> {
|
async updateEnergyConsumedHistoricalData(deviceUuid: string): Promise<void> {
|
||||||
try {
|
try {
|
||||||
const { dateStr, monthYear } = this.getFormattedDates();
|
const now = new Date();
|
||||||
|
const dateStr = now.toLocaleDateString('en-CA'); // YYYY-MM-DD
|
||||||
// Execute all procedures in parallel
|
const hour = now.getHours();
|
||||||
await Promise.all([
|
const monthYear = now
|
||||||
this.executeProcedureWithRetry(
|
|
||||||
'fact_hourly_device_energy_consumed_procedure',
|
|
||||||
[dateStr],
|
|
||||||
'fact_device_energy_consumed',
|
|
||||||
),
|
|
||||||
this.executeProcedureWithRetry(
|
|
||||||
'fact_daily_device_energy_consumed_procedure',
|
|
||||||
[dateStr],
|
|
||||||
'fact_device_energy_consumed',
|
|
||||||
),
|
|
||||||
this.executeProcedureWithRetry(
|
|
||||||
'fact_monthly_device_energy_consumed_procedure',
|
|
||||||
[monthYear],
|
|
||||||
'fact_device_energy_consumed',
|
|
||||||
),
|
|
||||||
]);
|
|
||||||
} catch (err) {
|
|
||||||
console.error('Failed to update energy consumption data:', err);
|
|
||||||
throw err;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private getFormattedDates(): { dateStr: string; monthYear: string } {
|
|
||||||
const now = new Date();
|
|
||||||
return {
|
|
||||||
dateStr: now.toLocaleDateString('en-CA'), // YYYY-MM-DD
|
|
||||||
monthYear: now
|
|
||||||
.toLocaleDateString('en-US', {
|
.toLocaleDateString('en-US', {
|
||||||
month: '2-digit',
|
month: '2-digit',
|
||||||
year: 'numeric',
|
year: 'numeric',
|
||||||
})
|
})
|
||||||
.replace('/', '-'), // MM-YYYY
|
.replace('/', '-'); // MM-YYYY
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
private async executeProcedureWithRetry(
|
await this.executeProcedure(
|
||||||
procedureFileName: string,
|
'fact_hourly_device_energy_consumed_procedure',
|
||||||
params: (string | number | null)[],
|
[deviceUuid, dateStr, hour],
|
||||||
folderName: string,
|
);
|
||||||
retries = 3,
|
|
||||||
): Promise<void> {
|
await this.executeProcedure(
|
||||||
try {
|
'fact_daily_device_energy_consumed_procedure',
|
||||||
const query = this.loadQuery(folderName, procedureFileName);
|
[deviceUuid, dateStr],
|
||||||
await this.dataSource.query(query, params);
|
);
|
||||||
console.log(`Procedure ${procedureFileName} executed successfully.`);
|
|
||||||
|
await this.executeProcedure(
|
||||||
|
'fact_monthly_device_energy_consumed_procedure',
|
||||||
|
[deviceUuid, monthYear],
|
||||||
|
);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
if (retries > 0) {
|
console.error('Failed to insert or update energy data:', err);
|
||||||
const delayMs = 1000 * (4 - retries); // Exponential backoff
|
|
||||||
console.warn(`Retrying ${procedureFileName} (${retries} retries left)`);
|
|
||||||
await new Promise((resolve) => setTimeout(resolve, delayMs));
|
|
||||||
return this.executeProcedureWithRetry(
|
|
||||||
procedureFileName,
|
|
||||||
params,
|
|
||||||
folderName,
|
|
||||||
retries - 1,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
console.error(`Failed to execute ${procedureFileName}:`, err);
|
|
||||||
throw err;
|
throw err;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private async executeProcedure(
|
||||||
|
procedureFileName: string,
|
||||||
|
params: (string | number | null)[],
|
||||||
|
): Promise<void> {
|
||||||
|
const query = this.loadQuery(
|
||||||
|
'fact_device_energy_consumed',
|
||||||
|
procedureFileName,
|
||||||
|
);
|
||||||
|
await this.dataSource.query(query, params);
|
||||||
|
console.log(`Procedure ${procedureFileName} executed successfully.`);
|
||||||
|
}
|
||||||
|
|
||||||
private loadQuery(folderName: string, fileName: string): string {
|
private loadQuery(folderName: string, fileName: string): string {
|
||||||
return this.sqlLoader.loadQuery(folderName, fileName, SQL_PROCEDURES_PATH);
|
return this.sqlLoader.loadQuery(folderName, fileName, SQL_PROCEDURES_PATH);
|
||||||
}
|
}
|
||||||
|
@ -16,46 +16,21 @@ export class SosHandlerService {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
async handleSosEventFirebase(device: any, logData: any): Promise<void> {
|
async handleSosEvent(devId: string, logData: any): Promise<void> {
|
||||||
const sosTrueStatus = [{ code: 'sos', value: true }];
|
|
||||||
const sosFalseStatus = [{ code: 'sos', value: false }];
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// ✅ Send true status
|
|
||||||
await this.deviceStatusFirebaseService.addDeviceStatusToFirebase({
|
await this.deviceStatusFirebaseService.addDeviceStatusToFirebase({
|
||||||
deviceTuyaUuid: device.deviceTuyaUuid,
|
deviceTuyaUuid: devId,
|
||||||
status: sosTrueStatus,
|
status: [{ code: 'sos', value: true }],
|
||||||
log: logData,
|
log: logData,
|
||||||
device,
|
|
||||||
});
|
});
|
||||||
|
|
||||||
await this.deviceStatusFirebaseService.addBatchDeviceStatusToOurDb([
|
|
||||||
{
|
|
||||||
deviceTuyaUuid: device.deviceTuyaUuid,
|
|
||||||
status: sosTrueStatus,
|
|
||||||
log: logData,
|
|
||||||
device,
|
|
||||||
},
|
|
||||||
]);
|
|
||||||
|
|
||||||
// ✅ Schedule false status
|
|
||||||
setTimeout(async () => {
|
setTimeout(async () => {
|
||||||
try {
|
try {
|
||||||
await this.deviceStatusFirebaseService.addDeviceStatusToFirebase({
|
await this.deviceStatusFirebaseService.addDeviceStatusToFirebase({
|
||||||
deviceTuyaUuid: device.deviceTuyaUuid,
|
deviceTuyaUuid: devId,
|
||||||
status: sosFalseStatus,
|
status: [{ code: 'sos', value: false }],
|
||||||
log: logData,
|
log: logData,
|
||||||
device,
|
|
||||||
});
|
});
|
||||||
|
|
||||||
await this.deviceStatusFirebaseService.addBatchDeviceStatusToOurDb([
|
|
||||||
{
|
|
||||||
deviceTuyaUuid: device.deviceTuyaUuid,
|
|
||||||
status: sosFalseStatus,
|
|
||||||
log: logData,
|
|
||||||
device,
|
|
||||||
},
|
|
||||||
]);
|
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
this.logger.error('Failed to send SOS false value', err);
|
this.logger.error('Failed to send SOS false value', err);
|
||||||
}
|
}
|
||||||
|
@ -1,24 +1,13 @@
|
|||||||
import { Injectable, OnModuleInit } from '@nestjs/common';
|
import { Injectable } from '@nestjs/common';
|
||||||
import TuyaWebsocket from '../../config/tuya-web-socket-config';
|
import TuyaWebsocket from '../../config/tuya-web-socket-config';
|
||||||
import { ConfigService } from '@nestjs/config';
|
import { ConfigService } from '@nestjs/config';
|
||||||
import { DeviceStatusFirebaseService } from '@app/common/firebase/devices-status/services/devices-status.service';
|
import { DeviceStatusFirebaseService } from '@app/common/firebase/devices-status/services/devices-status.service';
|
||||||
import { SosHandlerService } from './sos.handler.service';
|
import { SosHandlerService } from './sos.handler.service';
|
||||||
import * as NodeCache from 'node-cache';
|
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class TuyaWebSocketService implements OnModuleInit {
|
export class TuyaWebSocketService {
|
||||||
private client: any;
|
private client: any;
|
||||||
private readonly isDevEnv: boolean;
|
private readonly isDevEnv: boolean;
|
||||||
private readonly deviceCache = new NodeCache({ stdTTL: 7200 }); // TTL = 2 hour
|
|
||||||
|
|
||||||
private messageQueue: {
|
|
||||||
devId: string;
|
|
||||||
status: any;
|
|
||||||
logData: any;
|
|
||||||
device: any;
|
|
||||||
}[] = [];
|
|
||||||
|
|
||||||
private isProcessing = false;
|
|
||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
private readonly configService: ConfigService,
|
private readonly configService: ConfigService,
|
||||||
@ -37,36 +26,16 @@ export class TuyaWebSocketService implements OnModuleInit {
|
|||||||
});
|
});
|
||||||
|
|
||||||
if (this.configService.get<string>('tuya-config.TRUN_ON_TUYA_SOCKET')) {
|
if (this.configService.get<string>('tuya-config.TRUN_ON_TUYA_SOCKET')) {
|
||||||
|
// Set up event handlers
|
||||||
this.setupEventHandlers();
|
this.setupEventHandlers();
|
||||||
|
|
||||||
|
// Start receiving messages
|
||||||
this.client.start();
|
this.client.start();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Run the queue processor every 15 seconds
|
|
||||||
setInterval(() => this.processQueue(), 15000);
|
|
||||||
|
|
||||||
// Refresh the cache every 1 hour
|
|
||||||
setInterval(() => this.initializeDeviceCache(), 30 * 60 * 1000); // 30 minutes
|
|
||||||
}
|
|
||||||
|
|
||||||
async onModuleInit() {
|
|
||||||
await this.initializeDeviceCache();
|
|
||||||
}
|
|
||||||
|
|
||||||
private async initializeDeviceCache() {
|
|
||||||
try {
|
|
||||||
const allDevices = await this.deviceStatusFirebaseService.getAllDevices();
|
|
||||||
allDevices.forEach((device) => {
|
|
||||||
if (device.deviceTuyaUuid) {
|
|
||||||
this.deviceCache.set(device.deviceTuyaUuid, device);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
console.log(`✅ Refreshed cache with ${allDevices.length} devices.`);
|
|
||||||
} catch (error) {
|
|
||||||
console.error('❌ Failed to initialize device cache:', error);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private setupEventHandlers() {
|
private setupEventHandlers() {
|
||||||
|
// Event handlers
|
||||||
this.client.open(() => {
|
this.client.open(() => {
|
||||||
console.log('open');
|
console.log('open');
|
||||||
});
|
});
|
||||||
@ -74,38 +43,23 @@ export class TuyaWebSocketService implements OnModuleInit {
|
|||||||
this.client.message(async (ws: WebSocket, message: any) => {
|
this.client.message(async (ws: WebSocket, message: any) => {
|
||||||
try {
|
try {
|
||||||
const { devId, status, logData } = this.extractMessageData(message);
|
const { devId, status, logData } = this.extractMessageData(message);
|
||||||
if (!Array.isArray(logData?.properties)) {
|
|
||||||
this.client.ackMessage(message.messageId);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const device = this.deviceCache.get(devId);
|
|
||||||
if (!device) {
|
|
||||||
// console.log(⛔ Unknown device: ${devId}, message ignored.);
|
|
||||||
this.client.ackMessage(message.messageId);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (this.sosHandlerService.isSosTriggered(status)) {
|
if (this.sosHandlerService.isSosTriggered(status)) {
|
||||||
await this.sosHandlerService.handleSosEventFirebase(devId, logData);
|
await this.sosHandlerService.handleSosEvent(devId, logData);
|
||||||
} else {
|
} else {
|
||||||
await this.deviceStatusFirebaseService.addDeviceStatusToFirebase({
|
await this.deviceStatusFirebaseService.addDeviceStatusToFirebase({
|
||||||
deviceTuyaUuid: devId,
|
deviceTuyaUuid: devId,
|
||||||
status,
|
status: status,
|
||||||
log: logData,
|
log: logData,
|
||||||
device,
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// Push to internal queue
|
|
||||||
this.messageQueue.push({ devId, status, logData, device });
|
|
||||||
|
|
||||||
// Acknowledge the message
|
|
||||||
this.client.ackMessage(message.messageId);
|
this.client.ackMessage(message.messageId);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('❌ Error receiving message:', error);
|
console.error('Error processing message:', error);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
this.client.reconnect(() => {
|
this.client.reconnect(() => {
|
||||||
console.log('reconnect');
|
console.log('reconnect');
|
||||||
});
|
});
|
||||||
@ -126,37 +80,6 @@ export class TuyaWebSocketService implements OnModuleInit {
|
|||||||
console.error('WebSocket error:', error);
|
console.error('WebSocket error:', error);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
private async processQueue() {
|
|
||||||
if (this.isProcessing) {
|
|
||||||
console.log('⏳ Skipping: still processing previous batch');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (this.messageQueue.length === 0) return;
|
|
||||||
|
|
||||||
this.isProcessing = true;
|
|
||||||
const batch = [...this.messageQueue];
|
|
||||||
this.messageQueue = [];
|
|
||||||
|
|
||||||
console.log(`🔁 Processing batch of size: ${batch.length}`);
|
|
||||||
|
|
||||||
try {
|
|
||||||
await this.deviceStatusFirebaseService.addBatchDeviceStatusToOurDb(
|
|
||||||
batch.map((item) => ({
|
|
||||||
deviceTuyaUuid: item.devId,
|
|
||||||
status: item.status,
|
|
||||||
log: item.logData,
|
|
||||||
device: item.device,
|
|
||||||
})),
|
|
||||||
);
|
|
||||||
} catch (error) {
|
|
||||||
console.error('❌ Error processing batch:', error);
|
|
||||||
this.messageQueue.unshift(...batch); // retry
|
|
||||||
} finally {
|
|
||||||
this.isProcessing = false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private extractMessageData(message: any): {
|
private extractMessageData(message: any): {
|
||||||
devId: string;
|
devId: string;
|
||||||
status: any;
|
status: any;
|
||||||
|
@ -1,5 +0,0 @@
|
|||||||
// Convert time string (HH:mm) to minutes
|
|
||||||
export function timeToMinutes(time: string): number {
|
|
||||||
const [hours, minutes] = time.split(':').map(Number);
|
|
||||||
return hours * 60 + minutes;
|
|
||||||
}
|
|
@ -49,12 +49,12 @@ export class TuyaService {
|
|||||||
path,
|
path,
|
||||||
});
|
});
|
||||||
|
|
||||||
// if (!response.success) {
|
if (!response.success) {
|
||||||
// throw new HttpException(
|
throw new HttpException(
|
||||||
// `Error fetching device details: ${response.msg}`,
|
`Error fetching device details: ${response.msg}`,
|
||||||
// HttpStatus.BAD_REQUEST,
|
HttpStatus.BAD_REQUEST,
|
||||||
// );
|
);
|
||||||
// }
|
}
|
||||||
|
|
||||||
return response.result;
|
return response.result;
|
||||||
}
|
}
|
||||||
|
@ -1,6 +1,6 @@
|
|||||||
import { RoleType } from '@app/common/constants/role.type.enum';
|
import { RoleType } from '@app/common/constants/role.type.enum';
|
||||||
import { UserStatusEnum } from '@app/common/constants/user-status.enum';
|
import { UserStatusEnum } from '@app/common/constants/user-status.enum';
|
||||||
import { IsEnum, IsNotEmpty, IsOptional, IsString } from 'class-validator';
|
import { IsEnum, IsNotEmpty, IsString } from 'class-validator';
|
||||||
|
|
||||||
export class InviteUserDto {
|
export class InviteUserDto {
|
||||||
@IsString()
|
@IsString()
|
||||||
@ -12,12 +12,8 @@ export class InviteUserDto {
|
|||||||
public email: string;
|
public email: string;
|
||||||
|
|
||||||
@IsString()
|
@IsString()
|
||||||
@IsOptional()
|
@IsNotEmpty()
|
||||||
public jobTitle?: string;
|
public jobTitle: string;
|
||||||
|
|
||||||
@IsString()
|
|
||||||
@IsOptional()
|
|
||||||
public companyName?: string;
|
|
||||||
|
|
||||||
@IsEnum(UserStatusEnum)
|
@IsEnum(UserStatusEnum)
|
||||||
@IsNotEmpty()
|
@IsNotEmpty()
|
||||||
|
@ -37,11 +37,6 @@ export class InviteUserEntity extends AbstractEntity<InviteUserDto> {
|
|||||||
})
|
})
|
||||||
jobTitle: string;
|
jobTitle: string;
|
||||||
|
|
||||||
@Column({
|
|
||||||
nullable: true,
|
|
||||||
})
|
|
||||||
companyName: string;
|
|
||||||
|
|
||||||
@Column({
|
@Column({
|
||||||
nullable: false,
|
nullable: false,
|
||||||
enum: Object.values(UserStatusEnum),
|
enum: Object.values(UserStatusEnum),
|
||||||
|
@ -1,11 +0,0 @@
|
|||||||
import { Module } from '@nestjs/common';
|
|
||||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
|
||||||
import { BookableSpaceEntity } from './entities/bookable-space.entity';
|
|
||||||
|
|
||||||
@Module({
|
|
||||||
providers: [],
|
|
||||||
exports: [],
|
|
||||||
controllers: [],
|
|
||||||
imports: [TypeOrmModule.forFeature([BookableSpaceEntity])],
|
|
||||||
})
|
|
||||||
export class BookableRepositoryModule {}
|
|
@ -1,51 +0,0 @@
|
|||||||
import { DaysEnum } from '@app/common/constants/days.enum';
|
|
||||||
import {
|
|
||||||
Column,
|
|
||||||
CreateDateColumn,
|
|
||||||
Entity,
|
|
||||||
JoinColumn,
|
|
||||||
OneToOne,
|
|
||||||
UpdateDateColumn,
|
|
||||||
} from 'typeorm';
|
|
||||||
import { AbstractEntity } from '../../abstract/entities/abstract.entity';
|
|
||||||
import { SpaceEntity } from '../../space/entities/space.entity';
|
|
||||||
|
|
||||||
@Entity('bookable-space')
|
|
||||||
export class BookableSpaceEntity extends AbstractEntity {
|
|
||||||
@Column({
|
|
||||||
type: 'uuid',
|
|
||||||
default: () => 'gen_random_uuid()',
|
|
||||||
nullable: false,
|
|
||||||
})
|
|
||||||
public uuid: string;
|
|
||||||
|
|
||||||
@OneToOne(() => SpaceEntity, (space) => space.bookableConfig)
|
|
||||||
@JoinColumn({ name: 'space_uuid' })
|
|
||||||
space: SpaceEntity;
|
|
||||||
|
|
||||||
@Column({
|
|
||||||
type: 'enum',
|
|
||||||
enum: DaysEnum,
|
|
||||||
array: true,
|
|
||||||
nullable: false,
|
|
||||||
})
|
|
||||||
daysAvailable: DaysEnum[];
|
|
||||||
|
|
||||||
@Column({ type: 'time' })
|
|
||||||
startTime: string;
|
|
||||||
|
|
||||||
@Column({ type: 'time' })
|
|
||||||
endTime: string;
|
|
||||||
|
|
||||||
@Column({ type: Boolean, default: true })
|
|
||||||
active: boolean;
|
|
||||||
|
|
||||||
@Column({ type: 'int', default: null })
|
|
||||||
points?: number;
|
|
||||||
|
|
||||||
@CreateDateColumn()
|
|
||||||
createdAt: Date;
|
|
||||||
|
|
||||||
@UpdateDateColumn()
|
|
||||||
updatedAt: Date;
|
|
||||||
}
|
|
@ -1 +0,0 @@
|
|||||||
export * from './bookable-space.entity';
|
|
@ -1,10 +0,0 @@
|
|||||||
import { DataSource, Repository } from 'typeorm';
|
|
||||||
import { Injectable } from '@nestjs/common';
|
|
||||||
import { BookableSpaceEntity } from '../entities/bookable-space.entity';
|
|
||||||
|
|
||||||
@Injectable()
|
|
||||||
export class BookableSpaceEntityRepository extends Repository<BookableSpaceEntity> {
|
|
||||||
constructor(private dataSource: DataSource) {
|
|
||||||
super(BookableSpaceEntity, dataSource.createEntityManager());
|
|
||||||
}
|
|
||||||
}
|
|
@ -1 +0,0 @@
|
|||||||
export * from './booking.repository';
|
|
@ -28,11 +28,6 @@ export class DeviceEntity extends AbstractEntity<DeviceDto> {
|
|||||||
})
|
})
|
||||||
deviceTuyaUuid: string;
|
deviceTuyaUuid: string;
|
||||||
|
|
||||||
@Column({
|
|
||||||
nullable: true,
|
|
||||||
})
|
|
||||||
deviceTuyaConstUuid: string;
|
|
||||||
|
|
||||||
@Column({
|
@Column({
|
||||||
nullable: true,
|
nullable: true,
|
||||||
default: true,
|
default: true,
|
||||||
|
32
libs/common/src/modules/space/entities/space-link.entity.ts
Normal file
32
libs/common/src/modules/space/entities/space-link.entity.ts
Normal file
@ -0,0 +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';
|
||||||
|
|
||||||
|
@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,25 +1,18 @@
|
|||||||
import {
|
import { Column, Entity, JoinColumn, ManyToOne, OneToMany } from 'typeorm';
|
||||||
Column,
|
import { SpaceDto } from '../dtos';
|
||||||
Entity,
|
|
||||||
JoinColumn,
|
|
||||||
ManyToOne,
|
|
||||||
OneToMany,
|
|
||||||
OneToOne,
|
|
||||||
} from 'typeorm';
|
|
||||||
import { AbstractEntity } from '../../abstract/entities/abstract.entity';
|
import { AbstractEntity } from '../../abstract/entities/abstract.entity';
|
||||||
import { AqiSpaceDailyPollutantStatsEntity } from '../../aqi/entities';
|
import { UserSpaceEntity } from '../../user/entities';
|
||||||
import { BookableSpaceEntity } from '../../booking/entities';
|
|
||||||
import { CommunityEntity } from '../../community/entities';
|
|
||||||
import { DeviceEntity } from '../../device/entities';
|
import { DeviceEntity } from '../../device/entities';
|
||||||
import { InviteUserSpaceEntity } from '../../Invite-user/entities';
|
import { CommunityEntity } from '../../community/entities';
|
||||||
import { SpaceDailyOccupancyDurationEntity } from '../../occupancy/entities';
|
import { SpaceLinkEntity } from './space-link.entity';
|
||||||
import { PresenceSensorDailySpaceEntity } from '../../presence-sensor/entities';
|
|
||||||
import { SceneEntity } from '../../scene/entities';
|
import { SceneEntity } from '../../scene/entities';
|
||||||
import { SpaceModelEntity } from '../../space-model';
|
import { SpaceModelEntity } from '../../space-model';
|
||||||
import { UserSpaceEntity } from '../../user/entities';
|
import { InviteUserSpaceEntity } from '../../Invite-user/entities';
|
||||||
import { SpaceDto } from '../dtos';
|
|
||||||
import { SpaceProductAllocationEntity } from './space-product-allocation.entity';
|
import { SpaceProductAllocationEntity } from './space-product-allocation.entity';
|
||||||
import { SubspaceEntity } from './subspace/subspace.entity';
|
import { SubspaceEntity } from './subspace/subspace.entity';
|
||||||
|
import { PresenceSensorDailySpaceEntity } from '../../presence-sensor/entities';
|
||||||
|
import { AqiSpaceDailyPollutantStatsEntity } from '../../aqi/entities';
|
||||||
|
import { SpaceDailyOccupancyDurationEntity } from '../../occupancy/entities';
|
||||||
|
|
||||||
@Entity({ name: 'space' })
|
@Entity({ name: 'space' })
|
||||||
export class SpaceEntity extends AbstractEntity<SpaceDto> {
|
export class SpaceEntity extends AbstractEntity<SpaceDto> {
|
||||||
@ -64,12 +57,6 @@ export class SpaceEntity extends AbstractEntity<SpaceDto> {
|
|||||||
})
|
})
|
||||||
public disabled: boolean;
|
public disabled: boolean;
|
||||||
|
|
||||||
@Column({
|
|
||||||
nullable: true,
|
|
||||||
type: Number,
|
|
||||||
})
|
|
||||||
public order?: number;
|
|
||||||
|
|
||||||
@OneToMany(() => SubspaceEntity, (subspace) => subspace.space, {
|
@OneToMany(() => SubspaceEntity, (subspace) => subspace.space, {
|
||||||
nullable: true,
|
nullable: true,
|
||||||
})
|
})
|
||||||
@ -88,6 +75,16 @@ export class SpaceEntity extends AbstractEntity<SpaceDto> {
|
|||||||
)
|
)
|
||||||
devices: DeviceEntity[];
|
devices: DeviceEntity[];
|
||||||
|
|
||||||
|
@OneToMany(() => SpaceLinkEntity, (connection) => connection.startSpace, {
|
||||||
|
nullable: true,
|
||||||
|
})
|
||||||
|
public outgoingConnections: SpaceLinkEntity[];
|
||||||
|
|
||||||
|
@OneToMany(() => SpaceLinkEntity, (connection) => connection.endSpace, {
|
||||||
|
nullable: true,
|
||||||
|
})
|
||||||
|
public incomingConnections: SpaceLinkEntity[];
|
||||||
|
|
||||||
@Column({
|
@Column({
|
||||||
nullable: true,
|
nullable: true,
|
||||||
type: 'text',
|
type: 'text',
|
||||||
@ -129,9 +126,6 @@ export class SpaceEntity extends AbstractEntity<SpaceDto> {
|
|||||||
)
|
)
|
||||||
occupancyDaily: SpaceDailyOccupancyDurationEntity[];
|
occupancyDaily: SpaceDailyOccupancyDurationEntity[];
|
||||||
|
|
||||||
@OneToOne(() => BookableSpaceEntity, (bookable) => bookable.space)
|
|
||||||
bookableConfig: BookableSpaceEntity;
|
|
||||||
|
|
||||||
constructor(partial: Partial<SpaceEntity>) {
|
constructor(partial: Partial<SpaceEntity>) {
|
||||||
super();
|
super();
|
||||||
Object.assign(this, partial);
|
Object.assign(this, partial);
|
||||||
|
@ -1,6 +1,7 @@
|
|||||||
import { Injectable } from '@nestjs/common';
|
import { Injectable } from '@nestjs/common';
|
||||||
import { DataSource, Repository } from 'typeorm';
|
import { DataSource, Repository } from 'typeorm';
|
||||||
import { InviteSpaceEntity } from '../entities/invite-space.entity';
|
import { InviteSpaceEntity } from '../entities/invite-space.entity';
|
||||||
|
import { SpaceLinkEntity } from '../entities/space-link.entity';
|
||||||
import { SpaceProductAllocationEntity } from '../entities/space-product-allocation.entity';
|
import { SpaceProductAllocationEntity } from '../entities/space-product-allocation.entity';
|
||||||
import { SpaceEntity } from '../entities/space.entity';
|
import { SpaceEntity } from '../entities/space.entity';
|
||||||
|
|
||||||
@ -11,6 +12,13 @@ export class SpaceRepository extends Repository<SpaceEntity> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class SpaceLinkRepository extends Repository<SpaceLinkEntity> {
|
||||||
|
constructor(private dataSource: DataSource) {
|
||||||
|
super(SpaceLinkEntity, dataSource.createEntityManager());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class InviteSpaceRepository extends Repository<InviteSpaceEntity> {
|
export class InviteSpaceRepository extends Repository<InviteSpaceEntity> {
|
||||||
constructor(private dataSource: DataSource) {
|
constructor(private dataSource: DataSource) {
|
||||||
|
@ -82,12 +82,6 @@ export class UserEntity extends AbstractEntity<UserDto> {
|
|||||||
})
|
})
|
||||||
public isActive: boolean;
|
public isActive: boolean;
|
||||||
|
|
||||||
@Column({
|
|
||||||
nullable: true,
|
|
||||||
type: Number,
|
|
||||||
})
|
|
||||||
public bookingPoints?: number;
|
|
||||||
|
|
||||||
@Column({ default: false })
|
@Column({ default: false })
|
||||||
hasAcceptedWebAgreement: boolean;
|
hasAcceptedWebAgreement: boolean;
|
||||||
|
|
||||||
|
@ -1,6 +1,7 @@
|
|||||||
WITH params AS (
|
WITH params AS (
|
||||||
SELECT
|
SELECT
|
||||||
TO_DATE(NULLIF($1, ''), 'YYYY-MM-DD') AS event_date
|
TO_DATE(NULLIF($1, ''), 'YYYY-MM-DD') AS event_date,
|
||||||
|
$2::uuid AS space_id
|
||||||
),
|
),
|
||||||
|
|
||||||
-- Query Pipeline Starts Here
|
-- Query Pipeline Starts Here
|
||||||
@ -276,10 +277,7 @@ SELECT
|
|||||||
a.daily_avg_ch2o,a.daily_max_ch2o, a.daily_min_ch2o
|
a.daily_avg_ch2o,a.daily_max_ch2o, a.daily_min_ch2o
|
||||||
FROM daily_percentages p
|
FROM daily_percentages p
|
||||||
LEFT JOIN daily_averages a
|
LEFT JOIN daily_averages a
|
||||||
ON p.space_id = a.space_id
|
ON p.space_id = a.space_id AND p.event_date = a.event_date
|
||||||
AND p.event_date = a.event_date
|
|
||||||
JOIN params
|
|
||||||
ON params.event_date = a.event_date
|
|
||||||
ORDER BY p.space_id, p.event_date)
|
ORDER BY p.space_id, p.event_date)
|
||||||
|
|
||||||
|
|
||||||
|
@ -1,6 +1,7 @@
|
|||||||
WITH params AS (
|
WITH params AS (
|
||||||
SELECT
|
SELECT
|
||||||
TO_DATE(NULLIF($1, ''), 'YYYY-MM-DD') AS event_date
|
TO_DATE(NULLIF($1, ''), 'YYYY-MM-DD') AS event_date,
|
||||||
|
$2::uuid AS space_id
|
||||||
),
|
),
|
||||||
|
|
||||||
presence_logs AS (
|
presence_logs AS (
|
||||||
@ -85,7 +86,8 @@ final_data AS (
|
|||||||
ROUND(LEAST(raw_occupied_seconds, 86400) / 86400.0 * 100, 2) AS occupancy_percentage
|
ROUND(LEAST(raw_occupied_seconds, 86400) / 86400.0 * 100, 2) AS occupancy_percentage
|
||||||
FROM summed_intervals s
|
FROM summed_intervals s
|
||||||
JOIN params p
|
JOIN params p
|
||||||
ON p.event_date = s.event_date
|
ON p.space_id = s.space_id
|
||||||
|
AND p.event_date = s.event_date
|
||||||
)
|
)
|
||||||
|
|
||||||
INSERT INTO public."space-daily-occupancy-duration" (
|
INSERT INTO public."space-daily-occupancy-duration" (
|
||||||
|
@ -1,6 +1,7 @@
|
|||||||
WITH params AS (
|
WITH params AS (
|
||||||
SELECT
|
SELECT
|
||||||
$1::date AS target_date
|
$1::uuid AS device_id,
|
||||||
|
$2::date AS target_date
|
||||||
),
|
),
|
||||||
total_energy AS (
|
total_energy AS (
|
||||||
SELECT
|
SELECT
|
||||||
@ -13,7 +14,8 @@ total_energy AS (
|
|||||||
MAX(log.value)::integer AS max_value
|
MAX(log.value)::integer AS max_value
|
||||||
FROM "device-status-log" log, params
|
FROM "device-status-log" log, params
|
||||||
WHERE log.code = 'EnergyConsumed'
|
WHERE log.code = 'EnergyConsumed'
|
||||||
AND log.event_time::date = params.target_date
|
AND log.device_id = params.device_id
|
||||||
|
AND log.event_time::date = params.target_date
|
||||||
GROUP BY 1,2,3,4,5
|
GROUP BY 1,2,3,4,5
|
||||||
),
|
),
|
||||||
energy_phase_A AS (
|
energy_phase_A AS (
|
||||||
@ -27,7 +29,8 @@ energy_phase_A AS (
|
|||||||
MAX(log.value)::integer AS max_value
|
MAX(log.value)::integer AS max_value
|
||||||
FROM "device-status-log" log, params
|
FROM "device-status-log" log, params
|
||||||
WHERE log.code = 'EnergyConsumedA'
|
WHERE log.code = 'EnergyConsumedA'
|
||||||
AND log.event_time::date = params.target_date
|
AND log.device_id = params.device_id
|
||||||
|
AND log.event_time::date = params.target_date
|
||||||
GROUP BY 1,2,3,4,5
|
GROUP BY 1,2,3,4,5
|
||||||
),
|
),
|
||||||
energy_phase_B AS (
|
energy_phase_B AS (
|
||||||
@ -41,7 +44,8 @@ energy_phase_B AS (
|
|||||||
MAX(log.value)::integer AS max_value
|
MAX(log.value)::integer AS max_value
|
||||||
FROM "device-status-log" log, params
|
FROM "device-status-log" log, params
|
||||||
WHERE log.code = 'EnergyConsumedB'
|
WHERE log.code = 'EnergyConsumedB'
|
||||||
AND log.event_time::date = params.target_date
|
AND log.device_id = params.device_id
|
||||||
|
AND log.event_time::date = params.target_date
|
||||||
GROUP BY 1,2,3,4,5
|
GROUP BY 1,2,3,4,5
|
||||||
),
|
),
|
||||||
energy_phase_C AS (
|
energy_phase_C AS (
|
||||||
@ -55,7 +59,8 @@ energy_phase_C AS (
|
|||||||
MAX(log.value)::integer AS max_value
|
MAX(log.value)::integer AS max_value
|
||||||
FROM "device-status-log" log, params
|
FROM "device-status-log" log, params
|
||||||
WHERE log.code = 'EnergyConsumedC'
|
WHERE log.code = 'EnergyConsumedC'
|
||||||
AND log.event_time::date = params.target_date
|
AND log.device_id = params.device_id
|
||||||
|
AND log.event_time::date = params.target_date
|
||||||
GROUP BY 1,2,3,4,5
|
GROUP BY 1,2,3,4,5
|
||||||
),
|
),
|
||||||
final_data AS (
|
final_data AS (
|
||||||
|
@ -1,6 +1,8 @@
|
|||||||
WITH params AS (
|
WITH params AS (
|
||||||
SELECT
|
SELECT
|
||||||
$1::date AS target_date
|
$1::uuid AS device_id,
|
||||||
|
$2::date AS target_date,
|
||||||
|
$3::text AS target_hour
|
||||||
),
|
),
|
||||||
total_energy AS (
|
total_energy AS (
|
||||||
SELECT
|
SELECT
|
||||||
@ -13,7 +15,9 @@ total_energy AS (
|
|||||||
MAX(log.value)::integer AS max_value
|
MAX(log.value)::integer AS max_value
|
||||||
FROM "device-status-log" log, params
|
FROM "device-status-log" log, params
|
||||||
WHERE log.code = 'EnergyConsumed'
|
WHERE log.code = 'EnergyConsumed'
|
||||||
|
AND log.device_id = params.device_id
|
||||||
AND log.event_time::date = params.target_date
|
AND log.event_time::date = params.target_date
|
||||||
|
AND EXTRACT(HOUR FROM log.event_time)::text = params.target_hour
|
||||||
GROUP BY 1,2,3,4,5
|
GROUP BY 1,2,3,4,5
|
||||||
),
|
),
|
||||||
energy_phase_A AS (
|
energy_phase_A AS (
|
||||||
@ -27,7 +31,9 @@ energy_phase_A AS (
|
|||||||
MAX(log.value)::integer AS max_value
|
MAX(log.value)::integer AS max_value
|
||||||
FROM "device-status-log" log, params
|
FROM "device-status-log" log, params
|
||||||
WHERE log.code = 'EnergyConsumedA'
|
WHERE log.code = 'EnergyConsumedA'
|
||||||
|
AND log.device_id = params.device_id
|
||||||
AND log.event_time::date = params.target_date
|
AND log.event_time::date = params.target_date
|
||||||
|
AND EXTRACT(HOUR FROM log.event_time)::text = params.target_hour
|
||||||
GROUP BY 1,2,3,4,5
|
GROUP BY 1,2,3,4,5
|
||||||
),
|
),
|
||||||
energy_phase_B AS (
|
energy_phase_B AS (
|
||||||
@ -41,7 +47,9 @@ energy_phase_B AS (
|
|||||||
MAX(log.value)::integer AS max_value
|
MAX(log.value)::integer AS max_value
|
||||||
FROM "device-status-log" log, params
|
FROM "device-status-log" log, params
|
||||||
WHERE log.code = 'EnergyConsumedB'
|
WHERE log.code = 'EnergyConsumedB'
|
||||||
|
AND log.device_id = params.device_id
|
||||||
AND log.event_time::date = params.target_date
|
AND log.event_time::date = params.target_date
|
||||||
|
AND EXTRACT(HOUR FROM log.event_time)::text = params.target_hour
|
||||||
GROUP BY 1,2,3,4,5
|
GROUP BY 1,2,3,4,5
|
||||||
),
|
),
|
||||||
energy_phase_C AS (
|
energy_phase_C AS (
|
||||||
@ -55,7 +63,9 @@ energy_phase_C AS (
|
|||||||
MAX(log.value)::integer AS max_value
|
MAX(log.value)::integer AS max_value
|
||||||
FROM "device-status-log" log, params
|
FROM "device-status-log" log, params
|
||||||
WHERE log.code = 'EnergyConsumedC'
|
WHERE log.code = 'EnergyConsumedC'
|
||||||
|
AND log.device_id = params.device_id
|
||||||
AND log.event_time::date = params.target_date
|
AND log.event_time::date = params.target_date
|
||||||
|
AND EXTRACT(HOUR FROM log.event_time)::text = params.target_hour
|
||||||
GROUP BY 1,2,3,4,5
|
GROUP BY 1,2,3,4,5
|
||||||
),
|
),
|
||||||
final_data AS (
|
final_data AS (
|
||||||
|
@ -1,6 +1,7 @@
|
|||||||
WITH params AS (
|
WITH params AS (
|
||||||
SELECT
|
SELECT
|
||||||
$1::text AS target_month -- Format should match 'MM-YYYY'
|
$1::uuid AS device_id,
|
||||||
|
$2::text AS target_month -- Format should match 'MM-YYYY'
|
||||||
),
|
),
|
||||||
total_energy AS (
|
total_energy AS (
|
||||||
SELECT
|
SELECT
|
||||||
@ -13,6 +14,7 @@ total_energy AS (
|
|||||||
MAX(log.value)::integer AS max_value
|
MAX(log.value)::integer AS max_value
|
||||||
FROM "device-status-log" log, params
|
FROM "device-status-log" log, params
|
||||||
WHERE log.code = 'EnergyConsumed'
|
WHERE log.code = 'EnergyConsumed'
|
||||||
|
AND log.device_id = params.device_id
|
||||||
AND TO_CHAR(log.event_time, 'MM-YYYY') = params.target_month
|
AND TO_CHAR(log.event_time, 'MM-YYYY') = params.target_month
|
||||||
GROUP BY 1,2,3,4,5
|
GROUP BY 1,2,3,4,5
|
||||||
),
|
),
|
||||||
@ -27,6 +29,7 @@ energy_phase_A AS (
|
|||||||
MAX(log.value)::integer AS max_value
|
MAX(log.value)::integer AS max_value
|
||||||
FROM "device-status-log" log, params
|
FROM "device-status-log" log, params
|
||||||
WHERE log.code = 'EnergyConsumedA'
|
WHERE log.code = 'EnergyConsumedA'
|
||||||
|
AND log.device_id = params.device_id
|
||||||
AND TO_CHAR(log.event_time, 'MM-YYYY') = params.target_month
|
AND TO_CHAR(log.event_time, 'MM-YYYY') = params.target_month
|
||||||
GROUP BY 1,2,3,4,5
|
GROUP BY 1,2,3,4,5
|
||||||
),
|
),
|
||||||
@ -41,6 +44,7 @@ energy_phase_B AS (
|
|||||||
MAX(log.value)::integer AS max_value
|
MAX(log.value)::integer AS max_value
|
||||||
FROM "device-status-log" log, params
|
FROM "device-status-log" log, params
|
||||||
WHERE log.code = 'EnergyConsumedB'
|
WHERE log.code = 'EnergyConsumedB'
|
||||||
|
AND log.device_id = params.device_id
|
||||||
AND TO_CHAR(log.event_time, 'MM-YYYY') = params.target_month
|
AND TO_CHAR(log.event_time, 'MM-YYYY') = params.target_month
|
||||||
GROUP BY 1,2,3,4,5
|
GROUP BY 1,2,3,4,5
|
||||||
),
|
),
|
||||||
@ -55,6 +59,7 @@ energy_phase_C AS (
|
|||||||
MAX(log.value)::integer AS max_value
|
MAX(log.value)::integer AS max_value
|
||||||
FROM "device-status-log" log, params
|
FROM "device-status-log" log, params
|
||||||
WHERE log.code = 'EnergyConsumedC'
|
WHERE log.code = 'EnergyConsumedC'
|
||||||
|
AND log.device_id = params.device_id
|
||||||
AND TO_CHAR(log.event_time, 'MM-YYYY') = params.target_month
|
AND TO_CHAR(log.event_time, 'MM-YYYY') = params.target_month
|
||||||
GROUP BY 1,2,3,4,5
|
GROUP BY 1,2,3,4,5
|
||||||
),
|
),
|
||||||
|
@ -1,6 +1,7 @@
|
|||||||
WITH params AS (
|
WITH params AS (
|
||||||
SELECT
|
SELECT
|
||||||
TO_DATE(NULLIF($1, ''), 'YYYY-MM-DD') AS event_date
|
TO_DATE(NULLIF($1, ''), 'YYYY-MM-DD') AS event_date,
|
||||||
|
$2::uuid AS space_id
|
||||||
),
|
),
|
||||||
|
|
||||||
device_logs AS (
|
device_logs AS (
|
||||||
@ -86,7 +87,8 @@ SELECT summary.space_id,
|
|||||||
count_total_presence_detected
|
count_total_presence_detected
|
||||||
FROM summary
|
FROM summary
|
||||||
JOIN params P ON true
|
JOIN params P ON true
|
||||||
where (P.event_date IS NULL or summary.event_date::date = P.event_date)
|
where summary.space_id = P.space_id
|
||||||
|
and (P.event_date IS NULL or summary.event_date::date = P.event_date)
|
||||||
ORDER BY space_id, event_date)
|
ORDER BY space_id, event_date)
|
||||||
|
|
||||||
|
|
||||||
|
3948
package-lock.json
generated
3948
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@ -30,7 +30,6 @@
|
|||||||
"@nestjs/jwt": "^10.2.0",
|
"@nestjs/jwt": "^10.2.0",
|
||||||
"@nestjs/passport": "^10.0.3",
|
"@nestjs/passport": "^10.0.3",
|
||||||
"@nestjs/platform-express": "^10.0.0",
|
"@nestjs/platform-express": "^10.0.0",
|
||||||
"@nestjs/schedule": "^6.0.0",
|
|
||||||
"@nestjs/swagger": "^7.3.0",
|
"@nestjs/swagger": "^7.3.0",
|
||||||
"@nestjs/terminus": "^11.0.0",
|
"@nestjs/terminus": "^11.0.0",
|
||||||
"@nestjs/throttler": "^6.4.0",
|
"@nestjs/throttler": "^6.4.0",
|
||||||
@ -51,12 +50,11 @@
|
|||||||
"ioredis": "^5.3.2",
|
"ioredis": "^5.3.2",
|
||||||
"morgan": "^1.10.0",
|
"morgan": "^1.10.0",
|
||||||
"nest-winston": "^1.10.2",
|
"nest-winston": "^1.10.2",
|
||||||
"node-cache": "^5.1.2",
|
|
||||||
"nodemailer": "^6.9.10",
|
"nodemailer": "^6.9.10",
|
||||||
"onesignal-node": "^3.4.0",
|
"onesignal-node": "^3.4.0",
|
||||||
"passport-jwt": "^4.0.1",
|
"passport-jwt": "^4.0.1",
|
||||||
"pg": "^8.11.3",
|
"pg": "^8.11.3",
|
||||||
"reflect-metadata": "^0.2.2",
|
"reflect-metadata": "^0.2.0",
|
||||||
"rxjs": "^7.8.1",
|
"rxjs": "^7.8.1",
|
||||||
"typeorm": "^0.3.20",
|
"typeorm": "^0.3.20",
|
||||||
"winston": "^3.17.0",
|
"winston": "^3.17.0",
|
||||||
|
@ -1,7 +1,7 @@
|
|||||||
import { SeederModule } from '@app/common/seed/seeder.module';
|
import { SeederModule } from '@app/common/seed/seeder.module';
|
||||||
import { Module } from '@nestjs/common';
|
import { Module } from '@nestjs/common';
|
||||||
import { ConfigModule } from '@nestjs/config';
|
import { ConfigModule } from '@nestjs/config';
|
||||||
import { APP_GUARD, APP_INTERCEPTOR } from '@nestjs/core';
|
import { APP_INTERCEPTOR } from '@nestjs/core';
|
||||||
import { WinstonModule } from 'nest-winston';
|
import { WinstonModule } from 'nest-winston';
|
||||||
import { AuthenticationModule } from './auth/auth.module';
|
import { AuthenticationModule } from './auth/auth.module';
|
||||||
import { AutomationModule } from './automation/automation.module';
|
import { AutomationModule } from './automation/automation.module';
|
||||||
@ -35,33 +35,18 @@ import { UserNotificationModule } from './user-notification/user-notification.mo
|
|||||||
import { UserModule } from './users/user.module';
|
import { UserModule } from './users/user.module';
|
||||||
import { VisitorPasswordModule } from './vistor-password/visitor-password.module';
|
import { VisitorPasswordModule } from './vistor-password/visitor-password.module';
|
||||||
|
|
||||||
import { ThrottlerGuard } from '@nestjs/throttler';
|
|
||||||
import { ThrottlerModule } from '@nestjs/throttler/dist/throttler.module';
|
|
||||||
import { isArray } from 'class-validator';
|
|
||||||
import { winstonLoggerOptions } from '../libs/common/src/logger/services/winston.logger';
|
import { winstonLoggerOptions } from '../libs/common/src/logger/services/winston.logger';
|
||||||
import { AqiModule } from './aqi/aqi.module';
|
import { AqiModule } from './aqi/aqi.module';
|
||||||
import { OccupancyModule } from './occupancy/occupancy.module';
|
import { OccupancyModule } from './occupancy/occupancy.module';
|
||||||
import { WeatherModule } from './weather/weather.module';
|
import { WeatherModule } from './weather/weather.module';
|
||||||
import { ScheduleModule as NestScheduleModule } from '@nestjs/schedule';
|
|
||||||
import { SchedulerModule } from './scheduler/scheduler.module';
|
|
||||||
import { BookingModule } from './booking';
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [
|
imports: [
|
||||||
ConfigModule.forRoot({
|
ConfigModule.forRoot({
|
||||||
load: config,
|
load: config,
|
||||||
}),
|
}),
|
||||||
ThrottlerModule.forRoot({
|
/* ThrottlerModule.forRoot({
|
||||||
throttlers: [{ ttl: 60000, limit: 100 }],
|
throttlers: [{ ttl: 100000, limit: 30 }],
|
||||||
generateKey: (context) => {
|
}), */
|
||||||
const req = context.switchToHttp().getRequest();
|
|
||||||
console.log('Real IP:', req.headers['x-forwarded-for']);
|
|
||||||
return req.headers['x-forwarded-for']
|
|
||||||
? isArray(req.headers['x-forwarded-for'])
|
|
||||||
? req.headers['x-forwarded-for'][0].split(':')[0]
|
|
||||||
: req.headers['x-forwarded-for'].split(':')[0]
|
|
||||||
: req.ip;
|
|
||||||
},
|
|
||||||
}),
|
|
||||||
WinstonModule.forRoot(winstonLoggerOptions),
|
WinstonModule.forRoot(winstonLoggerOptions),
|
||||||
ClientModule,
|
ClientModule,
|
||||||
AuthenticationModule,
|
AuthenticationModule,
|
||||||
@ -97,19 +82,16 @@ import { BookingModule } from './booking';
|
|||||||
OccupancyModule,
|
OccupancyModule,
|
||||||
WeatherModule,
|
WeatherModule,
|
||||||
AqiModule,
|
AqiModule,
|
||||||
SchedulerModule,
|
|
||||||
NestScheduleModule.forRoot(),
|
|
||||||
BookingModule,
|
|
||||||
],
|
],
|
||||||
providers: [
|
providers: [
|
||||||
{
|
{
|
||||||
provide: APP_INTERCEPTOR,
|
provide: APP_INTERCEPTOR,
|
||||||
useClass: LoggingInterceptor,
|
useClass: LoggingInterceptor,
|
||||||
},
|
},
|
||||||
{
|
/* {
|
||||||
provide: APP_GUARD,
|
provide: APP_GUARD,
|
||||||
useClass: ThrottlerGuard,
|
useClass: ThrottlerGuard,
|
||||||
},
|
}, */
|
||||||
],
|
],
|
||||||
})
|
})
|
||||||
export class AppModule {}
|
export class AppModule {}
|
||||||
|
@ -1,25 +1,25 @@
|
|||||||
import { RoleType } from '@app/common/constants/role.type.enum';
|
import { UserRepository } from '../../../libs/common/src/modules/user/repositories';
|
||||||
import { differenceInSeconds } from '@app/common/helper/differenceInSeconds';
|
|
||||||
import {
|
import {
|
||||||
BadRequestException,
|
BadRequestException,
|
||||||
ForbiddenException,
|
ForbiddenException,
|
||||||
Injectable,
|
Injectable,
|
||||||
} from '@nestjs/common';
|
} from '@nestjs/common';
|
||||||
import { ConfigService } from '@nestjs/config';
|
|
||||||
import * as argon2 from 'argon2';
|
|
||||||
import { RoleService } from 'src/role/services';
|
|
||||||
import { LessThan, MoreThan } from 'typeorm';
|
|
||||||
import { AuthService } from '../../../libs/common/src/auth/services/auth.service';
|
|
||||||
import { OtpType } from '../../../libs/common/src/constants/otp-type.enum';
|
|
||||||
import { HelperHashService } from '../../../libs/common/src/helper/services';
|
|
||||||
import { UserSessionRepository } from '../../../libs/common/src/modules/session/repositories/session.repository';
|
|
||||||
import { UserEntity } from '../../../libs/common/src/modules/user/entities/user.entity';
|
|
||||||
import { UserRepository } from '../../../libs/common/src/modules/user/repositories';
|
|
||||||
import { UserOtpRepository } from '../../../libs/common/src/modules/user/repositories/user.repository';
|
|
||||||
import { EmailService } from '../../../libs/common/src/util/email.service';
|
|
||||||
import { ForgetPasswordDto, UserOtpDto, VerifyOtpDto } from '../dtos';
|
|
||||||
import { UserSignUpDto } from '../dtos/user-auth.dto';
|
import { UserSignUpDto } from '../dtos/user-auth.dto';
|
||||||
|
import { HelperHashService } from '../../../libs/common/src/helper/services';
|
||||||
import { UserLoginDto } from '../dtos/user-login.dto';
|
import { UserLoginDto } from '../dtos/user-login.dto';
|
||||||
|
import { AuthService } from '../../../libs/common/src/auth/services/auth.service';
|
||||||
|
import { UserSessionRepository } from '../../../libs/common/src/modules/session/repositories/session.repository';
|
||||||
|
import { UserOtpRepository } from '../../../libs/common/src/modules/user/repositories/user.repository';
|
||||||
|
import { ForgetPasswordDto, UserOtpDto, VerifyOtpDto } from '../dtos';
|
||||||
|
import { EmailService } from '../../../libs/common/src/util/email.service';
|
||||||
|
import { OtpType } from '../../../libs/common/src/constants/otp-type.enum';
|
||||||
|
import { UserEntity } from '../../../libs/common/src/modules/user/entities/user.entity';
|
||||||
|
import * as argon2 from 'argon2';
|
||||||
|
import { differenceInSeconds } from '@app/common/helper/differenceInSeconds';
|
||||||
|
import { LessThan, MoreThan } from 'typeorm';
|
||||||
|
import { ConfigService } from '@nestjs/config';
|
||||||
|
import { RoleService } from 'src/role/services';
|
||||||
|
import { RoleType } from '@app/common/constants/role.type.enum';
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class UserAuthService {
|
export class UserAuthService {
|
||||||
@ -108,7 +108,7 @@ export class UserAuthService {
|
|||||||
|
|
||||||
async userLogin(data: UserLoginDto) {
|
async userLogin(data: UserLoginDto) {
|
||||||
try {
|
try {
|
||||||
let user: Omit<UserEntity, 'password'>;
|
let user;
|
||||||
if (data.googleCode) {
|
if (data.googleCode) {
|
||||||
const googleUserData = await this.authService.login({
|
const googleUserData = await this.authService.login({
|
||||||
googleCode: data.googleCode,
|
googleCode: data.googleCode,
|
||||||
@ -145,7 +145,7 @@ export class UserAuthService {
|
|||||||
}
|
}
|
||||||
const session = await Promise.all([
|
const session = await Promise.all([
|
||||||
await this.sessionRepository.update(
|
await this.sessionRepository.update(
|
||||||
{ userId: user?.['id'] },
|
{ userId: user.id },
|
||||||
{
|
{
|
||||||
isLoggedOut: true,
|
isLoggedOut: true,
|
||||||
},
|
},
|
||||||
@ -166,7 +166,6 @@ export class UserAuthService {
|
|||||||
hasAcceptedAppAgreement: user.hasAcceptedAppAgreement,
|
hasAcceptedAppAgreement: user.hasAcceptedAppAgreement,
|
||||||
project: user.project,
|
project: user.project,
|
||||||
sessionId: session[1].uuid,
|
sessionId: session[1].uuid,
|
||||||
bookingPoints: user.bookingPoints,
|
|
||||||
});
|
});
|
||||||
return res;
|
return res;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
@ -348,7 +347,6 @@ export class UserAuthService {
|
|||||||
userId: user.uuid,
|
userId: user.uuid,
|
||||||
uuid: user.uuid,
|
uuid: user.uuid,
|
||||||
type,
|
type,
|
||||||
bookingPoints: user.bookingPoints,
|
|
||||||
sessionId,
|
sessionId,
|
||||||
});
|
});
|
||||||
await this.authService.updateRefreshToken(user.uuid, tokens.refreshToken);
|
await this.authService.updateRefreshToken(user.uuid, tokens.refreshToken);
|
||||||
|
@ -1,17 +0,0 @@
|
|||||||
import { Global, Module } from '@nestjs/common';
|
|
||||||
import { BookableSpaceController } from './controllers';
|
|
||||||
import { BookableSpaceService } from './services';
|
|
||||||
import { BookableSpaceEntityRepository } from '@app/common/modules/booking/repositories';
|
|
||||||
import { SpaceRepository } from '@app/common/modules/space';
|
|
||||||
|
|
||||||
@Global()
|
|
||||||
@Module({
|
|
||||||
controllers: [BookableSpaceController],
|
|
||||||
providers: [
|
|
||||||
BookableSpaceService,
|
|
||||||
BookableSpaceEntityRepository,
|
|
||||||
SpaceRepository,
|
|
||||||
],
|
|
||||||
exports: [BookableSpaceService],
|
|
||||||
})
|
|
||||||
export class BookingModule {}
|
|
@ -1,107 +0,0 @@
|
|||||||
import { ControllerRoute } from '@app/common/constants/controller-route';
|
|
||||||
import { EnableDisableStatusEnum } from '@app/common/constants/days.enum';
|
|
||||||
import { BaseResponseDto } from '@app/common/dto/base.response.dto';
|
|
||||||
import { JwtAuthGuard } from '@app/common/guards/jwt.auth.guard';
|
|
||||||
import {
|
|
||||||
Body,
|
|
||||||
Controller,
|
|
||||||
Get,
|
|
||||||
Param,
|
|
||||||
ParseUUIDPipe,
|
|
||||||
Post,
|
|
||||||
Put,
|
|
||||||
Query,
|
|
||||||
Req,
|
|
||||||
UseGuards,
|
|
||||||
} from '@nestjs/common';
|
|
||||||
import { ApiBearerAuth, ApiOperation, ApiTags } from '@nestjs/swagger';
|
|
||||||
|
|
||||||
import { PageResponse } from '@app/common/dto/pagination.response.dto';
|
|
||||||
import { SuccessResponseDto } from '@app/common/dto/success.response.dto';
|
|
||||||
import { plainToInstance } from 'class-transformer';
|
|
||||||
import { CreateBookableSpaceDto } from '../dtos';
|
|
||||||
import { BookableSpaceRequestDto } from '../dtos/bookable-space-request.dto';
|
|
||||||
import { BookableSpaceResponseDto } from '../dtos/bookable-space-response.dto';
|
|
||||||
import { UpdateBookableSpaceDto } from '../dtos/update-bookable-space.dto';
|
|
||||||
import { BookableSpaceService } from '../services';
|
|
||||||
|
|
||||||
@ApiTags('Booking Module')
|
|
||||||
@Controller({
|
|
||||||
version: EnableDisableStatusEnum.ENABLED,
|
|
||||||
path: ControllerRoute.BOOKABLE_SPACES.ROUTE,
|
|
||||||
})
|
|
||||||
export class BookableSpaceController {
|
|
||||||
constructor(private readonly bookableSpaceService: BookableSpaceService) {}
|
|
||||||
@ApiBearerAuth()
|
|
||||||
@UseGuards(JwtAuthGuard)
|
|
||||||
@Post()
|
|
||||||
@ApiOperation({
|
|
||||||
summary:
|
|
||||||
ControllerRoute.BOOKABLE_SPACES.ACTIONS.ADD_BOOKABLE_SPACES_SUMMARY,
|
|
||||||
description:
|
|
||||||
ControllerRoute.BOOKABLE_SPACES.ACTIONS.ADD_BOOKABLE_SPACES_DESCRIPTION,
|
|
||||||
})
|
|
||||||
async create(@Body() dto: CreateBookableSpaceDto): Promise<BaseResponseDto> {
|
|
||||||
const result = await this.bookableSpaceService.create(dto);
|
|
||||||
return new SuccessResponseDto({
|
|
||||||
data: result,
|
|
||||||
message: 'Successfully created bookable spaces',
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
@ApiBearerAuth()
|
|
||||||
@UseGuards(JwtAuthGuard)
|
|
||||||
@Get()
|
|
||||||
@ApiOperation({
|
|
||||||
summary:
|
|
||||||
ControllerRoute.BOOKABLE_SPACES.ACTIONS.GET_ALL_BOOKABLE_SPACES_SUMMARY,
|
|
||||||
description:
|
|
||||||
ControllerRoute.BOOKABLE_SPACES.ACTIONS
|
|
||||||
.GET_ALL_BOOKABLE_SPACES_DESCRIPTION,
|
|
||||||
})
|
|
||||||
async findAll(
|
|
||||||
@Query() query: BookableSpaceRequestDto,
|
|
||||||
@Req() req: Request,
|
|
||||||
): Promise<PageResponse<BookableSpaceResponseDto>> {
|
|
||||||
const project = req['user']?.project?.uuid;
|
|
||||||
if (!project) {
|
|
||||||
throw new Error('Project UUID is required in the request');
|
|
||||||
}
|
|
||||||
const { data, pagination } = await this.bookableSpaceService.findAll(
|
|
||||||
query,
|
|
||||||
project,
|
|
||||||
);
|
|
||||||
return new PageResponse<BookableSpaceResponseDto>(
|
|
||||||
{
|
|
||||||
data: data.map((space) =>
|
|
||||||
plainToInstance(BookableSpaceResponseDto, space, {
|
|
||||||
excludeExtraneousValues: true,
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
message: 'Successfully fetched all bookable spaces',
|
|
||||||
},
|
|
||||||
pagination,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
@ApiBearerAuth()
|
|
||||||
@UseGuards(JwtAuthGuard)
|
|
||||||
@Put(':spaceUuid')
|
|
||||||
@ApiOperation({
|
|
||||||
summary:
|
|
||||||
ControllerRoute.BOOKABLE_SPACES.ACTIONS.UPDATE_BOOKABLE_SPACES_SUMMARY,
|
|
||||||
description:
|
|
||||||
ControllerRoute.BOOKABLE_SPACES.ACTIONS
|
|
||||||
.UPDATE_BOOKABLE_SPACES_DESCRIPTION,
|
|
||||||
})
|
|
||||||
async update(
|
|
||||||
@Param('spaceUuid', ParseUUIDPipe) spaceUuid: string,
|
|
||||||
@Body() dto: UpdateBookableSpaceDto,
|
|
||||||
): Promise<BaseResponseDto> {
|
|
||||||
const result = await this.bookableSpaceService.update(spaceUuid, dto);
|
|
||||||
return new SuccessResponseDto({
|
|
||||||
data: result,
|
|
||||||
message: 'Successfully updated bookable spaces',
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
@ -1 +0,0 @@
|
|||||||
export * from './bookable-space.controller';
|
|
@ -1,31 +0,0 @@
|
|||||||
import { BooleanValues } from '@app/common/constants/boolean-values.enum';
|
|
||||||
import { PaginationRequestWithSearchGetListDto } from '@app/common/dto/pagination-with-search.request.dto';
|
|
||||||
import { ApiProperty, OmitType } from '@nestjs/swagger';
|
|
||||||
import { Transform } from 'class-transformer';
|
|
||||||
import { IsBoolean, IsNotEmpty, IsOptional } from 'class-validator';
|
|
||||||
|
|
||||||
export class BookableSpaceRequestDto extends OmitType(
|
|
||||||
PaginationRequestWithSearchGetListDto,
|
|
||||||
['includeSpaces'],
|
|
||||||
) {
|
|
||||||
@ApiProperty({
|
|
||||||
type: Boolean,
|
|
||||||
required: false,
|
|
||||||
})
|
|
||||||
@IsBoolean()
|
|
||||||
@IsOptional()
|
|
||||||
@Transform(({ obj }) => {
|
|
||||||
return obj.active === BooleanValues.TRUE;
|
|
||||||
})
|
|
||||||
active?: boolean;
|
|
||||||
|
|
||||||
@ApiProperty({
|
|
||||||
type: Boolean,
|
|
||||||
})
|
|
||||||
@IsBoolean()
|
|
||||||
@IsNotEmpty()
|
|
||||||
@Transform(({ obj }) => {
|
|
||||||
return obj.configured === BooleanValues.TRUE;
|
|
||||||
})
|
|
||||||
configured: boolean;
|
|
||||||
}
|
|
@ -1,59 +0,0 @@
|
|||||||
import { ApiProperty } from '@nestjs/swagger';
|
|
||||||
import { Expose, Type } from 'class-transformer';
|
|
||||||
export class BookableSpaceConfigResponseDto {
|
|
||||||
@ApiProperty()
|
|
||||||
@Expose()
|
|
||||||
uuid: string;
|
|
||||||
|
|
||||||
@ApiProperty({
|
|
||||||
type: [String],
|
|
||||||
})
|
|
||||||
@Expose()
|
|
||||||
daysAvailable: string[];
|
|
||||||
|
|
||||||
@ApiProperty()
|
|
||||||
@Expose()
|
|
||||||
startTime: string;
|
|
||||||
|
|
||||||
@ApiProperty()
|
|
||||||
@Expose()
|
|
||||||
endTime: string;
|
|
||||||
|
|
||||||
@ApiProperty({
|
|
||||||
type: Boolean,
|
|
||||||
})
|
|
||||||
@Expose()
|
|
||||||
active: boolean;
|
|
||||||
|
|
||||||
@ApiProperty({
|
|
||||||
type: Number,
|
|
||||||
nullable: true,
|
|
||||||
})
|
|
||||||
@Expose()
|
|
||||||
points?: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
export class BookableSpaceResponseDto {
|
|
||||||
@ApiProperty()
|
|
||||||
@Expose()
|
|
||||||
uuid: string;
|
|
||||||
|
|
||||||
@ApiProperty()
|
|
||||||
@Expose()
|
|
||||||
spaceUuid: string;
|
|
||||||
|
|
||||||
@ApiProperty()
|
|
||||||
@Expose()
|
|
||||||
spaceName: string;
|
|
||||||
|
|
||||||
@ApiProperty()
|
|
||||||
@Expose()
|
|
||||||
virtualLocation: string;
|
|
||||||
|
|
||||||
@ApiProperty({
|
|
||||||
type: BookableSpaceConfigResponseDto,
|
|
||||||
})
|
|
||||||
@Expose()
|
|
||||||
@Type(() => BookableSpaceConfigResponseDto)
|
|
||||||
bookableConfig: BookableSpaceConfigResponseDto;
|
|
||||||
}
|
|
@ -1,63 +0,0 @@
|
|||||||
import { DaysEnum } from '@app/common/constants/days.enum';
|
|
||||||
import { ApiProperty } from '@nestjs/swagger';
|
|
||||||
import {
|
|
||||||
ArrayMinSize,
|
|
||||||
IsArray,
|
|
||||||
IsEnum,
|
|
||||||
IsInt,
|
|
||||||
IsNotEmpty,
|
|
||||||
IsOptional,
|
|
||||||
IsString,
|
|
||||||
IsUUID,
|
|
||||||
Matches,
|
|
||||||
Max,
|
|
||||||
Min,
|
|
||||||
} from 'class-validator';
|
|
||||||
|
|
||||||
export class CreateBookableSpaceDto {
|
|
||||||
@ApiProperty({
|
|
||||||
type: 'string',
|
|
||||||
isArray: true,
|
|
||||||
example: [
|
|
||||||
'3fa85f64-5717-4562-b3fc-2c963f66afa6',
|
|
||||||
'4fa85f64-5717-4562-b3fc-2c963f66afa7',
|
|
||||||
],
|
|
||||||
})
|
|
||||||
@IsArray()
|
|
||||||
@ArrayMinSize(1, { message: 'At least one space must be selected' })
|
|
||||||
@IsUUID('all', { each: true, message: 'Invalid space UUID provided' })
|
|
||||||
spaceUuids: string[];
|
|
||||||
|
|
||||||
@ApiProperty({
|
|
||||||
enum: DaysEnum,
|
|
||||||
isArray: true,
|
|
||||||
example: [DaysEnum.MON, DaysEnum.WED, DaysEnum.FRI],
|
|
||||||
})
|
|
||||||
@IsArray()
|
|
||||||
@ArrayMinSize(1, { message: 'At least one day must be selected' })
|
|
||||||
@IsEnum(DaysEnum, { each: true, message: 'Invalid day provided' })
|
|
||||||
daysAvailable: DaysEnum[];
|
|
||||||
|
|
||||||
@ApiProperty({ example: '09:00' })
|
|
||||||
@IsString()
|
|
||||||
@IsNotEmpty({ message: 'Start time cannot be empty' })
|
|
||||||
@Matches(/^([01]?[0-9]|2[0-3]):[0-5][0-9]$/, {
|
|
||||||
message: 'Start time must be in HH:mm format (24-hour)',
|
|
||||||
})
|
|
||||||
startTime: string;
|
|
||||||
|
|
||||||
@ApiProperty({ example: '17:00' })
|
|
||||||
@IsString()
|
|
||||||
@IsNotEmpty({ message: 'End time cannot be empty' })
|
|
||||||
@Matches(/^([01]?[0-9]|2[0-3]):[0-5][0-9]$/, {
|
|
||||||
message: 'End time must be in HH:mm format (24-hour)',
|
|
||||||
})
|
|
||||||
endTime: string;
|
|
||||||
|
|
||||||
@ApiProperty({ example: 10, required: false })
|
|
||||||
@IsOptional()
|
|
||||||
@IsInt()
|
|
||||||
@Min(0, { message: 'Points cannot be negative' })
|
|
||||||
@Max(1000, { message: 'Points cannot exceed 1000' })
|
|
||||||
points?: number;
|
|
||||||
}
|
|
@ -1 +0,0 @@
|
|||||||
export * from './create-bookable-space.dto';
|
|
@ -1,12 +0,0 @@
|
|||||||
import { ApiProperty, OmitType, PartialType } from '@nestjs/swagger';
|
|
||||||
import { IsBoolean, IsOptional } from 'class-validator';
|
|
||||||
import { CreateBookableSpaceDto } from './create-bookable-space.dto';
|
|
||||||
|
|
||||||
export class UpdateBookableSpaceDto extends PartialType(
|
|
||||||
OmitType(CreateBookableSpaceDto, ['spaceUuids']),
|
|
||||||
) {
|
|
||||||
@ApiProperty({ type: Boolean })
|
|
||||||
@IsOptional()
|
|
||||||
@IsBoolean()
|
|
||||||
active?: boolean;
|
|
||||||
}
|
|
@ -1 +0,0 @@
|
|||||||
export * from './booking.module';
|
|
@ -1,197 +0,0 @@
|
|||||||
import { BaseResponseDto } from '@app/common/dto/base.response.dto';
|
|
||||||
import { PageResponseDto } from '@app/common/dto/pagination.response.dto';
|
|
||||||
import { timeToMinutes } from '@app/common/helper/timeToMinutes';
|
|
||||||
import { TypeORMCustomModel } from '@app/common/models/typeOrmCustom.model';
|
|
||||||
import { BookableSpaceEntityRepository } from '@app/common/modules/booking/repositories';
|
|
||||||
import { SpaceEntity } from '@app/common/modules/space/entities/space.entity';
|
|
||||||
import { SpaceRepository } from '@app/common/modules/space/repositories/space.repository';
|
|
||||||
import {
|
|
||||||
BadRequestException,
|
|
||||||
ConflictException,
|
|
||||||
Injectable,
|
|
||||||
NotFoundException,
|
|
||||||
} from '@nestjs/common';
|
|
||||||
import { In } from 'typeorm';
|
|
||||||
import { CreateBookableSpaceDto } from '../dtos';
|
|
||||||
import { BookableSpaceRequestDto } from '../dtos/bookable-space-request.dto';
|
|
||||||
import { UpdateBookableSpaceDto } from '../dtos/update-bookable-space.dto';
|
|
||||||
|
|
||||||
@Injectable()
|
|
||||||
export class BookableSpaceService {
|
|
||||||
constructor(
|
|
||||||
private readonly bookableSpaceEntityRepository: BookableSpaceEntityRepository,
|
|
||||||
private readonly spaceRepository: SpaceRepository,
|
|
||||||
) {}
|
|
||||||
|
|
||||||
async create(dto: CreateBookableSpaceDto) {
|
|
||||||
// Validate time slots first
|
|
||||||
this.validateTimeSlot(dto.startTime, dto.endTime);
|
|
||||||
|
|
||||||
// fetch spaces exist
|
|
||||||
const spaces = await this.getSpacesOrFindMissing(dto.spaceUuids);
|
|
||||||
|
|
||||||
// Validate no duplicate bookable configurations
|
|
||||||
await this.validateNoDuplicateBookableConfigs(dto.spaceUuids);
|
|
||||||
|
|
||||||
// Create and save bookable spaces
|
|
||||||
return this.createBookableSpaces(spaces, dto);
|
|
||||||
}
|
|
||||||
|
|
||||||
async findAll(
|
|
||||||
{ active, page, size, configured, search }: BookableSpaceRequestDto,
|
|
||||||
project: string,
|
|
||||||
): Promise<{
|
|
||||||
data: BaseResponseDto['data'];
|
|
||||||
pagination: PageResponseDto;
|
|
||||||
}> {
|
|
||||||
let qb = this.spaceRepository
|
|
||||||
.createQueryBuilder('space')
|
|
||||||
.leftJoinAndSelect('space.parent', 'parentSpace')
|
|
||||||
.leftJoinAndSelect('space.community', 'community')
|
|
||||||
.where('community.project = :project', { project });
|
|
||||||
|
|
||||||
if (search) {
|
|
||||||
qb = qb.andWhere(
|
|
||||||
'(space.spaceName ILIKE :search OR community.name ILIKE :search OR parentSpace.spaceName ILIKE :search)',
|
|
||||||
{ search: `%${search}%` },
|
|
||||||
);
|
|
||||||
}
|
|
||||||
if (configured) {
|
|
||||||
qb = qb
|
|
||||||
.leftJoinAndSelect('space.bookableConfig', 'bookableConfig')
|
|
||||||
.andWhere('bookableConfig.uuid IS NOT NULL');
|
|
||||||
if (active !== undefined) {
|
|
||||||
qb = qb.andWhere('bookableConfig.active = :active', { active });
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
qb = qb
|
|
||||||
.leftJoinAndSelect('space.bookableConfig', 'bookableConfig')
|
|
||||||
.andWhere('bookableConfig.uuid IS NULL');
|
|
||||||
}
|
|
||||||
const customModel = TypeORMCustomModel(this.spaceRepository);
|
|
||||||
|
|
||||||
const { baseResponseDto, paginationResponseDto } =
|
|
||||||
await customModel.findAll({ page, size, modelName: 'space' }, qb);
|
|
||||||
return {
|
|
||||||
data: baseResponseDto.data.map((space) => {
|
|
||||||
return {
|
|
||||||
...space,
|
|
||||||
virtualLocation: `${space.community?.name} - ${space.parent ? space.parent?.spaceName + ' - ' : ''}${space.spaceName}`,
|
|
||||||
};
|
|
||||||
}),
|
|
||||||
pagination: paginationResponseDto,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* todo: if updating availability, send to the ones who have access to this space
|
|
||||||
* todo: if updating other fields, just send emails to all users who's bookings might be affected
|
|
||||||
*/
|
|
||||||
async update(spaceUuid: string, dto: UpdateBookableSpaceDto) {
|
|
||||||
// fetch spaces exist
|
|
||||||
const space = (await this.getSpacesOrFindMissing([spaceUuid]))[0];
|
|
||||||
|
|
||||||
if (!space.bookableConfig) {
|
|
||||||
throw new NotFoundException(
|
|
||||||
`Bookable configuration not found for space: ${spaceUuid}`,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
if (dto.startTime || dto.endTime) {
|
|
||||||
// Validate time slots first
|
|
||||||
this.validateTimeSlot(
|
|
||||||
dto.startTime || space.bookableConfig.startTime,
|
|
||||||
dto.endTime || space.bookableConfig.endTime,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
Object.assign(space.bookableConfig, dto);
|
|
||||||
return this.bookableSpaceEntityRepository.save(space.bookableConfig);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Fetch spaces by UUIDs and throw an error if any are missing
|
|
||||||
*/
|
|
||||||
private async getSpacesOrFindMissing(
|
|
||||||
spaceUuids: string[],
|
|
||||||
): Promise<SpaceEntity[]> {
|
|
||||||
const spaces = await this.spaceRepository.find({
|
|
||||||
where: { uuid: In(spaceUuids) },
|
|
||||||
relations: ['bookableConfig'],
|
|
||||||
});
|
|
||||||
|
|
||||||
if (spaces.length !== spaceUuids.length) {
|
|
||||||
const foundUuids = spaces.map((s) => s.uuid);
|
|
||||||
const missingUuids = spaceUuids.filter(
|
|
||||||
(uuid) => !foundUuids.includes(uuid),
|
|
||||||
);
|
|
||||||
throw new NotFoundException(
|
|
||||||
`Spaces not found: ${missingUuids.join(', ')}`,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
return spaces;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Validate there are no existing bookable configurations for these spaces
|
|
||||||
*/
|
|
||||||
private async validateNoDuplicateBookableConfigs(
|
|
||||||
spaceUuids: string[],
|
|
||||||
): Promise<void> {
|
|
||||||
const existingBookables = await this.bookableSpaceEntityRepository.find({
|
|
||||||
where: { space: { uuid: In(spaceUuids) } },
|
|
||||||
relations: ['space'],
|
|
||||||
});
|
|
||||||
|
|
||||||
if (existingBookables.length > 0) {
|
|
||||||
const existingUuids = [
|
|
||||||
...new Set(existingBookables.map((b) => b.space.uuid)),
|
|
||||||
];
|
|
||||||
throw new ConflictException(
|
|
||||||
`Bookable configuration already exists for spaces: ${existingUuids.join(', ')}`,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Ensure the slot start time is before the end time
|
|
||||||
*/
|
|
||||||
private validateTimeSlot(startTime: string, endTime: string): void {
|
|
||||||
const start = timeToMinutes(startTime);
|
|
||||||
const end = timeToMinutes(endTime);
|
|
||||||
|
|
||||||
if (start >= end) {
|
|
||||||
throw new BadRequestException(
|
|
||||||
`End time must be after start time for slot: ${startTime}-${endTime}`,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Create bookable space entries after all validations pass
|
|
||||||
*/
|
|
||||||
private async createBookableSpaces(
|
|
||||||
spaces: SpaceEntity[],
|
|
||||||
dto: CreateBookableSpaceDto,
|
|
||||||
) {
|
|
||||||
try {
|
|
||||||
const entries = spaces.map((space) =>
|
|
||||||
this.bookableSpaceEntityRepository.create({
|
|
||||||
space,
|
|
||||||
daysAvailable: dto.daysAvailable,
|
|
||||||
startTime: dto.startTime,
|
|
||||||
endTime: dto.endTime,
|
|
||||||
points: dto.points,
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
return this.bookableSpaceEntityRepository.save(entries);
|
|
||||||
} catch (error) {
|
|
||||||
if (error.code === '23505') {
|
|
||||||
throw new ConflictException(
|
|
||||||
'Duplicate bookable space configuration detected',
|
|
||||||
);
|
|
||||||
}
|
|
||||||
throw error;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
@ -1 +0,0 @@
|
|||||||
export * from './bookable-space.service';
|
|
@ -30,8 +30,6 @@ import { PowerClampService } from '@app/common/helper/services/power.clamp.servi
|
|||||||
import { SqlLoaderService } from '@app/common/helper/services/sql-loader.service';
|
import { SqlLoaderService } from '@app/common/helper/services/sql-loader.service';
|
||||||
import { OccupancyService } from '@app/common/helper/services/occupancy.service';
|
import { OccupancyService } from '@app/common/helper/services/occupancy.service';
|
||||||
import { AqiDataService } from '@app/common/helper/services/aqi.data.service';
|
import { AqiDataService } from '@app/common/helper/services/aqi.data.service';
|
||||||
import { PresenceSensorDailySpaceRepository } from '@app/common/modules/presence-sensor/repositories';
|
|
||||||
import { AqiSpaceDailyPollutantStatsRepository } from '@app/common/modules/aqi/repositories';
|
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [ConfigModule, SpaceRepositoryModule],
|
imports: [ConfigModule, SpaceRepositoryModule],
|
||||||
@ -61,8 +59,6 @@ import { AqiSpaceDailyPollutantStatsRepository } from '@app/common/modules/aqi/r
|
|||||||
SqlLoaderService,
|
SqlLoaderService,
|
||||||
OccupancyService,
|
OccupancyService,
|
||||||
AqiDataService,
|
AqiDataService,
|
||||||
PresenceSensorDailySpaceRepository,
|
|
||||||
AqiSpaceDailyPollutantStatsRepository,
|
|
||||||
],
|
],
|
||||||
exports: [],
|
exports: [],
|
||||||
})
|
})
|
||||||
|
@ -3,7 +3,6 @@ import * as fs from 'fs';
|
|||||||
|
|
||||||
import { ProjectParam } from '@app/common/dto/project-param.dto';
|
import { ProjectParam } from '@app/common/dto/project-param.dto';
|
||||||
import { SuccessResponseDto } from '@app/common/dto/success.response.dto';
|
import { SuccessResponseDto } from '@app/common/dto/success.response.dto';
|
||||||
import { DeviceStatusFirebaseService } from '@app/common/firebase/devices-status/services/devices-status.service';
|
|
||||||
import { TuyaService } from '@app/common/integrations/tuya/services/tuya.service';
|
import { TuyaService } from '@app/common/integrations/tuya/services/tuya.service';
|
||||||
import { CommunityRepository } from '@app/common/modules/community/repositories';
|
import { CommunityRepository } from '@app/common/modules/community/repositories';
|
||||||
import { DeviceRepository } from '@app/common/modules/device/repositories';
|
import { DeviceRepository } from '@app/common/modules/device/repositories';
|
||||||
@ -21,7 +20,6 @@ export class DeviceCommissionService {
|
|||||||
constructor(
|
constructor(
|
||||||
private readonly tuyaService: TuyaService,
|
private readonly tuyaService: TuyaService,
|
||||||
private readonly deviceService: DeviceService,
|
private readonly deviceService: DeviceService,
|
||||||
private readonly deviceStatusFirebaseService: DeviceStatusFirebaseService,
|
|
||||||
private readonly communityRepository: CommunityRepository,
|
private readonly communityRepository: CommunityRepository,
|
||||||
private readonly spaceRepository: SpaceRepository,
|
private readonly spaceRepository: SpaceRepository,
|
||||||
private readonly subspaceRepository: SubspaceRepository,
|
private readonly subspaceRepository: SubspaceRepository,
|
||||||
@ -211,10 +209,6 @@ export class DeviceCommissionService {
|
|||||||
rawDeviceId,
|
rawDeviceId,
|
||||||
tuyaSpaceId,
|
tuyaSpaceId,
|
||||||
);
|
);
|
||||||
|
|
||||||
await this.deviceStatusFirebaseService.addDeviceStatusByDeviceUuid(
|
|
||||||
rawDeviceId,
|
|
||||||
);
|
|
||||||
successCount.value++;
|
successCount.value++;
|
||||||
console.log(
|
console.log(
|
||||||
`Device ${rawDeviceId} successfully processed and transferred to Tuya space ${tuyaSpaceId}`,
|
`Device ${rawDeviceId} successfully processed and transferred to Tuya space ${tuyaSpaceId}`,
|
||||||
|
@ -5,6 +5,7 @@ import { ConfigModule } from '@nestjs/config';
|
|||||||
import { SpaceRepositoryModule } from '@app/common/modules/space/space.repository.module';
|
import { SpaceRepositoryModule } from '@app/common/modules/space/space.repository.module';
|
||||||
import {
|
import {
|
||||||
InviteSpaceRepository,
|
InviteSpaceRepository,
|
||||||
|
SpaceLinkRepository,
|
||||||
SpaceProductAllocationRepository,
|
SpaceProductAllocationRepository,
|
||||||
SpaceRepository,
|
SpaceRepository,
|
||||||
} from '@app/common/modules/space/repositories';
|
} from '@app/common/modules/space/repositories';
|
||||||
@ -15,12 +16,14 @@ import { CommunityRepository } from '@app/common/modules/community/repositories'
|
|||||||
import { TuyaService } from '@app/common/integrations/tuya/services/tuya.service';
|
import { TuyaService } from '@app/common/integrations/tuya/services/tuya.service';
|
||||||
import { ProjectRepository } from '@app/common/modules/project/repositiories';
|
import { ProjectRepository } from '@app/common/modules/project/repositiories';
|
||||||
import {
|
import {
|
||||||
|
SpaceLinkService,
|
||||||
SpaceService,
|
SpaceService,
|
||||||
SubspaceDeviceService,
|
SubspaceDeviceService,
|
||||||
SubSpaceService,
|
SubSpaceService,
|
||||||
ValidationService,
|
ValidationService,
|
||||||
} from 'src/space/services';
|
} from 'src/space/services';
|
||||||
import { TagService as NewTagService } from 'src/tags/services';
|
import { TagService as NewTagService } from 'src/tags/services';
|
||||||
|
import { TagService } from 'src/space/services/tag';
|
||||||
import {
|
import {
|
||||||
SpaceModelService,
|
SpaceModelService,
|
||||||
SubSpaceModelService,
|
SubSpaceModelService,
|
||||||
@ -61,8 +64,6 @@ import {
|
|||||||
import { SqlLoaderService } from '@app/common/helper/services/sql-loader.service';
|
import { SqlLoaderService } from '@app/common/helper/services/sql-loader.service';
|
||||||
import { OccupancyService } from '@app/common/helper/services/occupancy.service';
|
import { OccupancyService } from '@app/common/helper/services/occupancy.service';
|
||||||
import { AqiDataService } from '@app/common/helper/services/aqi.data.service';
|
import { AqiDataService } from '@app/common/helper/services/aqi.data.service';
|
||||||
import { PresenceSensorDailySpaceRepository } from '@app/common/modules/presence-sensor/repositories';
|
|
||||||
import { AqiSpaceDailyPollutantStatsRepository } from '@app/common/modules/aqi/repositories';
|
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [ConfigModule, SpaceRepositoryModule, UserRepositoryModule],
|
imports: [ConfigModule, SpaceRepositoryModule, UserRepositoryModule],
|
||||||
@ -77,14 +78,16 @@ import { AqiSpaceDailyPollutantStatsRepository } from '@app/common/modules/aqi/r
|
|||||||
ProjectRepository,
|
ProjectRepository,
|
||||||
SpaceService,
|
SpaceService,
|
||||||
InviteSpaceRepository,
|
InviteSpaceRepository,
|
||||||
// Todo: find out why this is needed
|
SpaceLinkService,
|
||||||
SubSpaceService,
|
SubSpaceService,
|
||||||
ValidationService,
|
ValidationService,
|
||||||
NewTagService,
|
NewTagService,
|
||||||
SpaceModelService,
|
SpaceModelService,
|
||||||
SpaceProductAllocationService,
|
SpaceProductAllocationService,
|
||||||
|
SpaceLinkRepository,
|
||||||
SubspaceRepository,
|
SubspaceRepository,
|
||||||
// Todo: find out why this is needed
|
// Todo: find out why this is needed
|
||||||
|
TagService,
|
||||||
SubspaceDeviceService,
|
SubspaceDeviceService,
|
||||||
SubspaceProductAllocationService,
|
SubspaceProductAllocationService,
|
||||||
SpaceModelRepository,
|
SpaceModelRepository,
|
||||||
@ -114,8 +117,6 @@ import { AqiSpaceDailyPollutantStatsRepository } from '@app/common/modules/aqi/r
|
|||||||
SqlLoaderService,
|
SqlLoaderService,
|
||||||
OccupancyService,
|
OccupancyService,
|
||||||
AqiDataService,
|
AqiDataService,
|
||||||
PresenceSensorDailySpaceRepository,
|
|
||||||
AqiSpaceDailyPollutantStatsRepository,
|
|
||||||
],
|
],
|
||||||
exports: [CommunityService, SpacePermissionService],
|
exports: [CommunityService, SpacePermissionService],
|
||||||
})
|
})
|
||||||
|
@ -1,3 +1,4 @@
|
|||||||
|
import { CommunityService } from '../services/community.service';
|
||||||
import {
|
import {
|
||||||
Body,
|
Body,
|
||||||
Controller,
|
Controller,
|
||||||
@ -9,18 +10,17 @@ import {
|
|||||||
Query,
|
Query,
|
||||||
UseGuards,
|
UseGuards,
|
||||||
} from '@nestjs/common';
|
} 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 { AddCommunityDto } from '../dtos/add.community.dto';
|
||||||
import { GetCommunityParams } from '../dtos/get.community.dto';
|
import { GetCommunityParams } from '../dtos/get.community.dto';
|
||||||
import { UpdateCommunityNameDto } from '../dtos/update.community.dto';
|
import { UpdateCommunityNameDto } from '../dtos/update.community.dto';
|
||||||
import { CommunityService } from '../services/community.service';
|
|
||||||
// import { CheckUserCommunityGuard } from 'src/guards/user.community.guard';
|
// import { CheckUserCommunityGuard } from 'src/guards/user.community.guard';
|
||||||
import { ControllerRoute } from '@app/common/constants/controller-route';
|
import { ControllerRoute } from '@app/common/constants/controller-route';
|
||||||
import { BaseResponseDto } from '@app/common/dto/base.response.dto';
|
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 { 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')
|
@ApiTags('Community Module')
|
||||||
@Controller({
|
@Controller({
|
||||||
@ -45,21 +45,6 @@ export class CommunityController {
|
|||||||
return await this.communityService.createCommunity(param, addCommunityDto);
|
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()
|
@ApiBearerAuth()
|
||||||
@UseGuards(PermissionsGuard)
|
@UseGuards(PermissionsGuard)
|
||||||
@Permissions('COMMUNITY_VIEW')
|
@Permissions('COMMUNITY_VIEW')
|
||||||
|
@ -1,7 +1,4 @@
|
|||||||
import {
|
import { ORPHAN_COMMUNITY_NAME } from '@app/common/constants/orphan-constant';
|
||||||
ORPHAN_COMMUNITY_NAME,
|
|
||||||
ORPHAN_SPACE_NAME,
|
|
||||||
} from '@app/common/constants/orphan-constant';
|
|
||||||
import { BaseResponseDto } from '@app/common/dto/base.response.dto';
|
import { BaseResponseDto } from '@app/common/dto/base.response.dto';
|
||||||
import { PageResponse } from '@app/common/dto/pagination.response.dto';
|
import { PageResponse } from '@app/common/dto/pagination.response.dto';
|
||||||
import { SuccessResponseDto } from '@app/common/dto/success.response.dto';
|
import { SuccessResponseDto } from '@app/common/dto/success.response.dto';
|
||||||
@ -25,7 +22,7 @@ import {
|
|||||||
NotFoundException,
|
NotFoundException,
|
||||||
} from '@nestjs/common';
|
} from '@nestjs/common';
|
||||||
import { SpaceService } from 'src/space/services';
|
import { SpaceService } from 'src/space/services';
|
||||||
import { QueryRunner, SelectQueryBuilder } from 'typeorm';
|
import { SelectQueryBuilder } from 'typeorm';
|
||||||
import { AddCommunityDto, GetCommunityParams, ProjectParam } from '../dtos';
|
import { AddCommunityDto, GetCommunityParams, ProjectParam } from '../dtos';
|
||||||
import { UpdateCommunityNameDto } from '../dtos/update.community.dto';
|
import { UpdateCommunityNameDto } from '../dtos/update.community.dto';
|
||||||
|
|
||||||
@ -72,18 +69,12 @@ export class CommunityService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async getCommunityById(
|
async getCommunityById(params: GetCommunityParams): Promise<BaseResponseDto> {
|
||||||
params: GetCommunityParams,
|
|
||||||
queryRunner?: QueryRunner,
|
|
||||||
): Promise<BaseResponseDto> {
|
|
||||||
const { communityUuid, projectUuid } = params;
|
const { communityUuid, projectUuid } = params;
|
||||||
|
|
||||||
await this.validateProject(projectUuid);
|
await this.validateProject(projectUuid);
|
||||||
|
|
||||||
const communityRepository =
|
const community = await this.communityRepository.findOneBy({
|
||||||
queryRunner?.manager.getRepository(CommunityEntity) ||
|
|
||||||
this.communityRepository;
|
|
||||||
const community = await communityRepository.findOneBy({
|
|
||||||
uuid: communityUuid,
|
uuid: communityUuid,
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -171,75 +162,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: `%${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(
|
async updateCommunity(
|
||||||
params: GetCommunityParams,
|
params: GetCommunityParams,
|
||||||
updateCommunityDto: UpdateCommunityNameDto,
|
updateCommunityDto: UpdateCommunityNameDto,
|
||||||
|
@ -1,28 +0,0 @@
|
|||||||
interface BaseCommand {
|
|
||||||
code: string;
|
|
||||||
value: any;
|
|
||||||
}
|
|
||||||
export interface ControlCur2Command extends BaseCommand {
|
|
||||||
code: 'control';
|
|
||||||
value: 'open' | 'close' | 'stop';
|
|
||||||
}
|
|
||||||
export interface ControlCur2PercentCommand extends BaseCommand {
|
|
||||||
code: 'percent_control';
|
|
||||||
value: 10 | 20 | 30 | 40 | 50 | 60 | 70 | 80 | 90 | 100;
|
|
||||||
}
|
|
||||||
export interface ControlCur2AccurateCalibrationCommand extends BaseCommand {
|
|
||||||
code: 'accurate_calibration';
|
|
||||||
value: 'start' | 'end'; // Assuming this is a numeric value for calibration
|
|
||||||
}
|
|
||||||
export interface ControlCur2TDirectionConCommand extends BaseCommand {
|
|
||||||
code: 'control_t_direction_con';
|
|
||||||
value: 'forward' | 'back';
|
|
||||||
}
|
|
||||||
export interface ControlCur2QuickCalibrationCommand extends BaseCommand {
|
|
||||||
code: 'tr_timecon';
|
|
||||||
value: number; // between 10 and 120
|
|
||||||
}
|
|
||||||
export interface ControlCur2MotorModeCommand extends BaseCommand {
|
|
||||||
code: 'elec_machinery_mode';
|
|
||||||
value: 'strong_power' | 'dry_contact';
|
|
||||||
}
|
|
@ -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 { 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')
|
@ApiTags('Device Module')
|
||||||
@Controller({
|
@Controller({
|
||||||
@ -25,7 +25,7 @@ export class DeviceProjectController {
|
|||||||
})
|
})
|
||||||
async getAllDevices(
|
async getAllDevices(
|
||||||
@Param() param: ProjectParam,
|
@Param() param: ProjectParam,
|
||||||
@Query() query: GetDevicesFilterDto,
|
@Query() query: GetDoorLockDevices,
|
||||||
) {
|
) {
|
||||||
return await this.deviceService.getAllDevices(param, query);
|
return await this.deviceService.getAllDevices(param, query);
|
||||||
}
|
}
|
||||||
|
@ -1,41 +1,39 @@
|
|||||||
import { ControllerRoute } from '@app/common/constants/controller-route';
|
import { DeviceService } from '../services/device.service';
|
||||||
import { EnableDisableStatusEnum } from '@app/common/constants/days.enum';
|
|
||||||
import { RoleType } from '@app/common/constants/role.type.enum';
|
|
||||||
import { BaseResponseDto } from '@app/common/dto/base.response.dto';
|
|
||||||
import {
|
import {
|
||||||
Body,
|
Body,
|
||||||
Controller,
|
Controller,
|
||||||
Delete,
|
|
||||||
Get,
|
Get,
|
||||||
Param,
|
|
||||||
Post,
|
Post,
|
||||||
Put,
|
|
||||||
Query,
|
Query,
|
||||||
Req,
|
Param,
|
||||||
UnauthorizedException,
|
|
||||||
UseGuards,
|
UseGuards,
|
||||||
|
Put,
|
||||||
|
Delete,
|
||||||
|
Req,
|
||||||
} from '@nestjs/common';
|
} from '@nestjs/common';
|
||||||
import { ApiBearerAuth, ApiOperation, ApiTags } from '@nestjs/swagger';
|
import { ApiTags, ApiBearerAuth, ApiOperation } from '@nestjs/swagger';
|
||||||
import { Permissions } from 'src/decorators/permissions.decorator';
|
|
||||||
import { PermissionsGuard } from 'src/guards/permissions.guard';
|
|
||||||
import { CheckRoomGuard } from 'src/guards/room.guard';
|
|
||||||
import { CheckFourAndSixSceneDeviceTypeGuard } from 'src/guards/scene.device.type.guard';
|
|
||||||
import {
|
import {
|
||||||
AddDeviceDto,
|
AddDeviceDto,
|
||||||
AddSceneToFourSceneDeviceDto,
|
AddSceneToFourSceneDeviceDto,
|
||||||
AssignDeviceToSpaceDto,
|
AssignDeviceToSpaceDto,
|
||||||
UpdateDeviceDto,
|
UpdateDeviceDto,
|
||||||
} from '../dtos/add.device.dto';
|
} from '../dtos/add.device.dto';
|
||||||
|
import { GetDeviceLogsDto } from '../dtos/get.device.dto';
|
||||||
import {
|
import {
|
||||||
|
ControlDeviceDto,
|
||||||
BatchControlDevicesDto,
|
BatchControlDevicesDto,
|
||||||
BatchStatusDevicesDto,
|
BatchStatusDevicesDto,
|
||||||
ControlDeviceDto,
|
|
||||||
GetSceneFourSceneDeviceDto,
|
GetSceneFourSceneDeviceDto,
|
||||||
} from '../dtos/control.device.dto';
|
} from '../dtos/control.device.dto';
|
||||||
import { DeleteSceneFromSceneDeviceDto } from '../dtos/delete.device.dto';
|
import { CheckRoomGuard } from 'src/guards/room.guard';
|
||||||
|
import { EnableDisableStatusEnum } from '@app/common/constants/days.enum';
|
||||||
|
import { CheckFourAndSixSceneDeviceTypeGuard } from 'src/guards/scene.device.type.guard';
|
||||||
|
import { ControllerRoute } from '@app/common/constants/controller-route';
|
||||||
|
import { BaseResponseDto } from '@app/common/dto/base.response.dto';
|
||||||
import { DeviceSceneParamDto } from '../dtos/device.param.dto';
|
import { DeviceSceneParamDto } from '../dtos/device.param.dto';
|
||||||
import { GetDeviceLogsDto } from '../dtos/get.device.dto';
|
import { DeleteSceneFromSceneDeviceDto } from '../dtos/delete.device.dto';
|
||||||
import { DeviceService } from '../services/device.service';
|
import { PermissionsGuard } from 'src/guards/permissions.guard';
|
||||||
|
import { Permissions } from 'src/decorators/permissions.decorator';
|
||||||
|
|
||||||
@ApiTags('Device Module')
|
@ApiTags('Device Module')
|
||||||
@Controller({
|
@Controller({
|
||||||
@ -342,22 +340,4 @@ export class DeviceController {
|
|||||||
projectUuid,
|
projectUuid,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ApiBearerAuth()
|
|
||||||
@UseGuards(PermissionsGuard)
|
|
||||||
@Permissions('DEVICE_UPDATE')
|
|
||||||
@Post('/populate-tuya-const-uuids')
|
|
||||||
@ApiOperation({
|
|
||||||
summary: ControllerRoute.DEVICE.ACTIONS.POPULATE_TUYA_CONST_UUID_SUMMARY,
|
|
||||||
description:
|
|
||||||
ControllerRoute.DEVICE.ACTIONS.POPULATE_TUYA_CONST_UUID_DESCRIPTION,
|
|
||||||
})
|
|
||||||
async populateTuyaConstUuid(@Req() req: any): Promise<void> {
|
|
||||||
const userUuid = req['user']?.userUuid;
|
|
||||||
const userRole = req['user']?.role;
|
|
||||||
if (!userUuid || (userRole && userRole !== RoleType.SUPER_ADMIN)) {
|
|
||||||
throw new UnauthorizedException('Unauthorized to perform this action');
|
|
||||||
}
|
|
||||||
return this.deviceService.addTuyaConstUuidToDevices();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
@ -18,14 +18,6 @@ export class AddDeviceDto {
|
|||||||
@IsNotEmpty()
|
@IsNotEmpty()
|
||||||
public spaceUuid: string;
|
public spaceUuid: string;
|
||||||
|
|
||||||
@ApiProperty({
|
|
||||||
description: 'tagUuid',
|
|
||||||
required: true,
|
|
||||||
})
|
|
||||||
@IsString()
|
|
||||||
@IsNotEmpty()
|
|
||||||
public tagUuid: string;
|
|
||||||
|
|
||||||
@ApiProperty({
|
@ApiProperty({
|
||||||
description: 'deviceName',
|
description: 'deviceName',
|
||||||
required: true,
|
required: true,
|
||||||
|
@ -1,6 +1,5 @@
|
|||||||
import { DeviceTypeEnum } from '@app/common/constants/device-type.enum';
|
import { DeviceTypeEnum } from '@app/common/constants/device-type.enum';
|
||||||
import { ApiProperty } from '@nestjs/swagger';
|
import { ApiProperty } from '@nestjs/swagger';
|
||||||
import { Transform } from 'class-transformer';
|
|
||||||
import {
|
import {
|
||||||
IsEnum,
|
IsEnum,
|
||||||
IsNotEmpty,
|
IsNotEmpty,
|
||||||
@ -42,7 +41,16 @@ export class GetDeviceLogsDto {
|
|||||||
@IsOptional()
|
@IsOptional()
|
||||||
public endTime: string;
|
public endTime: string;
|
||||||
}
|
}
|
||||||
|
export class GetDoorLockDevices {
|
||||||
|
@ApiProperty({
|
||||||
|
description: 'Device Type',
|
||||||
|
enum: DeviceTypeEnum,
|
||||||
|
required: false,
|
||||||
|
})
|
||||||
|
@IsEnum(DeviceTypeEnum)
|
||||||
|
@IsOptional()
|
||||||
|
public deviceType: DeviceTypeEnum;
|
||||||
|
}
|
||||||
export class GetDevicesBySpaceOrCommunityDto {
|
export class GetDevicesBySpaceOrCommunityDto {
|
||||||
@ApiProperty({
|
@ApiProperty({
|
||||||
description: 'Device Product Type',
|
description: 'Device Product Type',
|
||||||
@ -64,44 +72,3 @@ export class GetDevicesBySpaceOrCommunityDto {
|
|||||||
@IsNotEmpty({ message: 'Either spaceUuid or communityUuid must be provided' })
|
@IsNotEmpty({ message: 'Either spaceUuid or communityUuid must be provided' })
|
||||||
requireEither?: never; // This ensures at least one of them is 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()
|
|
||||||
@Transform(({ value }) => {
|
|
||||||
if (!Array.isArray(value)) {
|
|
||||||
return [value];
|
|
||||||
}
|
|
||||||
return value;
|
|
||||||
})
|
|
||||||
@IsUUID('4', { each: true })
|
|
||||||
public spaces?: string[];
|
|
||||||
|
|
||||||
@ApiProperty({
|
|
||||||
description: 'List of Community IDs to filter devices',
|
|
||||||
required: false,
|
|
||||||
example: ['60d21b4667d0d8992e610c85', '60d21b4967d0d8992e610c86'],
|
|
||||||
})
|
|
||||||
@Transform(({ value }) => {
|
|
||||||
if (!Array.isArray(value)) {
|
|
||||||
return [value];
|
|
||||||
}
|
|
||||||
return value;
|
|
||||||
})
|
|
||||||
@IsOptional()
|
|
||||||
@IsUUID('4', { each: true })
|
|
||||||
public communities?: string[];
|
|
||||||
}
|
|
||||||
|
File diff suppressed because it is too large
Load Diff
@ -30,8 +30,6 @@ import { SqlLoaderService } from '@app/common/helper/services/sql-loader.service
|
|||||||
import { OccupancyService } from '@app/common/helper/services/occupancy.service';
|
import { OccupancyService } from '@app/common/helper/services/occupancy.service';
|
||||||
import { CommunityRepository } from '@app/common/modules/community/repositories';
|
import { CommunityRepository } from '@app/common/modules/community/repositories';
|
||||||
import { AqiDataService } from '@app/common/helper/services/aqi.data.service';
|
import { AqiDataService } from '@app/common/helper/services/aqi.data.service';
|
||||||
import { PresenceSensorDailySpaceRepository } from '@app/common/modules/presence-sensor/repositories';
|
|
||||||
import { AqiSpaceDailyPollutantStatsRepository } from '@app/common/modules/aqi/repositories';
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [ConfigModule, DeviceRepositoryModule],
|
imports: [ConfigModule, DeviceRepositoryModule],
|
||||||
controllers: [DoorLockController],
|
controllers: [DoorLockController],
|
||||||
@ -60,8 +58,6 @@ import { AqiSpaceDailyPollutantStatsRepository } from '@app/common/modules/aqi/r
|
|||||||
OccupancyService,
|
OccupancyService,
|
||||||
CommunityRepository,
|
CommunityRepository,
|
||||||
AqiDataService,
|
AqiDataService,
|
||||||
PresenceSensorDailySpaceRepository,
|
|
||||||
AqiSpaceDailyPollutantStatsRepository,
|
|
||||||
],
|
],
|
||||||
exports: [DoorLockService],
|
exports: [DoorLockService],
|
||||||
})
|
})
|
||||||
|
@ -28,8 +28,6 @@ import { SqlLoaderService } from '@app/common/helper/services/sql-loader.service
|
|||||||
import { OccupancyService } from '@app/common/helper/services/occupancy.service';
|
import { OccupancyService } from '@app/common/helper/services/occupancy.service';
|
||||||
import { CommunityRepository } from '@app/common/modules/community/repositories';
|
import { CommunityRepository } from '@app/common/modules/community/repositories';
|
||||||
import { AqiDataService } from '@app/common/helper/services/aqi.data.service';
|
import { AqiDataService } from '@app/common/helper/services/aqi.data.service';
|
||||||
import { PresenceSensorDailySpaceRepository } from '@app/common/modules/presence-sensor/repositories';
|
|
||||||
import { AqiSpaceDailyPollutantStatsRepository } from '@app/common/modules/aqi/repositories';
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [ConfigModule, DeviceRepositoryModule],
|
imports: [ConfigModule, DeviceRepositoryModule],
|
||||||
controllers: [GroupController],
|
controllers: [GroupController],
|
||||||
@ -57,8 +55,6 @@ import { AqiSpaceDailyPollutantStatsRepository } from '@app/common/modules/aqi/r
|
|||||||
OccupancyService,
|
OccupancyService,
|
||||||
CommunityRepository,
|
CommunityRepository,
|
||||||
AqiDataService,
|
AqiDataService,
|
||||||
PresenceSensorDailySpaceRepository,
|
|
||||||
AqiSpaceDailyPollutantStatsRepository,
|
|
||||||
],
|
],
|
||||||
exports: [GroupService],
|
exports: [GroupService],
|
||||||
})
|
})
|
||||||
|
@ -5,7 +5,6 @@ import {
|
|||||||
IsNotEmpty,
|
IsNotEmpty,
|
||||||
IsOptional,
|
IsOptional,
|
||||||
IsString,
|
IsString,
|
||||||
IsUUID,
|
|
||||||
} from 'class-validator';
|
} from 'class-validator';
|
||||||
|
|
||||||
export class AddUserInvitationDto {
|
export class AddUserInvitationDto {
|
||||||
@ -45,15 +44,6 @@ export class AddUserInvitationDto {
|
|||||||
@IsOptional()
|
@IsOptional()
|
||||||
public jobTitle?: string;
|
public jobTitle?: string;
|
||||||
|
|
||||||
@ApiProperty({
|
|
||||||
description: 'The company name of the user',
|
|
||||||
example: 'Tech Corp',
|
|
||||||
required: false,
|
|
||||||
})
|
|
||||||
@IsString()
|
|
||||||
@IsOptional()
|
|
||||||
public companyName?: string;
|
|
||||||
|
|
||||||
@ApiProperty({
|
@ApiProperty({
|
||||||
description: 'The phone number of the user',
|
description: 'The phone number of the user',
|
||||||
example: '+1234567890',
|
example: '+1234567890',
|
||||||
@ -68,7 +58,7 @@ export class AddUserInvitationDto {
|
|||||||
example: 'd290f1ee-6c54-4b01-90e6-d701748f0851',
|
example: 'd290f1ee-6c54-4b01-90e6-d701748f0851',
|
||||||
required: true,
|
required: true,
|
||||||
})
|
})
|
||||||
@IsUUID('4')
|
@IsString()
|
||||||
@IsNotEmpty()
|
@IsNotEmpty()
|
||||||
public roleUuid: string;
|
public roleUuid: string;
|
||||||
@ApiProperty({
|
@ApiProperty({
|
||||||
@ -76,17 +66,15 @@ export class AddUserInvitationDto {
|
|||||||
example: 'd290f1ee-6c54-4b01-90e6-d701748f0851',
|
example: 'd290f1ee-6c54-4b01-90e6-d701748f0851',
|
||||||
required: true,
|
required: true,
|
||||||
})
|
})
|
||||||
@IsUUID('4')
|
@IsString()
|
||||||
@IsNotEmpty()
|
@IsNotEmpty()
|
||||||
public projectUuid: string;
|
public projectUuid: string;
|
||||||
|
|
||||||
@ApiProperty({
|
@ApiProperty({
|
||||||
description: 'The array of space UUIDs (at least one required)',
|
description: 'The array of space UUIDs (at least one required)',
|
||||||
example: ['b5f3c9d2-58b7-4377-b3f7-60acb711d5d9'],
|
example: ['b5f3c9d2-58b7-4377-b3f7-60acb711d5d9'],
|
||||||
required: true,
|
required: true,
|
||||||
})
|
})
|
||||||
@IsArray()
|
@IsArray()
|
||||||
@IsUUID('4', { each: true })
|
|
||||||
@ArrayMinSize(1)
|
@ArrayMinSize(1)
|
||||||
public spaceUuids: string[];
|
public spaceUuids: string[];
|
||||||
constructor(dto: Partial<AddUserInvitationDto>) {
|
constructor(dto: Partial<AddUserInvitationDto>) {
|
||||||
|
@ -1,10 +1,78 @@
|
|||||||
import { ApiProperty, OmitType } from '@nestjs/swagger';
|
import { ApiProperty } from '@nestjs/swagger';
|
||||||
import { IsBoolean, IsNotEmpty, IsString } from 'class-validator';
|
import {
|
||||||
import { AddUserInvitationDto } from './add.invite-user.dto';
|
ArrayMinSize,
|
||||||
|
IsArray,
|
||||||
|
IsBoolean,
|
||||||
|
IsNotEmpty,
|
||||||
|
IsOptional,
|
||||||
|
IsString,
|
||||||
|
} from 'class-validator';
|
||||||
|
|
||||||
export class UpdateUserInvitationDto extends OmitType(AddUserInvitationDto, [
|
export class UpdateUserInvitationDto {
|
||||||
'email',
|
@ApiProperty({
|
||||||
]) {}
|
description: 'The first name of the user',
|
||||||
|
example: 'John',
|
||||||
|
required: true,
|
||||||
|
})
|
||||||
|
@IsString()
|
||||||
|
@IsNotEmpty()
|
||||||
|
public firstName: string;
|
||||||
|
|
||||||
|
@ApiProperty({
|
||||||
|
description: 'The last name of the user',
|
||||||
|
example: 'Doe',
|
||||||
|
required: true,
|
||||||
|
})
|
||||||
|
@IsString()
|
||||||
|
@IsNotEmpty()
|
||||||
|
public lastName: string;
|
||||||
|
|
||||||
|
@ApiProperty({
|
||||||
|
description: 'The job title of the user',
|
||||||
|
example: 'Software Engineer',
|
||||||
|
required: false,
|
||||||
|
})
|
||||||
|
@IsString()
|
||||||
|
@IsOptional()
|
||||||
|
public jobTitle?: string;
|
||||||
|
|
||||||
|
@ApiProperty({
|
||||||
|
description: 'The phone number of the user',
|
||||||
|
example: '+1234567890',
|
||||||
|
required: false,
|
||||||
|
})
|
||||||
|
@IsString()
|
||||||
|
@IsOptional()
|
||||||
|
public phoneNumber?: string;
|
||||||
|
|
||||||
|
@ApiProperty({
|
||||||
|
description: 'The role uuid of the user',
|
||||||
|
example: 'd290f1ee-6c54-4b01-90e6-d701748f0851',
|
||||||
|
required: true,
|
||||||
|
})
|
||||||
|
@IsString()
|
||||||
|
@IsNotEmpty()
|
||||||
|
public roleUuid: string;
|
||||||
|
@ApiProperty({
|
||||||
|
description: 'The project uuid of the user',
|
||||||
|
example: 'd290f1ee-6c54-4b01-90e6-d701748f0851',
|
||||||
|
required: true,
|
||||||
|
})
|
||||||
|
@IsString()
|
||||||
|
@IsNotEmpty()
|
||||||
|
public projectUuid: string;
|
||||||
|
@ApiProperty({
|
||||||
|
description: 'The array of space UUIDs (at least one required)',
|
||||||
|
example: ['b5f3c9d2-58b7-4377-b3f7-60acb711d5d9'],
|
||||||
|
required: true,
|
||||||
|
})
|
||||||
|
@IsArray()
|
||||||
|
@ArrayMinSize(1)
|
||||||
|
public spaceUuids: string[];
|
||||||
|
constructor(dto: Partial<UpdateUserInvitationDto>) {
|
||||||
|
Object.assign(this, dto);
|
||||||
|
}
|
||||||
|
}
|
||||||
export class DisableUserInvitationDto {
|
export class DisableUserInvitationDto {
|
||||||
@ApiProperty({
|
@ApiProperty({
|
||||||
description: 'The disable status of the user',
|
description: 'The disable status of the user',
|
||||||
|
@ -38,6 +38,7 @@ import {
|
|||||||
} from '@app/common/modules/scene/repositories';
|
} from '@app/common/modules/scene/repositories';
|
||||||
import {
|
import {
|
||||||
InviteSpaceRepository,
|
InviteSpaceRepository,
|
||||||
|
SpaceLinkRepository,
|
||||||
SpaceProductAllocationRepository,
|
SpaceProductAllocationRepository,
|
||||||
SpaceRepository,
|
SpaceRepository,
|
||||||
} from '@app/common/modules/space';
|
} from '@app/common/modules/space';
|
||||||
@ -70,6 +71,7 @@ import {
|
|||||||
import { SpaceModelProductAllocationService } from 'src/space-model/services/space-model-product-allocation.service';
|
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 { SubspaceModelProductAllocationService } from 'src/space-model/services/subspace/subspace-model-product-allocation.service';
|
||||||
import {
|
import {
|
||||||
|
SpaceLinkService,
|
||||||
SpaceService,
|
SpaceService,
|
||||||
SpaceUserService,
|
SpaceUserService,
|
||||||
SubspaceDeviceService,
|
SubspaceDeviceService,
|
||||||
@ -81,8 +83,6 @@ import { SubspaceProductAllocationService } from 'src/space/services/subspace/su
|
|||||||
import { TagService as NewTagService } from 'src/tags/services';
|
import { TagService as NewTagService } from 'src/tags/services';
|
||||||
import { UserDevicePermissionService } from 'src/user-device-permission/services';
|
import { UserDevicePermissionService } from 'src/user-device-permission/services';
|
||||||
import { UserService, UserSpaceService } from 'src/users/services';
|
import { UserService, UserSpaceService } from 'src/users/services';
|
||||||
import { PresenceSensorDailySpaceRepository } from '@app/common/modules/presence-sensor/repositories';
|
|
||||||
import { AqiSpaceDailyPollutantStatsRepository } from '@app/common/modules/aqi/repositories';
|
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [ConfigModule, InviteUserRepositoryModule, CommunityModule],
|
imports: [ConfigModule, InviteUserRepositoryModule, CommunityModule],
|
||||||
@ -115,11 +115,13 @@ import { AqiSpaceDailyPollutantStatsRepository } from '@app/common/modules/aqi/r
|
|||||||
TimeZoneRepository,
|
TimeZoneRepository,
|
||||||
SpaceService,
|
SpaceService,
|
||||||
InviteSpaceRepository,
|
InviteSpaceRepository,
|
||||||
|
SpaceLinkService,
|
||||||
SubSpaceService,
|
SubSpaceService,
|
||||||
ValidationService,
|
ValidationService,
|
||||||
NewTagService,
|
NewTagService,
|
||||||
SpaceModelService,
|
SpaceModelService,
|
||||||
SpaceProductAllocationService,
|
SpaceProductAllocationService,
|
||||||
|
SpaceLinkRepository,
|
||||||
SubspaceRepository,
|
SubspaceRepository,
|
||||||
SubspaceDeviceService,
|
SubspaceDeviceService,
|
||||||
SubspaceProductAllocationService,
|
SubspaceProductAllocationService,
|
||||||
@ -150,8 +152,6 @@ import { AqiSpaceDailyPollutantStatsRepository } from '@app/common/modules/aqi/r
|
|||||||
SqlLoaderService,
|
SqlLoaderService,
|
||||||
OccupancyService,
|
OccupancyService,
|
||||||
AqiDataService,
|
AqiDataService,
|
||||||
PresenceSensorDailySpaceRepository,
|
|
||||||
AqiSpaceDailyPollutantStatsRepository,
|
|
||||||
],
|
],
|
||||||
exports: [InviteUserService],
|
exports: [InviteUserService],
|
||||||
})
|
})
|
||||||
|
@ -8,8 +8,6 @@ import {
|
|||||||
InviteUserRepository,
|
InviteUserRepository,
|
||||||
InviteUserSpaceRepository,
|
InviteUserSpaceRepository,
|
||||||
} from '@app/common/modules/Invite-user/repositiories';
|
} from '@app/common/modules/Invite-user/repositiories';
|
||||||
import { ProjectEntity } from '@app/common/modules/project/entities';
|
|
||||||
import { RoleTypeEntity } from '@app/common/modules/role-type/entities';
|
|
||||||
import { RoleTypeRepository } from '@app/common/modules/role-type/repositories';
|
import { RoleTypeRepository } from '@app/common/modules/role-type/repositories';
|
||||||
import { SpaceRepository } from '@app/common/modules/space';
|
import { SpaceRepository } from '@app/common/modules/space';
|
||||||
import { SpaceEntity } from '@app/common/modules/space/entities/space.entity';
|
import { SpaceEntity } from '@app/common/modules/space/entities/space.entity';
|
||||||
@ -63,7 +61,6 @@ export class InviteUserService {
|
|||||||
lastName,
|
lastName,
|
||||||
email,
|
email,
|
||||||
jobTitle,
|
jobTitle,
|
||||||
companyName,
|
|
||||||
phoneNumber,
|
phoneNumber,
|
||||||
roleUuid,
|
roleUuid,
|
||||||
spaceUuids,
|
spaceUuids,
|
||||||
@ -93,8 +90,6 @@ export class InviteUserService {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
await this.checkRole(roleUuid, queryRunner);
|
|
||||||
await this.checkProject(projectUuid, queryRunner);
|
|
||||||
// Validate spaces
|
// Validate spaces
|
||||||
const validSpaces = await this.validateSpaces(
|
const validSpaces = await this.validateSpaces(
|
||||||
spaceUuids,
|
spaceUuids,
|
||||||
@ -107,7 +102,6 @@ export class InviteUserService {
|
|||||||
lastName,
|
lastName,
|
||||||
email,
|
email,
|
||||||
jobTitle,
|
jobTitle,
|
||||||
companyName,
|
|
||||||
phoneNumber,
|
phoneNumber,
|
||||||
roleType: { uuid: roleUuid },
|
roleType: { uuid: roleUuid },
|
||||||
status: UserStatusEnum.INVITED,
|
status: UserStatusEnum.INVITED,
|
||||||
@ -117,7 +111,6 @@ export class InviteUserService {
|
|||||||
});
|
});
|
||||||
|
|
||||||
const invitedUser = await queryRunner.manager.save(inviteUser);
|
const invitedUser = await queryRunner.manager.save(inviteUser);
|
||||||
const invitedRoleType = await this.getRoleTypeByUuid(roleUuid);
|
|
||||||
|
|
||||||
// Link user to spaces
|
// Link user to spaces
|
||||||
const spacePromises = validSpaces.map(async (space) => {
|
const spacePromises = validSpaces.map(async (space) => {
|
||||||
@ -135,7 +128,7 @@ export class InviteUserService {
|
|||||||
await this.emailService.sendEmailWithInvitationTemplate(email, {
|
await this.emailService.sendEmailWithInvitationTemplate(email, {
|
||||||
name: firstName,
|
name: firstName,
|
||||||
invitationCode,
|
invitationCode,
|
||||||
role: invitedRoleType.replace(/_/g, ' '),
|
role: roleType,
|
||||||
spacesList: spaceNames,
|
spacesList: spaceNames,
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -163,6 +156,185 @@ export class InviteUserService {
|
|||||||
await queryRunner.release();
|
await queryRunner.release();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
private async validateSpaces(
|
||||||
|
spaceUuids: string[],
|
||||||
|
entityManager: EntityManager,
|
||||||
|
): Promise<SpaceEntity[]> {
|
||||||
|
const spaceRepo = entityManager.getRepository(SpaceEntity);
|
||||||
|
|
||||||
|
const validSpaces = await spaceRepo.find({
|
||||||
|
where: { uuid: In(spaceUuids) },
|
||||||
|
});
|
||||||
|
|
||||||
|
if (validSpaces.length !== spaceUuids.length) {
|
||||||
|
const validSpaceUuids = validSpaces.map((space) => space.uuid);
|
||||||
|
const invalidSpaceUuids = spaceUuids.filter(
|
||||||
|
(uuid) => !validSpaceUuids.includes(uuid),
|
||||||
|
);
|
||||||
|
throw new HttpException(
|
||||||
|
`Invalid space UUIDs: ${invalidSpaceUuids.join(', ')}`,
|
||||||
|
HttpStatus.BAD_REQUEST,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return validSpaces;
|
||||||
|
}
|
||||||
|
|
||||||
|
async checkEmailAndProject(dto: CheckEmailDto): Promise<BaseResponseDto> {
|
||||||
|
const { email } = dto;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const user = await this.userRepository.findOne({
|
||||||
|
where: { email },
|
||||||
|
relations: ['project'],
|
||||||
|
});
|
||||||
|
this.validateUserOrInvite(user, 'User');
|
||||||
|
const invitedUser = await this.inviteUserRepository.findOne({
|
||||||
|
where: { email },
|
||||||
|
relations: ['project'],
|
||||||
|
});
|
||||||
|
this.validateUserOrInvite(invitedUser, 'Invited User');
|
||||||
|
|
||||||
|
return new SuccessResponseDto({
|
||||||
|
statusCode: HttpStatus.OK,
|
||||||
|
success: true,
|
||||||
|
message: 'Valid email',
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error checking email and project:', error);
|
||||||
|
throw new HttpException(
|
||||||
|
error.message ||
|
||||||
|
'An unexpected error occurred while checking the email',
|
||||||
|
error.status || HttpStatus.INTERNAL_SERVER_ERROR,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private validateUserOrInvite(user: any, userType: string): void {
|
||||||
|
if (user) {
|
||||||
|
if (!user.isActive) {
|
||||||
|
throw new HttpException(
|
||||||
|
`${userType} is deleted`,
|
||||||
|
HttpStatus.BAD_REQUEST,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (user.project) {
|
||||||
|
throw new HttpException(
|
||||||
|
`${userType} already has a project`,
|
||||||
|
HttpStatus.BAD_REQUEST,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async activationCode(dto: ActivateCodeDto): Promise<BaseResponseDto> {
|
||||||
|
const { activationCode, userUuid } = dto;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const user = await this.getUser(userUuid);
|
||||||
|
|
||||||
|
const invitedUser = await this.inviteUserRepository.findOne({
|
||||||
|
where: {
|
||||||
|
email: user.email,
|
||||||
|
status: UserStatusEnum.INVITED,
|
||||||
|
isActive: true,
|
||||||
|
},
|
||||||
|
relations: ['project', 'spaces.space.community', 'roleType'],
|
||||||
|
});
|
||||||
|
|
||||||
|
if (invitedUser) {
|
||||||
|
if (invitedUser.invitationCode !== activationCode) {
|
||||||
|
throw new HttpException(
|
||||||
|
'Invalid activation code',
|
||||||
|
HttpStatus.BAD_REQUEST,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Handle invited user with valid activation code
|
||||||
|
await this.handleInvitedUser(user, invitedUser);
|
||||||
|
} else {
|
||||||
|
// Handle case for non-invited user
|
||||||
|
await this.handleNonInvitedUser(activationCode, userUuid);
|
||||||
|
}
|
||||||
|
return new SuccessResponseDto({
|
||||||
|
statusCode: HttpStatus.OK,
|
||||||
|
success: true,
|
||||||
|
message: 'The code has been successfully activated',
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error activating the code:', error);
|
||||||
|
throw new HttpException(
|
||||||
|
error.message ||
|
||||||
|
'An unexpected error occurred while activating the code',
|
||||||
|
error.status || HttpStatus.INTERNAL_SERVER_ERROR,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async getUser(userUuid: string): Promise<UserEntity> {
|
||||||
|
const user = await this.userRepository.findOne({
|
||||||
|
where: { uuid: userUuid, isActive: true, isUserVerified: true },
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!user) {
|
||||||
|
throw new HttpException('User not found', HttpStatus.NOT_FOUND);
|
||||||
|
}
|
||||||
|
return user;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async handleNonInvitedUser(
|
||||||
|
activationCode: string,
|
||||||
|
userUuid: string,
|
||||||
|
): Promise<void> {
|
||||||
|
await this.userSpaceService.verifyCodeAndAddUserSpace(
|
||||||
|
{ inviteCode: activationCode },
|
||||||
|
userUuid,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async handleInvitedUser(
|
||||||
|
user: UserEntity,
|
||||||
|
invitedUser: InviteUserEntity,
|
||||||
|
): Promise<void> {
|
||||||
|
for (const invitedSpace of invitedUser.spaces) {
|
||||||
|
try {
|
||||||
|
const deviceUUIDs = await this.userSpaceService.getDeviceUUIDsForSpace(
|
||||||
|
invitedSpace.space.uuid,
|
||||||
|
);
|
||||||
|
|
||||||
|
await this.userSpaceService.addUserPermissionsToDevices(
|
||||||
|
user.uuid,
|
||||||
|
deviceUUIDs,
|
||||||
|
);
|
||||||
|
|
||||||
|
await this.spaceUserService.associateUserToSpace({
|
||||||
|
communityUuid: invitedSpace.space.community.uuid,
|
||||||
|
spaceUuid: invitedSpace.space.uuid,
|
||||||
|
userUuid: user.uuid,
|
||||||
|
projectUuid: invitedUser.project.uuid,
|
||||||
|
});
|
||||||
|
} catch (spaceError) {
|
||||||
|
console.error(
|
||||||
|
`Error processing space ${invitedSpace.space.uuid}:`,
|
||||||
|
spaceError,
|
||||||
|
);
|
||||||
|
continue; // Skip to the next space
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Update invited user and associated user data
|
||||||
|
await this.inviteUserRepository.update(
|
||||||
|
{ uuid: invitedUser.uuid },
|
||||||
|
{ status: UserStatusEnum.ACTIVE, user: { uuid: user.uuid } },
|
||||||
|
);
|
||||||
|
await this.userRepository.update(
|
||||||
|
{ uuid: user.uuid },
|
||||||
|
{
|
||||||
|
project: { uuid: invitedUser.project.uuid },
|
||||||
|
roleType: { uuid: invitedUser.roleType.uuid },
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
async updateUserInvitation(
|
async updateUserInvitation(
|
||||||
dto: UpdateUserInvitationDto,
|
dto: UpdateUserInvitationDto,
|
||||||
@ -184,9 +356,6 @@ export class InviteUserService {
|
|||||||
throw new HttpException('User not found', HttpStatus.NOT_FOUND);
|
throw new HttpException('User not found', HttpStatus.NOT_FOUND);
|
||||||
}
|
}
|
||||||
|
|
||||||
await this.checkRole(dto.roleUuid, queryRunner);
|
|
||||||
await this.checkProject(projectUuid, queryRunner);
|
|
||||||
|
|
||||||
// Perform update actions if status is 'INVITED'
|
// Perform update actions if status is 'INVITED'
|
||||||
if (userOldData.status === UserStatusEnum.INVITED) {
|
if (userOldData.status === UserStatusEnum.INVITED) {
|
||||||
await this.updateWhenUserIsInvite(queryRunner, dto, invitedUserUuid);
|
await this.updateWhenUserIsInvite(queryRunner, dto, invitedUserUuid);
|
||||||
@ -269,7 +438,174 @@ export class InviteUserService {
|
|||||||
await queryRunner.release();
|
await queryRunner.release();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
private async getRoleTypeByUuid(roleUuid: string) {
|
||||||
|
const role = await this.roleTypeRepository.findOne({
|
||||||
|
where: { uuid: roleUuid },
|
||||||
|
});
|
||||||
|
|
||||||
|
return role.type;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async updateWhenUserIsInvite(
|
||||||
|
queryRunner: QueryRunner,
|
||||||
|
dto: UpdateUserInvitationDto,
|
||||||
|
invitedUserUuid: string,
|
||||||
|
): Promise<void> {
|
||||||
|
const { firstName, lastName, jobTitle, phoneNumber, roleUuid, spaceUuids } =
|
||||||
|
dto;
|
||||||
|
|
||||||
|
// Update user invitation details
|
||||||
|
await queryRunner.manager.update(
|
||||||
|
this.inviteUserRepository.target,
|
||||||
|
{ uuid: invitedUserUuid },
|
||||||
|
{
|
||||||
|
firstName,
|
||||||
|
lastName,
|
||||||
|
jobTitle,
|
||||||
|
phoneNumber,
|
||||||
|
roleType: { uuid: roleUuid },
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
// Remove old space associations
|
||||||
|
await queryRunner.manager.delete(this.inviteUserSpaceRepository.target, {
|
||||||
|
inviteUser: { uuid: invitedUserUuid },
|
||||||
|
});
|
||||||
|
|
||||||
|
// Save new space associations
|
||||||
|
const spaceData = spaceUuids.map((spaceUuid) => ({
|
||||||
|
inviteUser: { uuid: invitedUserUuid },
|
||||||
|
space: { uuid: spaceUuid },
|
||||||
|
}));
|
||||||
|
await queryRunner.manager.save(
|
||||||
|
this.inviteUserSpaceRepository.target,
|
||||||
|
spaceData,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
private async updateWhenUserIsActive(
|
||||||
|
queryRunner: QueryRunner,
|
||||||
|
dto: UpdateUserInvitationDto,
|
||||||
|
invitedUserUuid: string,
|
||||||
|
): Promise<void> {
|
||||||
|
const {
|
||||||
|
firstName,
|
||||||
|
lastName,
|
||||||
|
jobTitle,
|
||||||
|
phoneNumber,
|
||||||
|
roleUuid,
|
||||||
|
spaceUuids,
|
||||||
|
projectUuid,
|
||||||
|
} = dto;
|
||||||
|
|
||||||
|
const userData = await this.inviteUserRepository.findOne({
|
||||||
|
where: { uuid: invitedUserUuid },
|
||||||
|
relations: ['user.userSpaces.space', 'user.userSpaces.space.community'],
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!userData) {
|
||||||
|
throw new HttpException(
|
||||||
|
`User with invitedUserUuid ${invitedUserUuid} not found`,
|
||||||
|
HttpStatus.NOT_FOUND,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Update user details
|
||||||
|
await queryRunner.manager.update(
|
||||||
|
this.inviteUserRepository.target,
|
||||||
|
{ uuid: invitedUserUuid },
|
||||||
|
{
|
||||||
|
firstName,
|
||||||
|
lastName,
|
||||||
|
jobTitle,
|
||||||
|
phoneNumber,
|
||||||
|
roleType: { uuid: roleUuid },
|
||||||
|
},
|
||||||
|
);
|
||||||
|
await this.userRepository.update(
|
||||||
|
{ uuid: userData.user.uuid },
|
||||||
|
{
|
||||||
|
roleType: { uuid: roleUuid },
|
||||||
|
},
|
||||||
|
);
|
||||||
|
// Disassociate the user from all current spaces
|
||||||
|
const disassociatePromises = userData.user.userSpaces.map((userSpace) =>
|
||||||
|
this.spaceUserService
|
||||||
|
.disassociateUserFromSpace({
|
||||||
|
communityUuid: userSpace.space.community.uuid,
|
||||||
|
spaceUuid: userSpace.space.uuid,
|
||||||
|
userUuid: userData.user.uuid,
|
||||||
|
projectUuid,
|
||||||
|
})
|
||||||
|
.catch((error) => {
|
||||||
|
console.error(
|
||||||
|
`Failed to disassociate user from space ${userSpace.space.uuid}:`,
|
||||||
|
error,
|
||||||
|
);
|
||||||
|
throw error;
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
await Promise.allSettled(disassociatePromises);
|
||||||
|
|
||||||
|
// Process new spaces
|
||||||
|
const associatePromises = spaceUuids.map(async (spaceUuid) => {
|
||||||
|
try {
|
||||||
|
// Fetch space details
|
||||||
|
const spaceDetails = await this.getSpaceByUuid(spaceUuid);
|
||||||
|
|
||||||
|
// Fetch device UUIDs for the space
|
||||||
|
const deviceUUIDs =
|
||||||
|
await this.userSpaceService.getDeviceUUIDsForSpace(spaceUuid);
|
||||||
|
|
||||||
|
// Grant permissions to the user for all devices in the space
|
||||||
|
await this.userSpaceService.addUserPermissionsToDevices(
|
||||||
|
userData.user.uuid,
|
||||||
|
deviceUUIDs,
|
||||||
|
);
|
||||||
|
|
||||||
|
// Associate the user with the new space
|
||||||
|
await this.spaceUserService.associateUserToSpace({
|
||||||
|
communityUuid: spaceDetails.communityUuid,
|
||||||
|
spaceUuid: spaceUuid,
|
||||||
|
userUuid: userData.user.uuid,
|
||||||
|
projectUuid,
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
console.error(`Failed to process space ${spaceUuid}:`, error);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
await Promise.all(associatePromises);
|
||||||
|
}
|
||||||
|
|
||||||
|
async getSpaceByUuid(spaceUuid: string) {
|
||||||
|
try {
|
||||||
|
const space = await this.spaceRepository.findOne({
|
||||||
|
where: {
|
||||||
|
uuid: spaceUuid,
|
||||||
|
},
|
||||||
|
relations: ['community'],
|
||||||
|
});
|
||||||
|
if (!space) {
|
||||||
|
throw new BadRequestException(`Invalid space UUID ${spaceUuid}`);
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
uuid: space.uuid,
|
||||||
|
createdAt: space.createdAt,
|
||||||
|
updatedAt: space.updatedAt,
|
||||||
|
name: space.spaceName,
|
||||||
|
spaceTuyaUuid: space.community.externalId,
|
||||||
|
communityUuid: space.community.uuid,
|
||||||
|
};
|
||||||
|
} catch (err) {
|
||||||
|
if (err instanceof BadRequestException) {
|
||||||
|
throw err; // Re-throw BadRequestException
|
||||||
|
} else {
|
||||||
|
throw new HttpException('Space not found', HttpStatus.NOT_FOUND);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
async disableUserInvitation(
|
async disableUserInvitation(
|
||||||
dto: DisableUserInvitationDto,
|
dto: DisableUserInvitationDto,
|
||||||
invitedUserUuid: string,
|
invitedUserUuid: string,
|
||||||
@ -349,6 +685,74 @@ export class InviteUserService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private async updateUserStatus(
|
||||||
|
invitedUserUuid: string,
|
||||||
|
projectUuid: string,
|
||||||
|
isEnabled: boolean,
|
||||||
|
) {
|
||||||
|
await this.inviteUserRepository.update(
|
||||||
|
{ uuid: invitedUserUuid, project: { uuid: projectUuid } },
|
||||||
|
{ isEnabled },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async disassociateUserFromSpaces(user: any, projectUuid: string) {
|
||||||
|
const disassociatePromises = user.userSpaces.map((userSpace) =>
|
||||||
|
this.spaceUserService.disassociateUserFromSpace({
|
||||||
|
communityUuid: userSpace.space.community.uuid,
|
||||||
|
spaceUuid: userSpace.space.uuid,
|
||||||
|
userUuid: user.uuid,
|
||||||
|
projectUuid,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
const results = await Promise.allSettled(disassociatePromises);
|
||||||
|
|
||||||
|
results.forEach((result, index) => {
|
||||||
|
if (result.status === 'rejected') {
|
||||||
|
console.error(
|
||||||
|
`Failed to disassociate user from space ${user.userSpaces[index].space.uuid}:`,
|
||||||
|
result.reason,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
private async associateUserToSpaces(
|
||||||
|
user: any,
|
||||||
|
userData: any,
|
||||||
|
projectUuid: string,
|
||||||
|
invitedUserUuid: string,
|
||||||
|
disable: boolean,
|
||||||
|
) {
|
||||||
|
const spaceUuids = userData.spaces.map((space) => space.space.uuid);
|
||||||
|
|
||||||
|
const associatePromises = spaceUuids.map(async (spaceUuid) => {
|
||||||
|
try {
|
||||||
|
const spaceDetails = await this.getSpaceByUuid(spaceUuid);
|
||||||
|
|
||||||
|
const deviceUUIDs =
|
||||||
|
await this.userSpaceService.getDeviceUUIDsForSpace(spaceUuid);
|
||||||
|
await this.userSpaceService.addUserPermissionsToDevices(
|
||||||
|
user.uuid,
|
||||||
|
deviceUUIDs,
|
||||||
|
);
|
||||||
|
|
||||||
|
await this.spaceUserService.associateUserToSpace({
|
||||||
|
communityUuid: spaceDetails.communityUuid,
|
||||||
|
spaceUuid,
|
||||||
|
userUuid: user.uuid,
|
||||||
|
projectUuid,
|
||||||
|
});
|
||||||
|
|
||||||
|
await this.updateUserStatus(invitedUserUuid, projectUuid, disable);
|
||||||
|
} catch (error) {
|
||||||
|
console.error(`Failed to associate user to space ${spaceUuid}:`, error);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
await Promise.allSettled(associatePromises);
|
||||||
|
}
|
||||||
|
|
||||||
async deleteUserInvitation(
|
async deleteUserInvitation(
|
||||||
invitedUserUuid: string,
|
invitedUserUuid: string,
|
||||||
): Promise<BaseResponseDto> {
|
): Promise<BaseResponseDto> {
|
||||||
@ -419,486 +823,4 @@ export class InviteUserService {
|
|||||||
await queryRunner.release();
|
await queryRunner.release();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async activationCode(dto: ActivateCodeDto): Promise<BaseResponseDto> {
|
|
||||||
const { activationCode, userUuid } = dto;
|
|
||||||
|
|
||||||
try {
|
|
||||||
const user = await this.getUser(userUuid);
|
|
||||||
|
|
||||||
const invitedUser = await this.inviteUserRepository.findOne({
|
|
||||||
where: {
|
|
||||||
email: user.email,
|
|
||||||
status: UserStatusEnum.INVITED,
|
|
||||||
isActive: true,
|
|
||||||
},
|
|
||||||
relations: ['project', 'spaces.space.community', 'roleType'],
|
|
||||||
});
|
|
||||||
|
|
||||||
if (invitedUser) {
|
|
||||||
if (invitedUser.invitationCode !== activationCode) {
|
|
||||||
throw new HttpException(
|
|
||||||
'Invalid activation code',
|
|
||||||
HttpStatus.BAD_REQUEST,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Handle invited user with valid activation code
|
|
||||||
await this.handleInvitedUser(user, invitedUser);
|
|
||||||
} else {
|
|
||||||
// Handle case for non-invited user
|
|
||||||
await this.handleNonInvitedUser(activationCode, userUuid);
|
|
||||||
}
|
|
||||||
return new SuccessResponseDto({
|
|
||||||
statusCode: HttpStatus.OK,
|
|
||||||
success: true,
|
|
||||||
message: 'The code has been successfully activated',
|
|
||||||
});
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Error activating the code:', error);
|
|
||||||
throw new HttpException(
|
|
||||||
error.message ||
|
|
||||||
'An unexpected error occurred while activating the code',
|
|
||||||
error.status || HttpStatus.INTERNAL_SERVER_ERROR,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async checkEmailAndProject(dto: CheckEmailDto): Promise<BaseResponseDto> {
|
|
||||||
const { email } = dto;
|
|
||||||
|
|
||||||
try {
|
|
||||||
const user = await this.userRepository.findOne({
|
|
||||||
where: { email },
|
|
||||||
relations: ['project'],
|
|
||||||
});
|
|
||||||
this.validateUserOrInvite(user, 'User');
|
|
||||||
const invitedUser = await this.inviteUserRepository.findOne({
|
|
||||||
where: { email },
|
|
||||||
relations: ['project'],
|
|
||||||
});
|
|
||||||
this.validateUserOrInvite(invitedUser, 'Invited User');
|
|
||||||
|
|
||||||
return new SuccessResponseDto({
|
|
||||||
statusCode: HttpStatus.OK,
|
|
||||||
success: true,
|
|
||||||
message: 'Valid email',
|
|
||||||
});
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Error checking email and project:', error);
|
|
||||||
throw new HttpException(
|
|
||||||
error.message ||
|
|
||||||
'An unexpected error occurred while checking the email',
|
|
||||||
error.status || HttpStatus.INTERNAL_SERVER_ERROR,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private async getSpaceByUuid(spaceUuid: string) {
|
|
||||||
try {
|
|
||||||
const space = await this.spaceRepository.findOne({
|
|
||||||
where: {
|
|
||||||
uuid: spaceUuid,
|
|
||||||
},
|
|
||||||
relations: ['community'],
|
|
||||||
});
|
|
||||||
if (!space) {
|
|
||||||
throw new BadRequestException(`Invalid space UUID ${spaceUuid}`);
|
|
||||||
}
|
|
||||||
return {
|
|
||||||
uuid: space.uuid,
|
|
||||||
createdAt: space.createdAt,
|
|
||||||
updatedAt: space.updatedAt,
|
|
||||||
name: space.spaceName,
|
|
||||||
spaceTuyaUuid: space.community.externalId,
|
|
||||||
communityUuid: space.community.uuid,
|
|
||||||
};
|
|
||||||
} catch (err) {
|
|
||||||
if (err instanceof BadRequestException) {
|
|
||||||
throw err; // Re-throw BadRequestException
|
|
||||||
} else {
|
|
||||||
throw new HttpException('Space not found', HttpStatus.NOT_FOUND);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private async validateSpaces(
|
|
||||||
spaceUuids: string[],
|
|
||||||
entityManager: EntityManager,
|
|
||||||
): Promise<SpaceEntity[]> {
|
|
||||||
const spaceRepo = entityManager.getRepository(SpaceEntity);
|
|
||||||
|
|
||||||
const validSpaces = await spaceRepo.find({
|
|
||||||
where: { uuid: In(spaceUuids) },
|
|
||||||
});
|
|
||||||
|
|
||||||
if (validSpaces.length !== spaceUuids.length) {
|
|
||||||
const validSpaceUuids = validSpaces.map((space) => space.uuid);
|
|
||||||
const invalidSpaceUuids = spaceUuids.filter(
|
|
||||||
(uuid) => !validSpaceUuids.includes(uuid),
|
|
||||||
);
|
|
||||||
throw new HttpException(
|
|
||||||
`Invalid space UUIDs: ${invalidSpaceUuids.join(', ')}`,
|
|
||||||
HttpStatus.BAD_REQUEST,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
return validSpaces;
|
|
||||||
}
|
|
||||||
|
|
||||||
private async checkRole(
|
|
||||||
roleUuid: string,
|
|
||||||
queryRunner: QueryRunner,
|
|
||||||
): Promise<BaseResponseDto> {
|
|
||||||
try {
|
|
||||||
const role = await queryRunner.manager.findOne(RoleTypeEntity, {
|
|
||||||
where: { uuid: roleUuid },
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!role) {
|
|
||||||
throw new HttpException('Role not found', HttpStatus.NOT_FOUND);
|
|
||||||
}
|
|
||||||
|
|
||||||
return new SuccessResponseDto({
|
|
||||||
statusCode: HttpStatus.OK,
|
|
||||||
success: true,
|
|
||||||
message: 'Valid role',
|
|
||||||
});
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Error checking role:', error);
|
|
||||||
throw new HttpException(
|
|
||||||
error.message || 'An unexpected error occurred while checking the role',
|
|
||||||
error.status || HttpStatus.INTERNAL_SERVER_ERROR,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private async checkProject(
|
|
||||||
projectUuid: string,
|
|
||||||
queryRunner: QueryRunner,
|
|
||||||
): Promise<BaseResponseDto> {
|
|
||||||
try {
|
|
||||||
const project = await queryRunner.manager.findOne(ProjectEntity, {
|
|
||||||
where: { uuid: projectUuid },
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!project) {
|
|
||||||
throw new HttpException('Project not found', HttpStatus.NOT_FOUND);
|
|
||||||
}
|
|
||||||
|
|
||||||
return new SuccessResponseDto({
|
|
||||||
statusCode: HttpStatus.OK,
|
|
||||||
success: true,
|
|
||||||
message: 'Valid project',
|
|
||||||
});
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Error checking project:', error);
|
|
||||||
throw new HttpException(
|
|
||||||
error.message ||
|
|
||||||
'An unexpected error occurred while checking the project',
|
|
||||||
error.status || HttpStatus.INTERNAL_SERVER_ERROR,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private validateUserOrInvite(user: any, userType: string): void {
|
|
||||||
if (user) {
|
|
||||||
if (!user.isActive) {
|
|
||||||
throw new HttpException(
|
|
||||||
`${userType} is deleted`,
|
|
||||||
HttpStatus.BAD_REQUEST,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
if (user.project) {
|
|
||||||
throw new HttpException(
|
|
||||||
`${userType} already has a project`,
|
|
||||||
HttpStatus.BAD_REQUEST,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private async getUser(userUuid: string): Promise<UserEntity> {
|
|
||||||
const user = await this.userRepository.findOne({
|
|
||||||
where: { uuid: userUuid, isActive: true, isUserVerified: true },
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!user) {
|
|
||||||
throw new HttpException('User not found', HttpStatus.NOT_FOUND);
|
|
||||||
}
|
|
||||||
return user;
|
|
||||||
}
|
|
||||||
|
|
||||||
private async handleNonInvitedUser(
|
|
||||||
activationCode: string,
|
|
||||||
userUuid: string,
|
|
||||||
): Promise<void> {
|
|
||||||
await this.userSpaceService.verifyCodeAndAddUserSpace(
|
|
||||||
{ inviteCode: activationCode },
|
|
||||||
userUuid,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
private async handleInvitedUser(
|
|
||||||
user: UserEntity,
|
|
||||||
invitedUser: InviteUserEntity,
|
|
||||||
): Promise<void> {
|
|
||||||
for (const invitedSpace of invitedUser.spaces) {
|
|
||||||
try {
|
|
||||||
const deviceUUIDs = await this.userSpaceService.getDeviceUUIDsForSpace(
|
|
||||||
invitedSpace.space.uuid,
|
|
||||||
);
|
|
||||||
|
|
||||||
await this.userSpaceService.addUserPermissionsToDevices(
|
|
||||||
user.uuid,
|
|
||||||
deviceUUIDs,
|
|
||||||
);
|
|
||||||
|
|
||||||
await this.spaceUserService.associateUserToSpace({
|
|
||||||
communityUuid: invitedSpace.space.community.uuid,
|
|
||||||
spaceUuid: invitedSpace.space.uuid,
|
|
||||||
userUuid: user.uuid,
|
|
||||||
projectUuid: invitedUser.project.uuid,
|
|
||||||
});
|
|
||||||
} catch (spaceError) {
|
|
||||||
console.error(
|
|
||||||
`Error processing space ${invitedSpace.space.uuid}:`,
|
|
||||||
spaceError,
|
|
||||||
);
|
|
||||||
continue; // Skip to the next space
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Update invited user and associated user data
|
|
||||||
await this.inviteUserRepository.update(
|
|
||||||
{ uuid: invitedUser.uuid },
|
|
||||||
{ status: UserStatusEnum.ACTIVE, user: { uuid: user.uuid } },
|
|
||||||
);
|
|
||||||
await this.userRepository.update(
|
|
||||||
{ uuid: user.uuid },
|
|
||||||
{
|
|
||||||
project: { uuid: invitedUser.project.uuid },
|
|
||||||
roleType: { uuid: invitedUser.roleType.uuid },
|
|
||||||
},
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
private async getRoleTypeByUuid(roleUuid: string) {
|
|
||||||
const role = await this.roleTypeRepository.findOne({
|
|
||||||
where: { uuid: roleUuid },
|
|
||||||
});
|
|
||||||
|
|
||||||
return role.type;
|
|
||||||
}
|
|
||||||
|
|
||||||
private async updateWhenUserIsInvite(
|
|
||||||
queryRunner: QueryRunner,
|
|
||||||
dto: UpdateUserInvitationDto,
|
|
||||||
invitedUserUuid: string,
|
|
||||||
): Promise<void> {
|
|
||||||
const {
|
|
||||||
firstName,
|
|
||||||
lastName,
|
|
||||||
jobTitle,
|
|
||||||
companyName,
|
|
||||||
phoneNumber,
|
|
||||||
roleUuid,
|
|
||||||
spaceUuids,
|
|
||||||
} = dto;
|
|
||||||
|
|
||||||
// Update user invitation details
|
|
||||||
await queryRunner.manager.update(
|
|
||||||
this.inviteUserRepository.target,
|
|
||||||
{ uuid: invitedUserUuid },
|
|
||||||
{
|
|
||||||
firstName,
|
|
||||||
lastName,
|
|
||||||
jobTitle,
|
|
||||||
companyName,
|
|
||||||
phoneNumber,
|
|
||||||
roleType: { uuid: roleUuid },
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
// Remove old space associations
|
|
||||||
await queryRunner.manager.delete(this.inviteUserSpaceRepository.target, {
|
|
||||||
inviteUser: { uuid: invitedUserUuid },
|
|
||||||
});
|
|
||||||
|
|
||||||
// Save new space associations
|
|
||||||
const spaceData = spaceUuids.map((spaceUuid) => ({
|
|
||||||
inviteUser: { uuid: invitedUserUuid },
|
|
||||||
space: { uuid: spaceUuid },
|
|
||||||
}));
|
|
||||||
await queryRunner.manager.save(
|
|
||||||
this.inviteUserSpaceRepository.target,
|
|
||||||
spaceData,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
private async updateWhenUserIsActive(
|
|
||||||
queryRunner: QueryRunner,
|
|
||||||
dto: UpdateUserInvitationDto,
|
|
||||||
invitedUserUuid: string,
|
|
||||||
): Promise<void> {
|
|
||||||
const {
|
|
||||||
firstName,
|
|
||||||
lastName,
|
|
||||||
jobTitle,
|
|
||||||
companyName,
|
|
||||||
phoneNumber,
|
|
||||||
roleUuid,
|
|
||||||
spaceUuids,
|
|
||||||
projectUuid,
|
|
||||||
} = dto;
|
|
||||||
|
|
||||||
const userData = await this.inviteUserRepository.findOne({
|
|
||||||
where: { uuid: invitedUserUuid },
|
|
||||||
relations: ['user.userSpaces.space', 'user.userSpaces.space.community'],
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!userData) {
|
|
||||||
throw new HttpException(
|
|
||||||
`User with invitedUserUuid ${invitedUserUuid} not found`,
|
|
||||||
HttpStatus.NOT_FOUND,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Update user details
|
|
||||||
await queryRunner.manager.update(
|
|
||||||
this.inviteUserRepository.target,
|
|
||||||
{ uuid: invitedUserUuid },
|
|
||||||
{
|
|
||||||
firstName,
|
|
||||||
lastName,
|
|
||||||
jobTitle,
|
|
||||||
companyName,
|
|
||||||
phoneNumber,
|
|
||||||
roleType: { uuid: roleUuid },
|
|
||||||
},
|
|
||||||
);
|
|
||||||
await this.userRepository.update(
|
|
||||||
{ uuid: userData.user.uuid },
|
|
||||||
{
|
|
||||||
roleType: { uuid: roleUuid },
|
|
||||||
},
|
|
||||||
);
|
|
||||||
// Disassociate the user from all current spaces
|
|
||||||
const disassociatePromises = userData.user.userSpaces.map((userSpace) =>
|
|
||||||
this.spaceUserService
|
|
||||||
.disassociateUserFromSpace({
|
|
||||||
communityUuid: userSpace.space.community.uuid,
|
|
||||||
spaceUuid: userSpace.space.uuid,
|
|
||||||
userUuid: userData.user.uuid,
|
|
||||||
projectUuid,
|
|
||||||
})
|
|
||||||
.catch((error) => {
|
|
||||||
console.error(
|
|
||||||
`Failed to disassociate user from space ${userSpace.space.uuid}:`,
|
|
||||||
error,
|
|
||||||
);
|
|
||||||
throw error;
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
await Promise.allSettled(disassociatePromises);
|
|
||||||
|
|
||||||
// Process new spaces
|
|
||||||
const associatePromises = spaceUuids.map(async (spaceUuid) => {
|
|
||||||
try {
|
|
||||||
// Fetch space details
|
|
||||||
const spaceDetails = await this.getSpaceByUuid(spaceUuid);
|
|
||||||
|
|
||||||
// Fetch device UUIDs for the space
|
|
||||||
const deviceUUIDs =
|
|
||||||
await this.userSpaceService.getDeviceUUIDsForSpace(spaceUuid);
|
|
||||||
|
|
||||||
// Grant permissions to the user for all devices in the space
|
|
||||||
await this.userSpaceService.addUserPermissionsToDevices(
|
|
||||||
userData.user.uuid,
|
|
||||||
deviceUUIDs,
|
|
||||||
);
|
|
||||||
|
|
||||||
// Associate the user with the new space
|
|
||||||
await this.spaceUserService.associateUserToSpace({
|
|
||||||
communityUuid: spaceDetails.communityUuid,
|
|
||||||
spaceUuid: spaceUuid,
|
|
||||||
userUuid: userData.user.uuid,
|
|
||||||
projectUuid,
|
|
||||||
});
|
|
||||||
} catch (error) {
|
|
||||||
console.error(`Failed to process space ${spaceUuid}:`, error);
|
|
||||||
throw error;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
await Promise.all(associatePromises);
|
|
||||||
}
|
|
||||||
|
|
||||||
private async updateUserStatus(
|
|
||||||
invitedUserUuid: string,
|
|
||||||
projectUuid: string,
|
|
||||||
isEnabled: boolean,
|
|
||||||
) {
|
|
||||||
await this.inviteUserRepository.update(
|
|
||||||
{ uuid: invitedUserUuid, project: { uuid: projectUuid } },
|
|
||||||
{ isEnabled },
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
private async disassociateUserFromSpaces(user: any, projectUuid: string) {
|
|
||||||
const disassociatePromises = user.userSpaces.map((userSpace) =>
|
|
||||||
this.spaceUserService.disassociateUserFromSpace({
|
|
||||||
communityUuid: userSpace.space.community.uuid,
|
|
||||||
spaceUuid: userSpace.space.uuid,
|
|
||||||
userUuid: user.uuid,
|
|
||||||
projectUuid,
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
const results = await Promise.allSettled(disassociatePromises);
|
|
||||||
|
|
||||||
results.forEach((result, index) => {
|
|
||||||
if (result.status === 'rejected') {
|
|
||||||
console.error(
|
|
||||||
`Failed to disassociate user from space ${user.userSpaces[index].space.uuid}:`,
|
|
||||||
result.reason,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
private async associateUserToSpaces(
|
|
||||||
user: any,
|
|
||||||
userData: any,
|
|
||||||
projectUuid: string,
|
|
||||||
invitedUserUuid: string,
|
|
||||||
disable: boolean,
|
|
||||||
) {
|
|
||||||
const spaceUuids = userData.spaces.map((space) => space.space.uuid);
|
|
||||||
|
|
||||||
const associatePromises = spaceUuids.map(async (spaceUuid) => {
|
|
||||||
try {
|
|
||||||
const spaceDetails = await this.getSpaceByUuid(spaceUuid);
|
|
||||||
|
|
||||||
const deviceUUIDs =
|
|
||||||
await this.userSpaceService.getDeviceUUIDsForSpace(spaceUuid);
|
|
||||||
await this.userSpaceService.addUserPermissionsToDevices(
|
|
||||||
user.uuid,
|
|
||||||
deviceUUIDs,
|
|
||||||
);
|
|
||||||
|
|
||||||
await this.spaceUserService.associateUserToSpace({
|
|
||||||
communityUuid: spaceDetails.communityUuid,
|
|
||||||
spaceUuid,
|
|
||||||
userUuid: user.uuid,
|
|
||||||
projectUuid,
|
|
||||||
});
|
|
||||||
|
|
||||||
await this.updateUserStatus(invitedUserUuid, projectUuid, disable);
|
|
||||||
} catch (error) {
|
|
||||||
console.error(`Failed to associate user to space ${spaceUuid}:`, error);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
await Promise.allSettled(associatePromises);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
23
src/main.ts
23
src/main.ts
@ -1,13 +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 { NestFactory } from '@nestjs/core';
|
||||||
import { json, urlencoded } from 'body-parser';
|
|
||||||
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 { AppModule } from './app.module';
|
||||||
|
import rateLimit from 'express-rate-limit';
|
||||||
|
import helmet from 'helmet';
|
||||||
|
import { setupSwaggerAuthentication } from '../libs/common/src/util/user-auth.swagger.utils';
|
||||||
|
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 { 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() {
|
async function bootstrap() {
|
||||||
const app = await NestFactory.create(AppModule);
|
const app = await NestFactory.create(AppModule);
|
||||||
@ -21,6 +23,13 @@ async function bootstrap() {
|
|||||||
|
|
||||||
app.use(new RequestContextMiddleware().use);
|
app.use(new RequestContextMiddleware().use);
|
||||||
|
|
||||||
|
app.use(
|
||||||
|
rateLimit({
|
||||||
|
windowMs: 5 * 60 * 1000,
|
||||||
|
max: 500,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
app.use(
|
app.use(
|
||||||
helmet({
|
helmet({
|
||||||
contentSecurityPolicy: false,
|
contentSecurityPolicy: false,
|
||||||
|
@ -1,5 +1,4 @@
|
|||||||
import { DeviceStatusFirebaseService } from '@app/common/firebase/devices-status/services/devices-status.service';
|
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 { OccupancyService } from '@app/common/helper/services/occupancy.service';
|
||||||
import { PowerClampService } from '@app/common/helper/services/power.clamp.service';
|
import { PowerClampService } from '@app/common/helper/services/power.clamp.service';
|
||||||
import { SqlLoaderService } from '@app/common/helper/services/sql-loader.service';
|
import { SqlLoaderService } from '@app/common/helper/services/sql-loader.service';
|
||||||
@ -22,6 +21,7 @@ import {
|
|||||||
} from '@app/common/modules/scene/repositories';
|
} from '@app/common/modules/scene/repositories';
|
||||||
import {
|
import {
|
||||||
InviteSpaceRepository,
|
InviteSpaceRepository,
|
||||||
|
SpaceLinkRepository,
|
||||||
SpaceProductAllocationRepository,
|
SpaceProductAllocationRepository,
|
||||||
SpaceRepository,
|
SpaceRepository,
|
||||||
} from '@app/common/modules/space';
|
} from '@app/common/modules/space';
|
||||||
@ -49,6 +49,7 @@ import { SpaceModelProductAllocationService } from 'src/space-model/services/spa
|
|||||||
import { SubspaceModelProductAllocationService } from 'src/space-model/services/subspace/subspace-model-product-allocation.service';
|
import { SubspaceModelProductAllocationService } from 'src/space-model/services/subspace/subspace-model-product-allocation.service';
|
||||||
import {
|
import {
|
||||||
SpaceDeviceService,
|
SpaceDeviceService,
|
||||||
|
SpaceLinkService,
|
||||||
SpaceService,
|
SpaceService,
|
||||||
SubspaceDeviceService,
|
SubspaceDeviceService,
|
||||||
SubSpaceService,
|
SubSpaceService,
|
||||||
@ -59,8 +60,7 @@ import { SubspaceProductAllocationService } from 'src/space/services/subspace/su
|
|||||||
import { TagService } from 'src/tags/services';
|
import { TagService } from 'src/tags/services';
|
||||||
import { PowerClampController } from './controllers';
|
import { PowerClampController } from './controllers';
|
||||||
import { PowerClampService as PowerClamp } from './services/power-clamp.service';
|
import { PowerClampService as PowerClamp } from './services/power-clamp.service';
|
||||||
import { PresenceSensorDailySpaceRepository } from '@app/common/modules/presence-sensor/repositories';
|
import { AqiDataService } from '@app/common/helper/services/aqi.data.service';
|
||||||
import { AqiSpaceDailyPollutantStatsRepository } from '@app/common/modules/aqi/repositories';
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [ConfigModule],
|
imports: [ConfigModule],
|
||||||
controllers: [PowerClampController],
|
controllers: [PowerClampController],
|
||||||
@ -90,11 +90,13 @@ import { AqiSpaceDailyPollutantStatsRepository } from '@app/common/modules/aqi/r
|
|||||||
SceneRepository,
|
SceneRepository,
|
||||||
AutomationRepository,
|
AutomationRepository,
|
||||||
InviteSpaceRepository,
|
InviteSpaceRepository,
|
||||||
|
SpaceLinkService,
|
||||||
SubSpaceService,
|
SubSpaceService,
|
||||||
TagService,
|
TagService,
|
||||||
SpaceModelService,
|
SpaceModelService,
|
||||||
SpaceProductAllocationService,
|
SpaceProductAllocationService,
|
||||||
SqlLoaderService,
|
SqlLoaderService,
|
||||||
|
SpaceLinkRepository,
|
||||||
SubspaceRepository,
|
SubspaceRepository,
|
||||||
SubspaceDeviceService,
|
SubspaceDeviceService,
|
||||||
SubspaceProductAllocationService,
|
SubspaceProductAllocationService,
|
||||||
@ -109,8 +111,6 @@ import { AqiSpaceDailyPollutantStatsRepository } from '@app/common/modules/aqi/r
|
|||||||
SubspaceModelProductAllocationRepoitory,
|
SubspaceModelProductAllocationRepoitory,
|
||||||
OccupancyService,
|
OccupancyService,
|
||||||
AqiDataService,
|
AqiDataService,
|
||||||
PresenceSensorDailySpaceRepository,
|
|
||||||
AqiSpaceDailyPollutantStatsRepository,
|
|
||||||
],
|
],
|
||||||
exports: [PowerClamp],
|
exports: [PowerClamp],
|
||||||
})
|
})
|
||||||
|
@ -23,6 +23,7 @@ import {
|
|||||||
} from '@app/common/modules/scene/repositories';
|
} from '@app/common/modules/scene/repositories';
|
||||||
import {
|
import {
|
||||||
InviteSpaceRepository,
|
InviteSpaceRepository,
|
||||||
|
SpaceLinkRepository,
|
||||||
SpaceProductAllocationRepository,
|
SpaceProductAllocationRepository,
|
||||||
SpaceRepository,
|
SpaceRepository,
|
||||||
} from '@app/common/modules/space';
|
} from '@app/common/modules/space';
|
||||||
@ -53,6 +54,7 @@ import {
|
|||||||
import { SpaceModelProductAllocationService } from 'src/space-model/services/space-model-product-allocation.service';
|
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 { SubspaceModelProductAllocationService } from 'src/space-model/services/subspace/subspace-model-product-allocation.service';
|
||||||
import {
|
import {
|
||||||
|
SpaceLinkService,
|
||||||
SpaceService,
|
SpaceService,
|
||||||
SubspaceDeviceService,
|
SubspaceDeviceService,
|
||||||
SubSpaceService,
|
SubSpaceService,
|
||||||
@ -66,8 +68,6 @@ import { ProjectUserController } from './controllers/project-user.controller';
|
|||||||
import { CreateOrphanSpaceHandler } from './handler';
|
import { CreateOrphanSpaceHandler } from './handler';
|
||||||
import { ProjectService } from './services';
|
import { ProjectService } from './services';
|
||||||
import { ProjectUserService } from './services/project-user.service';
|
import { ProjectUserService } from './services/project-user.service';
|
||||||
import { PresenceSensorDailySpaceRepository } from '@app/common/modules/presence-sensor/repositories';
|
|
||||||
import { AqiSpaceDailyPollutantStatsRepository } from '@app/common/modules/aqi/repositories';
|
|
||||||
|
|
||||||
const CommandHandlers = [CreateOrphanSpaceHandler];
|
const CommandHandlers = [CreateOrphanSpaceHandler];
|
||||||
|
|
||||||
@ -87,12 +87,14 @@ const CommandHandlers = [CreateOrphanSpaceHandler];
|
|||||||
UserRepository,
|
UserRepository,
|
||||||
SpaceService,
|
SpaceService,
|
||||||
InviteSpaceRepository,
|
InviteSpaceRepository,
|
||||||
|
SpaceLinkService,
|
||||||
SubSpaceService,
|
SubSpaceService,
|
||||||
ValidationService,
|
ValidationService,
|
||||||
TagService,
|
TagService,
|
||||||
SpaceModelService,
|
SpaceModelService,
|
||||||
DeviceService,
|
DeviceService,
|
||||||
SpaceProductAllocationService,
|
SpaceProductAllocationService,
|
||||||
|
SpaceLinkRepository,
|
||||||
SubspaceRepository,
|
SubspaceRepository,
|
||||||
SubspaceDeviceService,
|
SubspaceDeviceService,
|
||||||
SubspaceProductAllocationService,
|
SubspaceProductAllocationService,
|
||||||
@ -124,8 +126,6 @@ const CommandHandlers = [CreateOrphanSpaceHandler];
|
|||||||
SqlLoaderService,
|
SqlLoaderService,
|
||||||
OccupancyService,
|
OccupancyService,
|
||||||
AqiDataService,
|
AqiDataService,
|
||||||
PresenceSensorDailySpaceRepository,
|
|
||||||
AqiSpaceDailyPollutantStatsRepository,
|
|
||||||
],
|
],
|
||||||
exports: [ProjectService, CqrsModule],
|
exports: [ProjectService, CqrsModule],
|
||||||
})
|
})
|
||||||
|
@ -33,7 +33,6 @@ export class ProjectUserService {
|
|||||||
'status',
|
'status',
|
||||||
'phoneNumber',
|
'phoneNumber',
|
||||||
'jobTitle',
|
'jobTitle',
|
||||||
'companyName',
|
|
||||||
'invitedBy',
|
'invitedBy',
|
||||||
'isEnabled',
|
'isEnabled',
|
||||||
],
|
],
|
||||||
@ -92,7 +91,6 @@ export class ProjectUserService {
|
|||||||
'status',
|
'status',
|
||||||
'phoneNumber',
|
'phoneNumber',
|
||||||
'jobTitle',
|
'jobTitle',
|
||||||
'companyName',
|
|
||||||
'invitedBy',
|
'invitedBy',
|
||||||
'isEnabled',
|
'isEnabled',
|
||||||
],
|
],
|
||||||
|
@ -24,7 +24,6 @@ import { SpaceService } from 'src/space/services';
|
|||||||
import { PassThrough } from 'stream';
|
import { PassThrough } from 'stream';
|
||||||
import { CreateOrphanSpaceCommand } from '../command/create-orphan-space-command';
|
import { CreateOrphanSpaceCommand } from '../command/create-orphan-space-command';
|
||||||
import { CreateProjectDto, GetProjectParam } from '../dto';
|
import { CreateProjectDto, GetProjectParam } from '../dto';
|
||||||
import { QueryRunner } from 'typeorm';
|
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class ProjectService {
|
export class ProjectService {
|
||||||
@ -213,14 +212,8 @@ export class ProjectService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async findOne(
|
async findOne(uuid: string): Promise<ProjectEntity> {
|
||||||
uuid: string,
|
const project = await this.projectRepository.findOne({ where: { uuid } });
|
||||||
queryRunner?: QueryRunner,
|
|
||||||
): Promise<ProjectEntity> {
|
|
||||||
const projectRepository = queryRunner
|
|
||||||
? queryRunner.manager.getRepository(ProjectEntity)
|
|
||||||
: this.projectRepository;
|
|
||||||
const project = await projectRepository.findOne({ where: { uuid } });
|
|
||||||
if (!project) {
|
if (!project) {
|
||||||
throw new HttpException(
|
throw new HttpException(
|
||||||
`Invalid project with uuid ${uuid}`,
|
`Invalid project with uuid ${uuid}`,
|
||||||
|
@ -1,32 +0,0 @@
|
|||||||
import {
|
|
||||||
ControlCur2AccurateCalibrationCommand,
|
|
||||||
ControlCur2Command,
|
|
||||||
ControlCur2PercentCommand,
|
|
||||||
ControlCur2QuickCalibrationCommand,
|
|
||||||
ControlCur2TDirectionConCommand,
|
|
||||||
} from 'src/device/commands/cur2-commands';
|
|
||||||
|
|
||||||
export enum ScheduleProductType {
|
|
||||||
CUR_2 = 'CUR_2',
|
|
||||||
}
|
|
||||||
export const DeviceFunctionMap: {
|
|
||||||
[T in ScheduleProductType]: (body: DeviceFunction[T]) => any;
|
|
||||||
} = {
|
|
||||||
[ScheduleProductType.CUR_2]: ({ code, value }) => {
|
|
||||||
return [
|
|
||||||
{
|
|
||||||
code,
|
|
||||||
value,
|
|
||||||
},
|
|
||||||
];
|
|
||||||
},
|
|
||||||
};
|
|
||||||
|
|
||||||
type DeviceFunction = {
|
|
||||||
[ScheduleProductType.CUR_2]:
|
|
||||||
| ControlCur2Command
|
|
||||||
| ControlCur2PercentCommand
|
|
||||||
| ControlCur2AccurateCalibrationCommand
|
|
||||||
| ControlCur2TDirectionConCommand
|
|
||||||
| ControlCur2QuickCalibrationCommand;
|
|
||||||
};
|
|
@ -49,11 +49,23 @@ export class ScheduleService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Corrected condition for supported device types
|
// Corrected condition for supported device types
|
||||||
this.ensureProductTypeSupportedForSchedule(
|
if (
|
||||||
deviceDetails.productDevice.prodType as ProductType,
|
deviceDetails.productDevice.prodType !== ProductType.THREE_G &&
|
||||||
);
|
deviceDetails.productDevice.prodType !== ProductType.ONE_G &&
|
||||||
|
deviceDetails.productDevice.prodType !== ProductType.TWO_G &&
|
||||||
return this.enableScheduleDeviceInTuya(
|
deviceDetails.productDevice.prodType !== ProductType.WH &&
|
||||||
|
deviceDetails.productDevice.prodType !== ProductType.ONE_1TG &&
|
||||||
|
deviceDetails.productDevice.prodType !== ProductType.TWO_2TG &&
|
||||||
|
deviceDetails.productDevice.prodType !== ProductType.THREE_3TG &&
|
||||||
|
deviceDetails.productDevice.prodType !== ProductType.GD &&
|
||||||
|
deviceDetails.productDevice.prodType !== ProductType.CUR_2
|
||||||
|
) {
|
||||||
|
throw new HttpException(
|
||||||
|
'This device is not supported for schedule',
|
||||||
|
HttpStatus.BAD_REQUEST,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return await this.enableScheduleDeviceInTuya(
|
||||||
deviceDetails.deviceTuyaUuid,
|
deviceDetails.deviceTuyaUuid,
|
||||||
enableScheduleDto,
|
enableScheduleDto,
|
||||||
);
|
);
|
||||||
@ -64,281 +76,7 @@ export class ScheduleService {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
async deleteDeviceSchedule(deviceUuid: string, scheduleId: string) {
|
async enableScheduleDeviceInTuya(
|
||||||
try {
|
|
||||||
const deviceDetails = await this.getDeviceByDeviceUuid(deviceUuid);
|
|
||||||
|
|
||||||
if (!deviceDetails || !deviceDetails.deviceTuyaUuid) {
|
|
||||||
throw new HttpException('Device Not Found', HttpStatus.NOT_FOUND);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Corrected condition for supported device types
|
|
||||||
this.ensureProductTypeSupportedForSchedule(
|
|
||||||
deviceDetails.productDevice.prodType as ProductType,
|
|
||||||
);
|
|
||||||
|
|
||||||
return await this.deleteScheduleDeviceInTuya(
|
|
||||||
deviceDetails.deviceTuyaUuid,
|
|
||||||
scheduleId,
|
|
||||||
);
|
|
||||||
} catch (error) {
|
|
||||||
throw new HttpException(
|
|
||||||
error.message || 'Error While Deleting Schedule',
|
|
||||||
error.status || HttpStatus.INTERNAL_SERVER_ERROR,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
async addDeviceSchedule(deviceUuid: string, addScheduleDto: AddScheduleDto) {
|
|
||||||
try {
|
|
||||||
const deviceDetails = await this.getDeviceByDeviceUuid(deviceUuid);
|
|
||||||
|
|
||||||
if (!deviceDetails || !deviceDetails.deviceTuyaUuid) {
|
|
||||||
throw new HttpException('Device Not Found', HttpStatus.NOT_FOUND);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (
|
|
||||||
deviceDetails.productDevice.prodType == ProductType.CUR_2 &&
|
|
||||||
addScheduleDto.category != 'Timer'
|
|
||||||
) {
|
|
||||||
throw new HttpException(
|
|
||||||
'Invalid category for CUR_2 devices',
|
|
||||||
HttpStatus.BAD_REQUEST,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (
|
|
||||||
deviceDetails.productDevice.prodType == ProductType.CUR_2 &&
|
|
||||||
addScheduleDto.category != 'Timer'
|
|
||||||
) {
|
|
||||||
throw new HttpException(
|
|
||||||
'Invalid category for CUR_2 devices',
|
|
||||||
HttpStatus.BAD_REQUEST,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
this.ensureProductTypeSupportedForSchedule(
|
|
||||||
deviceDetails.productDevice.prodType as ProductType,
|
|
||||||
);
|
|
||||||
|
|
||||||
await this.addScheduleDeviceInTuya(
|
|
||||||
deviceDetails.deviceTuyaUuid,
|
|
||||||
addScheduleDto,
|
|
||||||
deviceDetails.productDevice.prodType as ProductType,
|
|
||||||
);
|
|
||||||
} catch (error) {
|
|
||||||
throw new HttpException(
|
|
||||||
error.message || 'Error While Adding Schedule',
|
|
||||||
error.status || HttpStatus.INTERNAL_SERVER_ERROR,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
async getDeviceScheduleByCategory(deviceUuid: string, category: string) {
|
|
||||||
try {
|
|
||||||
const deviceDetails = await this.getDeviceByDeviceUuid(deviceUuid);
|
|
||||||
|
|
||||||
if (!deviceDetails || !deviceDetails.deviceTuyaUuid) {
|
|
||||||
throw new HttpException('Device Not Found', HttpStatus.NOT_FOUND);
|
|
||||||
}
|
|
||||||
// Corrected condition for supported device types
|
|
||||||
this.ensureProductTypeSupportedForSchedule(
|
|
||||||
deviceDetails.productDevice.prodType as ProductType,
|
|
||||||
);
|
|
||||||
const schedules = await this.getScheduleDeviceInTuya(
|
|
||||||
deviceDetails.deviceTuyaUuid,
|
|
||||||
category,
|
|
||||||
deviceDetails.productDevice.prodType as ProductType,
|
|
||||||
);
|
|
||||||
const result = schedules.result.map((schedule: any) => {
|
|
||||||
return {
|
|
||||||
category:
|
|
||||||
deviceDetails.productDevice.prodType == ProductType.CUR_2
|
|
||||||
? schedule.category
|
|
||||||
: schedule.category.replace('category_', ''),
|
|
||||||
enable: schedule.enable,
|
|
||||||
function: {
|
|
||||||
code: schedule.functions[0].code,
|
|
||||||
value: schedule.functions[0].value,
|
|
||||||
},
|
|
||||||
time: schedule.time,
|
|
||||||
schedule_id: schedule.timer_id,
|
|
||||||
timezone_id: schedule.timezone_id,
|
|
||||||
days: getEnabledDays(schedule.loops),
|
|
||||||
};
|
|
||||||
});
|
|
||||||
return convertKeysToCamelCase(result);
|
|
||||||
} catch (error) {
|
|
||||||
throw new HttpException(
|
|
||||||
error.message || 'Error While Adding Schedule',
|
|
||||||
error.status || HttpStatus.INTERNAL_SERVER_ERROR,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
async updateDeviceSchedule(
|
|
||||||
deviceUuid: string,
|
|
||||||
updateScheduleDto: UpdateScheduleDto,
|
|
||||||
) {
|
|
||||||
try {
|
|
||||||
const deviceDetails = await this.getDeviceByDeviceUuid(deviceUuid);
|
|
||||||
|
|
||||||
if (!deviceDetails || !deviceDetails.deviceTuyaUuid) {
|
|
||||||
throw new HttpException('Device Not Found', HttpStatus.NOT_FOUND);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (
|
|
||||||
deviceDetails.productDevice.prodType == ProductType.CUR_2 &&
|
|
||||||
updateScheduleDto.category != 'Timer'
|
|
||||||
) {
|
|
||||||
throw new HttpException(
|
|
||||||
'Invalid category for CUR_2 devices',
|
|
||||||
HttpStatus.BAD_REQUEST,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (
|
|
||||||
deviceDetails.productDevice.prodType == ProductType.CUR_2 &&
|
|
||||||
updateScheduleDto.category != 'Timer'
|
|
||||||
) {
|
|
||||||
throw new HttpException(
|
|
||||||
'Invalid category for CUR_2 devices',
|
|
||||||
HttpStatus.BAD_REQUEST,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Corrected condition for supported device types
|
|
||||||
this.ensureProductTypeSupportedForSchedule(
|
|
||||||
deviceDetails.productDevice.prodType as ProductType,
|
|
||||||
);
|
|
||||||
|
|
||||||
await this.updateScheduleDeviceInTuya(
|
|
||||||
deviceDetails.deviceTuyaUuid,
|
|
||||||
updateScheduleDto,
|
|
||||||
deviceDetails.productDevice.prodType as ProductType,
|
|
||||||
);
|
|
||||||
} catch (error) {
|
|
||||||
throw new HttpException(
|
|
||||||
error.message || 'Error While Updating Schedule',
|
|
||||||
error.status || HttpStatus.INTERNAL_SERVER_ERROR,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private getDeviceByDeviceUuid(
|
|
||||||
deviceUuid: string,
|
|
||||||
withProductDevice: boolean = true,
|
|
||||||
) {
|
|
||||||
return this.deviceRepository.findOne({
|
|
||||||
where: {
|
|
||||||
uuid: deviceUuid,
|
|
||||||
isActive: true,
|
|
||||||
},
|
|
||||||
...(withProductDevice && { relations: ['productDevice'] }),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
private async addScheduleDeviceInTuya(
|
|
||||||
deviceId: string,
|
|
||||||
addScheduleDto: AddScheduleDto,
|
|
||||||
deviceType: ProductType,
|
|
||||||
): Promise<addScheduleDeviceInterface> {
|
|
||||||
try {
|
|
||||||
const convertedTime = convertTimestampToDubaiTime(addScheduleDto.time);
|
|
||||||
const loops = getScheduleStatus(addScheduleDto.days);
|
|
||||||
|
|
||||||
const path = `/v2.0/cloud/timer/device/${deviceId}`;
|
|
||||||
const response = await this.tuya.request({
|
|
||||||
method: 'POST',
|
|
||||||
path,
|
|
||||||
body: {
|
|
||||||
time: convertedTime.time,
|
|
||||||
timezone_id: 'Asia/Dubai',
|
|
||||||
loops: `${loops}`,
|
|
||||||
functions: [
|
|
||||||
{
|
|
||||||
...addScheduleDto.function,
|
|
||||||
},
|
|
||||||
],
|
|
||||||
category:
|
|
||||||
deviceType == ProductType.CUR_2
|
|
||||||
? addScheduleDto.category
|
|
||||||
: `category_${addScheduleDto.category}`,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
return response as addScheduleDeviceInterface;
|
|
||||||
} catch (error) {
|
|
||||||
throw new HttpException(
|
|
||||||
'Error adding schedule from Tuya',
|
|
||||||
HttpStatus.INTERNAL_SERVER_ERROR,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private async getScheduleDeviceInTuya(
|
|
||||||
deviceId: string,
|
|
||||||
category: string,
|
|
||||||
deviceType: ProductType,
|
|
||||||
): Promise<getDeviceScheduleInterface> {
|
|
||||||
try {
|
|
||||||
const categoryToSent =
|
|
||||||
deviceType == ProductType.CUR_2 ? category : `category_${category}`;
|
|
||||||
const path = `/v2.0/cloud/timer/device/${deviceId}?category=${categoryToSent}`;
|
|
||||||
const response = await this.tuya.request({
|
|
||||||
method: 'GET',
|
|
||||||
path,
|
|
||||||
});
|
|
||||||
|
|
||||||
return response as getDeviceScheduleInterface;
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Error fetching device schedule from Tuya:', error);
|
|
||||||
|
|
||||||
throw new HttpException(
|
|
||||||
'Error fetching device schedule from Tuya',
|
|
||||||
HttpStatus.INTERNAL_SERVER_ERROR,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private async updateScheduleDeviceInTuya(
|
|
||||||
deviceId: string,
|
|
||||||
updateScheduleDto: UpdateScheduleDto,
|
|
||||||
deviceType: ProductType,
|
|
||||||
): Promise<addScheduleDeviceInterface> {
|
|
||||||
try {
|
|
||||||
const convertedTime = convertTimestampToDubaiTime(updateScheduleDto.time);
|
|
||||||
const loops = getScheduleStatus(updateScheduleDto.days);
|
|
||||||
|
|
||||||
const path = `/v2.0/cloud/timer/device/${deviceId}`;
|
|
||||||
const response = await this.tuya.request({
|
|
||||||
method: 'PUT',
|
|
||||||
path,
|
|
||||||
body: {
|
|
||||||
timer_id: updateScheduleDto.scheduleId,
|
|
||||||
time: convertedTime.time,
|
|
||||||
timezone_id: 'Asia/Dubai',
|
|
||||||
loops: `${loops}`,
|
|
||||||
functions: [
|
|
||||||
{
|
|
||||||
code: updateScheduleDto.function.code,
|
|
||||||
value: updateScheduleDto.function.value,
|
|
||||||
},
|
|
||||||
],
|
|
||||||
category:
|
|
||||||
deviceType == ProductType.CUR_2
|
|
||||||
? updateScheduleDto.category
|
|
||||||
: `category_${updateScheduleDto.category}`,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
return response as addScheduleDeviceInterface;
|
|
||||||
} catch (error) {
|
|
||||||
throw new HttpException(
|
|
||||||
'Error updating schedule from Tuya',
|
|
||||||
HttpStatus.INTERNAL_SERVER_ERROR,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private async enableScheduleDeviceInTuya(
|
|
||||||
deviceId: string,
|
deviceId: string,
|
||||||
enableScheduleDto: EnableScheduleDto,
|
enableScheduleDto: EnableScheduleDto,
|
||||||
): Promise<addScheduleDeviceInterface> {
|
): Promise<addScheduleDeviceInterface> {
|
||||||
@ -361,8 +99,43 @@ export class ScheduleService {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
async deleteDeviceSchedule(deviceUuid: string, scheduleId: string) {
|
||||||
|
try {
|
||||||
|
const deviceDetails = await this.getDeviceByDeviceUuid(deviceUuid);
|
||||||
|
|
||||||
private async deleteScheduleDeviceInTuya(
|
if (!deviceDetails || !deviceDetails.deviceTuyaUuid) {
|
||||||
|
throw new HttpException('Device Not Found', HttpStatus.NOT_FOUND);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Corrected condition for supported device types
|
||||||
|
if (
|
||||||
|
deviceDetails.productDevice.prodType !== ProductType.THREE_G &&
|
||||||
|
deviceDetails.productDevice.prodType !== ProductType.ONE_G &&
|
||||||
|
deviceDetails.productDevice.prodType !== ProductType.TWO_G &&
|
||||||
|
deviceDetails.productDevice.prodType !== ProductType.WH &&
|
||||||
|
deviceDetails.productDevice.prodType !== ProductType.ONE_1TG &&
|
||||||
|
deviceDetails.productDevice.prodType !== ProductType.TWO_2TG &&
|
||||||
|
deviceDetails.productDevice.prodType !== ProductType.THREE_3TG &&
|
||||||
|
deviceDetails.productDevice.prodType !== ProductType.GD &&
|
||||||
|
deviceDetails.productDevice.prodType !== ProductType.CUR_2
|
||||||
|
) {
|
||||||
|
throw new HttpException(
|
||||||
|
'This device is not supported for schedule',
|
||||||
|
HttpStatus.BAD_REQUEST,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return await this.deleteScheduleDeviceInTuya(
|
||||||
|
deviceDetails.deviceTuyaUuid,
|
||||||
|
scheduleId,
|
||||||
|
);
|
||||||
|
} catch (error) {
|
||||||
|
throw new HttpException(
|
||||||
|
error.message || 'Error While Deleting Schedule',
|
||||||
|
error.status || HttpStatus.INTERNAL_SERVER_ERROR,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
async deleteScheduleDeviceInTuya(
|
||||||
deviceId: string,
|
deviceId: string,
|
||||||
scheduleId: string,
|
scheduleId: string,
|
||||||
): Promise<addScheduleDeviceInterface> {
|
): Promise<addScheduleDeviceInterface> {
|
||||||
@ -381,24 +154,230 @@ export class ScheduleService {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
async addDeviceSchedule(deviceUuid: string, addScheduleDto: AddScheduleDto) {
|
||||||
|
try {
|
||||||
|
const deviceDetails = await this.getDeviceByDeviceUuid(deviceUuid);
|
||||||
|
|
||||||
private ensureProductTypeSupportedForSchedule(deviceType: ProductType): void {
|
if (!deviceDetails || !deviceDetails.deviceTuyaUuid) {
|
||||||
if (
|
throw new HttpException('Device Not Found', HttpStatus.NOT_FOUND);
|
||||||
![
|
}
|
||||||
ProductType.THREE_G,
|
|
||||||
ProductType.ONE_G,
|
// Corrected condition for supported device types
|
||||||
ProductType.TWO_G,
|
if (
|
||||||
ProductType.WH,
|
deviceDetails.productDevice.prodType !== ProductType.THREE_G &&
|
||||||
ProductType.ONE_1TG,
|
deviceDetails.productDevice.prodType !== ProductType.ONE_G &&
|
||||||
ProductType.TWO_2TG,
|
deviceDetails.productDevice.prodType !== ProductType.TWO_G &&
|
||||||
ProductType.THREE_3TG,
|
deviceDetails.productDevice.prodType !== ProductType.WH &&
|
||||||
ProductType.GD,
|
deviceDetails.productDevice.prodType !== ProductType.ONE_1TG &&
|
||||||
ProductType.CUR_2,
|
deviceDetails.productDevice.prodType !== ProductType.TWO_2TG &&
|
||||||
].includes(deviceType)
|
deviceDetails.productDevice.prodType !== ProductType.THREE_3TG &&
|
||||||
) {
|
deviceDetails.productDevice.prodType !== ProductType.GD &&
|
||||||
|
deviceDetails.productDevice.prodType !== ProductType.CUR_2
|
||||||
|
) {
|
||||||
|
throw new HttpException(
|
||||||
|
'This device is not supported for schedule',
|
||||||
|
HttpStatus.BAD_REQUEST,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
await this.addScheduleDeviceInTuya(
|
||||||
|
deviceDetails.deviceTuyaUuid,
|
||||||
|
addScheduleDto,
|
||||||
|
);
|
||||||
|
} catch (error) {
|
||||||
throw new HttpException(
|
throw new HttpException(
|
||||||
'This device is not supported for schedule',
|
error.message || 'Error While Adding Schedule',
|
||||||
HttpStatus.BAD_REQUEST,
|
error.status || HttpStatus.INTERNAL_SERVER_ERROR,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
async addScheduleDeviceInTuya(
|
||||||
|
deviceId: string,
|
||||||
|
addScheduleDto: AddScheduleDto,
|
||||||
|
): Promise<addScheduleDeviceInterface> {
|
||||||
|
try {
|
||||||
|
const convertedTime = convertTimestampToDubaiTime(addScheduleDto.time);
|
||||||
|
const loops = getScheduleStatus(addScheduleDto.days);
|
||||||
|
|
||||||
|
const path = `/v2.0/cloud/timer/device/${deviceId}`;
|
||||||
|
const response = await this.tuya.request({
|
||||||
|
method: 'POST',
|
||||||
|
path,
|
||||||
|
body: {
|
||||||
|
time: convertedTime.time,
|
||||||
|
timezone_id: 'Asia/Dubai',
|
||||||
|
loops: `${loops}`,
|
||||||
|
functions: [
|
||||||
|
{
|
||||||
|
code: addScheduleDto.function.code,
|
||||||
|
value: addScheduleDto.function.value,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
category: `category_${addScheduleDto.category}`,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
return response as addScheduleDeviceInterface;
|
||||||
|
} catch (error) {
|
||||||
|
throw new HttpException(
|
||||||
|
'Error adding schedule from Tuya',
|
||||||
|
HttpStatus.INTERNAL_SERVER_ERROR,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
async getDeviceScheduleByCategory(deviceUuid: string, category: string) {
|
||||||
|
try {
|
||||||
|
const deviceDetails = await this.getDeviceByDeviceUuid(deviceUuid);
|
||||||
|
|
||||||
|
if (!deviceDetails || !deviceDetails.deviceTuyaUuid) {
|
||||||
|
throw new HttpException('Device Not Found', HttpStatus.NOT_FOUND);
|
||||||
|
}
|
||||||
|
// Corrected condition for supported device types
|
||||||
|
if (
|
||||||
|
deviceDetails.productDevice.prodType !== ProductType.THREE_G &&
|
||||||
|
deviceDetails.productDevice.prodType !== ProductType.ONE_G &&
|
||||||
|
deviceDetails.productDevice.prodType !== ProductType.TWO_G &&
|
||||||
|
deviceDetails.productDevice.prodType !== ProductType.WH &&
|
||||||
|
deviceDetails.productDevice.prodType !== ProductType.ONE_1TG &&
|
||||||
|
deviceDetails.productDevice.prodType !== ProductType.TWO_2TG &&
|
||||||
|
deviceDetails.productDevice.prodType !== ProductType.THREE_3TG &&
|
||||||
|
deviceDetails.productDevice.prodType !== ProductType.GD &&
|
||||||
|
deviceDetails.productDevice.prodType !== ProductType.CUR_2
|
||||||
|
) {
|
||||||
|
throw new HttpException(
|
||||||
|
'This device is not supported for schedule',
|
||||||
|
HttpStatus.BAD_REQUEST,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const schedules = await this.getScheduleDeviceInTuya(
|
||||||
|
deviceDetails.deviceTuyaUuid,
|
||||||
|
category,
|
||||||
|
);
|
||||||
|
const result = schedules.result.map((schedule: any) => {
|
||||||
|
return {
|
||||||
|
category: schedule.category.replace('category_', ''),
|
||||||
|
enable: schedule.enable,
|
||||||
|
function: {
|
||||||
|
code: schedule.functions[0].code,
|
||||||
|
value: schedule.functions[0].value,
|
||||||
|
},
|
||||||
|
time: schedule.time,
|
||||||
|
schedule_id: schedule.timer_id,
|
||||||
|
timezone_id: schedule.timezone_id,
|
||||||
|
days: getEnabledDays(schedule.loops),
|
||||||
|
};
|
||||||
|
});
|
||||||
|
return convertKeysToCamelCase(result);
|
||||||
|
} catch (error) {
|
||||||
|
throw new HttpException(
|
||||||
|
error.message || 'Error While Adding Schedule',
|
||||||
|
error.status || HttpStatus.INTERNAL_SERVER_ERROR,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
async getScheduleDeviceInTuya(
|
||||||
|
deviceId: string,
|
||||||
|
category: string,
|
||||||
|
): Promise<getDeviceScheduleInterface> {
|
||||||
|
try {
|
||||||
|
const path = `/v2.0/cloud/timer/device/${deviceId}?category=category_${category}`;
|
||||||
|
const response = await this.tuya.request({
|
||||||
|
method: 'GET',
|
||||||
|
path,
|
||||||
|
});
|
||||||
|
|
||||||
|
return response as getDeviceScheduleInterface;
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error fetching device schedule from Tuya:', error);
|
||||||
|
|
||||||
|
throw new HttpException(
|
||||||
|
'Error fetching device schedule from Tuya',
|
||||||
|
HttpStatus.INTERNAL_SERVER_ERROR,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
async getDeviceByDeviceUuid(
|
||||||
|
deviceUuid: string,
|
||||||
|
withProductDevice: boolean = true,
|
||||||
|
) {
|
||||||
|
return await this.deviceRepository.findOne({
|
||||||
|
where: {
|
||||||
|
uuid: deviceUuid,
|
||||||
|
isActive: true,
|
||||||
|
},
|
||||||
|
...(withProductDevice && { relations: ['productDevice'] }),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
async updateDeviceSchedule(
|
||||||
|
deviceUuid: string,
|
||||||
|
updateScheduleDto: UpdateScheduleDto,
|
||||||
|
) {
|
||||||
|
try {
|
||||||
|
const deviceDetails = await this.getDeviceByDeviceUuid(deviceUuid);
|
||||||
|
|
||||||
|
if (!deviceDetails || !deviceDetails.deviceTuyaUuid) {
|
||||||
|
throw new HttpException('Device Not Found', HttpStatus.NOT_FOUND);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Corrected condition for supported device types
|
||||||
|
if (
|
||||||
|
deviceDetails.productDevice.prodType !== ProductType.THREE_G &&
|
||||||
|
deviceDetails.productDevice.prodType !== ProductType.ONE_G &&
|
||||||
|
deviceDetails.productDevice.prodType !== ProductType.TWO_G &&
|
||||||
|
deviceDetails.productDevice.prodType !== ProductType.WH &&
|
||||||
|
deviceDetails.productDevice.prodType !== ProductType.ONE_1TG &&
|
||||||
|
deviceDetails.productDevice.prodType !== ProductType.TWO_2TG &&
|
||||||
|
deviceDetails.productDevice.prodType !== ProductType.THREE_3TG &&
|
||||||
|
deviceDetails.productDevice.prodType !== ProductType.GD &&
|
||||||
|
deviceDetails.productDevice.prodType !== ProductType.CUR_2
|
||||||
|
) {
|
||||||
|
throw new HttpException(
|
||||||
|
'This device is not supported for schedule',
|
||||||
|
HttpStatus.BAD_REQUEST,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
await this.updateScheduleDeviceInTuya(
|
||||||
|
deviceDetails.deviceTuyaUuid,
|
||||||
|
updateScheduleDto,
|
||||||
|
);
|
||||||
|
} catch (error) {
|
||||||
|
throw new HttpException(
|
||||||
|
error.message || 'Error While Updating Schedule',
|
||||||
|
error.status || HttpStatus.INTERNAL_SERVER_ERROR,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
async updateScheduleDeviceInTuya(
|
||||||
|
deviceId: string,
|
||||||
|
updateScheduleDto: UpdateScheduleDto,
|
||||||
|
): Promise<addScheduleDeviceInterface> {
|
||||||
|
try {
|
||||||
|
const convertedTime = convertTimestampToDubaiTime(updateScheduleDto.time);
|
||||||
|
const loops = getScheduleStatus(updateScheduleDto.days);
|
||||||
|
|
||||||
|
const path = `/v2.0/cloud/timer/device/${deviceId}`;
|
||||||
|
const response = await this.tuya.request({
|
||||||
|
method: 'PUT',
|
||||||
|
path,
|
||||||
|
body: {
|
||||||
|
timer_id: updateScheduleDto.scheduleId,
|
||||||
|
time: convertedTime.time,
|
||||||
|
timezone_id: 'Asia/Dubai',
|
||||||
|
loops: `${loops}`,
|
||||||
|
functions: [
|
||||||
|
{
|
||||||
|
code: updateScheduleDto.function.code,
|
||||||
|
value: updateScheduleDto.function.value,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
category: `category_${updateScheduleDto.category}`,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
return response as addScheduleDeviceInterface;
|
||||||
|
} catch (error) {
|
||||||
|
throw new HttpException(
|
||||||
|
'Error updating schedule from Tuya',
|
||||||
|
HttpStatus.INTERNAL_SERVER_ERROR,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,25 +0,0 @@
|
|||||||
import { DatabaseModule } from '@app/common/database/database.module';
|
|
||||||
import { SqlLoaderService } from '@app/common/helper/services/sql-loader.service';
|
|
||||||
import { Module } from '@nestjs/common';
|
|
||||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
|
||||||
import { SchedulerService } from './scheduler.service';
|
|
||||||
import { ScheduleModule as NestScheduleModule } from '@nestjs/schedule';
|
|
||||||
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';
|
|
||||||
|
|
||||||
@Module({
|
|
||||||
imports: [
|
|
||||||
NestScheduleModule.forRoot(),
|
|
||||||
TypeOrmModule.forFeature([]),
|
|
||||||
DatabaseModule,
|
|
||||||
],
|
|
||||||
providers: [
|
|
||||||
SchedulerService,
|
|
||||||
SqlLoaderService,
|
|
||||||
PowerClampService,
|
|
||||||
OccupancyService,
|
|
||||||
AqiDataService,
|
|
||||||
],
|
|
||||||
})
|
|
||||||
export class SchedulerModule {}
|
|
@ -1,92 +0,0 @@
|
|||||||
import { AqiDataService } from '@app/common/helper/services/aqi.data.service';
|
|
||||||
import { Injectable } from '@nestjs/common';
|
|
||||||
import { Cron, CronExpression } from '@nestjs/schedule';
|
|
||||||
import { OccupancyService } from '@app/common/helper/services/occupancy.service';
|
|
||||||
import { PowerClampService } from '@app/common/helper/services/power.clamp.service';
|
|
||||||
|
|
||||||
@Injectable()
|
|
||||||
export class SchedulerService {
|
|
||||||
constructor(
|
|
||||||
private readonly powerClampService: PowerClampService,
|
|
||||||
private readonly occupancyService: OccupancyService,
|
|
||||||
private readonly aqiDataService: AqiDataService,
|
|
||||||
) {
|
|
||||||
console.log('SchedulerService initialized!');
|
|
||||||
}
|
|
||||||
|
|
||||||
@Cron(CronExpression.EVERY_HOUR)
|
|
||||||
async runHourlyProcedures() {
|
|
||||||
console.log('\n======== Starting Procedures ========');
|
|
||||||
console.log(new Date().toISOString(), 'Scheduler running...');
|
|
||||||
|
|
||||||
try {
|
|
||||||
const results = await Promise.allSettled([
|
|
||||||
this.executeTask(
|
|
||||||
() => this.powerClampService.updateEnergyConsumedHistoricalData(),
|
|
||||||
'Energy Consumption',
|
|
||||||
),
|
|
||||||
this.executeTask(
|
|
||||||
() => this.occupancyService.updateOccupancyDataProcedures(),
|
|
||||||
'Occupancy Data',
|
|
||||||
),
|
|
||||||
this.executeTask(
|
|
||||||
() => this.aqiDataService.updateAQISensorHistoricalData(),
|
|
||||||
'AQI Data',
|
|
||||||
),
|
|
||||||
]);
|
|
||||||
|
|
||||||
this.logResults(results);
|
|
||||||
} catch (error) {
|
|
||||||
console.error('MAIN SCHEDULER ERROR:', error);
|
|
||||||
if (error.stack) {
|
|
||||||
console.error('Error stack:', error.stack);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private async executeTask(
|
|
||||||
task: () => Promise<void>,
|
|
||||||
name: string,
|
|
||||||
): Promise<{ name: string; status: string }> {
|
|
||||||
try {
|
|
||||||
console.log(`[${new Date().toISOString()}] Starting ${name} task...`);
|
|
||||||
await task();
|
|
||||||
console.log(
|
|
||||||
`[${new Date().toISOString()}] ${name} task completed successfully`,
|
|
||||||
);
|
|
||||||
return { name, status: 'success' };
|
|
||||||
} catch (error) {
|
|
||||||
console.error(
|
|
||||||
`[${new Date().toISOString()}] ${name} task failed:`,
|
|
||||||
error.message,
|
|
||||||
);
|
|
||||||
if (error.stack) {
|
|
||||||
console.error('Task error stack:', error.stack);
|
|
||||||
}
|
|
||||||
return { name, status: 'failed' };
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private logResults(results: PromiseSettledResult<any>[]) {
|
|
||||||
const successCount = results.filter((r) => r.status === 'fulfilled').length;
|
|
||||||
const failedCount = results.length - successCount;
|
|
||||||
|
|
||||||
console.log('\n======== Task Results ========');
|
|
||||||
console.log(`Successful tasks: ${successCount}`);
|
|
||||||
console.log(`Failed tasks: ${failedCount}`);
|
|
||||||
|
|
||||||
if (failedCount > 0) {
|
|
||||||
console.log('\n======== Failed Tasks Details ========');
|
|
||||||
results.forEach((result, index) => {
|
|
||||||
if (result.status === 'rejected') {
|
|
||||||
console.error(`Task ${index + 1} failed:`, result.reason);
|
|
||||||
if (result.reason.stack) {
|
|
||||||
console.error('Error stack:', result.reason.stack);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
console.log('\n======== Scheduler Completed ========\n');
|
|
||||||
}
|
|
||||||
}
|
|
@ -51,12 +51,8 @@ export class SubSpaceModelService {
|
|||||||
for (const [index, dto] of dtos.entries()) {
|
for (const [index, dto] of dtos.entries()) {
|
||||||
const subspaceModel = savedSubspaces[index];
|
const subspaceModel = savedSubspaces[index];
|
||||||
|
|
||||||
const processedTags = await this.tagService.upsertTags(
|
const processedTags = await this.tagService.processTags(
|
||||||
dto.tags.map((tag) => ({
|
dto.tags,
|
||||||
tagName: tag.name,
|
|
||||||
productUuid: tag.productUuid,
|
|
||||||
tagUuid: tag.uuid,
|
|
||||||
})),
|
|
||||||
spaceModel.project.uuid,
|
spaceModel.project.uuid,
|
||||||
queryRunner,
|
queryRunner,
|
||||||
);
|
);
|
||||||
|
@ -22,6 +22,7 @@ import {
|
|||||||
} from '@app/common/modules/scene/repositories';
|
} from '@app/common/modules/scene/repositories';
|
||||||
import {
|
import {
|
||||||
InviteSpaceRepository,
|
InviteSpaceRepository,
|
||||||
|
SpaceLinkRepository,
|
||||||
SpaceProductAllocationRepository,
|
SpaceProductAllocationRepository,
|
||||||
SpaceRepository,
|
SpaceRepository,
|
||||||
} from '@app/common/modules/space';
|
} from '@app/common/modules/space';
|
||||||
@ -45,6 +46,7 @@ import { CommunityService } from 'src/community/services';
|
|||||||
import { DeviceService } from 'src/device/services';
|
import { DeviceService } from 'src/device/services';
|
||||||
import { SceneService } from 'src/scene/services';
|
import { SceneService } from 'src/scene/services';
|
||||||
import {
|
import {
|
||||||
|
SpaceLinkService,
|
||||||
SpaceService,
|
SpaceService,
|
||||||
SubspaceDeviceService,
|
SubspaceDeviceService,
|
||||||
SubSpaceService,
|
SubSpaceService,
|
||||||
@ -62,8 +64,6 @@ import {
|
|||||||
import { SpaceModelService, SubSpaceModelService } from './services';
|
import { SpaceModelService, SubSpaceModelService } from './services';
|
||||||
import { SpaceModelProductAllocationService } from './services/space-model-product-allocation.service';
|
import { SpaceModelProductAllocationService } from './services/space-model-product-allocation.service';
|
||||||
import { SubspaceModelProductAllocationService } from './services/subspace/subspace-model-product-allocation.service';
|
import { SubspaceModelProductAllocationService } from './services/subspace/subspace-model-product-allocation.service';
|
||||||
import { PresenceSensorDailySpaceRepository } from '@app/common/modules/presence-sensor/repositories';
|
|
||||||
import { AqiSpaceDailyPollutantStatsRepository } from '@app/common/modules/aqi/repositories';
|
|
||||||
|
|
||||||
const CommandHandlers = [
|
const CommandHandlers = [
|
||||||
PropogateUpdateSpaceModelHandler,
|
PropogateUpdateSpaceModelHandler,
|
||||||
@ -92,6 +92,8 @@ const CommandHandlers = [
|
|||||||
DeviceRepository,
|
DeviceRepository,
|
||||||
TuyaService,
|
TuyaService,
|
||||||
CommunityRepository,
|
CommunityRepository,
|
||||||
|
SpaceLinkService,
|
||||||
|
SpaceLinkRepository,
|
||||||
InviteSpaceRepository,
|
InviteSpaceRepository,
|
||||||
NewTagService,
|
NewTagService,
|
||||||
DeviceService,
|
DeviceService,
|
||||||
@ -120,8 +122,6 @@ const CommandHandlers = [
|
|||||||
SqlLoaderService,
|
SqlLoaderService,
|
||||||
OccupancyService,
|
OccupancyService,
|
||||||
AqiDataService,
|
AqiDataService,
|
||||||
PresenceSensorDailySpaceRepository,
|
|
||||||
AqiSpaceDailyPollutantStatsRepository,
|
|
||||||
],
|
],
|
||||||
exports: [CqrsModule, SpaceModelService],
|
exports: [CqrsModule, SpaceModelService],
|
||||||
})
|
})
|
||||||
|
@ -1,26 +1,23 @@
|
|||||||
|
import { ApiBearerAuth, ApiOperation, ApiTags } from '@nestjs/swagger';
|
||||||
|
import { SpaceService } from '../services';
|
||||||
import { ControllerRoute } from '@app/common/constants/controller-route';
|
import { ControllerRoute } from '@app/common/constants/controller-route';
|
||||||
import { BaseResponseDto } from '@app/common/dto/base.response.dto';
|
|
||||||
import { SuccessResponseDto } from '@app/common/dto/success.response.dto';
|
|
||||||
import {
|
import {
|
||||||
Body,
|
Body,
|
||||||
Controller,
|
Controller,
|
||||||
Delete,
|
Delete,
|
||||||
Get,
|
Get,
|
||||||
Param,
|
Param,
|
||||||
ParseUUIDPipe,
|
|
||||||
Post,
|
Post,
|
||||||
Put,
|
Put,
|
||||||
Query,
|
Query,
|
||||||
UseGuards,
|
UseGuards,
|
||||||
} from '@nestjs/common';
|
} 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 { AddSpaceDto, CommunitySpaceParam, UpdateSpaceDto } from '../dtos';
|
import { AddSpaceDto, CommunitySpaceParam, UpdateSpaceDto } from '../dtos';
|
||||||
import { GetSpaceDto } from '../dtos/get.space.dto';
|
import { BaseResponseDto } from '@app/common/dto/base.response.dto';
|
||||||
import { GetSpaceParam } from '../dtos/get.space.param';
|
import { GetSpaceParam } from '../dtos/get.space.param';
|
||||||
import { OrderSpacesDto } from '../dtos/order.spaces.dto';
|
import { PermissionsGuard } from 'src/guards/permissions.guard';
|
||||||
import { SpaceService } from '../services';
|
import { Permissions } from 'src/decorators/permissions.decorator';
|
||||||
|
import { GetSpaceDto } from '../dtos/get.space.dto';
|
||||||
|
|
||||||
@ApiTags('Space Module')
|
@ApiTags('Space Module')
|
||||||
@Controller({
|
@Controller({
|
||||||
@ -68,30 +65,6 @@ export class SpaceController {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ApiBearerAuth()
|
|
||||||
@UseGuards(PermissionsGuard)
|
|
||||||
@Permissions('SPACE_UPDATE')
|
|
||||||
@ApiOperation({
|
|
||||||
summary:
|
|
||||||
ControllerRoute.SPACE.ACTIONS
|
|
||||||
.UPDATE_CHILDREN_SPACES_ORDER_OF_A_SPACE_SUMMARY,
|
|
||||||
description:
|
|
||||||
ControllerRoute.SPACE.ACTIONS
|
|
||||||
.UPDATE_CHILDREN_SPACES_ORDER_OF_A_SPACE_DESCRIPTION,
|
|
||||||
})
|
|
||||||
@Post(':parentSpaceUuid/spaces/order')
|
|
||||||
async updateSpacesOrder(
|
|
||||||
@Body() orderSpacesDto: OrderSpacesDto,
|
|
||||||
@Param() communitySpaceParam: CommunitySpaceParam,
|
|
||||||
@Param('parentSpaceUuid', ParseUUIDPipe) parentSpaceUuid: string,
|
|
||||||
) {
|
|
||||||
await this.spaceService.updateSpacesOrder(parentSpaceUuid, orderSpacesDto);
|
|
||||||
return new SuccessResponseDto({
|
|
||||||
statusCode: 200,
|
|
||||||
message: 'Spaces order updated successfully',
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
@ApiBearerAuth()
|
@ApiBearerAuth()
|
||||||
@UseGuards(PermissionsGuard)
|
@UseGuards(PermissionsGuard)
|
||||||
@Permissions('SPACE_DELETE')
|
@Permissions('SPACE_DELETE')
|
||||||
|
@ -3,8 +3,7 @@ import { ApiProperty } from '@nestjs/swagger';
|
|||||||
import { Type } from 'class-transformer';
|
import { Type } from 'class-transformer';
|
||||||
import {
|
import {
|
||||||
ArrayUnique,
|
ArrayUnique,
|
||||||
IsArray,
|
IsBoolean,
|
||||||
IsMongoId,
|
|
||||||
IsNotEmpty,
|
IsNotEmpty,
|
||||||
IsNumber,
|
IsNumber,
|
||||||
IsOptional,
|
IsOptional,
|
||||||
@ -13,7 +12,7 @@ import {
|
|||||||
NotEquals,
|
NotEquals,
|
||||||
ValidateNested,
|
ValidateNested,
|
||||||
} from 'class-validator';
|
} from 'class-validator';
|
||||||
import { CreateProductAllocationDto } from './create-product-allocation.dto';
|
import { ProcessTagDto } from 'src/tags/dtos';
|
||||||
import { AddSubspaceDto } from './subspace';
|
import { AddSubspaceDto } from './subspace';
|
||||||
|
|
||||||
export class AddSpaceDto {
|
export class AddSpaceDto {
|
||||||
@ -48,6 +47,14 @@ export class AddSpaceDto {
|
|||||||
@IsOptional()
|
@IsOptional()
|
||||||
public icon?: string;
|
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 })
|
@ApiProperty({ description: 'X position on canvas', example: 120 })
|
||||||
@IsNumber()
|
@IsNumber()
|
||||||
x: number;
|
x: number;
|
||||||
@ -57,19 +64,23 @@ export class AddSpaceDto {
|
|||||||
y: number;
|
y: number;
|
||||||
|
|
||||||
@ApiProperty({
|
@ApiProperty({
|
||||||
description: 'UUID of the Space Model',
|
description: 'UUID of the Space',
|
||||||
example: 'd290f1ee-6c54-4b01-90e6-d701748f0851',
|
example: 'd290f1ee-6c54-4b01-90e6-d701748f0851',
|
||||||
})
|
})
|
||||||
@IsMongoId()
|
@IsString()
|
||||||
@IsOptional()
|
@IsOptional()
|
||||||
spaceModelUuid?: string;
|
spaceModelUuid?: string;
|
||||||
|
|
||||||
|
@ApiProperty({ description: 'Y position on canvas', example: 200 })
|
||||||
|
@IsString()
|
||||||
|
@IsOptional()
|
||||||
|
direction?: string;
|
||||||
|
|
||||||
@ApiProperty({
|
@ApiProperty({
|
||||||
description: 'List of subspaces included in the model',
|
description: 'List of subspaces included in the model',
|
||||||
type: [AddSubspaceDto],
|
type: [AddSubspaceDto],
|
||||||
})
|
})
|
||||||
@IsOptional()
|
@IsOptional()
|
||||||
@IsArray()
|
|
||||||
@ValidateNested({ each: true })
|
@ValidateNested({ each: true })
|
||||||
@ArrayUnique((subspace) => subspace.subspaceName, {
|
@ArrayUnique((subspace) => subspace.subspaceName, {
|
||||||
message(validationArguments) {
|
message(validationArguments) {
|
||||||
@ -89,21 +100,51 @@ export class AddSpaceDto {
|
|||||||
subspaces?: AddSubspaceDto[];
|
subspaces?: AddSubspaceDto[];
|
||||||
|
|
||||||
@ApiProperty({
|
@ApiProperty({
|
||||||
description: 'List of allocations associated with the space',
|
description: 'List of tags associated with the space model',
|
||||||
type: [CreateProductAllocationDto],
|
type: [ProcessTagDto],
|
||||||
})
|
})
|
||||||
@IsOptional()
|
|
||||||
@IsArray()
|
|
||||||
@ValidateNested({ each: true })
|
@ValidateNested({ each: true })
|
||||||
@Type(() => CreateProductAllocationDto)
|
@Type(() => ProcessTagDto)
|
||||||
productAllocations?: CreateProductAllocationDto[];
|
tags?: ProcessTagDto[];
|
||||||
|
}
|
||||||
@ApiProperty({
|
|
||||||
description: 'List of children spaces associated with the space',
|
export class AddUserSpaceDto {
|
||||||
type: [AddSpaceDto],
|
@ApiProperty({
|
||||||
})
|
description: 'spaceUuid',
|
||||||
@IsOptional()
|
required: true,
|
||||||
@ValidateNested({ each: true })
|
})
|
||||||
@Type(() => AddSpaceDto)
|
@IsString()
|
||||||
children?: AddSpaceDto[];
|
@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,14 +1,14 @@
|
|||||||
import { SpaceEntity } from '@app/common/modules/space/entities/space.entity';
|
import { SpaceEntity } from '@app/common/modules/space/entities/space.entity';
|
||||||
import { SubspaceEntity } from '@app/common/modules/space/entities/subspace/subspace.entity';
|
import { SubspaceEntity } from '@app/common/modules/space/entities/subspace/subspace.entity';
|
||||||
|
import { ProcessTagDto } from 'src/tags/dtos';
|
||||||
import { QueryRunner } from 'typeorm';
|
import { QueryRunner } from 'typeorm';
|
||||||
import { CreateProductAllocationDto } from './create-product-allocation.dto';
|
|
||||||
|
|
||||||
export enum AllocationsOwnerType {
|
export enum AllocationsOwnerType {
|
||||||
SPACE = 'space',
|
SPACE = 'space',
|
||||||
SUBSPACE = 'subspace',
|
SUBSPACE = 'subspace',
|
||||||
}
|
}
|
||||||
export class BaseCreateAllocationsDto {
|
export class BaseCreateAllocationsDto {
|
||||||
productAllocations: CreateProductAllocationDto[];
|
tags: ProcessTagDto[];
|
||||||
projectUuid: string;
|
projectUuid: string;
|
||||||
queryRunner: QueryRunner;
|
queryRunner: QueryRunner;
|
||||||
type: AllocationsOwnerType;
|
type: AllocationsOwnerType;
|
||||||
|
@ -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 './add.space.dto';
|
||||||
export * from './community-space.param';
|
export * from './community-space.param';
|
||||||
export * from './create-allocations.dto';
|
|
||||||
export * from './create-product-allocation.dto';
|
|
||||||
export * from './get.space.param';
|
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 './user-space.param';
|
||||||
|
export * from './subspace';
|
||||||
|
export * from './project.param.dto';
|
||||||
|
export * from './update.space.dto';
|
||||||
|
export * from './tag';
|
||||||
|
@ -1,13 +0,0 @@
|
|||||||
import { ApiProperty } from '@nestjs/swagger';
|
|
||||||
import { ArrayUnique, IsNotEmpty, IsUUID } from 'class-validator';
|
|
||||||
|
|
||||||
export class OrderSpacesDto {
|
|
||||||
@ApiProperty({
|
|
||||||
description: 'List of children spaces associated with the space',
|
|
||||||
type: [String],
|
|
||||||
})
|
|
||||||
@IsNotEmpty()
|
|
||||||
@ArrayUnique()
|
|
||||||
@IsUUID('4', { each: true, message: 'Invalid space UUID provided' })
|
|
||||||
spacesUuids: string[];
|
|
||||||
}
|
|
@ -1,5 +1,4 @@
|
|||||||
import { ApiProperty } from '@nestjs/swagger';
|
import { ApiProperty } from '@nestjs/swagger';
|
||||||
import { Type } from 'class-transformer';
|
|
||||||
import {
|
import {
|
||||||
IsArray,
|
IsArray,
|
||||||
IsNotEmpty,
|
IsNotEmpty,
|
||||||
@ -7,8 +6,8 @@ import {
|
|||||||
IsString,
|
IsString,
|
||||||
ValidateNested,
|
ValidateNested,
|
||||||
} from 'class-validator';
|
} from 'class-validator';
|
||||||
|
import { Type } from 'class-transformer';
|
||||||
import { ProcessTagDto } from 'src/tags/dtos';
|
import { ProcessTagDto } from 'src/tags/dtos';
|
||||||
import { CreateProductAllocationDto } from '../create-product-allocation.dto';
|
|
||||||
|
|
||||||
export class AddSubspaceDto {
|
export class AddSubspaceDto {
|
||||||
@ApiProperty({
|
@ApiProperty({
|
||||||
@ -25,7 +24,7 @@ export class AddSubspaceDto {
|
|||||||
})
|
})
|
||||||
@IsArray()
|
@IsArray()
|
||||||
@ValidateNested({ each: true })
|
@ValidateNested({ each: true })
|
||||||
@Type(() => CreateProductAllocationDto)
|
@Type(() => ProcessTagDto)
|
||||||
@IsOptional()
|
@IsOptional()
|
||||||
productAllocations?: CreateProductAllocationDto[];
|
tags?: ProcessTagDto[];
|
||||||
}
|
}
|
||||||
|
@ -1,5 +1,6 @@
|
|||||||
export * from './add.subspace-device.param';
|
|
||||||
export * from './add.subspace.dto';
|
export * from './add.subspace.dto';
|
||||||
export * from './delete.subspace.dto';
|
|
||||||
export * from './get.subspace.param';
|
export * from './get.subspace.param';
|
||||||
|
export * from './add.subspace-device.param';
|
||||||
export * from './update.subspace.dto';
|
export * from './update.subspace.dto';
|
||||||
|
export * from './delete.subspace.dto';
|
||||||
|
export * from './modify.subspace.dto';
|
||||||
|
14
src/space/dtos/subspace/modify.subspace.dto.ts
Normal file
14
src/space/dtos/subspace/modify.subspace.dto.ts
Normal file
@ -0,0 +1,14 @@
|
|||||||
|
import { ApiPropertyOptional, PartialType } from '@nestjs/swagger';
|
||||||
|
import { IsOptional, IsUUID } from 'class-validator';
|
||||||
|
import { AddSubspaceDto } from './add.subspace.dto';
|
||||||
|
|
||||||
|
export class ModifySubspaceDto extends PartialType(AddSubspaceDto) {
|
||||||
|
@ApiPropertyOptional({
|
||||||
|
description:
|
||||||
|
'UUID of the subspace (will present if updating an existing subspace)',
|
||||||
|
example: '123e4567-e89b-12d3-a456-426614174000',
|
||||||
|
})
|
||||||
|
@IsOptional()
|
||||||
|
@IsUUID()
|
||||||
|
uuid?: string;
|
||||||
|
}
|
@ -1,14 +1,16 @@
|
|||||||
import { ApiPropertyOptional, PartialType } from '@nestjs/swagger';
|
import { ApiProperty } from '@nestjs/swagger';
|
||||||
import { IsOptional, IsUUID } from 'class-validator';
|
import { IsNotEmpty, IsString } from 'class-validator';
|
||||||
import { AddSubspaceDto } from './add.subspace.dto';
|
|
||||||
|
|
||||||
export class UpdateSubspaceDto extends PartialType(AddSubspaceDto) {
|
export class UpdateSubspaceDto {
|
||||||
@ApiPropertyOptional({
|
@ApiProperty({
|
||||||
description:
|
description: 'Name of the subspace',
|
||||||
'UUID of the subspace (will present if updating an existing subspace)',
|
example: 'Living Room',
|
||||||
example: '123e4567-e89b-12d3-a456-426614174000',
|
|
||||||
})
|
})
|
||||||
@IsOptional()
|
@IsNotEmpty()
|
||||||
@IsUUID()
|
@IsString()
|
||||||
uuid?: string;
|
subspaceName?: string;
|
||||||
|
|
||||||
|
@IsNotEmpty()
|
||||||
|
@IsString()
|
||||||
|
subspaceUuid: string;
|
||||||
}
|
}
|
||||||
|
@ -2,7 +2,6 @@ import { ORPHAN_SPACE_NAME } from '@app/common/constants/orphan-constant';
|
|||||||
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||||
import { Type } from 'class-transformer';
|
import { Type } from 'class-transformer';
|
||||||
import {
|
import {
|
||||||
ArrayUnique,
|
|
||||||
IsArray,
|
IsArray,
|
||||||
IsNumber,
|
IsNumber,
|
||||||
IsOptional,
|
IsOptional,
|
||||||
@ -10,8 +9,8 @@ import {
|
|||||||
NotEquals,
|
NotEquals,
|
||||||
ValidateNested,
|
ValidateNested,
|
||||||
} from 'class-validator';
|
} from 'class-validator';
|
||||||
import { CreateProductAllocationDto } from './create-product-allocation.dto';
|
import { ModifySubspaceDto } from './subspace';
|
||||||
import { UpdateSubspaceDto } from './subspace';
|
import { ModifyTagDto } from './tag/modify-tag.dto';
|
||||||
|
|
||||||
export class UpdateSpaceDto {
|
export class UpdateSpaceDto {
|
||||||
@ApiProperty({
|
@ApiProperty({
|
||||||
@ -47,39 +46,25 @@ export class UpdateSpaceDto {
|
|||||||
y?: number;
|
y?: number;
|
||||||
|
|
||||||
@ApiPropertyOptional({
|
@ApiPropertyOptional({
|
||||||
description: 'List of subspace modifications',
|
description: 'List of subspace modifications (add/update/delete)',
|
||||||
type: [UpdateSubspaceDto],
|
type: [ModifySubspaceDto],
|
||||||
})
|
|
||||||
@ArrayUnique((subspace) => subspace.subspaceName ?? subspace.uuid, {
|
|
||||||
message(validationArguments) {
|
|
||||||
const subspaces = validationArguments.value;
|
|
||||||
const nameCounts = subspaces.reduce((acc, curr) => {
|
|
||||||
acc[curr.subspaceName ?? curr.uuid] =
|
|
||||||
(acc[curr.subspaceName ?? curr.uuid] || 0) + 1;
|
|
||||||
return acc;
|
|
||||||
}, {});
|
|
||||||
// Find duplicates
|
|
||||||
const duplicates = Object.keys(nameCounts).filter(
|
|
||||||
(name) => nameCounts[name] > 1,
|
|
||||||
);
|
|
||||||
return `Duplicate subspace names found: ${duplicates.join(', ')}`;
|
|
||||||
},
|
|
||||||
})
|
})
|
||||||
@IsOptional()
|
@IsOptional()
|
||||||
@IsArray()
|
@IsArray()
|
||||||
@ValidateNested({ each: true })
|
@ValidateNested({ each: true })
|
||||||
@Type(() => UpdateSubspaceDto)
|
@Type(() => ModifySubspaceDto)
|
||||||
subspaces?: UpdateSubspaceDto[];
|
subspaces?: ModifySubspaceDto[];
|
||||||
|
|
||||||
@ApiPropertyOptional({
|
@ApiPropertyOptional({
|
||||||
description: 'List of allocations modifications',
|
description:
|
||||||
type: [CreateProductAllocationDto],
|
'List of tag modifications (add/update/delete) for the space model',
|
||||||
|
type: [ModifyTagDto],
|
||||||
})
|
})
|
||||||
@IsOptional()
|
@IsOptional()
|
||||||
@IsArray()
|
@IsArray()
|
||||||
@ValidateNested({ each: true })
|
@ValidateNested({ each: true })
|
||||||
@Type(() => CreateProductAllocationDto)
|
@Type(() => ModifyTagDto)
|
||||||
productAllocations?: CreateProductAllocationDto[];
|
tags?: ModifyTagDto[];
|
||||||
|
|
||||||
@ApiProperty({
|
@ApiProperty({
|
||||||
description: 'UUID of the Space',
|
description: 'UUID of the Space',
|
||||||
|
@ -5,7 +5,11 @@ import { DeviceService } from 'src/device/services';
|
|||||||
import { UserSpaceService } from 'src/users/services';
|
import { UserSpaceService } from 'src/users/services';
|
||||||
import { DataSource } from 'typeorm';
|
import { DataSource } from 'typeorm';
|
||||||
import { DisableSpaceCommand } from '../commands';
|
import { DisableSpaceCommand } from '../commands';
|
||||||
import { SpaceSceneService, SubSpaceService } from '../services';
|
import {
|
||||||
|
SpaceLinkService,
|
||||||
|
SpaceSceneService,
|
||||||
|
SubSpaceService,
|
||||||
|
} from '../services';
|
||||||
|
|
||||||
@CommandHandler(DisableSpaceCommand)
|
@CommandHandler(DisableSpaceCommand)
|
||||||
export class DisableSpaceHandler
|
export class DisableSpaceHandler
|
||||||
@ -15,6 +19,7 @@ export class DisableSpaceHandler
|
|||||||
private readonly subSpaceService: SubSpaceService,
|
private readonly subSpaceService: SubSpaceService,
|
||||||
private readonly userService: UserSpaceService,
|
private readonly userService: UserSpaceService,
|
||||||
private readonly deviceService: DeviceService,
|
private readonly deviceService: DeviceService,
|
||||||
|
private readonly spaceLinkService: SpaceLinkService,
|
||||||
private readonly sceneService: SpaceSceneService,
|
private readonly sceneService: SpaceSceneService,
|
||||||
private readonly dataSource: DataSource,
|
private readonly dataSource: DataSource,
|
||||||
) {}
|
) {}
|
||||||
@ -34,6 +39,8 @@ export class DisableSpaceHandler
|
|||||||
'subspaces',
|
'subspaces',
|
||||||
'parent',
|
'parent',
|
||||||
'devices',
|
'devices',
|
||||||
|
'outgoingConnections',
|
||||||
|
'incomingConnections',
|
||||||
'scenes',
|
'scenes',
|
||||||
'children',
|
'children',
|
||||||
'userSpaces',
|
'userSpaces',
|
||||||
@ -72,6 +79,7 @@ export class DisableSpaceHandler
|
|||||||
orphanSpace,
|
orphanSpace,
|
||||||
queryRunner,
|
queryRunner,
|
||||||
),
|
),
|
||||||
|
this.spaceLinkService.deleteSpaceLink(space, queryRunner),
|
||||||
this.sceneService.deleteScenes(space, queryRunner),
|
this.sceneService.deleteScenes(space, queryRunner),
|
||||||
];
|
];
|
||||||
|
|
||||||
|
@ -2,5 +2,6 @@ export * from './space.service';
|
|||||||
export * from './space-user.service';
|
export * from './space-user.service';
|
||||||
export * from './space-device.service';
|
export * from './space-device.service';
|
||||||
export * from './subspace';
|
export * from './subspace';
|
||||||
|
export * from './space-link';
|
||||||
export * from './space-scene.service';
|
export * from './space-scene.service';
|
||||||
export * from './space-validation.service';
|
export * from './space-validation.service';
|
||||||
|
@ -16,10 +16,10 @@ export class ProductAllocationService {
|
|||||||
) {}
|
) {}
|
||||||
|
|
||||||
async createAllocations(dto: CreateAllocationsDto): Promise<void> {
|
async createAllocations(dto: CreateAllocationsDto): Promise<void> {
|
||||||
const { projectUuid, queryRunner, productAllocations, type } = dto;
|
const { projectUuid, queryRunner, tags, type } = dto;
|
||||||
|
|
||||||
const allocationsData = await this.tagService.upsertTags(
|
const allocationsData = await this.tagService.processTags(
|
||||||
productAllocations,
|
tags,
|
||||||
projectUuid,
|
projectUuid,
|
||||||
queryRunner,
|
queryRunner,
|
||||||
);
|
);
|
||||||
@ -29,17 +29,15 @@ export class ProductAllocationService {
|
|||||||
const createdTagsByName = new Map(allocationsData.map((t) => [t.name, t]));
|
const createdTagsByName = new Map(allocationsData.map((t) => [t.name, t]));
|
||||||
|
|
||||||
// Create the product-tag mapping based on the processed tags
|
// Create the product-tag mapping based on the processed tags
|
||||||
const productTagMapping = productAllocations.map(
|
const productTagMapping = tags.map(({ uuid, name, productUuid }) => {
|
||||||
({ tagUuid, tagName, productUuid }) => {
|
const inputTag = uuid
|
||||||
const inputTag = tagUuid
|
? createdTagsByUUID.get(uuid)
|
||||||
? createdTagsByUUID.get(tagUuid)
|
: createdTagsByName.get(name);
|
||||||
: createdTagsByName.get(tagName);
|
return {
|
||||||
return {
|
tag: inputTag?.uuid,
|
||||||
tag: inputTag?.uuid,
|
product: productUuid,
|
||||||
product: productUuid,
|
};
|
||||||
};
|
});
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
switch (type) {
|
switch (type) {
|
||||||
case AllocationsOwnerType.SPACE: {
|
case AllocationsOwnerType.SPACE: {
|
||||||
|
1
src/space/services/space-link/index.ts
Normal file
1
src/space/services/space-link/index.ts
Normal file
@ -0,0 +1 @@
|
|||||||
|
export * from './space-link.service';
|
121
src/space/services/space-link/space-link.service.ts
Normal file
121
src/space/services/space-link/space-link.service.ts
Normal file
@ -0,0 +1,121 @@
|
|||||||
|
import { SpaceLinkEntity } from '@app/common/modules/space/entities/space-link.entity';
|
||||||
|
import { SpaceEntity } from '@app/common/modules/space/entities/space.entity';
|
||||||
|
import { SpaceLinkRepository } from '@app/common/modules/space/repositories';
|
||||||
|
import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
|
||||||
|
import { QueryRunner } from 'typeorm';
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class SpaceLinkService {
|
||||||
|
constructor(private readonly spaceLinkRepository: SpaceLinkRepository) {}
|
||||||
|
|
||||||
|
async saveSpaceLink(
|
||||||
|
startSpaceId: string,
|
||||||
|
endSpaceId: string,
|
||||||
|
direction: string,
|
||||||
|
queryRunner: QueryRunner,
|
||||||
|
): Promise<void> {
|
||||||
|
try {
|
||||||
|
// Check if a link between the startSpace and endSpace already exists
|
||||||
|
const existingLink = await queryRunner.manager.findOne(SpaceLinkEntity, {
|
||||||
|
where: {
|
||||||
|
startSpace: { uuid: startSpaceId },
|
||||||
|
endSpace: { uuid: endSpaceId },
|
||||||
|
disabled: false,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
if (existingLink) {
|
||||||
|
// Update the direction if the link exists
|
||||||
|
existingLink.direction = direction;
|
||||||
|
await queryRunner.manager.save(SpaceLinkEntity, existingLink);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const existingEndSpaceLink = await queryRunner.manager.findOne(
|
||||||
|
SpaceLinkEntity,
|
||||||
|
{
|
||||||
|
where: { endSpace: { uuid: endSpaceId } },
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
if (
|
||||||
|
existingEndSpaceLink &&
|
||||||
|
existingEndSpaceLink.startSpace.uuid !== startSpaceId
|
||||||
|
) {
|
||||||
|
throw new Error(
|
||||||
|
`Space with ID ${endSpaceId} is already an endSpace in another link and cannot be reused.`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Find start space
|
||||||
|
const startSpace = await queryRunner.manager.findOne(SpaceEntity, {
|
||||||
|
where: { uuid: startSpaceId },
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!startSpace) {
|
||||||
|
throw new HttpException(
|
||||||
|
`Start space with ID ${startSpaceId} not found.`,
|
||||||
|
HttpStatus.NOT_FOUND,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Find end space
|
||||||
|
const endSpace = await queryRunner.manager.findOne(SpaceEntity, {
|
||||||
|
where: { uuid: endSpaceId },
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!endSpace) {
|
||||||
|
throw new HttpException(
|
||||||
|
`End space with ID ${endSpaceId} not found.`,
|
||||||
|
HttpStatus.NOT_FOUND,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create and save the space link
|
||||||
|
const spaceLink = this.spaceLinkRepository.create({
|
||||||
|
startSpace,
|
||||||
|
endSpace,
|
||||||
|
direction,
|
||||||
|
});
|
||||||
|
|
||||||
|
await queryRunner.manager.save(SpaceLinkEntity, spaceLink);
|
||||||
|
} catch (error) {
|
||||||
|
throw new HttpException(
|
||||||
|
error.message ||
|
||||||
|
`Failed to save space link. Internal Server Error: ${error.message}`,
|
||||||
|
error.status || HttpStatus.INTERNAL_SERVER_ERROR,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
async deleteSpaceLink(
|
||||||
|
space: SpaceEntity,
|
||||||
|
queryRunner: QueryRunner,
|
||||||
|
): Promise<void> {
|
||||||
|
try {
|
||||||
|
const spaceLinks = await queryRunner.manager.find(SpaceLinkEntity, {
|
||||||
|
where: [
|
||||||
|
{ startSpace: space, disabled: false },
|
||||||
|
{ endSpace: space, disabled: false },
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
if (spaceLinks.length === 0) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const linkIds = spaceLinks.map((link) => link.uuid);
|
||||||
|
|
||||||
|
await queryRunner.manager
|
||||||
|
.createQueryBuilder()
|
||||||
|
.update(SpaceLinkEntity)
|
||||||
|
.set({ disabled: true })
|
||||||
|
.whereInIds(linkIds)
|
||||||
|
.execute();
|
||||||
|
} catch (error) {
|
||||||
|
throw new HttpException(
|
||||||
|
`Failed to disable space links for the given space: ${error.message}`,
|
||||||
|
HttpStatus.INTERNAL_SERVER_ERROR,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -16,7 +16,7 @@ import {
|
|||||||
Inject,
|
Inject,
|
||||||
Injectable,
|
Injectable,
|
||||||
} from '@nestjs/common';
|
} from '@nestjs/common';
|
||||||
import { In, QueryRunner } from 'typeorm';
|
import { In } from 'typeorm';
|
||||||
import { CommunityService } from '../../community/services';
|
import { CommunityService } from '../../community/services';
|
||||||
import { ProjectService } from '../../project/services';
|
import { ProjectService } from '../../project/services';
|
||||||
import { ProjectParam } from '../dtos';
|
import { ProjectParam } from '../dtos';
|
||||||
@ -69,17 +69,12 @@ export class ValidationService {
|
|||||||
async validateCommunityAndProject(
|
async validateCommunityAndProject(
|
||||||
communityUuid: string,
|
communityUuid: string,
|
||||||
projectUuid: string,
|
projectUuid: string,
|
||||||
queryRunner?: QueryRunner,
|
|
||||||
) {
|
) {
|
||||||
const project = await this.projectService.findOne(projectUuid, queryRunner);
|
const project = await this.projectService.findOne(projectUuid);
|
||||||
|
const community = await this.communityService.getCommunityById({
|
||||||
const community = await this.communityService.getCommunityById(
|
communityUuid,
|
||||||
{
|
projectUuid,
|
||||||
communityUuid,
|
});
|
||||||
projectUuid,
|
|
||||||
},
|
|
||||||
queryRunner,
|
|
||||||
);
|
|
||||||
|
|
||||||
return { community: community.data, project: project };
|
return { community: community.data, project: project };
|
||||||
}
|
}
|
||||||
@ -175,14 +170,8 @@ export class ValidationService {
|
|||||||
return space;
|
return space;
|
||||||
}
|
}
|
||||||
|
|
||||||
async validateSpaceModel(
|
async validateSpaceModel(spaceModelUuid: string): Promise<SpaceModelEntity> {
|
||||||
spaceModelUuid: string,
|
const queryBuilder = this.spaceModelRepository
|
||||||
queryRunner?: QueryRunner,
|
|
||||||
): Promise<SpaceModelEntity> {
|
|
||||||
const queryBuilder = (
|
|
||||||
queryRunner.manager.getRepository(SpaceModelEntity) ||
|
|
||||||
this.spaceModelRepository
|
|
||||||
)
|
|
||||||
.createQueryBuilder('spaceModel')
|
.createQueryBuilder('spaceModel')
|
||||||
.leftJoinAndSelect(
|
.leftJoinAndSelect(
|
||||||
'spaceModel.subspaceModels',
|
'spaceModel.subspaceModels',
|
||||||
|
@ -22,6 +22,7 @@ import {
|
|||||||
import { CommandBus } from '@nestjs/cqrs';
|
import { CommandBus } from '@nestjs/cqrs';
|
||||||
import { DeviceService } from 'src/device/services';
|
import { DeviceService } from 'src/device/services';
|
||||||
import { SpaceModelService } from 'src/space-model/services';
|
import { SpaceModelService } from 'src/space-model/services';
|
||||||
|
import { ProcessTagDto } from 'src/tags/dtos';
|
||||||
import { TagService } from 'src/tags/services/tags.service';
|
import { TagService } from 'src/tags/services/tags.service';
|
||||||
import { DataSource, In, Not, QueryRunner } from 'typeorm';
|
import { DataSource, In, Not, QueryRunner } from 'typeorm';
|
||||||
import { DisableSpaceCommand } from '../commands';
|
import { DisableSpaceCommand } from '../commands';
|
||||||
@ -31,10 +32,9 @@ import {
|
|||||||
GetSpaceParam,
|
GetSpaceParam,
|
||||||
UpdateSpaceDto,
|
UpdateSpaceDto,
|
||||||
} from '../dtos';
|
} from '../dtos';
|
||||||
import { CreateProductAllocationDto } from '../dtos/create-product-allocation.dto';
|
|
||||||
import { GetSpaceDto } from '../dtos/get.space.dto';
|
import { GetSpaceDto } from '../dtos/get.space.dto';
|
||||||
import { OrderSpacesDto } from '../dtos/order.spaces.dto';
|
|
||||||
import { SpaceWithParentsDto } from '../dtos/space.parents.dto';
|
import { SpaceWithParentsDto } from '../dtos/space.parents.dto';
|
||||||
|
import { SpaceLinkService } from './space-link';
|
||||||
import { SpaceProductAllocationService } from './space-product-allocation.service';
|
import { SpaceProductAllocationService } from './space-product-allocation.service';
|
||||||
import { ValidationService } from './space-validation.service';
|
import { ValidationService } from './space-validation.service';
|
||||||
import { SubSpaceService } from './subspace';
|
import { SubSpaceService } from './subspace';
|
||||||
@ -44,6 +44,7 @@ export class SpaceService {
|
|||||||
private readonly dataSource: DataSource,
|
private readonly dataSource: DataSource,
|
||||||
private readonly spaceRepository: SpaceRepository,
|
private readonly spaceRepository: SpaceRepository,
|
||||||
private readonly inviteSpaceRepository: InviteSpaceRepository,
|
private readonly inviteSpaceRepository: InviteSpaceRepository,
|
||||||
|
private readonly spaceLinkService: SpaceLinkService,
|
||||||
private readonly subSpaceService: SubSpaceService,
|
private readonly subSpaceService: SubSpaceService,
|
||||||
private readonly validationService: ValidationService,
|
private readonly validationService: ValidationService,
|
||||||
private readonly tagService: TagService,
|
private readonly tagService: TagService,
|
||||||
@ -56,72 +57,50 @@ export class SpaceService {
|
|||||||
async createSpace(
|
async createSpace(
|
||||||
addSpaceDto: AddSpaceDto,
|
addSpaceDto: AddSpaceDto,
|
||||||
params: CommunitySpaceParam,
|
params: CommunitySpaceParam,
|
||||||
queryRunner?: QueryRunner,
|
|
||||||
recursiveCallParentEntity?: SpaceEntity,
|
|
||||||
): Promise<BaseResponseDto> {
|
): Promise<BaseResponseDto> {
|
||||||
const isRecursiveCall = !!queryRunner;
|
const { parentUuid, direction, spaceModelUuid, subspaces, tags } =
|
||||||
|
addSpaceDto;
|
||||||
const {
|
|
||||||
parentUuid,
|
|
||||||
spaceModelUuid,
|
|
||||||
subspaces,
|
|
||||||
productAllocations,
|
|
||||||
children,
|
|
||||||
} = addSpaceDto;
|
|
||||||
const { communityUuid, projectUuid } = params;
|
const { communityUuid, projectUuid } = params;
|
||||||
|
|
||||||
if (!queryRunner) {
|
const queryRunner = this.dataSource.createQueryRunner();
|
||||||
queryRunner = this.dataSource.createQueryRunner();
|
|
||||||
await queryRunner.connect();
|
await queryRunner.connect();
|
||||||
await queryRunner.startTransaction();
|
await queryRunner.startTransaction();
|
||||||
}
|
|
||||||
|
|
||||||
const { community } =
|
const { community } =
|
||||||
await this.validationService.validateCommunityAndProject(
|
await this.validationService.validateCommunityAndProject(
|
||||||
communityUuid,
|
communityUuid,
|
||||||
projectUuid,
|
projectUuid,
|
||||||
queryRunner,
|
|
||||||
);
|
);
|
||||||
|
|
||||||
this.validateSpaceCreationCriteria({
|
this.validateSpaceCreationCriteria({ spaceModelUuid, subspaces, tags });
|
||||||
spaceModelUuid,
|
|
||||||
subspaces,
|
|
||||||
productAllocations,
|
|
||||||
});
|
|
||||||
|
|
||||||
const parent =
|
const parent = parentUuid
|
||||||
parentUuid && !isRecursiveCall
|
? await this.validationService.validateSpace(parentUuid)
|
||||||
? await this.validationService.validateSpace(parentUuid)
|
: null;
|
||||||
: null;
|
|
||||||
|
|
||||||
const spaceModel = spaceModelUuid
|
const spaceModel = spaceModelUuid
|
||||||
? await this.validationService.validateSpaceModel(spaceModelUuid)
|
? await this.validationService.validateSpaceModel(spaceModelUuid)
|
||||||
: null;
|
: null;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const space = queryRunner.manager.create(SpaceEntity, {
|
const space = queryRunner.manager.create(SpaceEntity, {
|
||||||
// todo: find a better way to handle this instead of naming every key
|
...addSpaceDto,
|
||||||
spaceName: addSpaceDto.spaceName,
|
|
||||||
icon: addSpaceDto.icon,
|
|
||||||
x: addSpaceDto.x,
|
|
||||||
y: addSpaceDto.y,
|
|
||||||
spaceModel,
|
spaceModel,
|
||||||
parent: isRecursiveCall
|
parent: parentUuid ? parent : null,
|
||||||
? recursiveCallParentEntity
|
|
||||||
: parentUuid
|
|
||||||
? parent
|
|
||||||
: null,
|
|
||||||
community,
|
community,
|
||||||
});
|
});
|
||||||
|
|
||||||
const newSpace = await queryRunner.manager.save(space);
|
const newSpace = await queryRunner.manager.save(space);
|
||||||
this.checkDuplicateTags([
|
|
||||||
...(productAllocations || []),
|
const subspaceTags =
|
||||||
...(subspaces?.flatMap(
|
subspaces?.flatMap((subspace) => subspace.tags || []) || [];
|
||||||
(subspace) => subspace.productAllocations || [],
|
|
||||||
) || []),
|
this.checkDuplicateTags([...tags, ...subspaceTags]);
|
||||||
]);
|
|
||||||
|
|
||||||
if (spaceModelUuid) {
|
if (spaceModelUuid) {
|
||||||
|
// no need to check for existing dependencies here as validateSpaceCreationCriteria
|
||||||
|
// ensures no tags or subspaces are present along with spaceModelUuid
|
||||||
await this.spaceModelService.linkToSpace(
|
await this.spaceModelService.linkToSpace(
|
||||||
newSpace,
|
newSpace,
|
||||||
spaceModel,
|
spaceModel,
|
||||||
@ -130,6 +109,15 @@ export class SpaceService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
await Promise.all([
|
await Promise.all([
|
||||||
|
// todo: remove this logic as we are not using space links anymore
|
||||||
|
direction && parent
|
||||||
|
? this.spaceLinkService.saveSpaceLink(
|
||||||
|
parent.uuid,
|
||||||
|
newSpace.uuid,
|
||||||
|
direction,
|
||||||
|
queryRunner,
|
||||||
|
)
|
||||||
|
: Promise.resolve(),
|
||||||
subspaces?.length
|
subspaces?.length
|
||||||
? this.subSpaceService.createSubspacesFromDto(
|
? this.subSpaceService.createSubspacesFromDto(
|
||||||
subspaces,
|
subspaces,
|
||||||
@ -138,32 +126,12 @@ export class SpaceService {
|
|||||||
projectUuid,
|
projectUuid,
|
||||||
)
|
)
|
||||||
: Promise.resolve(),
|
: Promise.resolve(),
|
||||||
productAllocations?.length
|
tags?.length
|
||||||
? this.createAllocations(
|
? this.createAllocations(tags, projectUuid, queryRunner, newSpace)
|
||||||
productAllocations,
|
|
||||||
projectUuid,
|
|
||||||
queryRunner,
|
|
||||||
newSpace,
|
|
||||||
)
|
|
||||||
: Promise.resolve(),
|
: Promise.resolve(),
|
||||||
]);
|
]);
|
||||||
|
|
||||||
if (children?.length) {
|
await queryRunner.commitTransaction();
|
||||||
await Promise.all(
|
|
||||||
children.map((child) =>
|
|
||||||
this.createSpace(
|
|
||||||
{ ...child, parentUuid: newSpace.uuid },
|
|
||||||
{ communityUuid, projectUuid },
|
|
||||||
queryRunner,
|
|
||||||
newSpace,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!isRecursiveCall) {
|
|
||||||
await queryRunner.commitTransaction();
|
|
||||||
}
|
|
||||||
|
|
||||||
return new SuccessResponseDto({
|
return new SuccessResponseDto({
|
||||||
statusCode: HttpStatus.CREATED,
|
statusCode: HttpStatus.CREATED,
|
||||||
@ -171,34 +139,34 @@ export class SpaceService {
|
|||||||
message: 'Space created successfully',
|
message: 'Space created successfully',
|
||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
!isRecursiveCall ? await queryRunner.rollbackTransaction() : null;
|
await queryRunner.rollbackTransaction();
|
||||||
|
|
||||||
if (error instanceof HttpException) {
|
if (error instanceof HttpException) {
|
||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR);
|
throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR);
|
||||||
} finally {
|
} finally {
|
||||||
!isRecursiveCall ? await queryRunner.release() : null;
|
await queryRunner.release();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
private checkDuplicateTags(allocations: CreateProductAllocationDto[]) {
|
private checkDuplicateTags(allTags: ProcessTagDto[]) {
|
||||||
const tagUuidSet = new Set<string>();
|
const tagUuidSet = new Set<string>();
|
||||||
const tagNameProductSet = new Set<string>();
|
const tagNameProductSet = new Set<string>();
|
||||||
|
|
||||||
for (const allocation of allocations) {
|
for (const tag of allTags) {
|
||||||
if (allocation.tagUuid) {
|
if (tag.uuid) {
|
||||||
if (tagUuidSet.has(allocation.tagUuid)) {
|
if (tagUuidSet.has(tag.uuid)) {
|
||||||
throw new HttpException(
|
throw new HttpException(
|
||||||
`Duplicate tag UUID found: ${allocation.tagUuid}`,
|
`Duplicate tag UUID found: ${tag.uuid}`,
|
||||||
HttpStatus.BAD_REQUEST,
|
HttpStatus.BAD_REQUEST,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
tagUuidSet.add(allocation.tagUuid);
|
tagUuidSet.add(tag.uuid);
|
||||||
} else {
|
} else {
|
||||||
const tagKey = `${allocation.tagName}-${allocation.productUuid}`;
|
const tagKey = `${tag.name}-${tag.productUuid}`;
|
||||||
if (tagNameProductSet.has(tagKey)) {
|
if (tagNameProductSet.has(tagKey)) {
|
||||||
throw new HttpException(
|
throw new HttpException(
|
||||||
`Duplicate tag found with name "${allocation.tagName}" and product "${allocation.productUuid}".`,
|
`Duplicate tag found with name "${tag.name}" and product "${tag.productUuid}".`,
|
||||||
HttpStatus.BAD_REQUEST,
|
HttpStatus.BAD_REQUEST,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@ -227,7 +195,12 @@ export class SpaceService {
|
|||||||
'children.disabled = :disabled',
|
'children.disabled = :disabled',
|
||||||
{ disabled: false },
|
{ disabled: false },
|
||||||
)
|
)
|
||||||
|
.leftJoinAndSelect(
|
||||||
|
'space.incomingConnections',
|
||||||
|
'incomingConnections',
|
||||||
|
'incomingConnections.disabled = :incomingConnectionDisabled',
|
||||||
|
{ incomingConnectionDisabled: false },
|
||||||
|
)
|
||||||
.leftJoinAndSelect('space.productAllocations', 'productAllocations')
|
.leftJoinAndSelect('space.productAllocations', 'productAllocations')
|
||||||
.leftJoinAndSelect('productAllocations.tag', 'tag')
|
.leftJoinAndSelect('productAllocations.tag', 'tag')
|
||||||
.leftJoinAndSelect('productAllocations.product', 'product')
|
.leftJoinAndSelect('productAllocations.product', 'product')
|
||||||
@ -298,6 +271,7 @@ export class SpaceService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// todo refactor this method to eliminate wrong use of tags
|
||||||
async findOne(params: GetSpaceParam): Promise<BaseResponseDto> {
|
async findOne(params: GetSpaceParam): Promise<BaseResponseDto> {
|
||||||
const { communityUuid, spaceUuid, projectUuid } = params;
|
const { communityUuid, spaceUuid, projectUuid } = params;
|
||||||
try {
|
try {
|
||||||
@ -308,6 +282,19 @@ export class SpaceService {
|
|||||||
|
|
||||||
const queryBuilder = this.spaceRepository
|
const queryBuilder = this.spaceRepository
|
||||||
.createQueryBuilder('space')
|
.createQueryBuilder('space')
|
||||||
|
.leftJoinAndSelect('space.parent', 'parent')
|
||||||
|
.leftJoinAndSelect(
|
||||||
|
'space.children',
|
||||||
|
'children',
|
||||||
|
'children.disabled = :disabled',
|
||||||
|
{ disabled: false },
|
||||||
|
)
|
||||||
|
.leftJoinAndSelect(
|
||||||
|
'space.incomingConnections',
|
||||||
|
'incomingConnections',
|
||||||
|
'incomingConnections.disabled = :incomingConnectionDisabled',
|
||||||
|
{ incomingConnectionDisabled: false },
|
||||||
|
)
|
||||||
.leftJoinAndSelect('space.productAllocations', 'productAllocations')
|
.leftJoinAndSelect('space.productAllocations', 'productAllocations')
|
||||||
.leftJoinAndSelect('productAllocations.tag', 'spaceTag')
|
.leftJoinAndSelect('productAllocations.tag', 'spaceTag')
|
||||||
.leftJoinAndSelect('productAllocations.product', 'spaceProduct')
|
.leftJoinAndSelect('productAllocations.product', 'spaceProduct')
|
||||||
@ -334,12 +321,7 @@ export class SpaceService {
|
|||||||
.andWhere('space.disabled = :disabled', { disabled: false });
|
.andWhere('space.disabled = :disabled', { disabled: false });
|
||||||
|
|
||||||
const space = await queryBuilder.getOne();
|
const space = await queryBuilder.getOne();
|
||||||
if (!space) {
|
|
||||||
throw new HttpException(
|
|
||||||
`Space with ID ${spaceUuid} not found`,
|
|
||||||
HttpStatus.NOT_FOUND,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
return new SuccessResponseDto({
|
return new SuccessResponseDto({
|
||||||
message: `Space with ID ${spaceUuid} successfully fetched`,
|
message: `Space with ID ${spaceUuid} successfully fetched`,
|
||||||
data: space,
|
data: space,
|
||||||
@ -349,61 +331,13 @@ export class SpaceService {
|
|||||||
throw error; // If it's an HttpException, rethrow it
|
throw error; // If it's an HttpException, rethrow it
|
||||||
} else {
|
} else {
|
||||||
throw new HttpException(
|
throw new HttpException(
|
||||||
'An error occurred while fetching the space',
|
'An error occurred while deleting the community',
|
||||||
HttpStatus.INTERNAL_SERVER_ERROR,
|
HttpStatus.INTERNAL_SERVER_ERROR,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async updateSpacesOrder(
|
|
||||||
parentSpaceUuid: string,
|
|
||||||
{ spacesUuids }: OrderSpacesDto,
|
|
||||||
) {
|
|
||||||
const parentSpace = await this.spaceRepository.findOne({
|
|
||||||
where: { uuid: parentSpaceUuid, disabled: false },
|
|
||||||
relations: ['children'],
|
|
||||||
});
|
|
||||||
if (!parentSpace) {
|
|
||||||
throw new HttpException(
|
|
||||||
`Parent space with ID ${parentSpaceUuid} not found`,
|
|
||||||
HttpStatus.NOT_FOUND,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
// ensure that all sent spaces belong to the parent space
|
|
||||||
const missingSpaces = spacesUuids.filter(
|
|
||||||
(uuid) => !parentSpace.children.some((child) => child.uuid === uuid),
|
|
||||||
);
|
|
||||||
if (missingSpaces.length > 0) {
|
|
||||||
throw new HttpException(
|
|
||||||
`Some spaces with IDs ${missingSpaces.join(
|
|
||||||
', ',
|
|
||||||
)} do not belong to the parent space with ID ${parentSpaceUuid}`,
|
|
||||||
HttpStatus.BAD_REQUEST,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
await this.spaceRepository.update(
|
|
||||||
{ uuid: In(spacesUuids), parent: { uuid: parentSpaceUuid } },
|
|
||||||
{
|
|
||||||
order: () =>
|
|
||||||
'CASE ' +
|
|
||||||
spacesUuids
|
|
||||||
.map((s, index) => `WHEN uuid = '${s}' THEN ${index + 1}`)
|
|
||||||
.join(' ') +
|
|
||||||
' END',
|
|
||||||
},
|
|
||||||
);
|
|
||||||
return;
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Error updating spaces order:', error);
|
|
||||||
throw new HttpException(
|
|
||||||
'An error occurred while updating spaces order',
|
|
||||||
HttpStatus.INTERNAL_SERVER_ERROR,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async delete(params: GetSpaceParam): Promise<BaseResponseDto> {
|
async delete(params: GetSpaceParam): Promise<BaseResponseDto> {
|
||||||
const queryRunner = this.dataSource.createQueryRunner();
|
const queryRunner = this.dataSource.createQueryRunner();
|
||||||
await queryRunner.connect();
|
await queryRunner.connect();
|
||||||
@ -475,7 +409,7 @@ export class SpaceService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private async disableSpace(space: SpaceEntity, orphanSpace: SpaceEntity) {
|
async disableSpace(space: SpaceEntity, orphanSpace: SpaceEntity) {
|
||||||
await this.commandBus.execute(
|
await this.commandBus.execute(
|
||||||
new DisableSpaceCommand({ spaceUuid: space.uuid, orphanSpace }),
|
new DisableSpaceCommand({ spaceUuid: space.uuid, orphanSpace }),
|
||||||
);
|
);
|
||||||
@ -489,7 +423,7 @@ export class SpaceService {
|
|||||||
|
|
||||||
const queryRunner = this.dataSource.createQueryRunner();
|
const queryRunner = this.dataSource.createQueryRunner();
|
||||||
const hasSubspace = updateSpaceDto.subspaces?.length > 0;
|
const hasSubspace = updateSpaceDto.subspaces?.length > 0;
|
||||||
const hasAllocations = updateSpaceDto.productAllocations?.length > 0;
|
const hasTags = updateSpaceDto.tags?.length > 0;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await queryRunner.connect();
|
await queryRunner.connect();
|
||||||
@ -514,7 +448,7 @@ export class SpaceService {
|
|||||||
|
|
||||||
await this.updateSpaceProperties(space, updateSpaceDto, queryRunner);
|
await this.updateSpaceProperties(space, updateSpaceDto, queryRunner);
|
||||||
|
|
||||||
if (hasSubspace || hasAllocations) {
|
if (hasSubspace || hasTags) {
|
||||||
await queryRunner.manager.update(SpaceEntity, space.uuid, {
|
await queryRunner.manager.update(SpaceEntity, space.uuid, {
|
||||||
spaceModel: null,
|
spaceModel: null,
|
||||||
});
|
});
|
||||||
@ -558,7 +492,7 @@ export class SpaceService {
|
|||||||
await this.subSpaceService.unlinkModels(space.subspaces, queryRunner);
|
await this.subSpaceService.unlinkModels(space.subspaces, queryRunner);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (hasAllocations && space.productAllocations && space.spaceModel) {
|
if (hasTags && space.productAllocations && space.spaceModel) {
|
||||||
await this.spaceProductAllocationService.unlinkModels(
|
await this.spaceProductAllocationService.unlinkModels(
|
||||||
space,
|
space,
|
||||||
queryRunner,
|
queryRunner,
|
||||||
@ -574,13 +508,13 @@ export class SpaceService {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (updateSpaceDto.productAllocations) {
|
if (updateSpaceDto.tags) {
|
||||||
await queryRunner.manager.delete(SpaceProductAllocationEntity, {
|
await queryRunner.manager.delete(SpaceProductAllocationEntity, {
|
||||||
space: { uuid: space.uuid },
|
space: { uuid: space.uuid },
|
||||||
tag: {
|
tag: {
|
||||||
uuid: Not(
|
uuid: Not(
|
||||||
In(
|
In(
|
||||||
updateSpaceDto.productAllocations
|
updateSpaceDto.tags
|
||||||
.filter((tag) => tag.tagUuid)
|
.filter((tag) => tag.tagUuid)
|
||||||
.map((tag) => tag.tagUuid),
|
.map((tag) => tag.tagUuid),
|
||||||
),
|
),
|
||||||
@ -588,7 +522,11 @@ export class SpaceService {
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
await this.createAllocations(
|
await this.createAllocations(
|
||||||
updateSpaceDto.productAllocations,
|
updateSpaceDto.tags.map((tag) => ({
|
||||||
|
name: tag.name,
|
||||||
|
uuid: tag.tagUuid,
|
||||||
|
productUuid: tag.productUuid,
|
||||||
|
})),
|
||||||
projectUuid,
|
projectUuid,
|
||||||
queryRunner,
|
queryRunner,
|
||||||
space,
|
space,
|
||||||
@ -735,7 +673,7 @@ export class SpaceService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
buildSpaceHierarchy(spaces: SpaceEntity[]): SpaceEntity[] {
|
private buildSpaceHierarchy(spaces: SpaceEntity[]): SpaceEntity[] {
|
||||||
const map = new Map<string, SpaceEntity>();
|
const map = new Map<string, SpaceEntity>();
|
||||||
|
|
||||||
// Step 1: Create a map of spaces by UUID
|
// Step 1: Create a map of spaces by UUID
|
||||||
@ -758,34 +696,19 @@ export class SpaceService {
|
|||||||
rootSpaces.push(map.get(space.uuid)!); // Push only root spaces
|
rootSpaces.push(map.get(space.uuid)!); // Push only root spaces
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
rootSpaces.forEach(this.sortSpaceChildren.bind(this));
|
|
||||||
return rootSpaces;
|
|
||||||
}
|
|
||||||
|
|
||||||
private sortSpaceChildren(space: SpaceEntity) {
|
return rootSpaces;
|
||||||
if (space.children && space.children.length > 0) {
|
|
||||||
space.children.sort((a, b) => {
|
|
||||||
const aOrder = a.order ?? Infinity;
|
|
||||||
const bOrder = b.order ?? Infinity;
|
|
||||||
return aOrder - bOrder;
|
|
||||||
});
|
|
||||||
space.children.forEach(this.sortSpaceChildren.bind(this)); // Recursively sort children of children
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private validateSpaceCreationCriteria({
|
private validateSpaceCreationCriteria({
|
||||||
spaceModelUuid,
|
spaceModelUuid,
|
||||||
productAllocations,
|
tags,
|
||||||
subspaces,
|
subspaces,
|
||||||
}: Pick<
|
}: Pick<AddSpaceDto, 'spaceModelUuid' | 'tags' | 'subspaces'>): void {
|
||||||
AddSpaceDto,
|
const hasTagsOrSubspaces =
|
||||||
'spaceModelUuid' | 'productAllocations' | 'subspaces'
|
(tags && tags.length > 0) || (subspaces && subspaces.length > 0);
|
||||||
>): void {
|
|
||||||
const hasProductsOrSubspaces =
|
|
||||||
(productAllocations && productAllocations.length > 0) ||
|
|
||||||
(subspaces && subspaces.length > 0);
|
|
||||||
|
|
||||||
if (spaceModelUuid && hasProductsOrSubspaces) {
|
if (spaceModelUuid && hasTagsOrSubspaces) {
|
||||||
throw new HttpException(
|
throw new HttpException(
|
||||||
'For space creation choose either space model or products and subspace',
|
'For space creation choose either space model or products and subspace',
|
||||||
HttpStatus.CONFLICT,
|
HttpStatus.CONFLICT,
|
||||||
@ -794,13 +717,13 @@ export class SpaceService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private async createAllocations(
|
private async createAllocations(
|
||||||
productAllocations: CreateProductAllocationDto[],
|
tags: ProcessTagDto[],
|
||||||
projectUuid: string,
|
projectUuid: string,
|
||||||
queryRunner: QueryRunner,
|
queryRunner: QueryRunner,
|
||||||
space: SpaceEntity,
|
space: SpaceEntity,
|
||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
const allocationsData = await this.tagService.upsertTags(
|
const allocationsData = await this.tagService.processTags(
|
||||||
productAllocations,
|
tags,
|
||||||
projectUuid,
|
projectUuid,
|
||||||
queryRunner,
|
queryRunner,
|
||||||
);
|
);
|
||||||
@ -810,17 +733,15 @@ export class SpaceService {
|
|||||||
const createdTagsByName = new Map(allocationsData.map((t) => [t.name, t]));
|
const createdTagsByName = new Map(allocationsData.map((t) => [t.name, t]));
|
||||||
|
|
||||||
// Create the product-tag mapping based on the processed tags
|
// Create the product-tag mapping based on the processed tags
|
||||||
const productTagMapping = productAllocations.map(
|
const productTagMapping = tags.map(({ uuid, name, productUuid }) => {
|
||||||
({ tagUuid, tagName, productUuid }) => {
|
const inputTag = uuid
|
||||||
const inputTag = tagUuid
|
? createdTagsByUUID.get(uuid)
|
||||||
? createdTagsByUUID.get(tagUuid)
|
: createdTagsByName.get(name);
|
||||||
: createdTagsByName.get(tagName);
|
return {
|
||||||
return {
|
tag: inputTag?.uuid,
|
||||||
tag: inputTag?.uuid,
|
product: productUuid,
|
||||||
product: productUuid,
|
};
|
||||||
};
|
});
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
await this.spaceProductAllocationService.createProductAllocations(
|
await this.spaceProductAllocationService.createProductAllocations(
|
||||||
space,
|
space,
|
||||||
|
@ -3,7 +3,7 @@ import { SubspaceProductAllocationEntity } from '@app/common/modules/space/entit
|
|||||||
import { SubspaceEntity } from '@app/common/modules/space/entities/subspace/subspace.entity';
|
import { SubspaceEntity } from '@app/common/modules/space/entities/subspace/subspace.entity';
|
||||||
import { SubspaceProductAllocationRepository } from '@app/common/modules/space/repositories/subspace.repository';
|
import { SubspaceProductAllocationRepository } from '@app/common/modules/space/repositories/subspace.repository';
|
||||||
import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
|
import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
|
||||||
import { UpdateSubspaceDto } from 'src/space/dtos';
|
import { UpdateSpaceAllocationDto } from 'src/space/interfaces/update-subspace-allocation.dto';
|
||||||
import { TagService as NewTagService } from 'src/tags/services';
|
import { TagService as NewTagService } from 'src/tags/services';
|
||||||
import { In, Not, QueryRunner } from 'typeorm';
|
import { In, Not, QueryRunner } from 'typeorm';
|
||||||
|
|
||||||
@ -23,7 +23,7 @@ export class SubspaceProductAllocationService {
|
|||||||
// spaceAllocationsToExclude?: SpaceProductAllocationEntity[],
|
// spaceAllocationsToExclude?: SpaceProductAllocationEntity[],
|
||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
try {
|
try {
|
||||||
if (!allocationsData?.length) return;
|
if (!allocationsData.length) return;
|
||||||
|
|
||||||
const allocations: SubspaceProductAllocationEntity[] = [];
|
const allocations: SubspaceProductAllocationEntity[] = [];
|
||||||
|
|
||||||
@ -60,46 +60,31 @@ export class SubspaceProductAllocationService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async updateSubspaceProductAllocationsV2(
|
async updateSubspaceProductAllocationsV2(
|
||||||
subSpaces: UpdateSubspaceDto[],
|
subSpaces: UpdateSpaceAllocationDto[],
|
||||||
projectUuid: string,
|
projectUuid: string,
|
||||||
queryRunner: QueryRunner,
|
queryRunner: QueryRunner,
|
||||||
) {
|
) {
|
||||||
await Promise.all(
|
await Promise.all(
|
||||||
subSpaces.map(async (subspace) => {
|
subSpaces.map(async (subspace) => {
|
||||||
await queryRunner.manager.delete(SubspaceProductAllocationEntity, {
|
await queryRunner.manager.delete(SubspaceProductAllocationEntity, {
|
||||||
subspace: subspace.uuid ? { uuid: subspace.uuid } : undefined,
|
subspace: { uuid: subspace.uuid },
|
||||||
tag: subspace.productAllocations
|
tag: {
|
||||||
? {
|
uuid: Not(
|
||||||
uuid: Not(
|
In(
|
||||||
In(
|
subspace.tags.filter((tag) => tag.uuid).map((tag) => tag.uuid),
|
||||||
subspace.productAllocations
|
),
|
||||||
.filter((allocation) => allocation.tagUuid)
|
),
|
||||||
.map((allocation) => allocation.tagUuid),
|
},
|
||||||
),
|
|
||||||
),
|
|
||||||
}
|
|
||||||
: undefined,
|
|
||||||
product: subspace.productAllocations
|
|
||||||
? {
|
|
||||||
uuid: Not(
|
|
||||||
In(
|
|
||||||
subspace.productAllocations
|
|
||||||
.filter((allocation) => allocation.productUuid)
|
|
||||||
.map((allocation) => allocation.productUuid),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
}
|
|
||||||
: undefined,
|
|
||||||
});
|
});
|
||||||
|
|
||||||
const subspaceEntity = await queryRunner.manager.findOne(
|
const subspaceEntity = await queryRunner.manager.findOne(
|
||||||
SubspaceEntity,
|
SubspaceEntity,
|
||||||
{
|
{
|
||||||
where: { uuid: subspace.uuid },
|
where: { uuid: subspace.uuid },
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
const processedTags = await this.tagService.upsertTags(
|
|
||||||
subspace.productAllocations,
|
const processedTags = await this.tagService.processTags(
|
||||||
|
subspace.tags,
|
||||||
projectUuid,
|
projectUuid,
|
||||||
queryRunner,
|
queryRunner,
|
||||||
);
|
);
|
||||||
@ -112,11 +97,11 @@ export class SubspaceProductAllocationService {
|
|||||||
);
|
);
|
||||||
|
|
||||||
// Create the product-tag mapping based on the processed tags
|
// Create the product-tag mapping based on the processed tags
|
||||||
const productTagMapping = subspace.productAllocations?.map(
|
const productTagMapping = subspace.tags.map(
|
||||||
({ tagUuid, tagName, productUuid }) => {
|
({ uuid, name, productUuid }) => {
|
||||||
const inputTag = tagUuid
|
const inputTag = uuid
|
||||||
? createdTagsByUUID.get(tagUuid)
|
? createdTagsByUUID.get(uuid)
|
||||||
: createdTagsByName.get(tagName);
|
: createdTagsByName.get(name);
|
||||||
return {
|
return {
|
||||||
tag: inputTag?.uuid,
|
tag: inputTag?.uuid,
|
||||||
product: productUuid,
|
product: productUuid,
|
||||||
@ -133,6 +118,71 @@ export class SubspaceProductAllocationService {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// async processDeleteActions(dtos: ModifyTagDto[], queryRunner: QueryRunner) {
|
||||||
|
// // : Promise<SubspaceProductAllocationEntity[]>
|
||||||
|
// try {
|
||||||
|
// // if (!dtos || dtos.length === 0) {
|
||||||
|
// // throw new Error('No DTOs provided for deletion.');
|
||||||
|
// // }
|
||||||
|
// // const tagUuidsToDelete = dtos
|
||||||
|
// // .filter((dto) => dto.action === ModifyAction.DELETE && dto.tagUuid)
|
||||||
|
// // .map((dto) => dto.tagUuid);
|
||||||
|
// // if (tagUuidsToDelete.length === 0) return [];
|
||||||
|
// // const allocationsToUpdate = await queryRunner.manager.find(
|
||||||
|
// // SubspaceProductAllocationEntity,
|
||||||
|
// // {
|
||||||
|
// // where: { tag: In(tagUuidsToDelete) },
|
||||||
|
// // },
|
||||||
|
// // );
|
||||||
|
// // if (!allocationsToUpdate || allocationsToUpdate.length === 0) return [];
|
||||||
|
// // const deletedAllocations: SubspaceProductAllocationEntity[] = [];
|
||||||
|
// // const allocationUpdates: SubspaceProductAllocationEntity[] = [];
|
||||||
|
// // 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);
|
||||||
|
// // }
|
||||||
|
// // }
|
||||||
|
// // if (allocationUpdates.length > 0) {
|
||||||
|
// // await queryRunner.manager.save(
|
||||||
|
// // SubspaceProductAllocationEntity,
|
||||||
|
// // allocationUpdates,
|
||||||
|
// // );
|
||||||
|
// // }
|
||||||
|
// // if (deletedAllocations.length > 0) {
|
||||||
|
// // await queryRunner.manager.remove(
|
||||||
|
// // SubspaceProductAllocationEntity,
|
||||||
|
// // deletedAllocations,
|
||||||
|
// // );
|
||||||
|
// // }
|
||||||
|
// // await queryRunner.manager
|
||||||
|
// // .createQueryBuilder()
|
||||||
|
// // .delete()
|
||||||
|
// // .from('subspace_product_tags')
|
||||||
|
// // .where(
|
||||||
|
// // 'subspace_product_allocation_uuid NOT IN ' +
|
||||||
|
// // queryRunner.manager
|
||||||
|
// // .createQueryBuilder()
|
||||||
|
// // .select('allocation.uuid')
|
||||||
|
// // .from(SubspaceProductAllocationEntity, 'allocation')
|
||||||
|
// // .getQuery() +
|
||||||
|
// // ')',
|
||||||
|
// // )
|
||||||
|
// // .execute();
|
||||||
|
// // return deletedAllocations;
|
||||||
|
// } catch (error) {
|
||||||
|
// throw this.handleError(error, `Failed to delete tags in subspace`);
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
|
||||||
async unlinkModels(
|
async unlinkModels(
|
||||||
allocations: SubspaceProductAllocationEntity[],
|
allocations: SubspaceProductAllocationEntity[],
|
||||||
queryRunner: QueryRunner,
|
queryRunner: QueryRunner,
|
||||||
@ -155,6 +205,67 @@ export class SubspaceProductAllocationService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// private async validateTagWithinSubspace(
|
||||||
|
// queryRunner: QueryRunner | undefined,
|
||||||
|
// tag: NewTagEntity & { product: string },
|
||||||
|
// subspace: SubspaceEntity,
|
||||||
|
// spaceAllocationsToExclude?: SpaceProductAllocationEntity[],
|
||||||
|
// ): Promise<void> {
|
||||||
|
// // const existingTagInSpace = await (queryRunner
|
||||||
|
// // ? queryRunner.manager.findOne(SpaceProductAllocationEntity, {
|
||||||
|
// // where: {
|
||||||
|
// // product: { uuid: tag.product },
|
||||||
|
// // space: { uuid: subspace.space.uuid },
|
||||||
|
// // tag: { uuid: tag.uuid },
|
||||||
|
// // },
|
||||||
|
// // })
|
||||||
|
// // : this.spaceProductAllocationRepository.findOne({
|
||||||
|
// // where: {
|
||||||
|
// // product: { uuid: tag.product },
|
||||||
|
// // space: { uuid: subspace.space.uuid },
|
||||||
|
// // tag: { uuid: tag.uuid },
|
||||||
|
// // },
|
||||||
|
// // }));
|
||||||
|
// // const isExcluded = spaceAllocationsToExclude?.some(
|
||||||
|
// // (excludedAllocation) =>
|
||||||
|
// // excludedAllocation.product.uuid === tag.product &&
|
||||||
|
// // excludedAllocation.tags.some((t) => t.uuid === tag.uuid),
|
||||||
|
// // );
|
||||||
|
// // if (!isExcluded && existingTagInSpace) {
|
||||||
|
// // throw new HttpException(
|
||||||
|
// // `Tag ${tag.uuid} (Product: ${tag.product}) is already allocated at the space level (${subspace.space.uuid}). Cannot allocate the same tag in a subspace.`,
|
||||||
|
// // HttpStatus.BAD_REQUEST,
|
||||||
|
// // );
|
||||||
|
// // }
|
||||||
|
// // // ?: Check if the tag is already allocated in another "subspace" within the same space
|
||||||
|
// // const existingTagInSameSpace = await (queryRunner
|
||||||
|
// // ? queryRunner.manager.findOne(SubspaceProductAllocationEntity, {
|
||||||
|
// // where: {
|
||||||
|
// // product: { uuid: tag.product },
|
||||||
|
// // subspace: { space: subspace.space },
|
||||||
|
// // tag: { uuid: tag.uuid },
|
||||||
|
// // },
|
||||||
|
// // relations: ['subspace'],
|
||||||
|
// // })
|
||||||
|
// // : this.subspaceProductAllocationRepository.findOne({
|
||||||
|
// // where: {
|
||||||
|
// // product: { uuid: tag.product },
|
||||||
|
// // subspace: { space: subspace.space },
|
||||||
|
// // tag: { uuid: tag.uuid },
|
||||||
|
// // },
|
||||||
|
// // relations: ['subspace'],
|
||||||
|
// // }));
|
||||||
|
// // if (
|
||||||
|
// // existingTagInSameSpace &&
|
||||||
|
// // existingTagInSameSpace.subspace.uuid !== subspace.uuid
|
||||||
|
// // ) {
|
||||||
|
// // throw new HttpException(
|
||||||
|
// // `Tag ${tag.uuid} (Product: ${tag.product}) is already allocated in another subspace (${existingTagInSameSpace.subspace.uuid}) within the same space (${subspace.space.uuid}).`,
|
||||||
|
// // HttpStatus.BAD_REQUEST,
|
||||||
|
// // );
|
||||||
|
// // }
|
||||||
|
// }
|
||||||
|
|
||||||
private createNewSubspaceAllocation(
|
private createNewSubspaceAllocation(
|
||||||
subspace: SubspaceEntity,
|
subspace: SubspaceEntity,
|
||||||
allocationData: { product: string; tag: string },
|
allocationData: { product: string; tag: string },
|
||||||
|
@ -12,7 +12,7 @@ import {
|
|||||||
AddSubspaceDto,
|
AddSubspaceDto,
|
||||||
GetSpaceParam,
|
GetSpaceParam,
|
||||||
GetSubSpaceParam,
|
GetSubSpaceParam,
|
||||||
UpdateSubspaceDto,
|
ModifySubspaceDto,
|
||||||
} from '../../dtos';
|
} from '../../dtos';
|
||||||
|
|
||||||
import { SubspaceModelEntity } from '@app/common/modules/space-model';
|
import { SubspaceModelEntity } from '@app/common/modules/space-model';
|
||||||
@ -39,7 +39,7 @@ export class SubSpaceService {
|
|||||||
private readonly subspaceProductAllocationService: SubspaceProductAllocationService,
|
private readonly subspaceProductAllocationService: SubspaceProductAllocationService,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
private async createSubspaces(
|
async createSubspaces(
|
||||||
subspaceData: Array<{
|
subspaceData: Array<{
|
||||||
subspaceName: string;
|
subspaceName: string;
|
||||||
space: SpaceEntity;
|
space: SpaceEntity;
|
||||||
@ -103,13 +103,13 @@ export class SubSpaceService {
|
|||||||
queryRunner,
|
queryRunner,
|
||||||
);
|
);
|
||||||
await Promise.all(
|
await Promise.all(
|
||||||
addSubspaceDtos.map(async ({ productAllocations }, index) => {
|
addSubspaceDtos.map(async ({ tags }, index) => {
|
||||||
// map the dto to the corresponding subspace
|
// map the dto to the corresponding subspace
|
||||||
const subspace = createdSubspaces[index];
|
const subspace = createdSubspaces[index];
|
||||||
await this.createAllocations({
|
await this.createAllocations({
|
||||||
projectUuid,
|
projectUuid,
|
||||||
queryRunner,
|
queryRunner,
|
||||||
productAllocations,
|
tags,
|
||||||
type: AllocationsOwnerType.SUBSPACE,
|
type: AllocationsOwnerType.SUBSPACE,
|
||||||
subspace,
|
subspace,
|
||||||
});
|
});
|
||||||
@ -145,7 +145,7 @@ export class SubSpaceService {
|
|||||||
space,
|
space,
|
||||||
);
|
);
|
||||||
const newSubspace = this.subspaceRepository.create({
|
const newSubspace = this.subspaceRepository.create({
|
||||||
subspaceName: addSubspaceDto.subspaceName,
|
...addSubspaceDto,
|
||||||
space,
|
space,
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -305,7 +305,7 @@ export class SubSpaceService {
|
|||||||
} */
|
} */
|
||||||
|
|
||||||
async updateSubspaceInSpace(
|
async updateSubspaceInSpace(
|
||||||
subspaceDtos: UpdateSubspaceDto[],
|
subspaceDtos: ModifySubspaceDto[],
|
||||||
queryRunner: QueryRunner,
|
queryRunner: QueryRunner,
|
||||||
space: SpaceEntity,
|
space: SpaceEntity,
|
||||||
projectUuid: string,
|
projectUuid: string,
|
||||||
@ -324,63 +324,42 @@ export class SubSpaceService {
|
|||||||
disabled: true,
|
disabled: true,
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
await queryRunner.manager.delete(SubspaceProductAllocationEntity, {
|
await queryRunner.manager.delete(SubspaceProductAllocationEntity, {
|
||||||
subspace: {
|
subspace: { uuid: Not(In(subspaceDtos.map((dto) => dto.uuid))) },
|
||||||
uuid: Not(
|
|
||||||
In(subspaceDtos.filter(({ uuid }) => uuid).map(({ uuid }) => uuid)),
|
|
||||||
),
|
|
||||||
},
|
|
||||||
});
|
});
|
||||||
|
|
||||||
// create or update subspaces provided in the list
|
// create or update subspaces provided in the list
|
||||||
const newSubspaces = this.subspaceRepository.create(
|
const newSubspaces = this.subspaceRepository.create(
|
||||||
subspaceDtos
|
subspaceDtos.filter((dto) => !dto.uuid),
|
||||||
.filter((dto) => !dto.uuid)
|
|
||||||
.map((dto) => ({
|
|
||||||
subspaceName: dto.subspaceName,
|
|
||||||
space,
|
|
||||||
})),
|
|
||||||
);
|
);
|
||||||
|
|
||||||
const existingSubspaces = await this.subspaceRepository.find({
|
|
||||||
where: {
|
|
||||||
uuid: In(
|
|
||||||
subspaceDtos.filter((dto) => dto.uuid).map((dto) => dto.uuid),
|
|
||||||
),
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
if (
|
|
||||||
existingSubspaces.length !==
|
|
||||||
subspaceDtos.filter((dto) => dto.uuid).length
|
|
||||||
) {
|
|
||||||
throw new HttpException(
|
|
||||||
`Some subspaces with provided UUIDs do not exist in the space.`,
|
|
||||||
HttpStatus.NOT_FOUND,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
const updatedSubspaces: SubspaceEntity[] = await queryRunner.manager.save(
|
const updatedSubspaces: SubspaceEntity[] = await queryRunner.manager.save(
|
||||||
SubspaceEntity,
|
SubspaceEntity,
|
||||||
newSubspaces,
|
[...newSubspaces, ...subspaceDtos.filter((dto) => dto.uuid)].map(
|
||||||
|
(subspace) => ({ ...subspace, space }),
|
||||||
|
),
|
||||||
);
|
);
|
||||||
const allSubspaces = [...updatedSubspaces, ...existingSubspaces];
|
|
||||||
// create or update allocations for the subspaces
|
// create or update allocations for the subspaces
|
||||||
if (allSubspaces.length > 0) {
|
if (updatedSubspaces.length > 0) {
|
||||||
await this.subspaceProductAllocationService.updateSubspaceProductAllocationsV2(
|
await this.subspaceProductAllocationService.updateSubspaceProductAllocationsV2(
|
||||||
subspaceDtos.map((dto) => ({
|
subspaceDtos.map((dto) => {
|
||||||
...dto,
|
if (!dto.uuid) {
|
||||||
uuid:
|
dto.uuid = updatedSubspaces.find(
|
||||||
dto.uuid ||
|
(subspace) => subspace.subspaceName === dto.subspaceName,
|
||||||
allSubspaces.find((s) => s.subspaceName === dto.subspaceName)
|
)?.uuid;
|
||||||
?.uuid,
|
}
|
||||||
})),
|
return {
|
||||||
|
tags: dto.tags || [],
|
||||||
|
uuid: dto.uuid,
|
||||||
|
};
|
||||||
|
}),
|
||||||
projectUuid,
|
projectUuid,
|
||||||
queryRunner,
|
queryRunner,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.log(error);
|
|
||||||
throw new HttpException(
|
throw new HttpException(
|
||||||
`An error occurred while modifying subspaces: ${error.message}`,
|
`An error occurred while modifying subspaces: ${error.message}`,
|
||||||
HttpStatus.INTERNAL_SERVER_ERROR,
|
HttpStatus.INTERNAL_SERVER_ERROR,
|
||||||
@ -499,10 +478,10 @@ export class SubSpaceService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async createAllocations(dto: CreateAllocationsDto): Promise<void> {
|
async createAllocations(dto: CreateAllocationsDto): Promise<void> {
|
||||||
const { projectUuid, queryRunner, productAllocations, type } = dto;
|
const { projectUuid, queryRunner, tags, type } = dto;
|
||||||
if (!productAllocations) return;
|
|
||||||
const allocationsData = await this.newTagService.upsertTags(
|
const allocationsData = await this.newTagService.processTags(
|
||||||
productAllocations,
|
tags,
|
||||||
projectUuid,
|
projectUuid,
|
||||||
queryRunner,
|
queryRunner,
|
||||||
);
|
);
|
||||||
@ -512,17 +491,15 @@ export class SubSpaceService {
|
|||||||
const createdTagsByName = new Map(allocationsData.map((t) => [t.name, t]));
|
const createdTagsByName = new Map(allocationsData.map((t) => [t.name, t]));
|
||||||
|
|
||||||
// Create the product-tag mapping based on the processed tags
|
// Create the product-tag mapping based on the processed tags
|
||||||
const productTagMapping = productAllocations.map(
|
const productTagMapping = tags.map(({ uuid, name, productUuid }) => {
|
||||||
({ tagUuid, tagName, productUuid }) => {
|
const inputTag = uuid
|
||||||
const inputTag = tagUuid
|
? createdTagsByUUID.get(uuid)
|
||||||
? createdTagsByUUID.get(tagUuid)
|
: createdTagsByName.get(name);
|
||||||
: createdTagsByName.get(tagName);
|
return {
|
||||||
return {
|
tag: inputTag?.uuid,
|
||||||
tag: inputTag?.uuid,
|
product: productUuid,
|
||||||
product: productUuid,
|
};
|
||||||
};
|
});
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
switch (type) {
|
switch (type) {
|
||||||
case AllocationsOwnerType.SUBSPACE: {
|
case AllocationsOwnerType.SUBSPACE: {
|
||||||
|
1
src/space/services/tag/index.ts
Normal file
1
src/space/services/tag/index.ts
Normal file
@ -0,0 +1 @@
|
|||||||
|
export * from './tag.service';
|
8
src/space/services/tag/tag.service.ts
Normal file
8
src/space/services/tag/tag.service.ts
Normal file
@ -0,0 +1,8 @@
|
|||||||
|
import { Injectable } from '@nestjs/common';
|
||||||
|
|
||||||
|
// todo: find out why we need to import this
|
||||||
|
// in community module in order for the whole system to work
|
||||||
|
@Injectable()
|
||||||
|
export class TagService {
|
||||||
|
constructor() {}
|
||||||
|
}
|
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user