mirror of
https://github.com/SyncrowIOT/backend.git
synced 2025-07-16 02:36:19 +00:00
69 lines
2.3 KiB
TypeScript
69 lines
2.3 KiB
TypeScript
import { DeviceRepository } from '@app/common/modules/device/repositories';
|
|
import { Injectable } from '@nestjs/common';
|
|
import { SqlLoaderService } from './sql-loader.service';
|
|
import { DataSource } from 'typeorm';
|
|
import { SQL_PROCEDURES_PATH } from '@app/common/constants/sql-query-path';
|
|
|
|
@Injectable()
|
|
export class 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],
|
|
);
|
|
} catch (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);
|
|
}
|
|
}
|