mirror of
https://github.com/SyncrowIOT/backend.git
synced 2025-07-10 15:17:41 +00:00
Compare commits
1 Commits
refactor/a
...
fix/SP-163
Author | SHA1 | Date | |
---|---|---|---|
2b00dd0aac |
@ -15,7 +15,6 @@ export enum ProductType {
|
||||
WL = 'WL',
|
||||
GD = 'GD',
|
||||
CUR = 'CUR',
|
||||
CUR_2 = 'CUR_2',
|
||||
PC = 'PC',
|
||||
FOUR_S = '4S',
|
||||
SIX_S = '6S',
|
||||
|
@ -125,8 +125,8 @@ import { VisitorPasswordEntity } from '../modules/visitor-password/entities';
|
||||
logger: typeOrmLogger,
|
||||
extra: {
|
||||
charset: 'utf8mb4',
|
||||
max: 100, // set pool max size
|
||||
idleTimeoutMillis: 3000, // close idle clients after 5 second
|
||||
max: 50, // set pool max size
|
||||
idleTimeoutMillis: 5000, // close idle clients after 5 second
|
||||
connectionTimeoutMillis: 12_000, // return an error after 11 second if connection could not be established
|
||||
maxUses: 7500, // close (and replace) a connection after it has been used 7500 times (see below for discussion)
|
||||
},
|
||||
|
@ -3,12 +3,28 @@ 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],
|
||||
|
@ -18,6 +18,12 @@ 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;
|
||||
@ -25,6 +31,9 @@ export class DeviceStatusFirebaseService {
|
||||
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');
|
||||
@ -67,94 +76,25 @@ export class DeviceStatusFirebaseService {
|
||||
);
|
||||
}
|
||||
}
|
||||
async addBatchDeviceStatusToOurDb(
|
||||
batch: {
|
||||
deviceTuyaUuid: string;
|
||||
status: any;
|
||||
log: any;
|
||||
device: any;
|
||||
}[],
|
||||
): Promise<void> {
|
||||
const allLogs = [];
|
||||
|
||||
console.log(`🔁 Preparing logs from batch of ${batch.length} items...`);
|
||||
|
||||
for (const item of batch) {
|
||||
const device = item.device;
|
||||
if (!device?.uuid) {
|
||||
console.log(`⛔ Skipped unknown device: ${item.deviceTuyaUuid}`);
|
||||
continue;
|
||||
}
|
||||
|
||||
const logs = item.log.properties.map((property) =>
|
||||
this.deviceStatusLogRepository.create({
|
||||
deviceId: device.uuid,
|
||||
deviceTuyaId: item.deviceTuyaUuid,
|
||||
productId: item.log.productId,
|
||||
log: item.log,
|
||||
code: property.code,
|
||||
value: property.value,
|
||||
eventId: item.log.dataId,
|
||||
eventTime: new Date(property.time).toISOString(),
|
||||
}),
|
||||
);
|
||||
allLogs.push(...logs);
|
||||
}
|
||||
|
||||
console.log(`📝 Total logs to insert: ${allLogs.length}`);
|
||||
|
||||
const insertLogsPromise = (async () => {
|
||||
const chunkSize = 300;
|
||||
let insertedCount = 0;
|
||||
|
||||
for (let i = 0; i < allLogs.length; i += chunkSize) {
|
||||
const chunk = allLogs.slice(i, i + chunkSize);
|
||||
try {
|
||||
const result = await this.deviceStatusLogRepository
|
||||
.createQueryBuilder()
|
||||
.insert()
|
||||
.into('device-status-log') // or use DeviceStatusLogEntity
|
||||
.values(chunk)
|
||||
.orIgnore() // skip duplicates
|
||||
.execute();
|
||||
|
||||
insertedCount += result.identifiers.length;
|
||||
console.log(
|
||||
`✅ Inserted ${result.identifiers.length} / ${chunk.length} logs (chunk)`,
|
||||
);
|
||||
} catch (error) {
|
||||
console.error('❌ Insert error (skipped chunk):', error.message);
|
||||
}
|
||||
}
|
||||
|
||||
console.log(
|
||||
`✅ Total logs inserted: ${insertedCount} / ${allLogs.length}`,
|
||||
);
|
||||
})();
|
||||
|
||||
await insertLogsPromise;
|
||||
}
|
||||
|
||||
async addDeviceStatusToFirebase(
|
||||
addDeviceStatusDto: AddDeviceStatusDto & { device?: any },
|
||||
addDeviceStatusDto: AddDeviceStatusDto,
|
||||
): Promise<AddDeviceStatusDto | null> {
|
||||
try {
|
||||
let device = addDeviceStatusDto.device;
|
||||
if (!device) {
|
||||
device = await this.getDeviceByDeviceTuyaUuid(
|
||||
addDeviceStatusDto.deviceTuyaUuid,
|
||||
);
|
||||
}
|
||||
const 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;
|
||||
}
|
||||
}
|
||||
@ -168,15 +108,6 @@ 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);
|
||||
@ -280,6 +211,64 @@ export class DeviceStatusFirebaseService {
|
||||
return existingData;
|
||||
});
|
||||
|
||||
// Save logs to your repository
|
||||
const newLogs = addDeviceStatusDto.log.properties.map((property) => {
|
||||
return this.deviceStatusLogRepository.create({
|
||||
deviceId: addDeviceStatusDto.deviceUuid,
|
||||
deviceTuyaId: addDeviceStatusDto.deviceTuyaUuid,
|
||||
productId: addDeviceStatusDto.log.productId,
|
||||
log: addDeviceStatusDto.log,
|
||||
code: property.code,
|
||||
value: property.value,
|
||||
eventId: addDeviceStatusDto.log.dataId,
|
||||
eventTime: new Date(property.time).toISOString(),
|
||||
});
|
||||
});
|
||||
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,
|
||||
);
|
||||
}
|
||||
// Return the updated data
|
||||
const snapshot: DataSnapshot = await get(dataRef);
|
||||
return snapshot.val();
|
||||
|
@ -8,10 +8,7 @@ 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,
|
||||
DeviceRepository,
|
||||
} from '../modules/device/repositories';
|
||||
import { DeviceNotificationRepository } 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';
|
||||
@ -30,7 +27,6 @@ import { SosHandlerService } from './services/sos.handler.service';
|
||||
DeviceNotificationRepository,
|
||||
CommunityRepository,
|
||||
SosHandlerService,
|
||||
DeviceRepository,
|
||||
],
|
||||
exports: [
|
||||
HelperHashService,
|
||||
|
@ -1,63 +1,44 @@
|
||||
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(): Promise<void> {
|
||||
async updateAQISensorHistoricalData(deviceUuid: string): Promise<void> {
|
||||
try {
|
||||
const { dateStr } = this.getFormattedDates();
|
||||
const now = new Date();
|
||||
const dateStr = now.toLocaleDateString('en-CA'); // YYYY-MM-DD
|
||||
const device = await this.deviceRepository.findOne({
|
||||
where: { uuid: deviceUuid },
|
||||
relations: ['spaceDevice'],
|
||||
});
|
||||
|
||||
// Execute all procedures in parallel
|
||||
await Promise.all([
|
||||
this.executeProcedureWithRetry(
|
||||
'proceduce_update_daily_space_aqi',
|
||||
[dateStr],
|
||||
'fact_daily_space_aqi',
|
||||
),
|
||||
]);
|
||||
await this.executeProcedure(
|
||||
'fact_daily_space_aqi',
|
||||
'proceduce_update_daily_space_aqi',
|
||||
[dateStr, device.spaceDevice?.uuid],
|
||||
);
|
||||
} catch (err) {
|
||||
console.error('Failed to update AQI sensor historical data:', err);
|
||||
console.error('Failed to insert or update aqi data:', err);
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
private getFormattedDates(): { dateStr: string } {
|
||||
const now = new Date();
|
||||
return {
|
||||
dateStr: now.toLocaleDateString('en-CA'), // YYYY-MM-DD
|
||||
};
|
||||
}
|
||||
private async executeProcedureWithRetry(
|
||||
|
||||
private async executeProcedure(
|
||||
procedureFolderName: string,
|
||||
procedureFileName: string,
|
||||
params: (string | number | null)[],
|
||||
folderName: string,
|
||||
retries = 3,
|
||||
): Promise<void> {
|
||||
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;
|
||||
}
|
||||
const query = this.loadQuery(procedureFolderName, procedureFileName);
|
||||
await this.dataSource.query(query, params);
|
||||
console.log(`Procedure ${procedureFileName} executed successfully.`);
|
||||
}
|
||||
|
||||
private loadQuery(folderName: string, fileName: string): string {
|
||||
|
@ -1,69 +1,66 @@
|
||||
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 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 update occupancy data:', err);
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
private getFormattedDates(): { dateStr: string } {
|
||||
const now = new Date();
|
||||
return {
|
||||
dateStr: now.toLocaleDateString('en-CA'), // YYYY-MM-DD
|
||||
};
|
||||
}
|
||||
private async executeProcedureWithRetry(
|
||||
procedureFileName: string,
|
||||
params: (string | number | null)[],
|
||||
folderName: string,
|
||||
retries = 3,
|
||||
async updateOccupancySensorHistoricalDurationData(
|
||||
deviceUuid: string,
|
||||
): Promise<void> {
|
||||
try {
|
||||
const query = this.loadQuery(folderName, procedureFileName);
|
||||
await this.dataSource.query(query, params);
|
||||
console.log(`Procedure ${procedureFileName} executed successfully.`);
|
||||
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],
|
||||
);
|
||||
} 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);
|
||||
console.error('Failed to insert or update occupancy duration 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 async executeProcedure(
|
||||
procedureFolderName: string,
|
||||
procedureFileName: string,
|
||||
params: (string | number | null)[],
|
||||
): Promise<void> {
|
||||
const query = this.loadQuery(procedureFolderName, procedureFileName);
|
||||
await this.dataSource.query(query, params);
|
||||
console.log(`Procedure ${procedureFileName} executed successfully.`);
|
||||
}
|
||||
|
||||
private loadQuery(folderName: string, fileName: string): string {
|
||||
return this.sqlLoader.loadQuery(folderName, fileName, SQL_PROCEDURES_PATH);
|
||||
|
@ -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,74 +10,50 @@ export class PowerClampService {
|
||||
private readonly dataSource: DataSource,
|
||||
) {}
|
||||
|
||||
async updateEnergyConsumedHistoricalData(): Promise<void> {
|
||||
async updateEnergyConsumedHistoricalData(deviceUuid: string): Promise<void> {
|
||||
try {
|
||||
const { dateStr, monthYear } = this.getFormattedDates();
|
||||
|
||||
// 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 update energy consumption data:', err);
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
private getFormattedDates(): { dateStr: string; monthYear: string } {
|
||||
const now = new Date();
|
||||
return {
|
||||
dateStr: now.toLocaleDateString('en-CA'), // YYYY-MM-DD
|
||||
monthYear: now
|
||||
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
|
||||
};
|
||||
}
|
||||
.replace('/', '-'); // MM-YYYY
|
||||
|
||||
private async executeProcedureWithRetry(
|
||||
procedureFileName: string,
|
||||
params: (string | number | null)[],
|
||||
folderName: string,
|
||||
retries = 3,
|
||||
): Promise<void> {
|
||||
try {
|
||||
const query = this.loadQuery(folderName, procedureFileName);
|
||||
await this.dataSource.query(query, params);
|
||||
console.log(`Procedure ${procedureFileName} executed successfully.`);
|
||||
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],
|
||||
);
|
||||
} 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);
|
||||
console.error('Failed to insert or update energy data:', err);
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
private async executeProcedure(
|
||||
procedureFileName: string,
|
||||
params: (string | number | null)[],
|
||||
): Promise<void> {
|
||||
const query = this.loadQuery(
|
||||
'fact_device_energy_consumed',
|
||||
procedureFileName,
|
||||
);
|
||||
await this.dataSource.query(query, params);
|
||||
console.log(`Procedure ${procedureFileName} executed successfully.`);
|
||||
}
|
||||
|
||||
private loadQuery(folderName: string, fileName: string): string {
|
||||
return this.sqlLoader.loadQuery(folderName, fileName, SQL_PROCEDURES_PATH);
|
||||
}
|
||||
|
@ -16,46 +16,21 @@ export class SosHandlerService {
|
||||
);
|
||||
}
|
||||
|
||||
async handleSosEventFirebase(device: any, logData: any): Promise<void> {
|
||||
const sosTrueStatus = [{ code: 'sos', value: true }];
|
||||
const sosFalseStatus = [{ code: 'sos', value: false }];
|
||||
|
||||
async handleSosEvent(devId: string, logData: any): Promise<void> {
|
||||
try {
|
||||
// ✅ Send true status
|
||||
await this.deviceStatusFirebaseService.addDeviceStatusToFirebase({
|
||||
deviceTuyaUuid: device.deviceTuyaUuid,
|
||||
status: sosTrueStatus,
|
||||
deviceTuyaUuid: devId,
|
||||
status: [{ code: 'sos', value: true }],
|
||||
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: device.deviceTuyaUuid,
|
||||
status: sosFalseStatus,
|
||||
deviceTuyaUuid: devId,
|
||||
status: [{ code: 'sos', value: false }],
|
||||
log: logData,
|
||||
device,
|
||||
});
|
||||
|
||||
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,24 +1,13 @@
|
||||
import { Injectable, OnModuleInit } from '@nestjs/common';
|
||||
import { Injectable } 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 implements OnModuleInit {
|
||||
export class TuyaWebSocketService {
|
||||
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;
|
||||
|
||||
constructor(
|
||||
private readonly configService: ConfigService,
|
||||
@ -37,36 +26,16 @@ export class TuyaWebSocketService implements OnModuleInit {
|
||||
});
|
||||
|
||||
if (this.configService.get<string>('tuya-config.TRUN_ON_TUYA_SOCKET')) {
|
||||
// Set up event handlers
|
||||
this.setupEventHandlers();
|
||||
|
||||
// Start receiving messages
|
||||
this.client.start();
|
||||
}
|
||||
|
||||
// Run the queue processor every 15 seconds
|
||||
setInterval(() => this.processQueue(), 15000);
|
||||
|
||||
// Refresh the cache every 1 hour
|
||||
setInterval(() => this.initializeDeviceCache(), 30 * 60 * 1000); // 30 minutes
|
||||
}
|
||||
|
||||
async onModuleInit() {
|
||||
await this.initializeDeviceCache();
|
||||
}
|
||||
|
||||
private async initializeDeviceCache() {
|
||||
try {
|
||||
const allDevices = await this.deviceStatusFirebaseService.getAllDevices();
|
||||
allDevices.forEach((device) => {
|
||||
if (device.deviceTuyaUuid) {
|
||||
this.deviceCache.set(device.deviceTuyaUuid, device);
|
||||
}
|
||||
});
|
||||
console.log(`✅ Refreshed cache with ${allDevices.length} devices.`);
|
||||
} catch (error) {
|
||||
console.error('❌ Failed to initialize device cache:', error);
|
||||
}
|
||||
}
|
||||
|
||||
private setupEventHandlers() {
|
||||
// Event handlers
|
||||
this.client.open(() => {
|
||||
console.log('open');
|
||||
});
|
||||
@ -74,38 +43,23 @@ export class TuyaWebSocketService implements OnModuleInit {
|
||||
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);
|
||||
await this.sosHandlerService.handleSosEvent(devId, logData);
|
||||
} else {
|
||||
await this.deviceStatusFirebaseService.addDeviceStatusToFirebase({
|
||||
deviceTuyaUuid: devId,
|
||||
status,
|
||||
status: status,
|
||||
log: logData,
|
||||
device,
|
||||
});
|
||||
}
|
||||
|
||||
// Push to internal queue
|
||||
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 processing message:', error);
|
||||
}
|
||||
});
|
||||
|
||||
this.client.reconnect(() => {
|
||||
console.log('reconnect');
|
||||
});
|
||||
@ -126,37 +80,6 @@ export class TuyaWebSocketService implements OnModuleInit {
|
||||
console.error('WebSocket error:', error);
|
||||
});
|
||||
}
|
||||
private async processQueue() {
|
||||
if (this.isProcessing) {
|
||||
console.log('⏳ Skipping: still processing previous batch');
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.messageQueue.length === 0) return;
|
||||
|
||||
this.isProcessing = true;
|
||||
const batch = [...this.messageQueue];
|
||||
this.messageQueue = [];
|
||||
|
||||
console.log(`🔁 Processing batch of size: ${batch.length}`);
|
||||
|
||||
try {
|
||||
await this.deviceStatusFirebaseService.addBatchDeviceStatusToOurDb(
|
||||
batch.map((item) => ({
|
||||
deviceTuyaUuid: item.devId,
|
||||
status: item.status,
|
||||
log: item.logData,
|
||||
device: item.device,
|
||||
})),
|
||||
);
|
||||
} catch (error) {
|
||||
console.error('❌ Error processing batch:', error);
|
||||
this.messageQueue.unshift(...batch); // retry
|
||||
} finally {
|
||||
this.isProcessing = false;
|
||||
}
|
||||
}
|
||||
|
||||
private extractMessageData(message: any): {
|
||||
devId: string;
|
||||
status: any;
|
||||
|
@ -1,6 +1,7 @@
|
||||
WITH params AS (
|
||||
SELECT
|
||||
TO_DATE(NULLIF($1, ''), 'YYYY-MM-DD') AS event_date
|
||||
TO_DATE(NULLIF($1, ''), 'YYYY-MM-DD') AS event_date,
|
||||
$2::uuid AS space_id
|
||||
),
|
||||
|
||||
-- Query Pipeline Starts Here
|
||||
@ -276,10 +277,7 @@ 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
|
||||
JOIN params
|
||||
ON params.event_date = a.event_date
|
||||
ON p.space_id = a.space_id AND p.event_date = a.event_date
|
||||
ORDER BY p.space_id, p.event_date)
|
||||
|
||||
|
||||
|
@ -1,6 +1,7 @@
|
||||
WITH params AS (
|
||||
SELECT
|
||||
TO_DATE(NULLIF($1, ''), 'YYYY-MM-DD') AS event_date
|
||||
TO_DATE(NULLIF($1, ''), 'YYYY-MM-DD') AS event_date,
|
||||
$2::uuid AS space_id
|
||||
),
|
||||
|
||||
presence_logs AS (
|
||||
@ -85,7 +86,8 @@ 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.event_date = s.event_date
|
||||
ON p.space_id = s.space_id
|
||||
AND p.event_date = s.event_date
|
||||
)
|
||||
|
||||
INSERT INTO public."space-daily-occupancy-duration" (
|
||||
|
@ -1,6 +1,7 @@
|
||||
WITH params AS (
|
||||
SELECT
|
||||
$1::date AS target_date
|
||||
$1::uuid AS device_id,
|
||||
$2::date AS target_date
|
||||
),
|
||||
total_energy AS (
|
||||
SELECT
|
||||
@ -13,7 +14,8 @@ total_energy AS (
|
||||
MAX(log.value)::integer AS max_value
|
||||
FROM "device-status-log" log, params
|
||||
WHERE log.code = 'EnergyConsumed'
|
||||
AND log.event_time::date = params.target_date
|
||||
AND log.device_id = params.device_id
|
||||
AND log.event_time::date = params.target_date
|
||||
GROUP BY 1,2,3,4,5
|
||||
),
|
||||
energy_phase_A AS (
|
||||
@ -27,7 +29,8 @@ energy_phase_A AS (
|
||||
MAX(log.value)::integer AS max_value
|
||||
FROM "device-status-log" log, params
|
||||
WHERE log.code = 'EnergyConsumedA'
|
||||
AND log.event_time::date = params.target_date
|
||||
AND log.device_id = params.device_id
|
||||
AND log.event_time::date = params.target_date
|
||||
GROUP BY 1,2,3,4,5
|
||||
),
|
||||
energy_phase_B AS (
|
||||
@ -41,7 +44,8 @@ energy_phase_B AS (
|
||||
MAX(log.value)::integer AS max_value
|
||||
FROM "device-status-log" log, params
|
||||
WHERE log.code = 'EnergyConsumedB'
|
||||
AND log.event_time::date = params.target_date
|
||||
AND log.device_id = params.device_id
|
||||
AND log.event_time::date = params.target_date
|
||||
GROUP BY 1,2,3,4,5
|
||||
),
|
||||
energy_phase_C AS (
|
||||
@ -55,7 +59,8 @@ energy_phase_C AS (
|
||||
MAX(log.value)::integer AS max_value
|
||||
FROM "device-status-log" log, params
|
||||
WHERE log.code = 'EnergyConsumedC'
|
||||
AND log.event_time::date = params.target_date
|
||||
AND log.device_id = params.device_id
|
||||
AND log.event_time::date = params.target_date
|
||||
GROUP BY 1,2,3,4,5
|
||||
),
|
||||
final_data AS (
|
||||
|
@ -1,6 +1,8 @@
|
||||
WITH params AS (
|
||||
SELECT
|
||||
$1::date AS target_date
|
||||
$1::uuid AS device_id,
|
||||
$2::date AS target_date,
|
||||
$3::text AS target_hour
|
||||
),
|
||||
total_energy AS (
|
||||
SELECT
|
||||
@ -13,7 +15,9 @@ 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 (
|
||||
@ -27,7 +31,9 @@ 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 (
|
||||
@ -41,7 +47,9 @@ 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 (
|
||||
@ -55,7 +63,9 @@ 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,6 +1,7 @@
|
||||
WITH params AS (
|
||||
SELECT
|
||||
$1::text AS target_month -- Format should match 'MM-YYYY'
|
||||
$1::uuid AS device_id,
|
||||
$2::text AS target_month -- Format should match 'MM-YYYY'
|
||||
),
|
||||
total_energy AS (
|
||||
SELECT
|
||||
@ -13,6 +14,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 TO_CHAR(log.event_time, 'MM-YYYY') = params.target_month
|
||||
GROUP BY 1,2,3,4,5
|
||||
),
|
||||
@ -27,6 +29,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 TO_CHAR(log.event_time, 'MM-YYYY') = params.target_month
|
||||
GROUP BY 1,2,3,4,5
|
||||
),
|
||||
@ -41,6 +44,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 TO_CHAR(log.event_time, 'MM-YYYY') = params.target_month
|
||||
GROUP BY 1,2,3,4,5
|
||||
),
|
||||
@ -55,6 +59,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 TO_CHAR(log.event_time, 'MM-YYYY') = params.target_month
|
||||
GROUP BY 1,2,3,4,5
|
||||
),
|
||||
|
@ -1,6 +1,7 @@
|
||||
WITH params AS (
|
||||
SELECT
|
||||
TO_DATE(NULLIF($1, ''), 'YYYY-MM-DD') AS event_date
|
||||
TO_DATE(NULLIF($1, ''), 'YYYY-MM-DD') AS event_date,
|
||||
$2::uuid AS space_id
|
||||
),
|
||||
|
||||
device_logs AS (
|
||||
@ -86,7 +87,8 @@ SELECT summary.space_id,
|
||||
count_total_presence_detected
|
||||
FROM summary
|
||||
JOIN params P ON true
|
||||
where (P.event_date IS NULL or summary.event_date::date = P.event_date)
|
||||
where summary.space_id = P.space_id
|
||||
and (P.event_date IS NULL or summary.event_date::date = P.event_date)
|
||||
ORDER BY space_id, event_date)
|
||||
|
||||
|
||||
|
64
package-lock.json
generated
64
package-lock.json
generated
@ -18,7 +18,6 @@
|
||||
"@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",
|
||||
@ -39,7 +38,6 @@
|
||||
"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",
|
||||
@ -2540,19 +2538,6 @@
|
||||
"@nestjs/core": "^10.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@nestjs/schedule": {
|
||||
"version": "6.0.0",
|
||||
"resolved": "https://registry.npmjs.org/@nestjs/schedule/-/schedule-6.0.0.tgz",
|
||||
"integrity": "sha512-aQySMw6tw2nhitELXd3EiRacQRgzUKD9mFcUZVOJ7jPLqIBvXOyvRWLsK9SdurGA+jjziAlMef7iB5ZEFFoQpw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"cron": "4.3.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@nestjs/common": "^10.0.0 || ^11.0.0",
|
||||
"@nestjs/core": "^10.0.0 || ^11.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@nestjs/schematics": {
|
||||
"version": "10.2.3",
|
||||
"resolved": "https://registry.npmjs.org/@nestjs/schematics/-/schematics-10.2.3.tgz",
|
||||
@ -3230,12 +3215,6 @@
|
||||
"@types/node": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/luxon": {
|
||||
"version": "3.6.2",
|
||||
"resolved": "https://registry.npmjs.org/@types/luxon/-/luxon-3.6.2.tgz",
|
||||
"integrity": "sha512-R/BdP7OxEMc44l2Ex5lSXHoIXTB2JLNa3y2QISIbr58U/YcsffyQrYW//hZSdrfxrjRZj3GcUoxMPGdO8gSYuw==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/methods": {
|
||||
"version": "1.1.4",
|
||||
"resolved": "https://registry.npmjs.org/@types/methods/-/methods-1.1.4.tgz",
|
||||
@ -5447,19 +5426,6 @@
|
||||
"devOptional": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/cron": {
|
||||
"version": "4.3.0",
|
||||
"resolved": "https://registry.npmjs.org/cron/-/cron-4.3.0.tgz",
|
||||
"integrity": "sha512-ciiYNLfSlF9MrDqnbMdRWFiA6oizSF7kA1osPP9lRzNu0Uu+AWog1UKy7SkckiDY2irrNjeO6qLyKnXC8oxmrw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@types/luxon": "~3.6.0",
|
||||
"luxon": "~3.6.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18.x"
|
||||
}
|
||||
},
|
||||
"node_modules/cross-spawn": {
|
||||
"version": "7.0.6",
|
||||
"resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz",
|
||||
@ -9811,15 +9777,6 @@
|
||||
"yallist": "^3.0.2"
|
||||
}
|
||||
},
|
||||
"node_modules/luxon": {
|
||||
"version": "3.6.1",
|
||||
"resolved": "https://registry.npmjs.org/luxon/-/luxon-3.6.1.tgz",
|
||||
"integrity": "sha512-tJLxrKJhO2ukZ5z0gyjY1zPh3Rh88Ej9P7jNrZiHMUXHae1yvI2imgOZtL1TO8TW6biMMKfTtAOoEJANgtWBMQ==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/magic-string": {
|
||||
"version": "0.30.8",
|
||||
"resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.8.tgz",
|
||||
@ -10185,27 +10142,6 @@
|
||||
"node": "^18 || ^20 || >= 21"
|
||||
}
|
||||
},
|
||||
"node_modules/node-cache": {
|
||||
"version": "5.1.2",
|
||||
"resolved": "https://registry.npmjs.org/node-cache/-/node-cache-5.1.2.tgz",
|
||||
"integrity": "sha512-t1QzWwnk4sjLWaQAS8CHgOJ+RAfmHpxFWmc36IWTiWHQfs0w5JDMBS1b1ZxQteo0vVVuWJvIUKHDkkeK7vIGCg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"clone": "2.x"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 8.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/node-cache/node_modules/clone": {
|
||||
"version": "2.1.2",
|
||||
"resolved": "https://registry.npmjs.org/clone/-/clone-2.1.2.tgz",
|
||||
"integrity": "sha512-3Pe/CF1Nn94hyhIYpjtiLhdCoEoz0DqQ+988E9gmeEdQZlojxnOb74wctFyuwWQHzqyf9X7C7MG8juUpqBJT8w==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=0.8"
|
||||
}
|
||||
},
|
||||
"node_modules/node-emoji": {
|
||||
"version": "1.11.0",
|
||||
"resolved": "https://registry.npmjs.org/node-emoji/-/node-emoji-1.11.0.tgz",
|
||||
|
@ -30,7 +30,6 @@
|
||||
"@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",
|
||||
@ -51,7 +50,6 @@
|
||||
"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",
|
||||
|
@ -1,7 +1,7 @@
|
||||
import { SeederModule } from '@app/common/seed/seeder.module';
|
||||
import { Module } from '@nestjs/common';
|
||||
import { ConfigModule } from '@nestjs/config';
|
||||
import { APP_GUARD, APP_INTERCEPTOR } from '@nestjs/core';
|
||||
import { APP_INTERCEPTOR } from '@nestjs/core';
|
||||
import { WinstonModule } from 'nest-winston';
|
||||
import { AuthenticationModule } from './auth/auth.module';
|
||||
import { AutomationModule } from './automation/automation.module';
|
||||
@ -35,32 +35,18 @@ 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';
|
||||
@Module({
|
||||
imports: [
|
||||
ConfigModule.forRoot({
|
||||
load: config,
|
||||
}),
|
||||
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;
|
||||
},
|
||||
}),
|
||||
/* ThrottlerModule.forRoot({
|
||||
throttlers: [{ ttl: 100000, limit: 30 }],
|
||||
}), */
|
||||
WinstonModule.forRoot(winstonLoggerOptions),
|
||||
ClientModule,
|
||||
AuthenticationModule,
|
||||
@ -96,18 +82,16 @@ import { SchedulerModule } from './scheduler/scheduler.module';
|
||||
OccupancyModule,
|
||||
WeatherModule,
|
||||
AqiModule,
|
||||
SchedulerModule,
|
||||
NestScheduleModule.forRoot(),
|
||||
],
|
||||
providers: [
|
||||
{
|
||||
provide: APP_INTERCEPTOR,
|
||||
useClass: LoggingInterceptor,
|
||||
},
|
||||
{
|
||||
/* {
|
||||
provide: APP_GUARD,
|
||||
useClass: ThrottlerGuard,
|
||||
},
|
||||
}, */
|
||||
],
|
||||
})
|
||||
export class AppModule {}
|
||||
|
@ -30,8 +30,6 @@ import { PowerClampService } from '@app/common/helper/services/power.clamp.servi
|
||||
import { SqlLoaderService } from '@app/common/helper/services/sql-loader.service';
|
||||
import { 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],
|
||||
@ -61,8 +59,6 @@ import { AqiSpaceDailyPollutantStatsRepository } from '@app/common/modules/aqi/r
|
||||
SqlLoaderService,
|
||||
OccupancyService,
|
||||
AqiDataService,
|
||||
PresenceSensorDailySpaceRepository,
|
||||
AqiSpaceDailyPollutantStatsRepository,
|
||||
],
|
||||
exports: [],
|
||||
})
|
||||
|
@ -64,8 +64,6 @@ 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],
|
||||
@ -120,8 +118,6 @@ import { AqiSpaceDailyPollutantStatsRepository } from '@app/common/modules/aqi/r
|
||||
SqlLoaderService,
|
||||
OccupancyService,
|
||||
AqiDataService,
|
||||
PresenceSensorDailySpaceRepository,
|
||||
AqiSpaceDailyPollutantStatsRepository,
|
||||
],
|
||||
exports: [CommunityService, SpacePermissionService],
|
||||
})
|
||||
|
@ -1,28 +0,0 @@
|
||||
interface BaseCommand {
|
||||
code: string;
|
||||
value: any;
|
||||
}
|
||||
export interface ControlCur2Command extends BaseCommand {
|
||||
code: 'control';
|
||||
value: 'open' | 'close' | 'stop';
|
||||
}
|
||||
export interface ControlCur2PercentCommand extends BaseCommand {
|
||||
code: 'percent_control';
|
||||
value: 10 | 20 | 30 | 40 | 50 | 60 | 70 | 80 | 90 | 100;
|
||||
}
|
||||
export interface ControlCur2AccurateCalibrationCommand extends BaseCommand {
|
||||
code: 'accurate_calibration';
|
||||
value: 'start' | 'end'; // Assuming this is a numeric value for calibration
|
||||
}
|
||||
export interface ControlCur2TDirectionConCommand extends BaseCommand {
|
||||
code: 'control_t_direction_con';
|
||||
value: 'forward' | 'back';
|
||||
}
|
||||
export interface ControlCur2QuickCalibrationCommand extends BaseCommand {
|
||||
code: 'tr_timecon';
|
||||
value: number; // between 10 and 120
|
||||
}
|
||||
export interface ControlCur2MotorModeCommand extends BaseCommand {
|
||||
code: 'elec_machinery_mode';
|
||||
value: 'strong_power' | 'dry_contact';
|
||||
}
|
@ -30,8 +30,6 @@ 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],
|
||||
@ -60,8 +58,6 @@ import { AqiSpaceDailyPollutantStatsRepository } from '@app/common/modules/aqi/r
|
||||
OccupancyService,
|
||||
CommunityRepository,
|
||||
AqiDataService,
|
||||
PresenceSensorDailySpaceRepository,
|
||||
AqiSpaceDailyPollutantStatsRepository,
|
||||
],
|
||||
exports: [DoorLockService],
|
||||
})
|
||||
|
@ -28,8 +28,6 @@ import { SqlLoaderService } from '@app/common/helper/services/sql-loader.service
|
||||
import { OccupancyService } from '@app/common/helper/services/occupancy.service';
|
||||
import { 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],
|
||||
@ -57,8 +55,6 @@ import { AqiSpaceDailyPollutantStatsRepository } from '@app/common/modules/aqi/r
|
||||
OccupancyService,
|
||||
CommunityRepository,
|
||||
AqiDataService,
|
||||
PresenceSensorDailySpaceRepository,
|
||||
AqiSpaceDailyPollutantStatsRepository,
|
||||
],
|
||||
exports: [GroupService],
|
||||
})
|
||||
|
@ -82,8 +82,6 @@ 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],
|
||||
@ -152,8 +150,6 @@ import { AqiSpaceDailyPollutantStatsRepository } from '@app/common/modules/aqi/r
|
||||
SqlLoaderService,
|
||||
OccupancyService,
|
||||
AqiDataService,
|
||||
PresenceSensorDailySpaceRepository,
|
||||
AqiSpaceDailyPollutantStatsRepository,
|
||||
],
|
||||
exports: [InviteUserService],
|
||||
})
|
||||
|
15
src/main.ts
15
src/main.ts
@ -3,6 +3,7 @@ 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';
|
||||
@ -21,6 +22,20 @@ 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,
|
||||
|
@ -60,8 +60,6 @@ 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],
|
||||
@ -111,8 +109,6 @@ import { AqiSpaceDailyPollutantStatsRepository } from '@app/common/modules/aqi/r
|
||||
SubspaceModelProductAllocationRepoitory,
|
||||
OccupancyService,
|
||||
AqiDataService,
|
||||
PresenceSensorDailySpaceRepository,
|
||||
AqiSpaceDailyPollutantStatsRepository,
|
||||
],
|
||||
exports: [PowerClamp],
|
||||
})
|
||||
|
@ -67,8 +67,6 @@ 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];
|
||||
|
||||
@ -126,8 +124,6 @@ const CommandHandlers = [CreateOrphanSpaceHandler];
|
||||
SqlLoaderService,
|
||||
OccupancyService,
|
||||
AqiDataService,
|
||||
PresenceSensorDailySpaceRepository,
|
||||
AqiSpaceDailyPollutantStatsRepository,
|
||||
],
|
||||
exports: [ProjectService, CqrsModule],
|
||||
})
|
||||
|
@ -1,32 +0,0 @@
|
||||
import {
|
||||
ControlCur2AccurateCalibrationCommand,
|
||||
ControlCur2Command,
|
||||
ControlCur2PercentCommand,
|
||||
ControlCur2QuickCalibrationCommand,
|
||||
ControlCur2TDirectionConCommand,
|
||||
} from 'src/device/commands/cur2-commands';
|
||||
|
||||
export enum ScheduleProductType {
|
||||
CUR_2 = 'CUR_2',
|
||||
}
|
||||
export const DeviceFunctionMap: {
|
||||
[T in ScheduleProductType]: (body: DeviceFunction[T]) => any;
|
||||
} = {
|
||||
[ScheduleProductType.CUR_2]: ({ code, value }) => {
|
||||
return [
|
||||
{
|
||||
code,
|
||||
value,
|
||||
},
|
||||
];
|
||||
},
|
||||
};
|
||||
|
||||
type DeviceFunction = {
|
||||
[ScheduleProductType.CUR_2]:
|
||||
| ControlCur2Command
|
||||
| ControlCur2PercentCommand
|
||||
| ControlCur2AccurateCalibrationCommand
|
||||
| ControlCur2TDirectionConCommand
|
||||
| ControlCur2QuickCalibrationCommand;
|
||||
};
|
@ -1,6 +1,6 @@
|
||||
import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { Injectable, HttpException, HttpStatus } from '@nestjs/common';
|
||||
import { TuyaContext } from '@tuya/tuya-connector-nodejs';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import {
|
||||
AddScheduleDto,
|
||||
EnableScheduleDto,
|
||||
@ -11,14 +11,14 @@ import {
|
||||
getDeviceScheduleInterface,
|
||||
} from '../interfaces/get.schedule.interface';
|
||||
|
||||
import { ProductType } from '@app/common/constants/product-type.enum';
|
||||
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 { 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,11 +49,22 @@ export class ScheduleService {
|
||||
}
|
||||
|
||||
// Corrected condition for supported device types
|
||||
this.ensureProductTypeSupportedForSchedule(
|
||||
deviceDetails.productDevice.prodType as ProductType,
|
||||
);
|
||||
|
||||
return this.enableScheduleDeviceInTuya(
|
||||
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(
|
||||
deviceDetails.deviceTuyaUuid,
|
||||
enableScheduleDto,
|
||||
);
|
||||
@ -64,6 +75,29 @@ export class ScheduleService {
|
||||
);
|
||||
}
|
||||
}
|
||||
async enableScheduleDeviceInTuya(
|
||||
deviceId: string,
|
||||
enableScheduleDto: EnableScheduleDto,
|
||||
): Promise<addScheduleDeviceInterface> {
|
||||
try {
|
||||
const path = `/v2.0/cloud/timer/device/${deviceId}/state`;
|
||||
const response = await this.tuya.request({
|
||||
method: 'PUT',
|
||||
path,
|
||||
body: {
|
||||
enable: enableScheduleDto.enable,
|
||||
timer_id: enableScheduleDto.scheduleId,
|
||||
},
|
||||
});
|
||||
|
||||
return response as addScheduleDeviceInterface;
|
||||
} catch (error) {
|
||||
throw new HttpException(
|
||||
'Error while updating schedule from Tuya',
|
||||
HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
}
|
||||
async deleteDeviceSchedule(deviceUuid: string, scheduleId: string) {
|
||||
try {
|
||||
const deviceDetails = await this.getDeviceByDeviceUuid(deviceUuid);
|
||||
@ -73,10 +107,21 @@ export class ScheduleService {
|
||||
}
|
||||
|
||||
// Corrected condition for supported device types
|
||||
this.ensureProductTypeSupportedForSchedule(
|
||||
deviceDetails.productDevice.prodType as ProductType,
|
||||
);
|
||||
|
||||
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,
|
||||
@ -88,6 +133,25 @@ export class ScheduleService {
|
||||
);
|
||||
}
|
||||
}
|
||||
async deleteScheduleDeviceInTuya(
|
||||
deviceId: string,
|
||||
scheduleId: string,
|
||||
): Promise<addScheduleDeviceInterface> {
|
||||
try {
|
||||
const path = `/v2.0/cloud/timer/device/${deviceId}/batch?timer_ids=${scheduleId}`;
|
||||
const response = await this.tuya.request({
|
||||
method: 'DELETE',
|
||||
path,
|
||||
});
|
||||
|
||||
return response as addScheduleDeviceInterface;
|
||||
} catch (error) {
|
||||
throw new HttpException(
|
||||
'Error while deleting schedule from Tuya',
|
||||
HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
}
|
||||
async addDeviceSchedule(deviceUuid: string, addScheduleDto: AddScheduleDto) {
|
||||
try {
|
||||
const deviceDetails = await this.getDeviceByDeviceUuid(deviceUuid);
|
||||
@ -96,10 +160,22 @@ export class ScheduleService {
|
||||
throw new HttpException('Device Not Found', HttpStatus.NOT_FOUND);
|
||||
}
|
||||
|
||||
this.ensureProductTypeSupportedForSchedule(
|
||||
deviceDetails.productDevice.prodType as ProductType,
|
||||
);
|
||||
|
||||
// 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,
|
||||
@ -111,6 +187,40 @@ export class ScheduleService {
|
||||
);
|
||||
}
|
||||
}
|
||||
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);
|
||||
@ -119,9 +229,21 @@ export class ScheduleService {
|
||||
throw new HttpException('Device Not Found', HttpStatus.NOT_FOUND);
|
||||
}
|
||||
// Corrected condition for supported device types
|
||||
this.ensureProductTypeSupportedForSchedule(
|
||||
deviceDetails.productDevice.prodType as ProductType,
|
||||
);
|
||||
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,
|
||||
@ -148,82 +270,7 @@ export class ScheduleService {
|
||||
);
|
||||
}
|
||||
}
|
||||
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
|
||||
this.ensureProductTypeSupportedForSchedule(
|
||||
deviceDetails.productDevice.prodType as ProductType,
|
||||
);
|
||||
|
||||
await this.updateScheduleDeviceInTuya(
|
||||
deviceDetails.deviceTuyaUuid,
|
||||
updateScheduleDto,
|
||||
);
|
||||
} 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,
|
||||
): 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: `category_${addScheduleDto.category}`,
|
||||
},
|
||||
});
|
||||
|
||||
return response as addScheduleDeviceInterface;
|
||||
} catch (error) {
|
||||
throw new HttpException(
|
||||
'Error adding schedule from Tuya',
|
||||
HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private async getScheduleDeviceInTuya(
|
||||
async getScheduleDeviceInTuya(
|
||||
deviceId: string,
|
||||
category: string,
|
||||
): Promise<getDeviceScheduleInterface> {
|
||||
@ -244,8 +291,57 @@ export class ScheduleService {
|
||||
);
|
||||
}
|
||||
}
|
||||
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);
|
||||
|
||||
private async updateScheduleDeviceInTuya(
|
||||
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> {
|
||||
@ -280,69 +376,4 @@ export class ScheduleService {
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private async enableScheduleDeviceInTuya(
|
||||
deviceId: string,
|
||||
enableScheduleDto: EnableScheduleDto,
|
||||
): Promise<addScheduleDeviceInterface> {
|
||||
try {
|
||||
const path = `/v2.0/cloud/timer/device/${deviceId}/state`;
|
||||
const response = await this.tuya.request({
|
||||
method: 'PUT',
|
||||
path,
|
||||
body: {
|
||||
enable: enableScheduleDto.enable,
|
||||
timer_id: enableScheduleDto.scheduleId,
|
||||
},
|
||||
});
|
||||
|
||||
return response as addScheduleDeviceInterface;
|
||||
} catch (error) {
|
||||
throw new HttpException(
|
||||
'Error while updating schedule from Tuya',
|
||||
HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private async deleteScheduleDeviceInTuya(
|
||||
deviceId: string,
|
||||
scheduleId: string,
|
||||
): Promise<addScheduleDeviceInterface> {
|
||||
try {
|
||||
const path = `/v2.0/cloud/timer/device/${deviceId}/batch?timer_ids=${scheduleId}`;
|
||||
const response = await this.tuya.request({
|
||||
method: 'DELETE',
|
||||
path,
|
||||
});
|
||||
|
||||
return response as addScheduleDeviceInterface;
|
||||
} catch (error) {
|
||||
throw new HttpException(
|
||||
'Error while deleting schedule from Tuya',
|
||||
HttpStatus.INTERNAL_SERVER_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(
|
||||
'This device is not supported for schedule',
|
||||
HttpStatus.BAD_REQUEST,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -1,25 +0,0 @@
|
||||
import { DatabaseModule } from '@app/common/database/database.module';
|
||||
import { SqlLoaderService } from '@app/common/helper/services/sql-loader.service';
|
||||
import { Module } from '@nestjs/common';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { SchedulerService } from './scheduler.service';
|
||||
import { ScheduleModule as NestScheduleModule } from '@nestjs/schedule';
|
||||
import { AqiDataService } from '@app/common/helper/services/aqi.data.service';
|
||||
import { OccupancyService } from '@app/common/helper/services/occupancy.service';
|
||||
import { PowerClampService } from '@app/common/helper/services/power.clamp.service';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
NestScheduleModule.forRoot(),
|
||||
TypeOrmModule.forFeature([]),
|
||||
DatabaseModule,
|
||||
],
|
||||
providers: [
|
||||
SchedulerService,
|
||||
SqlLoaderService,
|
||||
PowerClampService,
|
||||
OccupancyService,
|
||||
AqiDataService,
|
||||
],
|
||||
})
|
||||
export class SchedulerModule {}
|
@ -1,92 +0,0 @@
|
||||
import { AqiDataService } from '@app/common/helper/services/aqi.data.service';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { Cron, CronExpression } from '@nestjs/schedule';
|
||||
import { OccupancyService } from '@app/common/helper/services/occupancy.service';
|
||||
import { PowerClampService } from '@app/common/helper/services/power.clamp.service';
|
||||
|
||||
@Injectable()
|
||||
export class SchedulerService {
|
||||
constructor(
|
||||
private readonly powerClampService: PowerClampService,
|
||||
private readonly occupancyService: OccupancyService,
|
||||
private readonly aqiDataService: AqiDataService,
|
||||
) {
|
||||
console.log('SchedulerService initialized!');
|
||||
}
|
||||
|
||||
@Cron(CronExpression.EVERY_HOUR)
|
||||
async runHourlyProcedures() {
|
||||
console.log('\n======== Starting Procedures ========');
|
||||
console.log(new Date().toISOString(), 'Scheduler running...');
|
||||
|
||||
try {
|
||||
const results = await Promise.allSettled([
|
||||
this.executeTask(
|
||||
() => this.powerClampService.updateEnergyConsumedHistoricalData(),
|
||||
'Energy Consumption',
|
||||
),
|
||||
this.executeTask(
|
||||
() => this.occupancyService.updateOccupancyDataProcedures(),
|
||||
'Occupancy Data',
|
||||
),
|
||||
this.executeTask(
|
||||
() => this.aqiDataService.updateAQISensorHistoricalData(),
|
||||
'AQI Data',
|
||||
),
|
||||
]);
|
||||
|
||||
this.logResults(results);
|
||||
} catch (error) {
|
||||
console.error('MAIN SCHEDULER ERROR:', error);
|
||||
if (error.stack) {
|
||||
console.error('Error stack:', error.stack);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async executeTask(
|
||||
task: () => Promise<void>,
|
||||
name: string,
|
||||
): Promise<{ name: string; status: string }> {
|
||||
try {
|
||||
console.log(`[${new Date().toISOString()}] Starting ${name} task...`);
|
||||
await task();
|
||||
console.log(
|
||||
`[${new Date().toISOString()}] ${name} task completed successfully`,
|
||||
);
|
||||
return { name, status: 'success' };
|
||||
} catch (error) {
|
||||
console.error(
|
||||
`[${new Date().toISOString()}] ${name} task failed:`,
|
||||
error.message,
|
||||
);
|
||||
if (error.stack) {
|
||||
console.error('Task error stack:', error.stack);
|
||||
}
|
||||
return { name, status: 'failed' };
|
||||
}
|
||||
}
|
||||
|
||||
private logResults(results: PromiseSettledResult<any>[]) {
|
||||
const successCount = results.filter((r) => r.status === 'fulfilled').length;
|
||||
const failedCount = results.length - successCount;
|
||||
|
||||
console.log('\n======== Task Results ========');
|
||||
console.log(`Successful tasks: ${successCount}`);
|
||||
console.log(`Failed tasks: ${failedCount}`);
|
||||
|
||||
if (failedCount > 0) {
|
||||
console.log('\n======== Failed Tasks Details ========');
|
||||
results.forEach((result, index) => {
|
||||
if (result.status === 'rejected') {
|
||||
console.error(`Task ${index + 1} failed:`, result.reason);
|
||||
if (result.reason.stack) {
|
||||
console.error('Error stack:', result.reason.stack);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
console.log('\n======== Scheduler Completed ========\n');
|
||||
}
|
||||
}
|
@ -63,8 +63,6 @@ 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,
|
||||
@ -122,8 +120,6 @@ const CommandHandlers = [
|
||||
SqlLoaderService,
|
||||
OccupancyService,
|
||||
AqiDataService,
|
||||
PresenceSensorDailySpaceRepository,
|
||||
AqiSpaceDailyPollutantStatsRepository,
|
||||
],
|
||||
exports: [CqrsModule, SpaceModelService],
|
||||
})
|
||||
|
@ -88,8 +88,6 @@ 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];
|
||||
|
||||
@ -163,8 +161,6 @@ export const CommandHandlers = [DisableSpaceHandler];
|
||||
SqlLoaderService,
|
||||
OccupancyService,
|
||||
AqiDataService,
|
||||
PresenceSensorDailySpaceRepository,
|
||||
AqiSpaceDailyPollutantStatsRepository,
|
||||
],
|
||||
exports: [SpaceService],
|
||||
})
|
||||
|
@ -1,39 +1,39 @@
|
||||
import { ProductType } from '@app/common/constants/product-type.enum';
|
||||
import { DeviceRepository } from '@app/common/modules/device/repositories';
|
||||
import { VisitorPasswordRepository } from './../../../libs/common/src/modules/visitor-password/repositories/visitor-password.repository';
|
||||
import {
|
||||
BadRequestException,
|
||||
Injectable,
|
||||
HttpException,
|
||||
HttpStatus,
|
||||
Injectable,
|
||||
BadRequestException,
|
||||
} from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { TuyaContext } from '@tuya/tuya-connector-nodejs';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import {
|
||||
addDeviceObjectInterface,
|
||||
createTickInterface,
|
||||
} from '../interfaces/visitor-password.interface';
|
||||
import { VisitorPasswordRepository } from './../../../libs/common/src/modules/visitor-password/repositories/visitor-password.repository';
|
||||
import { DeviceRepository } from '@app/common/modules/device/repositories';
|
||||
import { ProductType } from '@app/common/constants/product-type.enum';
|
||||
|
||||
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 { DeviceStatuses } from '@app/common/constants/device-status.enum';
|
||||
import { PasswordType } from '@app/common/constants/password-type.enum';
|
||||
import {
|
||||
CommonHourMinutes,
|
||||
CommonHours,
|
||||
} from '@app/common/constants/hours-minutes.enum';
|
||||
import { ORPHAN_SPACE_NAME } from '@app/common/constants/orphan-constant';
|
||||
import { PasswordType } from '@app/common/constants/password-type.enum';
|
||||
import { ProjectRepository } from '@app/common/modules/project/repositiories';
|
||||
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 { AddDoorLockTemporaryPasswordDto } from '../dtos';
|
||||
import { ORPHAN_SPACE_NAME } from '@app/common/constants/orphan-constant';
|
||||
|
||||
@Injectable()
|
||||
export class VisitorPasswordService {
|
||||
@ -57,67 +57,6 @@ 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,
|
||||
@ -166,7 +105,7 @@ export class VisitorPasswordService {
|
||||
statusCode: HttpStatus.CREATED,
|
||||
});
|
||||
}
|
||||
private async addOfflineMultipleTimeTemporaryPassword(
|
||||
async addOfflineMultipleTimeTemporaryPassword(
|
||||
addDoorLockOfflineMultipleDto: AddDoorLockTemporaryPasswordDto,
|
||||
userUuid: string,
|
||||
projectUuid: string,
|
||||
@ -230,7 +169,6 @@ export class VisitorPasswordService {
|
||||
success: true,
|
||||
result: createMultipleOfflinePass.result,
|
||||
deviceUuid,
|
||||
deviceName: deviceDetails.name,
|
||||
};
|
||||
} catch (error) {
|
||||
return {
|
||||
@ -293,7 +231,7 @@ export class VisitorPasswordService {
|
||||
}
|
||||
}
|
||||
|
||||
private async addOfflineOneTimeTemporaryPassword(
|
||||
async addOfflineOneTimeTemporaryPassword(
|
||||
addDoorLockOfflineOneTimeDto: AddDoorLockTemporaryPasswordDto,
|
||||
userUuid: string,
|
||||
projectUuid: string,
|
||||
@ -357,7 +295,6 @@ export class VisitorPasswordService {
|
||||
success: true,
|
||||
result: createOnceOfflinePass.result,
|
||||
deviceUuid,
|
||||
deviceName: deviceDetails.name,
|
||||
};
|
||||
} catch (error) {
|
||||
return {
|
||||
@ -420,7 +357,7 @@ export class VisitorPasswordService {
|
||||
}
|
||||
}
|
||||
|
||||
private async addOfflineTemporaryPasswordTuya(
|
||||
async addOfflineTemporaryPasswordTuya(
|
||||
doorLockUuid: string,
|
||||
type: string,
|
||||
addDoorLockOfflineMultipleDto: AddDoorLockTemporaryPasswordDto,
|
||||
@ -450,7 +387,7 @@ export class VisitorPasswordService {
|
||||
);
|
||||
}
|
||||
}
|
||||
private async addOnlineTemporaryPasswordMultipleTime(
|
||||
async addOnlineTemporaryPasswordMultipleTime(
|
||||
addDoorLockOnlineMultipleDto: AddDoorLockTemporaryPasswordDto,
|
||||
userUuid: string,
|
||||
projectUuid: string,
|
||||
@ -511,7 +448,6 @@ export class VisitorPasswordService {
|
||||
success: true,
|
||||
id: createPass.result.id,
|
||||
deviceUuid,
|
||||
deviceName: passwordData.deviceName,
|
||||
};
|
||||
} catch (error) {
|
||||
return {
|
||||
@ -572,8 +508,67 @@ export class VisitorPasswordService {
|
||||
);
|
||||
}
|
||||
}
|
||||
async getPasswords(projectUuid: string) {
|
||||
await this.validateProject(projectUuid);
|
||||
|
||||
private async addOnlineTemporaryPasswordOneTime(
|
||||
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(
|
||||
addDoorLockOnlineOneTimeDto: AddDoorLockTemporaryPasswordDto,
|
||||
userUuid: string,
|
||||
projectUuid: string,
|
||||
@ -632,7 +627,6 @@ export class VisitorPasswordService {
|
||||
return {
|
||||
success: true,
|
||||
id: createPass.result.id,
|
||||
deviceName: passwordData.deviceName,
|
||||
deviceUuid,
|
||||
};
|
||||
} catch (error) {
|
||||
@ -694,7 +688,7 @@ export class VisitorPasswordService {
|
||||
);
|
||||
}
|
||||
}
|
||||
private async getTicketAndEncryptedPassword(
|
||||
async getTicketAndEncryptedPassword(
|
||||
doorLockUuid: string,
|
||||
passwordPlan: string,
|
||||
projectUuid: string,
|
||||
@ -731,7 +725,6 @@ export class VisitorPasswordService {
|
||||
ticketKey: ticketDetails.result.ticket_key,
|
||||
encryptedPassword: decrypted,
|
||||
deviceTuyaUuid: deviceDetails.deviceTuyaUuid,
|
||||
deviceName: deviceDetails.name,
|
||||
};
|
||||
} catch (error) {
|
||||
throw new HttpException(
|
||||
@ -741,7 +734,7 @@ export class VisitorPasswordService {
|
||||
}
|
||||
}
|
||||
|
||||
private async createDoorLockTicketTuya(
|
||||
async createDoorLockTicketTuya(
|
||||
deviceUuid: string,
|
||||
): Promise<createTickInterface> {
|
||||
try {
|
||||
@ -760,7 +753,7 @@ export class VisitorPasswordService {
|
||||
}
|
||||
}
|
||||
|
||||
private async addOnlineTemporaryPasswordMultipleTuya(
|
||||
async addOnlineTemporaryPasswordMultipleTuya(
|
||||
addDeviceObj: addDeviceObjectInterface,
|
||||
doorLockUuid: string,
|
||||
): Promise<createTickInterface> {
|
||||
@ -802,7 +795,7 @@ export class VisitorPasswordService {
|
||||
}
|
||||
}
|
||||
|
||||
private getWorkingDayValue(days) {
|
||||
getWorkingDayValue(days) {
|
||||
// Array representing the days of the week
|
||||
const weekDays = [
|
||||
DaysEnum.SAT,
|
||||
@ -834,7 +827,36 @@ export class VisitorPasswordService {
|
||||
|
||||
return workingDayValue;
|
||||
}
|
||||
private timeToMinutes(timeStr) {
|
||||
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) {
|
||||
try {
|
||||
// Special case for "24:00"
|
||||
if (timeStr === CommonHours.TWENTY_FOUR) {
|
||||
@ -861,7 +883,38 @@ export class VisitorPasswordService {
|
||||
throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR);
|
||||
}
|
||||
}
|
||||
private async getDeviceByDeviceUuid(
|
||||
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(
|
||||
deviceUuid: string,
|
||||
withProductDevice: boolean = true,
|
||||
projectUuid: string,
|
||||
@ -886,7 +939,7 @@ export class VisitorPasswordService {
|
||||
throw new HttpException('Device Not Found', HttpStatus.NOT_FOUND);
|
||||
}
|
||||
}
|
||||
private async addOnlineTemporaryPasswordOneTimeTuya(
|
||||
async addOnlineTemporaryPasswordOneTimeTuya(
|
||||
addDeviceObj: addDeviceObjectInterface,
|
||||
doorLockUuid: string,
|
||||
): Promise<createTickInterface> {
|
||||
|
@ -32,8 +32,6 @@ 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],
|
||||
@ -63,8 +61,6 @@ import { AqiSpaceDailyPollutantStatsRepository } from '@app/common/modules/aqi/r
|
||||
OccupancyService,
|
||||
CommunityRepository,
|
||||
AqiDataService,
|
||||
PresenceSensorDailySpaceRepository,
|
||||
AqiSpaceDailyPollutantStatsRepository,
|
||||
],
|
||||
exports: [VisitorPasswordService],
|
||||
})
|
||||
|
Reference in New Issue
Block a user