Compare commits

..

43 Commits

Author SHA1 Message Date
6973e8b195 task: sort communities by creation date (#416) 2025-06-19 11:13:24 +03:00
92d102d08f Merge pull request #413 from SyncrowIOT/fix-staging-insirt-logs-data
Fix-staging-insirt-logs-data
2025-06-18 07:35:30 -06:00
7dc28d0cb3 fix: enable AQI sensor historical data update in device status processing 2025-06-18 07:32:39 -06:00
d9ad431a23 fix: correct procedure names in energy consumption updates 2025-06-18 05:33:49 -06:00
4bf43dab2b feat: enhance device status DTO and service with optional properties and environment checks 2025-06-18 05:33:43 -06:00
7520b8d9c7 fix: power clamp historical API (#408) 2025-06-17 15:17:49 +03:00
72753b6dfb merge dev to main 2025-06-14 15:18:20 -06:00
568eef8119 Merge branch 'dev' 2025-06-14 15:04:48 -06:00
a40560a0b1 Merge pull request #380 from SyncrowIOT/revert-378-daily-aqi-sensor
Revert "SQL model for aqi score and processing air data"
2025-05-21 20:04:43 -04:00
7d6f1bb944 Revert "SQL model for aqi score and processing air data" 2025-05-21 20:01:05 -04:00
434316fe51 Merge pull request #378 from SyncrowIOT/daily-aqi-sensor
SQL model for aqi score and processing air data
2025-05-21 16:54:19 -04:00
287bb4c5e4 SQL model for aqi score and processing air data 2025-05-21 16:49:44 -04:00
85602fa952 check deployment 2025-05-08 13:15:31 +03:00
25a4d3e91b Merge pull request #364 from SyncrowIOT/revert-363-DATA-date-param-filtering
Revert "DATA-date-param-moved"
2025-05-08 13:08:58 +03:00
d3a560d18f Revert "DATA-date-param-moved" 2025-05-08 13:08:41 +03:00
ab99bb5afc Merge pull request #363 from SyncrowIOT/DATA-date-param-filtering
DATA-date-param-moved
2025-05-08 13:07:51 +03:00
67911d5ff1 moved param 2025-05-08 13:06:39 +03:00
13e3f3e213 Merge branch 'dev' 2025-04-29 09:58:05 +03:00
327d678656 Enhance TuyaWebSocketService to handle environment-specific message extraction 2025-03-28 03:40:09 +03:00
dd5447fc5f Merge pull request #311 from SyncrowIOT/dev 2025-03-13 13:56:50 +04:00
7df5b9ab08 Merge branch 'main' of https://github.com/SyncrowIOT/backend 2025-03-13 11:06:06 +03:00
06b4407b85 Merge branch 'dev' 2025-03-13 11:05:11 +03:00
1d6f3b8e65 Merge pull request #309 from SyncrowIOT:dev
propagating of space model to space
2025-03-13 00:27:23 +04:00
80659f7a48 Merge branch 'dev' 2025-03-12 02:22:33 +03:00
4a5f2f3b9f Merge branch 'dev' 2025-03-11 20:27:22 +03:00
a57f4e1c65 Merge branch 'dev' 2025-03-11 15:33:52 +03:00
b2d52c7622 Merge branch 'dev' 2025-02-20 03:46:08 -06:00
c9cbb2e085 Merge pull request #262 from SyncrowIOT/dev
change subspace tag movement
2025-02-19 13:11:46 +04:00
8aa3de5fdc config 2025-02-18 16:59:38 +04:00
bc1ee9a53b test deploy 2 2025-02-18 05:39:55 -06:00
19356c3833 test deploy 2025-02-18 05:35:06 -06:00
8737ee992b Update GitHub Actions workflow for Node.js app deployment to Azure 2025-02-18 05:08:51 -06:00
e98a99be73 Update GitHub Actions workflow for containerized deployment to Azure Web App 2025-02-18 05:03:05 -06:00
93efa15f3c Empty commit 2025-02-18 04:50:54 -06:00
c305e39ff2 Add or update the Azure App Service build and deployment workflow config 2025-02-18 04:34:31 -06:00
61e4d220dc test deploy 2025-02-18 04:15:24 -06:00
cd4bbe1788 Empty commit 2025-02-18 00:10:22 -06:00
d770a0c732 Remove robots.txt request handling middleware 2025-02-17 18:51:16 -06:00
030e6ae902 Add middleware to ignore requests for robots*.txt files 2025-02-17 18:43:43 -06:00
9d8287b82b Remove trailing whitespace in GitHub workflow file 2025-02-17 18:05:20 -06:00
d741a6c1f3 Empty commit 2025-02-17 17:50:51 -06:00
6d55704dd4 Merge branch 'dev' 2025-02-17 17:35:45 -06:00
d8ad9e55ea Merge pull request #253 from SyncrowIOT/dev
Dev
2025-02-06 09:26:54 +04:00
47 changed files with 992 additions and 662 deletions

View File

@ -21,7 +21,6 @@ module.exports = {
'@typescript-eslint/explicit-function-return-type': 'off',
'@typescript-eslint/explicit-module-boundary-types': 'off',
'@typescript-eslint/no-explicit-any': 'off',
"@typescript-eslint/no-unused-vars": 'warn',
},
settings: {
'import/resolver': {

View File

@ -1,4 +1,7 @@
name: Backend deployment to Azure App Service
# Docs for the Azure Web Apps Deploy action: https://github.com/Azure/webapps-deploy
# More GitHub Actions for Azure: https://github.com/Azure/actions
name: Build and deploy container app to Azure Web App - syncrow(staging)
on:
push:
@ -6,50 +9,43 @@ on:
- main
workflow_dispatch:
env:
AZURE_WEB_APP_NAME: 'syncrow'
AZURE_WEB_APP_SLOT_NAME: 'staging'
ACR_REGISTRY: 'syncrow.azurecr.io'
IMAGE_NAME: 'backend'
IMAGE_TAG: 'latest'
jobs:
build_and_deploy:
runs-on: ubuntu-latest
build:
runs-on: 'ubuntu-latest'
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v2
- name: Set up Node.js
uses: actions/setup-node@v3
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v2
- name: Log in to registry
uses: docker/login-action@v2
with:
node-version: '20'
registry: https://syncrow.azurecr.io/
username: ${{ secrets.AzureAppService_ContainerUsername_47395803300340b49931ea82f6d80be3 }}
password: ${{ secrets.AzureAppService_ContainerPassword_e7b0ff54f54d44cba04a970a22384848 }}
- name: Install dependencies and build project
run: |
npm install
npm run build
- name: Log in to Azure
uses: azure/login@v1
- name: Build and push container image to registry
uses: docker/build-push-action@v3
with:
creds: ${{ secrets.AZURE_CREDENTIALS }}
push: true
tags: syncrow.azurecr.io/${{ secrets.AzureAppService_ContainerUsername_47395803300340b49931ea82f6d80be3 }}/syncrow/backend:${{ github.sha }}
file: ./Dockerfile
- name: Log in to Azure Container Registry
run: az acr login --name ${{ env.ACR_REGISTRY }}
deploy:
runs-on: ubuntu-latest
needs: build
environment:
name: 'staging'
url: ${{ steps.deploy-to-webapp.outputs.webapp-url }}
- name: List build output
run: ls -R dist/
- name: Build and push Docker image
run: |
docker build . -t ${{ env.ACR_REGISTRY }}/${{ env.IMAGE_NAME }}:${{ env.IMAGE_TAG }}
docker push ${{ env.ACR_REGISTRY }}/${{ env.IMAGE_NAME }}:${{ env.IMAGE_TAG }}
- name: Set Web App with Docker container
run: |
az webapp config container set \
--name ${{ env.AZURE_WEB_APP_NAME }} \
--resource-group backend \
--docker-custom-image-name ${{ env.ACR_REGISTRY }}/${{ env.IMAGE_NAME }}:${{ env.IMAGE_TAG }} \
--docker-registry-server-url https://${{ env.ACR_REGISTRY }}
steps:
- name: Deploy to Azure Web App
id: deploy-to-webapp
uses: azure/webapps-deploy@v2
with:
app-name: 'syncrow'
slot-name: 'staging'
publish-profile: ${{ secrets.AzureAppService_PublishProfile_44f7766441ec4796b74789e9761ef589 }}
images: 'syncrow.azurecr.io/${{ secrets.AzureAppService_ContainerUsername_47395803300340b49931ea82f6d80be3 }}/syncrow/backend:${{ github.sha }}'

73
.github/workflows/main_syncrow(stg).yml vendored Normal file
View File

@ -0,0 +1,73 @@
# Docs for the Azure Web Apps Deploy action: https://github.com/Azure/webapps-deploy
# More GitHub Actions for Azure: https://github.com/Azure/actions
name: Build and deploy Node.js app to Azure Web App - syncrow
on:
push:
branches:
- main
workflow_dispatch:
jobs:
build:
runs-on: ubuntu-latest
permissions:
contents: read #This is required for actions/checkout
steps:
- uses: actions/checkout@v4
- name: Set up Node.js version
uses: actions/setup-node@v3
with:
node-version: '20.x'
- name: npm install, build, and test
run: |
npm install
npm run build --if-present
npm run test --if-present
- name: Zip artifact for deployment
run: zip release.zip ./* -r
- name: Upload artifact for deployment job
uses: actions/upload-artifact@v4
with:
name: node-app
path: release.zip
deploy:
runs-on: ubuntu-latest
needs: build
environment:
name: 'stg'
url: ${{ steps.deploy-to-webapp.outputs.webapp-url }}
permissions:
id-token: write #This is required for requesting the JWT
contents: read #This is required for actions/checkout
steps:
- name: Download artifact from build job
uses: actions/download-artifact@v4
with:
name: node-app
- name: Unzip artifact for deployment
run: unzip release.zip
- name: Login to Azure
uses: azure/login@v2
with:
client-id: ${{ secrets.AZUREAPPSERVICE_CLIENTID_515C8E782CFF431AB20448C85CA0FE58 }}
tenant-id: ${{ secrets.AZUREAPPSERVICE_TENANTID_2AEFE5534424490387C08FAE41573CC2 }}
subscription-id: ${{ secrets.AZUREAPPSERVICE_SUBSCRIPTIONID_00623C33023749FEA5F6BC36884F9C8A }}
- name: 'Deploy to Azure Web App'
id: deploy-to-webapp
uses: azure/webapps-deploy@v3
with:
app-name: 'syncrow'
slot-name: 'stg'
package: .

View File

@ -501,7 +501,6 @@ export class ControllerRoute {
};
static PowerClamp = class {
public static readonly ROUTE = 'power-clamp';
static ACTIONS = class {
public static readonly GET_ENERGY_SUMMARY =
'Get power clamp historical data';

View File

@ -25,7 +25,6 @@ import {
InviteUserEntity,
InviteUserSpaceEntity,
} from '../modules/Invite-user/entities';
import { SpaceDailyOccupancyDurationEntity } from '../modules/occupancy/entities';
import {
PowerClampDailyEntity,
PowerClampHourlyEntity,
@ -47,6 +46,7 @@ import {
SubspaceModelProductAllocationEntity,
} from '../modules/space-model/entities';
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 { SpaceEntity } from '../modules/space/entities/space.entity';
import { SubspaceProductAllocationEntity } from '../modules/space/entities/subspace/subspace-product-allocation.entity';
@ -58,6 +58,7 @@ import {
UserSpaceEntity,
} from '../modules/user/entities';
import { VisitorPasswordEntity } from '../modules/visitor-password/entities';
import { SpaceDailyOccupancyDurationEntity } from '../modules/occupancy/entities';
@Module({
imports: [
TypeOrmModule.forRootAsync({
@ -86,6 +87,7 @@ import { VisitorPasswordEntity } from '../modules/visitor-password/entities';
PermissionTypeEntity,
CommunityEntity,
SpaceEntity,
SpaceLinkEntity,
SubspaceEntity,
UserSpaceEntity,
DeviceUserPermissionEntity,
@ -125,7 +127,7 @@ import { VisitorPasswordEntity } from '../modules/visitor-password/entities';
logger: typeOrmLogger,
extra: {
charset: 'utf8mb4',
max: 50, // set pool max size
max: 20, // set pool max size
idleTimeoutMillis: 5000, // close idle clients after 5 second
connectionTimeoutMillis: 12_000, // return an error after 11 second if connection could not be established
maxUses: 7500, // close (and replace) a connection after it has been used 7500 times (see below for discussion)

View File

@ -1,9 +1,10 @@
import { ApiProperty } from '@nestjs/swagger';
import { Transform } from 'class-transformer';
import { IsBoolean, IsOptional } from 'class-validator';
import { BooleanValues } from '../constants/boolean-values.enum';
import { IsBoolean, IsDate, IsOptional } from 'class-validator';
import { IsPageRequestParam } from '../validators/is-page-request-param.validator';
import { ApiProperty } from '@nestjs/swagger';
import { IsSizeRequestParam } from '../validators/is-size-request-param.validator';
import { Transform } from 'class-transformer';
import { parseToDate } from '../util/parseToDate';
import { BooleanValues } from '../constants/boolean-values.enum';
export class PaginationRequestGetListDto {
@ApiProperty({
@ -18,7 +19,6 @@ export class PaginationRequestGetListDto {
return value.obj.includeSpaces === BooleanValues.TRUE;
})
public includeSpaces?: boolean = false;
@IsOptional()
@IsPageRequestParam({
message: 'Page must be bigger than 0',
@ -40,4 +40,40 @@ export class PaginationRequestGetListDto {
description: 'Size request',
})
size?: number;
@IsOptional()
@ApiProperty({
name: 'name',
required: false,
description: 'Name to be filtered',
})
name?: string;
@ApiProperty({
name: 'from',
required: false,
type: Number,
description: `Start time in UNIX timestamp format to filter`,
example: 1674172800000,
})
@IsOptional()
@Transform(({ value }) => parseToDate(value))
@IsDate({
message: `From must be in UNIX timestamp format in order to parse to Date instance`,
})
from?: Date;
@ApiProperty({
name: 'to',
required: false,
type: Number,
description: `End time in UNIX timestamp format to filter`,
example: 1674259200000,
})
@IsOptional()
@Transform(({ value }) => parseToDate(value))
@IsDate({
message: `To must be in UNIX timestamp format in order to parse to Date instance`,
})
to?: Date;
}

View File

@ -13,6 +13,7 @@ class StatusDto {
@IsNotEmpty()
value: any;
t?: string | number | Date;
}
export class AddDeviceStatusDto {

View File

@ -28,6 +28,8 @@ import { AqiDataService } from '@app/common/helper/services/aqi.data.service';
export class DeviceStatusFirebaseService {
private tuya: TuyaContext;
private firebaseDb: Database;
private readonly isDevEnv: boolean;
constructor(
private readonly configService: ConfigService,
private readonly deviceRepository: DeviceRepository,
@ -47,6 +49,8 @@ export class DeviceStatusFirebaseService {
// Initialize firebaseDb using firebaseDataBase function
this.firebaseDb = firebaseDataBase(this.configService);
this.isDevEnv =
this.configService.get<string>('NODE_ENV') === 'development';
}
async addDeviceStatusByDeviceUuid(
deviceTuyaUuid: string,
@ -61,7 +65,7 @@ export class DeviceStatusFirebaseService {
const deviceStatusSaved = await this.createDeviceStatusFirebase({
deviceUuid: device.uuid,
deviceTuyaUuid: deviceTuyaUuid,
status: deviceStatus.status,
status: deviceStatus?.status,
productUuid: deviceStatus.productUuid,
productType: deviceStatus.productType,
});
@ -122,7 +126,7 @@ export class DeviceStatusFirebaseService {
return {
productUuid: deviceDetails.productDevice.uuid,
productType: deviceDetails.productDevice.prodType,
status: deviceStatus.result[0].status,
status: deviceStatus.result[0]?.status,
};
} catch (error) {
throw new HttpException(
@ -187,18 +191,18 @@ export class DeviceStatusFirebaseService {
if (!existingData.productType) {
existingData.productType = addDeviceStatusDto.productType;
}
if (!existingData.status) {
if (!existingData?.status) {
existingData.status = [];
}
// Create a map to track existing status codes
const statusMap = new Map(
existingData.status.map((item) => [item.code, item.value]),
existingData?.status.map((item) => [item.code, item.value]),
);
// Update or add status codes
for (const statusItem of addDeviceStatusDto.status) {
for (const statusItem of addDeviceStatusDto?.status) {
statusMap.set(statusItem.code, statusItem.value);
}
@ -211,64 +215,126 @@ export class DeviceStatusFirebaseService {
return existingData;
});
// 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(),
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);
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,
]);
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),
);
const energyStatus = addDeviceStatusDto?.log?.properties?.find(
(status) => energyCodes.has(status.code),
);
if (energyStatus) {
await this.powerClampService.updateEnergyConsumedHistoricalData(
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.CPS ||
addDeviceStatusDto.productType === ProductType.WPS
) {
const occupancyCodes = new Set([PresenceSensorEnum.PRESENCE_STATE]);
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 occupancyStatus = addDeviceStatusDto?.log?.properties?.find(
(status) => occupancyCodes.has(status.code),
);
const energyStatus = addDeviceStatusDto?.status?.find((status) => {
return energyCodes.has(status.code as PowerClampEnergyEnum);
});
if (occupancyStatus) {
await this.occupancyService.updateOccupancySensorHistoricalData(
addDeviceStatusDto.deviceUuid,
);
await this.occupancyService.updateOccupancySensorHistoricalDurationData(
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,
);
}
}
if (addDeviceStatusDto.productType === ProductType.AQI) {
await this.aqiDataService.updateAQISensorHistoricalData(
addDeviceStatusDto.deviceUuid,
);
}
// Return the updated data
const snapshot: DataSnapshot = await get(dataRef);
return snapshot.val();

View File

@ -1,43 +1,26 @@
import { utilities as nestWinstonModuleUtilities } from 'nest-winston';
import * as winston from 'winston';
const environment = process.env.NODE_ENV || 'local';
export const winstonLoggerOptions: winston.LoggerOptions = {
level:
environment === 'local'
? 'debug'
: environment === 'development'
? 'warn'
: 'error',
process.env.AZURE_POSTGRESQL_DATABASE === 'development' ? 'debug' : 'error',
transports: [
new winston.transports.Console({
level:
environment === 'local'
? 'debug'
: environment === 'development'
? 'warn'
: 'error',
format: winston.format.combine(
winston.format.timestamp(),
nestWinstonModuleUtilities.format.nestLike('MyApp', {
prettyPrint: environment === 'local',
prettyPrint: true,
}),
),
}),
// Only create file logs if NOT local
...(environment !== 'local'
? [
new winston.transports.File({
filename: 'logs/error.log',
level: 'error',
format: winston.format.json(),
}),
new winston.transports.File({
filename: 'logs/combined.log',
level: 'info',
format: winston.format.json(),
}),
]
: []),
new winston.transports.File({
filename: 'logs/error.log',
level: 'error',
format: winston.format.json(),
}),
new winston.transports.File({
filename: 'logs/combined.log',
format: winston.format.json(),
}),
],
};

View File

@ -1,3 +1,32 @@
import { Column, Entity, JoinColumn, ManyToOne } from 'typeorm';
import { AbstractEntity } from '../../abstract/entities/abstract.entity';
import { SpaceEntity } from './space.entity';
import { Direction } from '@app/common/constants/direction.enum';
export class SpaceLinkEntity extends AbstractEntity {}
@Entity({ name: 'space-link' })
export class SpaceLinkEntity extends AbstractEntity {
@ManyToOne(() => SpaceEntity, { nullable: false, onDelete: 'CASCADE' })
@JoinColumn({ name: 'start_space_id' })
public startSpace: SpaceEntity;
@ManyToOne(() => SpaceEntity, { nullable: false, onDelete: 'CASCADE' })
@JoinColumn({ name: 'end_space_id' })
public endSpace: SpaceEntity;
@Column({
nullable: false,
default: false,
})
public disabled: boolean;
@Column({
nullable: false,
enum: Object.values(Direction),
})
direction: string;
constructor(partial: Partial<SpaceLinkEntity>) {
super();
Object.assign(this, partial);
}
}

View File

@ -1,17 +1,18 @@
import { Column, Entity, JoinColumn, ManyToOne, OneToMany } from 'typeorm';
import { SpaceDto } from '../dtos';
import { AbstractEntity } from '../../abstract/entities/abstract.entity';
import { AqiSpaceDailyPollutantStatsEntity } from '../../aqi/entities';
import { CommunityEntity } from '../../community/entities';
import { UserSpaceEntity } from '../../user/entities';
import { DeviceEntity } from '../../device/entities';
import { InviteUserSpaceEntity } from '../../Invite-user/entities';
import { SpaceDailyOccupancyDurationEntity } from '../../occupancy/entities';
import { PresenceSensorDailySpaceEntity } from '../../presence-sensor/entities';
import { CommunityEntity } from '../../community/entities';
import { SpaceLinkEntity } from './space-link.entity';
import { SceneEntity } from '../../scene/entities';
import { SpaceModelEntity } from '../../space-model';
import { UserSpaceEntity } from '../../user/entities';
import { SpaceDto } from '../dtos';
import { InviteUserSpaceEntity } from '../../Invite-user/entities';
import { SpaceProductAllocationEntity } from './space-product-allocation.entity';
import { SubspaceEntity } from './subspace/subspace.entity';
import { PresenceSensorDailySpaceEntity } from '../../presence-sensor/entities';
import { AqiSpaceDailyPollutantStatsEntity } from '../../aqi/entities';
import { SpaceDailyOccupancyDurationEntity } from '../../occupancy/entities';
@Entity({ name: 'space' })
export class SpaceEntity extends AbstractEntity<SpaceDto> {
@ -74,6 +75,16 @@ export class SpaceEntity extends AbstractEntity<SpaceDto> {
)
devices: DeviceEntity[];
@OneToMany(() => SpaceLinkEntity, (connection) => connection.startSpace, {
nullable: true,
})
public outgoingConnections: SpaceLinkEntity[];
@OneToMany(() => SpaceLinkEntity, (connection) => connection.endSpace, {
nullable: true,
})
public incomingConnections: SpaceLinkEntity[];
@Column({
nullable: true,
type: 'text',

View File

@ -1,6 +1,7 @@
import { Injectable } from '@nestjs/common';
import { DataSource, Repository } from 'typeorm';
import { InviteSpaceEntity } from '../entities/invite-space.entity';
import { SpaceLinkEntity } from '../entities/space-link.entity';
import { SpaceProductAllocationEntity } from '../entities/space-product-allocation.entity';
import { SpaceEntity } from '../entities/space.entity';
@ -12,7 +13,11 @@ export class SpaceRepository extends Repository<SpaceEntity> {
}
@Injectable()
export class SpaceLinkRepository {}
export class SpaceLinkRepository extends Repository<SpaceLinkEntity> {
constructor(private dataSource: DataSource) {
super(SpaceLinkEntity, dataSource.createEntityManager());
}
}
@Injectable()
export class InviteSpaceRepository extends Repository<InviteSpaceEntity> {

View File

@ -87,5 +87,9 @@
"ts-node": "^10.9.1",
"tsconfig-paths": "^4.2.0",
"typescript": "^5.1.3"
},
"engines": {
"node": "20.x",
"npm": "10.x"
}
}

View File

@ -78,7 +78,6 @@ import { AqiDataService } from '@app/common/helper/services/aqi.data.service';
ProjectRepository,
SpaceService,
InviteSpaceRepository,
// Todo: find out why this is needed
SpaceLinkService,
SubSpaceService,
ValidationService,

View File

@ -1,3 +1,4 @@
import { CommunityService } from '../services/community.service';
import {
Body,
Controller,
@ -9,18 +10,17 @@ import {
Query,
UseGuards,
} from '@nestjs/common';
import { ApiBearerAuth, ApiOperation, ApiTags } from '@nestjs/swagger';
import { ApiTags, ApiBearerAuth, ApiOperation } from '@nestjs/swagger';
import { AddCommunityDto } from '../dtos/add.community.dto';
import { GetCommunityParams } from '../dtos/get.community.dto';
import { UpdateCommunityNameDto } from '../dtos/update.community.dto';
import { CommunityService } from '../services/community.service';
// import { CheckUserCommunityGuard } from 'src/guards/user.community.guard';
import { ControllerRoute } from '@app/common/constants/controller-route';
import { BaseResponseDto } from '@app/common/dto/base.response.dto';
import { PaginationRequestWithSearchGetListDto } from '@app/common/dto/pagination-with-search.request.dto';
import { Permissions } from 'src/decorators/permissions.decorator';
import { PermissionsGuard } from 'src/guards/permissions.guard';
import { ProjectParam } from '../dtos';
import { PermissionsGuard } from 'src/guards/permissions.guard';
import { Permissions } from 'src/decorators/permissions.decorator';
import { PaginationRequestWithSearchGetListDto } from '@app/common/dto/pagination-with-search.request.dto';
@ApiTags('Community Module')
@Controller({
@ -45,21 +45,6 @@ export class CommunityController {
return await this.communityService.createCommunity(param, addCommunityDto);
}
@ApiBearerAuth()
@UseGuards(PermissionsGuard)
@Permissions('COMMUNITY_VIEW')
@ApiOperation({
summary: ControllerRoute.COMMUNITY.ACTIONS.LIST_COMMUNITY_SUMMARY,
description: ControllerRoute.COMMUNITY.ACTIONS.LIST_COMMUNITY_DESCRIPTION,
})
@Get('v2')
async getCommunitiesV2(
@Param() param: ProjectParam,
@Query() query: PaginationRequestWithSearchGetListDto,
): Promise<any> {
return this.communityService.getCommunitiesV2(param, query);
}
@ApiBearerAuth()
@UseGuards(PermissionsGuard)
@Permissions('COMMUNITY_VIEW')

View File

@ -1,7 +1,4 @@
import {
ORPHAN_COMMUNITY_NAME,
ORPHAN_SPACE_NAME,
} from '@app/common/constants/orphan-constant';
import { ORPHAN_COMMUNITY_NAME } from '@app/common/constants/orphan-constant';
import { BaseResponseDto } from '@app/common/dto/base.response.dto';
import { PageResponse } from '@app/common/dto/pagination.response.dto';
import { SuccessResponseDto } from '@app/common/dto/success.response.dto';
@ -25,7 +22,7 @@ import {
NotFoundException,
} from '@nestjs/common';
import { SpaceService } from 'src/space/services';
import { QueryRunner, SelectQueryBuilder } from 'typeorm';
import { SelectQueryBuilder } from 'typeorm';
import { AddCommunityDto, GetCommunityParams, ProjectParam } from '../dtos';
import { UpdateCommunityNameDto } from '../dtos/update.community.dto';
@ -72,18 +69,12 @@ export class CommunityService {
}
}
async getCommunityById(
params: GetCommunityParams,
queryRunner?: QueryRunner,
): Promise<BaseResponseDto> {
async getCommunityById(params: GetCommunityParams): Promise<BaseResponseDto> {
const { communityUuid, projectUuid } = params;
await this.validateProject(projectUuid);
const communityRepository =
queryRunner?.manager.getRepository(CommunityEntity) ||
this.communityRepository;
const community = await communityRepository.findOneBy({
const community = await this.communityRepository.findOneBy({
uuid: communityUuid,
});
@ -120,6 +111,7 @@ export class CommunityService {
.leftJoin('c.spaces', 's', 's.disabled = false')
.where('c.project = :projectUuid', { projectUuid })
.andWhere(`c.name != '${ORPHAN_COMMUNITY_NAME}-${project.name}'`)
.orderBy('c.createdAt', 'DESC')
.distinct(true);
if (pageable.search) {
qb.andWhere(
@ -170,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 },
);
}
const customModel = TypeORMCustomModel(this.communityRepository);
const { baseResponseDto, paginationResponseDto } =
await customModel.findAll({ ...pageable, modelName: 'community' }, qb);
if (includeSpaces) {
baseResponseDto.data = baseResponseDto.data.map((community) => ({
...community,
spaces: this.spaceService.buildSpaceHierarchy(community.spaces || []),
}));
}
return new PageResponse<CommunityDto>(
baseResponseDto,
paginationResponseDto,
);
} catch (error) {
// Generic error handling
if (error instanceof HttpException) {
throw error;
}
throw new HttpException(
error.message || 'An error occurred while fetching communities.',
HttpStatus.INTERNAL_SERVER_ERROR,
);
}
}
async updateCommunity(
params: GetCommunityParams,
updateCommunityDto: UpdateCommunityNameDto,

View File

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

View File

@ -1,7 +1,6 @@
import { DeviceTypeEnum } from '@app/common/constants/device-type.enum';
import { ApiProperty } from '@nestjs/swagger';
import {
IsArray,
IsEnum,
IsNotEmpty,
IsOptional,
@ -42,7 +41,16 @@ export class GetDeviceLogsDto {
@IsOptional()
public endTime: string;
}
export class GetDoorLockDevices {
@ApiProperty({
description: 'Device Type',
enum: DeviceTypeEnum,
required: false,
})
@IsEnum(DeviceTypeEnum)
@IsOptional()
public deviceType: DeviceTypeEnum;
}
export class GetDevicesBySpaceOrCommunityDto {
@ApiProperty({
description: 'Device Product Type',
@ -64,23 +72,3 @@ export class GetDevicesBySpaceOrCommunityDto {
@IsNotEmpty({ message: 'Either spaceUuid or communityUuid must be provided' })
requireEither?: never; // This ensures at least one of them is provided
}
export class GetDevicesFilterDto {
@ApiProperty({
description: 'Device Type',
enum: DeviceTypeEnum,
required: false,
})
@IsEnum(DeviceTypeEnum)
@IsOptional()
public deviceType: DeviceTypeEnum;
@ApiProperty({
description: 'List of Space IDs to filter devices',
required: false,
example: ['60d21b4667d0d8992e610c85', '60d21b4967d0d8992e610c86'],
})
@IsOptional()
@IsArray()
@IsUUID('4', { each: true })
public spaces?: string[];
}

View File

@ -53,7 +53,7 @@ import { DeviceSceneParamDto } from '../dtos/device.param.dto';
import {
GetDeviceLogsDto,
GetDevicesBySpaceOrCommunityDto,
GetDevicesFilterDto,
GetDoorLockDevices,
} from '../dtos/get.device.dto';
import {
controlDeviceInterface,
@ -955,20 +955,19 @@ export class DeviceService {
async getAllDevices(
param: ProjectParam,
{ deviceType, spaces }: GetDevicesFilterDto,
query: GetDoorLockDevices,
): Promise<BaseResponseDto> {
try {
await this.validateProject(param.projectUuid);
if (deviceType === DeviceTypeEnum.DOOR_LOCK) {
return await this.getDoorLockDevices(param.projectUuid, spaces);
} else if (!deviceType) {
if (query.deviceType === DeviceTypeEnum.DOOR_LOCK) {
return await this.getDoorLockDevices(param.projectUuid);
} else if (!query.deviceType) {
const devices = await this.deviceRepository.find({
where: {
isActive: true,
spaceDevice: {
uuid: spaces && spaces.length ? In(spaces) : undefined,
spaceName: Not(ORPHAN_SPACE_NAME),
community: { project: { uuid: param.projectUuid } },
spaceName: Not(ORPHAN_SPACE_NAME),
},
},
relations: [
@ -1564,7 +1563,7 @@ export class DeviceService {
}
}
async getDoorLockDevices(projectUuid: string, spaces?: string[]) {
async getDoorLockDevices(projectUuid: string) {
await this.validateProject(projectUuid);
const devices = await this.deviceRepository.find({
@ -1574,7 +1573,6 @@ export class DeviceService {
},
spaceDevice: {
spaceName: Not(ORPHAN_SPACE_NAME),
uuid: spaces && spaces.length ? In(spaces) : undefined,
community: {
project: {
uuid: projectUuid,

View File

@ -71,6 +71,7 @@ import {
import { SpaceModelProductAllocationService } from 'src/space-model/services/space-model-product-allocation.service';
import { SubspaceModelProductAllocationService } from 'src/space-model/services/subspace/subspace-model-product-allocation.service';
import {
SpaceLinkService,
SpaceService,
SpaceUserService,
SubspaceDeviceService,
@ -114,6 +115,7 @@ import { UserService, UserSpaceService } from 'src/users/services';
TimeZoneRepository,
SpaceService,
InviteSpaceRepository,
SpaceLinkService,
SubSpaceService,
ValidationService,
NewTagService,

View File

@ -1,14 +1,15 @@
import { RequestContextMiddleware } from '@app/common/middleware/request-context.middleware';
import { SeederService } from '@app/common/seed/services/seeder.service';
import { Logger, ValidationPipe } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import { json, urlencoded } from 'body-parser';
import { AppModule } from './app.module';
import rateLimit from 'express-rate-limit';
import helmet from 'helmet';
import { WINSTON_MODULE_NEST_PROVIDER } from 'nest-winston';
import { setupSwaggerAuthentication } from '../libs/common/src/util/user-auth.swagger.utils';
import { AppModule } from './app.module';
import { ValidationPipe } from '@nestjs/common';
import { json, urlencoded } from 'body-parser';
import { SeederService } from '@app/common/seed/services/seeder.service';
import { HttpExceptionFilter } from './common/filters/http-exception/http-exception.filter';
import { Logger } from '@nestjs/common';
import { WINSTON_MODULE_NEST_PROVIDER } from 'nest-winston';
import { RequestContextMiddleware } from '@app/common/middleware/request-context.middleware';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
@ -29,13 +30,6 @@ async function bootstrap() {
}),
);
app.use((req, res, next) => {
console.log('Real IP:', req.ip);
next();
});
// app.getHttpAdapter().getInstance().set('trust proxy', 1);
app.use(
helmet({
contentSecurityPolicy: false,

View File

@ -1,25 +1,24 @@
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 { Controller, Get, Param, Query, UseGuards } from '@nestjs/common';
import {
ApiTags,
ApiBearerAuth,
ApiOperation,
ApiParam,
ApiQuery,
ApiTags,
} from '@nestjs/swagger';
import { EnableDisableStatusEnum } from '@app/common/constants/days.enum';
import { ControllerRoute } from '@app/common/constants/controller-route';
import { JwtAuthGuard } from '@app/common/guards/jwt.auth.guard';
import { PowerClampService } from '../services/power-clamp.service';
import {
GetPowerClampBySpaceDto,
GetPowerClampDto,
} from '../dto/get-power-clamp.dto';
import { BaseResponseDto } from '@app/common/dto/base.response.dto';
import {
PowerClampParamsDto,
ResourceParamsDto,
} from '../dto/power-clamp-params.dto';
import { PowerClampService } from '../services/power-clamp.service';
@ApiTags('Power Clamp Module')
@Controller({
version: EnableDisableStatusEnum.ENABLED,
@ -27,7 +26,6 @@ import {
})
export class PowerClampController {
constructor(private readonly powerClampService: PowerClampService) {}
@ApiBearerAuth()
@UseGuards(JwtAuthGuard)
@Get(':powerClampUuid/historical')

View File

@ -1,5 +1,4 @@
import { DeviceStatusFirebaseService } from '@app/common/firebase/devices-status/services/devices-status.service';
import { AqiDataService } from '@app/common/helper/services/aqi.data.service';
import { OccupancyService } from '@app/common/helper/services/occupancy.service';
import { PowerClampService } from '@app/common/helper/services/power.clamp.service';
import { SqlLoaderService } from '@app/common/helper/services/sql-loader.service';
@ -50,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 {
SpaceDeviceService,
SpaceLinkService,
SpaceService,
SubspaceDeviceService,
SubSpaceService,
@ -60,6 +60,7 @@ import { SubspaceProductAllocationService } from 'src/space/services/subspace/su
import { TagService } from 'src/tags/services';
import { PowerClampController } from './controllers';
import { PowerClampService as PowerClamp } from './services/power-clamp.service';
import { AqiDataService } from '@app/common/helper/services/aqi.data.service';
@Module({
imports: [ConfigModule],
controllers: [PowerClampController],
@ -89,6 +90,7 @@ import { PowerClampService as PowerClamp } from './services/power-clamp.service'
SceneRepository,
AutomationRepository,
InviteSpaceRepository,
SpaceLinkService,
SubSpaceService,
TagService,
SpaceModelService,

View File

@ -23,10 +23,10 @@ import { SpaceDeviceService } from 'src/space/services';
import { SqlLoaderService } from '@app/common/helper/services/sql-loader.service';
import { DataSource } from 'typeorm';
import { SQL_PROCEDURES_PATH } from '@app/common/constants/sql-query-path';
import { filterByMonth, toMMYYYY } from '@app/common/helper/date-format';
import { ProductType } from '@app/common/constants/product-type.enum';
import { CommunityService } from 'src/community/services';
import { BaseResponseDto } from '@app/common/dto/base.response.dto';
import { filterByMonth, toMMYYYY } from '@app/common/helper/date-format';
@Injectable()
export class PowerClampService {

View File

@ -54,6 +54,7 @@ import {
import { SpaceModelProductAllocationService } from 'src/space-model/services/space-model-product-allocation.service';
import { SubspaceModelProductAllocationService } from 'src/space-model/services/subspace/subspace-model-product-allocation.service';
import {
SpaceLinkService,
SpaceService,
SubspaceDeviceService,
SubSpaceService,
@ -86,6 +87,7 @@ const CommandHandlers = [CreateOrphanSpaceHandler];
UserRepository,
SpaceService,
InviteSpaceRepository,
SpaceLinkService,
SubSpaceService,
ValidationService,
TagService,

View File

@ -24,7 +24,6 @@ import { SpaceService } from 'src/space/services';
import { PassThrough } from 'stream';
import { CreateOrphanSpaceCommand } from '../command/create-orphan-space-command';
import { CreateProjectDto, GetProjectParam } from '../dto';
import { QueryRunner } from 'typeorm';
@Injectable()
export class ProjectService {
@ -213,14 +212,8 @@ export class ProjectService {
}
}
async findOne(
uuid: string,
queryRunner?: QueryRunner,
): Promise<ProjectEntity> {
const projectRepository = queryRunner
? queryRunner.manager.getRepository(ProjectEntity)
: this.projectRepository;
const project = await projectRepository.findOne({ where: { uuid } });
async findOne(uuid: string): Promise<ProjectEntity> {
const project = await this.projectRepository.findOne({ where: { uuid } });
if (!project) {
throw new HttpException(
`Invalid project with uuid ${uuid}`,

View File

@ -51,12 +51,8 @@ export class SubSpaceModelService {
for (const [index, dto] of dtos.entries()) {
const subspaceModel = savedSubspaces[index];
const processedTags = await this.tagService.upsertTags(
dto.tags.map((tag) => ({
tagName: tag.name,
productUuid: tag.productUuid,
tagUuid: tag.uuid,
})),
const processedTags = await this.tagService.processTags(
dto.tags,
spaceModel.project.uuid,
queryRunner,
);

View File

@ -46,6 +46,7 @@ import { CommunityService } from 'src/community/services';
import { DeviceService } from 'src/device/services';
import { SceneService } from 'src/scene/services';
import {
SpaceLinkService,
SpaceService,
SubspaceDeviceService,
SubSpaceService,
@ -91,6 +92,7 @@ const CommandHandlers = [
DeviceRepository,
TuyaService,
CommunityRepository,
SpaceLinkService,
SpaceLinkRepository,
InviteSpaceRepository,
NewTagService,

View File

@ -3,8 +3,7 @@ import { ApiProperty } from '@nestjs/swagger';
import { Type } from 'class-transformer';
import {
ArrayUnique,
IsArray,
IsMongoId,
IsBoolean,
IsNotEmpty,
IsNumber,
IsOptional,
@ -13,7 +12,7 @@ import {
NotEquals,
ValidateNested,
} from 'class-validator';
import { CreateProductAllocationDto } from './create-product-allocation.dto';
import { ProcessTagDto } from 'src/tags/dtos';
import { AddSubspaceDto } from './subspace';
export class AddSpaceDto {
@ -48,6 +47,14 @@ export class AddSpaceDto {
@IsOptional()
public icon?: string;
@ApiProperty({
description: 'Indicates whether the space is private or public',
example: false,
default: false,
})
@IsBoolean()
isPrivate: boolean;
@ApiProperty({ description: 'X position on canvas', example: 120 })
@IsNumber()
x: number;
@ -57,19 +64,23 @@ export class AddSpaceDto {
y: number;
@ApiProperty({
description: 'UUID of the Space Model',
description: 'UUID of the Space',
example: 'd290f1ee-6c54-4b01-90e6-d701748f0851',
})
@IsMongoId()
@IsString()
@IsOptional()
spaceModelUuid?: string;
@ApiProperty({ description: 'Y position on canvas', example: 200 })
@IsString()
@IsOptional()
direction?: string;
@ApiProperty({
description: 'List of subspaces included in the model',
type: [AddSubspaceDto],
})
@IsOptional()
@IsArray()
@ValidateNested({ each: true })
@ArrayUnique((subspace) => subspace.subspaceName, {
message(validationArguments) {
@ -89,21 +100,51 @@ export class AddSpaceDto {
subspaces?: AddSubspaceDto[];
@ApiProperty({
description: 'List of allocations associated with the space',
type: [CreateProductAllocationDto],
description: 'List of tags associated with the space model',
type: [ProcessTagDto],
})
@IsOptional()
@IsArray()
@ValidateNested({ each: true })
@Type(() => CreateProductAllocationDto)
productAllocations?: CreateProductAllocationDto[];
@ApiProperty({
description: 'List of children spaces associated with the space',
type: [AddSpaceDto],
})
@IsOptional()
@ValidateNested({ each: true })
@Type(() => AddSpaceDto)
children?: AddSpaceDto[];
@Type(() => ProcessTagDto)
tags?: ProcessTagDto[];
}
export class AddUserSpaceDto {
@ApiProperty({
description: 'spaceUuid',
required: true,
})
@IsString()
@IsNotEmpty()
public spaceUuid: string;
@ApiProperty({
description: 'userUuid',
required: true,
})
@IsString()
@IsNotEmpty()
public userUuid: string;
constructor(dto: Partial<AddUserSpaceDto>) {
Object.assign(this, dto);
}
}
export class AddUserSpaceUsingCodeDto {
@ApiProperty({
description: 'userUuid',
required: true,
})
@IsString()
@IsNotEmpty()
public userUuid: string;
@ApiProperty({
description: 'inviteCode',
required: true,
})
@IsString()
@IsNotEmpty()
public inviteCode: string;
constructor(dto: Partial<AddUserSpaceDto>) {
Object.assign(this, dto);
}
}

View File

@ -1,14 +1,14 @@
import { SpaceEntity } from '@app/common/modules/space/entities/space.entity';
import { SubspaceEntity } from '@app/common/modules/space/entities/subspace/subspace.entity';
import { ProcessTagDto } from 'src/tags/dtos';
import { QueryRunner } from 'typeorm';
import { CreateProductAllocationDto } from './create-product-allocation.dto';
export enum AllocationsOwnerType {
SPACE = 'space',
SUBSPACE = 'subspace',
}
export class BaseCreateAllocationsDto {
productAllocations: CreateProductAllocationDto[];
tags: ProcessTagDto[];
projectUuid: string;
queryRunner: QueryRunner;
type: AllocationsOwnerType;

View File

@ -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;
}

View File

@ -1,10 +1,8 @@
export * from './add.space.dto';
export * from './community-space.param';
export * from './create-allocations.dto';
export * from './create-product-allocation.dto';
export * from './get.space.param';
export * from './project.param.dto';
export * from './subspace';
export * from './tag';
export * from './update.space.dto';
export * from './user-space.param';
export * from './subspace';
export * from './project.param.dto';
export * from './update.space.dto';
export * from './tag';

View File

@ -1,5 +1,4 @@
import { ApiProperty } from '@nestjs/swagger';
import { Type } from 'class-transformer';
import {
IsArray,
IsNotEmpty,
@ -7,8 +6,8 @@ import {
IsString,
ValidateNested,
} from 'class-validator';
import { Type } from 'class-transformer';
import { ProcessTagDto } from 'src/tags/dtos';
import { CreateProductAllocationDto } from '../create-product-allocation.dto';
export class AddSubspaceDto {
@ApiProperty({
@ -25,7 +24,7 @@ export class AddSubspaceDto {
})
@IsArray()
@ValidateNested({ each: true })
@Type(() => CreateProductAllocationDto)
@Type(() => ProcessTagDto)
@IsOptional()
productAllocations?: CreateProductAllocationDto[];
tags?: ProcessTagDto[];
}

View File

@ -1,5 +1,6 @@
export * from './add.subspace-device.param';
export * from './add.subspace.dto';
export * from './delete.subspace.dto';
export * from './get.subspace.param';
export * from './add.subspace-device.param';
export * from './update.subspace.dto';
export * from './delete.subspace.dto';
export * from './modify.subspace.dto';

View 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;
}

View File

@ -1,14 +1,16 @@
import { ApiPropertyOptional, PartialType } from '@nestjs/swagger';
import { IsOptional, IsUUID } from 'class-validator';
import { AddSubspaceDto } from './add.subspace.dto';
import { ApiProperty } from '@nestjs/swagger';
import { IsNotEmpty, IsString } from 'class-validator';
export class UpdateSubspaceDto extends PartialType(AddSubspaceDto) {
@ApiPropertyOptional({
description:
'UUID of the subspace (will present if updating an existing subspace)',
example: '123e4567-e89b-12d3-a456-426614174000',
export class UpdateSubspaceDto {
@ApiProperty({
description: 'Name of the subspace',
example: 'Living Room',
})
@IsOptional()
@IsUUID()
uuid?: string;
@IsNotEmpty()
@IsString()
subspaceName?: string;
@IsNotEmpty()
@IsString()
subspaceUuid: string;
}

View File

@ -9,8 +9,8 @@ import {
NotEquals,
ValidateNested,
} from 'class-validator';
import { CreateProductAllocationDto } from './create-product-allocation.dto';
import { UpdateSubspaceDto } from './subspace';
import { ModifySubspaceDto } from './subspace';
import { ModifyTagDto } from './tag/modify-tag.dto';
export class UpdateSpaceDto {
@ApiProperty({
@ -46,24 +46,25 @@ export class UpdateSpaceDto {
y?: number;
@ApiPropertyOptional({
description: 'List of subspace modifications',
type: [UpdateSubspaceDto],
description: 'List of subspace modifications (add/update/delete)',
type: [ModifySubspaceDto],
})
@IsOptional()
@IsArray()
@ValidateNested({ each: true })
@Type(() => UpdateSubspaceDto)
subspaces?: UpdateSubspaceDto[];
@Type(() => ModifySubspaceDto)
subspaces?: ModifySubspaceDto[];
@ApiPropertyOptional({
description: 'List of allocations modifications',
type: [CreateProductAllocationDto],
description:
'List of tag modifications (add/update/delete) for the space model',
type: [ModifyTagDto],
})
@IsOptional()
@IsArray()
@ValidateNested({ each: true })
@Type(() => CreateProductAllocationDto)
productAllocations?: CreateProductAllocationDto[];
@Type(() => ModifyTagDto)
tags?: ModifyTagDto[];
@ApiProperty({
description: 'UUID of the Space',

View File

@ -5,7 +5,11 @@ import { DeviceService } from 'src/device/services';
import { UserSpaceService } from 'src/users/services';
import { DataSource } from 'typeorm';
import { DisableSpaceCommand } from '../commands';
import { SpaceSceneService, SubSpaceService } from '../services';
import {
SpaceLinkService,
SpaceSceneService,
SubSpaceService,
} from '../services';
@CommandHandler(DisableSpaceCommand)
export class DisableSpaceHandler
@ -15,6 +19,7 @@ export class DisableSpaceHandler
private readonly subSpaceService: SubSpaceService,
private readonly userService: UserSpaceService,
private readonly deviceService: DeviceService,
private readonly spaceLinkService: SpaceLinkService,
private readonly sceneService: SpaceSceneService,
private readonly dataSource: DataSource,
) {}
@ -34,6 +39,8 @@ export class DisableSpaceHandler
'subspaces',
'parent',
'devices',
'outgoingConnections',
'incomingConnections',
'scenes',
'children',
'userSpaces',
@ -72,6 +79,7 @@ export class DisableSpaceHandler
orphanSpace,
queryRunner,
),
this.spaceLinkService.deleteSpaceLink(space, queryRunner),
this.sceneService.deleteScenes(space, queryRunner),
];

View File

@ -16,10 +16,10 @@ export class ProductAllocationService {
) {}
async createAllocations(dto: CreateAllocationsDto): Promise<void> {
const { projectUuid, queryRunner, productAllocations, type } = dto;
const { projectUuid, queryRunner, tags, type } = dto;
const allocationsData = await this.tagService.upsertTags(
productAllocations,
const allocationsData = await this.tagService.processTags(
tags,
projectUuid,
queryRunner,
);
@ -29,17 +29,15 @@ export class ProductAllocationService {
const createdTagsByName = new Map(allocationsData.map((t) => [t.name, t]));
// Create the product-tag mapping based on the processed tags
const productTagMapping = productAllocations.map(
({ tagUuid, tagName, productUuid }) => {
const inputTag = tagUuid
? createdTagsByUUID.get(tagUuid)
: createdTagsByName.get(tagName);
return {
tag: inputTag?.uuid,
product: productUuid,
};
},
);
const productTagMapping = tags.map(({ uuid, name, productUuid }) => {
const inputTag = uuid
? createdTagsByUUID.get(uuid)
: createdTagsByName.get(name);
return {
tag: inputTag?.uuid,
product: productUuid,
};
});
switch (type) {
case AllocationsOwnerType.SPACE: {

View File

@ -1,6 +1,121 @@
import { Injectable } from '@nestjs/common';
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';
// todo: find out why we need to import this
// in community module in order for the whole system to work
@Injectable()
export class SpaceLinkService {}
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,
);
}
}
}

View File

@ -16,7 +16,7 @@ import {
Inject,
Injectable,
} from '@nestjs/common';
import { In, QueryRunner } from 'typeorm';
import { In } from 'typeorm';
import { CommunityService } from '../../community/services';
import { ProjectService } from '../../project/services';
import { ProjectParam } from '../dtos';
@ -69,17 +69,12 @@ export class ValidationService {
async validateCommunityAndProject(
communityUuid: string,
projectUuid: string,
queryRunner?: QueryRunner,
) {
const project = await this.projectService.findOne(projectUuid, queryRunner);
const community = await this.communityService.getCommunityById(
{
communityUuid,
projectUuid,
},
queryRunner,
);
const project = await this.projectService.findOne(projectUuid);
const community = await this.communityService.getCommunityById({
communityUuid,
projectUuid,
});
return { community: community.data, project: project };
}
@ -175,14 +170,8 @@ export class ValidationService {
return space;
}
async validateSpaceModel(
spaceModelUuid: string,
queryRunner?: QueryRunner,
): Promise<SpaceModelEntity> {
const queryBuilder = (
queryRunner.manager.getRepository(SpaceModelEntity) ||
this.spaceModelRepository
)
async validateSpaceModel(spaceModelUuid: string): Promise<SpaceModelEntity> {
const queryBuilder = this.spaceModelRepository
.createQueryBuilder('spaceModel')
.leftJoinAndSelect(
'spaceModel.subspaceModels',

View File

@ -22,6 +22,7 @@ import {
import { CommandBus } from '@nestjs/cqrs';
import { DeviceService } from 'src/device/services';
import { SpaceModelService } from 'src/space-model/services';
import { ProcessTagDto } from 'src/tags/dtos';
import { TagService } from 'src/tags/services/tags.service';
import { DataSource, In, Not, QueryRunner } from 'typeorm';
import { DisableSpaceCommand } from '../commands';
@ -31,9 +32,9 @@ import {
GetSpaceParam,
UpdateSpaceDto,
} from '../dtos';
import { CreateProductAllocationDto } from '../dtos/create-product-allocation.dto';
import { GetSpaceDto } from '../dtos/get.space.dto';
import { SpaceWithParentsDto } from '../dtos/space.parents.dto';
import { SpaceLinkService } from './space-link';
import { SpaceProductAllocationService } from './space-product-allocation.service';
import { ValidationService } from './space-validation.service';
import { SubSpaceService } from './subspace';
@ -43,6 +44,7 @@ export class SpaceService {
private readonly dataSource: DataSource,
private readonly spaceRepository: SpaceRepository,
private readonly inviteSpaceRepository: InviteSpaceRepository,
private readonly spaceLinkService: SpaceLinkService,
private readonly subSpaceService: SubSpaceService,
private readonly validationService: ValidationService,
private readonly tagService: TagService,
@ -55,72 +57,50 @@ export class SpaceService {
async createSpace(
addSpaceDto: AddSpaceDto,
params: CommunitySpaceParam,
queryRunner?: QueryRunner,
recursiveCallParentEntity?: SpaceEntity,
): Promise<BaseResponseDto> {
const isRecursiveCall = !!queryRunner;
const {
parentUuid,
spaceModelUuid,
subspaces,
productAllocations,
children,
} = addSpaceDto;
const { parentUuid, direction, spaceModelUuid, subspaces, tags } =
addSpaceDto;
const { communityUuid, projectUuid } = params;
if (!queryRunner) {
queryRunner = this.dataSource.createQueryRunner();
await queryRunner.connect();
await queryRunner.startTransaction();
}
const queryRunner = this.dataSource.createQueryRunner();
await queryRunner.connect();
await queryRunner.startTransaction();
const { community } =
await this.validationService.validateCommunityAndProject(
communityUuid,
projectUuid,
queryRunner,
);
this.validateSpaceCreationCriteria({
spaceModelUuid,
subspaces,
productAllocations,
});
this.validateSpaceCreationCriteria({ spaceModelUuid, subspaces, tags });
const parent =
parentUuid && !isRecursiveCall
? await this.validationService.validateSpace(parentUuid)
: null;
const parent = parentUuid
? await this.validationService.validateSpace(parentUuid)
: null;
const spaceModel = spaceModelUuid
? await this.validationService.validateSpaceModel(spaceModelUuid)
: null;
try {
const space = queryRunner.manager.create(SpaceEntity, {
// todo: find a better way to handle this instead of naming every key
spaceName: addSpaceDto.spaceName,
icon: addSpaceDto.icon,
x: addSpaceDto.x,
y: addSpaceDto.y,
...addSpaceDto,
spaceModel,
parent: isRecursiveCall
? recursiveCallParentEntity
: parentUuid
? parent
: null,
parent: parentUuid ? parent : null,
community,
});
const newSpace = await queryRunner.manager.save(space);
this.checkDuplicateTags([
...(productAllocations || []),
...(subspaces?.flatMap(
(subspace) => subspace.productAllocations || [],
) || []),
]);
const subspaceTags =
subspaces?.flatMap((subspace) => subspace.tags || []) || [];
this.checkDuplicateTags([...tags, ...subspaceTags]);
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(
newSpace,
spaceModel,
@ -129,6 +109,15 @@ export class SpaceService {
}
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
? this.subSpaceService.createSubspacesFromDto(
subspaces,
@ -137,32 +126,12 @@ export class SpaceService {
projectUuid,
)
: Promise.resolve(),
productAllocations?.length
? this.createAllocations(
productAllocations,
projectUuid,
queryRunner,
newSpace,
)
tags?.length
? this.createAllocations(tags, projectUuid, queryRunner, newSpace)
: Promise.resolve(),
]);
if (children?.length) {
await Promise.all(
children.map((child) =>
this.createSpace(
{ ...child, parentUuid: newSpace.uuid },
{ communityUuid, projectUuid },
queryRunner,
newSpace,
),
),
);
}
if (!isRecursiveCall) {
await queryRunner.commitTransaction();
}
await queryRunner.commitTransaction();
return new SuccessResponseDto({
statusCode: HttpStatus.CREATED,
@ -170,34 +139,34 @@ export class SpaceService {
message: 'Space created successfully',
});
} catch (error) {
!isRecursiveCall ? await queryRunner.rollbackTransaction() : null;
await queryRunner.rollbackTransaction();
if (error instanceof HttpException) {
throw error;
}
throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR);
} finally {
!isRecursiveCall ? await queryRunner.release() : null;
await queryRunner.release();
}
}
private checkDuplicateTags(allocations: CreateProductAllocationDto[]) {
private checkDuplicateTags(allTags: ProcessTagDto[]) {
const tagUuidSet = new Set<string>();
const tagNameProductSet = new Set<string>();
for (const allocation of allocations) {
if (allocation.tagUuid) {
if (tagUuidSet.has(allocation.tagUuid)) {
for (const tag of allTags) {
if (tag.uuid) {
if (tagUuidSet.has(tag.uuid)) {
throw new HttpException(
`Duplicate tag UUID found: ${allocation.tagUuid}`,
`Duplicate tag UUID found: ${tag.uuid}`,
HttpStatus.BAD_REQUEST,
);
}
tagUuidSet.add(allocation.tagUuid);
tagUuidSet.add(tag.uuid);
} else {
const tagKey = `${allocation.tagName}-${allocation.productUuid}`;
const tagKey = `${tag.name}-${tag.productUuid}`;
if (tagNameProductSet.has(tagKey)) {
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,
);
}
@ -226,7 +195,12 @@ export class SpaceService {
'children.disabled = :disabled',
{ disabled: false },
)
.leftJoinAndSelect(
'space.incomingConnections',
'incomingConnections',
'incomingConnections.disabled = :incomingConnectionDisabled',
{ incomingConnectionDisabled: false },
)
.leftJoinAndSelect('space.productAllocations', 'productAllocations')
.leftJoinAndSelect('productAllocations.tag', 'tag')
.leftJoinAndSelect('productAllocations.product', 'product')
@ -297,6 +271,7 @@ export class SpaceService {
}
}
// todo refactor this method to eliminate wrong use of tags
async findOne(params: GetSpaceParam): Promise<BaseResponseDto> {
const { communityUuid, spaceUuid, projectUuid } = params;
try {
@ -307,6 +282,19 @@ export class SpaceService {
const queryBuilder = this.spaceRepository
.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('productAllocations.tag', 'spaceTag')
.leftJoinAndSelect('productAllocations.product', 'spaceProduct')
@ -435,7 +423,7 @@ export class SpaceService {
const queryRunner = this.dataSource.createQueryRunner();
const hasSubspace = updateSpaceDto.subspaces?.length > 0;
const hasAllocations = updateSpaceDto.productAllocations?.length > 0;
const hasTags = updateSpaceDto.tags?.length > 0;
try {
await queryRunner.connect();
@ -460,7 +448,7 @@ export class SpaceService {
await this.updateSpaceProperties(space, updateSpaceDto, queryRunner);
if (hasSubspace || hasAllocations) {
if (hasSubspace || hasTags) {
await queryRunner.manager.update(SpaceEntity, space.uuid, {
spaceModel: null,
});
@ -504,7 +492,7 @@ export class SpaceService {
await this.subSpaceService.unlinkModels(space.subspaces, queryRunner);
}
if (hasAllocations && space.productAllocations && space.spaceModel) {
if (hasTags && space.productAllocations && space.spaceModel) {
await this.spaceProductAllocationService.unlinkModels(
space,
queryRunner,
@ -520,13 +508,13 @@ export class SpaceService {
);
}
if (updateSpaceDto.productAllocations) {
if (updateSpaceDto.tags) {
await queryRunner.manager.delete(SpaceProductAllocationEntity, {
space: { uuid: space.uuid },
tag: {
uuid: Not(
In(
updateSpaceDto.productAllocations
updateSpaceDto.tags
.filter((tag) => tag.tagUuid)
.map((tag) => tag.tagUuid),
),
@ -534,7 +522,11 @@ export class SpaceService {
},
});
await this.createAllocations(
updateSpaceDto.productAllocations,
updateSpaceDto.tags.map((tag) => ({
name: tag.name,
uuid: tag.tagUuid,
productUuid: tag.productUuid,
})),
projectUuid,
queryRunner,
space,
@ -681,7 +673,7 @@ export class SpaceService {
}
}
buildSpaceHierarchy(spaces: SpaceEntity[]): SpaceEntity[] {
private buildSpaceHierarchy(spaces: SpaceEntity[]): SpaceEntity[] {
const map = new Map<string, SpaceEntity>();
// Step 1: Create a map of spaces by UUID
@ -710,17 +702,13 @@ export class SpaceService {
private validateSpaceCreationCriteria({
spaceModelUuid,
productAllocations,
tags,
subspaces,
}: Pick<
AddSpaceDto,
'spaceModelUuid' | 'productAllocations' | 'subspaces'
>): void {
const hasProductsOrSubspaces =
(productAllocations && productAllocations.length > 0) ||
(subspaces && subspaces.length > 0);
}: Pick<AddSpaceDto, 'spaceModelUuid' | 'tags' | 'subspaces'>): void {
const hasTagsOrSubspaces =
(tags && tags.length > 0) || (subspaces && subspaces.length > 0);
if (spaceModelUuid && hasProductsOrSubspaces) {
if (spaceModelUuid && hasTagsOrSubspaces) {
throw new HttpException(
'For space creation choose either space model or products and subspace',
HttpStatus.CONFLICT,
@ -729,13 +717,13 @@ export class SpaceService {
}
private async createAllocations(
productAllocations: CreateProductAllocationDto[],
tags: ProcessTagDto[],
projectUuid: string,
queryRunner: QueryRunner,
space: SpaceEntity,
): Promise<void> {
const allocationsData = await this.tagService.upsertTags(
productAllocations,
const allocationsData = await this.tagService.processTags(
tags,
projectUuid,
queryRunner,
);
@ -745,17 +733,15 @@ export class SpaceService {
const createdTagsByName = new Map(allocationsData.map((t) => [t.name, t]));
// Create the product-tag mapping based on the processed tags
const productTagMapping = productAllocations.map(
({ tagUuid, tagName, productUuid }) => {
const inputTag = tagUuid
? createdTagsByUUID.get(tagUuid)
: createdTagsByName.get(tagName);
return {
tag: inputTag?.uuid,
product: productUuid,
};
},
);
const productTagMapping = tags.map(({ uuid, name, productUuid }) => {
const inputTag = uuid
? createdTagsByUUID.get(uuid)
: createdTagsByName.get(name);
return {
tag: inputTag?.uuid,
product: productUuid,
};
});
await this.spaceProductAllocationService.createProductAllocations(
space,

View File

@ -3,7 +3,7 @@ import { SubspaceProductAllocationEntity } from '@app/common/modules/space/entit
import { SubspaceEntity } from '@app/common/modules/space/entities/subspace/subspace.entity';
import { SubspaceProductAllocationRepository } from '@app/common/modules/space/repositories/subspace.repository';
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 { In, Not, QueryRunner } from 'typeorm';
@ -60,46 +60,31 @@ export class SubspaceProductAllocationService {
}
async updateSubspaceProductAllocationsV2(
subSpaces: UpdateSubspaceDto[],
subSpaces: UpdateSpaceAllocationDto[],
projectUuid: string,
queryRunner: QueryRunner,
) {
await Promise.all(
subSpaces.map(async (subspace) => {
await queryRunner.manager.delete(SubspaceProductAllocationEntity, {
subspace: subspace.uuid ? { uuid: subspace.uuid } : undefined,
tag: subspace.productAllocations
? {
uuid: Not(
In(
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,
subspace: { uuid: subspace.uuid },
tag: {
uuid: Not(
In(
subspace.tags.filter((tag) => tag.uuid).map((tag) => tag.uuid),
),
),
},
});
const subspaceEntity = await queryRunner.manager.findOne(
SubspaceEntity,
{
where: { uuid: subspace.uuid },
},
);
const processedTags = await this.tagService.upsertTags(
subspace.productAllocations,
const processedTags = await this.tagService.processTags(
subspace.tags,
projectUuid,
queryRunner,
);
@ -112,11 +97,11 @@ export class SubspaceProductAllocationService {
);
// Create the product-tag mapping based on the processed tags
const productTagMapping = subspace.productAllocations.map(
({ tagUuid, tagName, productUuid }) => {
const inputTag = tagUuid
? createdTagsByUUID.get(tagUuid)
: createdTagsByName.get(tagName);
const productTagMapping = subspace.tags.map(
({ uuid, name, productUuid }) => {
const inputTag = uuid
? createdTagsByUUID.get(uuid)
: createdTagsByName.get(name);
return {
tag: inputTag?.uuid,
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(
allocations: SubspaceProductAllocationEntity[],
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(
subspace: SubspaceEntity,
allocationData: { product: string; tag: string },

View File

@ -12,7 +12,7 @@ import {
AddSubspaceDto,
GetSpaceParam,
GetSubSpaceParam,
UpdateSubspaceDto,
ModifySubspaceDto,
} from '../../dtos';
import { SubspaceModelEntity } from '@app/common/modules/space-model';
@ -103,13 +103,13 @@ export class SubSpaceService {
queryRunner,
);
await Promise.all(
addSubspaceDtos.map(async ({ productAllocations }, index) => {
addSubspaceDtos.map(async ({ tags }, index) => {
// map the dto to the corresponding subspace
const subspace = createdSubspaces[index];
await this.createAllocations({
projectUuid,
queryRunner,
productAllocations,
tags,
type: AllocationsOwnerType.SUBSPACE,
subspace,
});
@ -145,7 +145,7 @@ export class SubSpaceService {
space,
);
const newSubspace = this.subspaceRepository.create({
subspaceName: addSubspaceDto.subspaceName,
...addSubspaceDto,
space,
});
@ -305,7 +305,7 @@ export class SubSpaceService {
} */
async updateSubspaceInSpace(
subspaceDtos: UpdateSubspaceDto[],
subspaceDtos: ModifySubspaceDto[],
queryRunner: QueryRunner,
space: SpaceEntity,
projectUuid: string,
@ -324,52 +324,42 @@ export class SubSpaceService {
disabled: true,
},
);
await queryRunner.manager.delete(SubspaceProductAllocationEntity, {
subspace: {
uuid: Not(
In(subspaceDtos.filter(({ uuid }) => uuid).map(({ uuid }) => uuid)),
),
},
subspace: { uuid: Not(In(subspaceDtos.map((dto) => dto.uuid))) },
});
// create or update subspaces provided in the list
const newSubspaces = this.subspaceRepository.create(
subspaceDtos
.filter((dto) => !dto.uuid)
.map((dto) => ({
subspaceName: dto.subspaceName,
space,
})),
subspaceDtos.filter((dto) => !dto.uuid),
);
const updatedSubspaces: SubspaceEntity[] = await queryRunner.manager.save(
SubspaceEntity,
[
...newSubspaces,
...subspaceDtos
.filter((dto) => dto.uuid)
.map((dto) => ({
subspaceName: dto.subspaceName,
space,
})),
],
[...newSubspaces, ...subspaceDtos.filter((dto) => dto.uuid)].map(
(subspace) => ({ ...subspace, space }),
),
);
// create or update allocations for the subspaces
if (updatedSubspaces.length > 0) {
await this.subspaceProductAllocationService.updateSubspaceProductAllocationsV2(
subspaceDtos.map((dto) => ({
...dto,
uuid:
dto.uuid ||
updatedSubspaces.find((s) => s.subspaceName === dto.subspaceName)
?.uuid,
})),
subspaceDtos.map((dto) => {
if (!dto.uuid) {
dto.uuid = updatedSubspaces.find(
(subspace) => subspace.subspaceName === dto.subspaceName,
)?.uuid;
}
return {
tags: dto.tags || [],
uuid: dto.uuid,
};
}),
projectUuid,
queryRunner,
);
}
} catch (error) {
console.log(error);
throw new HttpException(
`An error occurred while modifying subspaces: ${error.message}`,
HttpStatus.INTERNAL_SERVER_ERROR,
@ -488,10 +478,10 @@ export class SubSpaceService {
}
async createAllocations(dto: CreateAllocationsDto): Promise<void> {
const { projectUuid, queryRunner, productAllocations, type } = dto;
if (!productAllocations) return;
const allocationsData = await this.newTagService.upsertTags(
productAllocations,
const { projectUuid, queryRunner, tags, type } = dto;
const allocationsData = await this.newTagService.processTags(
tags,
projectUuid,
queryRunner,
);
@ -501,17 +491,15 @@ export class SubSpaceService {
const createdTagsByName = new Map(allocationsData.map((t) => [t.name, t]));
// Create the product-tag mapping based on the processed tags
const productTagMapping = productAllocations.map(
({ tagUuid, tagName, productUuid }) => {
const inputTag = tagUuid
? createdTagsByUUID.get(tagUuid)
: createdTagsByName.get(tagName);
return {
tag: inputTag?.uuid,
product: productUuid,
};
},
);
const productTagMapping = tags.map(({ uuid, name, productUuid }) => {
const inputTag = uuid
? createdTagsByUUID.get(uuid)
: createdTagsByName.get(name);
return {
tag: inputTag?.uuid,
product: productUuid,
};
});
switch (type) {
case AllocationsOwnerType.SUBSPACE: {

View File

@ -79,6 +79,7 @@ import { SpaceValidationController } from './controllers/space-validation.contro
import { DisableSpaceHandler } from './handlers';
import {
SpaceDeviceService,
SpaceLinkService,
SpaceSceneService,
SpaceService,
SpaceUserService,
@ -109,6 +110,7 @@ export const CommandHandlers = [DisableSpaceHandler];
ProductRepository,
SubSpaceService,
SpaceDeviceService,
SpaceLinkService,
SubspaceDeviceService,
SpaceRepository,
SubspaceRepository,

View File

@ -14,8 +14,8 @@ import {
Injectable,
NotFoundException,
} from '@nestjs/common';
import { CreateProductAllocationDto } from 'src/space/dtos';
import { In, QueryRunner } from 'typeorm';
import { ProcessTagDto } from '../dtos';
import { CreateTagDto } from '../dtos/tags.dto';
@Injectable()
@ -68,13 +68,13 @@ export class TagService {
/**
* Processes an array of tag DTOs, creating or updating tags in the database.
* @param allocationDtos - The array of allocations DTOs to process.
* @param tagDtos - The array of tag DTOs to process.
* @param projectUuid - The UUID of the project to associate the tags with.
* @param queryRunner - Optional TypeORM query runner for transaction management.
* @returns An array of the processed tag entities.
*/
async upsertTags(
allocationDtos: CreateProductAllocationDto[],
async processTags(
tagDtos: ProcessTagDto[],
projectUuid: string,
queryRunner?: QueryRunner,
): Promise<NewTagEntity[]> {
@ -82,22 +82,20 @@ export class TagService {
const dbManager = queryRunner
? queryRunner.manager
: this.tagRepository.manager;
if (!allocationDtos || allocationDtos.length === 0) {
if (!tagDtos || tagDtos.length === 0) {
return [];
}
const [allocationsWithTagUuid, allocationsWithoutTagUuid]: [
Pick<CreateProductAllocationDto, 'tagUuid' | 'productUuid'>[],
Omit<CreateProductAllocationDto, 'tagUuid'>[],
] = this.splitTagsByUuid(allocationDtos);
const [tagsWithUuid, tagsWithoutUuid]: [
Pick<ProcessTagDto, 'uuid' | 'productUuid'>[],
Omit<ProcessTagDto, 'uuid'>[],
] = this.splitTagsByUuid(tagDtos);
// create a set of unique existing tag names for the project
const upsertedTagsByNameResult = await dbManager.upsert(
NewTagEntity,
Array.from(
new Set<string>(
allocationsWithoutTagUuid.map((allocation) => allocation.tagName),
).values(),
new Set<string>(tagsWithoutUuid.map((tag) => tag.name)).values(),
).map((name) => ({
name,
project: { uuid: projectUuid },
@ -113,22 +111,20 @@ export class TagService {
let foundByUuidTags: NewTagEntity[] = [];
// Fetch existing tags using UUIDs
if (allocationsWithTagUuid.length) {
if (tagsWithUuid.length) {
foundByUuidTags = await dbManager.find(NewTagEntity, {
where: {
uuid: In([
...allocationsWithTagUuid.map((allocation) => allocation.tagUuid),
]),
uuid: In([...tagsWithUuid.map((tag) => tag.uuid)]),
project: { uuid: projectUuid },
},
});
}
// Ensure all provided UUIDs exist in the database
if (foundByUuidTags.length !== allocationsWithTagUuid.length) {
if (foundByUuidTags.length !== tagsWithUuid.length) {
const foundUuids = new Set(foundByUuidTags.map((tag) => tag.uuid));
const missingUuids = allocationsWithTagUuid.filter(
({ tagUuid }) => !foundUuids.has(tagUuid),
const missingUuids = tagsWithUuid.filter(
({ uuid }) => !foundUuids.has(uuid),
);
throw new HttpException(
@ -183,22 +179,20 @@ export class TagService {
}
private splitTagsByUuid(
allocationsDtos: CreateProductAllocationDto[],
): [CreateProductAllocationDto[], CreateProductAllocationDto[]] {
return allocationsDtos.reduce<
[CreateProductAllocationDto[], CreateProductAllocationDto[]]
>(
([withUuid, withoutUuid], allocation) => {
if (allocation.tagUuid) {
withUuid.push(allocation);
tagDtos: ProcessTagDto[],
): [ProcessTagDto[], ProcessTagDto[]] {
return tagDtos.reduce<[ProcessTagDto[], ProcessTagDto[]]>(
([withUuid, withoutUuid], tag) => {
if (tag.uuid) {
withUuid.push(tag);
} else {
if (!allocation.tagName || !allocation.productUuid) {
if (!tag.name || !tag.productUuid) {
throw new HttpException(
`Tag name or product UUID is missing`,
HttpStatus.BAD_REQUEST,
);
}
withoutUuid.push(allocation);
withoutUuid.push(tag);
}
return [withUuid, withoutUuid];
},

View File

@ -1,5 +1,38 @@
import { ApiProperty } from '@nestjs/swagger';
import { IsNotEmpty, IsString } from 'class-validator';
import {
IsBoolean,
IsNotEmpty,
IsOptional,
IsString,
IsUUID,
} from 'class-validator';
export class AddSpaceDto {
@ApiProperty({
description: 'Name of the space (e.g., Floor 1, Unit 101)',
example: 'Unit 101',
})
@IsString()
@IsNotEmpty()
spaceName: string;
@ApiProperty({
description: 'UUID of the parent space (if any, for hierarchical spaces)',
example: 'f5d7e9c3-44bc-4b12-88f1-1b3cda84752e',
required: false,
})
@IsUUID()
@IsOptional()
parentUuid?: string;
@ApiProperty({
description: 'Indicates whether the space is private or public',
example: false,
default: false,
})
@IsBoolean()
isPrivate: boolean;
}
export class AddUserSpaceDto {
@ApiProperty({