Compare commits

..

9 Commits

Author SHA1 Message Date
7ea53feddc add deviceName to handle password API 2025-06-30 08:54:25 +03:00
c7a4ff1194 fix: schedule device types (#441) 2025-06-29 15:27:55 +03:00
8a4633b158 Merge pull request #439 from SyncrowIOT/add-check-log-to-trace-the-map-issue
feat: enhance device status handling with caching and batch processin…
2025-06-25 18:59:37 -06:00
f80d097ff8 refactor: optimize log insertion and clean up device cache handling in TuyaWebSocketService 2025-06-25 18:57:56 -06:00
04bd156df1 Merge branch 'dev' into add-check-log-to-trace-the-map-issue 2025-06-25 18:42:43 -06:00
731819aeaa feat: enhance device status handling with caching and batch processing improvements 2025-06-25 18:37:46 -06:00
68d2d3b53d fix: improve device retrieval logic in addDeviceStatusToFirebase method 2025-06-25 08:13:02 -06:00
3fcfe2d92f Merge pull request #438 from SyncrowIOT/temp-fix-to-check
fix: enhance device status handling by integrating device cache for improved performance
2025-06-25 08:06:29 -06:00
30724d7d37 Merge pull request #436 from SyncrowIOT/add-check-log-to-trace-the-map-issue
fix: add validation for missing properties in device status logs
2025-06-25 05:32:50 -06:00
7 changed files with 252 additions and 281 deletions

View File

@ -68,22 +68,21 @@ export class DeviceStatusFirebaseService {
} }
} }
async addBatchDeviceStatusToOurDb( async addBatchDeviceStatusToOurDb(
batch: { deviceTuyaUuid: string; status: any; log: any }[], batch: {
deviceCache: Map<string, any>, deviceTuyaUuid: string;
status: any;
log: any;
device: any;
}[],
): Promise<void> { ): Promise<void> {
const allLogs = []; const allLogs = [];
console.log( console.log(`🔁 Preparing logs from batch of ${batch.length} items...`);
`🧠 Preparing logs from batch of ${batch.length} items using cached devices only...`,
);
for (const item of batch) { for (const item of batch) {
const device = deviceCache.get(item.deviceTuyaUuid); const device = item.device;
if (!device?.uuid) { if (!device?.uuid) {
console.log( console.log(`⛔ Skipped unknown device: ${item.deviceTuyaUuid}`);
`⛔ Ignored unknown device in batch: ${item.deviceTuyaUuid}`,
);
continue; continue;
} }
@ -103,6 +102,8 @@ export class DeviceStatusFirebaseService {
} }
console.log(`📝 Total logs to insert: ${allLogs.length}`); console.log(`📝 Total logs to insert: ${allLogs.length}`);
const insertLogsPromise = (async () => {
const chunkSize = 300; const chunkSize = 300;
let insertedCount = 0; let insertedCount = 0;
@ -126,30 +127,34 @@ export class DeviceStatusFirebaseService {
} }
} }
console.log(`✅ Total logs inserted: ${insertedCount} / ${allLogs.length}`); console.log(
`✅ Total logs inserted: ${insertedCount} / ${allLogs.length}`,
);
})();
await insertLogsPromise;
} }
async addDeviceStatusToFirebase( async addDeviceStatusToFirebase(
addDeviceStatusDto: AddDeviceStatusDto, addDeviceStatusDto: AddDeviceStatusDto & { device?: any },
deviceCache: Map<string, any>,
): Promise<AddDeviceStatusDto | null> { ): Promise<AddDeviceStatusDto | null> {
try { try {
const device = deviceCache.get(addDeviceStatusDto.deviceTuyaUuid); let device = addDeviceStatusDto.device;
if (!device?.uuid) { if (!device) {
console.log( device = await this.getDeviceByDeviceTuyaUuid(
`⛔ Skipping Firebase update for unknown device: ${addDeviceStatusDto.deviceTuyaUuid}`, addDeviceStatusDto.deviceTuyaUuid,
); );
return null;
} }
if (device?.uuid) {
// Ensure product info and uuid are attached return await this.createDeviceStatusFirebase({
addDeviceStatusDto.deviceUuid = device.uuid; deviceUuid: device.uuid,
addDeviceStatusDto.productUuid = device.productDevice?.uuid; ...addDeviceStatusDto,
addDeviceStatusDto.productType = device.productDevice?.prodType; productType: device.productDevice?.prodType,
});
return await this.createDeviceStatusFirebase(addDeviceStatusDto); }
// Return null if device not found or no UUID
return null;
} catch (error) { } catch (error) {
console.error('❌ Error in addDeviceStatusToFirebase:', error);
return null; return null;
} }
} }
@ -163,6 +168,15 @@ export class DeviceStatusFirebaseService {
relations: ['productDevice'], relations: ['productDevice'],
}); });
} }
async getAllDevices() {
return await this.deviceRepository.find({
where: {
isActive: true,
},
relations: ['productDevice'],
});
}
async getDevicesInstructionStatus(deviceUuid: string) { async getDevicesInstructionStatus(deviceUuid: string) {
try { try {
const deviceDetails = await this.getDeviceByDeviceUuid(deviceUuid); const deviceDetails = await this.getDeviceByDeviceUuid(deviceUuid);

View File

@ -16,53 +16,46 @@ export class SosHandlerService {
); );
} }
async handleSosEventFirebase( async handleSosEventFirebase(device: any, logData: any): Promise<void> {
devId: string, const sosTrueStatus = [{ code: 'sos', value: true }];
logData: any, const sosFalseStatus = [{ code: 'sos', value: false }];
deviceCache: Map<string, any>,
): Promise<void> {
try { try {
await this.deviceStatusFirebaseService.addDeviceStatusToFirebase( // ✅ Send true status
{ await this.deviceStatusFirebaseService.addDeviceStatusToFirebase({
deviceTuyaUuid: devId, deviceTuyaUuid: device.deviceTuyaUuid,
status: [{ code: 'sos', value: true }], status: sosTrueStatus,
log: logData, log: logData,
}, device,
deviceCache, });
);
await this.deviceStatusFirebaseService.addBatchDeviceStatusToOurDb( await this.deviceStatusFirebaseService.addBatchDeviceStatusToOurDb([
[
{ {
deviceTuyaUuid: devId, deviceTuyaUuid: device.deviceTuyaUuid,
status: [{ code: 'sos', value: true }], status: sosTrueStatus,
log: logData, log: logData,
device,
}, },
], ]);
deviceCache,
);
// ✅ Schedule false status
setTimeout(async () => { setTimeout(async () => {
try { try {
await this.deviceStatusFirebaseService.addDeviceStatusToFirebase( await this.deviceStatusFirebaseService.addDeviceStatusToFirebase({
{ deviceTuyaUuid: device.deviceTuyaUuid,
deviceTuyaUuid: devId, status: sosFalseStatus,
status: [{ code: 'sos', value: false }],
log: logData, log: logData,
}, device,
deviceCache, });
);
await this.deviceStatusFirebaseService.addBatchDeviceStatusToOurDb( await this.deviceStatusFirebaseService.addBatchDeviceStatusToOurDb([
[
{ {
deviceTuyaUuid: devId, deviceTuyaUuid: device.deviceTuyaUuid,
status: [{ code: 'sos', value: false }], status: sosFalseStatus,
log: logData, log: logData,
device,
}, },
], ]);
deviceCache,
);
} catch (err) { } catch (err) {
this.logger.error('Failed to send SOS false value', err); this.logger.error('Failed to send SOS false value', err);
} }

View File

@ -1,29 +1,29 @@
import { Injectable } from '@nestjs/common'; import { Injectable, OnModuleInit } from '@nestjs/common';
import TuyaWebsocket from '../../config/tuya-web-socket-config'; import TuyaWebsocket from '../../config/tuya-web-socket-config';
import { ConfigService } from '@nestjs/config'; import { ConfigService } from '@nestjs/config';
import { DeviceStatusFirebaseService } from '@app/common/firebase/devices-status/services/devices-status.service'; import { DeviceStatusFirebaseService } from '@app/common/firebase/devices-status/services/devices-status.service';
import { SosHandlerService } from './sos.handler.service'; import { SosHandlerService } from './sos.handler.service';
import { DeviceRepository } from '@app/common/modules/device/repositories'; import * as NodeCache from 'node-cache';
@Injectable() @Injectable()
export class TuyaWebSocketService { export class TuyaWebSocketService implements OnModuleInit {
private client: any; private client: any;
private readonly isDevEnv: boolean; private readonly isDevEnv: boolean;
private readonly deviceCache = new NodeCache({ stdTTL: 7200 }); // TTL = 2 hour
private messageQueue: { private messageQueue: {
devId: string; devId: string;
status: any; status: any;
logData: any; logData: any;
device: any;
}[] = []; }[] = [];
private isProcessing = false; private isProcessing = false;
private deviceCache: Map<string, any> = new Map();
constructor( constructor(
private readonly configService: ConfigService, private readonly configService: ConfigService,
private readonly deviceStatusFirebaseService: DeviceStatusFirebaseService, private readonly deviceStatusFirebaseService: DeviceStatusFirebaseService,
private readonly sosHandlerService: SosHandlerService, private readonly sosHandlerService: SosHandlerService,
private readonly deviceRepository: DeviceRepository,
) { ) {
this.isDevEnv = this.isDevEnv =
this.configService.get<string>('NODE_ENV') === 'development'; this.configService.get<string>('NODE_ENV') === 'development';
@ -36,38 +36,37 @@ export class TuyaWebSocketService {
maxRetryTimes: 100, maxRetryTimes: 100,
}); });
this.loadAllActiveDevices();
// Reload device cache every 1 hour
setInterval(() => this.loadAllActiveDevices(), 60 * 60 * 1000);
if (this.configService.get<string>('tuya-config.TRUN_ON_TUYA_SOCKET')) { if (this.configService.get<string>('tuya-config.TRUN_ON_TUYA_SOCKET')) {
this.setupEventHandlers(); this.setupEventHandlers();
this.client.start(); this.client.start();
} }
// Trigger the queue processor every 15 seconds // Run the queue processor every 15 seconds
setInterval(() => this.processQueue(), 15000); setInterval(() => this.processQueue(), 15000);
// Refresh the cache every 1 hour
setInterval(() => this.initializeDeviceCache(), 30 * 60 * 1000); // 30 minutes
} }
private async loadAllActiveDevices(): Promise<void> { async onModuleInit() {
const devices = await this.deviceRepository.find({ await this.initializeDeviceCache();
where: { isActive: true }, }
relations: ['productDevice'],
});
this.deviceCache.clear(); private async initializeDeviceCache() {
devices.forEach((device) => { try {
const allDevices = await this.deviceStatusFirebaseService.getAllDevices();
allDevices.forEach((device) => {
if (device.deviceTuyaUuid) {
this.deviceCache.set(device.deviceTuyaUuid, device); this.deviceCache.set(device.deviceTuyaUuid, device);
}
}); });
console.log(`✅ Refreshed cache with ${allDevices.length} devices.`);
console.log( } catch (error) {
`🔄 Device cache reloaded: ${this.deviceCache.size} active devices at ${new Date().toISOString()}`, console.error('❌ Failed to initialize device cache:', error);
); }
} }
private setupEventHandlers() { private setupEventHandlers() {
// Event handlers
this.client.open(() => { this.client.open(() => {
console.log('open'); console.log('open');
}); });
@ -75,42 +74,38 @@ export class TuyaWebSocketService {
this.client.message(async (ws: WebSocket, message: any) => { this.client.message(async (ws: WebSocket, message: any) => {
try { try {
const { devId, status, logData } = this.extractMessageData(message); const { devId, status, logData } = this.extractMessageData(message);
if (!Array.isArray(logData?.properties)) return; if (!Array.isArray(logData?.properties)) {
this.client.ackMessage(message.messageId);
return;
}
const device = this.deviceCache.get(devId); const device = this.deviceCache.get(devId);
if (!device) { if (!device) {
// console.log(`Ignored unknown device: ${devId}`); // console.log(⛔ Unknown device: ${devId}, message ignored.);
this.client.ackMessage(message.messageId);
return; return;
} }
if (this.sosHandlerService.isSosTriggered(status)) { if (this.sosHandlerService.isSosTriggered(status)) {
await this.sosHandlerService.handleSosEventFirebase( await this.sosHandlerService.handleSosEventFirebase(devId, logData);
devId,
logData,
this.deviceCache,
);
} else { } else {
// Firebase real-time update await this.deviceStatusFirebaseService.addDeviceStatusToFirebase({
await this.deviceStatusFirebaseService.addDeviceStatusToFirebase(
{
deviceTuyaUuid: devId, deviceTuyaUuid: devId,
status, status,
log: logData, log: logData,
}, device,
this.deviceCache, });
);
} }
// Push to internal queue // Push to internal queue
this.messageQueue.push({ devId, status, logData }); this.messageQueue.push({ devId, status, logData, device });
// Acknowledge the message // Acknowledge the message
this.client.ackMessage(message.messageId); this.client.ackMessage(message.messageId);
} catch (error) { } catch (error) {
console.error('Error receiving message:', error); console.error('Error receiving message:', error);
} }
}); });
this.client.reconnect(() => { this.client.reconnect(() => {
console.log('reconnect'); console.log('reconnect');
}); });
@ -151,8 +146,8 @@ export class TuyaWebSocketService {
deviceTuyaUuid: item.devId, deviceTuyaUuid: item.devId,
status: item.status, status: item.status,
log: item.logData, log: item.logData,
device: item.device,
})), })),
this.deviceCache,
); );
} catch (error) { } catch (error) {
console.error('❌ Error processing batch:', error); console.error('❌ Error processing batch:', error);

22
package-lock.json generated
View File

@ -39,6 +39,7 @@
"ioredis": "^5.3.2", "ioredis": "^5.3.2",
"morgan": "^1.10.0", "morgan": "^1.10.0",
"nest-winston": "^1.10.2", "nest-winston": "^1.10.2",
"node-cache": "^5.1.2",
"nodemailer": "^6.9.10", "nodemailer": "^6.9.10",
"onesignal-node": "^3.4.0", "onesignal-node": "^3.4.0",
"passport-jwt": "^4.0.1", "passport-jwt": "^4.0.1",
@ -10184,6 +10185,27 @@
"node": "^18 || ^20 || >= 21" "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": { "node_modules/node-emoji": {
"version": "1.11.0", "version": "1.11.0",
"resolved": "https://registry.npmjs.org/node-emoji/-/node-emoji-1.11.0.tgz", "resolved": "https://registry.npmjs.org/node-emoji/-/node-emoji-1.11.0.tgz",

View File

@ -51,6 +51,7 @@
"ioredis": "^5.3.2", "ioredis": "^5.3.2",
"morgan": "^1.10.0", "morgan": "^1.10.0",
"nest-winston": "^1.10.2", "nest-winston": "^1.10.2",
"node-cache": "^5.1.2",
"nodemailer": "^6.9.10", "nodemailer": "^6.9.10",
"onesignal-node": "^3.4.0", "onesignal-node": "^3.4.0",
"passport-jwt": "^4.0.1", "passport-jwt": "^4.0.1",

View File

@ -50,7 +50,7 @@ export class ScheduleService {
// Corrected condition for supported device types // Corrected condition for supported device types
this.ensureProductTypeSupportedForSchedule( this.ensureProductTypeSupportedForSchedule(
ProductType[deviceDetails.productDevice.prodType], deviceDetails.productDevice.prodType as ProductType,
); );
return this.enableScheduleDeviceInTuya( return this.enableScheduleDeviceInTuya(
@ -74,7 +74,7 @@ export class ScheduleService {
// Corrected condition for supported device types // Corrected condition for supported device types
this.ensureProductTypeSupportedForSchedule( this.ensureProductTypeSupportedForSchedule(
ProductType[deviceDetails.productDevice.prodType], deviceDetails.productDevice.prodType as ProductType,
); );
return await this.deleteScheduleDeviceInTuya( return await this.deleteScheduleDeviceInTuya(
@ -97,7 +97,7 @@ export class ScheduleService {
} }
this.ensureProductTypeSupportedForSchedule( this.ensureProductTypeSupportedForSchedule(
ProductType[deviceDetails.productDevice.prodType], deviceDetails.productDevice.prodType as ProductType,
); );
await this.addScheduleDeviceInTuya( await this.addScheduleDeviceInTuya(
@ -120,9 +120,8 @@ export class ScheduleService {
} }
// Corrected condition for supported device types // Corrected condition for supported device types
this.ensureProductTypeSupportedForSchedule( this.ensureProductTypeSupportedForSchedule(
ProductType[deviceDetails.productDevice.prodType], deviceDetails.productDevice.prodType as ProductType,
); );
const schedules = await this.getScheduleDeviceInTuya( const schedules = await this.getScheduleDeviceInTuya(
deviceDetails.deviceTuyaUuid, deviceDetails.deviceTuyaUuid,
category, category,
@ -162,7 +161,7 @@ export class ScheduleService {
// Corrected condition for supported device types // Corrected condition for supported device types
this.ensureProductTypeSupportedForSchedule( this.ensureProductTypeSupportedForSchedule(
ProductType[deviceDetails.productDevice.prodType], deviceDetails.productDevice.prodType as ProductType,
); );
await this.updateScheduleDeviceInTuya( await this.updateScheduleDeviceInTuya(

View File

@ -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 { import {
Injectable, BadRequestException,
HttpException, HttpException,
HttpStatus, HttpStatus,
BadRequestException, Injectable,
} from '@nestjs/common'; } from '@nestjs/common';
import { TuyaContext } from '@tuya/tuya-connector-nodejs';
import { ConfigService } from '@nestjs/config'; import { ConfigService } from '@nestjs/config';
import { TuyaContext } from '@tuya/tuya-connector-nodejs';
import { import {
addDeviceObjectInterface, addDeviceObjectInterface,
createTickInterface, createTickInterface,
} from '../interfaces/visitor-password.interface'; } from '../interfaces/visitor-password.interface';
import { DeviceRepository } from '@app/common/modules/device/repositories'; import { VisitorPasswordRepository } from './../../../libs/common/src/modules/visitor-password/repositories/visitor-password.repository';
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 { import {
DaysEnum, DaysEnum,
EnableDisableStatusEnum, EnableDisableStatusEnum,
} from '@app/common/constants/days.enum'; } 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 { import {
CommonHourMinutes, CommonHourMinutes,
CommonHours, CommonHours,
} from '@app/common/constants/hours-minutes.enum'; } 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 { VisitorPasswordEnum } from '@app/common/constants/visitor-password.enum';
import { SuccessResponseDto } from '@app/common/dto/success.response.dto'; 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 { Not } from 'typeorm';
import { ORPHAN_SPACE_NAME } from '@app/common/constants/orphan-constant'; import { AddDoorLockTemporaryPasswordDto } from '../dtos';
@Injectable() @Injectable()
export class VisitorPasswordService { export class VisitorPasswordService {
@ -57,6 +57,67 @@ export class VisitorPasswordService {
secretKey, 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( async handleTemporaryPassword(
addDoorLockTemporaryPasswordDto: AddDoorLockTemporaryPasswordDto, addDoorLockTemporaryPasswordDto: AddDoorLockTemporaryPasswordDto,
userUuid: string, userUuid: string,
@ -105,7 +166,7 @@ export class VisitorPasswordService {
statusCode: HttpStatus.CREATED, statusCode: HttpStatus.CREATED,
}); });
} }
async addOfflineMultipleTimeTemporaryPassword( private async addOfflineMultipleTimeTemporaryPassword(
addDoorLockOfflineMultipleDto: AddDoorLockTemporaryPasswordDto, addDoorLockOfflineMultipleDto: AddDoorLockTemporaryPasswordDto,
userUuid: string, userUuid: string,
projectUuid: string, projectUuid: string,
@ -169,6 +230,7 @@ export class VisitorPasswordService {
success: true, success: true,
result: createMultipleOfflinePass.result, result: createMultipleOfflinePass.result,
deviceUuid, deviceUuid,
deviceName: deviceDetails.name,
}; };
} catch (error) { } catch (error) {
return { return {
@ -231,7 +293,7 @@ export class VisitorPasswordService {
} }
} }
async addOfflineOneTimeTemporaryPassword( private async addOfflineOneTimeTemporaryPassword(
addDoorLockOfflineOneTimeDto: AddDoorLockTemporaryPasswordDto, addDoorLockOfflineOneTimeDto: AddDoorLockTemporaryPasswordDto,
userUuid: string, userUuid: string,
projectUuid: string, projectUuid: string,
@ -295,6 +357,7 @@ export class VisitorPasswordService {
success: true, success: true,
result: createOnceOfflinePass.result, result: createOnceOfflinePass.result,
deviceUuid, deviceUuid,
deviceName: deviceDetails.name,
}; };
} catch (error) { } catch (error) {
return { return {
@ -357,7 +420,7 @@ export class VisitorPasswordService {
} }
} }
async addOfflineTemporaryPasswordTuya( private async addOfflineTemporaryPasswordTuya(
doorLockUuid: string, doorLockUuid: string,
type: string, type: string,
addDoorLockOfflineMultipleDto: AddDoorLockTemporaryPasswordDto, addDoorLockOfflineMultipleDto: AddDoorLockTemporaryPasswordDto,
@ -387,7 +450,7 @@ export class VisitorPasswordService {
); );
} }
} }
async addOnlineTemporaryPasswordMultipleTime( private async addOnlineTemporaryPasswordMultipleTime(
addDoorLockOnlineMultipleDto: AddDoorLockTemporaryPasswordDto, addDoorLockOnlineMultipleDto: AddDoorLockTemporaryPasswordDto,
userUuid: string, userUuid: string,
projectUuid: string, projectUuid: string,
@ -448,6 +511,7 @@ export class VisitorPasswordService {
success: true, success: true,
id: createPass.result.id, id: createPass.result.id,
deviceUuid, deviceUuid,
deviceName: passwordData.deviceName,
}; };
} catch (error) { } catch (error) {
return { return {
@ -508,67 +572,8 @@ export class VisitorPasswordService {
); );
} }
} }
async getPasswords(projectUuid: string) {
await this.validateProject(projectUuid);
const deviceIds = await this.deviceRepository.find({ private async addOnlineTemporaryPasswordOneTime(
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, addDoorLockOnlineOneTimeDto: AddDoorLockTemporaryPasswordDto,
userUuid: string, userUuid: string,
projectUuid: string, projectUuid: string,
@ -627,6 +632,7 @@ export class VisitorPasswordService {
return { return {
success: true, success: true,
id: createPass.result.id, id: createPass.result.id,
deviceName: passwordData.deviceName,
deviceUuid, deviceUuid,
}; };
} catch (error) { } catch (error) {
@ -688,7 +694,7 @@ export class VisitorPasswordService {
); );
} }
} }
async getTicketAndEncryptedPassword( private async getTicketAndEncryptedPassword(
doorLockUuid: string, doorLockUuid: string,
passwordPlan: string, passwordPlan: string,
projectUuid: string, projectUuid: string,
@ -725,6 +731,7 @@ export class VisitorPasswordService {
ticketKey: ticketDetails.result.ticket_key, ticketKey: ticketDetails.result.ticket_key,
encryptedPassword: decrypted, encryptedPassword: decrypted,
deviceTuyaUuid: deviceDetails.deviceTuyaUuid, deviceTuyaUuid: deviceDetails.deviceTuyaUuid,
deviceName: deviceDetails.name,
}; };
} catch (error) { } catch (error) {
throw new HttpException( throw new HttpException(
@ -734,7 +741,7 @@ export class VisitorPasswordService {
} }
} }
async createDoorLockTicketTuya( private async createDoorLockTicketTuya(
deviceUuid: string, deviceUuid: string,
): Promise<createTickInterface> { ): Promise<createTickInterface> {
try { try {
@ -753,7 +760,7 @@ export class VisitorPasswordService {
} }
} }
async addOnlineTemporaryPasswordMultipleTuya( private async addOnlineTemporaryPasswordMultipleTuya(
addDeviceObj: addDeviceObjectInterface, addDeviceObj: addDeviceObjectInterface,
doorLockUuid: string, doorLockUuid: string,
): Promise<createTickInterface> { ): Promise<createTickInterface> {
@ -795,7 +802,7 @@ export class VisitorPasswordService {
} }
} }
getWorkingDayValue(days) { private getWorkingDayValue(days) {
// Array representing the days of the week // Array representing the days of the week
const weekDays = [ const weekDays = [
DaysEnum.SAT, DaysEnum.SAT,
@ -827,36 +834,7 @@ export class VisitorPasswordService {
return workingDayValue; return workingDayValue;
} }
getDaysFromWorkingDayValue(workingDayValue) { private timeToMinutes(timeStr) {
// 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 { try {
// Special case for "24:00" // Special case for "24:00"
if (timeStr === CommonHours.TWENTY_FOUR) { if (timeStr === CommonHours.TWENTY_FOUR) {
@ -883,38 +861,7 @@ export class VisitorPasswordService {
throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR);
} }
} }
minutesToTime(totalMinutes) { private async getDeviceByDeviceUuid(
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, deviceUuid: string,
withProductDevice: boolean = true, withProductDevice: boolean = true,
projectUuid: string, projectUuid: string,
@ -939,7 +886,7 @@ export class VisitorPasswordService {
throw new HttpException('Device Not Found', HttpStatus.NOT_FOUND); throw new HttpException('Device Not Found', HttpStatus.NOT_FOUND);
} }
} }
async addOnlineTemporaryPasswordOneTimeTuya( private async addOnlineTemporaryPasswordOneTimeTuya(
addDeviceObj: addDeviceObjectInterface, addDeviceObj: addDeviceObjectInterface,
doorLockUuid: string, doorLockUuid: string,
): Promise<createTickInterface> { ): Promise<createTickInterface> {