Compare commits

..

63 Commits

Author SHA1 Message Date
9176fe779e task: add orderBy clause to communities 2025-06-19 11:10:57 +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
a91d0f22a4 fix: send correct enable status to email sender function (#407) 2025-06-13 09:46:41 +03:00
0db060ae3f Merge pull request #406 from SyncrowIOT/add-space-daily-occupancy-duration-entity
feat: add SpaceDailyOccupancyDuration entity, DTO, and repository for occupancy tracking
2025-06-12 04:17:18 -06:00
f2ed04f206 feat: add SpaceDailyOccupancyDuration entity, DTO, and repository for occupancy tracking 2025-06-12 02:49:59 -06:00
ea9a65178d fix: add space filter to "join" operation instead of "and" operation (#405) 2025-06-11 16:28:33 +03:00
8503ee728d Refactor/space management (#404)
* refactor: reducing used queries on get communities (#385)

* refactor: fix create space logic (#394)

* Remove unique constraint on subspace and product in SubspaceProductAllocationEntity; update product relation to nullable in NewTagEntity

* refactor: fix create space logic

* device model updated to include the fixes and final columns

* updated space models to include suggested fixes, update final logic and column names

* task: removing old references of the old tag-product relation

* task: remove old use of tags

* task: remove old tag & tag model usage

* refactor: delete space

* task: remove unused functions

* fix lint rule
2025-06-11 13:15:21 +03:00
4f5e1b23f6 Merge pull request #403 from SyncrowIOT/SP-1629-AND-SP-1630-AQI-APIs
Sp 1629 and sp 1630 aqi ap is
2025-06-11 00:28:14 -06:00
2cb77504ca Add PollutantType enum and update AQI-related entities and services to use it 2025-06-11 00:28:00 -06:00
c86be27576 Add AQI module and related services, controllers, and DTOs
- Introduced AqiModule with AqiService and AqiController for handling AQI data.
- Added DTOs for AQI requests: GetAqiDailyBySpaceDto and GetAqiPollutantBySpaceDto.
- Implemented AqiDataService for managing AQI sensor historical data.
- Updated existing modules to include AqiDataService where necessary.
- Defined new routes for AQI data retrieval in ControllerRoute.
2025-06-10 18:19:34 -06:00
3a08f9f258 Merge branch 'dev' into aqi-test 2025-06-10 17:08:06 -06:00
5c96a3b117 Merge pull request #402 from SyncrowIOT/add-code-and-value-as-uniqe-key
Refactor DeviceStatusLogEntity: expand unique constraint to include c…
2025-06-10 01:43:09 -06:00
97e14e70f7 Refactor DeviceStatusLogEntity: expand unique constraint to include code and value 2025-06-10 01:41:41 -06:00
03d44cb14f Merge pull request #401 from SyncrowIOT/fix-log-insert-error
Refactor DeviceStatusLogEntity: update unique constraint to include d…
2025-06-10 01:27:15 -06:00
0793441e06 Refactor DeviceStatusLogEntity: correct unique constraint name for event time and device ID 2025-06-10 01:24:33 -06:00
b6321c2530 Refactor DeviceStatusLogEntity: update unique constraint to include deviceId 2025-06-10 01:18:58 -06:00
b8d34b0d9f Merge pull request #400 from SyncrowIOT/revert-398-fix-log-duplication-issue
Revert "Refactor DeviceStatusLogEntity: update unique constraint and primary …"
2025-06-10 01:04:29 -06:00
c1065126aa Revert "Refactor DeviceStatusLogEntity: update unique constraint and primary …" 2025-06-10 01:03:45 -06:00
1742454984 Merge pull request #398 from SyncrowIOT/fix-log-duplication-issue
Refactor DeviceStatusLogEntity: update unique constraint and primary …
2025-06-10 00:26:43 -06:00
7eb13088ac Refactor DeviceStatusLogEntity: update unique constraint and primary key definition 2025-06-09 04:50:58 -06:00
0d6de2df43 Refactor AqiSpaceDailyPollutantStatsEntity: update unique constraint and rename event fields for clarity 2025-06-04 15:24:13 -06:00
ef2245eae1 Add AQI space daily pollutant stats module and related entities, DTOs, and repositories 2025-06-03 23:37:52 -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
109 changed files with 3522 additions and 4918 deletions

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: on:
push: push:
@ -6,50 +9,43 @@ on:
- main - main
workflow_dispatch: 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: jobs:
build_and_deploy: build:
runs-on: ubuntu-latest runs-on: 'ubuntu-latest'
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v2
- name: Set up Node.js - name: Set up Docker Buildx
uses: actions/setup-node@v3 uses: docker/setup-buildx-action@v2
- name: Log in to registry
uses: docker/login-action@v2
with: 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 - name: Build and push container image to registry
run: | uses: docker/build-push-action@v3
npm install
npm run build
- name: Log in to Azure
uses: azure/login@v1
with: 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 deploy:
run: az acr login --name ${{ env.ACR_REGISTRY }} runs-on: ubuntu-latest
needs: build
environment:
name: 'staging'
url: ${{ steps.deploy-to-webapp.outputs.webapp-url }}
- name: List build output steps:
run: ls -R dist/ - name: Deploy to Azure Web App
id: deploy-to-webapp
- name: Build and push Docker image uses: azure/webapps-deploy@v2
run: | with:
docker build . -t ${{ env.ACR_REGISTRY }}/${{ env.IMAGE_NAME }}:${{ env.IMAGE_TAG }} app-name: 'syncrow'
docker push ${{ env.ACR_REGISTRY }}/${{ env.IMAGE_NAME }}:${{ env.IMAGE_TAG }} slot-name: 'staging'
publish-profile: ${{ secrets.AzureAppService_PublishProfile_44f7766441ec4796b74789e9761ef589 }}
- name: Set Web App with Docker container images: 'syncrow.azurecr.io/${{ secrets.AzureAppService_ContainerUsername_47395803300340b49931ea82f6d80be3 }}/syncrow/backend:${{ github.sha }}'
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 }}

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 { static PowerClamp = class {
public static readonly ROUTE = 'power-clamp'; public static readonly ROUTE = 'power-clamp';
static ACTIONS = class { static ACTIONS = class {
public static readonly GET_ENERGY_SUMMARY = public static readonly GET_ENERGY_SUMMARY =
'Get power clamp historical data'; 'Get power clamp historical data';
@ -524,6 +523,20 @@ export class ControllerRoute {
'This endpoint retrieves the occupancy heat map data based on the provided parameters.'; 'This endpoint retrieves the occupancy heat map data based on the provided parameters.';
}; };
}; };
static AQI = class {
public static readonly ROUTE = 'aqi';
static ACTIONS = class {
public static readonly GET_AQI_RANGE_DATA_SUMMARY = 'Get AQI range data';
public static readonly GET_AQI_RANGE_DATA_DESCRIPTION =
'This endpoint retrieves the AQI (Air Quality Index) range data based on the provided parameters.';
public static readonly GET_AQI_DISTRIBUTION_DATA_SUMMARY =
'Get AQI distribution data';
public static readonly GET_AQI_DISTRIBUTION_DATA_DESCRIPTION =
'This endpoint retrieves the AQI (Air Quality Index) distribution data based on the provided parameters.';
};
};
static DEVICE = class { static DEVICE = class {
public static readonly ROUTE = 'devices'; public static readonly ROUTE = 'devices';

View File

@ -0,0 +1,8 @@
export enum PollutantType {
AQI = 'aqi',
PM25 = 'pm25',
PM10 = 'pm10',
VOC = 'voc',
CO2 = 'co2',
CH2O = 'ch2o',
}

View File

@ -19,4 +19,5 @@ export enum ProductType {
FOUR_S = '4S', FOUR_S = '4S',
SIX_S = '6S', SIX_S = '6S',
SOS = 'SOS', SOS = 'SOS',
AQI = 'AQI',
} }

View File

@ -1,51 +1,30 @@
import { Module } from '@nestjs/common'; import { Module } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config'; import { ConfigModule, ConfigService } from '@nestjs/config';
import { TypeOrmModule } from '@nestjs/typeorm'; import { TypeOrmModule } from '@nestjs/typeorm';
import { SnakeNamingStrategy } from './strategies';
import { UserEntity } from '../modules/user/entities/user.entity';
import { UserSessionEntity } from '../modules/session/entities/session.entity';
import { UserOtpEntity } from '../modules/user/entities';
import { ProductEntity } from '../modules/product/entities';
import { DeviceEntity } from '../modules/device/entities'; import { DeviceEntity } from '../modules/device/entities';
import { PermissionTypeEntity } from '../modules/permission/entities'; import { PermissionTypeEntity } from '../modules/permission/entities';
import { ProductEntity } from '../modules/product/entities';
import { UserSessionEntity } from '../modules/session/entities/session.entity';
import { UserOtpEntity } from '../modules/user/entities';
import { UserEntity } from '../modules/user/entities/user.entity';
import { SnakeNamingStrategy } from './strategies';
import { UserSpaceEntity } from '../modules/user/entities'; import { TypeOrmWinstonLogger } from '@app/common/logger/services/typeorm.logger';
import { DeviceUserPermissionEntity } from '../modules/device/entities'; import { createLogger } from 'winston';
import { RoleTypeEntity } from '../modules/role-type/entities'; import { winstonLoggerOptions } from '../logger/services/winston.logger';
import { UserNotificationEntity } from '../modules/user/entities'; import { AqiSpaceDailyPollutantStatsEntity } from '../modules/aqi/entities';
import { DeviceNotificationEntity } from '../modules/device/entities'; import { AutomationEntity } from '../modules/automation/entities';
import { RegionEntity } from '../modules/region/entities'; import { ClientEntity } from '../modules/client/entities';
import { TimeZoneEntity } from '../modules/timezone/entities';
import { VisitorPasswordEntity } from '../modules/visitor-password/entities';
import { CommunityEntity } from '../modules/community/entities'; import { CommunityEntity } from '../modules/community/entities';
import { DeviceStatusLogEntity } from '../modules/device-status-log/entities'; import { DeviceStatusLogEntity } from '../modules/device-status-log/entities';
import { SceneEntity, SceneIconEntity } from '../modules/scene/entities';
import { SceneDeviceEntity } from '../modules/scene-device/entities';
import { ProjectEntity } from '../modules/project/entities';
import { import {
SpaceModelEntity, DeviceNotificationEntity,
SubspaceModelEntity, DeviceUserPermissionEntity,
TagModel, } from '../modules/device/entities';
SpaceModelProductAllocationEntity,
SubspaceModelProductAllocationEntity,
} from '../modules/space-model/entities';
import { import {
InviteUserEntity, InviteUserEntity,
InviteUserSpaceEntity, InviteUserSpaceEntity,
} from '../modules/Invite-user/entities'; } from '../modules/Invite-user/entities';
import { InviteSpaceEntity } from '../modules/space/entities/invite-space.entity';
import { AutomationEntity } from '../modules/automation/entities';
import { SpaceProductAllocationEntity } from '../modules/space/entities/space-product-allocation.entity';
import { NewTagEntity } from '../modules/tag/entities/tag.entity';
import { SpaceEntity } from '../modules/space/entities/space.entity';
import { SpaceLinkEntity } from '../modules/space/entities/space-link.entity';
import { SubspaceProductAllocationEntity } from '../modules/space/entities/subspace/subspace-product-allocation.entity';
import { SubspaceEntity } from '../modules/space/entities/subspace/subspace.entity';
import { TagEntity } from '../modules/space/entities/tag.entity';
import { ClientEntity } from '../modules/client/entities';
import { TypeOrmWinstonLogger } from '@app/common/logger/services/typeorm.logger';
import { createLogger } from 'winston';
import { winstonLoggerOptions } from '../logger/services/winston.logger';
import { import {
PowerClampDailyEntity, PowerClampDailyEntity,
PowerClampHourlyEntity, PowerClampHourlyEntity,
@ -55,6 +34,31 @@ import {
PresenceSensorDailyDeviceEntity, PresenceSensorDailyDeviceEntity,
PresenceSensorDailySpaceEntity, PresenceSensorDailySpaceEntity,
} from '../modules/presence-sensor/entities'; } from '../modules/presence-sensor/entities';
import { ProjectEntity } from '../modules/project/entities';
import { RegionEntity } from '../modules/region/entities';
import { RoleTypeEntity } from '../modules/role-type/entities';
import { SceneDeviceEntity } from '../modules/scene-device/entities';
import { SceneEntity, SceneIconEntity } from '../modules/scene/entities';
import {
SpaceModelEntity,
SpaceModelProductAllocationEntity,
SubspaceModelEntity,
SubspaceModelProductAllocationEntity,
} from '../modules/space-model/entities';
import { InviteSpaceEntity } from '../modules/space/entities/invite-space.entity';
import { 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';
import { SubspaceEntity } from '../modules/space/entities/subspace/subspace.entity';
import { NewTagEntity } from '../modules/tag/entities/tag.entity';
import { TimeZoneEntity } from '../modules/timezone/entities';
import {
UserNotificationEntity,
UserSpaceEntity,
} from '../modules/user/entities';
import { VisitorPasswordEntity } from '../modules/visitor-password/entities';
import { SpaceDailyOccupancyDurationEntity } from '../modules/occupancy/entities';
@Module({ @Module({
imports: [ imports: [
TypeOrmModule.forRootAsync({ TypeOrmModule.forRootAsync({
@ -85,7 +89,6 @@ import {
SpaceEntity, SpaceEntity,
SpaceLinkEntity, SpaceLinkEntity,
SubspaceEntity, SubspaceEntity,
TagEntity,
UserSpaceEntity, UserSpaceEntity,
DeviceUserPermissionEntity, DeviceUserPermissionEntity,
RoleTypeEntity, RoleTypeEntity,
@ -100,7 +103,6 @@ import {
SceneDeviceEntity, SceneDeviceEntity,
SpaceModelEntity, SpaceModelEntity,
SubspaceModelEntity, SubspaceModelEntity,
TagModel,
InviteUserEntity, InviteUserEntity,
InviteUserSpaceEntity, InviteUserSpaceEntity,
InviteSpaceEntity, InviteSpaceEntity,
@ -115,6 +117,8 @@ import {
PowerClampMonthlyEntity, PowerClampMonthlyEntity,
PresenceSensorDailyDeviceEntity, PresenceSensorDailyDeviceEntity,
PresenceSensorDailySpaceEntity, PresenceSensorDailySpaceEntity,
AqiSpaceDailyPollutantStatsEntity,
SpaceDailyOccupancyDurationEntity,
], ],
namingStrategy: new SnakeNamingStrategy(), namingStrategy: new SnakeNamingStrategy(),
synchronize: Boolean(JSON.parse(configService.get('DB_SYNC'))), synchronize: Boolean(JSON.parse(configService.get('DB_SYNC'))),

View File

@ -11,6 +11,7 @@ import {
} from '@app/common/modules/power-clamp/repositories'; } from '@app/common/modules/power-clamp/repositories';
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';
@Module({ @Module({
providers: [ providers: [
@ -23,6 +24,7 @@ import { OccupancyService } from '@app/common/helper/services/occupancy.service'
PowerClampMonthlyRepository, PowerClampMonthlyRepository,
SqlLoaderService, SqlLoaderService,
OccupancyService, OccupancyService,
AqiDataService,
], ],
controllers: [DeviceStatusFirebaseController], controllers: [DeviceStatusFirebaseController],
exports: [DeviceStatusFirebaseService, DeviceStatusLogRepository], exports: [DeviceStatusFirebaseService, DeviceStatusLogRepository],

View File

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

View File

@ -23,15 +23,19 @@ import { PowerClampService } from '@app/common/helper/services/power.clamp.servi
import { PowerClampEnergyEnum } from '@app/common/constants/power.clamp.enargy.enum'; import { PowerClampEnergyEnum } from '@app/common/constants/power.clamp.enargy.enum';
import { PresenceSensorEnum } from '@app/common/constants/presence.sensor.enum'; import { PresenceSensorEnum } from '@app/common/constants/presence.sensor.enum';
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';
@Injectable() @Injectable()
export class DeviceStatusFirebaseService { export class DeviceStatusFirebaseService {
private tuya: TuyaContext; private tuya: TuyaContext;
private firebaseDb: Database; private firebaseDb: Database;
private readonly isDevEnv: boolean;
constructor( constructor(
private readonly configService: ConfigService, private readonly configService: ConfigService,
private readonly deviceRepository: DeviceRepository, private readonly deviceRepository: DeviceRepository,
private readonly powerClampService: PowerClampService, private readonly powerClampService: PowerClampService,
private readonly occupancyService: OccupancyService, 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');
@ -45,6 +49,8 @@ export class DeviceStatusFirebaseService {
// Initialize firebaseDb using firebaseDataBase function // Initialize firebaseDb using firebaseDataBase function
this.firebaseDb = firebaseDataBase(this.configService); this.firebaseDb = firebaseDataBase(this.configService);
this.isDevEnv =
this.configService.get<string>('NODE_ENV') === 'development';
} }
async addDeviceStatusByDeviceUuid( async addDeviceStatusByDeviceUuid(
deviceTuyaUuid: string, deviceTuyaUuid: string,
@ -59,7 +65,7 @@ export class DeviceStatusFirebaseService {
const deviceStatusSaved = await this.createDeviceStatusFirebase({ const deviceStatusSaved = await this.createDeviceStatusFirebase({
deviceUuid: device.uuid, deviceUuid: device.uuid,
deviceTuyaUuid: deviceTuyaUuid, deviceTuyaUuid: deviceTuyaUuid,
status: deviceStatus.status, status: deviceStatus?.status,
productUuid: deviceStatus.productUuid, productUuid: deviceStatus.productUuid,
productType: deviceStatus.productType, productType: deviceStatus.productType,
}); });
@ -120,7 +126,7 @@ export class DeviceStatusFirebaseService {
return { return {
productUuid: deviceDetails.productDevice.uuid, productUuid: deviceDetails.productDevice.uuid,
productType: deviceDetails.productDevice.prodType, productType: deviceDetails.productDevice.prodType,
status: deviceStatus.result[0].status, status: deviceStatus.result[0]?.status,
}; };
} catch (error) { } catch (error) {
throw new HttpException( throw new HttpException(
@ -185,18 +191,18 @@ export class DeviceStatusFirebaseService {
if (!existingData.productType) { if (!existingData.productType) {
existingData.productType = addDeviceStatusDto.productType; existingData.productType = addDeviceStatusDto.productType;
} }
if (!existingData.status) { if (!existingData?.status) {
existingData.status = []; existingData.status = [];
} }
// Create a map to track existing status codes // Create a map to track existing status codes
const statusMap = new Map( 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 // Update or add status codes
for (const statusItem of addDeviceStatusDto.status) { for (const statusItem of addDeviceStatusDto?.status) {
statusMap.set(statusItem.code, statusItem.value); statusMap.set(statusItem.code, statusItem.value);
} }
@ -209,60 +215,126 @@ export class DeviceStatusFirebaseService {
return existingData; return existingData;
}); });
// Save logs to your repository if (this.isDevEnv) {
const newLogs = addDeviceStatusDto.log.properties.map((property) => { // Save logs to your repository
return this.deviceStatusLogRepository.create({ const newLogs = addDeviceStatusDto.log.properties.map((property) => {
deviceId: addDeviceStatusDto.deviceUuid, return this.deviceStatusLogRepository.create({
deviceTuyaId: addDeviceStatusDto.deviceTuyaUuid, deviceId: addDeviceStatusDto.deviceUuid,
productId: addDeviceStatusDto.log.productId, deviceTuyaId: addDeviceStatusDto.deviceTuyaUuid,
log: addDeviceStatusDto.log, productId: addDeviceStatusDto.log.productId,
code: property.code, log: addDeviceStatusDto.log,
value: property.value, code: property.code,
eventId: addDeviceStatusDto.log.dataId, value: property.value,
eventTime: new Date(property.time).toISOString(), 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) { if (addDeviceStatusDto.productType === ProductType.PC) {
const energyCodes = new Set([ const energyCodes = new Set([
PowerClampEnergyEnum.ENERGY_CONSUMED, PowerClampEnergyEnum.ENERGY_CONSUMED,
PowerClampEnergyEnum.ENERGY_CONSUMED_A, PowerClampEnergyEnum.ENERGY_CONSUMED_A,
PowerClampEnergyEnum.ENERGY_CONSUMED_B, PowerClampEnergyEnum.ENERGY_CONSUMED_B,
PowerClampEnergyEnum.ENERGY_CONSUMED_C, PowerClampEnergyEnum.ENERGY_CONSUMED_C,
]); ]);
const energyStatus = addDeviceStatusDto?.log?.properties?.find((status) => const energyStatus = addDeviceStatusDto?.log?.properties?.find(
energyCodes.has(status.code), (status) => energyCodes.has(status.code),
); );
if (energyStatus) { if (energyStatus) {
await this.powerClampService.updateEnergyConsumedHistoricalData( 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, 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,
);
}
}
// 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();

View File

@ -0,0 +1,47 @@
import { DeviceRepository } from '@app/common/modules/device/repositories';
import { Injectable } from '@nestjs/common';
import { SqlLoaderService } from './sql-loader.service';
import { DataSource } from 'typeorm';
import { SQL_PROCEDURES_PATH } from '@app/common/constants/sql-query-path';
@Injectable()
export class AqiDataService {
constructor(
private readonly sqlLoader: SqlLoaderService,
private readonly dataSource: DataSource,
private readonly deviceRepository: DeviceRepository,
) {}
async updateAQISensorHistoricalData(deviceUuid: string): Promise<void> {
try {
const now = new Date();
const dateStr = now.toLocaleDateString('en-CA'); // YYYY-MM-DD
const device = await this.deviceRepository.findOne({
where: { uuid: deviceUuid },
relations: ['spaceDevice'],
});
await this.executeProcedure(
'fact_daily_space_aqi',
'proceduce_update_daily_space_aqi',
[dateStr, device.spaceDevice?.uuid],
);
} catch (err) {
console.error('Failed to insert or update aqi data:', err);
throw err;
}
}
private async executeProcedure(
procedureFolderName: string,
procedureFileName: string,
params: (string | number | null)[],
): Promise<void> {
const query = this.loadQuery(procedureFolderName, procedureFileName);
await this.dataSource.query(query, params);
console.log(`Procedure ${procedureFileName} executed successfully.`);
}
private loadQuery(folderName: string, fileName: string): string {
return this.sqlLoader.loadQuery(folderName, fileName, SQL_PROCEDURES_PATH);
}
}

View File

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

View File

@ -0,0 +1,11 @@
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { AqiSpaceDailyPollutantStatsEntity } from './entities/aqi.entity';
@Module({
providers: [],
exports: [],
controllers: [],
imports: [TypeOrmModule.forFeature([AqiSpaceDailyPollutantStatsEntity])],
})
export class AqiRepositoryModule {}

View File

@ -0,0 +1,82 @@
import { IsNotEmpty, IsNumber, IsString } from 'class-validator';
export class AqiSpaceDailyPollutantStatsDto {
@IsString()
@IsNotEmpty()
public uuid: string;
@IsNotEmpty()
@IsString()
spaceUuid: string;
@IsNotEmpty()
@IsString()
eventDay: string;
@IsNotEmpty()
@IsNumber()
eventHour: number;
@IsNumber()
pm1Min: number;
@IsNumber()
pm1Avg: number;
@IsNumber()
pm1Max: number;
@IsNumber()
pm10Min: number;
@IsNumber()
pm10Avg: number;
@IsNumber()
pm10Max: number;
@IsNumber()
pm25Min: number;
@IsNumber()
pm25Avg: number;
@IsNumber()
pm25Max: number;
@IsNumber()
ch2oMin: number;
@IsNumber()
ch2oAvg: number;
@IsNumber()
ch2oMax: number;
@IsNumber()
vocMin: number;
@IsNumber()
vocAvg: number;
@IsNumber()
vocMax: number;
@IsNumber()
co2Min: number;
@IsNumber()
co2Avg: number;
@IsNumber()
co2Max: number;
@IsNumber()
aqiMin: number;
@IsNumber()
aqiAvg: number;
@IsNumber()
aqiMax: number;
}

View File

@ -0,0 +1 @@
export * from './aqi.dto';

View File

@ -0,0 +1,184 @@
import { Column, Entity, ManyToOne, Unique } from 'typeorm';
import { AbstractEntity } from '../../abstract/entities/abstract.entity';
import { SpaceEntity } from '../../space/entities/space.entity';
import { AqiSpaceDailyPollutantStatsDto } from '../dtos';
@Entity({ name: 'space-daily-pollutant-stats' })
@Unique(['spaceUuid', 'eventDate'])
export class AqiSpaceDailyPollutantStatsEntity extends AbstractEntity<AqiSpaceDailyPollutantStatsDto> {
@Column({ nullable: false })
public spaceUuid: string;
@ManyToOne(() => SpaceEntity, (space) => space.aqiSensorDaily)
space: SpaceEntity;
@Column({ type: 'date', nullable: false })
public eventDate: Date;
@Column('float', { nullable: true })
public goodAqiPercentage?: number;
@Column('float', { nullable: true })
public moderateAqiPercentage?: number;
@Column('float', { nullable: true })
public unhealthySensitiveAqiPercentage?: number;
@Column('float', { nullable: true })
public unhealthyAqiPercentage?: number;
@Column('float', { nullable: true })
public veryUnhealthyAqiPercentage?: number;
@Column('float', { nullable: true })
public hazardousAqiPercentage?: number;
@Column('float', { nullable: true })
public dailyAvgAqi?: number;
@Column('float', { nullable: true })
public dailyMaxAqi?: number;
@Column('float', { nullable: true })
public dailyMinAqi?: number;
@Column('float', { nullable: true })
public goodPm25Percentage?: number;
@Column('float', { nullable: true })
public moderatePm25Percentage?: number;
@Column('float', { nullable: true })
public unhealthySensitivePm25Percentage?: number;
@Column('float', { nullable: true })
public unhealthyPm25Percentage?: number;
@Column('float', { nullable: true })
public veryUnhealthyPm25Percentage?: number;
@Column('float', { nullable: true })
public hazardousPm25Percentage?: number;
@Column('float', { nullable: true })
public dailyAvgPm25?: number;
@Column('float', { nullable: true })
public dailyMaxPm25?: number;
@Column('float', { nullable: true })
public dailyMinPm25?: number;
@Column('float', { nullable: true })
public goodPm10Percentage?: number;
@Column('float', { nullable: true })
public moderatePm10Percentage?: number;
@Column('float', { nullable: true })
public unhealthySensitivePm10Percentage?: number;
@Column('float', { nullable: true })
public unhealthyPm10Percentage?: number;
@Column('float', { nullable: true })
public veryUnhealthyPm10Percentage?: number;
@Column('float', { nullable: true })
public hazardousPm10Percentage?: number;
@Column('float', { nullable: true })
public dailyAvgPm10?: number;
@Column('float', { nullable: true })
public dailyMaxPm10?: number;
@Column('float', { nullable: true })
public dailyMinPm10?: number;
@Column('float', { nullable: true })
public goodVocPercentage?: number;
@Column('float', { nullable: true })
public moderateVocPercentage?: number;
@Column('float', { nullable: true })
public unhealthySensitiveVocPercentage?: number;
@Column('float', { nullable: true })
public unhealthyVocPercentage?: number;
@Column('float', { nullable: true })
public veryUnhealthyVocPercentage?: number;
@Column('float', { nullable: true })
public hazardousVocPercentage?: number;
@Column('float', { nullable: true })
public dailyAvgVoc?: number;
@Column('float', { nullable: true })
public dailyMaxVoc?: number;
@Column('float', { nullable: true })
public dailyMinVoc?: number;
@Column('float', { nullable: true })
public goodCo2Percentage?: number;
@Column('float', { nullable: true })
public moderateCo2Percentage?: number;
@Column('float', { nullable: true })
public unhealthySensitiveCo2Percentage?: number;
@Column('float', { nullable: true })
public unhealthyCo2Percentage?: number;
@Column('float', { nullable: true })
public veryUnhealthyCo2Percentage?: number;
@Column('float', { nullable: true })
public hazardousCo2Percentage?: number;
@Column('float', { nullable: true })
public dailyAvgCo2?: number;
@Column('float', { nullable: true })
public dailyMaxCo2?: number;
@Column('float', { nullable: true })
public dailyMinCo2?: number;
@Column('float', { nullable: true })
public goodCh2oPercentage?: number;
@Column('float', { nullable: true })
public moderateCh2oPercentage?: number;
@Column('float', { nullable: true })
public unhealthySensitiveCh2oPercentage?: number;
@Column('float', { nullable: true })
public unhealthyCh2oPercentage?: number;
@Column('float', { nullable: true })
public veryUnhealthyCh2oPercentage?: number;
@Column('float', { nullable: true })
public hazardousCh2oPercentage?: number;
@Column('float', { nullable: true })
public dailyAvgCh2o?: number;
@Column('float', { nullable: true })
public dailyMaxCh2o?: number;
@Column('float', { nullable: true })
public dailyMinCh2o?: number;
constructor(partial: Partial<AqiSpaceDailyPollutantStatsEntity>) {
super();
Object.assign(this, partial);
}
}

View File

@ -0,0 +1 @@
export * from './aqi.entity';

View File

@ -0,0 +1,10 @@
import { DataSource, Repository } from 'typeorm';
import { Injectable } from '@nestjs/common';
import { AqiSpaceDailyPollutantStatsEntity } from '../entities';
@Injectable()
export class AqiSpaceDailyPollutantStatsRepository extends Repository<AqiSpaceDailyPollutantStatsEntity> {
constructor(private dataSource: DataSource) {
super(AqiSpaceDailyPollutantStatsEntity, dataSource.createEntityManager());
}
}

View File

@ -0,0 +1 @@
export * from './aqi.repository';

View File

@ -2,15 +2,15 @@ import { SourceType } from '@app/common/constants/source-type.enum';
import { Entity, Column, PrimaryColumn, Unique } from 'typeorm'; import { Entity, Column, PrimaryColumn, Unique } from 'typeorm';
@Entity('device-status-log') @Entity('device-status-log')
@Unique('event_time_idx', ['eventTime']) @Unique('event_time_idx', ['eventTime', 'deviceId', 'code', 'value'])
export class DeviceStatusLogEntity { export class DeviceStatusLogEntity {
@Column({ type: 'int', generated: true, unsigned: true }) @PrimaryColumn({ type: 'int', generated: true, unsigned: true })
id: number; id: number;
@Column({ type: 'text' }) @Column({ type: 'text' })
eventId: string; eventId: string;
@PrimaryColumn({ type: 'timestamptz' }) @Column({ type: 'timestamptz' })
eventTime: Date; eventTime: Date;
@Column({ @Column({

View File

@ -78,8 +78,8 @@ export class DeviceEntity extends AbstractEntity<DeviceDto> {
@OneToMany(() => SceneDeviceEntity, (sceneDevice) => sceneDevice.device, {}) @OneToMany(() => SceneDeviceEntity, (sceneDevice) => sceneDevice.device, {})
sceneDevices: SceneDeviceEntity[]; sceneDevices: SceneDeviceEntity[];
@OneToMany(() => NewTagEntity, (tag) => tag.devices) @ManyToOne(() => NewTagEntity, (tag) => tag.devices)
// @JoinTable({ name: 'device_tags' }) @JoinColumn({ name: 'tag_uuid' })
public tag: NewTagEntity; public tag: NewTagEntity;
@OneToMany(() => PowerClampHourlyEntity, (powerClamp) => powerClamp.device) @OneToMany(() => PowerClampHourlyEntity, (powerClamp) => powerClamp.device)
powerClampHourly: PowerClampHourlyEntity[]; powerClampHourly: PowerClampHourlyEntity[];

View File

@ -0,0 +1 @@
export * from './occupancy.dto';

View File

@ -0,0 +1,23 @@
import { IsNotEmpty, IsNumber, IsString } from 'class-validator';
export class SpaceDailyOccupancyDurationDto {
@IsString()
@IsNotEmpty()
public uuid: string;
@IsString()
@IsNotEmpty()
public spaceUuid: string;
@IsString()
@IsNotEmpty()
public eventDate: string;
@IsNumber()
@IsNotEmpty()
public occupancyPercentage: number;
@IsNumber()
@IsNotEmpty()
public occupiedSeconds: number;
}

View File

@ -0,0 +1 @@
export * from './occupancy.entity';

View File

@ -0,0 +1,32 @@
import { Column, Entity, ManyToOne, Unique } from 'typeorm';
import { AbstractEntity } from '../../abstract/entities/abstract.entity';
import { SpaceEntity } from '../../space/entities/space.entity';
import { SpaceDailyOccupancyDurationDto } from '../dtos';
@Entity({ name: 'space-daily-occupancy-duration' })
@Unique(['spaceUuid', 'eventDate'])
export class SpaceDailyOccupancyDurationEntity extends AbstractEntity<SpaceDailyOccupancyDurationDto> {
@Column({ nullable: false })
public spaceUuid: string;
@Column({ nullable: false, type: 'date' })
public eventDate: string;
public CountTotalPresenceDetected: number;
@ManyToOne(() => SpaceEntity, (space) => space.presenceSensorDaily)
space: SpaceEntity;
@Column({ type: 'int' })
occupancyPercentage: number;
@Column({ type: 'int', nullable: true })
occupiedSeconds?: number;
@Column({ type: 'int', nullable: true })
deviceCount?: number;
constructor(partial: Partial<SpaceDailyOccupancyDurationEntity>) {
super();
Object.assign(this, partial);
}
}

View File

@ -0,0 +1,11 @@
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { SpaceDailyOccupancyDurationEntity } from './entities/occupancy.entity';
@Module({
providers: [],
exports: [],
controllers: [],
imports: [TypeOrmModule.forFeature([SpaceDailyOccupancyDurationEntity])],
})
export class SpaceDailyOccupancyDurationRepositoryModule {}

View File

@ -0,0 +1 @@
export * from './occupancy.repository';

View File

@ -0,0 +1,10 @@
import { DataSource, Repository } from 'typeorm';
import { Injectable } from '@nestjs/common';
import { SpaceDailyOccupancyDurationEntity } from '../entities/occupancy.entity';
@Injectable()
export class SpaceDailyOccupancyDurationEntityRepository extends Repository<SpaceDailyOccupancyDurationEntity> {
constructor(private dataSource: DataSource) {
super(SpaceDailyOccupancyDurationEntity, dataSource.createEntityManager());
}
}

View File

@ -1,10 +1,7 @@
import { Column, Entity, OneToMany } from 'typeorm'; import { Column, Entity, OneToMany } from 'typeorm';
import { ProductDto } from '../dtos';
import { AbstractEntity } from '../../abstract/entities/abstract.entity'; import { AbstractEntity } from '../../abstract/entities/abstract.entity';
import { DeviceEntity } from '../../device/entities'; import { DeviceEntity } from '../../device/entities';
import { TagModel } from '../../space-model'; import { ProductDto } from '../dtos';
import { TagEntity } from '../../space/entities/tag.entity';
import { NewTagEntity } from '../../tag/entities';
@Entity({ name: 'product' }) @Entity({ name: 'product' })
export class ProductEntity extends AbstractEntity<ProductDto> { export class ProductEntity extends AbstractEntity<ProductDto> {
@Column({ @Column({
@ -28,15 +25,6 @@ export class ProductEntity extends AbstractEntity<ProductDto> {
}) })
public prodType: string; public prodType: string;
@OneToMany(() => NewTagEntity, (tag) => tag.product, { cascade: true })
public newTags: NewTagEntity[];
@OneToMany(() => TagModel, (tag) => tag.product)
tagModels: TagModel[];
@OneToMany(() => TagEntity, (tag) => tag.product)
tags: TagEntity[];
@OneToMany( @OneToMany(
() => DeviceEntity, () => DeviceEntity,
(devicesProductEntity) => devicesProductEntity.productDevice, (devicesProductEntity) => devicesProductEntity.productDevice,

View File

@ -1,21 +0,0 @@
import { IsNotEmpty, IsString } from 'class-validator';
export class TagModelDto {
@IsString()
@IsNotEmpty()
public uuid: string;
@IsString()
@IsNotEmpty()
public name: string;
@IsString()
@IsNotEmpty()
public productUuid: string;
@IsString()
spaceModelUuid: string;
@IsString()
subspaceModelUuid: string;
}

View File

@ -1,4 +1,3 @@
export * from './space-model-product-allocation.entity';
export * from './space-model.entity'; export * from './space-model.entity';
export * from './subspace-model'; export * from './subspace-model';
export * from './tag-model.entity';
export * from './space-model-product-allocation.entity';

View File

@ -1,18 +1,12 @@
import { import { Column, Entity, ManyToOne, OneToMany, Unique } from 'typeorm';
Entity, import { AbstractEntity } from '../../abstract/entities/abstract.entity';
Column,
ManyToOne,
ManyToMany,
JoinTable,
OneToMany,
} from 'typeorm';
import { SpaceModelEntity } from './space-model.entity';
import { NewTagEntity } from '../../tag/entities/tag.entity';
import { ProductEntity } from '../../product/entities/product.entity'; import { ProductEntity } from '../../product/entities/product.entity';
import { SpaceProductAllocationEntity } from '../../space/entities/space-product-allocation.entity'; import { SpaceProductAllocationEntity } from '../../space/entities/space-product-allocation.entity';
import { AbstractEntity } from '../../abstract/entities/abstract.entity'; import { NewTagEntity } from '../../tag/entities/tag.entity';
import { SpaceModelEntity } from './space-model.entity';
@Entity({ name: 'space_model_product_allocation' }) @Entity({ name: 'space_model_product_allocation' })
@Unique(['spaceModel', 'product', 'tag'])
export class SpaceModelProductAllocationEntity extends AbstractEntity<SpaceModelProductAllocationEntity> { export class SpaceModelProductAllocationEntity extends AbstractEntity<SpaceModelProductAllocationEntity> {
@Column({ @Column({
type: 'uuid', type: 'uuid',
@ -31,9 +25,8 @@ export class SpaceModelProductAllocationEntity extends AbstractEntity<SpaceModel
@ManyToOne(() => ProductEntity, { nullable: false, onDelete: 'CASCADE' }) @ManyToOne(() => ProductEntity, { nullable: false, onDelete: 'CASCADE' })
public product: ProductEntity; public product: ProductEntity;
@ManyToMany(() => NewTagEntity, { cascade: true, onDelete: 'CASCADE' }) @ManyToOne(() => NewTagEntity, { nullable: true, onDelete: 'CASCADE' })
@JoinTable({ name: 'space_model_product_tags' }) public tag: NewTagEntity;
public tags: NewTagEntity[];
@OneToMany( @OneToMany(
() => SpaceProductAllocationEntity, () => SpaceProductAllocationEntity,

View File

@ -1,11 +1,10 @@
import { Entity, Column, OneToMany, ManyToOne, JoinColumn } from 'typeorm'; import { Column, Entity, JoinColumn, ManyToOne, OneToMany } from 'typeorm';
import { AbstractEntity } from '../../abstract/entities/abstract.entity'; import { AbstractEntity } from '../../abstract/entities/abstract.entity';
import { SpaceModelDto } from '../dtos';
import { SubspaceModelEntity } from './subspace-model';
import { ProjectEntity } from '../../project/entities'; import { ProjectEntity } from '../../project/entities';
import { TagModel } from './tag-model.entity';
import { SpaceModelProductAllocationEntity } from './space-model-product-allocation.entity';
import { SpaceEntity } from '../../space/entities/space.entity'; import { SpaceEntity } from '../../space/entities/space.entity';
import { SpaceModelDto } from '../dtos';
import { SpaceModelProductAllocationEntity } from './space-model-product-allocation.entity';
import { SubspaceModelEntity } from './subspace-model';
@Entity({ name: 'space-model' }) @Entity({ name: 'space-model' })
export class SpaceModelEntity extends AbstractEntity<SpaceModelDto> { export class SpaceModelEntity extends AbstractEntity<SpaceModelDto> {
@ -49,9 +48,6 @@ export class SpaceModelEntity extends AbstractEntity<SpaceModelDto> {
}) })
public spaces: SpaceEntity[]; public spaces: SpaceEntity[];
@OneToMany(() => TagModel, (tag) => tag.spaceModel)
tags: TagModel[];
@OneToMany( @OneToMany(
() => SpaceModelProductAllocationEntity, () => SpaceModelProductAllocationEntity,
(allocation) => allocation.spaceModel, (allocation) => allocation.spaceModel,

View File

@ -1,11 +1,12 @@
import { Entity, Column, ManyToOne, ManyToMany, JoinTable } from 'typeorm'; import { AbstractEntity } from '@app/common/modules/abstract/entities/abstract.entity';
import { SubspaceModelEntity } from './subspace-model.entity';
import { ProductEntity } from '@app/common/modules/product/entities/product.entity'; import { ProductEntity } from '@app/common/modules/product/entities/product.entity';
import { NewTagEntity } from '@app/common/modules/tag/entities/tag.entity'; import { NewTagEntity } from '@app/common/modules/tag/entities/tag.entity';
import { Column, Entity, ManyToOne, Unique } from 'typeorm';
import { SubspaceModelProductAllocationDto } from '../../dtos/subspace-model/subspace-model-product-allocation.dto'; import { SubspaceModelProductAllocationDto } from '../../dtos/subspace-model/subspace-model-product-allocation.dto';
import { AbstractEntity } from '@app/common/modules/abstract/entities/abstract.entity'; import { SubspaceModelEntity } from './subspace-model.entity';
@Entity({ name: 'subspace_model_product_allocation' }) @Entity({ name: 'subspace_model_product_allocation' })
@Unique(['subspaceModel', 'product', 'tag'])
export class SubspaceModelProductAllocationEntity extends AbstractEntity<SubspaceModelProductAllocationDto> { export class SubspaceModelProductAllocationEntity extends AbstractEntity<SubspaceModelProductAllocationDto> {
@Column({ @Column({
type: 'uuid', type: 'uuid',
@ -27,12 +28,8 @@ export class SubspaceModelProductAllocationEntity extends AbstractEntity<Subspac
@ManyToOne(() => ProductEntity, { nullable: false, onDelete: 'CASCADE' }) @ManyToOne(() => ProductEntity, { nullable: false, onDelete: 'CASCADE' })
public product: ProductEntity; public product: ProductEntity;
@ManyToMany(() => NewTagEntity, (tag) => tag.subspaceModelAllocations, { @ManyToOne(() => NewTagEntity, { nullable: true, onDelete: 'CASCADE' })
cascade: true, public tag: NewTagEntity;
onDelete: 'CASCADE',
})
@JoinTable({ name: 'subspace_model_product_tags' })
public tags: NewTagEntity[];
constructor(partial: Partial<SubspaceModelProductAllocationEntity>) { constructor(partial: Partial<SubspaceModelProductAllocationEntity>) {
super(); super();

View File

@ -1,10 +1,9 @@
import { AbstractEntity } from '@app/common/modules/abstract/entities/abstract.entity'; import { AbstractEntity } from '@app/common/modules/abstract/entities/abstract.entity';
import { SubspaceEntity } from '@app/common/modules/space/entities/subspace/subspace.entity';
import { Column, Entity, ManyToOne, OneToMany } from 'typeorm'; import { Column, Entity, ManyToOne, OneToMany } from 'typeorm';
import { SubSpaceModelDto } from '../../dtos'; import { SubSpaceModelDto } from '../../dtos';
import { SpaceModelEntity } from '../space-model.entity'; import { SpaceModelEntity } from '../space-model.entity';
import { TagModel } from '../tag-model.entity';
import { SubspaceModelProductAllocationEntity } from './subspace-model-product-allocation.entity'; import { SubspaceModelProductAllocationEntity } from './subspace-model-product-allocation.entity';
import { SubspaceEntity } from '@app/common/modules/space/entities/subspace/subspace.entity';
@Entity({ name: 'subspace-model' }) @Entity({ name: 'subspace-model' })
export class SubspaceModelEntity extends AbstractEntity<SubSpaceModelDto> { export class SubspaceModelEntity extends AbstractEntity<SubSpaceModelDto> {
@ -41,9 +40,6 @@ export class SubspaceModelEntity extends AbstractEntity<SubSpaceModelDto> {
}) })
public disabled: boolean; public disabled: boolean;
@OneToMany(() => TagModel, (tag) => tag.subspaceModel)
tags: TagModel[];
@OneToMany( @OneToMany(
() => SubspaceModelProductAllocationEntity, () => SubspaceModelProductAllocationEntity,
(allocation) => allocation.subspaceModel, (allocation) => allocation.subspaceModel,

View File

@ -1,38 +0,0 @@
import { Column, Entity, JoinColumn, ManyToOne, OneToMany } from 'typeorm';
import { AbstractEntity } from '../../abstract/entities/abstract.entity';
import { TagModelDto } from '../dtos/tag-model.dto';
import { SpaceModelEntity } from './space-model.entity';
import { SubspaceModelEntity } from './subspace-model';
import { ProductEntity } from '../../product/entities';
import { TagEntity } from '../../space/entities/tag.entity';
@Entity({ name: 'tag_model' })
export class TagModel extends AbstractEntity<TagModelDto> {
@Column({ type: 'varchar', length: 255 })
tag: string;
@ManyToOne(() => ProductEntity, (product) => product.tagModels, {
nullable: false,
})
@JoinColumn({ name: 'product_id' })
product: ProductEntity;
@ManyToOne(() => SpaceModelEntity, (space) => space.tags, { nullable: true })
@JoinColumn({ name: 'space_model_id' })
spaceModel: SpaceModelEntity;
@ManyToOne(() => SubspaceModelEntity, (subspace) => subspace.tags, {
nullable: true,
})
@JoinColumn({ name: 'subspace_model_id' })
subspaceModel: SubspaceModelEntity;
@Column({
nullable: false,
default: false,
})
public disabled: boolean;
@OneToMany(() => TagEntity, (tag) => tag.model)
tags: TagEntity[];
}

View File

@ -1,11 +1,10 @@
import { DataSource, Repository } from 'typeorm';
import { Injectable } from '@nestjs/common'; import { Injectable } from '@nestjs/common';
import { DataSource, Repository } from 'typeorm';
import { import {
SpaceModelEntity, SpaceModelEntity,
SpaceModelProductAllocationEntity, SpaceModelProductAllocationEntity,
SubspaceModelEntity, SubspaceModelEntity,
SubspaceModelProductAllocationEntity, SubspaceModelProductAllocationEntity,
TagModel,
} from '../entities'; } from '../entities';
@Injectable() @Injectable()
@ -21,13 +20,6 @@ export class SubspaceModelRepository extends Repository<SubspaceModelEntity> {
} }
} }
@Injectable()
export class TagModelRepository extends Repository<TagModel> {
constructor(private dataSource: DataSource) {
super(TagModel, dataSource.createEntityManager());
}
}
@Injectable() @Injectable()
export class SpaceModelProductAllocationRepoitory extends Repository<SpaceModelProductAllocationEntity> { export class SpaceModelProductAllocationRepoitory extends Repository<SpaceModelProductAllocationEntity> {
constructor(private dataSource: DataSource) { constructor(private dataSource: DataSource) {

View File

@ -1,13 +1,11 @@
import { TypeOrmModule } from '@nestjs/typeorm';
import { SpaceModelEntity, SubspaceModelEntity, TagModel } from './entities';
import { Module } from '@nestjs/common'; import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { SpaceModelEntity, SubspaceModelEntity } from './entities';
@Module({ @Module({
providers: [], providers: [],
exports: [], exports: [],
controllers: [], controllers: [],
imports: [ imports: [TypeOrmModule.forFeature([SpaceModelEntity, SubspaceModelEntity])],
TypeOrmModule.forFeature([SpaceModelEntity, SubspaceModelEntity, TagModel]),
],
}) })
export class SpaceModelRepositoryModule {} export class SpaceModelRepositoryModule {}

View File

@ -1,12 +1,13 @@
import { Entity, Column, ManyToOne, ManyToMany, JoinTable } from 'typeorm'; import { Column, Entity, ManyToOne, Unique } from 'typeorm';
import { SpaceEntity } from './space.entity';
import { SpaceModelProductAllocationEntity } from '../../space-model/entities/space-model-product-allocation.entity';
import { ProductEntity } from '../../product/entities/product.entity';
import { NewTagEntity } from '../../tag/entities/tag.entity';
import { AbstractEntity } from '../../abstract/entities/abstract.entity'; import { AbstractEntity } from '../../abstract/entities/abstract.entity';
import { ProductEntity } from '../../product/entities/product.entity';
import { SpaceModelProductAllocationEntity } from '../../space-model/entities/space-model-product-allocation.entity';
import { NewTagEntity } from '../../tag/entities/tag.entity';
import { SpaceProductAllocationDto } from '../dtos/space-product-allocation.dto'; import { SpaceProductAllocationDto } from '../dtos/space-product-allocation.dto';
import { SpaceEntity } from './space.entity';
@Entity({ name: 'space_product_allocation' }) @Entity({ name: 'space_product_allocation' })
@Unique(['space', 'product', 'tag'], {})
export class SpaceProductAllocationEntity extends AbstractEntity<SpaceProductAllocationDto> { export class SpaceProductAllocationEntity extends AbstractEntity<SpaceProductAllocationDto> {
@Column({ @Column({
type: 'uuid', type: 'uuid',
@ -30,9 +31,8 @@ export class SpaceProductAllocationEntity extends AbstractEntity<SpaceProductAll
@ManyToOne(() => ProductEntity, { nullable: false, onDelete: 'CASCADE' }) @ManyToOne(() => ProductEntity, { nullable: false, onDelete: 'CASCADE' })
public product: ProductEntity; public product: ProductEntity;
@ManyToMany(() => NewTagEntity) @ManyToOne(() => NewTagEntity, { nullable: true, onDelete: 'CASCADE' })
@JoinTable({ name: 'space_product_tags' }) public tag: NewTagEntity;
public tags: NewTagEntity[];
constructor(partial: Partial<SpaceProductAllocationEntity>) { constructor(partial: Partial<SpaceProductAllocationEntity>) {
super(); super();

View File

@ -11,6 +11,8 @@ import { InviteUserSpaceEntity } from '../../Invite-user/entities';
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 { 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> {
@ -115,6 +117,15 @@ export class SpaceEntity extends AbstractEntity<SpaceDto> {
@OneToMany(() => PresenceSensorDailySpaceEntity, (sensor) => sensor.space) @OneToMany(() => PresenceSensorDailySpaceEntity, (sensor) => sensor.space)
presenceSensorDaily: PresenceSensorDailySpaceEntity[]; presenceSensorDaily: PresenceSensorDailySpaceEntity[];
@OneToMany(() => AqiSpaceDailyPollutantStatsEntity, (aqi) => aqi.space)
aqiSensorDaily: AqiSpaceDailyPollutantStatsEntity[];
@OneToMany(
() => SpaceDailyOccupancyDurationEntity,
(occupancy) => occupancy.space,
)
occupancyDaily: SpaceDailyOccupancyDurationEntity[];
constructor(partial: Partial<SpaceEntity>) { constructor(partial: Partial<SpaceEntity>) {
super(); super();
Object.assign(this, partial); Object.assign(this, partial);

View File

@ -1,20 +1,13 @@
import { import { AbstractEntity } from '@app/common/modules/abstract/entities/abstract.entity';
Entity,
Column,
ManyToOne,
ManyToMany,
JoinTable,
Unique,
} from 'typeorm';
import { SubspaceEntity } from './subspace.entity';
import { ProductEntity } from '@app/common/modules/product/entities'; import { ProductEntity } from '@app/common/modules/product/entities';
import { SubspaceModelProductAllocationEntity } from '@app/common/modules/space-model'; import { SubspaceModelProductAllocationEntity } from '@app/common/modules/space-model';
import { NewTagEntity } from '@app/common/modules/tag/entities/tag.entity'; import { NewTagEntity } from '@app/common/modules/tag/entities/tag.entity';
import { AbstractEntity } from '@app/common/modules/abstract/entities/abstract.entity'; import { Column, Entity, ManyToOne, Unique } from 'typeorm';
import { SubspaceProductAllocationDto } from '../../dtos/subspace-product-allocation.dto'; import { SubspaceProductAllocationDto } from '../../dtos/subspace-product-allocation.dto';
import { SubspaceEntity } from './subspace.entity';
@Entity({ name: 'subspace_product_allocation' }) @Entity({ name: 'subspace_product_allocation' })
// @Unique(['subspace', 'product']) @Unique(['subspace', 'product', 'tag'])
export class SubspaceProductAllocationEntity extends AbstractEntity<SubspaceProductAllocationDto> { export class SubspaceProductAllocationEntity extends AbstractEntity<SubspaceProductAllocationDto> {
@Column({ @Column({
type: 'uuid', type: 'uuid',
@ -38,9 +31,8 @@ export class SubspaceProductAllocationEntity extends AbstractEntity<SubspaceProd
@ManyToOne(() => ProductEntity, { nullable: false, onDelete: 'CASCADE' }) @ManyToOne(() => ProductEntity, { nullable: false, onDelete: 'CASCADE' })
public product: ProductEntity; public product: ProductEntity;
@ManyToMany(() => NewTagEntity) @ManyToOne(() => NewTagEntity, { nullable: true, onDelete: 'CASCADE' })
@JoinTable({ name: 'subspace_product_tags' }) public tag: NewTagEntity;
public tags: NewTagEntity[];
constructor(partial: Partial<SubspaceProductAllocationEntity>) { constructor(partial: Partial<SubspaceProductAllocationEntity>) {
super(); super();

View File

@ -4,7 +4,6 @@ import { SubspaceModelEntity } from '@app/common/modules/space-model';
import { Column, Entity, JoinColumn, ManyToOne, OneToMany } from 'typeorm'; import { Column, Entity, JoinColumn, ManyToOne, OneToMany } from 'typeorm';
import { SubspaceDto } from '../../dtos'; import { SubspaceDto } from '../../dtos';
import { SpaceEntity } from '../space.entity'; import { SpaceEntity } from '../space.entity';
import { TagEntity } from '../tag.entity';
import { SubspaceProductAllocationEntity } from './subspace-product-allocation.entity'; import { SubspaceProductAllocationEntity } from './subspace-product-allocation.entity';
@Entity({ name: 'subspace' }) @Entity({ name: 'subspace' })
@ -43,9 +42,6 @@ export class SubspaceEntity extends AbstractEntity<SubspaceDto> {
}) })
subSpaceModel?: SubspaceModelEntity; subSpaceModel?: SubspaceModelEntity;
@OneToMany(() => TagEntity, (tag) => tag.subspace)
tags: TagEntity[];
@OneToMany( @OneToMany(
() => SubspaceProductAllocationEntity, () => SubspaceProductAllocationEntity,
(allocation) => allocation.subspace, (allocation) => allocation.subspace,

View File

@ -1,41 +0,0 @@
import { Entity, Column, ManyToOne, JoinColumn, OneToOne } from 'typeorm';
import { AbstractEntity } from '../../abstract/entities/abstract.entity';
import { ProductEntity } from '../../product/entities';
import { TagDto } from '../dtos';
import { TagModel } from '../../space-model/entities/tag-model.entity';
import { DeviceEntity } from '../../device/entities';
import { SubspaceEntity } from './subspace/subspace.entity';
@Entity({ name: 'tag' })
export class TagEntity extends AbstractEntity<TagDto> {
@Column({ type: 'varchar', length: 255, nullable: true })
tag: string;
@ManyToOne(() => TagModel, (model) => model.tags, {
nullable: true,
})
model: TagModel;
@ManyToOne(() => ProductEntity, (product) => product.tags, {
nullable: false,
})
product: ProductEntity;
@ManyToOne(() => SubspaceEntity, (subspace) => subspace.tags, {
nullable: true,
})
@JoinColumn({ name: 'subspace_id' })
subspace: SubspaceEntity;
@Column({
nullable: false,
default: false,
})
public disabled: boolean;
@OneToOne(() => DeviceEntity, (device) => device.tag, {
nullable: true,
})
@JoinColumn({ name: 'device_id' })
device: DeviceEntity;
}

View File

@ -1,10 +1,9 @@
import { DataSource, Repository } from 'typeorm';
import { Injectable } from '@nestjs/common'; import { Injectable } from '@nestjs/common';
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 { SpaceLinkEntity } from '../entities/space-link.entity';
import { SpaceEntity } from '../entities/space.entity';
import { TagEntity } from '../entities/tag.entity';
import { SpaceProductAllocationEntity } from '../entities/space-product-allocation.entity'; import { SpaceProductAllocationEntity } from '../entities/space-product-allocation.entity';
import { SpaceEntity } from '../entities/space.entity';
@Injectable() @Injectable()
export class SpaceRepository extends Repository<SpaceEntity> { export class SpaceRepository extends Repository<SpaceEntity> {
@ -20,13 +19,6 @@ export class SpaceLinkRepository extends Repository<SpaceLinkEntity> {
} }
} }
@Injectable()
export class TagRepository extends Repository<TagEntity> {
constructor(private dataSource: DataSource) {
super(TagEntity, dataSource.createEntityManager());
}
}
@Injectable() @Injectable()
export class InviteSpaceRepository extends Repository<InviteSpaceEntity> { export class InviteSpaceRepository extends Repository<InviteSpaceEntity> {
constructor(private dataSource: DataSource) { constructor(private dataSource: DataSource) {

View File

@ -6,7 +6,6 @@ import { SpaceProductAllocationEntity } from './entities/space-product-allocatio
import { SpaceEntity } from './entities/space.entity'; import { SpaceEntity } from './entities/space.entity';
import { SubspaceProductAllocationEntity } from './entities/subspace/subspace-product-allocation.entity'; import { SubspaceProductAllocationEntity } from './entities/subspace/subspace-product-allocation.entity';
import { SubspaceEntity } from './entities/subspace/subspace.entity'; import { SubspaceEntity } from './entities/subspace/subspace.entity';
import { TagEntity } from './entities/tag.entity';
@Module({ @Module({
providers: [], providers: [],
@ -16,7 +15,6 @@ import { TagEntity } from './entities/tag.entity';
TypeOrmModule.forFeature([ TypeOrmModule.forFeature([
SpaceEntity, SpaceEntity,
SubspaceEntity, SubspaceEntity,
TagEntity,
InviteSpaceEntity, InviteSpaceEntity,
SpaceProductAllocationEntity, SpaceProductAllocationEntity,
SubspaceProductAllocationEntity, SubspaceProductAllocationEntity,

View File

@ -1,11 +1,10 @@
import { Entity, Column, ManyToOne, Unique, ManyToMany } from 'typeorm'; import { Column, Entity, ManyToOne, OneToMany, Unique } from 'typeorm';
import { ProductEntity } from '../../product/entities';
import { ProjectEntity } from '../../project/entities';
import { AbstractEntity } from '../../abstract/entities/abstract.entity'; import { AbstractEntity } from '../../abstract/entities/abstract.entity';
import { NewTagDto } from '../dtos/tag.dto'; import { DeviceEntity } from '../../device/entities/device.entity';
import { ProjectEntity } from '../../project/entities';
import { SpaceModelProductAllocationEntity } from '../../space-model/entities/space-model-product-allocation.entity'; import { SpaceModelProductAllocationEntity } from '../../space-model/entities/space-model-product-allocation.entity';
import { SubspaceModelProductAllocationEntity } from '../../space-model/entities/subspace-model/subspace-model-product-allocation.entity'; import { SubspaceModelProductAllocationEntity } from '../../space-model/entities/subspace-model/subspace-model-product-allocation.entity';
import { DeviceEntity } from '../../device/entities/device.entity'; import { NewTagDto } from '../dtos/tag.dto';
@Entity({ name: 'new_tag' }) @Entity({ name: 'new_tag' })
@Unique(['name', 'project']) @Unique(['name', 'project'])
@ -24,31 +23,25 @@ export class NewTagEntity extends AbstractEntity<NewTagDto> {
}) })
name: string; name: string;
@ManyToOne(() => ProductEntity, (product) => product.newTags, {
nullable: true,
onDelete: 'CASCADE',
})
public product: ProductEntity;
@ManyToOne(() => ProjectEntity, (project) => project.tags, { @ManyToOne(() => ProjectEntity, (project) => project.tags, {
nullable: false, nullable: false,
onDelete: 'CASCADE', onDelete: 'CASCADE',
}) })
public project: ProjectEntity; public project: ProjectEntity;
@ManyToMany( @OneToMany(
() => SpaceModelProductAllocationEntity, () => SpaceModelProductAllocationEntity,
(allocation) => allocation.tags, (allocation) => allocation.tag,
) )
public spaceModelAllocations: SpaceModelProductAllocationEntity[]; public spaceModelAllocations: SpaceModelProductAllocationEntity[];
@ManyToMany( @OneToMany(
() => SubspaceModelProductAllocationEntity, () => SubspaceModelProductAllocationEntity,
(allocation) => allocation.tags, (allocation) => allocation.tag,
) )
public subspaceModelAllocations: SubspaceModelProductAllocationEntity[]; public subspaceModelAllocations: SubspaceModelProductAllocationEntity[];
@ManyToOne(() => DeviceEntity, (device) => device.tag) @OneToMany(() => DeviceEntity, (device) => device.tag)
public devices: DeviceEntity[]; public devices: DeviceEntity[];
constructor(partial: Partial<NewTagEntity>) { constructor(partial: Partial<NewTagEntity>) {

View File

@ -13,142 +13,81 @@ WITH presence_logs AS (
AND p.cat_name = 'hps' AND p.cat_name = 'hps'
), ),
raw_absence_intervals AS ( -- Intervals when device was in 'presence' (between prev_time and event_time when value='none')
presence_intervals AS (
SELECT SELECT
space_id, space_id,
device_id,
prev_time AS start_time, prev_time AS start_time,
event_time AS end_time event_time AS end_time
FROM presence_logs FROM presence_logs
WHERE prev_value = 'none' AND prev_time IS NOT NULL WHERE value = 'none'
AND prev_value = 'presence'
AND prev_time IS NOT NULL
), ),
absence_intervals AS ( -- Split intervals across days
SELECT split_intervals AS (
r.space_id,
r.device_id,
gs.day,
GREATEST(r.start_time, gs.day) AS start_time,
LEAST(r.end_time, gs.day + INTERVAL '1 day') AS end_time
FROM raw_absence_intervals r
CROSS JOIN LATERAL (
SELECT generate_series(
date_trunc('day', r.start_time),
date_trunc('day', r.end_time),
INTERVAL '1 day'
) AS day
) gs
WHERE GREATEST(r.start_time, gs.day) < LEAST(r.end_time, gs.day + INTERVAL '1 day')
),
device_counts AS (
SELECT space_id, day, COUNT(DISTINCT device_id) AS device_count
FROM absence_intervals
GROUP BY 1, 2
),
timeline AS (
SELECT
a.space_id,
a.day,
a.device_id,
a.start_time AS ts,
1 AS is_start
FROM absence_intervals a
UNION ALL
SELECT
a.space_id,
a.day,
a.device_id,
a.end_time AS ts,
0 AS is_start
FROM absence_intervals a
),
ordered_events AS (
SELECT SELECT
space_id, space_id,
day, generate_series(
ts, date_trunc('day', start_time),
is_start, date_trunc('day', end_time),
device_id, interval '1 day'
SUM(CASE WHEN is_start = 1 THEN 1 ELSE -1 END) )::date AS event_date,
OVER (PARTITION BY space_id, day, device_id ORDER BY ts) AS device_active GREATEST(start_time, date_trunc('day', start_time)) AS interval_start,
FROM timeline LEAST(end_time, date_trunc('day', end_time) + interval '1 day') AS interval_end
FROM presence_intervals
), ),
device_state_changes AS ( -- Mark and group overlapping intervals per space per day
ordered_intervals AS (
SELECT SELECT
space_id, space_id,
day, event_date,
ts, interval_start,
SUM(CASE WHEN is_start = 1 THEN 1 ELSE -1 END) interval_end,
OVER (PARTITION BY space_id, day ORDER BY ts) AS net_active_devices LAG(interval_end) OVER (PARTITION BY space_id, event_date ORDER BY interval_start) AS prev_end
FROM ( FROM split_intervals
SELECT DISTINCT space_id, day, ts, is_start
FROM timeline
) t
), ),
absence_windows AS ( grouped_intervals AS (
SELECT SELECT *,
dc.space_id, SUM(CASE
dc.day, WHEN prev_end IS NULL OR interval_start > prev_end THEN 1
ts AS start_time, ELSE 0
LEAD(ts) OVER (PARTITION BY dc.space_id, dc.day ORDER BY ts) AS end_time END) OVER (PARTITION BY space_id, event_date ORDER BY interval_start) AS grp
FROM device_state_changes dsc FROM ordered_intervals
JOIN device_counts dc ON dc.space_id = dsc.space_id AND dc.day = dsc.day
WHERE net_active_devices = 0
), ),
empty_periods AS ( -- Merge overlapping intervals per group
merged_intervals AS (
SELECT SELECT
space_id, space_id,
day, event_date,
EXTRACT(EPOCH FROM (end_time - start_time)) AS unoccupied_seconds MIN(interval_start) AS merged_start,
FROM absence_windows MAX(interval_end) AS merged_end
WHERE end_time IS NOT NULL FROM grouped_intervals
GROUP BY space_id, event_date, grp
), ),
unoccupied_summary AS ( -- Sum durations of merged intervals
summed_intervals AS (
SELECT SELECT
space_id, space_id,
day, event_date,
SUM(unoccupied_seconds) AS total_unoccupied_seconds SUM(EXTRACT(EPOCH FROM (merged_end - merged_start))) AS raw_occupied_seconds
FROM empty_periods FROM merged_intervals
GROUP BY space_id, day GROUP BY space_id, event_date
), ),
-- Include device count even for days with 0 unoccupied time final_data AS (
all_days_with_devices AS (
SELECT
space_id,
DATE(event_time) AS day,
COUNT(DISTINCT device_id) AS device_count
FROM presence_logs
GROUP BY 1, 2
),
final_occupancy AS (
SELECT
d.space_id,
d.day,
d.device_count,
COALESCE(u.total_unoccupied_seconds, 0) AS unoccupied_seconds,
86400 - COALESCE(u.total_unoccupied_seconds, 0) AS occupied_seconds
FROM all_days_with_devices d
LEFT JOIN unoccupied_summary u
ON d.space_id = u.space_id AND d.day = u.day
)
, final_data as (
SELECT SELECT
space_id, space_id,
day, event_date,
device_count, LEAST(raw_occupied_seconds, 86400) AS occupied_seconds,
occupied_seconds, ROUND(LEAST(raw_occupied_seconds, 86400) / 86400.0 * 100, 2) AS occupancy_percentage
ROUND(occupied_seconds / 86400.0 * 100, 2) AS occupancy_percentage FROM summed_intervals
FROM final_occupancy ORDER BY space_id, event_date)
ORDER BY space_id, day)
INSERT INTO public."space-daily-occupancy-duration" ( INSERT INTO public."space-daily-occupancy-duration" (

View File

@ -10,8 +10,7 @@ presence_logs AS (
l.device_id, l.device_id,
l.event_time, l.event_time,
l.value, l.value,
LAG(l.event_time) OVER (PARTITION BY l.device_id ORDER BY l.event_time) AS prev_time, LAG(l.event_time) OVER (PARTITION BY l.device_id ORDER BY l.event_time) AS prev_time
LAG(l.value) OVER (PARTITION BY l.device_id ORDER BY l.event_time) AS prev_value
FROM device d FROM device d
JOIN "device-status-log" l ON d.uuid = l.device_id JOIN "device-status-log" l ON d.uuid = l.device_id
JOIN product p ON p.uuid = d.product_device_uuid JOIN product p ON p.uuid = d.product_device_uuid
@ -19,147 +18,77 @@ presence_logs AS (
AND p.cat_name = 'hps' AND p.cat_name = 'hps'
), ),
raw_absence_intervals AS ( presence_intervals AS (
SELECT SELECT
space_id, space_id,
device_id,
prev_time AS start_time, prev_time AS start_time,
event_time AS end_time event_time AS end_time
FROM presence_logs FROM presence_logs
WHERE prev_value = 'none' AND prev_time IS NOT NULL WHERE value = 'none' AND prev_time IS NOT NULL
), ),
absence_intervals AS ( split_intervals AS (
SELECT
r.space_id,
r.device_id,
gs.day,
GREATEST(r.start_time, gs.day) AS start_time,
LEAST(r.end_time, gs.day + INTERVAL '1 day') AS end_time
FROM raw_absence_intervals r
CROSS JOIN LATERAL (
SELECT generate_series(
date_trunc('day', r.start_time),
date_trunc('day', r.end_time),
INTERVAL '1 day'
) AS day
) gs
WHERE GREATEST(r.start_time, gs.day) < LEAST(r.end_time, gs.day + INTERVAL '1 day')
),
device_counts AS (
SELECT space_id, day, COUNT(DISTINCT device_id) AS device_count
FROM absence_intervals
GROUP BY 1, 2
),
timeline AS (
SELECT
a.space_id,
a.day,
a.device_id,
a.start_time AS ts,
1 AS is_start
FROM absence_intervals a
UNION ALL
SELECT
a.space_id,
a.day,
a.device_id,
a.end_time AS ts,
0 AS is_start
FROM absence_intervals a
),
ordered_events AS (
SELECT SELECT
space_id, space_id,
day, generate_series(
ts, date_trunc('day', start_time),
is_start, date_trunc('day', end_time),
device_id, interval '1 day'
SUM(CASE WHEN is_start = 1 THEN 1 ELSE -1 END) )::date AS event_date,
OVER (PARTITION BY space_id, day, device_id ORDER BY ts) AS device_active GREATEST(start_time, date_trunc('day', start_time)) AS interval_start,
FROM timeline LEAST(end_time, date_trunc('day', end_time) + INTERVAL '1 day') AS interval_end
FROM presence_intervals
), ),
device_state_changes AS ( ordered_intervals AS (
SELECT SELECT
space_id, space_id,
day, event_date,
ts, interval_start,
SUM(CASE WHEN is_start = 1 THEN 1 ELSE -1 END) interval_end,
OVER (PARTITION BY space_id, day ORDER BY ts) AS net_active_devices LAG(interval_end) OVER (PARTITION BY space_id, event_date ORDER BY interval_start) AS prev_end
FROM ( FROM split_intervals
SELECT DISTINCT space_id, day, ts, is_start
FROM timeline
) t
), ),
absence_windows AS ( grouped_intervals AS (
SELECT SELECT *,
dc.space_id, SUM(CASE
dc.day, WHEN prev_end IS NULL OR interval_start > prev_end THEN 1
ts AS start_time, ELSE 0
LEAD(ts) OVER (PARTITION BY dc.space_id, dc.day ORDER BY ts) AS end_time END) OVER (PARTITION BY space_id, event_date ORDER BY interval_start) AS grp
FROM device_state_changes dsc FROM ordered_intervals
JOIN device_counts dc ON dc.space_id = dsc.space_id AND dc.day = dsc.day
WHERE net_active_devices = 0
), ),
empty_periods AS ( merged_intervals AS (
SELECT SELECT
space_id, space_id,
day, event_date,
EXTRACT(EPOCH FROM (end_time - start_time)) AS unoccupied_seconds MIN(interval_start) AS merged_start,
FROM absence_windows MAX(interval_end) AS merged_end
WHERE end_time IS NOT NULL FROM grouped_intervals
GROUP BY space_id, event_date, grp
), ),
unoccupied_summary AS ( summed_intervals AS (
SELECT SELECT
space_id, space_id,
day, event_date,
SUM(unoccupied_seconds) AS total_unoccupied_seconds SUM(EXTRACT(EPOCH FROM (merged_end - merged_start))) AS raw_occupied_seconds
FROM empty_periods FROM merged_intervals
GROUP BY space_id, day GROUP BY space_id, event_date
), ),
-- Include device count even for days with 0 unoccupied time final_data AS (
all_days_with_devices AS (
SELECT SELECT
space_id, s.space_id,
DATE(event_time) AS day, s.event_date,
COUNT(DISTINCT device_id) AS device_count LEAST(raw_occupied_seconds, 86400) AS occupied_seconds,
FROM presence_logs ROUND(LEAST(raw_occupied_seconds, 86400) / 86400.0 * 100, 2) AS occupancy_percentage
GROUP BY 1, 2 FROM summed_intervals s
), JOIN params p
final_occupancy AS (
SELECT
d.space_id,
d.day,
d.device_count,
COALESCE(u.total_unoccupied_seconds, 0) AS unoccupied_seconds,
86400 - COALESCE(u.total_unoccupied_seconds, 0) AS occupied_seconds
FROM all_days_with_devices d
LEFT JOIN unoccupied_summary u
ON d.space_id = u.space_id AND d.day = u.day
),
final_data as(
SELECT
space_id,
day,
device_count,
occupied_seconds,
ROUND(occupied_seconds / 86400.0 * 100, 2) AS occupancy_percentage
FROM final_occupancy s
JOIN params p
ON p.space_id = s.space_id ON p.space_id = s.space_id
AND p.event_date = s.event_date AND p.event_date = s.event_date
ORDER BY space_id, DAY) )
INSERT INTO public."space-daily-occupancy-duration" ( INSERT INTO public."space-daily-occupancy-duration" (
space_uuid, space_uuid,

View File

@ -13,7 +13,3 @@ AND (
OR TO_CHAR(psdsd.event_date, 'YYYY') = TO_CHAR(P.event_year, 'YYYY') OR TO_CHAR(psdsd.event_date, 'YYYY') = TO_CHAR(P.event_year, 'YYYY')
) )
ORDER BY space_uuid, event_date ORDER BY space_uuid, event_date

View File

@ -13,156 +13,78 @@ WITH presence_logs AS (
AND p.cat_name = 'hps' AND p.cat_name = 'hps'
), ),
-- Intervals when device was in 'absence' (between prev_time and event_time when value='none') -- Intervals when device was in 'presence' (between prev_time and event_time when value='none')
raw_absence_intervals AS ( presence_intervals AS (
SELECT SELECT
space_id, space_id,
device_id,
prev_time AS start_time, prev_time AS start_time,
event_time AS end_time event_time AS end_time
FROM presence_logs FROM presence_logs
WHERE value <> 'none' WHERE value = 'none'
AND prev_value = 'none' AND prev_value = 'presence'
AND prev_time IS NOT NULL AND prev_time IS NOT NULL
), ),
-- Split intervals that span multiple days into day-specific chunks -- Split intervals across days
absence_intervals AS ( split_intervals AS (
SELECT
r.space_id,
r.device_id,
GREATEST(r.start_time, gs.day::timestamp) AS start_time,
LEAST(r.end_time, (gs.day + INTERVAL '1 day' - INTERVAL '1 second')::timestamp) AS end_time
FROM raw_absence_intervals r
CROSS JOIN LATERAL (
SELECT generate_series(
date_trunc('day', r.start_time),
date_trunc('day', r.end_time),
INTERVAL '1 day'
) AS day
) gs
WHERE GREATEST(r.start_time, gs.day::timestamp) < LEAST(r.end_time, (gs.day + INTERVAL '1 day')::timestamp)
),
-- FIXED: Count devices based on presence_logs OR absence_intervals
devices_per_day AS (
SELECT SELECT
space_id, space_id,
day, generate_series(
COUNT(DISTINCT device_id) AS device_count date_trunc('day', start_time),
FROM ( date_trunc('day', end_time),
-- Devices that logged events on that day interval '1 day'
SELECT space_id, DATE(event_time) AS day, device_id )::date AS event_date,
FROM presence_logs GREATEST(start_time, date_trunc('day', start_time)) AS interval_start,
LEAST(end_time, date_trunc('day', end_time) + interval '1 day') AS interval_end
UNION FROM presence_intervals
-- Devices that had absence intervals on that day
SELECT space_id, DATE(start_time) AS day, device_id
FROM absence_intervals
) combined
GROUP BY space_id, day
), ),
-- Mark and group overlapping intervals per space per day
-- For multi-device spaces, find all time periods when ALL devices were absent ordered_intervals AS (
multi_device_unoccupied AS (
WITH device_absence_per_day AS (
SELECT
a.space_id,
DATE(a.start_time) AS day,
a.device_id,
a.start_time,
a.end_time,
d.device_count
FROM absence_intervals a
JOIN devices_per_day d ON a.space_id = d.space_id AND DATE(a.start_time) = d.day
WHERE d.device_count > 1
),
-- Generate time slots for each day with multiple devices
time_ranges AS (
SELECT
space_id,
day,
day::timestamp AS range_start,
(day + INTERVAL '1 day')::timestamp AS range_end,
device_count
FROM devices_per_day
WHERE device_count > 1
),
-- Find all time periods when all devices were absent
all_devices_absent AS (
SELECT
t.space_id,
t.day,
t.range_start,
t.range_end,
t.device_count,
-- Find the latest start time of all devices' absence intervals
MAX(a.start_time) OVER (PARTITION BY t.space_id, t.day) AS max_start_time,
-- Find the earliest end time of all devices' absence intervals
MIN(a.end_time) OVER (PARTITION BY t.space_id, t.day) AS min_end_time
FROM time_ranges t
LEFT JOIN device_absence_per_day a ON
t.space_id = a.space_id AND
t.day = a.day
GROUP BY t.space_id, t.day, t.range_start, t.range_end, t.device_count, a.start_time, a.end_time
)
-- Calculate total unoccupied seconds when all devices were absent
SELECT SELECT
space_id, space_id,
day, event_date,
CASE interval_start,
WHEN max_start_time IS NULL OR min_end_time IS NULL THEN 0 interval_end,
WHEN max_start_time >= min_end_time THEN 0 LAG(interval_end) OVER (PARTITION BY space_id, event_date ORDER BY interval_start) AS prev_end
ELSE EXTRACT(EPOCH FROM (LEAST(min_end_time, range_end) - GREATEST(max_start_time, range_start))) FROM split_intervals
END AS unoccupied_seconds
FROM all_devices_absent
GROUP BY space_id, day, range_start, range_end, device_count, max_start_time, min_end_time
HAVING COUNT(*) = device_count -- Only include periods when all devices were absent
)
,
-- Calculate unoccupied time for spaces with single device reporting
single_device_unoccupied AS (
SELECT
a.space_id,
DATE(a.start_time) AS day,
SUM(EXTRACT(EPOCH FROM (a.end_time - a.start_time))) AS unoccupied_seconds
FROM absence_intervals a
JOIN devices_per_day d ON a.space_id = d.space_id AND DATE(a.start_time) = d.day
WHERE d.device_count = 1
GROUP BY a.space_id, DATE(a.start_time)
)
,
-- Combine results from both single and multi-device cases
combined_unoccupied AS (
SELECT space_id, day, unoccupied_seconds FROM single_device_unoccupied
UNION ALL
SELECT space_id, day, unoccupied_seconds FROM multi_device_unoccupied
), ),
-- Calculate total occupied time per space per day grouped_intervals AS (
daily_occupancy AS ( SELECT *,
SUM(CASE
WHEN prev_end IS NULL OR interval_start > prev_end THEN 1
ELSE 0
END) OVER (PARTITION BY space_id, event_date ORDER BY interval_start) AS grp
FROM ordered_intervals
),
-- Merge overlapping intervals per group
merged_intervals AS (
SELECT SELECT
space_id, space_id,
day, event_date,
-- Total seconds in day (86400) minus unoccupied seconds MIN(interval_start) AS merged_start,
86400 - COALESCE(SUM(unoccupied_seconds), 0) AS occupied_seconds MAX(interval_end) AS merged_end
FROM combined_unoccupied FROM grouped_intervals
GROUP BY space_id, day GROUP BY space_id, event_date, grp
),
-- Sum durations of merged intervals
summed_intervals AS (
SELECT
space_id,
event_date,
SUM(EXTRACT(EPOCH FROM (merged_end - merged_start))) AS raw_occupied_seconds
FROM merged_intervals
GROUP BY space_id, event_date
) )
-- Final result -- Final output with capped seconds and percentage
SELECT SELECT
space_id, space_id,
day, event_date,
occupied_seconds, LEAST(raw_occupied_seconds, 86400) AS occupied_seconds,
-- Also include percentage for convenience ROUND(LEAST(raw_occupied_seconds, 86400) / 86400.0 * 100, 2) AS occupancy_percentage
ROUND((occupied_seconds / 86400.0) * 100, 2) AS occupancy_percentage FROM summed_intervals
FROM daily_occupancy ORDER BY space_id, event_date;
ORDER BY space_id, day;

View File

@ -1,7 +1,7 @@
import { HttpException, HttpStatus, Injectable } from '@nestjs/common'; import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config'; import { ConfigService } from '@nestjs/config';
import * as nodemailer from 'nodemailer';
import axios from 'axios'; import axios from 'axios';
import * as nodemailer from 'nodemailer';
import { import {
SEND_EMAIL_API_URL_DEV, SEND_EMAIL_API_URL_DEV,
SEND_EMAIL_API_URL_PROD, SEND_EMAIL_API_URL_PROD,
@ -83,12 +83,17 @@ export class EmailService {
); );
} }
} }
async sendEmailWithTemplate( async sendEmailWithTemplate({
email: string, email,
name: string, name,
isEnable: boolean, isEnable,
isDelete: boolean, isDelete,
): Promise<void> { }: {
email: string;
name: string;
isEnable: boolean;
isDelete: boolean;
}): Promise<void> {
const isProduction = process.env.NODE_ENV === 'production'; const isProduction = process.env.NODE_ENV === 'production';
const API_TOKEN = this.configService.get<string>( const API_TOKEN = this.configService.get<string>(
'email-config.MAILTRAP_API_TOKEN', 'email-config.MAILTRAP_API_TOKEN',

View File

@ -10,6 +10,7 @@
"format": "prettier --write \"apps/**/*.ts\" \"libs/**/*.ts\"", "format": "prettier --write \"apps/**/*.ts\" \"libs/**/*.ts\"",
"start": "npm run test && node dist/main", "start": "npm run test && node dist/main",
"start:dev": "npm run test && npx nest start --watch", "start:dev": "npm run test && npx nest start --watch",
"dev": "npx nest start --watch",
"start:debug": "npm run test && npx nest start --debug --watch", "start:debug": "npm run test && npx nest start --debug --watch",
"start:prod": "npm run test && node dist/main", "start:prod": "npm run test && node dist/main",
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix", "lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
@ -86,5 +87,9 @@
"ts-node": "^10.9.1", "ts-node": "^10.9.1",
"tsconfig-paths": "^4.2.0", "tsconfig-paths": "^4.2.0",
"typescript": "^5.1.3" "typescript": "^5.1.3"
},
"engines": {
"node": "20.x",
"npm": "10.x"
} }
} }

View File

@ -1,42 +1,42 @@
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 config from './config'; import { APP_INTERCEPTOR } from '@nestjs/core';
import { WinstonModule } from 'nest-winston';
import { AuthenticationModule } from './auth/auth.module'; import { AuthenticationModule } from './auth/auth.module';
import { UserModule } from './users/user.module';
import { GroupModule } from './group/group.module';
import { DeviceModule } from './device/device.module';
import { UserDevicePermissionModule } from './user-device-permission/user-device-permission.module';
import { CommunityModule } from './community/community.module';
import { SeederModule } from '@app/common/seed/seeder.module';
import { UserNotificationModule } from './user-notification/user-notification.module';
import { DeviceMessagesSubscriptionModule } from './device-messages/device-messages.module';
import { SceneModule } from './scene/scene.module';
import { DoorLockModule } from './door-lock/door.lock.module';
import { APP_GUARD, APP_INTERCEPTOR } from '@nestjs/core';
import { LoggingInterceptor } from './interceptors/logging.interceptor';
import { AutomationModule } from './automation/automation.module'; import { AutomationModule } from './automation/automation.module';
import { RegionModule } from './region/region.module';
import { TimeZoneModule } from './timezone/timezone.module';
import { VisitorPasswordModule } from './vistor-password/visitor-password.module';
import { ScheduleModule } from './schedule/schedule.module';
import { SpaceModule } from './space/space.module';
import { ProductModule } from './product';
import { ProjectModule } from './project';
import { SpaceModelModule } from './space-model';
import { InviteUserModule } from './invite-user/invite-user.module';
import { PermissionModule } from './permission/permission.module';
import { RoleModule } from './role/role.module';
import { TermsConditionsModule } from './terms-conditions/terms-conditions.module';
import { PrivacyPolicyModule } from './privacy-policy/privacy-policy.module';
import { TagModule } from './tags/tags.module';
import { ClientModule } from './client/client.module'; import { ClientModule } from './client/client.module';
import { DeviceCommissionModule } from './commission-device/commission-device.module'; import { DeviceCommissionModule } from './commission-device/commission-device.module';
import { PowerClampModule } from './power-clamp/power-clamp.module'; import { CommunityModule } from './community/community.module';
import { WinstonModule } from 'nest-winston'; import config from './config';
import { ThrottlerGuard, ThrottlerModule } from '@nestjs/throttler'; import { DeviceMessagesSubscriptionModule } from './device-messages/device-messages.module';
import { DeviceModule } from './device/device.module';
import { DoorLockModule } from './door-lock/door.lock.module';
import { GroupModule } from './group/group.module';
import { HealthModule } from './health/health.module'; import { HealthModule } from './health/health.module';
import { LoggingInterceptor } from './interceptors/logging.interceptor';
import { InviteUserModule } from './invite-user/invite-user.module';
import { PermissionModule } from './permission/permission.module';
import { PowerClampModule } from './power-clamp/power-clamp.module';
import { PrivacyPolicyModule } from './privacy-policy/privacy-policy.module';
import { ProductModule } from './product';
import { ProjectModule } from './project';
import { RegionModule } from './region/region.module';
import { RoleModule } from './role/role.module';
import { SceneModule } from './scene/scene.module';
import { ScheduleModule } from './schedule/schedule.module';
import { SpaceModelModule } from './space-model';
import { SpaceModule } from './space/space.module';
import { TagModule } from './tags/tags.module';
import { TermsConditionsModule } from './terms-conditions/terms-conditions.module';
import { TimeZoneModule } from './timezone/timezone.module';
import { UserDevicePermissionModule } from './user-device-permission/user-device-permission.module';
import { UserNotificationModule } from './user-notification/user-notification.module';
import { UserModule } from './users/user.module';
import { VisitorPasswordModule } from './vistor-password/visitor-password.module';
import { 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 { OccupancyModule } from './occupancy/occupancy.module'; import { OccupancyModule } from './occupancy/occupancy.module';
import { WeatherModule } from './weather/weather.module'; import { WeatherModule } from './weather/weather.module';
@Module({ @Module({
@ -81,6 +81,7 @@ import { WeatherModule } from './weather/weather.module';
HealthModule, HealthModule,
OccupancyModule, OccupancyModule,
WeatherModule, WeatherModule,
AqiModule,
], ],
providers: [ providers: [
{ {

11
src/aqi/aqi.module.ts Normal file
View File

@ -0,0 +1,11 @@
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { SqlLoaderService } from '@app/common/helper/services/sql-loader.service';
import { AqiService } from './services';
import { AqiController } from './controllers';
@Module({
imports: [ConfigModule],
controllers: [AqiController],
providers: [AqiService, SqlLoaderService],
})
export class AqiModule {}

View File

@ -0,0 +1,64 @@
import { Controller, Get, Param, Query, UseGuards } from '@nestjs/common';
import {
ApiTags,
ApiBearerAuth,
ApiOperation,
ApiParam,
} from '@nestjs/swagger';
import { EnableDisableStatusEnum } from '@app/common/constants/days.enum';
import { ControllerRoute } from '@app/common/constants/controller-route';
import { JwtAuthGuard } from '@app/common/guards/jwt.auth.guard';
import { AqiService } from '../services/aqi.service';
import {
GetAqiDailyBySpaceDto,
GetAqiPollutantBySpaceDto,
} from '../dto/get-aqi.dto';
import { BaseResponseDto } from '@app/common/dto/base.response.dto';
import { SpaceParamsDto } from '../dto/aqi-params.dto';
@ApiTags('AQI Module')
@Controller({
version: EnableDisableStatusEnum.ENABLED,
path: ControllerRoute.AQI.ROUTE,
})
export class AqiController {
constructor(private readonly aqiService: AqiService) {}
@ApiBearerAuth()
@UseGuards(JwtAuthGuard)
@Get('range/space/:spaceUuid')
@ApiOperation({
summary: ControllerRoute.AQI.ACTIONS.GET_AQI_RANGE_DATA_SUMMARY,
description: ControllerRoute.AQI.ACTIONS.GET_AQI_RANGE_DATA_DESCRIPTION,
})
@ApiParam({
name: 'spaceUuid',
description: 'UUID of the Space',
required: true,
})
async getAQIRangeDataBySpace(
@Param() params: SpaceParamsDto,
@Query() query: GetAqiDailyBySpaceDto,
): Promise<BaseResponseDto> {
return await this.aqiService.getAQIRangeDataBySpace(params, query);
}
@ApiBearerAuth()
@UseGuards(JwtAuthGuard)
@Get('distribution/space/:spaceUuid')
@ApiOperation({
summary: ControllerRoute.AQI.ACTIONS.GET_AQI_DISTRIBUTION_DATA_SUMMARY,
description:
ControllerRoute.AQI.ACTIONS.GET_AQI_DISTRIBUTION_DATA_DESCRIPTION,
})
@ApiParam({
name: 'spaceUuid',
description: 'UUID of the Space',
required: true,
})
async getAQIDistributionDataBySpace(
@Param() params: SpaceParamsDto,
@Query() query: GetAqiPollutantBySpaceDto,
): Promise<BaseResponseDto> {
return await this.aqiService.getAQIDistributionDataBySpace(params, query);
}
}

View File

@ -0,0 +1 @@
export * from './aqi.controller';

View File

@ -0,0 +1,7 @@
import { IsNotEmpty, IsUUID } from 'class-validator';
export class SpaceParamsDto {
@IsUUID('4', { message: 'Invalid UUID format' })
@IsNotEmpty()
spaceUuid: string;
}

View File

@ -0,0 +1,37 @@
import { PollutantType } from '@app/common/constants/pollutants.enum';
import { ApiProperty } from '@nestjs/swagger';
import { Matches, IsNotEmpty, IsString } from 'class-validator';
export class GetAqiDailyBySpaceDto {
@ApiProperty({
description: 'Month and year in format YYYY-MM',
example: '2025-03',
required: true,
})
@Matches(/^\d{4}-(0[1-9]|1[0-2])$/, {
message: 'monthDate must be in YYYY-MM format',
})
@IsNotEmpty()
monthDate: string;
}
export class GetAqiPollutantBySpaceDto {
@ApiProperty({
description: 'Pollutant Type',
enum: PollutantType,
example: PollutantType.AQI,
required: true,
})
@IsString()
@IsNotEmpty()
public pollutantType: string;
@ApiProperty({
description: 'Month and year in format YYYY-MM',
example: '2025-03',
required: true,
})
@Matches(/^\d{4}-(0[1-9]|1[0-2])$/, {
message: 'monthDate must be in YYYY-MM format',
})
@IsNotEmpty()
monthDate: string;
}

View File

@ -0,0 +1,138 @@
import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import {
GetAqiDailyBySpaceDto,
GetAqiPollutantBySpaceDto,
} from '../dto/get-aqi.dto';
import { SuccessResponseDto } from '@app/common/dto/success.response.dto';
import { SpaceParamsDto } from '../dto/aqi-params.dto';
import { SqlLoaderService } from '@app/common/helper/services/sql-loader.service';
import { DataSource } from 'typeorm';
import { SQL_PROCEDURES_PATH } from '@app/common/constants/sql-query-path';
import { BaseResponseDto } from '@app/common/dto/base.response.dto';
import { convertKeysToCamelCase } from '@app/common/helper/camelCaseConverter';
import { PollutantType } from '@app/common/constants/pollutants.enum';
@Injectable()
export class AqiService {
constructor(
private readonly sqlLoader: SqlLoaderService,
private readonly dataSource: DataSource,
) {}
async getAQIDistributionDataBySpace(
params: SpaceParamsDto,
query: GetAqiPollutantBySpaceDto,
): Promise<BaseResponseDto> {
const { monthDate, pollutantType } = query;
const { spaceUuid } = params;
try {
const data = await this.executeProcedure(
'fact_daily_space_aqi',
'proceduce_select_daily_space_aqi',
[spaceUuid, monthDate],
);
const categories = [
'good',
'moderate',
'unhealthy_sensitive',
'unhealthy',
'very_unhealthy',
'hazardous',
];
const transformedData = data.map((item) => {
const date = new Date(item.event_date).toLocaleDateString('en-CA'); // YYYY-MM-DD
const categoryData = categories.map((category) => {
const key = `${category}_${pollutantType.toLowerCase()}_percentage`;
return {
type: category,
percentage: item[key] ?? 0,
};
});
return { date, data: categoryData };
});
const response = this.buildResponse(
`AQI distribution data fetched successfully for ${spaceUuid} space and pollutant ${pollutantType}`,
transformedData,
);
return response;
} catch (error) {
console.error('Failed to fetch AQI distribution data', {
error,
spaceUuid,
});
throw new HttpException(
error.response?.message || 'Failed to fetch AQI distribution data',
error.status || HttpStatus.INTERNAL_SERVER_ERROR,
);
}
}
async getAQIRangeDataBySpace(
params: SpaceParamsDto,
query: GetAqiDailyBySpaceDto,
): Promise<BaseResponseDto> {
const { monthDate } = query;
const { spaceUuid } = params;
try {
const data = await this.executeProcedure(
'fact_daily_space_aqi',
'proceduce_select_daily_space_aqi',
[spaceUuid, monthDate],
);
// Define pollutants dynamically
const pollutants = Object.values(PollutantType);
const transformedData = data.map((item) => {
const date = new Date(item.event_date).toLocaleDateString('en-CA'); // YYYY-MM-DD
const dailyData = pollutants.map((type) => ({
type,
min: item[`daily_min_${type}`],
max: item[`daily_max_${type}`],
average: item[`daily_avg_${type}`],
}));
return { date, data: dailyData };
});
const response = this.buildResponse(
`AQI data fetched successfully for ${spaceUuid} space`,
transformedData,
);
return convertKeysToCamelCase(response);
} catch (error) {
console.error('Failed to fetch AQI data', {
error,
spaceUuid,
});
throw new HttpException(
error.response?.message || 'Failed to fetch AQI data',
error.status || HttpStatus.INTERNAL_SERVER_ERROR,
);
}
}
private buildResponse(message: string, data: any[]) {
return new SuccessResponseDto({
message,
data,
statusCode: HttpStatus.OK,
});
}
private async executeProcedure(
procedureFolderName: string,
procedureFileName: string,
params: (string | number | null)[],
): Promise<any[]> {
const query = this.loadQuery(procedureFolderName, procedureFileName);
return await this.dataSource.query(query, params);
}
private loadQuery(folderName: string, fileName: string): string {
return this.sqlLoader.loadQuery(folderName, fileName, SQL_PROCEDURES_PATH);
}
}

View File

@ -0,0 +1 @@
export * from './aqi.service';

View File

@ -29,6 +29,7 @@ import {
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';
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';
@Module({ @Module({
imports: [ConfigModule, SpaceRepositoryModule], imports: [ConfigModule, SpaceRepositoryModule],
@ -57,6 +58,7 @@ import { OccupancyService } from '@app/common/helper/services/occupancy.service'
PowerClampMonthlyRepository, PowerClampMonthlyRepository,
SqlLoaderService, SqlLoaderService,
OccupancyService, OccupancyService,
AqiDataService,
], ],
exports: [], exports: [],
}) })

View File

@ -1,17 +1,19 @@
import * as fs from 'fs';
import * as csv from 'csv-parser'; import * as csv from 'csv-parser';
import * as fs from 'fs';
import { ProjectParam } from '@app/common/dto/project-param.dto';
import { SuccessResponseDto } from '@app/common/dto/success.response.dto';
import { TuyaService } from '@app/common/integrations/tuya/services/tuya.service'; import { TuyaService } from '@app/common/integrations/tuya/services/tuya.service';
import { CommunityRepository } from '@app/common/modules/community/repositories';
import { DeviceRepository } from '@app/common/modules/device/repositories';
import { ProjectRepository } from '@app/common/modules/project/repositiories';
import { SpaceRepository } from '@app/common/modules/space';
import { SpaceProductAllocationEntity } from '@app/common/modules/space/entities/space-product-allocation.entity';
import { SubspaceProductAllocationEntity } from '@app/common/modules/space/entities/subspace/subspace-product-allocation.entity';
import { SubspaceEntity } from '@app/common/modules/space/entities/subspace/subspace.entity';
import { SubspaceRepository } from '@app/common/modules/space/repositories/subspace.repository';
import { HttpException, HttpStatus, Injectable } from '@nestjs/common'; import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { DeviceService } from 'src/device/services'; import { DeviceService } from 'src/device/services';
import { CommunityRepository } from '@app/common/modules/community/repositories';
import { SpaceRepository } from '@app/common/modules/space';
import { SubspaceRepository } from '@app/common/modules/space/repositories/subspace.repository';
import { SubspaceEntity } from '@app/common/modules/space/entities/subspace/subspace.entity';
import { DeviceRepository } from '@app/common/modules/device/repositories';
import { SuccessResponseDto } from '@app/common/dto/success.response.dto';
import { ProjectParam } from '@app/common/dto/project-param.dto';
import { ProjectRepository } from '@app/common/modules/project/repositiories';
@Injectable() @Injectable()
export class DeviceCommissionService { export class DeviceCommissionService {
@ -118,7 +120,7 @@ export class DeviceCommissionService {
where: { uuid: spaceId }, where: { uuid: spaceId },
relations: [ relations: [
'productAllocations', 'productAllocations',
'productAllocations.tags', 'productAllocations.tag',
'productAllocations.product', 'productAllocations.product',
], ],
}); });
@ -135,7 +137,7 @@ export class DeviceCommissionService {
where: { uuid: subspaceId }, where: { uuid: subspaceId },
relations: [ relations: [
'productAllocations', 'productAllocations',
'productAllocations.tags', 'productAllocations.tag',
'productAllocations.product', 'productAllocations.product',
], ],
}); });
@ -151,19 +153,23 @@ export class DeviceCommissionService {
subspace?.productAllocations || space.productAllocations; subspace?.productAllocations || space.productAllocations;
const match = allocations const match = allocations
.flatMap((pa) => .map(
(pa.tags || []).map((tag) => ({ product: pa.product, tag })), ({
product,
tag,
}:
| SpaceProductAllocationEntity
| SubspaceProductAllocationEntity) => ({ product, tag }),
) )
.find(({ tag }) => tag.name === tagName); .find(
({ tag, product }) =>
tag.name === tagName && product.name === productName,
);
if (!match) { if (!match) {
console.error(`No matching tag found for Device ID: ${rawDeviceId}`); console.error(
failureCount.value++; `No matching tag-product combination found for Device ID: ${rawDeviceId}`,
return; );
}
if (match.product.name !== productName) {
console.error(`Product name mismatch for Device ID: ${rawDeviceId}`);
failureCount.value++; failureCount.value++;
return; return;
} }

View File

@ -8,7 +8,6 @@ import {
SpaceLinkRepository, SpaceLinkRepository,
SpaceProductAllocationRepository, SpaceProductAllocationRepository,
SpaceRepository, SpaceRepository,
TagRepository,
} from '@app/common/modules/space/repositories'; } from '@app/common/modules/space/repositories';
import { UserSpaceRepository } from '@app/common/modules/user/repositories'; import { UserSpaceRepository } from '@app/common/modules/user/repositories';
import { UserRepositoryModule } from '@app/common/modules/user/user.repository.module'; import { UserRepositoryModule } from '@app/common/modules/user/user.repository.module';
@ -64,6 +63,7 @@ import {
} from '@app/common/modules/power-clamp/repositories'; } from '@app/common/modules/power-clamp/repositories';
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';
@Module({ @Module({
imports: [ConfigModule, SpaceRepositoryModule, UserRepositoryModule], imports: [ConfigModule, SpaceRepositoryModule, UserRepositoryModule],
@ -86,6 +86,7 @@ import { OccupancyService } from '@app/common/helper/services/occupancy.service'
SpaceProductAllocationService, SpaceProductAllocationService,
SpaceLinkRepository, SpaceLinkRepository,
SubspaceRepository, SubspaceRepository,
// Todo: find out why this is needed
TagService, TagService,
SubspaceDeviceService, SubspaceDeviceService,
SubspaceProductAllocationService, SubspaceProductAllocationService,
@ -97,7 +98,6 @@ import { OccupancyService } from '@app/common/helper/services/occupancy.service'
SpaceModelProductAllocationService, SpaceModelProductAllocationService,
SpaceProductAllocationRepository, SpaceProductAllocationRepository,
SubspaceProductAllocationRepository, SubspaceProductAllocationRepository,
TagRepository,
SubspaceModelRepository, SubspaceModelRepository,
SubspaceModelProductAllocationService, SubspaceModelProductAllocationService,
SpaceModelProductAllocationRepoitory, SpaceModelProductAllocationRepoitory,
@ -116,6 +116,7 @@ import { OccupancyService } from '@app/common/helper/services/occupancy.service'
PowerClampMonthlyRepository, PowerClampMonthlyRepository,
SqlLoaderService, SqlLoaderService,
OccupancyService, OccupancyService,
AqiDataService,
], ],
exports: [CommunityService, SpacePermissionService], exports: [CommunityService, SpacePermissionService],
}) })

View File

@ -1,29 +1,30 @@
import { import { ORPHAN_COMMUNITY_NAME } from '@app/common/constants/orphan-constant';
Injectable,
HttpException,
HttpStatus,
NotFoundException,
} from '@nestjs/common';
import { AddCommunityDto, GetCommunityParams, ProjectParam } from '../dtos';
import { UpdateCommunityNameDto } from '../dtos/update.community.dto';
import { BaseResponseDto } from '@app/common/dto/base.response.dto'; import { BaseResponseDto } from '@app/common/dto/base.response.dto';
import { PageResponse } from '@app/common/dto/pagination.response.dto';
import { SuccessResponseDto } from '@app/common/dto/success.response.dto';
import { TuyaService } from '@app/common/integrations/tuya/services/tuya.service';
import { import {
ExtendedTypeORMCustomModelFindAllQuery, ExtendedTypeORMCustomModelFindAllQuery,
TypeORMCustomModel, TypeORMCustomModel,
} from '@app/common/models/typeOrmCustom.model'; } from '@app/common/models/typeOrmCustom.model';
import { PageResponse } from '@app/common/dto/pagination.response.dto';
import { CommunityRepository } from '@app/common/modules/community/repositories';
import { CommunityDto } from '@app/common/modules/community/dtos'; import { CommunityDto } from '@app/common/modules/community/dtos';
import { SuccessResponseDto } from '@app/common/dto/success.response.dto'; import { CommunityEntity } from '@app/common/modules/community/entities';
import { TuyaService } from '@app/common/integrations/tuya/services/tuya.service'; import { CommunityRepository } from '@app/common/modules/community/repositories';
import { ProjectRepository } from '@app/common/modules/project/repositiories';
import { ORPHAN_COMMUNITY_NAME } from '@app/common/constants/orphan-constant';
import { ILike, In, Not } from 'typeorm';
import { SpaceService } from 'src/space/services';
import { SpaceRepository } from '@app/common/modules/space';
import { DeviceEntity } from '@app/common/modules/device/entities'; import { DeviceEntity } from '@app/common/modules/device/entities';
import { ProjectRepository } from '@app/common/modules/project/repositiories';
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';
import { addSpaceUuidToDevices } from '@app/common/util/device-utils'; import { addSpaceUuidToDevices } from '@app/common/util/device-utils';
import {
HttpException,
HttpStatus,
Injectable,
NotFoundException,
} from '@nestjs/common';
import { SpaceService } from 'src/space/services';
import { SelectQueryBuilder } from 'typeorm';
import { AddCommunityDto, GetCommunityParams, ProjectParam } from '../dtos';
import { UpdateCommunityNameDto } from '../dtos/update.community.dto';
@Injectable() @Injectable()
export class CommunityService { export class CommunityService {
@ -93,56 +94,37 @@ export class CommunityService {
} }
async getCommunities( async getCommunities(
param: ProjectParam, { projectUuid }: ProjectParam,
pageable: Partial<ExtendedTypeORMCustomModelFindAllQuery>, pageable: Partial<ExtendedTypeORMCustomModelFindAllQuery>,
): Promise<BaseResponseDto> { ): Promise<BaseResponseDto> {
try { try {
const project = await this.validateProject(param.projectUuid); const project = await this.validateProject(projectUuid);
pageable.modelName = 'community'; /**
pageable.where = { * TODO: removing this breaks the code (should be fixed when refactoring @see TypeORMCustomModel
project: { uuid: param.projectUuid }, */
name: Not(`${ORPHAN_COMMUNITY_NAME}-${project.name}`), pageable.where = {};
}; let qb: undefined | SelectQueryBuilder<CommunityEntity> = undefined;
qb = this.communityRepository
.createQueryBuilder('c')
.leftJoin('c.spaces', 's', 's.disabled = false')
.where('c.project = :projectUuid', { projectUuid })
.andWhere(`c.name != '${ORPHAN_COMMUNITY_NAME}-${project.name}'`)
.orderBy('c.createdAt', 'DESC')
.distinct(true);
if (pageable.search) { if (pageable.search) {
const matchingCommunities = await this.communityRepository.find({ qb.andWhere(
where: { `c.name ILIKE '%${pageable.search}%' OR s.space_name ILIKE '%${pageable.search}%'`,
project: { uuid: param.projectUuid }, );
name: ILike(`%${pageable.search}%`),
},
});
const matchingSpaces = await this.spaceRepository.find({
where: {
spaceName: ILike(`%${pageable.search}%`),
disabled: false,
community: { project: { uuid: param.projectUuid } },
},
relations: ['community'],
});
const spaceCommunityUuids = [
...new Set(matchingSpaces.map((space) => space.community.uuid)),
];
const allMatchedCommunityUuids = [
...new Set([
...matchingCommunities.map((c) => c.uuid),
...spaceCommunityUuids,
]),
];
pageable.where = {
...pageable.where,
uuid: In(allMatchedCommunityUuids),
};
} }
const customModel = TypeORMCustomModel(this.communityRepository); const customModel = TypeORMCustomModel(this.communityRepository);
const { baseResponseDto, paginationResponseDto } = const { baseResponseDto, paginationResponseDto } =
await customModel.findAll(pageable); await customModel.findAll({ ...pageable, modelName: 'community' }, qb);
// todo: refactor this to minimize the number of queries
if (pageable.includeSpaces) { if (pageable.includeSpaces) {
const communitiesWithSpaces = await Promise.all( const communitiesWithSpaces = await Promise.all(
baseResponseDto.data.map(async (community: CommunityDto) => { baseResponseDto.data.map(async (community: CommunityDto) => {
@ -150,7 +132,7 @@ export class CommunityService {
await this.spaceService.getSpacesHierarchyForCommunity( await this.spaceService.getSpacesHierarchyForCommunity(
{ {
communityUuid: community.uuid, communityUuid: community.uuid,
projectUuid: param.projectUuid, projectUuid: projectUuid,
}, },
{ {
onlyWithDevices: false, onlyWithDevices: false,

View File

@ -1,39 +1,46 @@
import { ORPHAN_SPACE_NAME } from './../../../libs/common/src/constants/orphan-constant'; import { AUTOMATION_CONFIG } from '@app/common/constants/automation.enum';
import { ProductRepository } from './../../../libs/common/src/modules/product/repositories/product.repository'; import { BatchDeviceTypeEnum } from '@app/common/constants/batch-device.enum';
import { BatteryStatus } from '@app/common/constants/battery-status.enum';
import { DeviceStatuses } from '@app/common/constants/device-status.enum';
import { DeviceTypeEnum } from '@app/common/constants/device-type.enum';
import { CommonErrorCodes } from '@app/common/constants/error-codes.enum';
import { ProductType } from '@app/common/constants/product-type.enum';
import { SceneSwitchesTypeEnum } from '@app/common/constants/scene-switch-type.enum';
import { BaseResponseDto } from '@app/common/dto/base.response.dto';
import { SuccessResponseDto } from '@app/common/dto/success.response.dto';
import { DeviceStatusFirebaseService } from '@app/common/firebase/devices-status/services/devices-status.service';
import { convertKeysToCamelCase } from '@app/common/helper/camelCaseConverter';
import { TuyaService } from '@app/common/integrations/tuya/services/tuya.service';
import { CommunityRepository } from '@app/common/modules/community/repositories';
import { DeviceEntity } from '@app/common/modules/device/entities';
import { DeviceRepository } from '@app/common/modules/device/repositories';
import { ProjectEntity } from '@app/common/modules/project/entities';
import { ProjectRepository } from '@app/common/modules/project/repositiories';
import { SceneDeviceRepository } from '@app/common/modules/scene-device/repositories';
import { SpaceEntity } from '@app/common/modules/space/entities/space.entity';
import { SpaceRepository } from '@app/common/modules/space/repositories';
import { addSpaceUuidToDevices } from '@app/common/util/device-utils';
import { import {
Injectable,
HttpException,
HttpStatus,
NotFoundException,
BadRequestException, BadRequestException,
forwardRef, forwardRef,
HttpException,
HttpStatus,
Inject, Inject,
Injectable,
NotFoundException,
} from '@nestjs/common'; } from '@nestjs/common';
import { TuyaContext } from '@tuya/tuya-connector-nodejs';
import { ConfigService } from '@nestjs/config'; import { ConfigService } from '@nestjs/config';
import { TuyaContext } from '@tuya/tuya-connector-nodejs';
import { AddAutomationDto } from 'src/automation/dtos';
import { SceneService } from 'src/scene/services';
import { In, Not, QueryRunner } from 'typeorm';
import { ProjectParam } from '../dtos';
import { import {
AddDeviceDto, AddDeviceDto,
AddSceneToFourSceneDeviceDto, AddSceneToFourSceneDeviceDto,
UpdateDeviceDto,
AssignDeviceToSpaceDto, AssignDeviceToSpaceDto,
UpdateDeviceDto,
} from '../dtos/add.device.dto'; } from '../dtos/add.device.dto';
import {
DeviceInstructionResponse,
GetDeviceDetailsFunctionsInterface,
GetDeviceDetailsFunctionsStatusInterface,
GetDeviceDetailsInterface,
GetMacAddressInterface,
GetPowerClampFunctionsStatusInterface,
controlDeviceInterface,
getDeviceLogsInterface,
updateDeviceFirmwareInterface,
} from '../interfaces/get.device.interface';
import {
GetDeviceBySpaceUuidDto,
GetDeviceLogsDto,
GetDevicesBySpaceOrCommunityDto,
GetDoorLockDevices,
} from '../dtos/get.device.dto';
import { import {
BatchControlDevicesDto, BatchControlDevicesDto,
BatchFactoryResetDevicesDto, BatchFactoryResetDevicesDto,
@ -41,33 +48,29 @@ import {
ControlDeviceDto, ControlDeviceDto,
GetSceneFourSceneDeviceDto, GetSceneFourSceneDeviceDto,
} from '../dtos/control.device.dto'; } from '../dtos/control.device.dto';
import { convertKeysToCamelCase } from '@app/common/helper/camelCaseConverter';
import { DeviceRepository } from '@app/common/modules/device/repositories';
import { In, Not, QueryRunner } from 'typeorm';
import { ProductType } from '@app/common/constants/product-type.enum';
import { SpaceRepository } from '@app/common/modules/space/repositories';
import { DeviceStatusFirebaseService } from '@app/common/firebase/devices-status/services/devices-status.service';
import { DeviceStatuses } from '@app/common/constants/device-status.enum';
import { CommonErrorCodes } from '@app/common/constants/error-codes.enum';
import { BatteryStatus } from '@app/common/constants/battery-status.enum';
import { SceneService } from 'src/scene/services';
import { AddAutomationDto } from 'src/automation/dtos';
import { TuyaService } from '@app/common/integrations/tuya/services/tuya.service';
import { SceneDeviceRepository } from '@app/common/modules/scene-device/repositories';
import { SceneSwitchesTypeEnum } from '@app/common/constants/scene-switch-type.enum';
import { AUTOMATION_CONFIG } from '@app/common/constants/automation.enum';
import { DeviceSceneParamDto } from '../dtos/device.param.dto';
import { BaseResponseDto } from '@app/common/dto/base.response.dto';
import { SuccessResponseDto } from '@app/common/dto/success.response.dto';
import { DeleteSceneFromSceneDeviceDto } from '../dtos/delete.device.dto'; import { DeleteSceneFromSceneDeviceDto } from '../dtos/delete.device.dto';
import { DeviceEntity } from '@app/common/modules/device/entities'; import { DeviceSceneParamDto } from '../dtos/device.param.dto';
import { SpaceEntity } from '@app/common/modules/space/entities/space.entity'; import {
import { ProjectRepository } from '@app/common/modules/project/repositiories'; GetDeviceLogsDto,
import { ProjectParam } from '../dtos'; GetDevicesBySpaceOrCommunityDto,
import { BatchDeviceTypeEnum } from '@app/common/constants/batch-device.enum'; GetDoorLockDevices,
import { DeviceTypeEnum } from '@app/common/constants/device-type.enum'; } from '../dtos/get.device.dto';
import { CommunityRepository } from '@app/common/modules/community/repositories'; import {
import { addSpaceUuidToDevices } from '@app/common/util/device-utils'; controlDeviceInterface,
DeviceInstructionResponse,
GetDeviceDetailsFunctionsInterface,
GetDeviceDetailsFunctionsStatusInterface,
GetDeviceDetailsInterface,
getDeviceLogsInterface,
GetMacAddressInterface,
GetPowerClampFunctionsStatusInterface,
updateDeviceFirmwareInterface,
} from '../interfaces/get.device.interface';
import {
ORPHAN_COMMUNITY_NAME,
ORPHAN_SPACE_NAME,
} from './../../../libs/common/src/constants/orphan-constant';
import { ProductRepository } from './../../../libs/common/src/modules/product/repositories/product.repository';
@Injectable() @Injectable()
export class DeviceService { export class DeviceService {
@ -198,46 +201,6 @@ export class DeviceService {
} }
} }
async getDevicesBySpaceId(
getDeviceBySpaceUuidDto: GetDeviceBySpaceUuidDto,
): Promise<GetDeviceDetailsInterface[]> {
try {
const devices = await this.deviceRepository.find({
where: {
spaceDevice: { uuid: getDeviceBySpaceUuidDto.spaceUuid },
isActive: true,
},
relations: [
'spaceDevice',
'productDevice',
'permission',
'permission.permissionType',
],
});
const devicesData = await Promise.all(
devices.map(async (device) => {
return {
haveRoom: device.spaceDevice ? true : false,
productUuid: device.productDevice.uuid,
productType: device.productDevice.prodType,
permissionType: device.permission[0].permissionType.type,
...(await this.getDeviceDetailsByDeviceIdTuya(
device.deviceTuyaUuid,
)),
uuid: device.uuid,
} as GetDeviceDetailsInterface;
}),
);
return devicesData;
} catch (error) {
// Handle the error here
throw new HttpException(
'Error fetching devices by space',
HttpStatus.INTERNAL_SERVER_ERROR,
);
}
}
async transferDeviceInSpaces( async transferDeviceInSpaces(
assignDeviceToSpaceDto: AssignDeviceToSpaceDto, assignDeviceToSpaceDto: AssignDeviceToSpaceDto,
projectUuid: string, projectUuid: string,
@ -1199,39 +1162,6 @@ export class DeviceService {
} }
} }
async getFullSpaceHierarchy(
space: SpaceEntity,
): Promise<{ uuid: string; spaceName: string }[]> {
try {
// Fetch only the relevant spaces, starting with the target space
const targetSpace = await this.spaceRepository.findOne({
where: { uuid: space.uuid },
relations: ['parent', 'children'],
});
// Fetch only the ancestors of the target space
const ancestors = await this.fetchAncestors(targetSpace);
// Optionally, fetch descendants if required
const descendants = await this.fetchDescendants(targetSpace);
const fullHierarchy = [...ancestors, targetSpace, ...descendants].map(
(space) => ({
uuid: space.uuid,
spaceName: space.spaceName,
}),
);
return fullHierarchy;
} catch (error) {
console.error('Error fetching space hierarchy:', error.message);
throw new HttpException(
'Error fetching space hierarchy',
HttpStatus.INTERNAL_SERVER_ERROR,
);
}
}
async getPowerClampInstructionStatus(deviceDetails: any) { async getPowerClampInstructionStatus(deviceDetails: any) {
try { try {
const deviceStatus = await this.getPowerClampInstructionStatusTuya( const deviceStatus = await this.getPowerClampInstructionStatusTuya(
@ -1331,27 +1261,6 @@ export class DeviceService {
return ancestors.reverse(); return ancestors.reverse();
} }
private async fetchDescendants(space: SpaceEntity): Promise<SpaceEntity[]> {
const descendants: SpaceEntity[] = [];
// Fetch the immediate children of the current space
const children = await this.spaceRepository.find({
where: { parent: { uuid: space.uuid } },
relations: ['children'], // To continue fetching downwards
});
for (const child of children) {
// Add the child to the descendants list
descendants.push(child);
// Recursively fetch the child's descendants
const childDescendants = await this.fetchDescendants(child);
descendants.push(...childDescendants);
}
return descendants;
}
async addSceneToSceneDevice( async addSceneToSceneDevice(
deviceUuid: string, deviceUuid: string,
addSceneToFourSceneDeviceDto: AddSceneToFourSceneDeviceDto, addSceneToFourSceneDeviceDto: AddSceneToFourSceneDeviceDto,
@ -1654,22 +1563,6 @@ export class DeviceService {
} }
} }
async moveDevicesToSpace(
targetSpace: SpaceEntity,
deviceIds: string[],
): Promise<void> {
if (!deviceIds || deviceIds.length === 0) {
throw new HttpException(
'No device IDs provided for transfer',
HttpStatus.BAD_REQUEST,
);
}
await this.deviceRepository.update(
{ uuid: In(deviceIds) },
{ spaceDevice: targetSpace },
);
}
async getDoorLockDevices(projectUuid: string) { async getDoorLockDevices(projectUuid: string) {
await this.validateProject(projectUuid); await this.validateProject(projectUuid);
@ -1860,4 +1753,39 @@ export class DeviceService {
return allDevices; return allDevices;
} }
async addDevicesToOrphanSpace(
space: SpaceEntity,
project: ProjectEntity,
queryRunner: QueryRunner,
) {
const spaceRepository = queryRunner.manager.getRepository(SpaceEntity);
const deviceRepository = queryRunner.manager.getRepository(DeviceEntity);
try {
const orphanSpace = await spaceRepository.findOne({
where: {
community: {
name: `${ORPHAN_COMMUNITY_NAME}-${project.name}`,
},
spaceName: ORPHAN_SPACE_NAME,
},
});
if (!orphanSpace) {
throw new HttpException(
`Orphan space not found in community ${project.name}`,
HttpStatus.NOT_FOUND,
);
}
await deviceRepository.update(
{ uuid: In(space.devices.map((device) => device.uuid)) },
{ spaceDevice: orphanSpace },
);
} catch (error) {
throw new Error(
`Failed to add devices to orphan spaces: ${error.message}`,
);
}
}
} }

View File

@ -29,6 +29,7 @@ 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 { 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';
@Module({ @Module({
imports: [ConfigModule, DeviceRepositoryModule], imports: [ConfigModule, DeviceRepositoryModule],
controllers: [DoorLockController], controllers: [DoorLockController],
@ -56,6 +57,7 @@ import { CommunityRepository } from '@app/common/modules/community/repositories'
SqlLoaderService, SqlLoaderService,
OccupancyService, OccupancyService,
CommunityRepository, CommunityRepository,
AqiDataService,
], ],
exports: [DoorLockService], exports: [DoorLockService],
}) })

View File

@ -27,6 +27,7 @@ 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 { 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';
@Module({ @Module({
imports: [ConfigModule, DeviceRepositoryModule], imports: [ConfigModule, DeviceRepositoryModule],
controllers: [GroupController], controllers: [GroupController],
@ -53,6 +54,7 @@ import { CommunityRepository } from '@app/common/modules/community/repositories'
SqlLoaderService, SqlLoaderService,
OccupancyService, OccupancyService,
CommunityRepository, CommunityRepository,
AqiDataService,
], ],
exports: [GroupService], exports: [GroupService],
}) })

View File

@ -1,18 +1,75 @@
import { Module } from '@nestjs/common'; import { Module } from '@nestjs/common';
import { InviteUserService } from './services/invite-user.service';
import { InviteUserController } from './controllers/invite-user.controller';
import { ConfigModule } from '@nestjs/config'; import { ConfigModule } from '@nestjs/config';
import { InviteUserController } from './controllers/invite-user.controller';
import { InviteUserService } from './services/invite-user.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 { PowerClampService } from '@app/common/helper/services/power.clamp.service';
import { SqlLoaderService } from '@app/common/helper/services/sql-loader.service';
import { TuyaService } from '@app/common/integrations/tuya/services/tuya.service';
import { AutomationRepository } from '@app/common/modules/automation/repositories';
import { CommunityRepository } from '@app/common/modules/community/repositories';
import { DeviceStatusLogRepository } from '@app/common/modules/device-status-log/repositories';
import { import {
UserRepository, DeviceRepository,
UserSpaceRepository, DeviceUserPermissionRepository,
} from '@app/common/modules/user/repositories'; } from '@app/common/modules/device/repositories';
import { InviteUserRepositoryModule } from '@app/common/modules/Invite-user/Invite-user.repository.module'; import { InviteUserRepositoryModule } from '@app/common/modules/Invite-user/Invite-user.repository.module';
import { import {
InviteUserRepository, InviteUserRepository,
InviteUserSpaceRepository, InviteUserSpaceRepository,
} from '@app/common/modules/Invite-user/repositiories'; } from '@app/common/modules/Invite-user/repositiories';
import { PermissionTypeRepository } from '@app/common/modules/permission/repositories';
import {
PowerClampDailyRepository,
PowerClampHourlyRepository,
PowerClampMonthlyRepository,
} from '@app/common/modules/power-clamp/repositories';
import { ProductRepository } from '@app/common/modules/product/repositories';
import { ProjectRepository } from '@app/common/modules/project/repositiories';
import { RegionRepository } from '@app/common/modules/region/repositories';
import { RoleTypeRepository } from '@app/common/modules/role-type/repositories';
import { SceneDeviceRepository } from '@app/common/modules/scene-device/repositories';
import {
SceneIconRepository,
SceneRepository,
} from '@app/common/modules/scene/repositories';
import {
InviteSpaceRepository,
SpaceLinkRepository,
SpaceProductAllocationRepository,
SpaceRepository,
} from '@app/common/modules/space';
import {
SpaceModelProductAllocationRepoitory,
SpaceModelRepository,
SubspaceModelProductAllocationRepoitory,
SubspaceModelRepository,
} from '@app/common/modules/space-model';
import {
SubspaceProductAllocationRepository,
SubspaceRepository,
} from '@app/common/modules/space/repositories/subspace.repository';
import { NewTagRepository } from '@app/common/modules/tag/repositories/tag-repository';
import { TimeZoneRepository } from '@app/common/modules/timezone/repositories';
import {
UserRepository,
UserSpaceRepository,
} from '@app/common/modules/user/repositories';
import { EmailService } from '@app/common/util/email.service'; import { EmailService } from '@app/common/util/email.service';
import { CommunityModule } from 'src/community/community.module';
import { CommunityService } from 'src/community/services';
import { DeviceService } from 'src/device/services';
import { ProjectUserService } from 'src/project/services/project-user.service';
import { SceneService } from 'src/scene/services';
import {
SpaceModelService,
SubSpaceModelService,
} from 'src/space-model/services';
import { SpaceModelProductAllocationService } from 'src/space-model/services/space-model-product-allocation.service';
import { SubspaceModelProductAllocationService } from 'src/space-model/services/subspace/subspace-model-product-allocation.service';
import { import {
SpaceLinkService, SpaceLinkService,
SpaceService, SpaceService,
@ -21,69 +78,11 @@ import {
SubSpaceService, SubSpaceService,
ValidationService, ValidationService,
} from 'src/space/services'; } from 'src/space/services';
import { CommunityService } from 'src/community/services';
import {
InviteSpaceRepository,
SpaceLinkRepository,
SpaceProductAllocationRepository,
SpaceRepository,
TagRepository,
} from '@app/common/modules/space';
import { SpaceModelRepository } from '@app/common/modules/space-model';
import { CommunityRepository } from '@app/common/modules/community/repositories';
import { ProjectRepository } from '@app/common/modules/project/repositiories';
import { TuyaService } from '@app/common/integrations/tuya/services/tuya.service';
import { UserService, UserSpaceService } from 'src/users/services';
import { UserDevicePermissionService } from 'src/user-device-permission/services';
import {
DeviceRepository,
DeviceUserPermissionRepository,
} from '@app/common/modules/device/repositories';
import { PermissionTypeRepository } from '@app/common/modules/permission/repositories';
import { ProjectUserService } from 'src/project/services/project-user.service';
import { RoleTypeRepository } from '@app/common/modules/role-type/repositories';
import { RegionRepository } from '@app/common/modules/region/repositories';
import { TimeZoneRepository } from '@app/common/modules/timezone/repositories';
import { CommunityModule } from 'src/community/community.module';
import { TagService as NewTagService } from 'src/tags/services';
import { TagService } from 'src/space/services/tag';
import {
SpaceModelService,
SubSpaceModelService,
} from 'src/space-model/services';
import { SpaceProductAllocationService } from 'src/space/services/space-product-allocation.service'; import { SpaceProductAllocationService } from 'src/space/services/space-product-allocation.service';
import {
SubspaceProductAllocationRepository,
SubspaceRepository,
} from '@app/common/modules/space/repositories/subspace.repository';
import { SubspaceProductAllocationService } from 'src/space/services/subspace/subspace-product-allocation.service'; import { SubspaceProductAllocationService } from 'src/space/services/subspace/subspace-product-allocation.service';
import { import { TagService as NewTagService } from 'src/tags/services';
SpaceModelProductAllocationRepoitory, import { UserDevicePermissionService } from 'src/user-device-permission/services';
SubspaceModelProductAllocationRepoitory, import { UserService, UserSpaceService } from 'src/users/services';
SubspaceModelRepository,
} from '@app/common/modules/space-model';
import { NewTagRepository } from '@app/common/modules/tag/repositories/tag-repository';
import { ProductRepository } from '@app/common/modules/product/repositories';
import { SpaceModelProductAllocationService } from 'src/space-model/services/space-model-product-allocation.service';
import { SubspaceModelProductAllocationService } from 'src/space-model/services/subspace/subspace-model-product-allocation.service';
import { DeviceService } from 'src/device/services';
import { SceneDeviceRepository } from '@app/common/modules/scene-device/repositories';
import { DeviceStatusFirebaseService } from '@app/common/firebase/devices-status/services/devices-status.service';
import { SceneService } from 'src/scene/services';
import { DeviceStatusLogRepository } from '@app/common/modules/device-status-log/repositories';
import {
SceneIconRepository,
SceneRepository,
} from '@app/common/modules/scene/repositories';
import { AutomationRepository } from '@app/common/modules/automation/repositories';
import {
PowerClampHourlyRepository,
PowerClampDailyRepository,
PowerClampMonthlyRepository,
} from '@app/common/modules/power-clamp/repositories';
import { PowerClampService } from '@app/common/helper/services/power.clamp.service';
import { SqlLoaderService } from '@app/common/helper/services/sql-loader.service';
import { OccupancyService } from '@app/common/helper/services/occupancy.service';
@Module({ @Module({
imports: [ConfigModule, InviteUserRepositoryModule, CommunityModule], imports: [ConfigModule, InviteUserRepositoryModule, CommunityModule],
@ -124,7 +123,6 @@ import { OccupancyService } from '@app/common/helper/services/occupancy.service'
SpaceProductAllocationService, SpaceProductAllocationService,
SpaceLinkRepository, SpaceLinkRepository,
SubspaceRepository, SubspaceRepository,
TagService,
SubspaceDeviceService, SubspaceDeviceService,
SubspaceProductAllocationService, SubspaceProductAllocationService,
SpaceModelRepository, SpaceModelRepository,
@ -135,7 +133,6 @@ import { OccupancyService } from '@app/common/helper/services/occupancy.service'
SpaceModelProductAllocationService, SpaceModelProductAllocationService,
SpaceProductAllocationRepository, SpaceProductAllocationRepository,
SubspaceProductAllocationRepository, SubspaceProductAllocationRepository,
TagRepository,
SubspaceModelRepository, SubspaceModelRepository,
SubspaceModelProductAllocationService, SubspaceModelProductAllocationService,
SpaceModelProductAllocationRepoitory, SpaceModelProductAllocationRepoitory,
@ -154,6 +151,7 @@ import { OccupancyService } from '@app/common/helper/services/occupancy.service'
PowerClampMonthlyRepository, PowerClampMonthlyRepository,
SqlLoaderService, SqlLoaderService,
OccupancyService, OccupancyService,
AqiDataService,
], ],
exports: [InviteUserService], exports: [InviteUserService],
}) })

View File

@ -1,36 +1,42 @@
import { import { RoleType } from '@app/common/constants/role.type.enum';
Injectable,
HttpException,
HttpStatus,
BadRequestException,
} from '@nestjs/common';
import { AddUserInvitationDto } from '../dtos';
import { BaseResponseDto } from '@app/common/dto/base.response.dto';
import { UserStatusEnum } from '@app/common/constants/user-status.enum'; import { UserStatusEnum } from '@app/common/constants/user-status.enum';
import { BaseResponseDto } from '@app/common/dto/base.response.dto';
import { SuccessResponseDto } from '@app/common/dto/success.response.dto'; import { SuccessResponseDto } from '@app/common/dto/success.response.dto';
import { generateRandomString } from '@app/common/helper/randomString'; import { generateRandomString } from '@app/common/helper/randomString';
import { EntityManager, In, IsNull, Not, QueryRunner } from 'typeorm'; import { InviteUserEntity } from '@app/common/modules/Invite-user/entities';
import { DataSource } from 'typeorm';
import { UserEntity } from '@app/common/modules/user/entities';
import { RoleType } from '@app/common/constants/role.type.enum';
import { import {
InviteUserRepository, InviteUserRepository,
InviteUserSpaceRepository, InviteUserSpaceRepository,
} from '@app/common/modules/Invite-user/repositiories'; } from '@app/common/modules/Invite-user/repositiories';
import { CheckEmailDto } from '../dtos/check-email.dto'; import { RoleTypeRepository } from '@app/common/modules/role-type/repositories';
import { SpaceRepository } from '@app/common/modules/space';
import { SpaceEntity } from '@app/common/modules/space/entities/space.entity';
import { UserEntity } from '@app/common/modules/user/entities';
import { UserRepository } from '@app/common/modules/user/repositories'; import { UserRepository } from '@app/common/modules/user/repositories';
import { EmailService } from '@app/common/util/email.service'; import { EmailService } from '@app/common/util/email.service';
import { SpaceRepository } from '@app/common/modules/space'; import {
import { ActivateCodeDto } from '../dtos/active-code.dto'; BadRequestException,
import { UserSpaceService } from 'src/users/services'; HttpException,
HttpStatus,
Injectable,
} from '@nestjs/common';
import { SpaceUserService } from 'src/space/services'; import { SpaceUserService } from 'src/space/services';
import { UserSpaceService } from 'src/users/services';
import {
DataSource,
EntityManager,
In,
IsNull,
Not,
QueryRunner,
} from 'typeorm';
import { AddUserInvitationDto } from '../dtos';
import { ActivateCodeDto } from '../dtos/active-code.dto';
import { CheckEmailDto } from '../dtos/check-email.dto';
import { import {
DisableUserInvitationDto, DisableUserInvitationDto,
UpdateUserInvitationDto, UpdateUserInvitationDto,
} from '../dtos/update.invite-user.dto'; } from '../dtos/update.invite-user.dto';
import { RoleTypeRepository } from '@app/common/modules/role-type/repositories';
import { InviteUserEntity } from '@app/common/modules/Invite-user/entities';
import { SpaceEntity } from '@app/common/modules/space/entities/space.entity';
@Injectable() @Injectable()
export class InviteUserService { export class InviteUserService {
@ -658,12 +664,12 @@ export class InviteUserService {
HttpStatus.BAD_REQUEST, HttpStatus.BAD_REQUEST,
); );
} }
await this.emailService.sendEmailWithTemplate( await this.emailService.sendEmailWithTemplate({
userData.email, email: userData.email,
userData.firstName, name: userData.firstName,
disable, isEnable: !disable,
false, isDelete: false,
); });
await queryRunner.commitTransaction(); await queryRunner.commitTransaction();
return new SuccessResponseDto({ return new SuccessResponseDto({
@ -797,12 +803,12 @@ export class InviteUserService {
{ isActive: false }, { isActive: false },
); );
} }
await this.emailService.sendEmailWithTemplate( await this.emailService.sendEmailWithTemplate({
userData.email, email: userData.email,
userData.firstName, name: userData.firstName,
false, isEnable: false,
true, isDelete: true,
); });
await queryRunner.commitTransaction(); await queryRunner.commitTransaction();
return new SuccessResponseDto({ return new SuccessResponseDto({

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

View File

@ -1,13 +1,52 @@
import { Module } from '@nestjs/common'; import { DeviceStatusFirebaseService } from '@app/common/firebase/devices-status/services/devices-status.service';
import { ConfigModule } from '@nestjs/config'; import { OccupancyService } from '@app/common/helper/services/occupancy.service';
import { PowerClampService as PowerClamp } from './services/power-clamp.service'; import { PowerClampService } from '@app/common/helper/services/power.clamp.service';
import { PowerClampController } from './controllers'; import { SqlLoaderService } from '@app/common/helper/services/sql-loader.service';
import { TuyaService } from '@app/common/integrations/tuya/services/tuya.service';
import { AutomationRepository } from '@app/common/modules/automation/repositories';
import { CommunityRepository } from '@app/common/modules/community/repositories';
import { DeviceStatusLogRepository } from '@app/common/modules/device-status-log/repositories';
import { DeviceRepository } from '@app/common/modules/device/repositories';
import { import {
PowerClampDailyRepository, PowerClampDailyRepository,
PowerClampHourlyRepository, PowerClampHourlyRepository,
PowerClampMonthlyRepository, PowerClampMonthlyRepository,
} from '@app/common/modules/power-clamp/repositories'; } from '@app/common/modules/power-clamp/repositories';
import { DeviceRepository } from '@app/common/modules/device/repositories'; import { ProductRepository } from '@app/common/modules/product/repositories';
import { ProjectRepository } from '@app/common/modules/project/repositiories';
import { SceneDeviceRepository } from '@app/common/modules/scene-device/repositories';
import {
SceneIconRepository,
SceneRepository,
} from '@app/common/modules/scene/repositories';
import {
InviteSpaceRepository,
SpaceLinkRepository,
SpaceProductAllocationRepository,
SpaceRepository,
} from '@app/common/modules/space';
import {
SpaceModelProductAllocationRepoitory,
SpaceModelRepository,
SubspaceModelProductAllocationRepoitory,
SubspaceModelRepository,
} from '@app/common/modules/space-model';
import {
SubspaceProductAllocationRepository,
SubspaceRepository,
} from '@app/common/modules/space/repositories/subspace.repository';
import { NewTagRepository } from '@app/common/modules/tag/repositories/tag-repository';
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { CommunityService } from 'src/community/services';
import { DeviceService } from 'src/device/services';
import { SceneService } from 'src/scene/services';
import {
SpaceModelService,
SubSpaceModelService,
} from 'src/space-model/services';
import { SpaceModelProductAllocationService } from 'src/space-model/services/space-model-product-allocation.service';
import { SubspaceModelProductAllocationService } from 'src/space-model/services/subspace/subspace-model-product-allocation.service';
import { import {
SpaceDeviceService, SpaceDeviceService,
SpaceLinkService, SpaceLinkService,
@ -16,51 +55,12 @@ import {
SubSpaceService, SubSpaceService,
ValidationService, ValidationService,
} from 'src/space/services'; } from 'src/space/services';
import { TuyaService } from '@app/common/integrations/tuya/services/tuya.service';
import { DeviceService } from 'src/device/services';
import {
InviteSpaceRepository,
SpaceLinkRepository,
SpaceProductAllocationRepository,
SpaceRepository,
TagRepository,
} from '@app/common/modules/space';
import { CommunityService } from 'src/community/services';
import { ProjectRepository } from '@app/common/modules/project/repositiories';
import { CommunityRepository } from '@app/common/modules/community/repositories';
import {
SpaceModelProductAllocationRepoitory,
SpaceModelRepository,
SubspaceModelProductAllocationRepoitory,
SubspaceModelRepository,
} from '@app/common/modules/space-model';
import { SceneDeviceRepository } from '@app/common/modules/scene-device/repositories';
import { ProductRepository } from '@app/common/modules/product/repositories';
import { DeviceStatusFirebaseService } from '@app/common/firebase/devices-status/services/devices-status.service';
import { SceneService } from 'src/scene/services';
import { PowerClampService } from '@app/common/helper/services/power.clamp.service';
import { DeviceStatusLogRepository } from '@app/common/modules/device-status-log/repositories';
import {
SceneIconRepository,
SceneRepository,
} from '@app/common/modules/scene/repositories';
import { AutomationRepository } from '@app/common/modules/automation/repositories';
import { TagService } from 'src/tags/services';
import {
SpaceModelService,
SubSpaceModelService,
} from 'src/space-model/services';
import { SpaceProductAllocationService } from 'src/space/services/space-product-allocation.service'; import { SpaceProductAllocationService } from 'src/space/services/space-product-allocation.service';
import { SqlLoaderService } from '@app/common/helper/services/sql-loader.service';
import {
SubspaceProductAllocationRepository,
SubspaceRepository,
} from '@app/common/modules/space/repositories/subspace.repository';
import { SubspaceProductAllocationService } from 'src/space/services/subspace/subspace-product-allocation.service'; import { SubspaceProductAllocationService } from 'src/space/services/subspace/subspace-product-allocation.service';
import { NewTagRepository } from '@app/common/modules/tag/repositories/tag-repository'; import { TagService } from 'src/tags/services';
import { SpaceModelProductAllocationService } from 'src/space-model/services/space-model-product-allocation.service'; import { PowerClampController } from './controllers';
import { SubspaceModelProductAllocationService } from 'src/space-model/services/subspace/subspace-model-product-allocation.service'; import { PowerClampService as PowerClamp } from './services/power-clamp.service';
import { OccupancyService } from '@app/common/helper/services/occupancy.service'; import { AqiDataService } from '@app/common/helper/services/aqi.data.service';
@Module({ @Module({
imports: [ConfigModule], imports: [ConfigModule],
controllers: [PowerClampController], controllers: [PowerClampController],
@ -105,12 +105,12 @@ import { OccupancyService } from '@app/common/helper/services/occupancy.service'
SpaceModelProductAllocationService, SpaceModelProductAllocationService,
SpaceProductAllocationRepository, SpaceProductAllocationRepository,
SubspaceProductAllocationRepository, SubspaceProductAllocationRepository,
TagRepository,
SubspaceModelRepository, SubspaceModelRepository,
SubspaceModelProductAllocationService, SubspaceModelProductAllocationService,
SpaceModelProductAllocationRepoitory, SpaceModelProductAllocationRepoitory,
SubspaceModelProductAllocationRepoitory, SubspaceModelProductAllocationRepoitory,
OccupancyService, OccupancyService,
AqiDataService,
], ],
exports: [PowerClamp], exports: [PowerClamp],
}) })

View File

@ -23,10 +23,10 @@ import { SpaceDeviceService } from 'src/space/services';
import { SqlLoaderService } from '@app/common/helper/services/sql-loader.service'; import { SqlLoaderService } from '@app/common/helper/services/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 { filterByMonth, toMMYYYY } from '@app/common/helper/date-format';
import { ProductType } from '@app/common/constants/product-type.enum'; import { ProductType } from '@app/common/constants/product-type.enum';
import { CommunityService } from 'src/community/services'; import { CommunityService } from 'src/community/services';
import { BaseResponseDto } from '@app/common/dto/base.response.dto'; import { BaseResponseDto } from '@app/common/dto/base.response.dto';
import { filterByMonth, toMMYYYY } from '@app/common/helper/date-format';
@Injectable() @Injectable()
export class PowerClampService { export class PowerClampService {

View File

@ -1,24 +1,58 @@
import { Global, Module } from '@nestjs/common'; import { DeviceStatusFirebaseService } from '@app/common/firebase/devices-status/services/devices-status.service';
import { CqrsModule } from '@nestjs/cqrs'; import { AqiDataService } from '@app/common/helper/services/aqi.data.service';
import { ProjectController } from './controllers'; import { OccupancyService } from '@app/common/helper/services/occupancy.service';
import { ProjectService } from './services'; import { PowerClampService } from '@app/common/helper/services/power.clamp.service';
import { SqlLoaderService } from '@app/common/helper/services/sql-loader.service';
import { TuyaService } from '@app/common/integrations/tuya/services/tuya.service';
import { AutomationRepository } from '@app/common/modules/automation/repositories';
import { CommunityRepository } from '@app/common/modules/community/repositories';
import { DeviceStatusLogRepository } from '@app/common/modules/device-status-log/repositories';
import { DeviceRepository } from '@app/common/modules/device/repositories';
import { InviteUserRepository } from '@app/common/modules/Invite-user/repositiories';
import {
PowerClampDailyRepository,
PowerClampHourlyRepository,
PowerClampMonthlyRepository,
} from '@app/common/modules/power-clamp/repositories';
import { ProductRepository } from '@app/common/modules/product/repositories';
import { ProjectRepository } from '@app/common/modules/project/repositiories'; import { ProjectRepository } from '@app/common/modules/project/repositiories';
import { CreateOrphanSpaceHandler } from './handler'; import { SceneDeviceRepository } from '@app/common/modules/scene-device/repositories';
import {
SceneIconRepository,
SceneRepository,
} from '@app/common/modules/scene/repositories';
import { import {
InviteSpaceRepository, InviteSpaceRepository,
SpaceLinkRepository, SpaceLinkRepository,
SpaceProductAllocationRepository, SpaceProductAllocationRepository,
SpaceRepository, SpaceRepository,
TagRepository,
} from '@app/common/modules/space'; } from '@app/common/modules/space';
import { CommunityRepository } from '@app/common/modules/community/repositories'; import {
import { InviteUserRepository } from '@app/common/modules/Invite-user/repositiories'; SpaceModelProductAllocationRepoitory,
import { ProjectUserController } from './controllers/project-user.controller'; SpaceModelRepository,
import { ProjectUserService } from './services/project-user.service'; SubspaceModelProductAllocationRepoitory,
SubspaceModelRepository,
} from '@app/common/modules/space-model';
import {
SubspaceProductAllocationRepository,
SubspaceRepository,
} from '@app/common/modules/space/repositories/subspace.repository';
import { NewTagRepository } from '@app/common/modules/tag/repositories/tag-repository';
import { import {
UserRepository, UserRepository,
UserSpaceRepository, UserSpaceRepository,
} from '@app/common/modules/user/repositories'; } from '@app/common/modules/user/repositories';
import { Global, Module } from '@nestjs/common';
import { CqrsModule } from '@nestjs/cqrs';
import { CommunityService } from 'src/community/services';
import { DeviceService } from 'src/device/services';
import { SceneService } from 'src/scene/services';
import {
SpaceModelService,
SubSpaceModelService,
} from 'src/space-model/services';
import { 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 { import {
SpaceLinkService, SpaceLinkService,
SpaceService, SpaceService,
@ -26,48 +60,14 @@ import {
SubSpaceService, SubSpaceService,
ValidationService, ValidationService,
} from 'src/space/services'; } from 'src/space/services';
import { TagService } from 'src/tags/services';
import {
SpaceModelService,
SubSpaceModelService,
} from 'src/space-model/services';
import { DeviceService } from 'src/device/services';
import { SpaceProductAllocationService } from 'src/space/services/space-product-allocation.service'; import { SpaceProductAllocationService } from 'src/space/services/space-product-allocation.service';
import {
SubspaceProductAllocationRepository,
SubspaceRepository,
} from '@app/common/modules/space/repositories/subspace.repository';
import { SubspaceProductAllocationService } from 'src/space/services/subspace/subspace-product-allocation.service'; import { SubspaceProductAllocationService } from 'src/space/services/subspace/subspace-product-allocation.service';
import { CommunityService } from 'src/community/services'; import { TagService } from 'src/tags/services';
import { import { ProjectController } from './controllers';
SpaceModelProductAllocationRepoitory, import { ProjectUserController } from './controllers/project-user.controller';
SpaceModelRepository, import { CreateOrphanSpaceHandler } from './handler';
SubspaceModelProductAllocationRepoitory, import { ProjectService } from './services';
SubspaceModelRepository, import { ProjectUserService } from './services/project-user.service';
} from '@app/common/modules/space-model';
import { DeviceRepository } from '@app/common/modules/device/repositories';
import { NewTagRepository } from '@app/common/modules/tag/repositories/tag-repository';
import { ProductRepository } from '@app/common/modules/product/repositories';
import { SpaceModelProductAllocationService } from 'src/space-model/services/space-model-product-allocation.service';
import { SceneDeviceRepository } from '@app/common/modules/scene-device/repositories';
import { DeviceStatusFirebaseService } from '@app/common/firebase/devices-status/services/devices-status.service';
import { SceneService } from 'src/scene/services';
import { TuyaService } from '@app/common/integrations/tuya/services/tuya.service';
import { SubspaceModelProductAllocationService } from 'src/space-model/services/subspace/subspace-model-product-allocation.service';
import { DeviceStatusLogRepository } from '@app/common/modules/device-status-log/repositories';
import {
SceneIconRepository,
SceneRepository,
} from '@app/common/modules/scene/repositories';
import { AutomationRepository } from '@app/common/modules/automation/repositories';
import { PowerClampService } from '@app/common/helper/services/power.clamp.service';
import {
PowerClampDailyRepository,
PowerClampHourlyRepository,
PowerClampMonthlyRepository,
} from '@app/common/modules/power-clamp/repositories';
import { SqlLoaderService } from '@app/common/helper/services/sql-loader.service';
import { OccupancyService } from '@app/common/helper/services/occupancy.service';
const CommandHandlers = [CreateOrphanSpaceHandler]; const CommandHandlers = [CreateOrphanSpaceHandler];
@ -111,7 +111,6 @@ const CommandHandlers = [CreateOrphanSpaceHandler];
DeviceStatusFirebaseService, DeviceStatusFirebaseService,
SceneService, SceneService,
TuyaService, TuyaService,
TagRepository,
SubspaceModelRepository, SubspaceModelRepository,
SubspaceModelProductAllocationService, SubspaceModelProductAllocationService,
SpaceModelProductAllocationRepoitory, SpaceModelProductAllocationRepoitory,
@ -126,6 +125,7 @@ const CommandHandlers = [CreateOrphanSpaceHandler];
PowerClampMonthlyRepository, PowerClampMonthlyRepository,
SqlLoaderService, SqlLoaderService,
OccupancyService, OccupancyService,
AqiDataService,
], ],
exports: [ProjectService, CqrsModule], exports: [ProjectService, CqrsModule],
}) })

View File

@ -1,4 +1,17 @@
import { ORPHAN_COMMUNITY_NAME } from '@app/common/constants/orphan-constant';
import { BaseResponseDto } from '@app/common/dto/base.response.dto';
import { PageResponse } from '@app/common/dto/pagination.response.dto';
import { SuccessResponseDto } from '@app/common/dto/success.response.dto';
import {
TypeORMCustomModel,
TypeORMCustomModelFindAllQuery,
} from '@app/common/models/typeOrmCustom.model';
import { ProjectDto } from '@app/common/modules/project/dtos';
import { ProjectEntity } from '@app/common/modules/project/entities';
import { ProjectRepository } from '@app/common/modules/project/repositiories'; import { ProjectRepository } from '@app/common/modules/project/repositiories';
import { SpaceEntity } from '@app/common/modules/space/entities/space.entity';
import { UserRepository } from '@app/common/modules/user/repositories';
import { format } from '@fast-csv/format';
import { import {
forwardRef, forwardRef,
HttpException, HttpException,
@ -6,24 +19,11 @@ import {
Inject, Inject,
Injectable, Injectable,
} from '@nestjs/common'; } from '@nestjs/common';
import { CreateProjectDto, GetProjectParam } from '../dto';
import { BaseResponseDto } from '@app/common/dto/base.response.dto';
import { SuccessResponseDto } from '@app/common/dto/success.response.dto';
import { ProjectEntity } from '@app/common/modules/project/entities';
import {
TypeORMCustomModel,
TypeORMCustomModelFindAllQuery,
} from '@app/common/models/typeOrmCustom.model';
import { ProjectDto } from '@app/common/modules/project/dtos';
import { PageResponse } from '@app/common/dto/pagination.response.dto';
import { CommandBus } from '@nestjs/cqrs'; import { CommandBus } from '@nestjs/cqrs';
import { CreateOrphanSpaceCommand } from '../command/create-orphan-space-command';
import { UserRepository } from '@app/common/modules/user/repositories';
import { format } from '@fast-csv/format';
import { PassThrough } from 'stream';
import { SpaceEntity } from '@app/common/modules/space/entities/space.entity';
import { SpaceService } from 'src/space/services'; import { SpaceService } from 'src/space/services';
import { ORPHAN_COMMUNITY_NAME } from '@app/common/constants/orphan-constant'; import { PassThrough } from 'stream';
import { CreateOrphanSpaceCommand } from '../command/create-orphan-space-command';
import { CreateProjectDto, GetProjectParam } from '../dto';
@Injectable() @Injectable()
export class ProjectService { export class ProjectService {
@ -236,11 +236,11 @@ export class ProjectService {
'communities.spaces.parent', 'communities.spaces.parent',
'communities.spaces.productAllocations', 'communities.spaces.productAllocations',
'communities.spaces.productAllocations.product', 'communities.spaces.productAllocations.product',
'communities.spaces.productAllocations.tags', 'communities.spaces.productAllocations.tag',
'communities.spaces.subspaces', 'communities.spaces.subspaces',
'communities.spaces.subspaces.productAllocations', 'communities.spaces.subspaces.productAllocations',
'communities.spaces.subspaces.productAllocations.product', 'communities.spaces.subspaces.productAllocations.product',
'communities.spaces.subspaces.productAllocations.tags', 'communities.spaces.subspaces.productAllocations.tag',
], ],
}); });
@ -303,52 +303,38 @@ export class ProjectService {
if (subspace.disabled) continue; if (subspace.disabled) continue;
for (const productAllocation of subspace.productAllocations || []) { for (const productAllocation of subspace.productAllocations || []) {
for (const tag of productAllocation.tags || []) {
csvStream.write({
'Device ID': '',
'Community Name': space.community?.name || '',
'Space Name': space.spaceName,
'Space Location': spaceLocation,
'Subspace Name': subspace.subspaceName || '',
Tag: tag.name,
'Product Name': productAllocation.product.name || '',
'Community UUID': space.community?.uuid || '',
'Space UUID': space.uuid,
'Subspace UUID': subspace.uuid,
});
}
}
}
for (const productAllocation of space.productAllocations || []) {
for (const tag of productAllocation.tags || []) {
csvStream.write({ csvStream.write({
'Device ID': '', 'Device ID': '',
'Community Name': space.community?.name || '', 'Community Name': space.community?.name || '',
'Space Name': space.spaceName, 'Space Name': space.spaceName,
'Space Location': spaceLocation, 'Space Location': spaceLocation,
'Subspace Name': '', 'Subspace Name': subspace.subspaceName || '',
Tag: tag.name, Tag: productAllocation.tag.name,
'Product Name': productAllocation.product.name || '', 'Product Name': productAllocation.product.name || '',
'Community UUID': space.community?.uuid || '', 'Community UUID': space.community?.uuid || '',
'Space UUID': space.uuid, 'Space UUID': space.uuid,
'Subspace UUID': '', 'Subspace UUID': subspace.uuid,
}); });
} }
} }
for (const productAllocation of space.productAllocations || []) {
csvStream.write({
'Device ID': '',
'Community Name': space.community?.name || '',
'Space Name': space.spaceName,
'Space Location': spaceLocation,
'Subspace Name': '',
Tag: productAllocation.tag.name,
'Product Name': productAllocation.product.name || '',
'Community UUID': space.community?.uuid || '',
'Space UUID': space.uuid,
'Subspace UUID': '',
});
}
} }
csvStream.end(); csvStream.end();
return stream; return stream;
} }
getSpaceLocation(space: SpaceEntity): string {
const names = [];
let current = space.parent;
while (current) {
names.unshift(current.spaceName);
current = current.parent;
}
return names.join(' > ');
}
} }

View File

@ -1,7 +1,6 @@
export * from './create-space-model.dto'; export * from './create-space-model.dto';
export * from './link-space-model.dto';
export * from './project-param.dto'; export * from './project-param.dto';
export * from './update-space-model.dto';
export * from './space-model-param'; export * from './space-model-param';
export * from './subspaces-model-dtos'; export * from './subspaces-model-dtos';
export * from './tag-model-dtos'; export * from './update-space-model.dto';
export * from './link-space-model.dto';

View File

@ -1,14 +1,14 @@
import { ModifyAction } from '@app/common/constants/modify-action.enum';
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger'; import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
import { Type } from 'class-transformer'; import { Type } from 'class-transformer';
import { import {
IsString,
IsOptional,
IsArray, IsArray,
ValidateNested,
IsEnum, IsEnum,
IsOptional,
IsString,
ValidateNested,
} from 'class-validator'; } from 'class-validator';
import { ModifyTagModelDto } from '../tag-model-dtos'; import { ModifyTagDto } from 'src/space/dtos/tag/modify-tag.dto';
import { ModifyAction } from '@app/common/constants/modify-action.enum';
export class ModifySubspaceModelDto { export class ModifySubspaceModelDto {
@ApiProperty({ @ApiProperty({
@ -37,11 +37,11 @@ export class ModifySubspaceModelDto {
@ApiPropertyOptional({ @ApiPropertyOptional({
description: description:
'List of tag modifications (add/update/delete) for the subspace', 'List of tag modifications (add/update/delete) for the subspace',
type: [ModifyTagModelDto], type: [ModifyTagDto],
}) })
@IsOptional() @IsOptional()
@IsArray() @IsArray()
@ValidateNested({ each: true }) @ValidateNested({ each: true })
@Type(() => ModifyTagModelDto) @Type(() => ModifyTagDto)
tags?: ModifyTagModelDto[]; tags?: ModifyTagDto[];
} }

View File

@ -1,28 +0,0 @@
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
import { IsNotEmpty, IsOptional, IsString } from 'class-validator';
export class CreateTagModelDto {
@ApiProperty({
description: 'Tag associated with the space or subspace models',
example: 'Temperature Control',
})
@IsNotEmpty()
@IsString()
tag: string;
@ApiPropertyOptional({
description: 'UUID of the tag model (required for update/delete)',
example: '123e4567-e89b-12d3-a456-426614174000',
})
@IsOptional()
@IsString()
uuid?: string;
@ApiProperty({
description: 'ID of the product associated with the tag',
example: '123e4567-e89b-12d3-a456-426614174000',
})
@IsNotEmpty()
@IsString()
productUuid: string;
}

View File

@ -1,3 +0,0 @@
export * from './create-tag-model.dto';
export * from './update-tag-model.dto';
export * from './modify-tag-model.dto';

View File

@ -1,46 +0,0 @@
import { ModifyAction } from '@app/common/constants/modify-action.enum';
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
import { IsString, IsOptional, IsEnum, IsUUID } from 'class-validator';
export class ModifyTagModelDto {
@ApiProperty({
description: 'Action to perform: add, update, or delete',
example: ModifyAction.ADD,
})
@IsEnum(ModifyAction)
action: ModifyAction;
@ApiPropertyOptional({
description: 'UUID of the new tag',
example: '123e4567-e89b-12d3-a456-426614174000',
})
@IsOptional()
@IsUUID()
newTagUuid: string;
@ApiPropertyOptional({
description:
'UUID of an existing tag (required for update/delete, optional for add)',
example: 'a1b2c3d4-5678-90ef-abcd-1234567890ef',
})
@IsOptional()
@IsUUID()
tagUuid?: string;
@ApiPropertyOptional({
description: 'Name of the tag (required for add/update)',
example: 'Temperature Sensor',
})
@IsOptional()
@IsString()
name?: string;
@ApiPropertyOptional({
description:
'UUID of the product associated with the tag (required for add)',
example: 'c789a91e-549a-4753-9006-02f89e8170e0',
})
@IsOptional()
@IsUUID()
productUuid?: string;
}

View File

@ -1,21 +0,0 @@
import { ApiProperty } from '@nestjs/swagger';
import { IsNotEmpty, IsOptional, IsString, IsUUID } from 'class-validator';
export class UpdateTagModelDto {
@ApiProperty({
description: 'UUID of the tag to be updated',
example: '123e4567-e89b-12d3-a456-426614174000',
})
@IsNotEmpty()
@IsUUID()
uuid: string;
@ApiProperty({
description: 'Updated name of the tag',
example: 'Updated Tag Name',
required: false,
})
@IsOptional()
@IsString()
tag?: string;
}

View File

@ -1,48 +1,13 @@
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger'; import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
import { IsArray, IsOptional, IsString, ValidateNested } from 'class-validator';
import { CreateSubspaceModelDto } from './subspaces-model-dtos/create-subspace-model.dto';
import { Type } from 'class-transformer'; import { Type } from 'class-transformer';
import { IsArray, IsOptional, IsString, ValidateNested } from 'class-validator';
import { import {
DeleteSubspaceModelDto, DeleteSubspaceModelDto,
ModifySubspaceModelDto, ModifySubspaceModelDto,
UpdateSubspaceModelDto, UpdateSubspaceModelDto,
} from './subspaces-model-dtos'; } from './subspaces-model-dtos';
import { ModifyTagModelDto } from './tag-model-dtos'; import { CreateSubspaceModelDto } from './subspaces-model-dtos/create-subspace-model.dto';
import { ModifyTagDto } from 'src/space/dtos/tag/modify-tag.dto';
export class ModifySubspacesModelDto {
@ApiProperty({
description: 'List of subspaces to add',
type: [CreateSubspaceModelDto],
required: false,
})
@IsOptional()
@IsArray()
@ValidateNested({ each: true })
@Type(() => CreateSubspaceModelDto)
add?: CreateSubspaceModelDto[];
@ApiProperty({
description: 'List of subspaces to add',
type: [CreateSubspaceModelDto],
required: false,
})
@IsOptional()
@IsArray()
@ValidateNested({ each: true })
@Type(() => UpdateSubspaceModelDto)
update?: UpdateSubspaceModelDto[];
@ApiProperty({
description: 'List of subspaces to delete',
type: [DeleteSubspaceModelDto],
required: false,
})
@IsOptional()
@IsArray()
@ValidateNested({ each: true })
@Type(() => DeleteSubspaceModelDto)
delete?: DeleteSubspaceModelDto[];
}
export class UpdateSpaceModelDto { export class UpdateSpaceModelDto {
@ApiProperty({ @ApiProperty({
@ -66,11 +31,11 @@ export class UpdateSpaceModelDto {
@ApiPropertyOptional({ @ApiPropertyOptional({
description: description:
'List of tag modifications (add/update/delete) for the space model', 'List of tag modifications (add/update/delete) for the space model',
type: [ModifyTagModelDto], type: [ModifyTagDto],
}) })
@IsOptional() @IsOptional()
@IsArray() @IsArray()
@ValidateNested({ each: true }) @ValidateNested({ each: true })
@Type(() => ModifyTagModelDto) @Type(() => ModifyTagDto)
tags?: ModifyTagModelDto[]; tags?: ModifyTagDto[];
} }

View File

@ -1,11 +1,11 @@
import { CommandHandler, ICommandHandler } from '@nestjs/cqrs';
import { PropogateUpdateSpaceModelProductAllocationCommand } from '../commands';
import { SpaceProductAllocationRepository } from '@app/common/modules/space'; import { SpaceProductAllocationRepository } from '@app/common/modules/space';
import { SubspaceModelProductAllocationRepoitory } from '@app/common/modules/space-model'; import { SubspaceModelProductAllocationRepoitory } from '@app/common/modules/space-model';
import { import {
SubspaceRepository,
SubspaceProductAllocationRepository, SubspaceProductAllocationRepository,
SubspaceRepository,
} from '@app/common/modules/space/repositories/subspace.repository'; } from '@app/common/modules/space/repositories/subspace.repository';
import { CommandHandler, ICommandHandler } from '@nestjs/cqrs';
import { PropogateUpdateSpaceModelProductAllocationCommand } from '../commands';
@CommandHandler(PropogateUpdateSpaceModelProductAllocationCommand) @CommandHandler(PropogateUpdateSpaceModelProductAllocationCommand)
export class PropogateUpdateSpaceModelProductAllocationHandler export class PropogateUpdateSpaceModelProductAllocationHandler
@ -31,89 +31,89 @@ export class PropogateUpdateSpaceModelProductAllocationHandler
console.log(`Processing ${updatedAllocations.length} allocations...`); console.log(`Processing ${updatedAllocations.length} allocations...`);
for (const allocation of updatedAllocations) { // for (const allocation of updatedAllocations) {
try { // try {
if (allocation.allocation) { // if (allocation.allocation) {
const spaceAllocations = await this.spaceProductRepository.find({ // const spaceAllocations = await this.spaceProductRepository.find({
where: { uuid: allocation.allocation.uuid }, // where: { uuid: allocation.allocation.uuid },
relations: ['tags'], // relations: ['tags'],
}); // });
if (!spaceAllocations || spaceAllocations.length === 0) { // if (!spaceAllocations || spaceAllocations.length === 0) {
console.warn( // console.warn(
`No space allocations found for UUID: ${allocation.allocation.uuid}`, // `No space allocations found for UUID: ${allocation.allocation.uuid}`,
); // );
continue; // continue;
} // }
if (allocation.tagsAdded?.length) { // if (allocation.tagsAdded?.length) {
for (const spaceAllocation of spaceAllocations) { // for (const spaceAllocation of spaceAllocations) {
spaceAllocation.tags.push(...allocation.tagsAdded); // spaceAllocation.tags.push(...allocation.tagsAdded);
} // }
await this.spaceProductRepository.save(spaceAllocations); // await this.spaceProductRepository.save(spaceAllocations);
console.log( // console.log(
`Added tags to ${spaceAllocations.length} space allocations.`, // `Added tags to ${spaceAllocations.length} space allocations.`,
); // );
} // }
if (allocation.tagsRemoved?.length) { // if (allocation.tagsRemoved?.length) {
const tagsToRemoveUUIDs = new Set( // const tagsToRemoveUUIDs = new Set(
allocation.tagsRemoved.map((tag) => tag.uuid), // allocation.tagsRemoved.map((tag) => tag.uuid),
); // );
for (const spaceAllocation of spaceAllocations) { // for (const spaceAllocation of spaceAllocations) {
spaceAllocation.tags = spaceAllocation.tags.filter( // spaceAllocation.tags = spaceAllocation.tags.filter(
(tag) => !tagsToRemoveUUIDs.has(tag.uuid), // (tag) => !tagsToRemoveUUIDs.has(tag.uuid),
); // );
} // }
await this.spaceProductRepository.save(spaceAllocations); // await this.spaceProductRepository.save(spaceAllocations);
console.log( // console.log(
`Removed tags from ${spaceAllocations.length} space allocations.`, // `Removed tags from ${spaceAllocations.length} space allocations.`,
); // );
} // }
} // }
if (allocation.deletedAllocation) { // if (allocation.deletedAllocation) {
const spaceAllocations = await this.spaceProductRepository.find({ // const spaceAllocations = await this.spaceProductRepository.find({
where: { uuid: allocation.deletedAllocation.uuid }, // where: { uuid: allocation.deletedAllocation.uuid },
relations: ['tags'], // relations: ['tags'],
}); // });
if (!spaceAllocations || spaceAllocations.length === 0) { // if (!spaceAllocations || spaceAllocations.length === 0) {
console.warn( // console.warn(
`No space allocations found to delete for UUID: ${allocation.deletedAllocation.uuid}`, // `No space allocations found to delete for UUID: ${allocation.deletedAllocation.uuid}`,
); // );
continue; // continue;
} // }
await this.spaceProductRepository.remove(spaceAllocations); // await this.spaceProductRepository.remove(spaceAllocations);
console.log( // console.log(
`Deleted ${spaceAllocations.length} space allocations.`, // `Deleted ${spaceAllocations.length} space allocations.`,
); // );
} // }
if (allocation.newAllocation) { // if (allocation.newAllocation) {
const newAllocations = spaces.map((space) => // const newAllocations = spaces.map((space) =>
this.spaceProductRepository.create({ // this.spaceProductRepository.create({
space, // space,
product: allocation.newAllocation.product, // product: allocation.newAllocation.product,
tags: allocation.newAllocation.tags, // tag: allocation.newAllocation.tag,
inheritedFromModel: allocation.newAllocation, // inheritedFromModel: allocation.newAllocation,
}), // }),
); // );
await this.spaceProductRepository.save(newAllocations); // await this.spaceProductRepository.save(newAllocations);
console.log( // console.log(
`Created ${newAllocations.length} new space allocations.`, // `Created ${newAllocations.length} new space allocations.`,
); // );
} // }
} catch (error) { // } catch (error) {
console.error( // console.error(
`Error processing allocation update: ${JSON.stringify(allocation)}`, // `Error processing allocation update: ${JSON.stringify(allocation)}`,
error, // error,
); // );
} // }
} // }
console.log('Finished processing all allocations.'); console.log('Finished processing all allocations.');
} catch (error) { } catch (error) {

View File

@ -1,15 +1,14 @@
import { CommandHandler, ICommandHandler } from '@nestjs/cqrs'; import { ModifyAction } from '@app/common/constants/modify-action.enum';
import { PropogateUpdateSpaceModelCommand } from '../commands';
import { SpaceProductAllocationRepository } from '@app/common/modules/space'; import { SpaceProductAllocationRepository } from '@app/common/modules/space';
import { SubspaceModelProductAllocationRepoitory } from '@app/common/modules/space-model';
import { SpaceEntity } from '@app/common/modules/space/entities/space.entity';
import { import {
SubspaceProductAllocationRepository, SubspaceProductAllocationRepository,
SubspaceRepository, SubspaceRepository,
} from '@app/common/modules/space/repositories/subspace.repository'; } from '@app/common/modules/space/repositories/subspace.repository';
import { SubspaceModelProductAllocationRepoitory } from '@app/common/modules/space-model'; import { CommandHandler, ICommandHandler } from '@nestjs/cqrs';
import { In } from 'typeorm'; import { PropogateUpdateSpaceModelCommand } from '../commands';
import { ISingleSubspaceModel } from '../interfaces'; import { ISingleSubspaceModel } from '../interfaces';
import { SpaceEntity } from '@app/common/modules/space/entities/space.entity';
import { ModifyAction } from '@app/common/constants/modify-action.enum';
import { IUpdatedAllocations } from '../interfaces/subspace-product-allocation-update-result.interface'; import { IUpdatedAllocations } from '../interfaces/subspace-product-allocation-update-result.interface';
@CommandHandler(PropogateUpdateSpaceModelCommand) @CommandHandler(PropogateUpdateSpaceModelCommand)
@ -72,48 +71,48 @@ export class PropogateUpdateSpaceModelHandler
for (const allocation of allocations) { for (const allocation of allocations) {
if (!allocation) continue; if (!allocation) continue;
if (allocation.allocation) { // if (allocation.allocation) {
try { // try {
const subspaceAllocations = // const subspaceAllocations =
await this.subspaceProductRepository.find({ // await this.subspaceProductRepository.find({
where: { // where: {
inheritedFromModel: { uuid: allocation.allocation.uuid }, // inheritedFromModel: { uuid: allocation.allocation.uuid },
}, // },
relations: ['tags'], // relations: ['tags'],
}); // });
if (!subspaceAllocations || subspaceAllocations.length === 0) // if (!subspaceAllocations || subspaceAllocations.length === 0)
continue; // continue;
if (allocation.tagsAdded?.length) { // if (allocation.tagsAdded?.length) {
for (const subspaceAllocation of subspaceAllocations) { // for (const subspaceAllocation of subspaceAllocations) {
subspaceAllocation.tags.push(...allocation.tagsAdded); // subspaceAllocation.tags.push(...allocation.tagsAdded);
} // }
await this.subspaceProductRepository.save(subspaceAllocations); // await this.subspaceProductRepository.save(subspaceAllocations);
console.log( // console.log(
`Added tags to ${subspaceAllocations.length} subspace allocations.`, // `Added tags to ${subspaceAllocations.length} subspace allocations.`,
); // );
} // }
if (allocation.tagsRemoved?.length) { // if (allocation.tagsRemoved?.length) {
const tagsToRemoveUUIDs = allocation.tagsRemoved.map( // const tagsToRemoveUUIDs = allocation.tagsRemoved.map(
(tag) => tag.uuid, // (tag) => tag.uuid,
); // );
for (const subspaceAllocation of subspaceAllocations) { // for (const subspaceAllocation of subspaceAllocations) {
subspaceAllocation.tags = subspaceAllocation.tags.filter( // subspaceAllocation.tags = subspaceAllocation.tags.filter(
(tag) => !tagsToRemoveUUIDs.includes(tag.uuid), // (tag) => !tagsToRemoveUUIDs.includes(tag.uuid),
); // );
} // }
await this.subspaceProductRepository.save(subspaceAllocations); // await this.subspaceProductRepository.save(subspaceAllocations);
console.log( // console.log(
`Removed tags from ${subspaceAllocations.length} subspace allocations.`, // `Removed tags from ${subspaceAllocations.length} subspace allocations.`,
); // );
} // }
} catch (error) { // } catch (error) {
console.error('Error processing allocation update:', error); // console.error('Error processing allocation update:', error);
} // }
} // }
if (allocation.newAllocation) { if (allocation.newAllocation) {
try { try {
@ -127,7 +126,7 @@ export class PropogateUpdateSpaceModelHandler
const newAllocations = subspaces.map((subspace) => const newAllocations = subspaces.map((subspace) =>
this.subspaceProductRepository.create({ this.subspaceProductRepository.create({
product: allocation.newAllocation.product, product: allocation.newAllocation.product,
tags: allocation.newAllocation.tags, tag: allocation.newAllocation.tag,
subspace, subspace,
inheritedFromModel: allocation.newAllocation, inheritedFromModel: allocation.newAllocation,
}), }),
@ -198,7 +197,7 @@ export class PropogateUpdateSpaceModelHandler
const subspaceAllocation = this.subspaceProductRepository.create({ const subspaceAllocation = this.subspaceProductRepository.create({
subspace: subspace, subspace: subspace,
product: allocation.product, product: allocation.product,
tags: allocation.tags, tag: allocation.tag,
inheritedFromModel: allocation, inheritedFromModel: allocation,
}); });
await this.subspaceProductRepository.save(subspaceAllocation); await this.subspaceProductRepository.save(subspaceAllocation);
@ -211,67 +210,59 @@ export class PropogateUpdateSpaceModelHandler
subspaceModel: ISingleSubspaceModel, subspaceModel: ISingleSubspaceModel,
spaces: SpaceEntity[], spaces: SpaceEntity[],
) { ) {
const subspaces = await this.subspaceRepository.find({ // const subspaces = await this.subspaceRepository.find({
where: { // where: {
subSpaceModel: { uuid: subspaceModel.subspaceModel.uuid }, // subSpaceModel: { uuid: subspaceModel.subspaceModel.uuid },
disabled: false, // disabled: false,
}, // },
relations: [ // relations: [
'productAllocations', // 'productAllocations',
'productAllocations.product', // 'productAllocations.product',
'productAllocations.tags', // 'productAllocations.tags',
], // ],
}); // });
// if (!subspaces.length) {
if (!subspaces.length) { // return;
return; // }
} // const allocationUuidsToRemove = subspaces.flatMap((subspace) =>
// subspace.productAllocations.map((allocation) => allocation.uuid),
const allocationUuidsToRemove = subspaces.flatMap((subspace) => // );
subspace.productAllocations.map((allocation) => allocation.uuid), // if (allocationUuidsToRemove.length) {
); // await this.subspaceProductRepository.delete(allocationUuidsToRemove);
// }
if (allocationUuidsToRemove.length) { // await this.subspaceRepository.update(
await this.subspaceProductRepository.delete(allocationUuidsToRemove); // { uuid: In(subspaces.map((s) => s.uuid)) },
} // { disabled: true },
// );
await this.subspaceRepository.update( // const relocatedAllocations = subspaceModel.relocatedAllocations || [];
{ uuid: In(subspaces.map((s) => s.uuid)) }, // if (!relocatedAllocations.length) {
{ disabled: true }, // return;
); // }
// for (const space of spaces) {
const relocatedAllocations = subspaceModel.relocatedAllocations || []; // for (const { allocation, tags = [] } of relocatedAllocations) {
// const spaceAllocation = await this.spaceProductRepository.findOne({
if (!relocatedAllocations.length) { // where: {
return; // inheritedFromModel: { uuid: allocation.uuid },
} // space: { uuid: space.uuid },
// },
for (const space of spaces) { // relations: ['tags'],
for (const { allocation, tags = [] } of relocatedAllocations) { // });
const spaceAllocation = await this.spaceProductRepository.findOne({ // if (spaceAllocation) {
where: { // if (tags.length) {
inheritedFromModel: { uuid: allocation.uuid }, // spaceAllocation.tags.push(...tags);
space: { uuid: space.uuid }, // await this.spaceProductRepository.save(spaceAllocation);
}, // }
relations: ['tags'], // } else {
}); // const newSpaceAllocation = this.spaceProductRepository.create({
// space,
if (spaceAllocation) { // inheritedFromModel: allocation,
if (tags.length) { // tag: allocation.tag,
spaceAllocation.tags.push(...tags); // product: allocation.product,
await this.spaceProductRepository.save(spaceAllocation); // });
} // await this.spaceProductRepository.save(newSpaceAllocation);
} else { // }
const newSpaceAllocation = this.spaceProductRepository.create({ // }
space, // }
inheritedFromModel: allocation,
tags: allocation.tags,
product: allocation.product,
});
await this.spaceProductRepository.save(newSpaceAllocation);
}
}
}
} }
async updateSubspaceModel(subspaceModel: ISingleSubspaceModel) { async updateSubspaceModel(subspaceModel: ISingleSubspaceModel) {

View File

@ -1,4 +1,3 @@
export * from './update-subspace.interface';
export * from './modify-subspace.interface';
export * from './single-subspace.interface'; export * from './single-subspace.interface';
export * from './space-product-allocation.interface'; export * from './space-product-allocation.interface';
export * from './update-subspace.interface';

View File

@ -1,24 +0,0 @@
import { SubspaceModelEntity, TagModel } from '@app/common/modules/space-model';
export interface ModifyspaceModelPayload {
modifiedSubspaceModels?: ModifySubspaceModelPayload;
modifiedTags?: ModifiedTagsModelPayload;
}
export interface ModifySubspaceModelPayload {
addedSubspaceModels?: SubspaceModelEntity[];
updatedSubspaceModels?: UpdatedSubspaceModelPayload[];
deletedSubspaceModels?: string[];
}
export interface UpdatedSubspaceModelPayload {
subspaceName?: string;
modifiedTags?: ModifiedTagsModelPayload;
subspaceModelUuid: string;
}
export interface ModifiedTagsModelPayload {
added?: TagModel[];
updated?: TagModel[];
deleted?: string[];
}

View File

@ -1,11 +1,11 @@
import { ModifyAction } from '@app/common/constants/modify-action.enum';
import { import {
SpaceModelProductAllocationEntity, SpaceModelProductAllocationEntity,
SubspaceModelEntity, SubspaceModelEntity,
} from '@app/common/modules/space-model'; } from '@app/common/modules/space-model';
import { ModifyTagModelDto } from '../dtos';
import { ModifyAction } from '@app/common/constants/modify-action.enum';
import { NewTagEntity } from '@app/common/modules/tag'; import { NewTagEntity } from '@app/common/modules/tag';
import { IUpdatedAllocations } from './subspace-product-allocation-update-result.interface'; import { IUpdatedAllocations } from './subspace-product-allocation-update-result.interface';
import { ModifyTagDto } from 'src/space/dtos/tag/modify-tag.dto';
export interface IRelocatedAllocation { export interface IRelocatedAllocation {
allocation: SpaceModelProductAllocationEntity; allocation: SpaceModelProductAllocationEntity;
@ -14,7 +14,7 @@ export interface IRelocatedAllocation {
export interface ISingleSubspaceModel { export interface ISingleSubspaceModel {
subspaceModel: SubspaceModelEntity; subspaceModel: SubspaceModelEntity;
action: ModifyAction; action: ModifyAction;
tags?: ModifyTagModelDto[]; tags?: ModifyTagDto[];
relocatedAllocations?: IRelocatedAllocation[]; relocatedAllocations?: IRelocatedAllocation[];
} }

View File

@ -1,20 +1,19 @@
import { In, QueryRunner } from 'typeorm';
import { HttpException, HttpStatus, Injectable } from '@nestjs/common'; import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { In, QueryRunner } from 'typeorm';
import { ProductEntity } from '@app/common/modules/product/entities';
import { ProjectEntity } from '@app/common/modules/project/entities';
import { SpaceRepository } from '@app/common/modules/space';
import { import {
SpaceModelEntity, SpaceModelEntity,
SpaceModelProductAllocationEntity, SpaceModelProductAllocationEntity,
SpaceModelProductAllocationRepoitory, SpaceModelProductAllocationRepoitory,
SubspaceModelProductAllocationEntity,
} from '@app/common/modules/space-model'; } from '@app/common/modules/space-model';
import { TagService as NewTagService } from 'src/tags/services';
import { ProcessTagDto } from 'src/tags/dtos';
import { ModifySubspaceModelDto, ModifyTagModelDto } from '../dtos';
import { ModifyAction } from '@app/common/constants/modify-action.enum';
import { NewTagEntity } from '@app/common/modules/tag'; import { NewTagEntity } from '@app/common/modules/tag';
import { ProductEntity } from '@app/common/modules/product/entities'; import { ModifyTagDto } from 'src/space/dtos/tag/modify-tag.dto';
import { SpaceRepository } from '@app/common/modules/space'; import { ProcessTagDto } from 'src/tags/dtos';
import { ProjectEntity } from '@app/common/modules/project/entities'; import { TagService as NewTagService } from 'src/tags/services';
import { ModifySubspaceModelDto } from '../dtos';
import { IUpdatedSpaceAllocations } from '../interfaces'; import { IUpdatedSpaceAllocations } from '../interfaces';
@Injectable() @Injectable()
@ -32,225 +31,220 @@ export class SpaceModelProductAllocationService {
queryRunner?: QueryRunner, queryRunner?: QueryRunner,
modifySubspaceModels?: ModifySubspaceModelDto[], modifySubspaceModels?: ModifySubspaceModelDto[],
): Promise<IUpdatedSpaceAllocations[]> { ): Promise<IUpdatedSpaceAllocations[]> {
try { // try {
if (!tags.length) return []; if (!tags.length) return [];
const allocationUpdates: IUpdatedSpaceAllocations[] = []; const allocationUpdates: IUpdatedSpaceAllocations[] = [];
return allocationUpdates;
// const processedTags = await this.tagService.processTags(
// tags,
// projectUuid,
// queryRunner,
// );
const processedTags = await this.tagService.processTags( // const productAllocations: SpaceModelProductAllocationEntity[] = [];
tags, // const existingAllocations = new Map<
projectUuid, // string,
queryRunner, // SpaceModelProductAllocationEntity
); // >();
const productAllocations: SpaceModelProductAllocationEntity[] = []; // for (const tag of processedTags) {
const existingAllocations = new Map< // let isTagNeeded = true;
string,
SpaceModelProductAllocationEntity
>();
for (const tag of processedTags) { // if (modifySubspaceModels) {
let isTagNeeded = true; // const relatedSubspaces = await queryRunner.manager.find(
// SubspaceModelProductAllocationEntity,
// {
// where: {
// product: { uuid: tag.product.uuid },
// subspaceModel: { spaceModel: { uuid: spaceModel.uuid } },
// tags: { uuid: tag.uuid },
// },
// relations: ['subspaceModel', 'tags'],
// },
// );
if (modifySubspaceModels) { // for (const subspaceWithTag of relatedSubspaces) {
const relatedSubspaces = await queryRunner.manager.find( // const modifyingSubspace = modifySubspaceModels.find(
SubspaceModelProductAllocationEntity, // (subspace) =>
{ // subspace.action === ModifyAction.UPDATE &&
where: { // subspace.uuid === subspaceWithTag.subspaceModel.uuid,
product: { uuid: tag.product.uuid }, // );
subspaceModel: { spaceModel: { uuid: spaceModel.uuid } },
tags: { uuid: tag.uuid },
},
relations: ['subspaceModel', 'tags'],
},
);
for (const subspaceWithTag of relatedSubspaces) { // if (
const modifyingSubspace = modifySubspaceModels.find( // modifyingSubspace &&
(subspace) => // modifyingSubspace.tags &&
subspace.action === ModifyAction.UPDATE && // modifyingSubspace.tags.some(
subspace.uuid === subspaceWithTag.subspaceModel.uuid, // (subspaceTag) =>
); // subspaceTag.action === ModifyAction.DELETE &&
// subspaceTag.tagUuid === tag.uuid,
// )
// ) {
// isTagNeeded = true;
// break;
// }
// }
// }
if ( // if (isTagNeeded) {
modifyingSubspace && // const hasTags = await this.validateTagWithinSpaceModel(
modifyingSubspace.tags && // queryRunner,
modifyingSubspace.tags.some( // tag,
(subspaceTag) => // spaceModel,
subspaceTag.action === ModifyAction.DELETE && // );
subspaceTag.tagUuid === tag.uuid,
)
) {
isTagNeeded = true;
break;
}
}
}
if (isTagNeeded) { // if (hasTags) continue;
const hasTags = await this.validateTagWithinSpaceModel(
queryRunner,
tag,
spaceModel,
);
if (hasTags) continue; // let allocation = existingAllocations.get(tag.product.uuid);
// if (!allocation) {
// allocation = await this.getAllocationByProduct(
// tag.product,
// spaceModel,
// queryRunner,
// );
// if (allocation) {
// existingAllocations.set(tag.product.uuid, allocation);
// }
// }
let allocation = existingAllocations.get(tag.product.uuid); // if (!allocation) {
if (!allocation) { // allocation = this.createNewAllocation(spaceModel, tag, queryRunner);
allocation = await this.getAllocationByProduct( // productAllocations.push(allocation);
tag.product, // allocationUpdates.push({
spaceModel, // newAllocation: allocation,
queryRunner, // });
); // } else if (!allocation.tags.some((t) => t.uuid === tag.uuid)) {
if (allocation) { // allocation.tags.push(tag);
existingAllocations.set(tag.product.uuid, allocation); // allocationUpdates.push({
} // allocation: allocation,
} // tagsAdded: [tag],
// });
// await this.saveAllocation(allocation, queryRunner);
// }
// }
// }
if (!allocation) { // if (productAllocations.length > 0) {
allocation = this.createNewAllocation(spaceModel, tag, queryRunner); // await this.saveAllocations(productAllocations, queryRunner);
productAllocations.push(allocation); // }
allocationUpdates.push({
newAllocation: allocation,
});
} else if (!allocation.tags.some((t) => t.uuid === tag.uuid)) {
allocation.tags.push(tag);
allocationUpdates.push({
allocation: allocation,
tagsAdded: [tag],
});
await this.saveAllocation(allocation, queryRunner);
}
}
}
if (productAllocations.length > 0) { // return allocationUpdates;
await this.saveAllocations(productAllocations, queryRunner); // } catch (error) {
} // throw this.handleError(error, 'Failed to create product allocations');
// }
return allocationUpdates;
} catch (error) {
throw this.handleError(error, 'Failed to create product allocations');
}
} }
async updateProductAllocations( async updateProductAllocations(
dtos: ModifyTagModelDto[], dtos: ModifyTagDto[],
project: ProjectEntity, project: ProjectEntity,
spaceModel: SpaceModelEntity, spaceModel: SpaceModelEntity,
queryRunner: QueryRunner, queryRunner: QueryRunner,
modifySubspaceModels?: ModifySubspaceModelDto[], modifySubspaceModels?: ModifySubspaceModelDto[],
): Promise<IUpdatedSpaceAllocations[]> { ): Promise<IUpdatedSpaceAllocations[]> {
try { const allocationUpdates: IUpdatedSpaceAllocations[] = [];
const addDtos = dtos.filter((dto) => dto.action === ModifyAction.ADD); return allocationUpdates;
const deleteDtos = dtos.filter( // try {
(dto) => dto.action === ModifyAction.DELETE, // const addDtos = dtos.filter((dto) => dto.action === ModifyAction.ADD);
); // const deleteDtos = dtos.filter(
// (dto) => dto.action === ModifyAction.DELETE,
const addTagDtos: ProcessTagDto[] = addDtos.map((dto) => ({ // );
name: dto.name, // const addTagDtos: ProcessTagDto[] = addDtos.map((dto) => ({
productUuid: dto.productUuid, // name: dto.name,
uuid: dto.newTagUuid, // productUuid: dto.productUuid,
})); // uuid: dto.newTagUuid,
// }));
// Process added tags // // Process added tags
const processedTags = await this.tagService.processTags( // const processedTags = await this.tagService.processTags(
addTagDtos, // addTagDtos,
project.uuid, // project.uuid,
queryRunner, // queryRunner,
); // );
// const addTagUuidMap = new Map<string, ModifyTagModelDto>();
const addTagUuidMap = new Map<string, ModifyTagModelDto>(); // processedTags.forEach((tag, index) => {
processedTags.forEach((tag, index) => { // addTagUuidMap.set(tag.uuid, addDtos[index]);
addTagUuidMap.set(tag.uuid, addDtos[index]); // });
}); // const addTagUuids = new Set(processedTags.map((tag) => tag.uuid));
// const deleteTagUuids = new Set(deleteDtos.map((dto) => dto.tagUuid));
const addTagUuids = new Set(processedTags.map((tag) => tag.uuid)); // const tagsToIgnore = new Set(
const deleteTagUuids = new Set(deleteDtos.map((dto) => dto.tagUuid)); // [...addTagUuids].filter((uuid) => deleteTagUuids.has(uuid)),
// );
const tagsToIgnore = new Set( // // Filter out tags that are added and deleted in the same request
[...addTagUuids].filter((uuid) => deleteTagUuids.has(uuid)), // const filteredDtos = dtos.filter(
); // (dto) =>
// !(
// Filter out tags that are added and deleted in the same request // tagsToIgnore.has(dto.tagUuid) ||
const filteredDtos = dtos.filter( // (dto.action === ModifyAction.ADD &&
(dto) => // tagsToIgnore.has(
!( // [...addTagUuidMap.keys()].find(
tagsToIgnore.has(dto.tagUuid) || // (uuid) => addTagUuidMap.get(uuid) === dto,
(dto.action === ModifyAction.ADD && // ),
tagsToIgnore.has( // ))
[...addTagUuidMap.keys()].find( // ),
(uuid) => addTagUuidMap.get(uuid) === dto, // );
), // // Process add and delete actions concurrently
)) // const [updatedAllocations, deletedAllocations] = await Promise.all([
), // this.processAddActions(
); // filteredDtos,
// project.uuid,
// Process add and delete actions concurrently // spaceModel,
const [updatedAllocations, deletedAllocations] = await Promise.all([ // queryRunner,
this.processAddActions( // modifySubspaceModels,
filteredDtos, // ),
project.uuid, // this.processDeleteActions(filteredDtos, queryRunner, spaceModel),
spaceModel, // ]);
queryRunner, // // Combine results and return
modifySubspaceModels, // return [...updatedAllocations, ...deletedAllocations];
), // } catch (error) {
this.processDeleteActions(filteredDtos, queryRunner, spaceModel), // throw this.handleError(error, 'Error while updating product allocations');
]); // }
// Combine results and return
return [...updatedAllocations, ...deletedAllocations];
} catch (error) {
throw this.handleError(error, 'Error while updating product allocations');
}
} }
private async processAddActions( private async processAddActions(
dtos: ModifyTagModelDto[], dtos: ModifyTagDto[],
projectUuid: string, projectUuid: string,
spaceModel: SpaceModelEntity, spaceModel: SpaceModelEntity,
queryRunner: QueryRunner, queryRunner: QueryRunner,
modifySubspaceModels?: ModifySubspaceModelDto[], modifySubspaceModels?: ModifySubspaceModelDto[],
): Promise<IUpdatedSpaceAllocations[]> { ): Promise<IUpdatedSpaceAllocations[]> {
let allocationUpdates: IUpdatedSpaceAllocations[] = []; const allocationUpdates: IUpdatedSpaceAllocations[] = [];
const addDtos: ProcessTagDto[] = dtos
.filter((dto) => dto.action === ModifyAction.ADD)
.map((dto) => ({
name: dto.name,
productUuid: dto.productUuid,
uuid: dto.newTagUuid,
}));
if (addDtos.length > 0) {
allocationUpdates = await this.createProductAllocations(
projectUuid,
spaceModel,
addDtos,
queryRunner,
modifySubspaceModels,
);
}
return allocationUpdates; return allocationUpdates;
// const addDtos: ProcessTagDto[] = dtos
// .filter((dto) => dto.action === ModifyAction.ADD)
// .map((dto) => ({
// name: dto.name,
// productUuid: dto.productUuid,
// uuid: dto.newTagUuid,
// }));
// if (addDtos.length > 0) {
// allocationUpdates = await this.createProductAllocations(
// projectUuid,
// spaceModel,
// addDtos,
// queryRunner,
// modifySubspaceModels,
// );
// }
// return allocationUpdates;
} }
private createNewAllocation( private createNewAllocation(
spaceModel: SpaceModelEntity, spaceModel: SpaceModelEntity,
tag: NewTagEntity, tag: NewTagEntity,
queryRunner?: QueryRunner, queryRunner?: QueryRunner,
): SpaceModelProductAllocationEntity { ) {
return queryRunner // : SpaceModelProductAllocationEntity
? queryRunner.manager.create(SpaceModelProductAllocationEntity, { // return queryRunner
spaceModel, // ? queryRunner.manager.create(SpaceModelProductAllocationEntity, {
product: tag.product, // spaceModel,
tags: [tag], // product: tag.product,
}) // tags: [tag],
: this.spaceModelProductAllocationRepository.create({ // })
spaceModel, // : this.spaceModelProductAllocationRepository.create({
product: tag.product, // spaceModel,
tags: [tag], // product: tag.product,
}); // tags: [tag],
// });
} }
private async getAllocationByProduct( private async getAllocationByProduct(
@ -309,7 +303,7 @@ export class SpaceModelProductAllocationService {
} }
private async processDeleteActions( private async processDeleteActions(
dtos: ModifyTagModelDto[], dtos: ModifyTagDto[],
queryRunner: QueryRunner, queryRunner: QueryRunner,
spaceModel: SpaceModelEntity, spaceModel: SpaceModelEntity,
): Promise<IUpdatedSpaceAllocations[]> { ): Promise<IUpdatedSpaceAllocations[]> {
@ -317,10 +311,10 @@ export class SpaceModelProductAllocationService {
if (!dtos || dtos.length === 0) { if (!dtos || dtos.length === 0) {
return; return;
} }
let allocationUpdateToPropagate: IUpdatedSpaceAllocations[] = []; const allocationUpdateToPropagate: IUpdatedSpaceAllocations[] = [];
const tagUuidsToDelete = dtos const tagUuidsToDelete = dtos
.filter((dto) => dto.action === ModifyAction.DELETE && dto.tagUuid) // .filter((dto) => dto.action === ModifyAction.DELETE && dto.tagUuid)
.map((dto) => dto.tagUuid); .map((dto) => dto.tagUuid);
if (tagUuidsToDelete.length === 0) return []; if (tagUuidsToDelete.length === 0) return [];
@ -329,7 +323,7 @@ export class SpaceModelProductAllocationService {
SpaceModelProductAllocationEntity, SpaceModelProductAllocationEntity,
{ {
where: { where: {
tags: { uuid: In(tagUuidsToDelete) }, tag: In(tagUuidsToDelete),
spaceModel: { spaceModel: {
uuid: spaceModel.uuid, uuid: spaceModel.uuid,
}, },
@ -348,31 +342,28 @@ export class SpaceModelProductAllocationService {
const allocationUpdates: SpaceModelProductAllocationEntity[] = []; const allocationUpdates: SpaceModelProductAllocationEntity[] = [];
for (const allocation of allocationsToUpdate) { for (const allocation of allocationsToUpdate) {
const updatedTags = allocation.tags.filter( // const updatedTags = allocation.tags.filter(
(tag) => !tagUuidsToDelete.includes(tag.uuid), // (tag) => !tagUuidsToDelete.includes(tag.uuid),
); // );
// const deletedTags = allocation.tags.filter((tag) =>
const deletedTags = allocation.tags.filter((tag) => // tagUuidsToDelete.includes(tag.uuid),
tagUuidsToDelete.includes(tag.uuid), // );
); // if (updatedTags.length === allocation.tags.length) {
// continue;
if (updatedTags.length === allocation.tags.length) { // }
continue; // if (updatedTags.length === 0) {
} // deletedAllocations.push(allocation);
// allocationUpdateToPropagate.push({
if (updatedTags.length === 0) { // deletedAllocation: allocation,
deletedAllocations.push(allocation); // });
allocationUpdateToPropagate.push({ // } else {
deletedAllocation: allocation, // allocation.tags = updatedTags;
}); // allocationUpdates.push(allocation);
} else { // allocationUpdateToPropagate.push({
allocation.tags = updatedTags; // allocation: allocation,
allocationUpdates.push(allocation); // tagsRemoved: deletedTags,
allocationUpdateToPropagate.push({ // });
allocation: allocation, // }
tagsRemoved: deletedTags,
});
}
} }
if (allocationUpdates.length > 0) { if (allocationUpdates.length > 0) {
@ -415,33 +406,34 @@ export class SpaceModelProductAllocationService {
tag: NewTagEntity, tag: NewTagEntity,
spaceModel: SpaceModelEntity, spaceModel: SpaceModelEntity,
): Promise<boolean> { ): Promise<boolean> {
const existingAllocationsForProduct = await queryRunner.manager.find( return true;
SpaceModelProductAllocationEntity, // const existingAllocationsForProduct = await queryRunner.manager.find(
{ // SpaceModelProductAllocationEntity,
where: { // {
spaceModel: { // where: {
uuid: spaceModel.uuid, // spaceModel: {
}, // uuid: spaceModel.uuid,
product: { // },
uuid: tag.product.uuid, // product: {
}, // uuid: tag.product.uuid,
}, // },
relations: ['tags'], // },
}, // relations: ['tags'],
); // },
// );
const existingTagsForProduct = existingAllocationsForProduct.flatMap( // const existingTagsForProduct = existingAllocationsForProduct.flatMap(
(allocation) => allocation.tags, // (allocation) => allocation.tags,
); // );
const isDuplicateTag = existingTagsForProduct.some( // const isDuplicateTag = existingTagsForProduct.some(
(existingTag) => existingTag.uuid === tag.uuid, // (existingTag) => existingTag.uuid === tag.uuid,
); // );
if (isDuplicateTag) { // if (isDuplicateTag) {
return true; // return true;
} // }
return false; // return false;
} }
async clearAllAllocations(spaceModelUuid: string, queryRunner: QueryRunner) { async clearAllAllocations(spaceModelUuid: string, queryRunner: QueryRunner) {

View File

@ -1,58 +1,47 @@
import { import { BaseResponseDto } from '@app/common/dto/base.response.dto';
SpaceModelEntity,
SpaceModelProductAllocationEntity,
SpaceModelRepository,
SubspaceModelProductAllocationEntity,
} from '@app/common/modules/space-model';
import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import {
CreateSpaceModelDto,
LinkSpacesToModelDto,
UpdateSpaceModelDto,
} from '../dtos';
import { ProjectParam } from 'src/community/dtos';
import { SuccessResponseDto } from '@app/common/dto/success.response.dto'; import { SuccessResponseDto } from '@app/common/dto/success.response.dto';
import { SubSpaceModelService } from './subspace/subspace-model.service';
import { DataSource, In, QueryRunner, SelectQueryBuilder } from 'typeorm';
import { import {
TypeORMCustomModel, TypeORMCustomModel,
TypeORMCustomModelFindAllQuery, TypeORMCustomModelFindAllQuery,
} from '@app/common/models/typeOrmCustom.model'; } from '@app/common/models/typeOrmCustom.model';
import { SpaceModelParam } from '../dtos/space-model-param';
import { ProjectService } from 'src/project/services';
import { ProjectEntity } from '@app/common/modules/project/entities'; import { ProjectEntity } from '@app/common/modules/project/entities';
import { BaseResponseDto } from '@app/common/dto/base.response.dto'; import {
SpaceProductAllocationRepository,
SpaceRepository,
} from '@app/common/modules/space';
import {
SpaceModelEntity,
SpaceModelRepository,
} from '@app/common/modules/space-model';
import { SpaceProductAllocationEntity } from '@app/common/modules/space/entities/space-product-allocation.entity';
import { SpaceEntity } from '@app/common/modules/space/entities/space.entity';
import { SubspaceProductAllocationEntity } from '@app/common/modules/space/entities/subspace/subspace-product-allocation.entity';
import { SubspaceEntity } from '@app/common/modules/space/entities/subspace/subspace.entity';
import {
SubspaceProductAllocationRepository,
SubspaceRepository,
} from '@app/common/modules/space/repositories/subspace.repository';
import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { CommandBus } from '@nestjs/cqrs'; import { CommandBus } from '@nestjs/cqrs';
import { ProjectParam } from 'src/community/dtos';
import { DeviceService } from 'src/device/services';
import { ProjectService } from 'src/project/services';
import { ProcessTagDto } from 'src/tags/dtos'; import { ProcessTagDto } from 'src/tags/dtos';
import { SpaceModelProductAllocationService } from './space-model-product-allocation.service'; import { DataSource, In, QueryRunner, SelectQueryBuilder } from 'typeorm';
import { import {
PropogateDeleteSpaceModelCommand, PropogateDeleteSpaceModelCommand,
PropogateUpdateSpaceModelCommand, PropogateUpdateSpaceModelCommand,
PropogateUpdateSpaceModelProductAllocationCommand, PropogateUpdateSpaceModelProductAllocationCommand,
} from '../commands'; } from '../commands';
import { import {
SpaceProductAllocationRepository, CreateSpaceModelDto,
SpaceRepository, LinkSpacesToModelDto,
} from '@app/common/modules/space'; UpdateSpaceModelDto,
import { SpaceEntity } from '@app/common/modules/space/entities/space.entity'; } from '../dtos';
import { import { SpaceModelParam } from '../dtos/space-model-param';
SubspaceProductAllocationRepository, import { ISubspaceModelUpdates, IUpdatedSpaceAllocations } from '../interfaces';
SubspaceRepository, import { SpaceModelProductAllocationService } from './space-model-product-allocation.service';
} from '@app/common/modules/space/repositories/subspace.repository'; import { SubSpaceModelService } from './subspace';
import {
ORPHAN_COMMUNITY_NAME,
ORPHAN_SPACE_NAME,
} from '@app/common/constants/orphan-constant';
import { DeviceRepository } from '@app/common/modules/device/repositories';
import { SpaceProductAllocationEntity } from '@app/common/modules/space/entities/space-product-allocation.entity';
import { SubspaceEntity } from '@app/common/modules/space/entities/subspace/subspace.entity';
import { SubspaceProductAllocationEntity } from '@app/common/modules/space/entities/subspace/subspace-product-allocation.entity';
import { DeviceEntity } from '@app/common/modules/device/entities';
import {
ISingleSubspaceModel,
ISubspaceModelUpdates,
IUpdatedSpaceAllocations,
} from '../interfaces';
@Injectable() @Injectable()
export class SpaceModelService { export class SpaceModelService {
@ -60,6 +49,7 @@ export class SpaceModelService {
private readonly dataSource: DataSource, private readonly dataSource: DataSource,
private readonly spaceModelRepository: SpaceModelRepository, private readonly spaceModelRepository: SpaceModelRepository,
private readonly projectService: ProjectService, private readonly projectService: ProjectService,
private readonly deviceService: DeviceService,
private readonly subSpaceModelService: SubSpaceModelService, private readonly subSpaceModelService: SubSpaceModelService,
private commandBus: CommandBus, private commandBus: CommandBus,
private readonly spaceModelProductAllocationService: SpaceModelProductAllocationService, private readonly spaceModelProductAllocationService: SpaceModelProductAllocationService,
@ -67,7 +57,6 @@ export class SpaceModelService {
private readonly spaceProductAllocationRepository: SpaceProductAllocationRepository, private readonly spaceProductAllocationRepository: SpaceProductAllocationRepository,
private readonly subspaceRepository: SubspaceRepository, private readonly subspaceRepository: SubspaceRepository,
private readonly subspaceProductAllocationRepository: SubspaceProductAllocationRepository, private readonly subspaceProductAllocationRepository: SubspaceProductAllocationRepository,
private readonly deviceRepository: DeviceRepository,
) {} ) {}
async createSpaceModel( async createSpaceModel(
@ -161,7 +150,7 @@ export class SpaceModelService {
disabled: false, disabled: false,
}; };
pageable.include = pageable.include =
'subspaceModels.productAllocations,subspaceModelProductAllocations.tags,subspaceModels, productAllocations, productAllocations.tags'; 'subspaceModels.productAllocations,subspaceModelProductAllocations.tag,subspaceModelProductAllocations.product,subspaceModels, productAllocations, productAllocations.tag,productAllocations.product';
const queryBuilder = this.buildSpaceModelQuery(param.projectUuid); const queryBuilder = this.buildSpaceModelQuery(param.projectUuid);
@ -231,7 +220,7 @@ export class SpaceModelService {
spaceModel, spaceModel,
queryRunner, queryRunner,
param.projectUuid, param.projectUuid,
dto.tags, // dto.tags,
); );
} }
@ -386,10 +375,10 @@ export class SpaceModelService {
'productAllocations', 'productAllocations',
'subspaceModels', 'subspaceModels',
'productAllocations.product', 'productAllocations.product',
'productAllocations.tags', 'productAllocations.tag',
'subspaceModels.productAllocations', 'subspaceModels.productAllocations',
'subspaceModels.productAllocations.product', 'subspaceModels.productAllocations.product',
'subspaceModels.productAllocations.tags', 'subspaceModels.productAllocations.tag',
], ],
}); });
@ -408,10 +397,10 @@ export class SpaceModelService {
'subspaces', 'subspaces',
'productAllocations', 'productAllocations',
'productAllocations.product', 'productAllocations.product',
'productAllocations.tags', 'productAllocations.tag',
'subspaces.productAllocations', 'subspaces.productAllocations',
'subspaces.productAllocations.product', 'subspaces.productAllocations.product',
'subspaces.productAllocations.product.tags', 'subspaces.productAllocations.product.tag',
'community', 'community',
], ],
}); });
@ -433,7 +422,7 @@ export class SpaceModelService {
if (!hasDependencies && !space.spaceModel) { if (!hasDependencies && !space.spaceModel) {
await this.linkToSpace(space, spaceModel); await this.linkToSpace(space, spaceModel);
} else if (dto.overwrite) { } else if (dto.overwrite) {
await this.overwriteSpace(space, project); await this.removeSpaceOldSubspacesAndAllocations(space, project);
await this.linkToSpace(space, spaceModel); await this.linkToSpace(space, spaceModel);
} }
}), }),
@ -470,10 +459,9 @@ export class SpaceModelService {
space, space,
inheritedFromModel: modelAllocation, inheritedFromModel: modelAllocation,
product: modelAllocation.product, product: modelAllocation.product,
tags: modelAllocation.tags, tag: modelAllocation.tag,
}), }),
); );
if (queryRunner) { if (queryRunner) {
await queryRunner.manager.save( await queryRunner.manager.save(
SpaceProductAllocationEntity, SpaceProductAllocationEntity,
@ -491,23 +479,20 @@ export class SpaceModelService {
subSpaceModel: subspaceModel, subSpaceModel: subspaceModel,
space: space, space: space,
}); });
if (queryRunner) { if (queryRunner) {
await queryRunner.manager.save(SubspaceEntity, subspace); await queryRunner.manager.save(SubspaceEntity, subspace);
} else { } else {
await this.subspaceRepository.save(subspace); await this.subspaceRepository.save(subspace);
} }
const subspaceAllocations = subspaceModel.productAllocations.map( const subspaceAllocations = subspaceModel.productAllocations.map(
(modelAllocation) => (modelAllocation) =>
this.subspaceProductAllocationRepository.create({ this.subspaceProductAllocationRepository.create({
subspace, subspace,
inheritedFromModel: modelAllocation, inheritedFromModel: modelAllocation,
product: modelAllocation.product, product: modelAllocation.product,
tags: modelAllocation.tags, tag: modelAllocation.tag,
}), }),
); );
if (subspaceAllocations.length) { if (subspaceAllocations.length) {
if (queryRunner) { if (queryRunner) {
await queryRunner.manager.save( await queryRunner.manager.save(
@ -530,7 +515,7 @@ export class SpaceModelService {
} }
} }
async overwriteSpace( async removeSpaceOldSubspacesAndAllocations(
space: SpaceEntity, space: SpaceEntity,
project: ProjectEntity, project: ProjectEntity,
queryRunner?: QueryRunner, queryRunner?: QueryRunner,
@ -548,14 +533,6 @@ export class SpaceModelService {
? queryRunner.manager.getRepository(SubspaceProductAllocationEntity) ? queryRunner.manager.getRepository(SubspaceProductAllocationEntity)
: this.subspaceProductAllocationRepository; : this.subspaceProductAllocationRepository;
const spaceRepository = queryRunner
? queryRunner.manager.getRepository(SpaceEntity)
: this.spaceRepository;
const deviceRepository = queryRunner
? queryRunner.manager.getRepository(DeviceEntity)
: this.deviceRepository;
if (space.productAllocations.length) { if (space.productAllocations.length) {
await spaceProductAllocationRepository.delete({ await spaceProductAllocationRepository.delete({
uuid: In( uuid: In(
@ -584,26 +561,7 @@ export class SpaceModelService {
); );
if (space.devices.length > 0) { if (space.devices.length > 0) {
const orphanSpace = await spaceRepository.findOne({ this.deviceService.addDevicesToOrphanSpace(space, project, queryRunner);
where: {
community: {
name: `${ORPHAN_COMMUNITY_NAME}-${project.name}`,
},
spaceName: ORPHAN_SPACE_NAME,
},
});
if (!orphanSpace) {
throw new HttpException(
`Orphan space not found in community ${project.name}`,
HttpStatus.NOT_FOUND,
);
}
await deviceRepository.update(
{ uuid: In(space.devices.map((device) => device.uuid)) },
{ spaceDevice: orphanSpace },
);
} }
} catch (error) { } catch (error) {
throw new Error( throw new Error(
@ -612,19 +570,6 @@ export class SpaceModelService {
} }
} }
async validateName(modelName: string, projectUuid: string): Promise<void> {
const isModelExist = await this.spaceModelRepository.findOne({
where: { modelName, project: { uuid: projectUuid }, disabled: false },
});
if (isModelExist) {
throw new HttpException(
`Model name ${modelName} already exists in the project with UUID ${projectUuid}.`,
HttpStatus.CONFLICT,
);
}
}
async validateNameUsingQueryRunner( async validateNameUsingQueryRunner(
modelName: string, modelName: string,
projectUuid: string, projectUuid: string,
@ -726,14 +671,20 @@ export class SpaceModelService {
'subspaceModelProductAllocations', 'subspaceModelProductAllocations',
) )
.leftJoinAndSelect( .leftJoinAndSelect(
'subspaceModelProductAllocations.tags', 'subspaceModelProductAllocations.tag',
'subspaceModelTags', 'subspaceModelTag',
)
.leftJoinAndSelect(
'subspaceModelProductAllocations.product',
'subspaceModelProduct',
) )
.leftJoinAndSelect('subspaceModelTags.product', 'subspaceModelTagProduct')
.leftJoinAndSelect('spaceModel.productAllocations', 'productAllocations') .leftJoinAndSelect('spaceModel.productAllocations', 'productAllocations')
.leftJoinAndSelect('productAllocations.product', 'allocatedProduct') .leftJoinAndSelect('productAllocations.product', 'allocatedProduct')
.leftJoinAndSelect('productAllocations.tags', 'productTags') .leftJoinAndSelect('productAllocations.tag', 'spaceModelTag')
.leftJoinAndSelect('productTags.product', 'productTagProduct') .leftJoinAndSelect(
'productAllocations.product',
'productAllocationsProduct',
)
.where('spaceModel.disabled = false') .where('spaceModel.disabled = false')
.andWhere('spaceModel.project = :projectUuid', { projectUuid }); .andWhere('spaceModel.project = :projectUuid', { projectUuid });
} }
@ -753,42 +704,12 @@ export class SpaceModelService {
updatedAt: subspace.updatedAt, updatedAt: subspace.updatedAt,
subspaceName: subspace.subspaceName, subspaceName: subspace.subspaceName,
disabled: subspace.disabled, disabled: subspace.disabled,
tags: this.extractTags(subspace.productAllocations), productAllocations: subspace.productAllocations,
})), })),
tags: this.extractTags(spaceModel.productAllocations), productAllocations: spaceModel.productAllocations,
})); }));
} }
private extractTags(
productAllocations:
| SpaceModelProductAllocationEntity[]
| SubspaceModelProductAllocationEntity[]
| undefined,
): any[] {
if (!productAllocations) return [];
return productAllocations
.flatMap((allocation) => allocation.tags ?? [])
.map((tag) => ({
uuid: tag.uuid,
createdAt: tag.createdAt,
updatedAt: tag.updatedAt,
name: tag.name,
disabled: tag.disabled,
product: tag.product
? {
uuid: tag.product.uuid,
createdAt: tag.product.createdAt,
updatedAt: tag.product.updatedAt,
catName: tag.product.catName,
prodId: tag.product.prodId,
name: tag.product.name,
prodType: tag.product.prodType,
}
: null,
}));
}
private formatSpaceModelResponse(spaceModel: SpaceModelEntity): any { private formatSpaceModelResponse(spaceModel: SpaceModelEntity): any {
return { return {
uuid: spaceModel.uuid, uuid: spaceModel.uuid,
@ -803,9 +724,9 @@ export class SpaceModelService {
updatedAt: subspace.updatedAt, updatedAt: subspace.updatedAt,
subspaceName: subspace.subspaceName, subspaceName: subspace.subspaceName,
disabled: subspace.disabled, disabled: subspace.disabled,
tags: this.extractTags(subspace.productAllocations), productAllocations: subspace.productAllocations,
})) ?? [], })) ?? [],
tags: this.extractTags(spaceModel.productAllocations), productAllocations: spaceModel.productAllocations,
}; };
} }
} }

View File

@ -9,10 +9,9 @@ import {
} from '@app/common/modules/space-model'; } from '@app/common/modules/space-model';
import { NewTagEntity } from '@app/common/modules/tag'; import { NewTagEntity } from '@app/common/modules/tag';
import { HttpException, HttpStatus, Injectable } from '@nestjs/common'; import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { ModifyTagModelDto } from 'src/space-model/dtos';
import { ISingleSubspaceModel } from 'src/space-model/interfaces'; import { ISingleSubspaceModel } from 'src/space-model/interfaces';
import { IUpdatedAllocations } from 'src/space-model/interfaces/subspace-product-allocation-update-result.interface'; import { IUpdatedAllocations } from 'src/space-model/interfaces/subspace-product-allocation-update-result.interface';
import { ProcessTagDto } from 'src/tags/dtos'; import { ModifyTagDto } from 'src/space/dtos/tag/modify-tag.dto';
import { TagService as NewTagService } from 'src/tags/services'; import { TagService as NewTagService } from 'src/tags/services';
import { In, QueryRunner } from 'typeorm'; import { In, QueryRunner } from 'typeorm';
@ -31,172 +30,159 @@ export class SubspaceModelProductAllocationService {
queryRunner?: QueryRunner, queryRunner?: QueryRunner,
spaceAllocationsToExclude?: SpaceModelProductAllocationEntity[], spaceAllocationsToExclude?: SpaceModelProductAllocationEntity[],
): Promise<IUpdatedAllocations[]> { ): Promise<IUpdatedAllocations[]> {
try { // try {
const updatedAllocations: IUpdatedAllocations[] = []; const updatedAllocations: IUpdatedAllocations[] = [];
return updatedAllocations;
const allocations: SubspaceModelProductAllocationEntity[] = []; // const allocations: SubspaceModelProductAllocationEntity[] = [];
// for (const tag of tags) {
for (const tag of tags) { // // Step 1: Check if this specific tag is already allocated at the space level
// Step 1: Check if this specific tag is already allocated at the space level // const existingTagInSpaceModel = await (queryRunner
const existingTagInSpaceModel = await (queryRunner // ? queryRunner.manager.findOne(SpaceModelProductAllocationEntity, {
? queryRunner.manager.findOne(SpaceModelProductAllocationEntity, { // where: {
where: { // spaceModel: {
spaceModel: { // uuid: spaceModel.uuid,
uuid: spaceModel.uuid, // }, // Check at the space level
}, // Check at the space level // tags: { uuid: tag.uuid }, // Check for the specific tag
tags: { uuid: tag.uuid }, // Check for the specific tag // },
}, // relations: ['tags'],
relations: ['tags'], // })
}) // : this.spaceModelAllocationRepository.findOne({
: this.spaceModelAllocationRepository.findOne({ // where: {
where: { // spaceModel: {
spaceModel: { // uuid: spaceModel.uuid,
uuid: spaceModel.uuid, // },
}, // tags: { uuid: tag.uuid },
tags: { uuid: tag.uuid }, // },
}, // relations: ['tags', 'product'],
relations: ['tags', 'product'], // }));
})); // const isExcluded = spaceAllocationsToExclude?.some(
// (excludedAllocation) =>
const isExcluded = spaceAllocationsToExclude?.some( // excludedAllocation.product.uuid === tag.product.uuid &&
(excludedAllocation) => // excludedAllocation.tags.some((t) => t.uuid === tag.uuid),
excludedAllocation.product.uuid === tag.product.uuid && // );
excludedAllocation.tags.some((t) => t.uuid === tag.uuid), // // If tag is found at the space level, prevent allocation at the subspace level
); // if (!isExcluded && existingTagInSpaceModel) {
// throw new HttpException(
// If tag is found at the space level, prevent allocation at the subspace level // `Tag ${tag.uuid} (Product: ${tag.product.uuid}) is already allocated at the space level (${subspaceModel.spaceModel.uuid}). Cannot allocate the same tag in a subspace.`,
if (!isExcluded && existingTagInSpaceModel) { // HttpStatus.BAD_REQUEST,
throw new HttpException( // );
`Tag ${tag.uuid} (Product: ${tag.product.uuid}) is already allocated at the space level (${subspaceModel.spaceModel.uuid}). Cannot allocate the same tag in a subspace.`, // }
HttpStatus.BAD_REQUEST, // // Check if this specific tag is already allocated within another subspace of the same space
); // const existingTagInSameSpace = await (queryRunner
} // ? queryRunner.manager.findOne(SubspaceModelProductAllocationEntity, {
// where: {
// Check if this specific tag is already allocated within another subspace of the same space // product: { uuid: tag.product.uuid },
const existingTagInSameSpace = await (queryRunner // subspaceModel: { spaceModel: subspaceModel.spaceModel },
? queryRunner.manager.findOne(SubspaceModelProductAllocationEntity, { // tags: { uuid: tag.uuid }, // Ensure the exact tag is checked
where: { // },
product: { uuid: tag.product.uuid }, // relations: ['subspaceModel', 'tags'],
subspaceModel: { spaceModel: subspaceModel.spaceModel }, // })
tags: { uuid: tag.uuid }, // Ensure the exact tag is checked // : this.subspaceModelProductAllocationRepository.findOne({
}, // where: {
relations: ['subspaceModel', 'tags'], // product: { uuid: tag.product.uuid },
}) // subspaceModel: { spaceModel: subspaceModel.spaceModel },
: this.subspaceModelProductAllocationRepository.findOne({ // tags: { uuid: tag.uuid },
where: { // },
product: { uuid: tag.product.uuid }, // relations: ['subspaceModel', 'tags'],
subspaceModel: { spaceModel: subspaceModel.spaceModel }, // }));
tags: { uuid: tag.uuid }, // // Prevent duplicate allocation if tag exists in another subspace of the same space
}, // if (
relations: ['subspaceModel', 'tags'], // existingTagInSameSpace &&
})); // existingTagInSameSpace.subspaceModel.uuid !== subspaceModel.uuid
// ) {
// Prevent duplicate allocation if tag exists in another subspace of the same space // throw new HttpException(
if ( // `Tag ${tag.uuid} (Product: ${tag.product.uuid}) is already allocated in another subspace (${existingTagInSameSpace.subspaceModel.uuid}) within the same space (${subspaceModel.spaceModel.uuid}).`,
existingTagInSameSpace && // HttpStatus.BAD_REQUEST,
existingTagInSameSpace.subspaceModel.uuid !== subspaceModel.uuid // );
) { // }
throw new HttpException( // //Check if there are existing allocations for this product in the subspace
`Tag ${tag.uuid} (Product: ${tag.product.uuid}) is already allocated in another subspace (${existingTagInSameSpace.subspaceModel.uuid}) within the same space (${subspaceModel.spaceModel.uuid}).`, // const existingAllocationsForProduct = await (queryRunner
HttpStatus.BAD_REQUEST, // ? queryRunner.manager.find(SubspaceModelProductAllocationEntity, {
); // where: {
} // subspaceModel: { uuid: subspaceModel.uuid },
// product: { uuid: tag.product.uuid },
//Check if there are existing allocations for this product in the subspace // },
const existingAllocationsForProduct = await (queryRunner // relations: ['tags'],
? queryRunner.manager.find(SubspaceModelProductAllocationEntity, { // })
where: { // : this.subspaceModelProductAllocationRepository.find({
subspaceModel: { uuid: subspaceModel.uuid }, // where: {
product: { uuid: tag.product.uuid }, // subspaceModel: { uuid: subspaceModel.uuid },
}, // product: { uuid: tag.product.uuid },
relations: ['tags'], // },
}) // relations: ['tags'],
: this.subspaceModelProductAllocationRepository.find({ // }));
where: { // //Flatten all existing tags for this product in the subspace
subspaceModel: { uuid: subspaceModel.uuid }, // const existingTagsForProduct = existingAllocationsForProduct.flatMap(
product: { uuid: tag.product.uuid }, // (allocation) => allocation.tags,
}, // );
relations: ['tags'], // // Check if the tag is already assigned to the same product in this subspace
})); // const isDuplicateTag = existingTagsForProduct.some(
// (existingTag) => existingTag.uuid === tag.uuid,
//Flatten all existing tags for this product in the subspace // );
const existingTagsForProduct = existingAllocationsForProduct.flatMap( // if (isDuplicateTag) {
(allocation) => allocation.tags, // throw new HttpException(
); // `Tag ${tag.uuid} is already allocated to product ${tag.product.uuid} within this subspace (${subspaceModel.uuid}).`,
// HttpStatus.BAD_REQUEST,
// Check if the tag is already assigned to the same product in this subspace // );
const isDuplicateTag = existingTagsForProduct.some( // }
(existingTag) => existingTag.uuid === tag.uuid, // // If no existing allocation, create a new one
); // if (existingAllocationsForProduct.length === 0) {
// const allocation = queryRunner
if (isDuplicateTag) { // ? queryRunner.manager.create(SubspaceModelProductAllocationEntity, {
throw new HttpException( // subspaceModel,
`Tag ${tag.uuid} is already allocated to product ${tag.product.uuid} within this subspace (${subspaceModel.uuid}).`, // product: tag.product,
HttpStatus.BAD_REQUEST, // tags: [tag],
); // })
} // : this.subspaceModelProductAllocationRepository.create({
// subspaceModel,
// If no existing allocation, create a new one // product: tag.product,
if (existingAllocationsForProduct.length === 0) { // tags: [tag],
const allocation = queryRunner // });
? queryRunner.manager.create(SubspaceModelProductAllocationEntity, { // allocations.push(allocation);
subspaceModel, // } else {
product: tag.product, // //If allocation exists, add the tag to it
tags: [tag], // existingAllocationsForProduct[0].tags.push(tag);
}) // if (queryRunner) {
: this.subspaceModelProductAllocationRepository.create({ // await queryRunner.manager.save(
subspaceModel, // SubspaceModelProductAllocationEntity,
product: tag.product, // existingAllocationsForProduct[0],
tags: [tag], // );
}); // } else {
allocations.push(allocation); // await this.subspaceModelProductAllocationRepository.save(
} else { // existingAllocationsForProduct[0],
//If allocation exists, add the tag to it // );
existingAllocationsForProduct[0].tags.push(tag); // }
if (queryRunner) { // updatedAllocations.push({
await queryRunner.manager.save( // allocation: existingAllocationsForProduct[0],
SubspaceModelProductAllocationEntity, // tagsAdded: [tag],
existingAllocationsForProduct[0], // });
); // }
} else { // }
await this.subspaceModelProductAllocationRepository.save( // // Save newly created allocations
existingAllocationsForProduct[0], // if (allocations.length > 0) {
); // if (queryRunner) {
} // await queryRunner.manager.save(
updatedAllocations.push({ // SubspaceModelProductAllocationEntity,
allocation: existingAllocationsForProduct[0], // allocations,
tagsAdded: [tag], // );
}); // } else {
} // await this.subspaceModelProductAllocationRepository.save(allocations);
} // }
// allocations.forEach((allocation) => {
// Save newly created allocations // updatedAllocations.push({ newAllocation: allocation });
if (allocations.length > 0) { // });
if (queryRunner) { // }
await queryRunner.manager.save( // return updatedAllocations;
SubspaceModelProductAllocationEntity, // } catch (error) {
allocations, // throw new HttpException(
); // `An unexpected error occurred while creating subspace product allocations ${error}`,
} else { // HttpStatus.INTERNAL_SERVER_ERROR,
await this.subspaceModelProductAllocationRepository.save(allocations); // );
} // }
allocations.forEach((allocation) => {
updatedAllocations.push({ newAllocation: allocation });
});
}
return updatedAllocations;
} catch (error) {
throw new HttpException(
`An unexpected error occurred while creating subspace product allocations ${error}`,
HttpStatus.INTERNAL_SERVER_ERROR,
);
}
} }
async processDeleteActions( async processDeleteActions(
dtos: ModifyTagModelDto[], dtos: ModifyTagDto[],
queryRunner: QueryRunner, queryRunner: QueryRunner,
): Promise<SubspaceModelProductAllocationEntity[]> { ): Promise<SubspaceModelProductAllocationEntity[]> {
try { try {
@ -205,7 +191,7 @@ export class SubspaceModelProductAllocationService {
} }
const tagUuidsToDelete = dtos const tagUuidsToDelete = dtos
.filter((dto) => dto.action === ModifyAction.DELETE && dto.tagUuid) // .filter((dto) => dto.action === ModifyAction.DELETE && dto.tagUuid)
.map((dto) => dto.tagUuid); .map((dto) => dto.tagUuid);
if (tagUuidsToDelete.length === 0) return []; if (tagUuidsToDelete.length === 0) return [];
@ -213,8 +199,7 @@ export class SubspaceModelProductAllocationService {
const allocationsToUpdate = await queryRunner.manager.find( const allocationsToUpdate = await queryRunner.manager.find(
SubspaceModelProductAllocationEntity, SubspaceModelProductAllocationEntity,
{ {
where: { tags: { uuid: In(tagUuidsToDelete) } }, where: { tag: In(tagUuidsToDelete) },
relations: ['tags'],
}, },
); );
@ -224,20 +209,18 @@ export class SubspaceModelProductAllocationService {
const allocationUpdates: SubspaceModelProductAllocationEntity[] = []; const allocationUpdates: SubspaceModelProductAllocationEntity[] = [];
for (const allocation of allocationsToUpdate) { for (const allocation of allocationsToUpdate) {
const updatedTags = allocation.tags.filter( // const updatedTags = allocation.tags.filter(
(tag) => !tagUuidsToDelete.includes(tag.uuid), // (tag) => !tagUuidsToDelete.includes(tag.uuid),
); // );
// if (updatedTags.length === allocation.tags.length) {
if (updatedTags.length === allocation.tags.length) { // continue;
continue; // }
} // if (updatedTags.length === 0) {
// deletedAllocations.push(allocation);
if (updatedTags.length === 0) { // } else {
deletedAllocations.push(allocation); // allocation.tags = updatedTags;
} else { // allocationUpdates.push(allocation);
allocation.tags = updatedTags; // }
allocationUpdates.push(allocation);
}
} }
if (allocationUpdates.length > 0) { if (allocationUpdates.length > 0) {
@ -280,254 +263,255 @@ export class SubspaceModelProductAllocationService {
projectUuid: string, projectUuid: string,
queryRunner: QueryRunner, queryRunner: QueryRunner,
spaceModel: SpaceModelEntity, spaceModel: SpaceModelEntity,
spaceTagUpdateDtos?: ModifyTagModelDto[], spaceTagUpdateDtos?: ModifyTagDto[],
): Promise<IUpdatedAllocations[]> { ) {
// : Promise<IUpdatedAllocations[]>
const spaceAllocationToExclude: SpaceModelProductAllocationEntity[] = []; const spaceAllocationToExclude: SpaceModelProductAllocationEntity[] = [];
const updatedAllocations: IUpdatedAllocations[] = []; const updatedAllocations: IUpdatedAllocations[] = [];
return updatedAllocations;
// for (const subspaceModel of subspaceModels) {
// const tagDtos = subspaceModel.tags;
// if (tagDtos.length > 0) {
// const tagsToAddDto: ProcessTagDto[] = tagDtos
// .filter((dto) => dto.action === ModifyAction.ADD)
// .map((dto) => ({
// name: dto.name,
// productUuid: dto.productUuid,
// uuid: dto.newTagUuid,
// }));
for (const subspaceModel of subspaceModels) { // const tagsToDeleteDto = tagDtos.filter(
const tagDtos = subspaceModel.tags; // (dto) => dto.action === ModifyAction.DELETE,
if (tagDtos.length > 0) { // );
const tagsToAddDto: ProcessTagDto[] = tagDtos
.filter((dto) => dto.action === ModifyAction.ADD)
.map((dto) => ({
name: dto.name,
productUuid: dto.productUuid,
uuid: dto.newTagUuid,
}));
const tagsToDeleteDto = tagDtos.filter( // if (tagsToAddDto.length > 0) {
(dto) => dto.action === ModifyAction.DELETE, // let processedTags = await this.tagService.processTags(
); // tagsToAddDto,
// projectUuid,
// queryRunner,
// );
if (tagsToAddDto.length > 0) { // for (const subspaceDto of subspaceModels) {
let processedTags = await this.tagService.processTags( // if (
tagsToAddDto, // subspaceDto !== subspaceModel &&
projectUuid, // subspaceDto.action === ModifyAction.UPDATE &&
queryRunner, // subspaceDto.tags
); // ) {
// // Tag is deleted from one subspace and added in another subspace
// const deletedTags = subspaceDto.tags.filter(
// (tagDto) =>
// tagDto.action === ModifyAction.DELETE &&
// processedTags.some((tag) => tag.uuid === tagDto.tagUuid),
// );
for (const subspaceDto of subspaceModels) { // for (const deletedTag of deletedTags) {
if ( // const allocation = await queryRunner.manager.findOne(
subspaceDto !== subspaceModel && // SubspaceModelProductAllocationEntity,
subspaceDto.action === ModifyAction.UPDATE && // {
subspaceDto.tags // where: {
) { // tags: {
// Tag is deleted from one subspace and added in another subspace // uuid: deletedTag.tagUuid,
const deletedTags = subspaceDto.tags.filter( // },
(tagDto) => // subspaceModel: {
tagDto.action === ModifyAction.DELETE && // uuid: subspaceDto.subspaceModel.uuid,
processedTags.some((tag) => tag.uuid === tagDto.tagUuid), // },
); // },
// relations: ['tags', 'product', 'subspaceModel'],
// },
// );
// if (allocation) {
// const isCommonTag = allocation.tags.some(
// (tag) => tag.uuid === deletedTag.tagUuid,
// );
for (const deletedTag of deletedTags) { // if (allocation && isCommonTag) {
const allocation = await queryRunner.manager.findOne( // const tagEntity = allocation.tags.find(
SubspaceModelProductAllocationEntity, // (tag) => tag.uuid === deletedTag.tagUuid,
{ // );
where: {
tags: {
uuid: deletedTag.tagUuid,
},
subspaceModel: {
uuid: subspaceDto.subspaceModel.uuid,
},
},
relations: ['tags', 'product', 'subspaceModel'],
},
);
if (allocation) {
const isCommonTag = allocation.tags.some(
(tag) => tag.uuid === deletedTag.tagUuid,
);
if (allocation && isCommonTag) { // allocation.tags = allocation.tags.filter(
const tagEntity = allocation.tags.find( // (tag) => tag.uuid !== deletedTag.tagUuid,
(tag) => tag.uuid === deletedTag.tagUuid, // );
);
allocation.tags = allocation.tags.filter( // updatedAllocations.push({
(tag) => tag.uuid !== deletedTag.tagUuid, // allocation,
); // tagsRemoved: [tagEntity],
// });
updatedAllocations.push({ // await queryRunner.manager.save(allocation);
allocation,
tagsRemoved: [tagEntity],
});
await queryRunner.manager.save(allocation); // const productAllocationExistInSubspace =
// await queryRunner.manager.findOne(
// SubspaceModelProductAllocationEntity,
// {
// where: {
// subspaceModel: {
// uuid: subspaceDto.subspaceModel.uuid,
// },
// product: { uuid: allocation.product.uuid },
// },
// relations: ['tags'],
// },
// );
const productAllocationExistInSubspace = // if (productAllocationExistInSubspace) {
await queryRunner.manager.findOne( // productAllocationExistInSubspace.tags.push(tagEntity);
SubspaceModelProductAllocationEntity,
{
where: {
subspaceModel: {
uuid: subspaceDto.subspaceModel.uuid,
},
product: { uuid: allocation.product.uuid },
},
relations: ['tags'],
},
);
if (productAllocationExistInSubspace) { // updatedAllocations.push({
productAllocationExistInSubspace.tags.push(tagEntity); // allocation: productAllocationExistInSubspace,
// tagsAdded: [tagEntity],
// });
updatedAllocations.push({ // await queryRunner.manager.save(
allocation: productAllocationExistInSubspace, // productAllocationExistInSubspace,
tagsAdded: [tagEntity], // );
}); // } else {
// const newProductAllocation = queryRunner.manager.create(
// SubspaceModelProductAllocationEntity,
// {
// subspaceModel: subspaceModel.subspaceModel,
// product: allocation.product,
// tags: [tagEntity],
// },
// );
await queryRunner.manager.save( // updatedAllocations.push({
productAllocationExistInSubspace, // allocation: newProductAllocation,
); // });
} else {
const newProductAllocation = queryRunner.manager.create(
SubspaceModelProductAllocationEntity,
{
subspaceModel: subspaceModel.subspaceModel,
product: allocation.product,
tags: [tagEntity],
},
);
updatedAllocations.push({ // await queryRunner.manager.save(newProductAllocation);
allocation: newProductAllocation, // }
});
await queryRunner.manager.save(newProductAllocation); // // Remove the tag from processedTags to prevent duplication
} // processedTags = processedTags.filter(
// (tag) => tag.uuid !== deletedTag.tagUuid,
// );
// Remove the tag from processedTags to prevent duplication // // Remove the tag from subspaceDto.tags to ensure it's not processed again while processing other dtos.
processedTags = processedTags.filter( // subspaceDto.tags = subspaceDto.tags.filter(
(tag) => tag.uuid !== deletedTag.tagUuid, // (tagDto) => tagDto.tagUuid !== deletedTag.tagUuid,
); // );
// }
// }
// }
// }
// if (
// subspaceDto !== subspaceModel &&
// subspaceDto.action === ModifyAction.DELETE
// ) {
// const allocation = await queryRunner.manager.findOne(
// SubspaceModelProductAllocationEntity,
// {
// where: {
// subspaceModel: { uuid: subspaceDto.subspaceModel.uuid },
// },
// relations: ['tags'],
// },
// );
// Remove the tag from subspaceDto.tags to ensure it's not processed again while processing other dtos. // const repeatedTags = allocation?.tags.filter((tag) =>
subspaceDto.tags = subspaceDto.tags.filter( // processedTags.some(
(tagDto) => tagDto.tagUuid !== deletedTag.tagUuid, // (processedTag) => processedTag.uuid === tag.uuid,
); // ),
} // );
} // if (repeatedTags.length > 0) {
} // allocation.tags = allocation.tags.filter(
} // (tag) =>
if ( // !repeatedTags.some(
subspaceDto !== subspaceModel && // (repeatedTag) => repeatedTag.uuid === tag.uuid,
subspaceDto.action === ModifyAction.DELETE // ),
) { // );
const allocation = await queryRunner.manager.findOne(
SubspaceModelProductAllocationEntity,
{
where: {
subspaceModel: { uuid: subspaceDto.subspaceModel.uuid },
},
relations: ['tags'],
},
);
const repeatedTags = allocation?.tags.filter((tag) => // updatedAllocations.push({
processedTags.some( // allocation: allocation,
(processedTag) => processedTag.uuid === tag.uuid, // tagsRemoved: repeatedTags,
), // });
);
if (repeatedTags.length > 0) {
allocation.tags = allocation.tags.filter(
(tag) =>
!repeatedTags.some(
(repeatedTag) => repeatedTag.uuid === tag.uuid,
),
);
updatedAllocations.push({ // await queryRunner.manager.save(allocation);
allocation: allocation,
tagsRemoved: repeatedTags,
});
await queryRunner.manager.save(allocation); // const productAllocationExistInSubspace =
// await queryRunner.manager.findOne(
// SubspaceModelProductAllocationEntity,
// {
// where: {
// subspaceModel: { uuid: subspaceDto.subspaceModel.uuid },
// product: { uuid: allocation.product.uuid },
// },
// relations: ['tags'],
// },
// );
const productAllocationExistInSubspace = // if (productAllocationExistInSubspace) {
await queryRunner.manager.findOne( // updatedAllocations.push({
SubspaceModelProductAllocationEntity, // allocation: productAllocationExistInSubspace,
{ // tagsAdded: repeatedTags,
where: { // });
subspaceModel: { uuid: subspaceDto.subspaceModel.uuid },
product: { uuid: allocation.product.uuid },
},
relations: ['tags'],
},
);
if (productAllocationExistInSubspace) { // productAllocationExistInSubspace.tags.push(...repeatedTags);
updatedAllocations.push({ // await queryRunner.manager.save(
allocation: productAllocationExistInSubspace, // productAllocationExistInSubspace,
tagsAdded: repeatedTags, // );
}); // } else {
// const newProductAllocation = queryRunner.manager.create(
// SubspaceModelProductAllocationEntity,
// {
// subspaceModel: subspaceModel.subspaceModel,
// product: allocation.product,
// tags: repeatedTags,
// },
// );
productAllocationExistInSubspace.tags.push(...repeatedTags); // updatedAllocations.push({
await queryRunner.manager.save( // newAllocation: newProductAllocation,
productAllocationExistInSubspace, // });
);
} else {
const newProductAllocation = queryRunner.manager.create(
SubspaceModelProductAllocationEntity,
{
subspaceModel: subspaceModel.subspaceModel,
product: allocation.product,
tags: repeatedTags,
},
);
updatedAllocations.push({ // await queryRunner.manager.save(newProductAllocation);
newAllocation: newProductAllocation, // }
}); // }
// }
// }
// if (spaceTagUpdateDtos) {
// const deletedSpaceTags = spaceTagUpdateDtos.filter(
// (tagDto) =>
// tagDto.action === ModifyAction.DELETE &&
// processedTags.some((tag) => tag.uuid === tagDto.tagUuid),
// );
// for (const deletedTag of deletedSpaceTags) {
// const allocation = await queryRunner.manager.findOne(
// SpaceModelProductAllocationEntity,
// {
// where: {
// spaceModel: { uuid: spaceModel.uuid },
// tags: { uuid: deletedTag.tagUuid },
// },
// relations: ['tags', 'product'],
// },
// );
await queryRunner.manager.save(newProductAllocation); // if (
} // allocation &&
} // allocation.tags.some((tag) => tag.uuid === deletedTag.tagUuid)
} // ) {
} // spaceAllocationToExclude.push(allocation);
if (spaceTagUpdateDtos) { // }
const deletedSpaceTags = spaceTagUpdateDtos.filter( // }
(tagDto) => // }
tagDto.action === ModifyAction.DELETE &&
processedTags.some((tag) => tag.uuid === tagDto.tagUuid),
);
for (const deletedTag of deletedSpaceTags) {
const allocation = await queryRunner.manager.findOne(
SpaceModelProductAllocationEntity,
{
where: {
spaceModel: { uuid: spaceModel.uuid },
tags: { uuid: deletedTag.tagUuid },
},
relations: ['tags', 'product'],
},
);
if ( // // Create new product allocations
allocation && // const newAllocations = await this.createProductAllocations(
allocation.tags.some((tag) => tag.uuid === deletedTag.tagUuid) // subspaceModel.subspaceModel,
) { // spaceModel,
spaceAllocationToExclude.push(allocation); // processedTags,
} // queryRunner,
} // spaceAllocationToExclude,
} // );
// return [...updatedAllocations, ...newAllocations];
// Create new product allocations // }
const newAllocations = await this.createProductAllocations( // if (tagsToDeleteDto.length > 0) {
subspaceModel.subspaceModel, // await this.processDeleteActions(tagsToDeleteDto, queryRunner);
spaceModel, // }
processedTags, // }
queryRunner, // }
spaceAllocationToExclude,
);
return [...updatedAllocations, ...newAllocations];
}
if (tagsToDeleteDto.length > 0) {
await this.processDeleteActions(tagsToDeleteDto, queryRunner);
}
}
}
} }
async clearAllAllocations(subspaceIds: string[], queryRunner: QueryRunner) { async clearAllAllocations(subspaceIds: string[], queryRunner: QueryRunner) {

View File

@ -1,3 +1,4 @@
import { ModifyAction } from '@app/common/constants/modify-action.enum';
import { import {
SpaceModelEntity, SpaceModelEntity,
SpaceModelProductAllocationEntity, SpaceModelProductAllocationEntity,
@ -5,21 +6,21 @@ import {
SubspaceModelProductAllocationEntity, SubspaceModelProductAllocationEntity,
SubspaceModelRepository, SubspaceModelRepository,
} from '@app/common/modules/space-model'; } from '@app/common/modules/space-model';
import { SpaceEntity } from '@app/common/modules/space/entities/space.entity';
import { HttpException, HttpStatus, Injectable } from '@nestjs/common'; import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { CreateSubspaceModelDto, ModifyTagModelDto } from '../../dtos';
import { In, Not, QueryFailedError, QueryRunner } from 'typeorm';
import { ModifySubspaceModelDto } from 'src/space-model/dtos/subspaces-model-dtos'; import { ModifySubspaceModelDto } from 'src/space-model/dtos/subspaces-model-dtos';
import { ModifyAction } from '@app/common/constants/modify-action.enum';
import { ProcessTagDto } from 'src/tags/dtos';
import { TagService } from 'src/tags/services';
import { SubspaceModelProductAllocationService } from './subspace-model-product-allocation.service';
import { import {
IRelocatedAllocation, IRelocatedAllocation,
ISingleSubspaceModel, ISingleSubspaceModel,
ISubspaceModelUpdates, ISubspaceModelUpdates,
} from 'src/space-model/interfaces'; } from 'src/space-model/interfaces';
import { SpaceEntity } from '@app/common/modules/space/entities/space.entity'; import { ModifyTagDto } from 'src/space/dtos/tag/modify-tag.dto';
import { SubSpaceService } from 'src/space/services/subspace'; import { SubSpaceService } from 'src/space/services/subspace';
import { ProcessTagDto } from 'src/tags/dtos';
import { TagService } from 'src/tags/services';
import { In, Not, QueryFailedError, QueryRunner } from 'typeorm';
import { CreateSubspaceModelDto } from '../../dtos';
import { SubspaceModelProductAllocationService } from './subspace-model-product-allocation.service';
@Injectable() @Injectable()
export class SubSpaceModelService { export class SubSpaceModelService {
@ -117,7 +118,7 @@ export class SubSpaceModelService {
spaceModel: SpaceModelEntity, spaceModel: SpaceModelEntity,
queryRunner: QueryRunner, queryRunner: QueryRunner,
projectUuid: string, projectUuid: string,
spaceTagUpdateDtos?: ModifyTagModelDto[], spaceTagUpdateDtos?: ModifyTagDto[],
spaces?: SpaceEntity[], spaces?: SpaceEntity[],
): Promise<ISubspaceModelUpdates> { ): Promise<ISubspaceModelUpdates> {
try { try {
@ -152,7 +153,7 @@ export class SubSpaceModelService {
projectUuid, projectUuid,
queryRunner, queryRunner,
spaceModel, spaceModel,
spaceTagUpdateDtos, // spaceTagUpdateDtos,
); );
const deletedSubspaces = await this.deleteSubspaceModels( const deletedSubspaces = await this.deleteSubspaceModels(
@ -188,7 +189,7 @@ export class SubSpaceModelService {
deleteDtos: ModifySubspaceModelDto[], deleteDtos: ModifySubspaceModelDto[],
queryRunner: QueryRunner, queryRunner: QueryRunner,
spaceModel: SpaceModelEntity, spaceModel: SpaceModelEntity,
spaceTagUpdateDtos?: ModifyTagModelDto[], spaceTagUpdateDtos?: ModifyTagDto[],
): Promise<ISingleSubspaceModel[]> { ): Promise<ISingleSubspaceModel[]> {
try { try {
if (!deleteDtos || deleteDtos.length === 0) { if (!deleteDtos || deleteDtos.length === 0) {
@ -230,92 +231,82 @@ export class SubSpaceModelService {
>(); >();
for (const allocation of allocationsToRemove) { for (const allocation of allocationsToRemove) {
const product = allocation.product; // const product = allocation.product;
const tags = allocation.tags; // const tags = allocation.tags;
const subspaceUuid = allocation.subspaceModel.uuid; // const subspaceUuid = allocation.subspaceModel.uuid;
const spaceAllocationKey = `${spaceModel.uuid}-${product.uuid}`; // const spaceAllocationKey = `${spaceModel.uuid}-${product.uuid}`;
// if (!spaceAllocationsMap.has(spaceAllocationKey)) {
if (!spaceAllocationsMap.has(spaceAllocationKey)) { // const spaceAllocation = await queryRunner.manager.findOne(
const spaceAllocation = await queryRunner.manager.findOne( // SpaceModelProductAllocationEntity,
SpaceModelProductAllocationEntity, // {
{ // where: {
where: { // spaceModel: { uuid: spaceModel.uuid },
spaceModel: { uuid: spaceModel.uuid }, // product: { uuid: product.uuid },
product: { uuid: product.uuid }, // },
}, // relations: ['tags'],
relations: ['tags'], // },
}, // );
); // if (spaceAllocation) {
if (spaceAllocation) { // spaceAllocationsMap.set(spaceAllocationKey, spaceAllocation);
spaceAllocationsMap.set(spaceAllocationKey, spaceAllocation); // }
} // }
} // const movedToAlreadyExistingSpaceAllocations: IRelocatedAllocation[] =
// [];
const movedToAlreadyExistingSpaceAllocations: IRelocatedAllocation[] = // const spaceAllocation = spaceAllocationsMap.get(spaceAllocationKey);
[]; // if (spaceAllocation) {
const spaceAllocation = spaceAllocationsMap.get(spaceAllocationKey); // const existingTagUuids = new Set(
// spaceAllocation.tags.map((tag) => tag.uuid),
if (spaceAllocation) { // );
const existingTagUuids = new Set( // const newTags = tags.filter(
spaceAllocation.tags.map((tag) => tag.uuid), // (tag) => !existingTagUuids.has(tag.uuid),
); // );
const newTags = tags.filter( // if (newTags.length > 0) {
(tag) => !existingTagUuids.has(tag.uuid), // movedToAlreadyExistingSpaceAllocations.push({
); // tags: newTags,
// allocation: spaceAllocation,
if (newTags.length > 0) { // });
movedToAlreadyExistingSpaceAllocations.push({ // spaceAllocation.tags.push(...newTags);
tags: newTags, // await queryRunner.manager.save(spaceAllocation);
allocation: spaceAllocation, // }
}); // } else {
spaceAllocation.tags.push(...newTags); // let tagsToAdd = [...tags];
// if (spaceTagUpdateDtos && spaceTagUpdateDtos.length > 0) {
await queryRunner.manager.save(spaceAllocation); // const spaceTagDtosToAdd = spaceTagUpdateDtos.filter(
} // (dto) => dto.action === ModifyAction.ADD,
} else { // );
let tagsToAdd = [...tags]; // tagsToAdd = tagsToAdd.filter(
// (tag) =>
if (spaceTagUpdateDtos && spaceTagUpdateDtos.length > 0) { // !spaceTagDtosToAdd.some(
const spaceTagDtosToAdd = spaceTagUpdateDtos.filter( // (addDto) =>
(dto) => dto.action === ModifyAction.ADD, // (addDto.name && addDto.name === tag.name) ||
); // (addDto.newTagUuid && addDto.newTagUuid === tag.uuid),
// ),
tagsToAdd = tagsToAdd.filter( // );
(tag) => // }
!spaceTagDtosToAdd.some( // if (tagsToAdd.length > 0) {
(addDto) => // const newSpaceAllocation = queryRunner.manager.create(
(addDto.name && addDto.name === tag.name) || // SpaceModelProductAllocationEntity,
(addDto.newTagUuid && addDto.newTagUuid === tag.uuid), // {
), // spaceModel: spaceModel,
); // product: product,
} // tags: tags,
// },
if (tagsToAdd.length > 0) { // );
const newSpaceAllocation = queryRunner.manager.create( // movedToAlreadyExistingSpaceAllocations.push({
SpaceModelProductAllocationEntity, // allocation: newSpaceAllocation,
{ // tags: tags,
spaceModel: spaceModel, // });
product: product, // await queryRunner.manager.save(newSpaceAllocation);
tags: tags, // }
}, // }
); // if (movedToAlreadyExistingSpaceAllocations.length > 0) {
// if (!relocatedAllocationsMap.has(subspaceUuid)) {
movedToAlreadyExistingSpaceAllocations.push({ // relocatedAllocationsMap.set(subspaceUuid, []);
allocation: newSpaceAllocation, // }
tags: tags, // relocatedAllocationsMap
}); // .get(subspaceUuid)
await queryRunner.manager.save(newSpaceAllocation); // .push(...movedToAlreadyExistingSpaceAllocations);
} // }
}
if (movedToAlreadyExistingSpaceAllocations.length > 0) {
if (!relocatedAllocationsMap.has(subspaceUuid)) {
relocatedAllocationsMap.set(subspaceUuid, []);
}
relocatedAllocationsMap
.get(subspaceUuid)
.push(...movedToAlreadyExistingSpaceAllocations);
}
} }
await queryRunner.manager.remove( await queryRunner.manager.remove(
@ -404,7 +395,7 @@ export class SubSpaceModelService {
const updatedSubspaces: { const updatedSubspaces: {
subspaceModel: SubspaceModelEntity; subspaceModel: SubspaceModelEntity;
tags: ModifyTagModelDto[]; tags: ModifyTagDto[];
action: ModifyAction.UPDATE; action: ModifyAction.UPDATE;
}[] = []; }[] = [];
@ -508,12 +499,6 @@ export class SubSpaceModelService {
return subspaceModels.flatMap((subspace) => subspace.tags || []); return subspaceModels.flatMap((subspace) => subspace.tags || []);
} }
extractTagsFromModifiedSubspaceModels(
subspaceModels: ModifySubspaceModelDto[],
): ModifyTagModelDto[] {
return subspaceModels.flatMap((subspace) => subspace.tags || []);
}
private async getSubspacesByUuids( private async getSubspacesByUuids(
queryRunner: QueryRunner, queryRunner: QueryRunner,
subspaceUuids: string[], subspaceUuids: string[],

View File

@ -1,34 +1,50 @@
import { SpaceRepositoryModule } from '@app/common/modules/space/space.repository.module'; import { DeviceStatusFirebaseService } from '@app/common/firebase/devices-status/services/devices-status.service';
import { Module } from '@nestjs/common'; import { AqiDataService } from '@app/common/helper/services/aqi.data.service';
import { ConfigModule } from '@nestjs/config'; import { OccupancyService } from '@app/common/helper/services/occupancy.service';
import { SpaceModelController } from './controllers'; import { PowerClampService } from '@app/common/helper/services/power.clamp.service';
import { SpaceModelService, SubSpaceModelService } from './services'; import { SqlLoaderService } from '@app/common/helper/services/sql-loader.service';
import { TuyaService } from '@app/common/integrations/tuya/services/tuya.service';
import { AutomationRepository } from '@app/common/modules/automation/repositories';
import { CommunityRepository } from '@app/common/modules/community/repositories';
import { DeviceStatusLogRepository } from '@app/common/modules/device-status-log/repositories';
import { DeviceRepository } from '@app/common/modules/device/repositories';
import { import {
SpaceModelProductAllocationRepoitory, PowerClampDailyRepository,
SpaceModelRepository, PowerClampHourlyRepository,
SubspaceModelProductAllocationRepoitory, PowerClampMonthlyRepository,
SubspaceModelRepository, } from '@app/common/modules/power-clamp/repositories';
TagModelRepository,
} from '@app/common/modules/space-model';
import { ProjectRepository } from '@app/common/modules/project/repositiories';
import { ProductRepository } from '@app/common/modules/product/repositories'; import { ProductRepository } from '@app/common/modules/product/repositories';
import { ProjectRepository } from '@app/common/modules/project/repositiories';
import { SceneDeviceRepository } from '@app/common/modules/scene-device/repositories';
import { import {
PropogateDeleteSpaceModelHandler, SceneIconRepository,
PropogateUpdateSpaceModelHandler, SceneRepository,
PropogateUpdateSpaceModelProductAllocationHandler, } from '@app/common/modules/scene/repositories';
} from './handlers';
import { CqrsModule } from '@nestjs/cqrs';
import { import {
InviteSpaceRepository, InviteSpaceRepository,
SpaceLinkRepository, SpaceLinkRepository,
SpaceProductAllocationRepository, SpaceProductAllocationRepository,
SpaceRepository, SpaceRepository,
TagRepository,
} from '@app/common/modules/space'; } from '@app/common/modules/space';
import {
SpaceModelProductAllocationRepoitory,
SpaceModelRepository,
SubspaceModelProductAllocationRepoitory,
SubspaceModelRepository,
} from '@app/common/modules/space-model';
import { import {
SubspaceProductAllocationRepository, SubspaceProductAllocationRepository,
SubspaceRepository, SubspaceRepository,
} from '@app/common/modules/space/repositories/subspace.repository'; } from '@app/common/modules/space/repositories/subspace.repository';
import { SpaceRepositoryModule } from '@app/common/modules/space/space.repository.module';
import { NewTagRepository } from '@app/common/modules/tag/repositories/tag-repository';
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { CqrsModule } from '@nestjs/cqrs';
import { CommunityModule } from 'src/community/community.module';
import { CommunityService } from 'src/community/services';
import { DeviceService } from 'src/device/services';
import { SceneService } from 'src/scene/services';
import { import {
SpaceLinkService, SpaceLinkService,
SpaceService, SpaceService,
@ -36,36 +52,18 @@ import {
SubSpaceService, SubSpaceService,
ValidationService, ValidationService,
} from 'src/space/services'; } from 'src/space/services';
import { TagService } from 'src/space/services/tag';
import { CommunityService } from 'src/community/services';
import { DeviceRepository } from '@app/common/modules/device/repositories';
import { TuyaService } from '@app/common/integrations/tuya/services/tuya.service';
import { CommunityRepository } from '@app/common/modules/community/repositories';
import { TagService as NewTagService } from 'src/tags/services/tags.service';
import { NewTagRepository } from '@app/common/modules/tag/repositories/tag-repository';
import { SpaceModelProductAllocationService } from './services/space-model-product-allocation.service';
import { SubspaceModelProductAllocationService } from './services/subspace/subspace-model-product-allocation.service';
import { SpaceProductAllocationService } from 'src/space/services/space-product-allocation.service'; import { SpaceProductAllocationService } from 'src/space/services/space-product-allocation.service';
import { SubspaceProductAllocationService } from 'src/space/services/subspace/subspace-product-allocation.service'; import { SubspaceProductAllocationService } from 'src/space/services/subspace/subspace-product-allocation.service';
import { DeviceService } from 'src/device/services'; import { TagService as NewTagService } from 'src/tags/services/tags.service';
import { SceneDeviceRepository } from '@app/common/modules/scene-device/repositories'; import { SpaceModelController } from './controllers';
import { DeviceStatusFirebaseService } from '@app/common/firebase/devices-status/services/devices-status.service';
import { SceneService } from 'src/scene/services';
import { DeviceStatusLogRepository } from '@app/common/modules/device-status-log/repositories';
import { import {
SceneIconRepository, PropogateDeleteSpaceModelHandler,
SceneRepository, PropogateUpdateSpaceModelHandler,
} from '@app/common/modules/scene/repositories'; PropogateUpdateSpaceModelProductAllocationHandler,
import { AutomationRepository } from '@app/common/modules/automation/repositories'; } from './handlers';
import { CommunityModule } from 'src/community/community.module'; import { SpaceModelService, SubSpaceModelService } from './services';
import { PowerClampService } from '@app/common/helper/services/power.clamp.service'; import { SpaceModelProductAllocationService } from './services/space-model-product-allocation.service';
import { import { SubspaceModelProductAllocationService } from './services/subspace/subspace-model-product-allocation.service';
PowerClampHourlyRepository,
PowerClampDailyRepository,
PowerClampMonthlyRepository,
} from '@app/common/modules/power-clamp/repositories';
import { SqlLoaderService } from '@app/common/helper/services/sql-loader.service';
import { OccupancyService } from '@app/common/helper/services/occupancy.service';
const CommandHandlers = [ const CommandHandlers = [
PropogateUpdateSpaceModelHandler, PropogateUpdateSpaceModelHandler,
@ -87,13 +85,10 @@ const CommandHandlers = [
SubspaceModelRepository, SubspaceModelRepository,
ProductRepository, ProductRepository,
SubspaceRepository, SubspaceRepository,
TagModelRepository,
SubSpaceService, SubSpaceService,
ValidationService, ValidationService,
TagService,
SubspaceDeviceService, SubspaceDeviceService,
CommunityService, CommunityService,
TagRepository,
DeviceRepository, DeviceRepository,
TuyaService, TuyaService,
CommunityRepository, CommunityRepository,
@ -126,6 +121,7 @@ const CommandHandlers = [
PowerClampMonthlyRepository, PowerClampMonthlyRepository,
SqlLoaderService, SqlLoaderService,
OccupancyService, OccupancyService,
AqiDataService,
], ],
exports: [CqrsModule, SpaceModelService], exports: [CqrsModule, SpaceModelService],
}) })

View File

@ -1,16 +1,19 @@
import { ORPHAN_SPACE_NAME } from '@app/common/constants/orphan-constant';
import { ApiProperty } from '@nestjs/swagger'; import { ApiProperty } from '@nestjs/swagger';
import { Type } from 'class-transformer'; import { Type } from 'class-transformer';
import { import {
ArrayUnique,
IsBoolean, IsBoolean,
IsNotEmpty, IsNotEmpty,
IsNumber, IsNumber,
IsOptional, IsOptional,
IsString, IsString,
IsUUID, IsUUID,
NotEquals,
ValidateNested, ValidateNested,
} from 'class-validator'; } from 'class-validator';
import { AddSubspaceDto } from './subspace';
import { ProcessTagDto } from 'src/tags/dtos'; import { ProcessTagDto } from 'src/tags/dtos';
import { AddSubspaceDto } from './subspace';
export class AddSpaceDto { export class AddSpaceDto {
@ApiProperty({ @ApiProperty({
@ -19,6 +22,11 @@ export class AddSpaceDto {
}) })
@IsString() @IsString()
@IsNotEmpty() @IsNotEmpty()
@NotEquals(ORPHAN_SPACE_NAME, {
message() {
return `Space name cannot be "${ORPHAN_SPACE_NAME}". Please choose a different name.`;
},
})
spaceName: string; spaceName: string;
@ApiProperty({ @ApiProperty({
@ -74,6 +82,20 @@ export class AddSpaceDto {
}) })
@IsOptional() @IsOptional()
@ValidateNested({ each: true }) @ValidateNested({ each: true })
@ArrayUnique((subspace) => subspace.subspaceName, {
message(validationArguments) {
const subspaces = validationArguments.value;
const nameCounts = subspaces.reduce((acc, curr) => {
acc[curr.subspaceName] = (acc[curr.subspaceName] || 0) + 1;
return acc;
}, {});
// Find duplicates
const duplicates = Object.keys(nameCounts).filter(
(name) => nameCounts[name] > 1,
);
return `Duplicate subspace names found: ${duplicates.join(', ')}`;
},
})
@Type(() => AddSubspaceDto) @Type(() => AddSubspaceDto)
subspaces?: AddSubspaceDto[]; subspaces?: AddSubspaceDto[];

View File

@ -0,0 +1,29 @@
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';
export enum AllocationsOwnerType {
SPACE = 'space',
SUBSPACE = 'subspace',
}
export class BaseCreateAllocationsDto {
tags: ProcessTagDto[];
projectUuid: string;
queryRunner: QueryRunner;
type: AllocationsOwnerType;
}
export class CreateSpaceAllocationsDto extends BaseCreateAllocationsDto {
space: SpaceEntity;
type: AllocationsOwnerType.SPACE;
}
export class CreateSubspaceAllocationsDto extends BaseCreateAllocationsDto {
subspace: SubspaceEntity;
type: AllocationsOwnerType.SUBSPACE;
}
export type CreateAllocationsDto =
| CreateSpaceAllocationsDto
| CreateSubspaceAllocationsDto;

View File

@ -1,47 +1,14 @@
import { ModifyAction } from '@app/common/constants/modify-action.enum'; import { ApiPropertyOptional, PartialType } from '@nestjs/swagger';
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger'; import { IsOptional, IsUUID } from 'class-validator';
import { Type } from 'class-transformer'; import { AddSubspaceDto } from './add.subspace.dto';
import {
IsEnum,
IsOptional,
IsString,
IsArray,
ValidateNested,
} from 'class-validator';
import { ModifyTagDto } from '../tag/modify-tag.dto';
export class ModifySubspaceDto {
@ApiProperty({
description: 'Action to perform: add, update, or delete',
example: ModifyAction.ADD,
})
@IsEnum(ModifyAction)
action: ModifyAction;
export class ModifySubspaceDto extends PartialType(AddSubspaceDto) {
@ApiPropertyOptional({ @ApiPropertyOptional({
description: 'UUID of the subspace (required for update/delete)', description:
'UUID of the subspace (will present if updating an existing subspace)',
example: '123e4567-e89b-12d3-a456-426614174000', example: '123e4567-e89b-12d3-a456-426614174000',
}) })
@IsOptional() @IsOptional()
@IsString() @IsUUID()
uuid?: string; uuid?: string;
@ApiPropertyOptional({
description: 'Name of the subspace (required for add/update)',
example: 'Living Room',
})
@IsOptional()
@IsString()
subspaceName?: string;
@ApiPropertyOptional({
description:
'List of tag modifications (add/update/delete) for the subspace',
type: [ModifyTagDto],
})
@IsOptional()
@IsArray()
@ValidateNested({ each: true })
@Type(() => ModifyTagDto)
tags?: ModifyTagDto[];
} }

View File

@ -1,26 +1,9 @@
import { ModifyAction } from '@app/common/constants/modify-action.enum'; import { ApiPropertyOptional } from '@nestjs/swagger';
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger'; import { IsOptional, IsString, IsUUID } from 'class-validator';
import { IsEnum, IsOptional, IsString, IsUUID } from 'class-validator';
export class ModifyTagDto { export class ModifyTagDto {
@ApiProperty({
description: 'Action to perform: add, update, or delete',
example: ModifyAction.ADD,
})
@IsEnum(ModifyAction)
action: ModifyAction;
@ApiPropertyOptional({ @ApiPropertyOptional({
description: 'UUID of the new tag', description: 'UUID of an existing tag',
example: '123e4567-e89b-12d3-a456-426614174000',
})
@IsOptional()
@IsUUID()
newTagUuid: string;
@ApiPropertyOptional({
description:
'UUID of an existing tag (required for update/delete, optional for add)',
example: 'a1b2c3d4-5678-90ef-abcd-1234567890ef', example: 'a1b2c3d4-5678-90ef-abcd-1234567890ef',
}) })
@IsOptional() @IsOptional()
@ -28,7 +11,7 @@ export class ModifyTagDto {
tagUuid?: string; tagUuid?: string;
@ApiPropertyOptional({ @ApiPropertyOptional({
description: 'Name of the tag (required for add/update)', description: 'Name of the tag',
example: 'Temperature Sensor', example: 'Temperature Sensor',
}) })
@IsOptional() @IsOptional()
@ -36,8 +19,7 @@ export class ModifyTagDto {
name?: string; name?: string;
@ApiPropertyOptional({ @ApiPropertyOptional({
description: description: 'UUID of the product associated with the tag',
'UUID of the product associated with the tag (required for add)',
example: 'c789a91e-549a-4753-9006-02f89e8170e0', example: 'c789a91e-549a-4753-9006-02f89e8170e0',
}) })
@IsOptional() @IsOptional()

View File

@ -1,13 +1,15 @@
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 { import {
IsArray, IsArray,
IsNumber, IsNumber,
IsOptional, IsOptional,
IsString, IsString,
NotEquals,
ValidateNested, ValidateNested,
} from 'class-validator'; } from 'class-validator';
import { ModifySubspaceDto } from './subspace'; import { ModifySubspaceDto } from './subspace';
import { Type } from 'class-transformer';
import { ModifyTagDto } from './tag/modify-tag.dto'; import { ModifyTagDto } from './tag/modify-tag.dto';
export class UpdateSpaceDto { export class UpdateSpaceDto {
@ -17,6 +19,11 @@ export class UpdateSpaceDto {
}) })
@IsOptional() @IsOptional()
@IsString() @IsString()
@NotEquals(ORPHAN_SPACE_NAME, {
message() {
return `Space name cannot be "${ORPHAN_SPACE_NAME}". Please choose a different name.`;
},
})
spaceName?: string; spaceName?: string;
@ApiProperty({ @ApiProperty({
@ -46,7 +53,7 @@ export class UpdateSpaceDto {
@IsArray() @IsArray()
@ValidateNested({ each: true }) @ValidateNested({ each: true })
@Type(() => ModifySubspaceDto) @Type(() => ModifySubspaceDto)
subspace?: ModifySubspaceDto[]; subspaces?: ModifySubspaceDto[];
@ApiPropertyOptional({ @ApiPropertyOptional({
description: description:
@ -58,6 +65,7 @@ export class UpdateSpaceDto {
@ValidateNested({ each: true }) @ValidateNested({ each: true })
@Type(() => ModifyTagDto) @Type(() => ModifyTagDto)
tags?: ModifyTagDto[]; tags?: ModifyTagDto[];
@ApiProperty({ @ApiProperty({
description: 'UUID of the Space', description: 'UUID of the Space',
example: 'd290f1ee-6c54-4b01-90e6-d701748f0851', example: 'd290f1ee-6c54-4b01-90e6-d701748f0851',

View File

@ -1,3 +1,4 @@
import { SpaceEntity } from '@app/common/modules/space/entities/space.entity';
import { HttpException, HttpStatus } from '@nestjs/common'; import { HttpException, HttpStatus } from '@nestjs/common';
import { CommandHandler, ICommandHandler } from '@nestjs/cqrs'; import { CommandHandler, ICommandHandler } from '@nestjs/cqrs';
import { DeviceService } from 'src/device/services'; import { DeviceService } from 'src/device/services';
@ -5,12 +6,10 @@ import { UserSpaceService } from 'src/users/services';
import { DataSource } from 'typeorm'; import { DataSource } from 'typeorm';
import { DisableSpaceCommand } from '../commands'; import { DisableSpaceCommand } from '../commands';
import { import {
SubSpaceService,
SpaceLinkService, SpaceLinkService,
SpaceSceneService, SpaceSceneService,
SubSpaceService,
} from '../services'; } from '../services';
import { TagService } from '../services/tag';
import { SpaceEntity } from '@app/common/modules/space/entities/space.entity';
@CommandHandler(DisableSpaceCommand) @CommandHandler(DisableSpaceCommand)
export class DisableSpaceHandler export class DisableSpaceHandler
@ -19,7 +18,6 @@ export class DisableSpaceHandler
constructor( constructor(
private readonly subSpaceService: SubSpaceService, private readonly subSpaceService: SubSpaceService,
private readonly userService: UserSpaceService, private readonly userService: UserSpaceService,
private readonly tagService: TagService,
private readonly deviceService: DeviceService, private readonly deviceService: DeviceService,
private readonly spaceLinkService: SpaceLinkService, private readonly spaceLinkService: SpaceLinkService,
private readonly sceneService: SpaceSceneService, private readonly sceneService: SpaceSceneService,
@ -46,6 +44,9 @@ export class DisableSpaceHandler
'scenes', 'scenes',
'children', 'children',
'userSpaces', 'userSpaces',
'productAllocations',
'productAllocations.tag',
'productAllocations.product',
], ],
}); });
@ -64,15 +65,15 @@ export class DisableSpaceHandler
} }
} }
const tagUuids = space.productAllocations?.map((tag) => tag.uuid) || []; const tagUuids =
space.productAllocations?.map(({ tag }) => tag.uuid) || [];
/* const subspaceDtos = /* const subspaceDtos =
space.subspaces?.map((subspace) => ({ space.subspaces?.map((subspace) => ({
subspaceUuid: subspace.uuid, subspaceUuid: subspace.uuid,
})) || []; */ })) || []; */
const deletionTasks = [ const deletionTasks = [
// this.subSpaceService.deleteSubspaces(subspaceDtos, queryRunner),
this.userService.deleteUserSpace(space.uuid), this.userService.deleteUserSpace(space.uuid),
this.tagService.deleteTags(tagUuids, queryRunner),
this.deviceService.deleteDevice( this.deviceService.deleteDevice(
space.devices, space.devices,
orphanSpace, orphanSpace,

View File

@ -1,9 +0,0 @@
import { ModifyAction } from '@app/common/constants/modify-action.enum';
import { SubspaceEntity } from '@app/common/modules/space/entities/subspace/subspace.entity';
import { ModifyTagDto } from '../dtos/tag/modify-tag.dto';
export interface ISingleSubspace {
subspace: SubspaceEntity;
action: ModifyAction;
tags: ModifyTagDto[];
}

View File

@ -0,0 +1,6 @@
import { ProcessTagDto } from 'src/tags/dtos';
export interface UpdateSpaceAllocationDto {
uuid: string;
tags: ProcessTagDto[];
}

View File

@ -0,0 +1,62 @@
import { Injectable } from '@nestjs/common';
import { TagService } from 'src/tags/services';
import {
AllocationsOwnerType,
CreateAllocationsDto,
} from '../../dtos/create-allocations.dto';
import { SpaceProductAllocationService } from '../space-product-allocation.service';
import { SubspaceProductAllocationService } from '../subspace/subspace-product-allocation.service';
@Injectable()
export class ProductAllocationService {
constructor(
private readonly tagService: TagService,
private readonly spaceProductAllocationService: SpaceProductAllocationService,
private readonly subSpaceProductAllocationService: SubspaceProductAllocationService,
) {}
async createAllocations(dto: CreateAllocationsDto): Promise<void> {
const { projectUuid, queryRunner, tags, type } = dto;
const allocationsData = await this.tagService.processTags(
tags,
projectUuid,
queryRunner,
);
// Create a mapping of created tags by UUID and name for quick lookup
const createdTagsByUUID = new Map(allocationsData.map((t) => [t.uuid, t]));
const createdTagsByName = new Map(allocationsData.map((t) => [t.name, t]));
// Create the product-tag mapping based on the processed tags
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: {
// todo: take to consideration original method implementation
await this.spaceProductAllocationService.createProductAllocations(
dto.space,
productTagMapping,
queryRunner,
);
break;
}
case AllocationsOwnerType.SUBSPACE: {
await this.subSpaceProductAllocationService.createProductAllocations(
dto.subspace,
productTagMapping,
queryRunner,
);
break;
}
}
}
}

View File

@ -1,113 +1,37 @@
import { ModifyAction } from '@app/common/constants/modify-action.enum';
import { ProductEntity } from '@app/common/modules/product/entities';
import { SpaceProductAllocationRepository } from '@app/common/modules/space'; import { SpaceProductAllocationRepository } from '@app/common/modules/space';
import { SpaceProductAllocationEntity } from '@app/common/modules/space/entities/space-product-allocation.entity'; import { SpaceProductAllocationEntity } from '@app/common/modules/space/entities/space-product-allocation.entity';
import { SpaceEntity } from '@app/common/modules/space/entities/space.entity'; import { SpaceEntity } from '@app/common/modules/space/entities/space.entity';
import { NewTagEntity } from '@app/common/modules/tag';
import { HttpException, HttpStatus, Injectable } from '@nestjs/common'; import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { In, QueryRunner } from 'typeorm'; import { In, QueryRunner } from 'typeorm';
import { SubspaceProductAllocationEntity } from '@app/common/modules/space/entities/subspace/subspace-product-allocation.entity';
import { ModifyTagDto } from '../dtos/tag/modify-tag.dto';
import { ModifySubspaceDto } from '../dtos';
import { ProcessTagDto } from 'src/tags/dtos';
import { TagService as NewTagService } from 'src/tags/services';
import { SpaceModelProductAllocationEntity } from '@app/common/modules/space-model';
import { DeviceEntity } from '@app/common/modules/device/entities';
import { ProjectEntity } from '@app/common/modules/project/entities';
import { ValidationService } from './space-validation.service';
@Injectable() @Injectable()
export class SpaceProductAllocationService { export class SpaceProductAllocationService {
constructor( constructor(
private readonly tagService: NewTagService,
private readonly spaceProductAllocationRepository: SpaceProductAllocationRepository, private readonly spaceProductAllocationRepository: SpaceProductAllocationRepository,
private readonly spaceService: ValidationService,
) {} ) {}
async createSpaceProductAllocations( async createProductAllocations(
space: SpaceEntity, space: SpaceEntity,
processedTags: NewTagEntity[], allocationsData: { product: string; tag: string }[],
queryRunner: QueryRunner, queryRunner: QueryRunner,
modifySubspaces?: ModifySubspaceDto[],
): Promise<void> { ): Promise<void> {
try { try {
if (!processedTags.length) return; if (!allocationsData.length) return;
const productAllocations: SpaceProductAllocationEntity[] = []; const productAllocations: SpaceProductAllocationEntity[] = [];
const existingAllocations = new Map<
string,
SpaceProductAllocationEntity
>();
for (const tag of processedTags) { for (const allocationData of allocationsData) {
let isTagNeeded = true; if (await this.isAllocationExist(queryRunner, allocationData, space))
continue;
if (modifySubspaces) { const allocation = this.createNewAllocation(
const relatedSubspaces = await queryRunner.manager.find( space,
SubspaceProductAllocationEntity, allocationData,
{ queryRunner,
where: { );
product: tag.product, productAllocations.push(allocation);
subspace: { space: { uuid: space.uuid } },
tags: { uuid: tag.uuid },
},
relations: ['subspace', 'tags'],
},
);
for (const subspaceWithTag of relatedSubspaces) {
const modifyingSubspace = modifySubspaces.find(
(subspace) =>
subspace.action === ModifyAction.UPDATE &&
subspace.uuid === subspaceWithTag.subspace.uuid,
);
if (
modifyingSubspace &&
modifyingSubspace.tags &&
modifyingSubspace.tags.some(
(subspaceTag) =>
subspaceTag.action === ModifyAction.DELETE &&
subspaceTag.tagUuid === tag.uuid,
)
) {
isTagNeeded = true;
break;
}
}
}
if (isTagNeeded) {
const isDuplicated = await this.validateTagWithinSpace(
queryRunner,
tag,
space,
);
if (isDuplicated) continue;
let allocation = existingAllocations.get(tag.product.uuid);
if (!allocation) {
allocation = await this.getAllocationByProduct(
tag.product,
space,
queryRunner,
);
if (allocation) {
existingAllocations.set(tag.product.uuid, allocation);
}
}
if (!allocation) {
allocation = this.createNewAllocation(space, tag, queryRunner);
productAllocations.push(allocation);
} else if (!allocation.tags.some((t) => t.uuid === tag.uuid)) {
allocation.tags.push(tag);
await this.saveAllocation(allocation, queryRunner);
}
}
} }
if (productAllocations.length > 0) { if (productAllocations.length > 0) {
await this.saveAllocations(productAllocations, queryRunner); await this.saveAllocations(productAllocations, queryRunner);
} }
@ -118,97 +42,6 @@ export class SpaceProductAllocationService {
); );
} }
} }
async createAllocationFromModel(
modelAllocations: SpaceModelProductAllocationEntity[],
queryRunner: QueryRunner,
spaces?: SpaceEntity[],
) {
if (!spaces || spaces.length === 0 || !modelAllocations.length) return;
const allocations: SpaceProductAllocationEntity[] = [];
for (const space of spaces) {
for (const modelAllocation of modelAllocations) {
const allocation = queryRunner.manager.create(
SpaceProductAllocationEntity,
{
space,
product: modelAllocation.product,
tags: modelAllocation.tags,
inheritedFromModel: modelAllocation,
},
);
allocations.push(allocation);
}
}
if (allocations.length > 0) {
await queryRunner.manager.save(SpaceProductAllocationEntity, allocations);
}
}
async addTagToAllocationFromModel(
modelAllocation: SpaceModelProductAllocationEntity,
queryRunner: QueryRunner,
tag: NewTagEntity,
spaces?: SpaceEntity[],
) {
try {
if (!spaces || spaces.length === 0 || !modelAllocation) return;
const spaceAllocations = await queryRunner.manager.find(
SpaceProductAllocationEntity,
{
where: { inheritedFromModel: { uuid: modelAllocation.uuid } },
relations: ['tags'],
},
);
if (spaceAllocations.length === 0) return;
for (const allocation of spaceAllocations) {
allocation.tags.push(tag);
}
await queryRunner.manager.save(
SpaceProductAllocationEntity,
spaceAllocations,
);
} catch (error) {
throw new HttpException(
'Failed to add tag to allocation from model',
HttpStatus.INTERNAL_SERVER_ERROR,
);
}
}
async updateSpaceProductAllocations(
dtos: ModifyTagDto[],
projectUuid: string,
space: SpaceEntity,
queryRunner: QueryRunner,
modifySubspace?: ModifySubspaceDto[],
): Promise<void> {
if (!dtos || dtos.length === 0) return;
try {
await Promise.all([
this.processAddActions(
dtos,
projectUuid,
space,
queryRunner,
modifySubspace,
),
this.processDeleteActions(dtos, queryRunner, space),
]);
} catch (error) {
throw this.handleError(error, 'Error while updating product allocations');
}
}
async unlinkModels(space: SpaceEntity, queryRunner: QueryRunner) { async unlinkModels(space: SpaceEntity, queryRunner: QueryRunner) {
try { try {
if (!space.productAllocations || space.productAllocations.length === 0) if (!space.productAllocations || space.productAllocations.length === 0)
@ -231,307 +64,30 @@ export class SpaceProductAllocationService {
} }
} }
async propagateDeleteToInheritedAllocations( private async isAllocationExist(
queryRunner: QueryRunner,
allocationsToUpdate: SpaceModelProductAllocationEntity[],
tagUuidsToDelete: string[],
project: ProjectEntity,
spaces?: SpaceEntity[],
): Promise<void> {
try {
const inheritedAllocationUpdates: SpaceProductAllocationEntity[] = [];
const inheritedAllocationsToDelete: SpaceProductAllocationEntity[] = [];
for (const allocation of allocationsToUpdate) {
for (const inheritedAllocation of allocation.inheritedSpaceAllocations) {
const updatedInheritedTags = inheritedAllocation.tags.filter(
(tag) => !tagUuidsToDelete.includes(tag.uuid),
);
if (updatedInheritedTags.length === inheritedAllocation.tags.length) {
continue;
}
if (updatedInheritedTags.length === 0) {
inheritedAllocationsToDelete.push(inheritedAllocation);
} else {
inheritedAllocation.tags = updatedInheritedTags;
inheritedAllocationUpdates.push(inheritedAllocation);
}
}
}
if (inheritedAllocationUpdates.length > 0) {
await queryRunner.manager.save(
SpaceProductAllocationEntity,
inheritedAllocationUpdates,
);
}
if (inheritedAllocationsToDelete.length > 0) {
await queryRunner.manager.remove(
SpaceProductAllocationEntity,
inheritedAllocationsToDelete,
);
}
if (spaces && spaces.length > 0) {
await this.moveDevicesToOrphanSpace(
queryRunner,
spaces,
tagUuidsToDelete,
project,
);
}
await queryRunner.manager
.createQueryBuilder()
.delete()
.from('space_product_tags')
.where(
'space_product_allocation_uuid NOT IN (' +
queryRunner.manager
.createQueryBuilder()
.select('allocation.uuid')
.from(SpaceProductAllocationEntity, 'allocation')
.getQuery() +
')',
)
.execute();
} catch (error) {
throw this.handleError(
error,
`Failed to propagate tag deletion to inherited allocations`,
);
}
}
async moveDevicesToOrphanSpace(
queryRunner: QueryRunner,
spaces: SpaceEntity[],
tagUuidsToDelete: string[],
project: ProjectEntity,
): Promise<void> {
try {
const orphanSpace = await this.spaceService.getOrphanSpace(project);
const devicesToMove = await queryRunner.manager
.createQueryBuilder(DeviceEntity, 'device')
.leftJoinAndSelect('device.tag', 'tag')
.where('device.spaceDevice IN (:...spaceUuids)', {
spaceUuids: spaces.map((space) => space.uuid),
})
.andWhere('tag.uuid IN (:...tagUuidsToDelete)', { tagUuidsToDelete })
.getMany();
if (devicesToMove.length === 0) return;
await queryRunner.manager
.createQueryBuilder()
.update(DeviceEntity)
.set({ spaceDevice: orphanSpace })
.where('uuid IN (:...deviceUuids)', {
deviceUuids: devicesToMove.map((device) => device.uuid),
})
.execute();
} catch (error) {
throw this.handleError(error, `Failed to move devices to orphan space`);
}
}
private async processDeleteActions(
dtos: ModifyTagDto[],
queryRunner: QueryRunner, queryRunner: QueryRunner,
allocation: { product: string; tag: string },
space: SpaceEntity, space: SpaceEntity,
): Promise<SpaceProductAllocationEntity[]> { ): Promise<boolean> {
try { const existingAllocations =
if (!dtos || dtos.length === 0) return; await queryRunner.manager.findOne<SpaceProductAllocationEntity>(
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(
SpaceProductAllocationEntity, SpaceProductAllocationEntity,
{ {
where: { where: {
tags: { uuid: In(tagUuidsToDelete) }, space: {
space: { uuid: space.uuid }, uuid: space.uuid,
}, },
relations: ['tags'], tag: {
}, uuid: allocation.tag,
); },
product: {
if (!allocationsToUpdate || allocationsToUpdate.length === 0) return []; uuid: allocation.product,
},
const deletedAllocations: SpaceProductAllocationEntity[] = [];
const allocationUpdates: SpaceProductAllocationEntity[] = [];
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(
SpaceProductAllocationEntity,
allocationUpdates,
);
}
if (deletedAllocations.length > 0) {
await queryRunner.manager.remove(
SpaceProductAllocationEntity,
deletedAllocations,
);
}
await queryRunner.manager
.createQueryBuilder()
.delete()
.from('space_product_tags')
.where(
'space_product_allocation_uuid NOT IN (' +
queryRunner.manager
.createQueryBuilder()
.select('allocation.uuid')
.from(SpaceProductAllocationEntity, 'allocation')
.getQuery() +
')',
)
.execute();
return deletedAllocations;
} catch (error) {
throw this.handleError(error, `Failed to delete tags in space`);
}
}
private async processAddActions(
dtos: ModifyTagDto[],
projectUuid: string,
space: SpaceEntity,
queryRunner: QueryRunner,
modifySubspace?: ModifySubspaceDto[],
): Promise<void> {
const addDtos: ProcessTagDto[] = dtos
.filter((dto) => dto.action === ModifyAction.ADD)
.map((dto) => ({
name: dto.name,
productUuid: dto.productUuid,
uuid: dto.newTagUuid,
}));
if (addDtos.length > 0) {
const processedTags = await this.tagService.processTags(
addDtos,
projectUuid,
queryRunner,
);
await this.createSpaceProductAllocations(
space,
processedTags,
queryRunner,
modifySubspace,
);
}
}
private async validateTagWithinSpace(
queryRunner: QueryRunner,
tag: NewTagEntity,
space: SpaceEntity,
): Promise<boolean> {
const existingAllocationsForProduct = await queryRunner.manager.find(
SpaceProductAllocationEntity,
{
where: {
space: {
uuid: space.uuid,
},
product: {
uuid: tag.product.uuid,
}, },
}, },
relations: ['tags'], );
},
);
if ( return existingAllocations ? true : false;
!existingAllocationsForProduct ||
existingAllocationsForProduct.length === 0
) {
return false;
}
const existingTagsForProduct = existingAllocationsForProduct.flatMap(
(allocation) => allocation.tags || [],
);
return existingTagsForProduct.some(
(existingTag) => existingTag.uuid === tag.uuid,
);
}
private async getAllocationByProduct(
product: ProductEntity,
space: SpaceEntity,
queryRunner?: QueryRunner,
): Promise<SpaceProductAllocationEntity | null> {
return queryRunner
? queryRunner.manager.findOne(SpaceProductAllocationEntity, {
where: {
space: { uuid: space.uuid },
product: { uuid: product.uuid },
},
relations: ['tags'],
})
: this.spaceProductAllocationRepository.findOne({
where: {
space: { uuid: space.uuid },
product: { uuid: product.uuid },
},
relations: ['tags'],
});
}
createNewAllocation(
space: SpaceEntity,
tag: NewTagEntity,
queryRunner?: QueryRunner,
): SpaceProductAllocationEntity {
return queryRunner
? queryRunner.manager.create(SpaceProductAllocationEntity, {
space,
product: tag.product,
tags: [tag],
})
: this.spaceProductAllocationRepository.create({
space,
product: tag.product,
tags: [tag],
});
}
private async saveAllocation(
allocation: SpaceProductAllocationEntity,
queryRunner?: QueryRunner,
) {
queryRunner
? await queryRunner.manager.save(SpaceProductAllocationEntity, allocation)
: await this.spaceProductAllocationRepository.save(allocation);
} }
async saveAllocations( async saveAllocations(
@ -546,6 +102,34 @@ export class SpaceProductAllocationService {
: await this.spaceProductAllocationRepository.save(allocations); : await this.spaceProductAllocationRepository.save(allocations);
} }
async clearAllAllocations(spaceUuid: string, queryRunner: QueryRunner) {
try {
await queryRunner.manager.delete(SpaceProductAllocationEntity, {
space: { uuid: spaceUuid },
});
} catch (error) {
throw this.handleError(error, 'Failed to clear all allocations');
}
}
private createNewAllocation(
space: SpaceEntity,
allocationData: { product: string; tag: string },
queryRunner?: QueryRunner,
): SpaceProductAllocationEntity {
return queryRunner
? queryRunner.manager.create(SpaceProductAllocationEntity, {
space,
product: { uuid: allocationData.product },
tag: { uuid: allocationData.tag },
})
: this.spaceProductAllocationRepository.create({
space,
product: { uuid: allocationData.product },
tag: { uuid: allocationData.tag },
});
}
private handleError(error: any, message: string): HttpException { private handleError(error: any, message: string): HttpException {
return new HttpException( return new HttpException(
error instanceof HttpException ? error.message : message, error instanceof HttpException ? error.message : message,
@ -554,36 +138,4 @@ export class SpaceProductAllocationService {
: HttpStatus.INTERNAL_SERVER_ERROR, : HttpStatus.INTERNAL_SERVER_ERROR,
); );
} }
async clearAllAllocations(spaceUuid: string, queryRunner: QueryRunner) {
try {
const allocationUuids = await queryRunner.manager
.createQueryBuilder(SpaceProductAllocationEntity, 'allocation')
.select('allocation.uuid')
.where('allocation.space_uuid = :spaceUuid', { spaceUuid })
.getRawMany()
.then((results) => results.map((r) => r.allocation_uuid));
if (allocationUuids.length === 0) {
return;
}
await queryRunner.manager
.createQueryBuilder()
.delete()
.from('space_product_tags')
.where('space_product_allocation_uuid IN (:...allocationUuids)', {
allocationUuids,
})
.execute();
await queryRunner.manager
.createQueryBuilder()
.delete()
.from(SpaceProductAllocationEntity)
.where('space_uuid = :spaceUuid', { spaceUuid })
.execute();
} catch (error) {
throw this.handleError(error, 'Failed to clear all allocations');
}
}
} }

Some files were not shown because too many files have changed in this diff Show More