mirror of
https://github.com/SyncrowIOT/backend.git
synced 2025-07-10 07:07:21 +00:00
Compare commits
106 Commits
add-queue-
...
5cf45c30f4
Author | SHA1 | Date | |
---|---|---|---|
5cf45c30f4 | |||
0bb178ed10 | |||
9971fb953d | |||
7a07f39f16 | |||
18b21d697c | |||
66391bafd8 | |||
25599b9fe2 | |||
807c5b7dd3 | |||
60bc03cf79 | |||
a9eaf44d31 | |||
d232c06ebe | |||
5c916ed445 | |||
b2fb378e52 | |||
c5f8f96977 | |||
8f9b15f49f | |||
0b9eef276e | |||
b3f8b92826 | |||
b9da00aaa6 | |||
5bf44a18e1 | |||
2b2772e4ca | |||
13c0f87fc6 | |||
c9d794d988 | |||
5d4e5ca87e | |||
f4e748d735 | |||
f4f7999ae0 | |||
82c82d521c | |||
c7a4ff1194 | |||
90ab291d83 | |||
8a4633b158 | |||
f80d097ff8 | |||
04bd156df1 | |||
731819aeaa | |||
68d2d3b53d | |||
3fcfe2d92f | |||
c0a069b460 | |||
5381a949bc | |||
30724d7d37 | |||
324661e1ee | |||
a83424f45b | |||
71f6ccb4db | |||
68692b7c8b | |||
4d60c1ed54 | |||
27dbe04299 | |||
9bebcb2f3e | |||
43ab0030f0 | |||
c48adb73b5 | |||
d255e6811e | |||
e58d2d4831 | |||
147cf0b582 | |||
4e6b6f6ac5 | |||
932a3efd1c | |||
0a1ccad120 | |||
f337e6c681 | |||
f5bf857071 | |||
37b582f521 | |||
d3d84da5e3 | |||
6973e8b195 | |||
92d102d08f | |||
7dc28d0cb3 | |||
d9ad431a23 | |||
4bf43dab2b | |||
49cc762962 | |||
a94d4610ed | |||
274cdf741f | |||
df59e9a4a3 | |||
8c34c68ba6 | |||
332b2f5851 | |||
8d44b66dd3 | |||
7520b8d9c7 | |||
72753b6dfb | |||
568eef8119 | |||
a40560a0b1 | |||
7d6f1bb944 | |||
434316fe51 | |||
287bb4c5e4 | |||
85602fa952 | |||
25a4d3e91b | |||
d3a560d18f | |||
ab99bb5afc | |||
67911d5ff1 | |||
13e3f3e213 | |||
327d678656 | |||
dd5447fc5f | |||
7df5b9ab08 | |||
06b4407b85 | |||
1d6f3b8e65 | |||
80659f7a48 | |||
4a5f2f3b9f | |||
a57f4e1c65 | |||
b2d52c7622 | |||
c9cbb2e085 | |||
8aa3de5fdc | |||
bc1ee9a53b | |||
19356c3833 | |||
8737ee992b | |||
e98a99be73 | |||
93efa15f3c | |||
c305e39ff2 | |||
61e4d220dc | |||
cd4bbe1788 | |||
d770a0c732 | |||
030e6ae902 | |||
9d8287b82b | |||
d741a6c1f3 | |||
6d55704dd4 | |||
d8ad9e55ea |
17
.github/pull_request_template.md
vendored
Normal file
17
.github/pull_request_template.md
vendored
Normal file
@ -0,0 +1,17 @@
|
||||
<!--
|
||||
Thanks for contributing!
|
||||
|
||||
Provide a description of your changes below and a general summary in the title.
|
||||
-->
|
||||
|
||||
## Jira Ticket
|
||||
|
||||
[SP-0000](https://syncrow.atlassian.net/browse/SP-0000)
|
||||
|
||||
## Description
|
||||
|
||||
<!--- Describe your changes in detail -->
|
||||
|
||||
## How to Test
|
||||
|
||||
<!--- Describe the created APIs / Logic -->
|
74
.github/workflows/main_syncrow(staging).yml
vendored
74
.github/workflows/main_syncrow(staging).yml
vendored
@ -1,4 +1,7 @@
|
||||
name: Backend deployment to Azure App Service
|
||||
# Docs for the Azure Web Apps Deploy action: https://github.com/Azure/webapps-deploy
|
||||
# More GitHub Actions for Azure: https://github.com/Azure/actions
|
||||
|
||||
name: Build and deploy container app to Azure Web App - syncrow(staging)
|
||||
|
||||
on:
|
||||
push:
|
||||
@ -6,50 +9,43 @@ on:
|
||||
- main
|
||||
workflow_dispatch:
|
||||
|
||||
env:
|
||||
AZURE_WEB_APP_NAME: 'syncrow'
|
||||
AZURE_WEB_APP_SLOT_NAME: 'staging'
|
||||
ACR_REGISTRY: 'syncrow.azurecr.io'
|
||||
IMAGE_NAME: 'backend'
|
||||
IMAGE_TAG: 'latest'
|
||||
|
||||
jobs:
|
||||
build_and_deploy:
|
||||
runs-on: ubuntu-latest
|
||||
build:
|
||||
runs-on: 'ubuntu-latest'
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@v2
|
||||
|
||||
- name: Set up Node.js
|
||||
uses: actions/setup-node@v3
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v2
|
||||
|
||||
- name: Log in to registry
|
||||
uses: docker/login-action@v2
|
||||
with:
|
||||
node-version: '20'
|
||||
registry: https://syncrow.azurecr.io/
|
||||
username: ${{ secrets.AzureAppService_ContainerUsername_47395803300340b49931ea82f6d80be3 }}
|
||||
password: ${{ secrets.AzureAppService_ContainerPassword_e7b0ff54f54d44cba04a970a22384848 }}
|
||||
|
||||
- name: Install dependencies and build project
|
||||
run: |
|
||||
npm install
|
||||
npm run build
|
||||
|
||||
- name: Log in to Azure
|
||||
uses: azure/login@v1
|
||||
- name: Build and push container image to registry
|
||||
uses: docker/build-push-action@v3
|
||||
with:
|
||||
creds: ${{ secrets.AZURE_CREDENTIALS }}
|
||||
push: true
|
||||
tags: syncrow.azurecr.io/${{ secrets.AzureAppService_ContainerUsername_47395803300340b49931ea82f6d80be3 }}/syncrow/backend:${{ github.sha }}
|
||||
file: ./Dockerfile
|
||||
|
||||
- name: Log in to Azure Container Registry
|
||||
run: az acr login --name ${{ env.ACR_REGISTRY }}
|
||||
deploy:
|
||||
runs-on: ubuntu-latest
|
||||
needs: build
|
||||
environment:
|
||||
name: 'staging'
|
||||
url: ${{ steps.deploy-to-webapp.outputs.webapp-url }}
|
||||
|
||||
- name: List build output
|
||||
run: ls -R dist/
|
||||
|
||||
- name: Build and push Docker image
|
||||
run: |
|
||||
docker build . -t ${{ env.ACR_REGISTRY }}/${{ env.IMAGE_NAME }}:${{ env.IMAGE_TAG }}
|
||||
docker push ${{ env.ACR_REGISTRY }}/${{ env.IMAGE_NAME }}:${{ env.IMAGE_TAG }}
|
||||
|
||||
- name: Set Web App with Docker container
|
||||
run: |
|
||||
az webapp config container set \
|
||||
--name ${{ env.AZURE_WEB_APP_NAME }} \
|
||||
--resource-group backend \
|
||||
--docker-custom-image-name ${{ env.ACR_REGISTRY }}/${{ env.IMAGE_NAME }}:${{ env.IMAGE_TAG }} \
|
||||
--docker-registry-server-url https://${{ env.ACR_REGISTRY }}
|
||||
steps:
|
||||
- name: Deploy to Azure Web App
|
||||
id: deploy-to-webapp
|
||||
uses: azure/webapps-deploy@v2
|
||||
with:
|
||||
app-name: 'syncrow'
|
||||
slot-name: 'staging'
|
||||
publish-profile: ${{ secrets.AzureAppService_PublishProfile_44f7766441ec4796b74789e9761ef589 }}
|
||||
images: 'syncrow.azurecr.io/${{ secrets.AzureAppService_ContainerUsername_47395803300340b49931ea82f6d80be3 }}/syncrow/backend:${{ github.sha }}'
|
||||
|
73
.github/workflows/main_syncrow(stg).yml
vendored
Normal file
73
.github/workflows/main_syncrow(stg).yml
vendored
Normal 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: .
|
2
.gitignore
vendored
2
.gitignore
vendored
@ -4,7 +4,7 @@
|
||||
/build
|
||||
|
||||
#github
|
||||
/.github
|
||||
/.github/workflows
|
||||
|
||||
# Logs
|
||||
logs
|
||||
|
@ -69,7 +69,28 @@ export class ControllerRoute {
|
||||
'Retrieve the list of all regions registered in Syncrow.';
|
||||
};
|
||||
};
|
||||
static BOOKABLE_SPACES = class {
|
||||
public static readonly ROUTE = 'bookable-spaces';
|
||||
static ACTIONS = class {
|
||||
public static readonly ADD_BOOKABLE_SPACES_SUMMARY =
|
||||
'Add new bookable spaces';
|
||||
|
||||
public static readonly ADD_BOOKABLE_SPACES_DESCRIPTION =
|
||||
'This endpoint allows you to add new bookable spaces by providing the required details.';
|
||||
|
||||
public static readonly GET_ALL_BOOKABLE_SPACES_SUMMARY =
|
||||
'Get all bookable spaces';
|
||||
|
||||
public static readonly GET_ALL_BOOKABLE_SPACES_DESCRIPTION =
|
||||
'This endpoint retrieves all bookable spaces.';
|
||||
|
||||
public static readonly UPDATE_BOOKABLE_SPACES_SUMMARY =
|
||||
'Update existing bookable spaces';
|
||||
|
||||
public static readonly UPDATE_BOOKABLE_SPACES_DESCRIPTION =
|
||||
'This endpoint allows you to update existing bookable spaces by providing the required details.';
|
||||
};
|
||||
};
|
||||
static COMMUNITY = class {
|
||||
public static readonly ROUTE = '/projects/:projectUuid/communities';
|
||||
static ACTIONS = class {
|
||||
@ -397,6 +418,11 @@ export class ControllerRoute {
|
||||
public static readonly DELETE_USER_SUMMARY = 'Delete user by UUID';
|
||||
public static readonly DELETE_USER_DESCRIPTION =
|
||||
'This endpoint deletes a user identified by their UUID. Accessible only by users with the Super Admin role.';
|
||||
|
||||
public static readonly DELETE_USER_PROFILE_SUMMARY =
|
||||
'Delete user profile by UUID';
|
||||
public static readonly DELETE_USER_PROFILE_DESCRIPTION =
|
||||
'This endpoint deletes a user profile identified by their UUID. Accessible only by users with the Super Admin role.';
|
||||
public static readonly UPDATE_USER_WEB_AGREEMENT_SUMMARY =
|
||||
'Update user web agreement by user UUID';
|
||||
public static readonly UPDATE_USER_WEB_AGREEMENT_DESCRIPTION =
|
||||
@ -501,7 +527,6 @@ export class ControllerRoute {
|
||||
};
|
||||
static PowerClamp = class {
|
||||
public static readonly ROUTE = 'power-clamp';
|
||||
|
||||
static ACTIONS = class {
|
||||
public static readonly GET_ENERGY_SUMMARY =
|
||||
'Get power clamp historical data';
|
||||
@ -628,6 +653,11 @@ export class ControllerRoute {
|
||||
'Delete scenes by device uuid and switch name';
|
||||
public static readonly DELETE_SCENES_BY_SWITCH_NAME_DESCRIPTION =
|
||||
'This endpoint deletes all scenes associated with a specific switch device.';
|
||||
|
||||
public static readonly POPULATE_TUYA_CONST_UUID_SUMMARY =
|
||||
'Populate Tuya const UUID';
|
||||
public static readonly POPULATE_TUYA_CONST_UUID_DESCRIPTION =
|
||||
'This endpoint populates the Tuya const UUID for all devices.';
|
||||
};
|
||||
};
|
||||
static DEVICE_COMMISSION = class {
|
||||
|
@ -15,6 +15,7 @@ export enum ProductType {
|
||||
WL = 'WL',
|
||||
GD = 'GD',
|
||||
CUR = 'CUR',
|
||||
CUR_2 = 'CUR_2',
|
||||
PC = 'PC',
|
||||
FOUR_S = '4S',
|
||||
SIX_S = '6S',
|
||||
|
@ -58,6 +58,7 @@ import {
|
||||
UserSpaceEntity,
|
||||
} from '../modules/user/entities';
|
||||
import { VisitorPasswordEntity } from '../modules/visitor-password/entities';
|
||||
import { BookableSpaceEntity } from '../modules/booking/entities';
|
||||
@Module({
|
||||
imports: [
|
||||
TypeOrmModule.forRootAsync({
|
||||
@ -117,6 +118,7 @@ import { VisitorPasswordEntity } from '../modules/visitor-password/entities';
|
||||
PresenceSensorDailySpaceEntity,
|
||||
AqiSpaceDailyPollutantStatsEntity,
|
||||
SpaceDailyOccupancyDurationEntity,
|
||||
BookableSpaceEntity,
|
||||
],
|
||||
namingStrategy: new SnakeNamingStrategy(),
|
||||
synchronize: Boolean(JSON.parse(configService.get('DB_SYNC'))),
|
||||
@ -126,7 +128,7 @@ import { VisitorPasswordEntity } from '../modules/visitor-password/entities';
|
||||
extra: {
|
||||
charset: 'utf8mb4',
|
||||
max: 100, // set pool max size
|
||||
idleTimeoutMillis: 5000, // close idle clients after 5 second
|
||||
idleTimeoutMillis: 3000, // close idle clients after 5 second
|
||||
connectionTimeoutMillis: 12_000, // return an error after 11 second if connection could not be established
|
||||
maxUses: 7500, // close (and replace) a connection after it has been used 7500 times (see below for discussion)
|
||||
},
|
||||
|
@ -3,28 +3,12 @@ import { DeviceStatusFirebaseController } from './controllers/devices-status.con
|
||||
import { DeviceStatusFirebaseService } from './services/devices-status.service';
|
||||
import { DeviceRepository } from '@app/common/modules/device/repositories';
|
||||
import { DeviceStatusLogRepository } from '@app/common/modules/device-status-log/repositories/device-status.repository';
|
||||
import { PowerClampService } from '@app/common/helper/services/power.clamp.service';
|
||||
import {
|
||||
PowerClampHourlyRepository,
|
||||
PowerClampDailyRepository,
|
||||
PowerClampMonthlyRepository,
|
||||
} from '@app/common/modules/power-clamp/repositories';
|
||||
import { SqlLoaderService } from '@app/common/helper/services/sql-loader.service';
|
||||
import { OccupancyService } from '@app/common/helper/services/occupancy.service';
|
||||
import { AqiDataService } from '@app/common/helper/services/aqi.data.service';
|
||||
|
||||
@Module({
|
||||
providers: [
|
||||
DeviceStatusFirebaseService,
|
||||
DeviceRepository,
|
||||
DeviceStatusLogRepository,
|
||||
PowerClampService,
|
||||
PowerClampHourlyRepository,
|
||||
PowerClampDailyRepository,
|
||||
PowerClampMonthlyRepository,
|
||||
SqlLoaderService,
|
||||
OccupancyService,
|
||||
AqiDataService,
|
||||
],
|
||||
controllers: [DeviceStatusFirebaseController],
|
||||
exports: [DeviceStatusFirebaseService, DeviceStatusLogRepository],
|
||||
|
@ -13,6 +13,7 @@ class StatusDto {
|
||||
|
||||
@IsNotEmpty()
|
||||
value: any;
|
||||
t?: string | number | Date;
|
||||
}
|
||||
|
||||
export class AddDeviceStatusDto {
|
||||
|
@ -18,22 +18,15 @@ import {
|
||||
runTransaction,
|
||||
} from 'firebase/database';
|
||||
import { DeviceStatusLogRepository } from '@app/common/modules/device-status-log/repositories';
|
||||
import { ProductType } from '@app/common/constants/product-type.enum';
|
||||
import { PowerClampService } from '@app/common/helper/services/power.clamp.service';
|
||||
import { PowerClampEnergyEnum } from '@app/common/constants/power.clamp.enargy.enum';
|
||||
import { PresenceSensorEnum } from '@app/common/constants/presence.sensor.enum';
|
||||
import { OccupancyService } from '@app/common/helper/services/occupancy.service';
|
||||
import { AqiDataService } from '@app/common/helper/services/aqi.data.service';
|
||||
@Injectable()
|
||||
export class DeviceStatusFirebaseService {
|
||||
private tuya: TuyaContext;
|
||||
private firebaseDb: Database;
|
||||
private readonly isDevEnv: boolean;
|
||||
|
||||
constructor(
|
||||
private readonly configService: ConfigService,
|
||||
private readonly deviceRepository: DeviceRepository,
|
||||
private readonly powerClampService: PowerClampService,
|
||||
private readonly occupancyService: OccupancyService,
|
||||
private readonly aqiDataService: AqiDataService,
|
||||
private deviceStatusLogRepository: DeviceStatusLogRepository,
|
||||
) {
|
||||
const accessKey = this.configService.get<string>('auth-config.ACCESS_KEY');
|
||||
@ -47,6 +40,8 @@ export class DeviceStatusFirebaseService {
|
||||
|
||||
// Initialize firebaseDb using firebaseDataBase function
|
||||
this.firebaseDb = firebaseDataBase(this.configService);
|
||||
this.isDevEnv =
|
||||
this.configService.get<string>('NODE_ENV') === 'development';
|
||||
}
|
||||
async addDeviceStatusByDeviceUuid(
|
||||
deviceTuyaUuid: string,
|
||||
@ -61,7 +56,7 @@ export class DeviceStatusFirebaseService {
|
||||
const deviceStatusSaved = await this.createDeviceStatusFirebase({
|
||||
deviceUuid: device.uuid,
|
||||
deviceTuyaUuid: deviceTuyaUuid,
|
||||
status: deviceStatus.status,
|
||||
status: deviceStatus?.status,
|
||||
productUuid: deviceStatus.productUuid,
|
||||
productType: deviceStatus.productType,
|
||||
});
|
||||
@ -76,47 +71,94 @@ export class DeviceStatusFirebaseService {
|
||||
);
|
||||
}
|
||||
}
|
||||
async addDeviceStatusToOurDb(
|
||||
addDeviceStatusDto: AddDeviceStatusDto,
|
||||
): Promise<AddDeviceStatusDto | null> {
|
||||
try {
|
||||
const device = await this.getDeviceByDeviceTuyaUuid(
|
||||
addDeviceStatusDto.deviceTuyaUuid,
|
||||
);
|
||||
async addBatchDeviceStatusToOurDb(
|
||||
batch: {
|
||||
deviceTuyaUuid: string;
|
||||
status: any;
|
||||
log: any;
|
||||
device: any;
|
||||
}[],
|
||||
): Promise<void> {
|
||||
const allLogs = [];
|
||||
|
||||
if (device?.uuid) {
|
||||
return await this.createDeviceStatusInOurDb({
|
||||
deviceUuid: device.uuid,
|
||||
...addDeviceStatusDto,
|
||||
productType: device.productDevice.prodType,
|
||||
});
|
||||
console.log(`🔁 Preparing logs from batch of ${batch.length} items...`);
|
||||
|
||||
for (const item of batch) {
|
||||
const device = item.device;
|
||||
if (!device?.uuid) {
|
||||
console.log(`⛔ Skipped unknown device: ${item.deviceTuyaUuid}`);
|
||||
continue;
|
||||
}
|
||||
// Return null if device not found or no UUID
|
||||
return null;
|
||||
} catch (error) {
|
||||
// Handle the error silently, perhaps log it internally or ignore it
|
||||
return null;
|
||||
|
||||
const logs = item.log.properties.map((property) =>
|
||||
this.deviceStatusLogRepository.create({
|
||||
deviceId: device.uuid,
|
||||
deviceTuyaId: item.deviceTuyaUuid,
|
||||
productId: item.log.productId,
|
||||
log: item.log,
|
||||
code: property.code,
|
||||
value: property.value,
|
||||
eventId: item.log.dataId,
|
||||
eventTime: new Date(property.time).toISOString(),
|
||||
}),
|
||||
);
|
||||
allLogs.push(...logs);
|
||||
}
|
||||
|
||||
console.log(`📝 Total logs to insert: ${allLogs.length}`);
|
||||
|
||||
const insertLogsPromise = (async () => {
|
||||
const chunkSize = 300;
|
||||
let insertedCount = 0;
|
||||
|
||||
for (let i = 0; i < allLogs.length; i += chunkSize) {
|
||||
const chunk = allLogs.slice(i, i + chunkSize);
|
||||
try {
|
||||
const result = await this.deviceStatusLogRepository
|
||||
.createQueryBuilder()
|
||||
.insert()
|
||||
.into('device-status-log') // or use DeviceStatusLogEntity
|
||||
.values(chunk)
|
||||
.orIgnore() // skip duplicates
|
||||
.execute();
|
||||
|
||||
insertedCount += result.identifiers.length;
|
||||
console.log(
|
||||
`✅ Inserted ${result.identifiers.length} / ${chunk.length} logs (chunk)`,
|
||||
);
|
||||
} catch (error) {
|
||||
console.error('❌ Insert error (skipped chunk):', error.message);
|
||||
}
|
||||
}
|
||||
|
||||
console.log(
|
||||
`✅ Total logs inserted: ${insertedCount} / ${allLogs.length}`,
|
||||
);
|
||||
})();
|
||||
|
||||
await insertLogsPromise;
|
||||
}
|
||||
|
||||
async addDeviceStatusToFirebase(
|
||||
addDeviceStatusDto: AddDeviceStatusDto,
|
||||
addDeviceStatusDto: AddDeviceStatusDto & { device?: any },
|
||||
): Promise<AddDeviceStatusDto | null> {
|
||||
try {
|
||||
const device = await this.getDeviceByDeviceTuyaUuid(
|
||||
addDeviceStatusDto.deviceTuyaUuid,
|
||||
);
|
||||
|
||||
let device = addDeviceStatusDto.device;
|
||||
if (!device) {
|
||||
device = await this.getDeviceByDeviceTuyaUuid(
|
||||
addDeviceStatusDto.deviceTuyaUuid,
|
||||
);
|
||||
}
|
||||
if (device?.uuid) {
|
||||
return await this.createDeviceStatusFirebase({
|
||||
deviceUuid: device.uuid,
|
||||
...addDeviceStatusDto,
|
||||
productType: device.productDevice.prodType,
|
||||
productType: device.productDevice?.prodType,
|
||||
});
|
||||
}
|
||||
// Return null if device not found or no UUID
|
||||
return null;
|
||||
} catch (error) {
|
||||
// Handle the error silently, perhaps log it internally or ignore it
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@ -130,6 +172,15 @@ export class DeviceStatusFirebaseService {
|
||||
relations: ['productDevice'],
|
||||
});
|
||||
}
|
||||
async getAllDevices() {
|
||||
return await this.deviceRepository.find({
|
||||
where: {
|
||||
isActive: true,
|
||||
},
|
||||
relations: ['productDevice'],
|
||||
});
|
||||
}
|
||||
|
||||
async getDevicesInstructionStatus(deviceUuid: string) {
|
||||
try {
|
||||
const deviceDetails = await this.getDeviceByDeviceUuid(deviceUuid);
|
||||
@ -144,7 +195,7 @@ export class DeviceStatusFirebaseService {
|
||||
return {
|
||||
productUuid: deviceDetails.productDevice.uuid,
|
||||
productType: deviceDetails.productDevice.prodType,
|
||||
status: deviceStatus.result[0].status,
|
||||
status: deviceStatus.result[0]?.status,
|
||||
};
|
||||
} catch (error) {
|
||||
throw new HttpException(
|
||||
@ -209,18 +260,18 @@ export class DeviceStatusFirebaseService {
|
||||
if (!existingData.productType) {
|
||||
existingData.productType = addDeviceStatusDto.productType;
|
||||
}
|
||||
if (!existingData.status) {
|
||||
if (!existingData?.status) {
|
||||
existingData.status = [];
|
||||
}
|
||||
|
||||
// Create a map to track existing status codes
|
||||
const statusMap = new Map(
|
||||
existingData.status.map((item) => [item.code, item.value]),
|
||||
existingData?.status.map((item) => [item.code, item.value]),
|
||||
);
|
||||
|
||||
// Update or add status codes
|
||||
|
||||
for (const statusItem of addDeviceStatusDto.status) {
|
||||
for (const statusItem of addDeviceStatusDto?.status) {
|
||||
statusMap.set(statusItem.code, statusItem.value);
|
||||
}
|
||||
|
||||
@ -237,66 +288,4 @@ export class DeviceStatusFirebaseService {
|
||||
const snapshot: DataSnapshot = await get(dataRef);
|
||||
return snapshot.val();
|
||||
}
|
||||
async createDeviceStatusInOurDb(
|
||||
addDeviceStatusDto: AddDeviceStatusDto,
|
||||
): Promise<any> {
|
||||
// Save logs to your repository
|
||||
const newLogs = addDeviceStatusDto.log.properties.map((property) => {
|
||||
return this.deviceStatusLogRepository.create({
|
||||
deviceId: addDeviceStatusDto.deviceUuid,
|
||||
deviceTuyaId: addDeviceStatusDto.deviceTuyaUuid,
|
||||
productId: addDeviceStatusDto.log.productId,
|
||||
log: addDeviceStatusDto.log,
|
||||
code: property.code,
|
||||
value: property.value,
|
||||
eventId: addDeviceStatusDto.log.dataId,
|
||||
eventTime: new Date(property.time).toISOString(),
|
||||
});
|
||||
});
|
||||
await this.deviceStatusLogRepository.save(newLogs);
|
||||
|
||||
if (addDeviceStatusDto.productType === ProductType.PC) {
|
||||
const energyCodes = new Set([
|
||||
PowerClampEnergyEnum.ENERGY_CONSUMED,
|
||||
PowerClampEnergyEnum.ENERGY_CONSUMED_A,
|
||||
PowerClampEnergyEnum.ENERGY_CONSUMED_B,
|
||||
PowerClampEnergyEnum.ENERGY_CONSUMED_C,
|
||||
]);
|
||||
|
||||
const energyStatus = addDeviceStatusDto?.log?.properties?.find((status) =>
|
||||
energyCodes.has(status.code),
|
||||
);
|
||||
|
||||
if (energyStatus) {
|
||||
await this.powerClampService.updateEnergyConsumedHistoricalData(
|
||||
addDeviceStatusDto.deviceUuid,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if (
|
||||
addDeviceStatusDto.productType === ProductType.CPS ||
|
||||
addDeviceStatusDto.productType === ProductType.WPS
|
||||
) {
|
||||
const occupancyCodes = new Set([PresenceSensorEnum.PRESENCE_STATE]);
|
||||
|
||||
const occupancyStatus = addDeviceStatusDto?.log?.properties?.find(
|
||||
(status) => occupancyCodes.has(status.code),
|
||||
);
|
||||
|
||||
if (occupancyStatus) {
|
||||
await this.occupancyService.updateOccupancySensorHistoricalData(
|
||||
addDeviceStatusDto.deviceUuid,
|
||||
);
|
||||
await this.occupancyService.updateOccupancySensorHistoricalDurationData(
|
||||
addDeviceStatusDto.deviceUuid,
|
||||
);
|
||||
}
|
||||
}
|
||||
if (addDeviceStatusDto.productType === ProductType.AQI) {
|
||||
await this.aqiDataService.updateAQISensorHistoricalData(
|
||||
addDeviceStatusDto.deviceUuid,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -8,7 +8,10 @@ import { TuyaWebSocketService } from './services/tuya.web.socket.service';
|
||||
import { OneSignalService } from './services/onesignal.service';
|
||||
import { DeviceMessagesService } from './services/device.messages.service';
|
||||
import { DeviceRepositoryModule } from '../modules/device/device.repository.module';
|
||||
import { DeviceNotificationRepository } from '../modules/device/repositories';
|
||||
import {
|
||||
DeviceNotificationRepository,
|
||||
DeviceRepository,
|
||||
} from '../modules/device/repositories';
|
||||
import { DeviceStatusFirebaseModule } from '../firebase/devices-status/devices-status.module';
|
||||
import { CommunityPermissionService } from './services/community.permission.service';
|
||||
import { CommunityRepository } from '../modules/community/repositories';
|
||||
@ -27,6 +30,7 @@ import { SosHandlerService } from './services/sos.handler.service';
|
||||
DeviceNotificationRepository,
|
||||
CommunityRepository,
|
||||
SosHandlerService,
|
||||
DeviceRepository,
|
||||
],
|
||||
exports: [
|
||||
HelperHashService,
|
||||
|
@ -1,44 +1,63 @@
|
||||
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';
|
||||
import { SqlLoaderService } from './sql-loader.service';
|
||||
|
||||
@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],
|
||||
);
|
||||
async updateAQISensorHistoricalData(): Promise<void> {
|
||||
try {
|
||||
const { dateStr } = this.getFormattedDates();
|
||||
|
||||
// Execute all procedures in parallel
|
||||
await Promise.all([
|
||||
this.executeProcedureWithRetry(
|
||||
'proceduce_update_daily_space_aqi',
|
||||
[dateStr],
|
||||
'fact_daily_space_aqi',
|
||||
),
|
||||
]);
|
||||
} catch (err) {
|
||||
console.error('Failed to insert or update aqi data:', err);
|
||||
console.error('Failed to update AQI sensor historical data:', err);
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
private async executeProcedure(
|
||||
procedureFolderName: string,
|
||||
private getFormattedDates(): { dateStr: string } {
|
||||
const now = new Date();
|
||||
return {
|
||||
dateStr: now.toLocaleDateString('en-CA'), // YYYY-MM-DD
|
||||
};
|
||||
}
|
||||
private async executeProcedureWithRetry(
|
||||
procedureFileName: string,
|
||||
params: (string | number | null)[],
|
||||
folderName: string,
|
||||
retries = 3,
|
||||
): Promise<void> {
|
||||
const query = this.loadQuery(procedureFolderName, procedureFileName);
|
||||
await this.dataSource.query(query, params);
|
||||
console.log(`Procedure ${procedureFileName} executed successfully.`);
|
||||
try {
|
||||
const query = this.loadQuery(folderName, procedureFileName);
|
||||
await this.dataSource.query(query, params);
|
||||
console.log(`Procedure ${procedureFileName} executed successfully.`);
|
||||
} catch (err) {
|
||||
if (retries > 0) {
|
||||
const delayMs = 1000 * (4 - retries); // Exponential backoff
|
||||
console.warn(`Retrying ${procedureFileName} (${retries} retries left)`);
|
||||
await new Promise((resolve) => setTimeout(resolve, delayMs));
|
||||
return this.executeProcedureWithRetry(
|
||||
procedureFileName,
|
||||
params,
|
||||
folderName,
|
||||
retries - 1,
|
||||
);
|
||||
}
|
||||
console.error(`Failed to execute ${procedureFileName}:`, err);
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
private loadQuery(folderName: string, fileName: string): string {
|
||||
|
@ -1,65 +1,68 @@
|
||||
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';
|
||||
import { SqlLoaderService } from './sql-loader.service';
|
||||
|
||||
@Injectable()
|
||||
export class OccupancyService {
|
||||
constructor(
|
||||
private readonly sqlLoader: SqlLoaderService,
|
||||
private readonly dataSource: DataSource,
|
||||
private readonly deviceRepository: DeviceRepository,
|
||||
) {}
|
||||
async updateOccupancySensorHistoricalDurationData(
|
||||
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_occupancy_duration',
|
||||
'procedure_update_daily_space_occupancy_duration',
|
||||
[dateStr, device.spaceDevice?.uuid],
|
||||
);
|
||||
async updateOccupancyDataProcedures(): Promise<void> {
|
||||
try {
|
||||
const { dateStr } = this.getFormattedDates();
|
||||
|
||||
// Execute all procedures in parallel
|
||||
await Promise.all([
|
||||
this.executeProcedureWithRetry(
|
||||
'procedure_update_fact_space_occupancy',
|
||||
[dateStr],
|
||||
'fact_space_occupancy_count',
|
||||
),
|
||||
this.executeProcedureWithRetry(
|
||||
'procedure_update_daily_space_occupancy_duration',
|
||||
[dateStr],
|
||||
'fact_daily_space_occupancy_duration',
|
||||
),
|
||||
]);
|
||||
} catch (err) {
|
||||
console.error('Failed to insert or update occupancy duration data:', err);
|
||||
console.error('Failed to update occupancy data:', err);
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
async updateOccupancySensorHistoricalData(deviceUuid: string): Promise<void> {
|
||||
try {
|
||||
const now = new Date();
|
||||
const dateStr = now.toLocaleDateString('en-CA'); // YYYY-MM-DD
|
||||
const device = await this.deviceRepository.findOne({
|
||||
where: { uuid: deviceUuid },
|
||||
relations: ['spaceDevice'],
|
||||
});
|
||||
|
||||
await this.executeProcedure(
|
||||
'fact_space_occupancy_count',
|
||||
'procedure_update_fact_space_occupancy',
|
||||
[dateStr, device.spaceDevice?.uuid],
|
||||
);
|
||||
} catch (err) {
|
||||
console.error('Failed to insert or update occupancy data:', err);
|
||||
throw err;
|
||||
}
|
||||
private getFormattedDates(): { dateStr: string } {
|
||||
const now = new Date();
|
||||
return {
|
||||
dateStr: now.toLocaleDateString('en-CA'), // YYYY-MM-DD
|
||||
};
|
||||
}
|
||||
|
||||
private async executeProcedure(
|
||||
procedureFolderName: string,
|
||||
private async executeProcedureWithRetry(
|
||||
procedureFileName: string,
|
||||
params: (string | number | null)[],
|
||||
folderName: string,
|
||||
retries = 3,
|
||||
): Promise<void> {
|
||||
const query = this.loadQuery(procedureFolderName, procedureFileName);
|
||||
await this.dataSource.query(query, params);
|
||||
console.log(`Procedure ${procedureFileName} executed successfully.`);
|
||||
try {
|
||||
const query = this.loadQuery(folderName, procedureFileName);
|
||||
await this.dataSource.query(query, params);
|
||||
console.log(`Procedure ${procedureFileName} executed successfully.`);
|
||||
} catch (err) {
|
||||
if (retries > 0) {
|
||||
const delayMs = 1000 * (4 - retries); // Exponential backoff
|
||||
console.warn(`Retrying ${procedureFileName} (${retries} retries left)`);
|
||||
await new Promise((resolve) => setTimeout(resolve, delayMs));
|
||||
return this.executeProcedureWithRetry(
|
||||
procedureFileName,
|
||||
params,
|
||||
folderName,
|
||||
retries - 1,
|
||||
);
|
||||
}
|
||||
console.error(`Failed to execute ${procedureFileName}:`, err);
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
private loadQuery(folderName: string, fileName: string): string {
|
||||
|
@ -1,7 +1,7 @@
|
||||
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';
|
||||
import { SqlLoaderService } from './sql-loader.service';
|
||||
|
||||
@Injectable()
|
||||
export class PowerClampService {
|
||||
@ -10,48 +10,72 @@ export class PowerClampService {
|
||||
private readonly dataSource: DataSource,
|
||||
) {}
|
||||
|
||||
async updateEnergyConsumedHistoricalData(deviceUuid: string): Promise<void> {
|
||||
async updateEnergyConsumedHistoricalData(): Promise<void> {
|
||||
try {
|
||||
const now = new Date();
|
||||
const dateStr = now.toLocaleDateString('en-CA'); // YYYY-MM-DD
|
||||
const hour = now.getHours();
|
||||
const monthYear = now
|
||||
.toLocaleDateString('en-US', {
|
||||
month: '2-digit',
|
||||
year: 'numeric',
|
||||
})
|
||||
.replace('/', '-'); // MM-YYYY
|
||||
const { dateStr, monthYear } = this.getFormattedDates();
|
||||
|
||||
await this.executeProcedure(
|
||||
'fact_hourly_device_energy_consumed_procedure',
|
||||
[deviceUuid, dateStr, hour],
|
||||
);
|
||||
|
||||
await this.executeProcedure(
|
||||
'fact_daily_device_energy_consumed_procedure',
|
||||
[deviceUuid, dateStr],
|
||||
);
|
||||
|
||||
await this.executeProcedure(
|
||||
'fact_monthly_device_energy_consumed_procedure',
|
||||
[deviceUuid, monthYear],
|
||||
);
|
||||
// Execute all procedures in parallel
|
||||
await Promise.all([
|
||||
this.executeProcedureWithRetry(
|
||||
'fact_hourly_device_energy_consumed_procedure',
|
||||
[dateStr],
|
||||
'fact_device_energy_consumed',
|
||||
),
|
||||
this.executeProcedureWithRetry(
|
||||
'fact_daily_device_energy_consumed_procedure',
|
||||
[dateStr],
|
||||
'fact_device_energy_consumed',
|
||||
),
|
||||
this.executeProcedureWithRetry(
|
||||
'fact_monthly_device_energy_consumed_procedure',
|
||||
[monthYear],
|
||||
'fact_device_energy_consumed',
|
||||
),
|
||||
]);
|
||||
} catch (err) {
|
||||
console.error('Failed to insert or update energy data:', err);
|
||||
console.error('Failed to update energy consumption data:', err);
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
private async executeProcedure(
|
||||
private getFormattedDates(): { dateStr: string; monthYear: string } {
|
||||
const now = new Date();
|
||||
return {
|
||||
dateStr: now.toLocaleDateString('en-CA'), // YYYY-MM-DD
|
||||
monthYear: now
|
||||
.toLocaleDateString('en-US', {
|
||||
month: '2-digit',
|
||||
year: 'numeric',
|
||||
})
|
||||
.replace('/', '-'), // MM-YYYY
|
||||
};
|
||||
}
|
||||
|
||||
private async executeProcedureWithRetry(
|
||||
procedureFileName: string,
|
||||
params: (string | number | null)[],
|
||||
folderName: string,
|
||||
retries = 3,
|
||||
): Promise<void> {
|
||||
const query = this.loadQuery(
|
||||
'fact_device_energy_consumed',
|
||||
procedureFileName,
|
||||
);
|
||||
await this.dataSource.query(query, params);
|
||||
console.log(`Procedure ${procedureFileName} executed successfully.`);
|
||||
try {
|
||||
const query = this.loadQuery(folderName, procedureFileName);
|
||||
await this.dataSource.query(query, params);
|
||||
console.log(`Procedure ${procedureFileName} executed successfully.`);
|
||||
} catch (err) {
|
||||
if (retries > 0) {
|
||||
const delayMs = 1000 * (4 - retries); // Exponential backoff
|
||||
console.warn(`Retrying ${procedureFileName} (${retries} retries left)`);
|
||||
await new Promise((resolve) => setTimeout(resolve, delayMs));
|
||||
return this.executeProcedureWithRetry(
|
||||
procedureFileName,
|
||||
params,
|
||||
folderName,
|
||||
retries - 1,
|
||||
);
|
||||
}
|
||||
console.error(`Failed to execute ${procedureFileName}:`, err);
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
private loadQuery(folderName: string, fileName: string): string {
|
||||
|
@ -16,45 +16,46 @@ export class SosHandlerService {
|
||||
);
|
||||
}
|
||||
|
||||
async handleSosEventFirebase(devId: string, logData: any): Promise<void> {
|
||||
async handleSosEventFirebase(device: any, logData: any): Promise<void> {
|
||||
const sosTrueStatus = [{ code: 'sos', value: true }];
|
||||
const sosFalseStatus = [{ code: 'sos', value: false }];
|
||||
|
||||
try {
|
||||
// ✅ Send true status
|
||||
await this.deviceStatusFirebaseService.addDeviceStatusToFirebase({
|
||||
deviceTuyaUuid: devId,
|
||||
status: [{ code: 'sos', value: true }],
|
||||
deviceTuyaUuid: device.deviceTuyaUuid,
|
||||
status: sosTrueStatus,
|
||||
log: logData,
|
||||
device,
|
||||
});
|
||||
|
||||
await this.deviceStatusFirebaseService.addBatchDeviceStatusToOurDb([
|
||||
{
|
||||
deviceTuyaUuid: device.deviceTuyaUuid,
|
||||
status: sosTrueStatus,
|
||||
log: logData,
|
||||
device,
|
||||
},
|
||||
]);
|
||||
|
||||
// ✅ Schedule false status
|
||||
setTimeout(async () => {
|
||||
try {
|
||||
await this.deviceStatusFirebaseService.addDeviceStatusToFirebase({
|
||||
deviceTuyaUuid: devId,
|
||||
status: [{ code: 'sos', value: false }],
|
||||
deviceTuyaUuid: device.deviceTuyaUuid,
|
||||
status: sosFalseStatus,
|
||||
log: logData,
|
||||
device,
|
||||
});
|
||||
} catch (err) {
|
||||
this.logger.error('Failed to send SOS false value', err);
|
||||
}
|
||||
}, 2000);
|
||||
} catch (err) {
|
||||
this.logger.error('Failed to send SOS true value', err);
|
||||
}
|
||||
}
|
||||
|
||||
async handleSosEventOurDb(devId: string, logData: any): Promise<void> {
|
||||
try {
|
||||
await this.deviceStatusFirebaseService.addDeviceStatusToOurDb({
|
||||
deviceTuyaUuid: devId,
|
||||
status: [{ code: 'sos', value: true }],
|
||||
log: logData,
|
||||
});
|
||||
|
||||
setTimeout(async () => {
|
||||
try {
|
||||
await this.deviceStatusFirebaseService.addDeviceStatusToOurDb({
|
||||
deviceTuyaUuid: devId,
|
||||
status: [{ code: 'sos', value: false }],
|
||||
log: logData,
|
||||
});
|
||||
await this.deviceStatusFirebaseService.addBatchDeviceStatusToOurDb([
|
||||
{
|
||||
deviceTuyaUuid: device.deviceTuyaUuid,
|
||||
status: sosFalseStatus,
|
||||
log: logData,
|
||||
device,
|
||||
},
|
||||
]);
|
||||
} catch (err) {
|
||||
this.logger.error('Failed to send SOS false value', err);
|
||||
}
|
||||
|
@ -1,18 +1,21 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { Injectable, OnModuleInit } from '@nestjs/common';
|
||||
import TuyaWebsocket from '../../config/tuya-web-socket-config';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { DeviceStatusFirebaseService } from '@app/common/firebase/devices-status/services/devices-status.service';
|
||||
import { SosHandlerService } from './sos.handler.service';
|
||||
import * as NodeCache from 'node-cache';
|
||||
|
||||
@Injectable()
|
||||
export class TuyaWebSocketService {
|
||||
export class TuyaWebSocketService implements OnModuleInit {
|
||||
private client: any;
|
||||
private readonly isDevEnv: boolean;
|
||||
private readonly deviceCache = new NodeCache({ stdTTL: 7200 }); // TTL = 2 hour
|
||||
|
||||
private messageQueue: {
|
||||
devId: string;
|
||||
status: any;
|
||||
logData: any;
|
||||
device: any;
|
||||
}[] = [];
|
||||
|
||||
private isProcessing = false;
|
||||
@ -38,12 +41,32 @@ export class TuyaWebSocketService {
|
||||
this.client.start();
|
||||
}
|
||||
|
||||
// Trigger the queue processor every 2 seconds
|
||||
setInterval(() => this.processQueue(), 10000);
|
||||
// Run the queue processor every 15 seconds
|
||||
setInterval(() => this.processQueue(), 15000);
|
||||
|
||||
// Refresh the cache every 1 hour
|
||||
setInterval(() => this.initializeDeviceCache(), 30 * 60 * 1000); // 30 minutes
|
||||
}
|
||||
|
||||
async onModuleInit() {
|
||||
await this.initializeDeviceCache();
|
||||
}
|
||||
|
||||
private async initializeDeviceCache() {
|
||||
try {
|
||||
const allDevices = await this.deviceStatusFirebaseService.getAllDevices();
|
||||
allDevices.forEach((device) => {
|
||||
if (device.deviceTuyaUuid) {
|
||||
this.deviceCache.set(device.deviceTuyaUuid, device);
|
||||
}
|
||||
});
|
||||
console.log(`✅ Refreshed cache with ${allDevices.length} devices.`);
|
||||
} catch (error) {
|
||||
console.error('❌ Failed to initialize device cache:', error);
|
||||
}
|
||||
}
|
||||
|
||||
private setupEventHandlers() {
|
||||
// Event handlers
|
||||
this.client.open(() => {
|
||||
console.log('open');
|
||||
});
|
||||
@ -51,27 +74,38 @@ export class TuyaWebSocketService {
|
||||
this.client.message(async (ws: WebSocket, message: any) => {
|
||||
try {
|
||||
const { devId, status, logData } = this.extractMessageData(message);
|
||||
if (!Array.isArray(logData?.properties)) {
|
||||
this.client.ackMessage(message.messageId);
|
||||
return;
|
||||
}
|
||||
|
||||
const device = this.deviceCache.get(devId);
|
||||
if (!device) {
|
||||
// console.log(⛔ Unknown device: ${devId}, message ignored.);
|
||||
this.client.ackMessage(message.messageId);
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.sosHandlerService.isSosTriggered(status)) {
|
||||
await this.sosHandlerService.handleSosEventFirebase(devId, logData);
|
||||
} else {
|
||||
// Firebase real-time update
|
||||
await this.deviceStatusFirebaseService.addDeviceStatusToFirebase({
|
||||
deviceTuyaUuid: devId,
|
||||
status: status,
|
||||
status,
|
||||
log: logData,
|
||||
device,
|
||||
});
|
||||
}
|
||||
|
||||
// Push to internal queue
|
||||
this.messageQueue.push({ devId, status, logData });
|
||||
this.messageQueue.push({ devId, status, logData, device });
|
||||
|
||||
// Acknowledge the message
|
||||
this.client.ackMessage(message.messageId);
|
||||
} catch (error) {
|
||||
console.error('Error receiving message:', error);
|
||||
console.error('❌ Error receiving message:', error);
|
||||
}
|
||||
});
|
||||
|
||||
this.client.reconnect(() => {
|
||||
console.log('reconnect');
|
||||
});
|
||||
@ -93,32 +127,31 @@ export class TuyaWebSocketService {
|
||||
});
|
||||
}
|
||||
private async processQueue() {
|
||||
if (this.isProcessing || this.messageQueue.length === 0) return;
|
||||
if (this.isProcessing) {
|
||||
console.log('⏳ Skipping: still processing previous batch');
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.messageQueue.length === 0) return;
|
||||
|
||||
this.isProcessing = true;
|
||||
|
||||
const batch = [...this.messageQueue];
|
||||
this.messageQueue = [];
|
||||
|
||||
console.log(`🔁 Processing batch of size: ${batch.length}`);
|
||||
|
||||
try {
|
||||
for (const item of batch) {
|
||||
if (this.sosHandlerService.isSosTriggered(item.status)) {
|
||||
await this.sosHandlerService.handleSosEventOurDb(
|
||||
item.devId,
|
||||
item.logData,
|
||||
);
|
||||
} else {
|
||||
await this.deviceStatusFirebaseService.addDeviceStatusToOurDb({
|
||||
deviceTuyaUuid: item.devId,
|
||||
status: item.status,
|
||||
log: item.logData,
|
||||
});
|
||||
}
|
||||
}
|
||||
await this.deviceStatusFirebaseService.addBatchDeviceStatusToOurDb(
|
||||
batch.map((item) => ({
|
||||
deviceTuyaUuid: item.devId,
|
||||
status: item.status,
|
||||
log: item.logData,
|
||||
device: item.device,
|
||||
})),
|
||||
);
|
||||
} catch (error) {
|
||||
console.error('Error processing batch:', error);
|
||||
// Re-add the batch to the queue for retry
|
||||
this.messageQueue.unshift(...batch);
|
||||
console.error('❌ Error processing batch:', error);
|
||||
this.messageQueue.unshift(...batch); // retry
|
||||
} finally {
|
||||
this.isProcessing = false;
|
||||
}
|
||||
|
5
libs/common/src/helper/timeToMinutes.ts
Normal file
5
libs/common/src/helper/timeToMinutes.ts
Normal file
@ -0,0 +1,5 @@
|
||||
// Convert time string (HH:mm) to minutes
|
||||
export function timeToMinutes(time: string): number {
|
||||
const [hours, minutes] = time.split(':').map(Number);
|
||||
return hours * 60 + minutes;
|
||||
}
|
@ -49,12 +49,12 @@ export class TuyaService {
|
||||
path,
|
||||
});
|
||||
|
||||
if (!response.success) {
|
||||
throw new HttpException(
|
||||
`Error fetching device details: ${response.msg}`,
|
||||
HttpStatus.BAD_REQUEST,
|
||||
);
|
||||
}
|
||||
// if (!response.success) {
|
||||
// throw new HttpException(
|
||||
// `Error fetching device details: ${response.msg}`,
|
||||
// HttpStatus.BAD_REQUEST,
|
||||
// );
|
||||
// }
|
||||
|
||||
return response.result;
|
||||
}
|
||||
|
@ -1,43 +1,26 @@
|
||||
import { utilities as nestWinstonModuleUtilities } from 'nest-winston';
|
||||
import * as winston from 'winston';
|
||||
const environment = process.env.NODE_ENV || 'local';
|
||||
|
||||
export const winstonLoggerOptions: winston.LoggerOptions = {
|
||||
level:
|
||||
environment === 'local'
|
||||
? 'debug'
|
||||
: environment === 'development'
|
||||
? 'warn'
|
||||
: 'error',
|
||||
process.env.AZURE_POSTGRESQL_DATABASE === 'development' ? 'debug' : 'error',
|
||||
transports: [
|
||||
new winston.transports.Console({
|
||||
level:
|
||||
environment === 'local'
|
||||
? 'debug'
|
||||
: environment === 'development'
|
||||
? 'warn'
|
||||
: 'error',
|
||||
format: winston.format.combine(
|
||||
winston.format.timestamp(),
|
||||
nestWinstonModuleUtilities.format.nestLike('MyApp', {
|
||||
prettyPrint: environment === 'local',
|
||||
prettyPrint: true,
|
||||
}),
|
||||
),
|
||||
}),
|
||||
// Only create file logs if NOT local
|
||||
...(environment !== 'local'
|
||||
? [
|
||||
new winston.transports.File({
|
||||
filename: 'logs/error.log',
|
||||
level: 'error',
|
||||
format: winston.format.json(),
|
||||
}),
|
||||
new winston.transports.File({
|
||||
filename: 'logs/combined.log',
|
||||
level: 'info',
|
||||
format: winston.format.json(),
|
||||
}),
|
||||
]
|
||||
: []),
|
||||
new winston.transports.File({
|
||||
filename: 'logs/error.log',
|
||||
level: 'error',
|
||||
format: winston.format.json(),
|
||||
}),
|
||||
new winston.transports.File({
|
||||
filename: 'logs/combined.log',
|
||||
format: winston.format.json(),
|
||||
}),
|
||||
],
|
||||
};
|
||||
|
@ -8,14 +8,14 @@ import {
|
||||
Unique,
|
||||
} from 'typeorm';
|
||||
|
||||
import { AbstractEntity } from '../../abstract/entities/abstract.entity';
|
||||
import { RoleTypeEntity } from '../../role-type/entities';
|
||||
import { UserStatusEnum } from '@app/common/constants/user-status.enum';
|
||||
import { UserEntity } from '../../user/entities';
|
||||
import { RoleType } from '@app/common/constants/role.type.enum';
|
||||
import { InviteUserDto, InviteUserSpaceDto } from '../dtos';
|
||||
import { UserStatusEnum } from '@app/common/constants/user-status.enum';
|
||||
import { AbstractEntity } from '../../abstract/entities/abstract.entity';
|
||||
import { ProjectEntity } from '../../project/entities';
|
||||
import { RoleTypeEntity } from '../../role-type/entities';
|
||||
import { SpaceEntity } from '../../space/entities/space.entity';
|
||||
import { UserEntity } from '../../user/entities';
|
||||
import { InviteUserDto, InviteUserSpaceDto } from '../dtos';
|
||||
|
||||
@Entity({ name: 'invite-user' })
|
||||
@Unique(['email', 'project'])
|
||||
@ -82,7 +82,10 @@ export class InviteUserEntity extends AbstractEntity<InviteUserDto> {
|
||||
onDelete: 'CASCADE',
|
||||
})
|
||||
public roleType: RoleTypeEntity;
|
||||
@OneToOne(() => UserEntity, (user) => user.inviteUser, { nullable: true })
|
||||
@OneToOne(() => UserEntity, (user) => user.inviteUser, {
|
||||
nullable: true,
|
||||
onDelete: 'CASCADE',
|
||||
})
|
||||
@JoinColumn({ name: 'user_uuid' })
|
||||
user: UserEntity;
|
||||
@OneToMany(
|
||||
@ -112,7 +115,9 @@ export class InviteUserSpaceEntity extends AbstractEntity<InviteUserSpaceDto> {
|
||||
})
|
||||
public uuid: string;
|
||||
|
||||
@ManyToOne(() => InviteUserEntity, (inviteUser) => inviteUser.spaces)
|
||||
@ManyToOne(() => InviteUserEntity, (inviteUser) => inviteUser.spaces, {
|
||||
onDelete: 'CASCADE',
|
||||
})
|
||||
@JoinColumn({ name: 'invite_user_uuid' })
|
||||
public inviteUser: InviteUserEntity;
|
||||
|
||||
|
11
libs/common/src/modules/booking/booking.repository.module.ts
Normal file
11
libs/common/src/modules/booking/booking.repository.module.ts
Normal file
@ -0,0 +1,11 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { BookableSpaceEntity } from './entities/bookable-space.entity';
|
||||
|
||||
@Module({
|
||||
providers: [],
|
||||
exports: [],
|
||||
controllers: [],
|
||||
imports: [TypeOrmModule.forFeature([BookableSpaceEntity])],
|
||||
})
|
||||
export class BookableRepositoryModule {}
|
@ -0,0 +1,51 @@
|
||||
import { DaysEnum } from '@app/common/constants/days.enum';
|
||||
import {
|
||||
Column,
|
||||
CreateDateColumn,
|
||||
Entity,
|
||||
JoinColumn,
|
||||
OneToOne,
|
||||
UpdateDateColumn,
|
||||
} from 'typeorm';
|
||||
import { AbstractEntity } from '../../abstract/entities/abstract.entity';
|
||||
import { SpaceEntity } from '../../space/entities/space.entity';
|
||||
|
||||
@Entity('bookable-space')
|
||||
export class BookableSpaceEntity extends AbstractEntity {
|
||||
@Column({
|
||||
type: 'uuid',
|
||||
default: () => 'gen_random_uuid()',
|
||||
nullable: false,
|
||||
})
|
||||
public uuid: string;
|
||||
|
||||
@OneToOne(() => SpaceEntity, (space) => space.bookableConfig)
|
||||
@JoinColumn({ name: 'space_uuid' })
|
||||
space: SpaceEntity;
|
||||
|
||||
@Column({
|
||||
type: 'enum',
|
||||
enum: DaysEnum,
|
||||
array: true,
|
||||
nullable: false,
|
||||
})
|
||||
daysAvailable: DaysEnum[];
|
||||
|
||||
@Column({ type: 'time' })
|
||||
startTime: string;
|
||||
|
||||
@Column({ type: 'time' })
|
||||
endTime: string;
|
||||
|
||||
@Column({ type: Boolean, default: true })
|
||||
active: boolean;
|
||||
|
||||
@Column({ type: 'int', default: null })
|
||||
points?: number;
|
||||
|
||||
@CreateDateColumn()
|
||||
createdAt: Date;
|
||||
|
||||
@UpdateDateColumn()
|
||||
updatedAt: Date;
|
||||
}
|
1
libs/common/src/modules/booking/entities/index.ts
Normal file
1
libs/common/src/modules/booking/entities/index.ts
Normal file
@ -0,0 +1 @@
|
||||
export * from './bookable-space.entity';
|
@ -0,0 +1,10 @@
|
||||
import { DataSource, Repository } from 'typeorm';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { BookableSpaceEntity } from '../entities/bookable-space.entity';
|
||||
|
||||
@Injectable()
|
||||
export class BookableSpaceEntityRepository extends Repository<BookableSpaceEntity> {
|
||||
constructor(private dataSource: DataSource) {
|
||||
super(BookableSpaceEntity, dataSource.createEntityManager());
|
||||
}
|
||||
}
|
1
libs/common/src/modules/booking/repositories/index.ts
Normal file
1
libs/common/src/modules/booking/repositories/index.ts
Normal file
@ -0,0 +1 @@
|
||||
export * from './booking.repository';
|
@ -1,24 +1,24 @@
|
||||
import {
|
||||
Column,
|
||||
Entity,
|
||||
Index,
|
||||
JoinColumn,
|
||||
ManyToOne,
|
||||
OneToMany,
|
||||
Unique,
|
||||
Index,
|
||||
JoinColumn,
|
||||
} from 'typeorm';
|
||||
import { AbstractEntity } from '../../abstract/entities/abstract.entity';
|
||||
import { DeviceDto, DeviceUserPermissionDto } from '../dtos/device.dto';
|
||||
import { ProductEntity } from '../../product/entities';
|
||||
import { UserEntity } from '../../user/entities';
|
||||
import { DeviceNotificationDto } from '../dtos';
|
||||
import { PermissionTypeEntity } from '../../permission/entities';
|
||||
import { PowerClampHourlyEntity } from '../../power-clamp/entities/power-clamp.entity';
|
||||
import { PresenceSensorDailyDeviceEntity } from '../../presence-sensor/entities';
|
||||
import { ProductEntity } from '../../product/entities';
|
||||
import { SceneDeviceEntity } from '../../scene-device/entities';
|
||||
import { SpaceEntity } from '../../space/entities/space.entity';
|
||||
import { SubspaceEntity } from '../../space/entities/subspace/subspace.entity';
|
||||
import { NewTagEntity } from '../../tag';
|
||||
import { PowerClampHourlyEntity } from '../../power-clamp/entities/power-clamp.entity';
|
||||
import { PresenceSensorDailyDeviceEntity } from '../../presence-sensor/entities';
|
||||
import { UserEntity } from '../../user/entities';
|
||||
import { DeviceNotificationDto } from '../dtos';
|
||||
import { DeviceDto, DeviceUserPermissionDto } from '../dtos/device.dto';
|
||||
|
||||
@Entity({ name: 'device' })
|
||||
@Unique(['deviceTuyaUuid'])
|
||||
@ -28,6 +28,11 @@ export class DeviceEntity extends AbstractEntity<DeviceDto> {
|
||||
})
|
||||
deviceTuyaUuid: string;
|
||||
|
||||
@Column({
|
||||
nullable: true,
|
||||
})
|
||||
deviceTuyaConstUuid: string;
|
||||
|
||||
@Column({
|
||||
nullable: true,
|
||||
default: true,
|
||||
@ -111,6 +116,7 @@ export class DeviceNotificationEntity extends AbstractEntity<DeviceNotificationD
|
||||
|
||||
@ManyToOne(() => UserEntity, (user) => user.userPermission, {
|
||||
nullable: false,
|
||||
onDelete: 'CASCADE',
|
||||
})
|
||||
user: UserEntity;
|
||||
|
||||
@ -149,6 +155,7 @@ export class DeviceUserPermissionEntity extends AbstractEntity<DeviceUserPermiss
|
||||
|
||||
@ManyToOne(() => UserEntity, (user) => user.userPermission, {
|
||||
nullable: false,
|
||||
onDelete: 'CASCADE',
|
||||
})
|
||||
user: UserEntity;
|
||||
constructor(partial: Partial<DeviceUserPermissionEntity>) {
|
||||
|
@ -1,4 +1,12 @@
|
||||
import { Column, Entity, JoinColumn, ManyToOne, OneToMany } from 'typeorm';
|
||||
import {
|
||||
Column,
|
||||
Entity,
|
||||
JoinColumn,
|
||||
ManyToOne,
|
||||
OneToMany,
|
||||
OneToOne,
|
||||
} from 'typeorm';
|
||||
import { SpaceDto } from '../dtos';
|
||||
import { AbstractEntity } from '../../abstract/entities/abstract.entity';
|
||||
import { AqiSpaceDailyPollutantStatsEntity } from '../../aqi/entities';
|
||||
import { CommunityEntity } from '../../community/entities';
|
||||
@ -9,9 +17,9 @@ import { PresenceSensorDailySpaceEntity } from '../../presence-sensor/entities';
|
||||
import { SceneEntity } from '../../scene/entities';
|
||||
import { SpaceModelEntity } from '../../space-model';
|
||||
import { UserSpaceEntity } from '../../user/entities';
|
||||
import { SpaceDto } from '../dtos';
|
||||
import { SpaceProductAllocationEntity } from './space-product-allocation.entity';
|
||||
import { SubspaceEntity } from './subspace/subspace.entity';
|
||||
import { BookableSpaceEntity } from '../../booking/entities';
|
||||
|
||||
@Entity({ name: 'space' })
|
||||
export class SpaceEntity extends AbstractEntity<SpaceDto> {
|
||||
@ -115,6 +123,9 @@ export class SpaceEntity extends AbstractEntity<SpaceDto> {
|
||||
)
|
||||
occupancyDaily: SpaceDailyOccupancyDurationEntity[];
|
||||
|
||||
@OneToOne(() => BookableSpaceEntity, (bookable) => bookable.space)
|
||||
bookableConfig: BookableSpaceEntity;
|
||||
|
||||
constructor(partial: Partial<SpaceEntity>) {
|
||||
super();
|
||||
Object.assign(this, partial);
|
||||
|
@ -1,3 +1,4 @@
|
||||
import { defaultProfilePicture } from '@app/common/constants/default.profile.picture';
|
||||
import {
|
||||
Column,
|
||||
DeleteDateColumn,
|
||||
@ -8,27 +9,26 @@ import {
|
||||
OneToOne,
|
||||
Unique,
|
||||
} from 'typeorm';
|
||||
import { OtpType } from '../../../../src/constants/otp-type.enum';
|
||||
import { AbstractEntity } from '../../abstract/entities/abstract.entity';
|
||||
import { ClientEntity } from '../../client/entities';
|
||||
import {
|
||||
DeviceNotificationEntity,
|
||||
DeviceUserPermissionEntity,
|
||||
} from '../../device/entities';
|
||||
import { InviteUserEntity } from '../../Invite-user/entities';
|
||||
import { ProjectEntity } from '../../project/entities';
|
||||
import { RegionEntity } from '../../region/entities';
|
||||
import { RoleTypeEntity } from '../../role-type/entities';
|
||||
import { SpaceEntity } from '../../space/entities/space.entity';
|
||||
import { TimeZoneEntity } from '../../timezone/entities';
|
||||
import { VisitorPasswordEntity } from '../../visitor-password/entities';
|
||||
import {
|
||||
UserDto,
|
||||
UserNotificationDto,
|
||||
UserOtpDto,
|
||||
UserSpaceDto,
|
||||
} from '../dtos';
|
||||
import { AbstractEntity } from '../../abstract/entities/abstract.entity';
|
||||
import {
|
||||
DeviceNotificationEntity,
|
||||
DeviceUserPermissionEntity,
|
||||
} from '../../device/entities';
|
||||
import { defaultProfilePicture } from '@app/common/constants/default.profile.picture';
|
||||
import { RegionEntity } from '../../region/entities';
|
||||
import { TimeZoneEntity } from '../../timezone/entities';
|
||||
import { OtpType } from '../../../../src/constants/otp-type.enum';
|
||||
import { RoleTypeEntity } from '../../role-type/entities';
|
||||
import { VisitorPasswordEntity } from '../../visitor-password/entities';
|
||||
import { InviteUserEntity } from '../../Invite-user/entities';
|
||||
import { ProjectEntity } from '../../project/entities';
|
||||
import { SpaceEntity } from '../../space/entities/space.entity';
|
||||
import { ClientEntity } from '../../client/entities';
|
||||
|
||||
@Entity({ name: 'user' })
|
||||
export class UserEntity extends AbstractEntity<UserDto> {
|
||||
@ -94,7 +94,9 @@ export class UserEntity extends AbstractEntity<UserDto> {
|
||||
@Column({ type: 'timestamp', nullable: true })
|
||||
appAgreementAcceptedAt: Date;
|
||||
|
||||
@OneToMany(() => UserSpaceEntity, (userSpace) => userSpace.user)
|
||||
@OneToMany(() => UserSpaceEntity, (userSpace) => userSpace.user, {
|
||||
onDelete: 'CASCADE',
|
||||
})
|
||||
userSpaces: UserSpaceEntity[];
|
||||
|
||||
@OneToMany(
|
||||
@ -158,6 +160,7 @@ export class UserEntity extends AbstractEntity<UserDto> {
|
||||
export class UserNotificationEntity extends AbstractEntity<UserNotificationDto> {
|
||||
@ManyToOne(() => UserEntity, (user) => user.roleType, {
|
||||
nullable: false,
|
||||
onDelete: 'CASCADE',
|
||||
})
|
||||
user: UserEntity;
|
||||
@Column({
|
||||
@ -219,7 +222,10 @@ export class UserSpaceEntity extends AbstractEntity<UserSpaceDto> {
|
||||
})
|
||||
public uuid: string;
|
||||
|
||||
@ManyToOne(() => UserEntity, (user) => user.userSpaces, { nullable: false })
|
||||
@ManyToOne(() => UserEntity, (user) => user.userSpaces, {
|
||||
nullable: false,
|
||||
onDelete: 'CASCADE',
|
||||
})
|
||||
user: UserEntity;
|
||||
|
||||
@ManyToOne(() => SpaceEntity, (space) => space.userSpaces, {
|
||||
|
@ -1,7 +1,7 @@
|
||||
import { Column, Entity, ManyToOne, JoinColumn, Index } from 'typeorm';
|
||||
import { VisitorPasswordDto } from '../dtos';
|
||||
import { Column, Entity, Index, JoinColumn, ManyToOne } from 'typeorm';
|
||||
import { AbstractEntity } from '../../abstract/entities/abstract.entity';
|
||||
import { UserEntity } from '../../user/entities/user.entity';
|
||||
import { VisitorPasswordDto } from '../dtos';
|
||||
|
||||
@Entity({ name: 'visitor-password' })
|
||||
@Index('IDX_PASSWORD_TUYA_UUID', ['passwordTuyaUuid'])
|
||||
@ -14,6 +14,7 @@ export class VisitorPasswordEntity extends AbstractEntity<VisitorPasswordDto> {
|
||||
|
||||
@ManyToOne(() => UserEntity, (user) => user.visitorPasswords, {
|
||||
nullable: false,
|
||||
onDelete: 'CASCADE',
|
||||
})
|
||||
@JoinColumn({ name: 'authorizer_uuid' })
|
||||
public user: UserEntity;
|
||||
|
@ -1,7 +1,6 @@
|
||||
WITH params AS (
|
||||
SELECT
|
||||
TO_DATE(NULLIF($1, ''), 'YYYY-MM-DD') AS event_date,
|
||||
$2::uuid AS space_id
|
||||
TO_DATE(NULLIF($1, ''), 'YYYY-MM-DD') AS event_date
|
||||
),
|
||||
|
||||
-- Query Pipeline Starts Here
|
||||
@ -277,7 +276,10 @@ SELECT
|
||||
a.daily_avg_ch2o,a.daily_max_ch2o, a.daily_min_ch2o
|
||||
FROM daily_percentages p
|
||||
LEFT JOIN daily_averages a
|
||||
ON p.space_id = a.space_id AND p.event_date = a.event_date
|
||||
ON p.space_id = a.space_id
|
||||
AND p.event_date = a.event_date
|
||||
JOIN params
|
||||
ON params.event_date = a.event_date
|
||||
ORDER BY p.space_id, p.event_date)
|
||||
|
||||
|
||||
|
@ -1,7 +1,6 @@
|
||||
WITH params AS (
|
||||
SELECT
|
||||
TO_DATE(NULLIF($1, ''), 'YYYY-MM-DD') AS event_date,
|
||||
$2::uuid AS space_id
|
||||
TO_DATE(NULLIF($1, ''), 'YYYY-MM-DD') AS event_date
|
||||
),
|
||||
|
||||
presence_logs AS (
|
||||
@ -86,8 +85,7 @@ final_data AS (
|
||||
ROUND(LEAST(raw_occupied_seconds, 86400) / 86400.0 * 100, 2) AS occupancy_percentage
|
||||
FROM summed_intervals s
|
||||
JOIN params p
|
||||
ON p.space_id = s.space_id
|
||||
AND p.event_date = s.event_date
|
||||
ON p.event_date = s.event_date
|
||||
)
|
||||
|
||||
INSERT INTO public."space-daily-occupancy-duration" (
|
||||
|
@ -1,7 +1,6 @@
|
||||
WITH params AS (
|
||||
SELECT
|
||||
$1::uuid AS device_id,
|
||||
$2::date AS target_date
|
||||
$1::date AS target_date
|
||||
),
|
||||
total_energy AS (
|
||||
SELECT
|
||||
@ -14,8 +13,7 @@ total_energy AS (
|
||||
MAX(log.value)::integer AS max_value
|
||||
FROM "device-status-log" log, params
|
||||
WHERE log.code = 'EnergyConsumed'
|
||||
AND log.device_id = params.device_id
|
||||
AND log.event_time::date = params.target_date
|
||||
AND log.event_time::date = params.target_date
|
||||
GROUP BY 1,2,3,4,5
|
||||
),
|
||||
energy_phase_A AS (
|
||||
@ -29,8 +27,7 @@ energy_phase_A AS (
|
||||
MAX(log.value)::integer AS max_value
|
||||
FROM "device-status-log" log, params
|
||||
WHERE log.code = 'EnergyConsumedA'
|
||||
AND log.device_id = params.device_id
|
||||
AND log.event_time::date = params.target_date
|
||||
AND log.event_time::date = params.target_date
|
||||
GROUP BY 1,2,3,4,5
|
||||
),
|
||||
energy_phase_B AS (
|
||||
@ -44,8 +41,7 @@ energy_phase_B AS (
|
||||
MAX(log.value)::integer AS max_value
|
||||
FROM "device-status-log" log, params
|
||||
WHERE log.code = 'EnergyConsumedB'
|
||||
AND log.device_id = params.device_id
|
||||
AND log.event_time::date = params.target_date
|
||||
AND log.event_time::date = params.target_date
|
||||
GROUP BY 1,2,3,4,5
|
||||
),
|
||||
energy_phase_C AS (
|
||||
@ -59,8 +55,7 @@ energy_phase_C AS (
|
||||
MAX(log.value)::integer AS max_value
|
||||
FROM "device-status-log" log, params
|
||||
WHERE log.code = 'EnergyConsumedC'
|
||||
AND log.device_id = params.device_id
|
||||
AND log.event_time::date = params.target_date
|
||||
AND log.event_time::date = params.target_date
|
||||
GROUP BY 1,2,3,4,5
|
||||
),
|
||||
final_data AS (
|
||||
|
@ -1,8 +1,6 @@
|
||||
WITH params AS (
|
||||
SELECT
|
||||
$1::uuid AS device_id,
|
||||
$2::date AS target_date,
|
||||
$3::text AS target_hour
|
||||
$1::date AS target_date
|
||||
),
|
||||
total_energy AS (
|
||||
SELECT
|
||||
@ -15,9 +13,7 @@ total_energy AS (
|
||||
MAX(log.value)::integer AS max_value
|
||||
FROM "device-status-log" log, params
|
||||
WHERE log.code = 'EnergyConsumed'
|
||||
AND log.device_id = params.device_id
|
||||
AND log.event_time::date = params.target_date
|
||||
AND EXTRACT(HOUR FROM log.event_time)::text = params.target_hour
|
||||
GROUP BY 1,2,3,4,5
|
||||
),
|
||||
energy_phase_A AS (
|
||||
@ -31,9 +27,7 @@ energy_phase_A AS (
|
||||
MAX(log.value)::integer AS max_value
|
||||
FROM "device-status-log" log, params
|
||||
WHERE log.code = 'EnergyConsumedA'
|
||||
AND log.device_id = params.device_id
|
||||
AND log.event_time::date = params.target_date
|
||||
AND EXTRACT(HOUR FROM log.event_time)::text = params.target_hour
|
||||
GROUP BY 1,2,3,4,5
|
||||
),
|
||||
energy_phase_B AS (
|
||||
@ -47,9 +41,7 @@ energy_phase_B AS (
|
||||
MAX(log.value)::integer AS max_value
|
||||
FROM "device-status-log" log, params
|
||||
WHERE log.code = 'EnergyConsumedB'
|
||||
AND log.device_id = params.device_id
|
||||
AND log.event_time::date = params.target_date
|
||||
AND EXTRACT(HOUR FROM log.event_time)::text = params.target_hour
|
||||
GROUP BY 1,2,3,4,5
|
||||
),
|
||||
energy_phase_C AS (
|
||||
@ -63,9 +55,7 @@ energy_phase_C AS (
|
||||
MAX(log.value)::integer AS max_value
|
||||
FROM "device-status-log" log, params
|
||||
WHERE log.code = 'EnergyConsumedC'
|
||||
AND log.device_id = params.device_id
|
||||
AND log.event_time::date = params.target_date
|
||||
AND EXTRACT(HOUR FROM log.event_time)::text = params.target_hour
|
||||
GROUP BY 1,2,3,4,5
|
||||
),
|
||||
final_data AS (
|
||||
|
@ -1,7 +1,6 @@
|
||||
WITH params AS (
|
||||
SELECT
|
||||
$1::uuid AS device_id,
|
||||
$2::text AS target_month -- Format should match 'MM-YYYY'
|
||||
$1::text AS target_month -- Format should match 'MM-YYYY'
|
||||
),
|
||||
total_energy AS (
|
||||
SELECT
|
||||
@ -14,7 +13,6 @@ total_energy AS (
|
||||
MAX(log.value)::integer AS max_value
|
||||
FROM "device-status-log" log, params
|
||||
WHERE log.code = 'EnergyConsumed'
|
||||
AND log.device_id = params.device_id
|
||||
AND TO_CHAR(log.event_time, 'MM-YYYY') = params.target_month
|
||||
GROUP BY 1,2,3,4,5
|
||||
),
|
||||
@ -29,7 +27,6 @@ energy_phase_A AS (
|
||||
MAX(log.value)::integer AS max_value
|
||||
FROM "device-status-log" log, params
|
||||
WHERE log.code = 'EnergyConsumedA'
|
||||
AND log.device_id = params.device_id
|
||||
AND TO_CHAR(log.event_time, 'MM-YYYY') = params.target_month
|
||||
GROUP BY 1,2,3,4,5
|
||||
),
|
||||
@ -44,7 +41,6 @@ energy_phase_B AS (
|
||||
MAX(log.value)::integer AS max_value
|
||||
FROM "device-status-log" log, params
|
||||
WHERE log.code = 'EnergyConsumedB'
|
||||
AND log.device_id = params.device_id
|
||||
AND TO_CHAR(log.event_time, 'MM-YYYY') = params.target_month
|
||||
GROUP BY 1,2,3,4,5
|
||||
),
|
||||
@ -59,7 +55,6 @@ energy_phase_C AS (
|
||||
MAX(log.value)::integer AS max_value
|
||||
FROM "device-status-log" log, params
|
||||
WHERE log.code = 'EnergyConsumedC'
|
||||
AND log.device_id = params.device_id
|
||||
AND TO_CHAR(log.event_time, 'MM-YYYY') = params.target_month
|
||||
GROUP BY 1,2,3,4,5
|
||||
),
|
||||
|
@ -1,7 +1,6 @@
|
||||
WITH params AS (
|
||||
SELECT
|
||||
TO_DATE(NULLIF($1, ''), 'YYYY-MM-DD') AS event_date,
|
||||
$2::uuid AS space_id
|
||||
TO_DATE(NULLIF($1, ''), 'YYYY-MM-DD') AS event_date
|
||||
),
|
||||
|
||||
device_logs AS (
|
||||
@ -87,8 +86,7 @@ SELECT summary.space_id,
|
||||
count_total_presence_detected
|
||||
FROM summary
|
||||
JOIN params P ON true
|
||||
where summary.space_id = P.space_id
|
||||
and (P.event_date IS NULL or summary.event_date::date = P.event_date)
|
||||
where (P.event_date IS NULL or summary.event_date::date = P.event_date)
|
||||
ORDER BY space_id, event_date)
|
||||
|
||||
|
||||
|
3956
package-lock.json
generated
3956
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@ -30,6 +30,7 @@
|
||||
"@nestjs/jwt": "^10.2.0",
|
||||
"@nestjs/passport": "^10.0.3",
|
||||
"@nestjs/platform-express": "^10.0.0",
|
||||
"@nestjs/schedule": "^6.0.0",
|
||||
"@nestjs/swagger": "^7.3.0",
|
||||
"@nestjs/terminus": "^11.0.0",
|
||||
"@nestjs/throttler": "^6.4.0",
|
||||
@ -50,11 +51,12 @@
|
||||
"ioredis": "^5.3.2",
|
||||
"morgan": "^1.10.0",
|
||||
"nest-winston": "^1.10.2",
|
||||
"node-cache": "^5.1.2",
|
||||
"nodemailer": "^6.9.10",
|
||||
"onesignal-node": "^3.4.0",
|
||||
"passport-jwt": "^4.0.1",
|
||||
"pg": "^8.11.3",
|
||||
"reflect-metadata": "^0.2.0",
|
||||
"reflect-metadata": "^0.2.2",
|
||||
"rxjs": "^7.8.1",
|
||||
"typeorm": "^0.3.20",
|
||||
"winston": "^3.17.0",
|
||||
@ -87,5 +89,9 @@
|
||||
"ts-node": "^10.9.1",
|
||||
"tsconfig-paths": "^4.2.0",
|
||||
"typescript": "^5.1.3"
|
||||
},
|
||||
"engines": {
|
||||
"node": "20.x",
|
||||
"npm": "10.x"
|
||||
}
|
||||
}
|
||||
|
@ -1,7 +1,7 @@
|
||||
import { SeederModule } from '@app/common/seed/seeder.module';
|
||||
import { Module } from '@nestjs/common';
|
||||
import { ConfigModule } from '@nestjs/config';
|
||||
import { APP_INTERCEPTOR } from '@nestjs/core';
|
||||
import { APP_GUARD, APP_INTERCEPTOR } from '@nestjs/core';
|
||||
import { WinstonModule } from 'nest-winston';
|
||||
import { AuthenticationModule } from './auth/auth.module';
|
||||
import { AutomationModule } from './automation/automation.module';
|
||||
@ -35,18 +35,33 @@ import { UserNotificationModule } from './user-notification/user-notification.mo
|
||||
import { UserModule } from './users/user.module';
|
||||
import { VisitorPasswordModule } from './vistor-password/visitor-password.module';
|
||||
|
||||
import { ThrottlerGuard } from '@nestjs/throttler';
|
||||
import { ThrottlerModule } from '@nestjs/throttler/dist/throttler.module';
|
||||
import { isArray } from 'class-validator';
|
||||
import { winstonLoggerOptions } from '../libs/common/src/logger/services/winston.logger';
|
||||
import { AqiModule } from './aqi/aqi.module';
|
||||
import { OccupancyModule } from './occupancy/occupancy.module';
|
||||
import { WeatherModule } from './weather/weather.module';
|
||||
import { ScheduleModule as NestScheduleModule } from '@nestjs/schedule';
|
||||
import { SchedulerModule } from './scheduler/scheduler.module';
|
||||
import { BookingModule } from './booking';
|
||||
@Module({
|
||||
imports: [
|
||||
ConfigModule.forRoot({
|
||||
load: config,
|
||||
}),
|
||||
/* ThrottlerModule.forRoot({
|
||||
throttlers: [{ ttl: 100000, limit: 30 }],
|
||||
}), */
|
||||
ThrottlerModule.forRoot({
|
||||
throttlers: [{ ttl: 60000, limit: 100 }],
|
||||
generateKey: (context) => {
|
||||
const req = context.switchToHttp().getRequest();
|
||||
console.log('Real IP:', req.headers['x-forwarded-for']);
|
||||
return req.headers['x-forwarded-for']
|
||||
? isArray(req.headers['x-forwarded-for'])
|
||||
? req.headers['x-forwarded-for'][0].split(':')[0]
|
||||
: req.headers['x-forwarded-for'].split(':')[0]
|
||||
: req.ip;
|
||||
},
|
||||
}),
|
||||
WinstonModule.forRoot(winstonLoggerOptions),
|
||||
ClientModule,
|
||||
AuthenticationModule,
|
||||
@ -82,16 +97,19 @@ import { WeatherModule } from './weather/weather.module';
|
||||
OccupancyModule,
|
||||
WeatherModule,
|
||||
AqiModule,
|
||||
SchedulerModule,
|
||||
NestScheduleModule.forRoot(),
|
||||
BookingModule,
|
||||
],
|
||||
providers: [
|
||||
{
|
||||
provide: APP_INTERCEPTOR,
|
||||
useClass: LoggingInterceptor,
|
||||
},
|
||||
/* {
|
||||
{
|
||||
provide: APP_GUARD,
|
||||
useClass: ThrottlerGuard,
|
||||
}, */
|
||||
},
|
||||
],
|
||||
})
|
||||
export class AppModule {}
|
||||
|
17
src/booking/booking.module.ts
Normal file
17
src/booking/booking.module.ts
Normal file
@ -0,0 +1,17 @@
|
||||
import { Global, Module } from '@nestjs/common';
|
||||
import { BookableSpaceController } from './controllers';
|
||||
import { BookableSpaceService } from './services';
|
||||
import { BookableSpaceEntityRepository } from '@app/common/modules/booking/repositories';
|
||||
import { SpaceRepository } from '@app/common/modules/space';
|
||||
|
||||
@Global()
|
||||
@Module({
|
||||
controllers: [BookableSpaceController],
|
||||
providers: [
|
||||
BookableSpaceService,
|
||||
BookableSpaceEntityRepository,
|
||||
SpaceRepository,
|
||||
],
|
||||
exports: [BookableSpaceService],
|
||||
})
|
||||
export class BookingModule {}
|
106
src/booking/controllers/bookable-space.controller.ts
Normal file
106
src/booking/controllers/bookable-space.controller.ts
Normal file
@ -0,0 +1,106 @@
|
||||
import { ControllerRoute } from '@app/common/constants/controller-route';
|
||||
import { EnableDisableStatusEnum } from '@app/common/constants/days.enum';
|
||||
import { BaseResponseDto } from '@app/common/dto/base.response.dto';
|
||||
import { JwtAuthGuard } from '@app/common/guards/jwt.auth.guard';
|
||||
import {
|
||||
Body,
|
||||
Controller,
|
||||
Get,
|
||||
Param,
|
||||
Post,
|
||||
Put,
|
||||
Query,
|
||||
Req,
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import { ApiBearerAuth, ApiOperation, ApiTags } from '@nestjs/swagger';
|
||||
|
||||
import { PageResponse } from '@app/common/dto/pagination.response.dto';
|
||||
import { SuccessResponseDto } from '@app/common/dto/success.response.dto';
|
||||
import { plainToInstance } from 'class-transformer';
|
||||
import { CreateBookableSpaceDto } from '../dtos';
|
||||
import { BookableSpaceRequestDto } from '../dtos/bookable-space-request.dto';
|
||||
import { BookableSpaceResponseDto } from '../dtos/bookable-space-response.dto';
|
||||
import { UpdateBookableSpaceDto } from '../dtos/update-bookable-space.dto';
|
||||
import { BookableSpaceService } from '../services';
|
||||
|
||||
@ApiTags('Booking Module')
|
||||
@Controller({
|
||||
version: EnableDisableStatusEnum.ENABLED,
|
||||
path: ControllerRoute.BOOKABLE_SPACES.ROUTE,
|
||||
})
|
||||
export class BookableSpaceController {
|
||||
constructor(private readonly bookableSpaceService: BookableSpaceService) {}
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@Post()
|
||||
@ApiOperation({
|
||||
summary:
|
||||
ControllerRoute.BOOKABLE_SPACES.ACTIONS.ADD_BOOKABLE_SPACES_SUMMARY,
|
||||
description:
|
||||
ControllerRoute.BOOKABLE_SPACES.ACTIONS.ADD_BOOKABLE_SPACES_DESCRIPTION,
|
||||
})
|
||||
async create(@Body() dto: CreateBookableSpaceDto): Promise<BaseResponseDto> {
|
||||
const result = await this.bookableSpaceService.create(dto);
|
||||
return new SuccessResponseDto({
|
||||
data: result,
|
||||
message: 'Successfully created bookable spaces',
|
||||
});
|
||||
}
|
||||
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@Get()
|
||||
@ApiOperation({
|
||||
summary:
|
||||
ControllerRoute.BOOKABLE_SPACES.ACTIONS.GET_ALL_BOOKABLE_SPACES_SUMMARY,
|
||||
description:
|
||||
ControllerRoute.BOOKABLE_SPACES.ACTIONS
|
||||
.GET_ALL_BOOKABLE_SPACES_DESCRIPTION,
|
||||
})
|
||||
async findAll(
|
||||
@Query() query: BookableSpaceRequestDto,
|
||||
@Req() req: Request,
|
||||
): Promise<PageResponse<BookableSpaceResponseDto>> {
|
||||
const project = req['user']?.project?.uuid;
|
||||
if (!project) {
|
||||
throw new Error('Project UUID is required in the request');
|
||||
}
|
||||
const { data, pagination } = await this.bookableSpaceService.findAll(
|
||||
query,
|
||||
project,
|
||||
);
|
||||
return new PageResponse<BookableSpaceResponseDto>(
|
||||
{
|
||||
data: data.map((space) =>
|
||||
plainToInstance(BookableSpaceResponseDto, space, {
|
||||
excludeExtraneousValues: true,
|
||||
}),
|
||||
),
|
||||
message: 'Successfully fetched all bookable spaces',
|
||||
},
|
||||
pagination,
|
||||
);
|
||||
}
|
||||
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@Put(':spaceUuid')
|
||||
@ApiOperation({
|
||||
summary:
|
||||
ControllerRoute.BOOKABLE_SPACES.ACTIONS.UPDATE_BOOKABLE_SPACES_SUMMARY,
|
||||
description:
|
||||
ControllerRoute.BOOKABLE_SPACES.ACTIONS
|
||||
.UPDATE_BOOKABLE_SPACES_DESCRIPTION,
|
||||
})
|
||||
async update(
|
||||
@Param('spaceUuid') spaceUuid: string,
|
||||
@Body() dto: UpdateBookableSpaceDto,
|
||||
): Promise<BaseResponseDto> {
|
||||
const result = await this.bookableSpaceService.update(spaceUuid, dto);
|
||||
return new SuccessResponseDto({
|
||||
data: result,
|
||||
message: 'Successfully updated bookable spaces',
|
||||
});
|
||||
}
|
||||
}
|
1
src/booking/controllers/index.ts
Normal file
1
src/booking/controllers/index.ts
Normal file
@ -0,0 +1 @@
|
||||
export * from './bookable-space.controller';
|
31
src/booking/dtos/bookable-space-request.dto.ts
Normal file
31
src/booking/dtos/bookable-space-request.dto.ts
Normal file
@ -0,0 +1,31 @@
|
||||
import { BooleanValues } from '@app/common/constants/boolean-values.enum';
|
||||
import { PaginationRequestWithSearchGetListDto } from '@app/common/dto/pagination-with-search.request.dto';
|
||||
import { ApiProperty, OmitType } from '@nestjs/swagger';
|
||||
import { Transform } from 'class-transformer';
|
||||
import { IsBoolean, IsNotEmpty, IsOptional } from 'class-validator';
|
||||
|
||||
export class BookableSpaceRequestDto extends OmitType(
|
||||
PaginationRequestWithSearchGetListDto,
|
||||
['includeSpaces'],
|
||||
) {
|
||||
@ApiProperty({
|
||||
type: Boolean,
|
||||
required: false,
|
||||
})
|
||||
@IsBoolean()
|
||||
@IsOptional()
|
||||
@Transform(({ obj }) => {
|
||||
return obj.active === BooleanValues.TRUE;
|
||||
})
|
||||
active?: boolean;
|
||||
|
||||
@ApiProperty({
|
||||
type: Boolean,
|
||||
})
|
||||
@IsBoolean()
|
||||
@IsNotEmpty()
|
||||
@Transform(({ obj }) => {
|
||||
return obj.configured === BooleanValues.TRUE;
|
||||
})
|
||||
configured: boolean;
|
||||
}
|
59
src/booking/dtos/bookable-space-response.dto.ts
Normal file
59
src/booking/dtos/bookable-space-response.dto.ts
Normal file
@ -0,0 +1,59 @@
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
import { Expose, Type } from 'class-transformer';
|
||||
export class BookableSpaceConfigResponseDto {
|
||||
@ApiProperty()
|
||||
@Expose()
|
||||
uuid: string;
|
||||
|
||||
@ApiProperty({
|
||||
type: [String],
|
||||
})
|
||||
@Expose()
|
||||
daysAvailable: string[];
|
||||
|
||||
@ApiProperty()
|
||||
@Expose()
|
||||
startTime: string;
|
||||
|
||||
@ApiProperty()
|
||||
@Expose()
|
||||
endTime: string;
|
||||
|
||||
@ApiProperty({
|
||||
type: Boolean,
|
||||
})
|
||||
@Expose()
|
||||
active: boolean;
|
||||
|
||||
@ApiProperty({
|
||||
type: Number,
|
||||
nullable: true,
|
||||
})
|
||||
@Expose()
|
||||
points?: number;
|
||||
}
|
||||
|
||||
export class BookableSpaceResponseDto {
|
||||
@ApiProperty()
|
||||
@Expose()
|
||||
uuid: string;
|
||||
|
||||
@ApiProperty()
|
||||
@Expose()
|
||||
spaceUuid: string;
|
||||
|
||||
@ApiProperty()
|
||||
@Expose()
|
||||
spaceName: string;
|
||||
|
||||
@ApiProperty()
|
||||
@Expose()
|
||||
virtualLocation: string;
|
||||
|
||||
@ApiProperty({
|
||||
type: BookableSpaceConfigResponseDto,
|
||||
})
|
||||
@Expose()
|
||||
@Type(() => BookableSpaceConfigResponseDto)
|
||||
bookableConfig: BookableSpaceConfigResponseDto;
|
||||
}
|
63
src/booking/dtos/create-bookable-space.dto.ts
Normal file
63
src/booking/dtos/create-bookable-space.dto.ts
Normal file
@ -0,0 +1,63 @@
|
||||
import { DaysEnum } from '@app/common/constants/days.enum';
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
import {
|
||||
ArrayMinSize,
|
||||
IsArray,
|
||||
IsEnum,
|
||||
IsInt,
|
||||
IsNotEmpty,
|
||||
IsOptional,
|
||||
IsString,
|
||||
IsUUID,
|
||||
Matches,
|
||||
Max,
|
||||
Min,
|
||||
} from 'class-validator';
|
||||
|
||||
export class CreateBookableSpaceDto {
|
||||
@ApiProperty({
|
||||
type: 'string',
|
||||
isArray: true,
|
||||
example: [
|
||||
'3fa85f64-5717-4562-b3fc-2c963f66afa6',
|
||||
'4fa85f64-5717-4562-b3fc-2c963f66afa7',
|
||||
],
|
||||
})
|
||||
@IsArray()
|
||||
@ArrayMinSize(1, { message: 'At least one space must be selected' })
|
||||
@IsUUID('all', { each: true, message: 'Invalid space UUID provided' })
|
||||
spaceUuids: string[];
|
||||
|
||||
@ApiProperty({
|
||||
enum: DaysEnum,
|
||||
isArray: true,
|
||||
example: [DaysEnum.MON, DaysEnum.WED, DaysEnum.FRI],
|
||||
})
|
||||
@IsArray()
|
||||
@ArrayMinSize(1, { message: 'At least one day must be selected' })
|
||||
@IsEnum(DaysEnum, { each: true, message: 'Invalid day provided' })
|
||||
daysAvailable: DaysEnum[];
|
||||
|
||||
@ApiProperty({ example: '09:00' })
|
||||
@IsString()
|
||||
@IsNotEmpty({ message: 'Start time cannot be empty' })
|
||||
@Matches(/^([01]?[0-9]|2[0-3]):[0-5][0-9]$/, {
|
||||
message: 'Start time must be in HH:mm format (24-hour)',
|
||||
})
|
||||
startTime: string;
|
||||
|
||||
@ApiProperty({ example: '17:00' })
|
||||
@IsString()
|
||||
@IsNotEmpty({ message: 'End time cannot be empty' })
|
||||
@Matches(/^([01]?[0-9]|2[0-3]):[0-5][0-9]$/, {
|
||||
message: 'End time must be in HH:mm format (24-hour)',
|
||||
})
|
||||
endTime: string;
|
||||
|
||||
@ApiProperty({ example: 10, required: false })
|
||||
@IsOptional()
|
||||
@IsInt()
|
||||
@Min(0, { message: 'Points cannot be negative' })
|
||||
@Max(1000, { message: 'Points cannot exceed 1000' })
|
||||
points?: number;
|
||||
}
|
1
src/booking/dtos/index.ts
Normal file
1
src/booking/dtos/index.ts
Normal file
@ -0,0 +1 @@
|
||||
export * from './create-bookable-space.dto';
|
12
src/booking/dtos/update-bookable-space.dto.ts
Normal file
12
src/booking/dtos/update-bookable-space.dto.ts
Normal file
@ -0,0 +1,12 @@
|
||||
import { ApiProperty, OmitType, PartialType } from '@nestjs/swagger';
|
||||
import { IsBoolean, IsOptional } from 'class-validator';
|
||||
import { CreateBookableSpaceDto } from './create-bookable-space.dto';
|
||||
|
||||
export class UpdateBookableSpaceDto extends PartialType(
|
||||
OmitType(CreateBookableSpaceDto, ['spaceUuids']),
|
||||
) {
|
||||
@ApiProperty({ type: Boolean })
|
||||
@IsOptional()
|
||||
@IsBoolean()
|
||||
active?: boolean;
|
||||
}
|
1
src/booking/index.ts
Normal file
1
src/booking/index.ts
Normal file
@ -0,0 +1 @@
|
||||
export * from './booking.module';
|
198
src/booking/services/bookable-space.service.ts
Normal file
198
src/booking/services/bookable-space.service.ts
Normal file
@ -0,0 +1,198 @@
|
||||
import { BaseResponseDto } from '@app/common/dto/base.response.dto';
|
||||
import { PageResponseDto } from '@app/common/dto/pagination.response.dto';
|
||||
import { timeToMinutes } from '@app/common/helper/timeToMinutes';
|
||||
import { TypeORMCustomModel } from '@app/common/models/typeOrmCustom.model';
|
||||
import { BookableSpaceEntityRepository } from '@app/common/modules/booking/repositories';
|
||||
import { SpaceEntity } from '@app/common/modules/space/entities/space.entity';
|
||||
import { SpaceRepository } from '@app/common/modules/space/repositories/space.repository';
|
||||
import {
|
||||
BadRequestException,
|
||||
ConflictException,
|
||||
Injectable,
|
||||
NotFoundException,
|
||||
} from '@nestjs/common';
|
||||
import { In } from 'typeorm';
|
||||
import { CreateBookableSpaceDto } from '../dtos';
|
||||
import { BookableSpaceRequestDto } from '../dtos/bookable-space-request.dto';
|
||||
import { UpdateBookableSpaceDto } from '../dtos/update-bookable-space.dto';
|
||||
|
||||
@Injectable()
|
||||
export class BookableSpaceService {
|
||||
constructor(
|
||||
private readonly bookableSpaceEntityRepository: BookableSpaceEntityRepository,
|
||||
private readonly spaceRepository: SpaceRepository,
|
||||
) {}
|
||||
|
||||
async create(dto: CreateBookableSpaceDto) {
|
||||
// Validate time slots first
|
||||
this.validateTimeSlot(dto.startTime, dto.endTime);
|
||||
|
||||
// fetch spaces exist
|
||||
const spaces = await this.getSpacesOrFindMissing(dto.spaceUuids);
|
||||
|
||||
// Validate no duplicate bookable configurations
|
||||
await this.validateNoDuplicateBookableConfigs(dto.spaceUuids);
|
||||
|
||||
// Create and save bookable spaces
|
||||
return this.createBookableSpaces(spaces, dto);
|
||||
}
|
||||
|
||||
async findAll(
|
||||
{ active, page, size, configured, search }: BookableSpaceRequestDto,
|
||||
project: string,
|
||||
): Promise<{
|
||||
data: BaseResponseDto['data'];
|
||||
pagination: PageResponseDto;
|
||||
}> {
|
||||
let qb = this.spaceRepository
|
||||
.createQueryBuilder('space')
|
||||
.leftJoinAndSelect('space.parent', 'parentSpace')
|
||||
.leftJoinAndSelect('space.community', 'community')
|
||||
.where('community.project = :project', { project });
|
||||
|
||||
if (search) {
|
||||
qb = qb.andWhere(
|
||||
'space.spaceName ILIKE :search OR community.name ILIKE :search OR parentSpace.spaceName ILIKE :search',
|
||||
{ search: `%${search}%` },
|
||||
);
|
||||
}
|
||||
if (configured) {
|
||||
qb = qb
|
||||
.leftJoinAndSelect('space.bookableConfig', 'bookableConfig')
|
||||
.andWhere('bookableConfig.uuid IS NOT NULL');
|
||||
if (active !== undefined) {
|
||||
qb = qb.andWhere('bookableConfig.active = :active', { active });
|
||||
}
|
||||
} else {
|
||||
qb = qb
|
||||
.leftJoinAndSelect('space.bookableConfig', 'bookableConfig')
|
||||
.andWhere('bookableConfig.uuid IS NULL');
|
||||
}
|
||||
|
||||
const customModel = TypeORMCustomModel(this.spaceRepository);
|
||||
|
||||
const { baseResponseDto, paginationResponseDto } =
|
||||
await customModel.findAll({ page, size, modelName: 'space' }, qb);
|
||||
return {
|
||||
data: baseResponseDto.data.map((space) => {
|
||||
return {
|
||||
...space,
|
||||
virtualLocation: `${space.community?.name} - ${space.parent ? space.parent?.spaceName + ' - ' : ''}${space.spaceName}`,
|
||||
};
|
||||
}),
|
||||
pagination: paginationResponseDto,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* todo: if updating availability, send to the ones who have access to this space
|
||||
* todo: if updating other fields, just send emails to all users who's bookings might be affected
|
||||
*/
|
||||
async update(spaceUuid: string, dto: UpdateBookableSpaceDto) {
|
||||
// fetch spaces exist
|
||||
const space = (await this.getSpacesOrFindMissing([spaceUuid]))[0];
|
||||
|
||||
if (!space.bookableConfig) {
|
||||
throw new NotFoundException(
|
||||
`Bookable configuration not found for space: ${spaceUuid}`,
|
||||
);
|
||||
}
|
||||
if (dto.startTime || dto.endTime) {
|
||||
// Validate time slots first
|
||||
this.validateTimeSlot(
|
||||
dto.startTime || space.bookableConfig.startTime,
|
||||
dto.endTime || space.bookableConfig.endTime,
|
||||
);
|
||||
}
|
||||
Object.assign(space.bookableConfig, dto);
|
||||
return this.bookableSpaceEntityRepository.save(space.bookableConfig);
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch spaces by UUIDs and throw an error if any are missing
|
||||
*/
|
||||
private async getSpacesOrFindMissing(
|
||||
spaceUuids: string[],
|
||||
): Promise<SpaceEntity[]> {
|
||||
const spaces = await this.spaceRepository.find({
|
||||
where: { uuid: In(spaceUuids) },
|
||||
relations: ['bookableConfig'],
|
||||
});
|
||||
|
||||
if (spaces.length !== spaceUuids.length) {
|
||||
const foundUuids = spaces.map((s) => s.uuid);
|
||||
const missingUuids = spaceUuids.filter(
|
||||
(uuid) => !foundUuids.includes(uuid),
|
||||
);
|
||||
throw new NotFoundException(
|
||||
`Spaces not found: ${missingUuids.join(', ')}`,
|
||||
);
|
||||
}
|
||||
|
||||
return spaces;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate there are no existing bookable configurations for these spaces
|
||||
*/
|
||||
private async validateNoDuplicateBookableConfigs(
|
||||
spaceUuids: string[],
|
||||
): Promise<void> {
|
||||
const existingBookables = await this.bookableSpaceEntityRepository.find({
|
||||
where: { space: { uuid: In(spaceUuids) } },
|
||||
relations: ['space'],
|
||||
});
|
||||
|
||||
if (existingBookables.length > 0) {
|
||||
const existingUuids = [
|
||||
...new Set(existingBookables.map((b) => b.space.uuid)),
|
||||
];
|
||||
throw new ConflictException(
|
||||
`Bookable configuration already exists for spaces: ${existingUuids.join(', ')}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensure the slot start time is before the end time
|
||||
*/
|
||||
private validateTimeSlot(startTime: string, endTime: string): void {
|
||||
const start = timeToMinutes(startTime);
|
||||
const end = timeToMinutes(endTime);
|
||||
|
||||
if (start >= end) {
|
||||
throw new BadRequestException(
|
||||
`End time must be after start time for slot: ${startTime}-${endTime}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create bookable space entries after all validations pass
|
||||
*/
|
||||
private async createBookableSpaces(
|
||||
spaces: SpaceEntity[],
|
||||
dto: CreateBookableSpaceDto,
|
||||
) {
|
||||
try {
|
||||
const entries = spaces.map((space) =>
|
||||
this.bookableSpaceEntityRepository.create({
|
||||
space,
|
||||
daysAvailable: dto.daysAvailable,
|
||||
startTime: dto.startTime,
|
||||
endTime: dto.endTime,
|
||||
points: dto.points,
|
||||
}),
|
||||
);
|
||||
|
||||
return this.bookableSpaceEntityRepository.save(entries);
|
||||
} catch (error) {
|
||||
if (error.code === '23505') {
|
||||
throw new ConflictException(
|
||||
'Duplicate bookable space configuration detected',
|
||||
);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
1
src/booking/services/index.ts
Normal file
1
src/booking/services/index.ts
Normal file
@ -0,0 +1 @@
|
||||
export * from './bookable-space.service';
|
@ -30,6 +30,8 @@ import { PowerClampService } from '@app/common/helper/services/power.clamp.servi
|
||||
import { SqlLoaderService } from '@app/common/helper/services/sql-loader.service';
|
||||
import { OccupancyService } from '@app/common/helper/services/occupancy.service';
|
||||
import { AqiDataService } from '@app/common/helper/services/aqi.data.service';
|
||||
import { PresenceSensorDailySpaceRepository } from '@app/common/modules/presence-sensor/repositories';
|
||||
import { AqiSpaceDailyPollutantStatsRepository } from '@app/common/modules/aqi/repositories';
|
||||
|
||||
@Module({
|
||||
imports: [ConfigModule, SpaceRepositoryModule],
|
||||
@ -59,6 +61,8 @@ import { AqiDataService } from '@app/common/helper/services/aqi.data.service';
|
||||
SqlLoaderService,
|
||||
OccupancyService,
|
||||
AqiDataService,
|
||||
PresenceSensorDailySpaceRepository,
|
||||
AqiSpaceDailyPollutantStatsRepository,
|
||||
],
|
||||
exports: [],
|
||||
})
|
||||
|
@ -3,6 +3,7 @@ import * as fs from 'fs';
|
||||
|
||||
import { ProjectParam } from '@app/common/dto/project-param.dto';
|
||||
import { SuccessResponseDto } from '@app/common/dto/success.response.dto';
|
||||
import { DeviceStatusFirebaseService } from '@app/common/firebase/devices-status/services/devices-status.service';
|
||||
import { TuyaService } from '@app/common/integrations/tuya/services/tuya.service';
|
||||
import { CommunityRepository } from '@app/common/modules/community/repositories';
|
||||
import { DeviceRepository } from '@app/common/modules/device/repositories';
|
||||
@ -20,6 +21,7 @@ export class DeviceCommissionService {
|
||||
constructor(
|
||||
private readonly tuyaService: TuyaService,
|
||||
private readonly deviceService: DeviceService,
|
||||
private readonly deviceStatusFirebaseService: DeviceStatusFirebaseService,
|
||||
private readonly communityRepository: CommunityRepository,
|
||||
private readonly spaceRepository: SpaceRepository,
|
||||
private readonly subspaceRepository: SubspaceRepository,
|
||||
@ -209,6 +211,10 @@ export class DeviceCommissionService {
|
||||
rawDeviceId,
|
||||
tuyaSpaceId,
|
||||
);
|
||||
|
||||
await this.deviceStatusFirebaseService.addDeviceStatusByDeviceUuid(
|
||||
rawDeviceId,
|
||||
);
|
||||
successCount.value++;
|
||||
console.log(
|
||||
`Device ${rawDeviceId} successfully processed and transferred to Tuya space ${tuyaSpaceId}`,
|
||||
|
@ -64,6 +64,8 @@ import {
|
||||
import { SqlLoaderService } from '@app/common/helper/services/sql-loader.service';
|
||||
import { OccupancyService } from '@app/common/helper/services/occupancy.service';
|
||||
import { AqiDataService } from '@app/common/helper/services/aqi.data.service';
|
||||
import { PresenceSensorDailySpaceRepository } from '@app/common/modules/presence-sensor/repositories';
|
||||
import { AqiSpaceDailyPollutantStatsRepository } from '@app/common/modules/aqi/repositories';
|
||||
|
||||
@Module({
|
||||
imports: [ConfigModule, SpaceRepositoryModule, UserRepositoryModule],
|
||||
@ -118,6 +120,8 @@ import { AqiDataService } from '@app/common/helper/services/aqi.data.service';
|
||||
SqlLoaderService,
|
||||
OccupancyService,
|
||||
AqiDataService,
|
||||
PresenceSensorDailySpaceRepository,
|
||||
AqiSpaceDailyPollutantStatsRepository,
|
||||
],
|
||||
exports: [CommunityService, SpacePermissionService],
|
||||
})
|
||||
|
@ -120,6 +120,7 @@ export class CommunityService {
|
||||
.leftJoin('c.spaces', 's', 's.disabled = false')
|
||||
.where('c.project = :projectUuid', { projectUuid })
|
||||
.andWhere(`c.name != '${ORPHAN_COMMUNITY_NAME}-${project.name}'`)
|
||||
.orderBy('c.createdAt', 'DESC')
|
||||
.distinct(true);
|
||||
if (pageable.search) {
|
||||
qb.andWhere(
|
||||
@ -209,7 +210,7 @@ export class CommunityService {
|
||||
if (search) {
|
||||
qb.andWhere(
|
||||
`c.name ILIKE :search ${includeSpaces ? 'OR space.space_name ILIKE :search' : ''}`,
|
||||
{ search },
|
||||
{ search: `%${search}%` },
|
||||
);
|
||||
}
|
||||
|
||||
|
28
src/device/commands/cur2-commands.ts
Normal file
28
src/device/commands/cur2-commands.ts
Normal file
@ -0,0 +1,28 @@
|
||||
interface BaseCommand {
|
||||
code: string;
|
||||
value: any;
|
||||
}
|
||||
export interface ControlCur2Command extends BaseCommand {
|
||||
code: 'control';
|
||||
value: 'open' | 'close' | 'stop';
|
||||
}
|
||||
export interface ControlCur2PercentCommand extends BaseCommand {
|
||||
code: 'percent_control';
|
||||
value: 10 | 20 | 30 | 40 | 50 | 60 | 70 | 80 | 90 | 100;
|
||||
}
|
||||
export interface ControlCur2AccurateCalibrationCommand extends BaseCommand {
|
||||
code: 'accurate_calibration';
|
||||
value: 'start' | 'end'; // Assuming this is a numeric value for calibration
|
||||
}
|
||||
export interface ControlCur2TDirectionConCommand extends BaseCommand {
|
||||
code: 'control_t_direction_con';
|
||||
value: 'forward' | 'back';
|
||||
}
|
||||
export interface ControlCur2QuickCalibrationCommand extends BaseCommand {
|
||||
code: 'tr_timecon';
|
||||
value: number; // between 10 and 120
|
||||
}
|
||||
export interface ControlCur2MotorModeCommand extends BaseCommand {
|
||||
code: 'elec_machinery_mode';
|
||||
value: 'strong_power' | 'dry_contact';
|
||||
}
|
@ -1,39 +1,41 @@
|
||||
import { DeviceService } from '../services/device.service';
|
||||
import { ControllerRoute } from '@app/common/constants/controller-route';
|
||||
import { EnableDisableStatusEnum } from '@app/common/constants/days.enum';
|
||||
import { RoleType } from '@app/common/constants/role.type.enum';
|
||||
import { BaseResponseDto } from '@app/common/dto/base.response.dto';
|
||||
import {
|
||||
Body,
|
||||
Controller,
|
||||
Get,
|
||||
Post,
|
||||
Query,
|
||||
Param,
|
||||
UseGuards,
|
||||
Put,
|
||||
Delete,
|
||||
Get,
|
||||
Param,
|
||||
Post,
|
||||
Put,
|
||||
Query,
|
||||
Req,
|
||||
UnauthorizedException,
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import { ApiTags, ApiBearerAuth, ApiOperation } from '@nestjs/swagger';
|
||||
import { ApiBearerAuth, ApiOperation, ApiTags } from '@nestjs/swagger';
|
||||
import { Permissions } from 'src/decorators/permissions.decorator';
|
||||
import { PermissionsGuard } from 'src/guards/permissions.guard';
|
||||
import { CheckRoomGuard } from 'src/guards/room.guard';
|
||||
import { CheckFourAndSixSceneDeviceTypeGuard } from 'src/guards/scene.device.type.guard';
|
||||
import {
|
||||
AddDeviceDto,
|
||||
AddSceneToFourSceneDeviceDto,
|
||||
AssignDeviceToSpaceDto,
|
||||
UpdateDeviceDto,
|
||||
} from '../dtos/add.device.dto';
|
||||
import { GetDeviceLogsDto } from '../dtos/get.device.dto';
|
||||
import {
|
||||
ControlDeviceDto,
|
||||
BatchControlDevicesDto,
|
||||
BatchStatusDevicesDto,
|
||||
ControlDeviceDto,
|
||||
GetSceneFourSceneDeviceDto,
|
||||
} from '../dtos/control.device.dto';
|
||||
import { CheckRoomGuard } from 'src/guards/room.guard';
|
||||
import { EnableDisableStatusEnum } from '@app/common/constants/days.enum';
|
||||
import { CheckFourAndSixSceneDeviceTypeGuard } from 'src/guards/scene.device.type.guard';
|
||||
import { ControllerRoute } from '@app/common/constants/controller-route';
|
||||
import { BaseResponseDto } from '@app/common/dto/base.response.dto';
|
||||
import { DeviceSceneParamDto } from '../dtos/device.param.dto';
|
||||
import { DeleteSceneFromSceneDeviceDto } from '../dtos/delete.device.dto';
|
||||
import { PermissionsGuard } from 'src/guards/permissions.guard';
|
||||
import { Permissions } from 'src/decorators/permissions.decorator';
|
||||
import { DeviceSceneParamDto } from '../dtos/device.param.dto';
|
||||
import { GetDeviceLogsDto } from '../dtos/get.device.dto';
|
||||
import { DeviceService } from '../services/device.service';
|
||||
|
||||
@ApiTags('Device Module')
|
||||
@Controller({
|
||||
@ -340,4 +342,22 @@ export class DeviceController {
|
||||
projectUuid,
|
||||
);
|
||||
}
|
||||
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(PermissionsGuard)
|
||||
@Permissions('DEVICE_UPDATE')
|
||||
@Post('/populate-tuya-const-uuids')
|
||||
@ApiOperation({
|
||||
summary: ControllerRoute.DEVICE.ACTIONS.POPULATE_TUYA_CONST_UUID_SUMMARY,
|
||||
description:
|
||||
ControllerRoute.DEVICE.ACTIONS.POPULATE_TUYA_CONST_UUID_DESCRIPTION,
|
||||
})
|
||||
async populateTuyaConstUuid(@Req() req: any): Promise<void> {
|
||||
const userUuid = req['user']?.userUuid;
|
||||
const userRole = req['user']?.role;
|
||||
if (!userUuid || (userRole && userRole !== RoleType.SUPER_ADMIN)) {
|
||||
throw new UnauthorizedException('Unauthorized to perform this action');
|
||||
}
|
||||
return this.deviceService.addTuyaConstUuidToDevices();
|
||||
}
|
||||
}
|
||||
|
@ -18,6 +18,14 @@ export class AddDeviceDto {
|
||||
@IsNotEmpty()
|
||||
public spaceUuid: string;
|
||||
|
||||
@ApiProperty({
|
||||
description: 'tagUuid',
|
||||
required: true,
|
||||
})
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
public tagUuid: string;
|
||||
|
||||
@ApiProperty({
|
||||
description: 'deviceName',
|
||||
required: true,
|
||||
|
@ -1,7 +1,7 @@
|
||||
import { DeviceTypeEnum } from '@app/common/constants/device-type.enum';
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
import { Transform } from 'class-transformer';
|
||||
import {
|
||||
IsArray,
|
||||
IsEnum,
|
||||
IsNotEmpty,
|
||||
IsOptional,
|
||||
@ -74,13 +74,34 @@ export class GetDevicesFilterDto {
|
||||
@IsEnum(DeviceTypeEnum)
|
||||
@IsOptional()
|
||||
public deviceType: DeviceTypeEnum;
|
||||
|
||||
@ApiProperty({
|
||||
description: 'List of Space IDs to filter devices',
|
||||
required: false,
|
||||
example: ['60d21b4667d0d8992e610c85', '60d21b4967d0d8992e610c86'],
|
||||
})
|
||||
@IsOptional()
|
||||
@IsArray()
|
||||
@Transform(({ value }) => {
|
||||
if (!Array.isArray(value)) {
|
||||
return [value];
|
||||
}
|
||||
return value;
|
||||
})
|
||||
@IsUUID('4', { each: true })
|
||||
public spaces?: string[];
|
||||
|
||||
@ApiProperty({
|
||||
description: 'List of Community IDs to filter devices',
|
||||
required: false,
|
||||
example: ['60d21b4667d0d8992e610c85', '60d21b4967d0d8992e610c86'],
|
||||
})
|
||||
@Transform(({ value }) => {
|
||||
if (!Array.isArray(value)) {
|
||||
return [value];
|
||||
}
|
||||
return value;
|
||||
})
|
||||
@IsOptional()
|
||||
@IsUUID('4', { each: true })
|
||||
public communities?: string[];
|
||||
}
|
||||
|
File diff suppressed because it is too large
Load Diff
@ -30,6 +30,8 @@ import { SqlLoaderService } from '@app/common/helper/services/sql-loader.service
|
||||
import { OccupancyService } from '@app/common/helper/services/occupancy.service';
|
||||
import { CommunityRepository } from '@app/common/modules/community/repositories';
|
||||
import { AqiDataService } from '@app/common/helper/services/aqi.data.service';
|
||||
import { PresenceSensorDailySpaceRepository } from '@app/common/modules/presence-sensor/repositories';
|
||||
import { AqiSpaceDailyPollutantStatsRepository } from '@app/common/modules/aqi/repositories';
|
||||
@Module({
|
||||
imports: [ConfigModule, DeviceRepositoryModule],
|
||||
controllers: [DoorLockController],
|
||||
@ -58,6 +60,8 @@ import { AqiDataService } from '@app/common/helper/services/aqi.data.service';
|
||||
OccupancyService,
|
||||
CommunityRepository,
|
||||
AqiDataService,
|
||||
PresenceSensorDailySpaceRepository,
|
||||
AqiSpaceDailyPollutantStatsRepository,
|
||||
],
|
||||
exports: [DoorLockService],
|
||||
})
|
||||
|
@ -28,6 +28,8 @@ import { SqlLoaderService } from '@app/common/helper/services/sql-loader.service
|
||||
import { OccupancyService } from '@app/common/helper/services/occupancy.service';
|
||||
import { CommunityRepository } from '@app/common/modules/community/repositories';
|
||||
import { AqiDataService } from '@app/common/helper/services/aqi.data.service';
|
||||
import { PresenceSensorDailySpaceRepository } from '@app/common/modules/presence-sensor/repositories';
|
||||
import { AqiSpaceDailyPollutantStatsRepository } from '@app/common/modules/aqi/repositories';
|
||||
@Module({
|
||||
imports: [ConfigModule, DeviceRepositoryModule],
|
||||
controllers: [GroupController],
|
||||
@ -55,6 +57,8 @@ import { AqiDataService } from '@app/common/helper/services/aqi.data.service';
|
||||
OccupancyService,
|
||||
CommunityRepository,
|
||||
AqiDataService,
|
||||
PresenceSensorDailySpaceRepository,
|
||||
AqiSpaceDailyPollutantStatsRepository,
|
||||
],
|
||||
exports: [GroupService],
|
||||
})
|
||||
|
@ -82,6 +82,8 @@ import { SubspaceProductAllocationService } from 'src/space/services/subspace/su
|
||||
import { TagService as NewTagService } from 'src/tags/services';
|
||||
import { UserDevicePermissionService } from 'src/user-device-permission/services';
|
||||
import { UserService, UserSpaceService } from 'src/users/services';
|
||||
import { PresenceSensorDailySpaceRepository } from '@app/common/modules/presence-sensor/repositories';
|
||||
import { AqiSpaceDailyPollutantStatsRepository } from '@app/common/modules/aqi/repositories';
|
||||
|
||||
@Module({
|
||||
imports: [ConfigModule, InviteUserRepositoryModule, CommunityModule],
|
||||
@ -150,6 +152,8 @@ import { UserService, UserSpaceService } from 'src/users/services';
|
||||
SqlLoaderService,
|
||||
OccupancyService,
|
||||
AqiDataService,
|
||||
PresenceSensorDailySpaceRepository,
|
||||
AqiSpaceDailyPollutantStatsRepository,
|
||||
],
|
||||
exports: [InviteUserService],
|
||||
})
|
||||
|
@ -111,6 +111,7 @@ export class InviteUserService {
|
||||
});
|
||||
|
||||
const invitedUser = await queryRunner.manager.save(inviteUser);
|
||||
const invitedRoleType = await this.getRoleTypeByUuid(roleUuid);
|
||||
|
||||
// Link user to spaces
|
||||
const spacePromises = validSpaces.map(async (space) => {
|
||||
@ -128,7 +129,7 @@ export class InviteUserService {
|
||||
await this.emailService.sendEmailWithInvitationTemplate(email, {
|
||||
name: firstName,
|
||||
invitationCode,
|
||||
role: roleType,
|
||||
role: invitedRoleType.replace(/_/g, ' '),
|
||||
spacesList: spaceNames,
|
||||
});
|
||||
|
||||
|
15
src/main.ts
15
src/main.ts
@ -3,7 +3,6 @@ import { SeederService } from '@app/common/seed/services/seeder.service';
|
||||
import { Logger, ValidationPipe } from '@nestjs/common';
|
||||
import { NestFactory } from '@nestjs/core';
|
||||
import { json, urlencoded } from 'body-parser';
|
||||
import rateLimit from 'express-rate-limit';
|
||||
import helmet from 'helmet';
|
||||
import { WINSTON_MODULE_NEST_PROVIDER } from 'nest-winston';
|
||||
import { setupSwaggerAuthentication } from '../libs/common/src/util/user-auth.swagger.utils';
|
||||
@ -22,20 +21,6 @@ async function bootstrap() {
|
||||
|
||||
app.use(new RequestContextMiddleware().use);
|
||||
|
||||
app.use(
|
||||
rateLimit({
|
||||
windowMs: 5 * 60 * 1000,
|
||||
max: 500,
|
||||
}),
|
||||
);
|
||||
|
||||
app.use((req, res, next) => {
|
||||
console.log('Real IP:', req.ip);
|
||||
next();
|
||||
});
|
||||
|
||||
// app.getHttpAdapter().getInstance().set('trust proxy', 1);
|
||||
|
||||
app.use(
|
||||
helmet({
|
||||
contentSecurityPolicy: false,
|
||||
|
@ -1,25 +1,24 @@
|
||||
import { ControllerRoute } from '@app/common/constants/controller-route';
|
||||
import { EnableDisableStatusEnum } from '@app/common/constants/days.enum';
|
||||
import { BaseResponseDto } from '@app/common/dto/base.response.dto';
|
||||
import { JwtAuthGuard } from '@app/common/guards/jwt.auth.guard';
|
||||
import { Controller, Get, Param, Query, UseGuards } from '@nestjs/common';
|
||||
import {
|
||||
ApiTags,
|
||||
ApiBearerAuth,
|
||||
ApiOperation,
|
||||
ApiParam,
|
||||
ApiQuery,
|
||||
ApiTags,
|
||||
} from '@nestjs/swagger';
|
||||
import { EnableDisableStatusEnum } from '@app/common/constants/days.enum';
|
||||
import { ControllerRoute } from '@app/common/constants/controller-route';
|
||||
import { JwtAuthGuard } from '@app/common/guards/jwt.auth.guard';
|
||||
import { PowerClampService } from '../services/power-clamp.service';
|
||||
import {
|
||||
GetPowerClampBySpaceDto,
|
||||
GetPowerClampDto,
|
||||
} from '../dto/get-power-clamp.dto';
|
||||
import { BaseResponseDto } from '@app/common/dto/base.response.dto';
|
||||
import {
|
||||
PowerClampParamsDto,
|
||||
ResourceParamsDto,
|
||||
} from '../dto/power-clamp-params.dto';
|
||||
|
||||
import { PowerClampService } from '../services/power-clamp.service';
|
||||
@ApiTags('Power Clamp Module')
|
||||
@Controller({
|
||||
version: EnableDisableStatusEnum.ENABLED,
|
||||
@ -27,7 +26,6 @@ import {
|
||||
})
|
||||
export class PowerClampController {
|
||||
constructor(private readonly powerClampService: PowerClampService) {}
|
||||
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@Get(':powerClampUuid/historical')
|
||||
|
@ -60,6 +60,8 @@ import { SubspaceProductAllocationService } from 'src/space/services/subspace/su
|
||||
import { TagService } from 'src/tags/services';
|
||||
import { PowerClampController } from './controllers';
|
||||
import { PowerClampService as PowerClamp } from './services/power-clamp.service';
|
||||
import { PresenceSensorDailySpaceRepository } from '@app/common/modules/presence-sensor/repositories';
|
||||
import { AqiSpaceDailyPollutantStatsRepository } from '@app/common/modules/aqi/repositories';
|
||||
@Module({
|
||||
imports: [ConfigModule],
|
||||
controllers: [PowerClampController],
|
||||
@ -109,6 +111,8 @@ import { PowerClampService as PowerClamp } from './services/power-clamp.service'
|
||||
SubspaceModelProductAllocationRepoitory,
|
||||
OccupancyService,
|
||||
AqiDataService,
|
||||
PresenceSensorDailySpaceRepository,
|
||||
AqiSpaceDailyPollutantStatsRepository,
|
||||
],
|
||||
exports: [PowerClamp],
|
||||
})
|
||||
|
@ -23,10 +23,10 @@ import { SpaceDeviceService } from 'src/space/services';
|
||||
import { SqlLoaderService } from '@app/common/helper/services/sql-loader.service';
|
||||
import { DataSource } from 'typeorm';
|
||||
import { SQL_PROCEDURES_PATH } from '@app/common/constants/sql-query-path';
|
||||
import { filterByMonth, toMMYYYY } from '@app/common/helper/date-format';
|
||||
import { ProductType } from '@app/common/constants/product-type.enum';
|
||||
import { CommunityService } from 'src/community/services';
|
||||
import { BaseResponseDto } from '@app/common/dto/base.response.dto';
|
||||
import { filterByMonth, toMMYYYY } from '@app/common/helper/date-format';
|
||||
|
||||
@Injectable()
|
||||
export class PowerClampService {
|
||||
|
@ -67,6 +67,8 @@ import { ProjectUserController } from './controllers/project-user.controller';
|
||||
import { CreateOrphanSpaceHandler } from './handler';
|
||||
import { ProjectService } from './services';
|
||||
import { ProjectUserService } from './services/project-user.service';
|
||||
import { PresenceSensorDailySpaceRepository } from '@app/common/modules/presence-sensor/repositories';
|
||||
import { AqiSpaceDailyPollutantStatsRepository } from '@app/common/modules/aqi/repositories';
|
||||
|
||||
const CommandHandlers = [CreateOrphanSpaceHandler];
|
||||
|
||||
@ -124,6 +126,8 @@ const CommandHandlers = [CreateOrphanSpaceHandler];
|
||||
SqlLoaderService,
|
||||
OccupancyService,
|
||||
AqiDataService,
|
||||
PresenceSensorDailySpaceRepository,
|
||||
AqiSpaceDailyPollutantStatsRepository,
|
||||
],
|
||||
exports: [ProjectService, CqrsModule],
|
||||
})
|
||||
|
32
src/schedule/constants/device-function-map.ts
Normal file
32
src/schedule/constants/device-function-map.ts
Normal file
@ -0,0 +1,32 @@
|
||||
import {
|
||||
ControlCur2AccurateCalibrationCommand,
|
||||
ControlCur2Command,
|
||||
ControlCur2PercentCommand,
|
||||
ControlCur2QuickCalibrationCommand,
|
||||
ControlCur2TDirectionConCommand,
|
||||
} from 'src/device/commands/cur2-commands';
|
||||
|
||||
export enum ScheduleProductType {
|
||||
CUR_2 = 'CUR_2',
|
||||
}
|
||||
export const DeviceFunctionMap: {
|
||||
[T in ScheduleProductType]: (body: DeviceFunction[T]) => any;
|
||||
} = {
|
||||
[ScheduleProductType.CUR_2]: ({ code, value }) => {
|
||||
return [
|
||||
{
|
||||
code,
|
||||
value,
|
||||
},
|
||||
];
|
||||
},
|
||||
};
|
||||
|
||||
type DeviceFunction = {
|
||||
[ScheduleProductType.CUR_2]:
|
||||
| ControlCur2Command
|
||||
| ControlCur2PercentCommand
|
||||
| ControlCur2AccurateCalibrationCommand
|
||||
| ControlCur2TDirectionConCommand
|
||||
| ControlCur2QuickCalibrationCommand;
|
||||
};
|
@ -1,6 +1,6 @@
|
||||
import { Injectable, HttpException, HttpStatus } from '@nestjs/common';
|
||||
import { TuyaContext } from '@tuya/tuya-connector-nodejs';
|
||||
import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { TuyaContext } from '@tuya/tuya-connector-nodejs';
|
||||
import {
|
||||
AddScheduleDto,
|
||||
EnableScheduleDto,
|
||||
@ -11,14 +11,14 @@ import {
|
||||
getDeviceScheduleInterface,
|
||||
} from '../interfaces/get.schedule.interface';
|
||||
|
||||
import { convertKeysToCamelCase } from '@app/common/helper/camelCaseConverter';
|
||||
import { DeviceRepository } from '@app/common/modules/device/repositories';
|
||||
import { ProductType } from '@app/common/constants/product-type.enum';
|
||||
import { convertKeysToCamelCase } from '@app/common/helper/camelCaseConverter';
|
||||
import { convertTimestampToDubaiTime } from '@app/common/helper/convertTimestampToDubaiTime';
|
||||
import {
|
||||
getEnabledDays,
|
||||
getScheduleStatus,
|
||||
} from '@app/common/helper/getScheduleStatus';
|
||||
import { DeviceRepository } from '@app/common/modules/device/repositories';
|
||||
|
||||
@Injectable()
|
||||
export class ScheduleService {
|
||||
@ -49,22 +49,11 @@ export class ScheduleService {
|
||||
}
|
||||
|
||||
// Corrected condition for supported device types
|
||||
if (
|
||||
deviceDetails.productDevice.prodType !== ProductType.THREE_G &&
|
||||
deviceDetails.productDevice.prodType !== ProductType.ONE_G &&
|
||||
deviceDetails.productDevice.prodType !== ProductType.TWO_G &&
|
||||
deviceDetails.productDevice.prodType !== ProductType.WH &&
|
||||
deviceDetails.productDevice.prodType !== ProductType.ONE_1TG &&
|
||||
deviceDetails.productDevice.prodType !== ProductType.TWO_2TG &&
|
||||
deviceDetails.productDevice.prodType !== ProductType.THREE_3TG &&
|
||||
deviceDetails.productDevice.prodType !== ProductType.GD
|
||||
) {
|
||||
throw new HttpException(
|
||||
'This device is not supported for schedule',
|
||||
HttpStatus.BAD_REQUEST,
|
||||
);
|
||||
}
|
||||
return await this.enableScheduleDeviceInTuya(
|
||||
this.ensureProductTypeSupportedForSchedule(
|
||||
deviceDetails.productDevice.prodType as ProductType,
|
||||
);
|
||||
|
||||
return this.enableScheduleDeviceInTuya(
|
||||
deviceDetails.deviceTuyaUuid,
|
||||
enableScheduleDto,
|
||||
);
|
||||
@ -75,7 +64,281 @@ export class ScheduleService {
|
||||
);
|
||||
}
|
||||
}
|
||||
async enableScheduleDeviceInTuya(
|
||||
async deleteDeviceSchedule(deviceUuid: string, scheduleId: string) {
|
||||
try {
|
||||
const deviceDetails = await this.getDeviceByDeviceUuid(deviceUuid);
|
||||
|
||||
if (!deviceDetails || !deviceDetails.deviceTuyaUuid) {
|
||||
throw new HttpException('Device Not Found', HttpStatus.NOT_FOUND);
|
||||
}
|
||||
|
||||
// Corrected condition for supported device types
|
||||
this.ensureProductTypeSupportedForSchedule(
|
||||
deviceDetails.productDevice.prodType as ProductType,
|
||||
);
|
||||
|
||||
return await this.deleteScheduleDeviceInTuya(
|
||||
deviceDetails.deviceTuyaUuid,
|
||||
scheduleId,
|
||||
);
|
||||
} catch (error) {
|
||||
throw new HttpException(
|
||||
error.message || 'Error While Deleting Schedule',
|
||||
error.status || HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
}
|
||||
async addDeviceSchedule(deviceUuid: string, addScheduleDto: AddScheduleDto) {
|
||||
try {
|
||||
const deviceDetails = await this.getDeviceByDeviceUuid(deviceUuid);
|
||||
|
||||
if (!deviceDetails || !deviceDetails.deviceTuyaUuid) {
|
||||
throw new HttpException('Device Not Found', HttpStatus.NOT_FOUND);
|
||||
}
|
||||
|
||||
if (
|
||||
deviceDetails.productDevice.prodType == ProductType.CUR_2 &&
|
||||
addScheduleDto.category != 'Timer'
|
||||
) {
|
||||
throw new HttpException(
|
||||
'Invalid category for CUR_2 devices',
|
||||
HttpStatus.BAD_REQUEST,
|
||||
);
|
||||
}
|
||||
|
||||
if (
|
||||
deviceDetails.productDevice.prodType == ProductType.CUR_2 &&
|
||||
addScheduleDto.category != 'Timer'
|
||||
) {
|
||||
throw new HttpException(
|
||||
'Invalid category for CUR_2 devices',
|
||||
HttpStatus.BAD_REQUEST,
|
||||
);
|
||||
}
|
||||
|
||||
this.ensureProductTypeSupportedForSchedule(
|
||||
deviceDetails.productDevice.prodType as ProductType,
|
||||
);
|
||||
|
||||
await this.addScheduleDeviceInTuya(
|
||||
deviceDetails.deviceTuyaUuid,
|
||||
addScheduleDto,
|
||||
deviceDetails.productDevice.prodType as ProductType,
|
||||
);
|
||||
} catch (error) {
|
||||
throw new HttpException(
|
||||
error.message || 'Error While Adding Schedule',
|
||||
error.status || HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
}
|
||||
async getDeviceScheduleByCategory(deviceUuid: string, category: string) {
|
||||
try {
|
||||
const deviceDetails = await this.getDeviceByDeviceUuid(deviceUuid);
|
||||
|
||||
if (!deviceDetails || !deviceDetails.deviceTuyaUuid) {
|
||||
throw new HttpException('Device Not Found', HttpStatus.NOT_FOUND);
|
||||
}
|
||||
// Corrected condition for supported device types
|
||||
this.ensureProductTypeSupportedForSchedule(
|
||||
deviceDetails.productDevice.prodType as ProductType,
|
||||
);
|
||||
const schedules = await this.getScheduleDeviceInTuya(
|
||||
deviceDetails.deviceTuyaUuid,
|
||||
category,
|
||||
deviceDetails.productDevice.prodType as ProductType,
|
||||
);
|
||||
const result = schedules.result.map((schedule: any) => {
|
||||
return {
|
||||
category:
|
||||
deviceDetails.productDevice.prodType == ProductType.CUR_2
|
||||
? schedule.category
|
||||
: schedule.category.replace('category_', ''),
|
||||
enable: schedule.enable,
|
||||
function: {
|
||||
code: schedule.functions[0].code,
|
||||
value: schedule.functions[0].value,
|
||||
},
|
||||
time: schedule.time,
|
||||
schedule_id: schedule.timer_id,
|
||||
timezone_id: schedule.timezone_id,
|
||||
days: getEnabledDays(schedule.loops),
|
||||
};
|
||||
});
|
||||
return convertKeysToCamelCase(result);
|
||||
} catch (error) {
|
||||
throw new HttpException(
|
||||
error.message || 'Error While Adding Schedule',
|
||||
error.status || HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
}
|
||||
async updateDeviceSchedule(
|
||||
deviceUuid: string,
|
||||
updateScheduleDto: UpdateScheduleDto,
|
||||
) {
|
||||
try {
|
||||
const deviceDetails = await this.getDeviceByDeviceUuid(deviceUuid);
|
||||
|
||||
if (!deviceDetails || !deviceDetails.deviceTuyaUuid) {
|
||||
throw new HttpException('Device Not Found', HttpStatus.NOT_FOUND);
|
||||
}
|
||||
|
||||
if (
|
||||
deviceDetails.productDevice.prodType == ProductType.CUR_2 &&
|
||||
updateScheduleDto.category != 'Timer'
|
||||
) {
|
||||
throw new HttpException(
|
||||
'Invalid category for CUR_2 devices',
|
||||
HttpStatus.BAD_REQUEST,
|
||||
);
|
||||
}
|
||||
|
||||
if (
|
||||
deviceDetails.productDevice.prodType == ProductType.CUR_2 &&
|
||||
updateScheduleDto.category != 'Timer'
|
||||
) {
|
||||
throw new HttpException(
|
||||
'Invalid category for CUR_2 devices',
|
||||
HttpStatus.BAD_REQUEST,
|
||||
);
|
||||
}
|
||||
|
||||
// Corrected condition for supported device types
|
||||
this.ensureProductTypeSupportedForSchedule(
|
||||
deviceDetails.productDevice.prodType as ProductType,
|
||||
);
|
||||
|
||||
await this.updateScheduleDeviceInTuya(
|
||||
deviceDetails.deviceTuyaUuid,
|
||||
updateScheduleDto,
|
||||
deviceDetails.productDevice.prodType as ProductType,
|
||||
);
|
||||
} catch (error) {
|
||||
throw new HttpException(
|
||||
error.message || 'Error While Updating Schedule',
|
||||
error.status || HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private getDeviceByDeviceUuid(
|
||||
deviceUuid: string,
|
||||
withProductDevice: boolean = true,
|
||||
) {
|
||||
return this.deviceRepository.findOne({
|
||||
where: {
|
||||
uuid: deviceUuid,
|
||||
isActive: true,
|
||||
},
|
||||
...(withProductDevice && { relations: ['productDevice'] }),
|
||||
});
|
||||
}
|
||||
|
||||
private async addScheduleDeviceInTuya(
|
||||
deviceId: string,
|
||||
addScheduleDto: AddScheduleDto,
|
||||
deviceType: ProductType,
|
||||
): Promise<addScheduleDeviceInterface> {
|
||||
try {
|
||||
const convertedTime = convertTimestampToDubaiTime(addScheduleDto.time);
|
||||
const loops = getScheduleStatus(addScheduleDto.days);
|
||||
|
||||
const path = `/v2.0/cloud/timer/device/${deviceId}`;
|
||||
const response = await this.tuya.request({
|
||||
method: 'POST',
|
||||
path,
|
||||
body: {
|
||||
time: convertedTime.time,
|
||||
timezone_id: 'Asia/Dubai',
|
||||
loops: `${loops}`,
|
||||
functions: [
|
||||
{
|
||||
...addScheduleDto.function,
|
||||
},
|
||||
],
|
||||
category:
|
||||
deviceType == ProductType.CUR_2
|
||||
? addScheduleDto.category
|
||||
: `category_${addScheduleDto.category}`,
|
||||
},
|
||||
});
|
||||
|
||||
return response as addScheduleDeviceInterface;
|
||||
} catch (error) {
|
||||
throw new HttpException(
|
||||
'Error adding schedule from Tuya',
|
||||
HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private async getScheduleDeviceInTuya(
|
||||
deviceId: string,
|
||||
category: string,
|
||||
deviceType: ProductType,
|
||||
): Promise<getDeviceScheduleInterface> {
|
||||
try {
|
||||
const categoryToSent =
|
||||
deviceType == ProductType.CUR_2 ? category : `category_${category}`;
|
||||
const path = `/v2.0/cloud/timer/device/${deviceId}?category=${categoryToSent}`;
|
||||
const response = await this.tuya.request({
|
||||
method: 'GET',
|
||||
path,
|
||||
});
|
||||
|
||||
return response as getDeviceScheduleInterface;
|
||||
} catch (error) {
|
||||
console.error('Error fetching device schedule from Tuya:', error);
|
||||
|
||||
throw new HttpException(
|
||||
'Error fetching device schedule from Tuya',
|
||||
HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private async updateScheduleDeviceInTuya(
|
||||
deviceId: string,
|
||||
updateScheduleDto: UpdateScheduleDto,
|
||||
deviceType: ProductType,
|
||||
): Promise<addScheduleDeviceInterface> {
|
||||
try {
|
||||
const convertedTime = convertTimestampToDubaiTime(updateScheduleDto.time);
|
||||
const loops = getScheduleStatus(updateScheduleDto.days);
|
||||
|
||||
const path = `/v2.0/cloud/timer/device/${deviceId}`;
|
||||
const response = await this.tuya.request({
|
||||
method: 'PUT',
|
||||
path,
|
||||
body: {
|
||||
timer_id: updateScheduleDto.scheduleId,
|
||||
time: convertedTime.time,
|
||||
timezone_id: 'Asia/Dubai',
|
||||
loops: `${loops}`,
|
||||
functions: [
|
||||
{
|
||||
code: updateScheduleDto.function.code,
|
||||
value: updateScheduleDto.function.value,
|
||||
},
|
||||
],
|
||||
category:
|
||||
deviceType == ProductType.CUR_2
|
||||
? updateScheduleDto.category
|
||||
: `category_${updateScheduleDto.category}`,
|
||||
},
|
||||
});
|
||||
|
||||
return response as addScheduleDeviceInterface;
|
||||
} catch (error) {
|
||||
throw new HttpException(
|
||||
'Error updating schedule from Tuya',
|
||||
HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private async enableScheduleDeviceInTuya(
|
||||
deviceId: string,
|
||||
enableScheduleDto: EnableScheduleDto,
|
||||
): Promise<addScheduleDeviceInterface> {
|
||||
@ -98,42 +361,8 @@ export class ScheduleService {
|
||||
);
|
||||
}
|
||||
}
|
||||
async deleteDeviceSchedule(deviceUuid: string, scheduleId: string) {
|
||||
try {
|
||||
const deviceDetails = await this.getDeviceByDeviceUuid(deviceUuid);
|
||||
|
||||
if (!deviceDetails || !deviceDetails.deviceTuyaUuid) {
|
||||
throw new HttpException('Device Not Found', HttpStatus.NOT_FOUND);
|
||||
}
|
||||
|
||||
// Corrected condition for supported device types
|
||||
if (
|
||||
deviceDetails.productDevice.prodType !== ProductType.THREE_G &&
|
||||
deviceDetails.productDevice.prodType !== ProductType.ONE_G &&
|
||||
deviceDetails.productDevice.prodType !== ProductType.TWO_G &&
|
||||
deviceDetails.productDevice.prodType !== ProductType.WH &&
|
||||
deviceDetails.productDevice.prodType !== ProductType.ONE_1TG &&
|
||||
deviceDetails.productDevice.prodType !== ProductType.TWO_2TG &&
|
||||
deviceDetails.productDevice.prodType !== ProductType.THREE_3TG &&
|
||||
deviceDetails.productDevice.prodType !== ProductType.GD
|
||||
) {
|
||||
throw new HttpException(
|
||||
'This device is not supported for schedule',
|
||||
HttpStatus.BAD_REQUEST,
|
||||
);
|
||||
}
|
||||
return await this.deleteScheduleDeviceInTuya(
|
||||
deviceDetails.deviceTuyaUuid,
|
||||
scheduleId,
|
||||
);
|
||||
} catch (error) {
|
||||
throw new HttpException(
|
||||
error.message || 'Error While Deleting Schedule',
|
||||
error.status || HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
}
|
||||
async deleteScheduleDeviceInTuya(
|
||||
private async deleteScheduleDeviceInTuya(
|
||||
deviceId: string,
|
||||
scheduleId: string,
|
||||
): Promise<addScheduleDeviceInterface> {
|
||||
@ -152,227 +381,24 @@ export class ScheduleService {
|
||||
);
|
||||
}
|
||||
}
|
||||
async addDeviceSchedule(deviceUuid: string, addScheduleDto: AddScheduleDto) {
|
||||
try {
|
||||
const deviceDetails = await this.getDeviceByDeviceUuid(deviceUuid);
|
||||
|
||||
if (!deviceDetails || !deviceDetails.deviceTuyaUuid) {
|
||||
throw new HttpException('Device Not Found', HttpStatus.NOT_FOUND);
|
||||
}
|
||||
|
||||
// Corrected condition for supported device types
|
||||
if (
|
||||
deviceDetails.productDevice.prodType !== ProductType.THREE_G &&
|
||||
deviceDetails.productDevice.prodType !== ProductType.ONE_G &&
|
||||
deviceDetails.productDevice.prodType !== ProductType.TWO_G &&
|
||||
deviceDetails.productDevice.prodType !== ProductType.WH &&
|
||||
deviceDetails.productDevice.prodType !== ProductType.ONE_1TG &&
|
||||
deviceDetails.productDevice.prodType !== ProductType.TWO_2TG &&
|
||||
deviceDetails.productDevice.prodType !== ProductType.THREE_3TG &&
|
||||
deviceDetails.productDevice.prodType !== ProductType.GD
|
||||
) {
|
||||
throw new HttpException(
|
||||
'This device is not supported for schedule',
|
||||
HttpStatus.BAD_REQUEST,
|
||||
);
|
||||
}
|
||||
await this.addScheduleDeviceInTuya(
|
||||
deviceDetails.deviceTuyaUuid,
|
||||
addScheduleDto,
|
||||
);
|
||||
} catch (error) {
|
||||
private ensureProductTypeSupportedForSchedule(deviceType: ProductType): void {
|
||||
if (
|
||||
![
|
||||
ProductType.THREE_G,
|
||||
ProductType.ONE_G,
|
||||
ProductType.TWO_G,
|
||||
ProductType.WH,
|
||||
ProductType.ONE_1TG,
|
||||
ProductType.TWO_2TG,
|
||||
ProductType.THREE_3TG,
|
||||
ProductType.GD,
|
||||
ProductType.CUR_2,
|
||||
].includes(deviceType)
|
||||
) {
|
||||
throw new HttpException(
|
||||
error.message || 'Error While Adding Schedule',
|
||||
error.status || HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
}
|
||||
async addScheduleDeviceInTuya(
|
||||
deviceId: string,
|
||||
addScheduleDto: AddScheduleDto,
|
||||
): Promise<addScheduleDeviceInterface> {
|
||||
try {
|
||||
const convertedTime = convertTimestampToDubaiTime(addScheduleDto.time);
|
||||
const loops = getScheduleStatus(addScheduleDto.days);
|
||||
|
||||
const path = `/v2.0/cloud/timer/device/${deviceId}`;
|
||||
const response = await this.tuya.request({
|
||||
method: 'POST',
|
||||
path,
|
||||
body: {
|
||||
time: convertedTime.time,
|
||||
timezone_id: 'Asia/Dubai',
|
||||
loops: `${loops}`,
|
||||
functions: [
|
||||
{
|
||||
code: addScheduleDto.function.code,
|
||||
value: addScheduleDto.function.value,
|
||||
},
|
||||
],
|
||||
category: `category_${addScheduleDto.category}`,
|
||||
},
|
||||
});
|
||||
|
||||
return response as addScheduleDeviceInterface;
|
||||
} catch (error) {
|
||||
throw new HttpException(
|
||||
'Error adding schedule from Tuya',
|
||||
HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
}
|
||||
async getDeviceScheduleByCategory(deviceUuid: string, category: string) {
|
||||
try {
|
||||
const deviceDetails = await this.getDeviceByDeviceUuid(deviceUuid);
|
||||
|
||||
if (!deviceDetails || !deviceDetails.deviceTuyaUuid) {
|
||||
throw new HttpException('Device Not Found', HttpStatus.NOT_FOUND);
|
||||
}
|
||||
// Corrected condition for supported device types
|
||||
if (
|
||||
deviceDetails.productDevice.prodType !== ProductType.THREE_G &&
|
||||
deviceDetails.productDevice.prodType !== ProductType.ONE_G &&
|
||||
deviceDetails.productDevice.prodType !== ProductType.TWO_G &&
|
||||
deviceDetails.productDevice.prodType !== ProductType.WH &&
|
||||
deviceDetails.productDevice.prodType !== ProductType.ONE_1TG &&
|
||||
deviceDetails.productDevice.prodType !== ProductType.TWO_2TG &&
|
||||
deviceDetails.productDevice.prodType !== ProductType.THREE_3TG &&
|
||||
deviceDetails.productDevice.prodType !== ProductType.GD
|
||||
) {
|
||||
throw new HttpException(
|
||||
'This device is not supported for schedule',
|
||||
HttpStatus.BAD_REQUEST,
|
||||
);
|
||||
}
|
||||
const schedules = await this.getScheduleDeviceInTuya(
|
||||
deviceDetails.deviceTuyaUuid,
|
||||
category,
|
||||
);
|
||||
const result = schedules.result.map((schedule: any) => {
|
||||
return {
|
||||
category: schedule.category.replace('category_', ''),
|
||||
enable: schedule.enable,
|
||||
function: {
|
||||
code: schedule.functions[0].code,
|
||||
value: schedule.functions[0].value,
|
||||
},
|
||||
time: schedule.time,
|
||||
schedule_id: schedule.timer_id,
|
||||
timezone_id: schedule.timezone_id,
|
||||
days: getEnabledDays(schedule.loops),
|
||||
};
|
||||
});
|
||||
return convertKeysToCamelCase(result);
|
||||
} catch (error) {
|
||||
throw new HttpException(
|
||||
error.message || 'Error While Adding Schedule',
|
||||
error.status || HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
}
|
||||
async getScheduleDeviceInTuya(
|
||||
deviceId: string,
|
||||
category: string,
|
||||
): Promise<getDeviceScheduleInterface> {
|
||||
try {
|
||||
const path = `/v2.0/cloud/timer/device/${deviceId}?category=category_${category}`;
|
||||
const response = await this.tuya.request({
|
||||
method: 'GET',
|
||||
path,
|
||||
});
|
||||
|
||||
return response as getDeviceScheduleInterface;
|
||||
} catch (error) {
|
||||
console.error('Error fetching device schedule from Tuya:', error);
|
||||
|
||||
throw new HttpException(
|
||||
'Error fetching device schedule from Tuya',
|
||||
HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
}
|
||||
async getDeviceByDeviceUuid(
|
||||
deviceUuid: string,
|
||||
withProductDevice: boolean = true,
|
||||
) {
|
||||
return await this.deviceRepository.findOne({
|
||||
where: {
|
||||
uuid: deviceUuid,
|
||||
isActive: true,
|
||||
},
|
||||
...(withProductDevice && { relations: ['productDevice'] }),
|
||||
});
|
||||
}
|
||||
async updateDeviceSchedule(
|
||||
deviceUuid: string,
|
||||
updateScheduleDto: UpdateScheduleDto,
|
||||
) {
|
||||
try {
|
||||
const deviceDetails = await this.getDeviceByDeviceUuid(deviceUuid);
|
||||
|
||||
if (!deviceDetails || !deviceDetails.deviceTuyaUuid) {
|
||||
throw new HttpException('Device Not Found', HttpStatus.NOT_FOUND);
|
||||
}
|
||||
|
||||
// Corrected condition for supported device types
|
||||
if (
|
||||
deviceDetails.productDevice.prodType !== ProductType.THREE_G &&
|
||||
deviceDetails.productDevice.prodType !== ProductType.ONE_G &&
|
||||
deviceDetails.productDevice.prodType !== ProductType.TWO_G &&
|
||||
deviceDetails.productDevice.prodType !== ProductType.WH &&
|
||||
deviceDetails.productDevice.prodType !== ProductType.ONE_1TG &&
|
||||
deviceDetails.productDevice.prodType !== ProductType.TWO_2TG &&
|
||||
deviceDetails.productDevice.prodType !== ProductType.THREE_3TG &&
|
||||
deviceDetails.productDevice.prodType !== ProductType.GD
|
||||
) {
|
||||
throw new HttpException(
|
||||
'This device is not supported for schedule',
|
||||
HttpStatus.BAD_REQUEST,
|
||||
);
|
||||
}
|
||||
await this.updateScheduleDeviceInTuya(
|
||||
deviceDetails.deviceTuyaUuid,
|
||||
updateScheduleDto,
|
||||
);
|
||||
} catch (error) {
|
||||
throw new HttpException(
|
||||
error.message || 'Error While Updating Schedule',
|
||||
error.status || HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
}
|
||||
async updateScheduleDeviceInTuya(
|
||||
deviceId: string,
|
||||
updateScheduleDto: UpdateScheduleDto,
|
||||
): Promise<addScheduleDeviceInterface> {
|
||||
try {
|
||||
const convertedTime = convertTimestampToDubaiTime(updateScheduleDto.time);
|
||||
const loops = getScheduleStatus(updateScheduleDto.days);
|
||||
|
||||
const path = `/v2.0/cloud/timer/device/${deviceId}`;
|
||||
const response = await this.tuya.request({
|
||||
method: 'PUT',
|
||||
path,
|
||||
body: {
|
||||
timer_id: updateScheduleDto.scheduleId,
|
||||
time: convertedTime.time,
|
||||
timezone_id: 'Asia/Dubai',
|
||||
loops: `${loops}`,
|
||||
functions: [
|
||||
{
|
||||
code: updateScheduleDto.function.code,
|
||||
value: updateScheduleDto.function.value,
|
||||
},
|
||||
],
|
||||
category: `category_${updateScheduleDto.category}`,
|
||||
},
|
||||
});
|
||||
|
||||
return response as addScheduleDeviceInterface;
|
||||
} catch (error) {
|
||||
throw new HttpException(
|
||||
'Error updating schedule from Tuya',
|
||||
HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
'This device is not supported for schedule',
|
||||
HttpStatus.BAD_REQUEST,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
25
src/scheduler/scheduler.module.ts
Normal file
25
src/scheduler/scheduler.module.ts
Normal file
@ -0,0 +1,25 @@
|
||||
import { DatabaseModule } from '@app/common/database/database.module';
|
||||
import { SqlLoaderService } from '@app/common/helper/services/sql-loader.service';
|
||||
import { Module } from '@nestjs/common';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { SchedulerService } from './scheduler.service';
|
||||
import { ScheduleModule as NestScheduleModule } from '@nestjs/schedule';
|
||||
import { AqiDataService } from '@app/common/helper/services/aqi.data.service';
|
||||
import { OccupancyService } from '@app/common/helper/services/occupancy.service';
|
||||
import { PowerClampService } from '@app/common/helper/services/power.clamp.service';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
NestScheduleModule.forRoot(),
|
||||
TypeOrmModule.forFeature([]),
|
||||
DatabaseModule,
|
||||
],
|
||||
providers: [
|
||||
SchedulerService,
|
||||
SqlLoaderService,
|
||||
PowerClampService,
|
||||
OccupancyService,
|
||||
AqiDataService,
|
||||
],
|
||||
})
|
||||
export class SchedulerModule {}
|
92
src/scheduler/scheduler.service.ts
Normal file
92
src/scheduler/scheduler.service.ts
Normal file
@ -0,0 +1,92 @@
|
||||
import { AqiDataService } from '@app/common/helper/services/aqi.data.service';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { Cron, CronExpression } from '@nestjs/schedule';
|
||||
import { OccupancyService } from '@app/common/helper/services/occupancy.service';
|
||||
import { PowerClampService } from '@app/common/helper/services/power.clamp.service';
|
||||
|
||||
@Injectable()
|
||||
export class SchedulerService {
|
||||
constructor(
|
||||
private readonly powerClampService: PowerClampService,
|
||||
private readonly occupancyService: OccupancyService,
|
||||
private readonly aqiDataService: AqiDataService,
|
||||
) {
|
||||
console.log('SchedulerService initialized!');
|
||||
}
|
||||
|
||||
@Cron(CronExpression.EVERY_HOUR)
|
||||
async runHourlyProcedures() {
|
||||
console.log('\n======== Starting Procedures ========');
|
||||
console.log(new Date().toISOString(), 'Scheduler running...');
|
||||
|
||||
try {
|
||||
const results = await Promise.allSettled([
|
||||
this.executeTask(
|
||||
() => this.powerClampService.updateEnergyConsumedHistoricalData(),
|
||||
'Energy Consumption',
|
||||
),
|
||||
this.executeTask(
|
||||
() => this.occupancyService.updateOccupancyDataProcedures(),
|
||||
'Occupancy Data',
|
||||
),
|
||||
this.executeTask(
|
||||
() => this.aqiDataService.updateAQISensorHistoricalData(),
|
||||
'AQI Data',
|
||||
),
|
||||
]);
|
||||
|
||||
this.logResults(results);
|
||||
} catch (error) {
|
||||
console.error('MAIN SCHEDULER ERROR:', error);
|
||||
if (error.stack) {
|
||||
console.error('Error stack:', error.stack);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async executeTask(
|
||||
task: () => Promise<void>,
|
||||
name: string,
|
||||
): Promise<{ name: string; status: string }> {
|
||||
try {
|
||||
console.log(`[${new Date().toISOString()}] Starting ${name} task...`);
|
||||
await task();
|
||||
console.log(
|
||||
`[${new Date().toISOString()}] ${name} task completed successfully`,
|
||||
);
|
||||
return { name, status: 'success' };
|
||||
} catch (error) {
|
||||
console.error(
|
||||
`[${new Date().toISOString()}] ${name} task failed:`,
|
||||
error.message,
|
||||
);
|
||||
if (error.stack) {
|
||||
console.error('Task error stack:', error.stack);
|
||||
}
|
||||
return { name, status: 'failed' };
|
||||
}
|
||||
}
|
||||
|
||||
private logResults(results: PromiseSettledResult<any>[]) {
|
||||
const successCount = results.filter((r) => r.status === 'fulfilled').length;
|
||||
const failedCount = results.length - successCount;
|
||||
|
||||
console.log('\n======== Task Results ========');
|
||||
console.log(`Successful tasks: ${successCount}`);
|
||||
console.log(`Failed tasks: ${failedCount}`);
|
||||
|
||||
if (failedCount > 0) {
|
||||
console.log('\n======== Failed Tasks Details ========');
|
||||
results.forEach((result, index) => {
|
||||
if (result.status === 'rejected') {
|
||||
console.error(`Task ${index + 1} failed:`, result.reason);
|
||||
if (result.reason.stack) {
|
||||
console.error('Error stack:', result.reason.stack);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
console.log('\n======== Scheduler Completed ========\n');
|
||||
}
|
||||
}
|
@ -63,6 +63,8 @@ import {
|
||||
import { SpaceModelService, SubSpaceModelService } from './services';
|
||||
import { SpaceModelProductAllocationService } from './services/space-model-product-allocation.service';
|
||||
import { SubspaceModelProductAllocationService } from './services/subspace/subspace-model-product-allocation.service';
|
||||
import { PresenceSensorDailySpaceRepository } from '@app/common/modules/presence-sensor/repositories';
|
||||
import { AqiSpaceDailyPollutantStatsRepository } from '@app/common/modules/aqi/repositories';
|
||||
|
||||
const CommandHandlers = [
|
||||
PropogateUpdateSpaceModelHandler,
|
||||
@ -120,6 +122,8 @@ const CommandHandlers = [
|
||||
SqlLoaderService,
|
||||
OccupancyService,
|
||||
AqiDataService,
|
||||
PresenceSensorDailySpaceRepository,
|
||||
AqiSpaceDailyPollutantStatsRepository,
|
||||
],
|
||||
exports: [CqrsModule, SpaceModelService],
|
||||
})
|
||||
|
@ -333,7 +333,12 @@ export class SpaceService {
|
||||
.andWhere('space.disabled = :disabled', { disabled: false });
|
||||
|
||||
const space = await queryBuilder.getOne();
|
||||
|
||||
if (!space) {
|
||||
throw new HttpException(
|
||||
`Space with ID ${spaceUuid} not found`,
|
||||
HttpStatus.NOT_FOUND,
|
||||
);
|
||||
}
|
||||
return new SuccessResponseDto({
|
||||
message: `Space with ID ${spaceUuid} successfully fetched`,
|
||||
data: space,
|
||||
@ -343,7 +348,7 @@ export class SpaceService {
|
||||
throw error; // If it's an HttpException, rethrow it
|
||||
} else {
|
||||
throw new HttpException(
|
||||
'An error occurred while deleting the community',
|
||||
'An error occurred while fetching the space',
|
||||
HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
|
@ -88,6 +88,8 @@ import {
|
||||
} from './services';
|
||||
import { SpaceProductAllocationService } from './services/space-product-allocation.service';
|
||||
import { SubspaceProductAllocationService } from './services/subspace/subspace-product-allocation.service';
|
||||
import { PresenceSensorDailySpaceRepository } from '@app/common/modules/presence-sensor/repositories';
|
||||
import { AqiSpaceDailyPollutantStatsRepository } from '@app/common/modules/aqi/repositories';
|
||||
|
||||
export const CommandHandlers = [DisableSpaceHandler];
|
||||
|
||||
@ -161,6 +163,8 @@ export const CommandHandlers = [DisableSpaceHandler];
|
||||
SqlLoaderService,
|
||||
OccupancyService,
|
||||
AqiDataService,
|
||||
PresenceSensorDailySpaceRepository,
|
||||
AqiSpaceDailyPollutantStatsRepository,
|
||||
],
|
||||
exports: [SpaceService],
|
||||
})
|
||||
|
@ -1,3 +1,7 @@
|
||||
import { ControllerRoute } from '@app/common/constants/controller-route';
|
||||
import { EnableDisableStatusEnum } from '@app/common/constants/days.enum';
|
||||
import { RoleType } from '@app/common/constants/role.type.enum';
|
||||
import { BaseResponseDto } from '@app/common/dto/base.response.dto';
|
||||
import {
|
||||
Body,
|
||||
Controller,
|
||||
@ -7,10 +11,12 @@ import {
|
||||
Param,
|
||||
Patch,
|
||||
Put,
|
||||
Req,
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import { UserService } from '../services/user.service';
|
||||
import { ApiTags, ApiBearerAuth, ApiOperation } from '@nestjs/swagger';
|
||||
import { ApiBearerAuth, ApiOperation, ApiTags } from '@nestjs/swagger';
|
||||
import { CheckProfilePictureGuard } from 'src/guards/profile.picture.guard';
|
||||
import { SuperAdminRoleGuard } from 'src/guards/super.admin.role.guard';
|
||||
import { JwtAuthGuard } from '../../../libs/common/src/guards/jwt.auth.guard';
|
||||
import {
|
||||
UpdateNameDto,
|
||||
@ -18,11 +24,7 @@ import {
|
||||
UpdateRegionDataDto,
|
||||
UpdateTimezoneDataDto,
|
||||
} from '../dtos';
|
||||
import { CheckProfilePictureGuard } from 'src/guards/profile.picture.guard';
|
||||
import { SuperAdminRoleGuard } from 'src/guards/super.admin.role.guard';
|
||||
import { EnableDisableStatusEnum } from '@app/common/constants/days.enum';
|
||||
import { ControllerRoute } from '@app/common/constants/controller-route';
|
||||
import { BaseResponseDto } from '@app/common/dto/base.response.dto';
|
||||
import { UserService } from '../services/user.service';
|
||||
|
||||
@ApiTags('User Module')
|
||||
@Controller({
|
||||
@ -154,6 +156,32 @@ export class UserController {
|
||||
};
|
||||
}
|
||||
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@Delete('')
|
||||
@ApiOperation({
|
||||
summary: ControllerRoute.USER.ACTIONS.DELETE_USER_PROFILE_SUMMARY,
|
||||
description: ControllerRoute.USER.ACTIONS.DELETE_USER_PROFILE_DESCRIPTION,
|
||||
})
|
||||
async deleteUserProfile(@Req() req: Request) {
|
||||
const userUuid = req['user']?.userUuid;
|
||||
const userRole = req['user']?.role;
|
||||
if (!userUuid || (userRole && userRole == RoleType.SUPER_ADMIN)) {
|
||||
throw {
|
||||
statusCode: HttpStatus.UNAUTHORIZED,
|
||||
message: 'Unauthorized',
|
||||
};
|
||||
}
|
||||
await this.userService.deleteUserProfile(userUuid);
|
||||
return {
|
||||
statusCode: HttpStatus.OK,
|
||||
data: {
|
||||
userId: userUuid,
|
||||
},
|
||||
message: 'User deleted successfully',
|
||||
};
|
||||
}
|
||||
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@Patch('agreements/web/:userUuid')
|
||||
|
@ -1,21 +1,21 @@
|
||||
import {
|
||||
UpdateNameDto,
|
||||
UpdateProfilePictureDataDto,
|
||||
UpdateRegionDataDto,
|
||||
UpdateTimezoneDataDto,
|
||||
} from './../dtos/update.user.dto';
|
||||
import { SuccessResponseDto } from '@app/common/dto/success.response.dto';
|
||||
import { removeBase64Prefix } from '@app/common/helper/removeBase64Prefix';
|
||||
import { RegionRepository } from '@app/common/modules/region/repositories';
|
||||
import { TimeZoneRepository } from '@app/common/modules/timezone/repositories';
|
||||
import { UserEntity } from '@app/common/modules/user/entities';
|
||||
import { UserRepository } from '@app/common/modules/user/repositories';
|
||||
import {
|
||||
BadRequestException,
|
||||
HttpException,
|
||||
HttpStatus,
|
||||
Injectable,
|
||||
} from '@nestjs/common';
|
||||
import { UserRepository } from '@app/common/modules/user/repositories';
|
||||
import { RegionRepository } from '@app/common/modules/region/repositories';
|
||||
import { TimeZoneRepository } from '@app/common/modules/timezone/repositories';
|
||||
import { removeBase64Prefix } from '@app/common/helper/removeBase64Prefix';
|
||||
import { UserEntity } from '@app/common/modules/user/entities';
|
||||
import { SuccessResponseDto } from '@app/common/dto/success.response.dto';
|
||||
import {
|
||||
UpdateNameDto,
|
||||
UpdateProfilePictureDataDto,
|
||||
UpdateRegionDataDto,
|
||||
UpdateTimezoneDataDto,
|
||||
} from './../dtos/update.user.dto';
|
||||
|
||||
@Injectable()
|
||||
export class UserService {
|
||||
@ -269,4 +269,12 @@ export class UserService {
|
||||
}
|
||||
return await this.userRepository.update({ uuid }, { isActive: false });
|
||||
}
|
||||
|
||||
async deleteUserProfile(uuid: string) {
|
||||
const user = await this.findOneById(uuid);
|
||||
if (!user) {
|
||||
throw new BadRequestException('User not found');
|
||||
}
|
||||
return this.userRepository.delete({ uuid });
|
||||
}
|
||||
}
|
||||
|
@ -1,39 +1,39 @@
|
||||
import { VisitorPasswordRepository } from './../../../libs/common/src/modules/visitor-password/repositories/visitor-password.repository';
|
||||
import { ProductType } from '@app/common/constants/product-type.enum';
|
||||
import { DeviceRepository } from '@app/common/modules/device/repositories';
|
||||
import {
|
||||
Injectable,
|
||||
BadRequestException,
|
||||
HttpException,
|
||||
HttpStatus,
|
||||
BadRequestException,
|
||||
Injectable,
|
||||
} from '@nestjs/common';
|
||||
import { TuyaContext } from '@tuya/tuya-connector-nodejs';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { TuyaContext } from '@tuya/tuya-connector-nodejs';
|
||||
import {
|
||||
addDeviceObjectInterface,
|
||||
createTickInterface,
|
||||
} from '../interfaces/visitor-password.interface';
|
||||
import { DeviceRepository } from '@app/common/modules/device/repositories';
|
||||
import { ProductType } from '@app/common/constants/product-type.enum';
|
||||
import { VisitorPasswordRepository } from './../../../libs/common/src/modules/visitor-password/repositories/visitor-password.repository';
|
||||
|
||||
import { AddDoorLockTemporaryPasswordDto } from '../dtos';
|
||||
import { EmailService } from '@app/common/util/email.service';
|
||||
import { PasswordEncryptionService } from 'src/door-lock/services/encryption.services';
|
||||
import { DoorLockService } from 'src/door-lock/services';
|
||||
import { DeviceService } from 'src/device/services';
|
||||
import { DeviceStatuses } from '@app/common/constants/device-status.enum';
|
||||
import {
|
||||
DaysEnum,
|
||||
EnableDisableStatusEnum,
|
||||
} from '@app/common/constants/days.enum';
|
||||
import { PasswordType } from '@app/common/constants/password-type.enum';
|
||||
import { DeviceStatuses } from '@app/common/constants/device-status.enum';
|
||||
import {
|
||||
CommonHourMinutes,
|
||||
CommonHours,
|
||||
} from '@app/common/constants/hours-minutes.enum';
|
||||
import { ProjectRepository } from '@app/common/modules/project/repositiories';
|
||||
import { ORPHAN_SPACE_NAME } from '@app/common/constants/orphan-constant';
|
||||
import { PasswordType } from '@app/common/constants/password-type.enum';
|
||||
import { VisitorPasswordEnum } from '@app/common/constants/visitor-password.enum';
|
||||
import { SuccessResponseDto } from '@app/common/dto/success.response.dto';
|
||||
import { ProjectRepository } from '@app/common/modules/project/repositiories';
|
||||
import { EmailService } from '@app/common/util/email.service';
|
||||
import { DeviceService } from 'src/device/services';
|
||||
import { DoorLockService } from 'src/door-lock/services';
|
||||
import { PasswordEncryptionService } from 'src/door-lock/services/encryption.services';
|
||||
import { Not } from 'typeorm';
|
||||
import { ORPHAN_SPACE_NAME } from '@app/common/constants/orphan-constant';
|
||||
import { AddDoorLockTemporaryPasswordDto } from '../dtos';
|
||||
|
||||
@Injectable()
|
||||
export class VisitorPasswordService {
|
||||
@ -57,6 +57,67 @@ export class VisitorPasswordService {
|
||||
secretKey,
|
||||
});
|
||||
}
|
||||
|
||||
async getPasswords(projectUuid: string) {
|
||||
await this.validateProject(projectUuid);
|
||||
|
||||
const deviceIds = await this.deviceRepository.find({
|
||||
where: {
|
||||
productDevice: {
|
||||
prodType: ProductType.DL,
|
||||
},
|
||||
spaceDevice: {
|
||||
spaceName: Not(ORPHAN_SPACE_NAME),
|
||||
community: {
|
||||
project: {
|
||||
uuid: projectUuid,
|
||||
},
|
||||
},
|
||||
},
|
||||
isActive: true,
|
||||
},
|
||||
});
|
||||
|
||||
const data = [];
|
||||
deviceIds.forEach((deviceId) => {
|
||||
data.push(
|
||||
this.doorLockService
|
||||
.getOnlineTemporaryPasswordsOneTime(deviceId.uuid, true, false)
|
||||
.catch(() => {}),
|
||||
this.doorLockService
|
||||
.getOnlineTemporaryPasswordsOneTime(deviceId.uuid, true, true)
|
||||
.catch(() => {}),
|
||||
this.doorLockService
|
||||
.getOnlineTemporaryPasswordsMultiple(deviceId.uuid, true, false)
|
||||
.catch(() => {}),
|
||||
this.doorLockService
|
||||
.getOnlineTemporaryPasswordsMultiple(deviceId.uuid, true, true)
|
||||
.catch(() => {}),
|
||||
this.doorLockService
|
||||
.getOfflineOneTimeTemporaryPasswords(deviceId.uuid, true, false)
|
||||
.catch(() => {}),
|
||||
this.doorLockService
|
||||
.getOfflineOneTimeTemporaryPasswords(deviceId.uuid, true, true)
|
||||
.catch(() => {}),
|
||||
this.doorLockService
|
||||
.getOfflineMultipleTimeTemporaryPasswords(deviceId.uuid, true, false)
|
||||
.catch(() => {}),
|
||||
this.doorLockService
|
||||
.getOfflineMultipleTimeTemporaryPasswords(deviceId.uuid, true, true)
|
||||
.catch(() => {}),
|
||||
);
|
||||
});
|
||||
const result = (await Promise.all(data)).flat().filter((datum) => {
|
||||
return datum != null;
|
||||
});
|
||||
|
||||
return new SuccessResponseDto({
|
||||
message: 'Successfully retrieved temporary passwords',
|
||||
data: result,
|
||||
statusCode: HttpStatus.OK,
|
||||
});
|
||||
}
|
||||
|
||||
async handleTemporaryPassword(
|
||||
addDoorLockTemporaryPasswordDto: AddDoorLockTemporaryPasswordDto,
|
||||
userUuid: string,
|
||||
@ -105,7 +166,7 @@ export class VisitorPasswordService {
|
||||
statusCode: HttpStatus.CREATED,
|
||||
});
|
||||
}
|
||||
async addOfflineMultipleTimeTemporaryPassword(
|
||||
private async addOfflineMultipleTimeTemporaryPassword(
|
||||
addDoorLockOfflineMultipleDto: AddDoorLockTemporaryPasswordDto,
|
||||
userUuid: string,
|
||||
projectUuid: string,
|
||||
@ -169,6 +230,7 @@ export class VisitorPasswordService {
|
||||
success: true,
|
||||
result: createMultipleOfflinePass.result,
|
||||
deviceUuid,
|
||||
deviceName: deviceDetails.name,
|
||||
};
|
||||
} catch (error) {
|
||||
return {
|
||||
@ -231,7 +293,7 @@ export class VisitorPasswordService {
|
||||
}
|
||||
}
|
||||
|
||||
async addOfflineOneTimeTemporaryPassword(
|
||||
private async addOfflineOneTimeTemporaryPassword(
|
||||
addDoorLockOfflineOneTimeDto: AddDoorLockTemporaryPasswordDto,
|
||||
userUuid: string,
|
||||
projectUuid: string,
|
||||
@ -295,6 +357,7 @@ export class VisitorPasswordService {
|
||||
success: true,
|
||||
result: createOnceOfflinePass.result,
|
||||
deviceUuid,
|
||||
deviceName: deviceDetails.name,
|
||||
};
|
||||
} catch (error) {
|
||||
return {
|
||||
@ -357,7 +420,7 @@ export class VisitorPasswordService {
|
||||
}
|
||||
}
|
||||
|
||||
async addOfflineTemporaryPasswordTuya(
|
||||
private async addOfflineTemporaryPasswordTuya(
|
||||
doorLockUuid: string,
|
||||
type: string,
|
||||
addDoorLockOfflineMultipleDto: AddDoorLockTemporaryPasswordDto,
|
||||
@ -387,7 +450,7 @@ export class VisitorPasswordService {
|
||||
);
|
||||
}
|
||||
}
|
||||
async addOnlineTemporaryPasswordMultipleTime(
|
||||
private async addOnlineTemporaryPasswordMultipleTime(
|
||||
addDoorLockOnlineMultipleDto: AddDoorLockTemporaryPasswordDto,
|
||||
userUuid: string,
|
||||
projectUuid: string,
|
||||
@ -448,6 +511,7 @@ export class VisitorPasswordService {
|
||||
success: true,
|
||||
id: createPass.result.id,
|
||||
deviceUuid,
|
||||
deviceName: passwordData.deviceName,
|
||||
};
|
||||
} catch (error) {
|
||||
return {
|
||||
@ -508,67 +572,8 @@ export class VisitorPasswordService {
|
||||
);
|
||||
}
|
||||
}
|
||||
async getPasswords(projectUuid: string) {
|
||||
await this.validateProject(projectUuid);
|
||||
|
||||
const deviceIds = await this.deviceRepository.find({
|
||||
where: {
|
||||
productDevice: {
|
||||
prodType: ProductType.DL,
|
||||
},
|
||||
spaceDevice: {
|
||||
spaceName: Not(ORPHAN_SPACE_NAME),
|
||||
community: {
|
||||
project: {
|
||||
uuid: projectUuid,
|
||||
},
|
||||
},
|
||||
},
|
||||
isActive: true,
|
||||
},
|
||||
});
|
||||
|
||||
const data = [];
|
||||
deviceIds.forEach((deviceId) => {
|
||||
data.push(
|
||||
this.doorLockService
|
||||
.getOnlineTemporaryPasswordsOneTime(deviceId.uuid, true, false)
|
||||
.catch(() => {}),
|
||||
this.doorLockService
|
||||
.getOnlineTemporaryPasswordsOneTime(deviceId.uuid, true, true)
|
||||
.catch(() => {}),
|
||||
this.doorLockService
|
||||
.getOnlineTemporaryPasswordsMultiple(deviceId.uuid, true, false)
|
||||
.catch(() => {}),
|
||||
this.doorLockService
|
||||
.getOnlineTemporaryPasswordsMultiple(deviceId.uuid, true, true)
|
||||
.catch(() => {}),
|
||||
this.doorLockService
|
||||
.getOfflineOneTimeTemporaryPasswords(deviceId.uuid, true, false)
|
||||
.catch(() => {}),
|
||||
this.doorLockService
|
||||
.getOfflineOneTimeTemporaryPasswords(deviceId.uuid, true, true)
|
||||
.catch(() => {}),
|
||||
this.doorLockService
|
||||
.getOfflineMultipleTimeTemporaryPasswords(deviceId.uuid, true, false)
|
||||
.catch(() => {}),
|
||||
this.doorLockService
|
||||
.getOfflineMultipleTimeTemporaryPasswords(deviceId.uuid, true, true)
|
||||
.catch(() => {}),
|
||||
);
|
||||
});
|
||||
const result = (await Promise.all(data)).flat().filter((datum) => {
|
||||
return datum != null;
|
||||
});
|
||||
|
||||
return new SuccessResponseDto({
|
||||
message: 'Successfully retrieved temporary passwords',
|
||||
data: result,
|
||||
statusCode: HttpStatus.OK,
|
||||
});
|
||||
}
|
||||
|
||||
async addOnlineTemporaryPasswordOneTime(
|
||||
private async addOnlineTemporaryPasswordOneTime(
|
||||
addDoorLockOnlineOneTimeDto: AddDoorLockTemporaryPasswordDto,
|
||||
userUuid: string,
|
||||
projectUuid: string,
|
||||
@ -627,6 +632,7 @@ export class VisitorPasswordService {
|
||||
return {
|
||||
success: true,
|
||||
id: createPass.result.id,
|
||||
deviceName: passwordData.deviceName,
|
||||
deviceUuid,
|
||||
};
|
||||
} catch (error) {
|
||||
@ -688,7 +694,7 @@ export class VisitorPasswordService {
|
||||
);
|
||||
}
|
||||
}
|
||||
async getTicketAndEncryptedPassword(
|
||||
private async getTicketAndEncryptedPassword(
|
||||
doorLockUuid: string,
|
||||
passwordPlan: string,
|
||||
projectUuid: string,
|
||||
@ -725,6 +731,7 @@ export class VisitorPasswordService {
|
||||
ticketKey: ticketDetails.result.ticket_key,
|
||||
encryptedPassword: decrypted,
|
||||
deviceTuyaUuid: deviceDetails.deviceTuyaUuid,
|
||||
deviceName: deviceDetails.name,
|
||||
};
|
||||
} catch (error) {
|
||||
throw new HttpException(
|
||||
@ -734,7 +741,7 @@ export class VisitorPasswordService {
|
||||
}
|
||||
}
|
||||
|
||||
async createDoorLockTicketTuya(
|
||||
private async createDoorLockTicketTuya(
|
||||
deviceUuid: string,
|
||||
): Promise<createTickInterface> {
|
||||
try {
|
||||
@ -753,7 +760,7 @@ export class VisitorPasswordService {
|
||||
}
|
||||
}
|
||||
|
||||
async addOnlineTemporaryPasswordMultipleTuya(
|
||||
private async addOnlineTemporaryPasswordMultipleTuya(
|
||||
addDeviceObj: addDeviceObjectInterface,
|
||||
doorLockUuid: string,
|
||||
): Promise<createTickInterface> {
|
||||
@ -795,7 +802,7 @@ export class VisitorPasswordService {
|
||||
}
|
||||
}
|
||||
|
||||
getWorkingDayValue(days) {
|
||||
private getWorkingDayValue(days) {
|
||||
// Array representing the days of the week
|
||||
const weekDays = [
|
||||
DaysEnum.SAT,
|
||||
@ -827,36 +834,7 @@ export class VisitorPasswordService {
|
||||
|
||||
return workingDayValue;
|
||||
}
|
||||
getDaysFromWorkingDayValue(workingDayValue) {
|
||||
// Array representing the days of the week
|
||||
const weekDays = [
|
||||
DaysEnum.SAT,
|
||||
DaysEnum.FRI,
|
||||
DaysEnum.THU,
|
||||
DaysEnum.WED,
|
||||
DaysEnum.TUE,
|
||||
DaysEnum.MON,
|
||||
DaysEnum.SUN,
|
||||
];
|
||||
|
||||
// Convert the integer to a binary string and pad with leading zeros to ensure 7 bits
|
||||
const binaryString = workingDayValue
|
||||
.toString(2)
|
||||
.padStart(7, EnableDisableStatusEnum.DISABLED);
|
||||
|
||||
// Initialize an array to hold the days of the week
|
||||
const days = [];
|
||||
|
||||
// Iterate through the binary string and weekDays array
|
||||
for (let i = 0; i < binaryString.length; i++) {
|
||||
if (binaryString[i] === EnableDisableStatusEnum.ENABLED) {
|
||||
days.push(weekDays[i]);
|
||||
}
|
||||
}
|
||||
|
||||
return days;
|
||||
}
|
||||
timeToMinutes(timeStr) {
|
||||
private timeToMinutes(timeStr) {
|
||||
try {
|
||||
// Special case for "24:00"
|
||||
if (timeStr === CommonHours.TWENTY_FOUR) {
|
||||
@ -883,38 +861,7 @@ export class VisitorPasswordService {
|
||||
throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR);
|
||||
}
|
||||
}
|
||||
minutesToTime(totalMinutes) {
|
||||
try {
|
||||
if (
|
||||
typeof totalMinutes !== 'number' ||
|
||||
totalMinutes < 0 ||
|
||||
totalMinutes > CommonHourMinutes.TWENTY_FOUR
|
||||
) {
|
||||
throw new Error('Invalid minutes value');
|
||||
}
|
||||
|
||||
if (totalMinutes === CommonHourMinutes.TWENTY_FOUR) {
|
||||
return CommonHours.TWENTY_FOUR;
|
||||
}
|
||||
|
||||
const hours = Math.floor(totalMinutes / 60);
|
||||
const minutes = totalMinutes % 60;
|
||||
|
||||
const formattedHours = String(hours).padStart(
|
||||
2,
|
||||
EnableDisableStatusEnum.DISABLED,
|
||||
);
|
||||
const formattedMinutes = String(minutes).padStart(
|
||||
2,
|
||||
EnableDisableStatusEnum.DISABLED,
|
||||
);
|
||||
|
||||
return `${formattedHours}:${formattedMinutes}`;
|
||||
} catch (error) {
|
||||
throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR);
|
||||
}
|
||||
}
|
||||
async getDeviceByDeviceUuid(
|
||||
private async getDeviceByDeviceUuid(
|
||||
deviceUuid: string,
|
||||
withProductDevice: boolean = true,
|
||||
projectUuid: string,
|
||||
@ -939,7 +886,7 @@ export class VisitorPasswordService {
|
||||
throw new HttpException('Device Not Found', HttpStatus.NOT_FOUND);
|
||||
}
|
||||
}
|
||||
async addOnlineTemporaryPasswordOneTimeTuya(
|
||||
private async addOnlineTemporaryPasswordOneTimeTuya(
|
||||
addDeviceObj: addDeviceObjectInterface,
|
||||
doorLockUuid: string,
|
||||
): Promise<createTickInterface> {
|
||||
|
@ -32,6 +32,8 @@ import { SqlLoaderService } from '@app/common/helper/services/sql-loader.service
|
||||
import { OccupancyService } from '@app/common/helper/services/occupancy.service';
|
||||
import { CommunityRepository } from '@app/common/modules/community/repositories';
|
||||
import { AqiDataService } from '@app/common/helper/services/aqi.data.service';
|
||||
import { PresenceSensorDailySpaceRepository } from '@app/common/modules/presence-sensor/repositories';
|
||||
import { AqiSpaceDailyPollutantStatsRepository } from '@app/common/modules/aqi/repositories';
|
||||
@Module({
|
||||
imports: [ConfigModule, DeviceRepositoryModule, DoorLockModule],
|
||||
controllers: [VisitorPasswordController],
|
||||
@ -61,6 +63,8 @@ import { AqiDataService } from '@app/common/helper/services/aqi.data.service';
|
||||
OccupancyService,
|
||||
CommunityRepository,
|
||||
AqiDataService,
|
||||
PresenceSensorDailySpaceRepository,
|
||||
AqiSpaceDailyPollutantStatsRepository,
|
||||
],
|
||||
exports: [VisitorPasswordService],
|
||||
})
|
||||
|
Reference in New Issue
Block a user