Merge branch 'dev' of https://github.com/SyncrowIOT/backend into feature/space-management

This commit is contained in:
hannathkadher
2024-10-30 23:08:51 +04:00
35 changed files with 611 additions and 42 deletions

View File

@ -0,0 +1,2 @@
export const defaultSceneIcon =
'iVBORw0KGgoAAAANSUhEUgAAAEYAAABGCAYAAABxLuKEAAAACXBIWXMAABYlAAAWJQFJUiTwAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAh9SURBVHgB3ZxfbFtXHce/59xrO7GTkLZUA6KpAa1aM62a80AZAymuxgs8sOZhvC7lCQkk2geg2UBJJMTgqZ2EBG/JkICtrdR24gGJSkklGgo8zBsP7WilOava/enauEsbx/a95+z3u+5N/D++9r3+k4+U2Nc+vvb9+vv7nd85514LtJH9f34QN2Q4rgXikHqfgIg7TwiMljTUSEml01qLtGGpd8wNpEKfWEv/fWUgiTYhECCj83q4fyA7pSFfoDeKa2AYTSKURngdaTOrlyKruQsK9tKV6V0pBEQgwhz4ayYB05ihuwkEgJHX6F+1IXP6vJGxX//Xy0Pn4TO+CnPgdG6KbmYqQiMgWKDImkLfqkpB23PL00ML8AlfhHEcYhjz7RKkHBYodseGmdG+CdSSMCTIKIXMPAIKGa9E79kUYopyNxaUzs21koOaFmbszMYxQM60klCDgJIzBj+yIPNIa9jHm3WPZ2EKPU2eBTmGLoVDa+g2iWPRhtCnLv9i4Dg84kkYDh1tGOcE1yFdTok4GkkbuUkvodWwME4+MYzFTiXYZigWhxyeorxzuFFxGhKmF0VxaVYcuV2DXhaFsUMCa18ynfvkglEpwovPvro6ut3rthWGc0qviuJiRQQe7ikcKotjIHwuMbtatzetK8zYmdzJXki0jbAxbCDf/yhz0DHl+0Mz9drXFIbL+27ukpvh4V4D2j1iLY598zcPah5f1eTLeUWYxtvdVrz5QV/aRuyuKmxo0FZuvFoyru4YKWf9FiVqoivgkFLuZxEYNkRovlq7Csc4I2SBefjE1/cK/OQpiUN7JTboi7p8V+MvN2ws39LoFOGHioYN9ua20OrwP6cHl4rb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oUWzun3jjARM7KwYeVPogtwXXIj428eqUUoU7pvBWOJbx1hkpMifeBMjh9IoIO4LrnyscIbV3k9O9hCIpQhGYpE11pduDIdS/H9osrXnqNUlEAHcF2y+HEweaQW4bKxlJZ6wb1ferbD2dz7lH1G4QMjtJB18bvbjzjYJe8+AE7/36aZ/2DySC2GV6xNx1DflFo+Ed08FaT0kyvM+XUayK2H2kmcI9Hqz7su+ePV4PNINSKflYYRjQPmip+vPKPKR9ccorWl16usLbFL/nZb4w/v2oHnkVrUcwtTOR+j7aPwif/c0XjpkoVr6cIH4M/x9w8Lj/3631bHRNnOLUz1szbP5BYRQA8VpWm2dodMNUrdgoXlE7EKM1SfwTPtozwnAZ/pBlH67he5hY5RaTlXrV1VYa5N9qdUFXv1OjwhxefeuWilj1+Z7k9VbVtrJ++92HeKXPMadhB85e1mCGn92vL0wEKttnUnwyNGaFb02HxNLaIkSt+ae0a4SJIodS8HqCsMDxW0aU9SLKbQw5hZcsu9gijcNdsQk9u9ZtvlE843MOzDvSoO55WBjwoz5SyK0uJwrbxSTOOX/p3LjMI2Fv0q/toBi8JXt3Fe8SKK81o0iOucXsk5xaJwTvEiCtPUwiZNhZ6iWb+fokspcQr1PuFsbHZpVniqy5pe8eXrDoTEyW6bK+ZEyznFsHUatp67/PLAKTRBaz9hwHnHkrO0m5fQBXBVG/vUZpdcovp2ykvolOPPj17wVSsSM51KzE7Pc8eCmUFK0iC4/NqjZvD/Z1LaKBAve7BLqMxPCVvN1atkPe8bATB21jpC0xdT1EUGcn3CliDWJcols344pOI9ECBODsobCSH0EQgx0UqiZjHC6zodemC/E1pX5yOZ2ILXnsbT+6GNPHUuF9eWStBQf5R/swrOGaN6uOI8QK1XhO18uKS0dMq0dDJ6x04u/7x9P971OV/Bx65CjlpJAAAAAElFTkSuQmCC';

View File

@ -15,4 +15,5 @@ export enum ProductType {
WL = 'WL',
GD = 'GD',
CUR = 'CUR',
PC = 'PC',
}

View File

@ -0,0 +1,4 @@
export enum SceneIconType {
Default = 'default',
Other = 'other',
}

View File

@ -0,0 +1,7 @@
export enum SourceType {
Device = 1,
Client = 2,
ThirdParty = 3,
Cloud = 4,
Unknown = -1,
}

View File

@ -20,6 +20,8 @@ import { RegionEntity } from '../modules/region/entities';
import { TimeZoneEntity } from '../modules/timezone/entities';
import { VisitorPasswordEntity } from '../modules/visitor-password/entities';
import { CommunityEntity } from '../modules/community/entities';
import { DeviceStatusLogEntity } from '../modules/device-status-log/entities';
import { SceneEntity, SceneIconEntity } from '../modules/scene/entities';
@Module({
imports: [
@ -55,6 +57,9 @@ import { CommunityEntity } from '../modules/community/entities';
RegionEntity,
TimeZoneEntity,
VisitorPasswordEntity,
DeviceStatusLogEntity,
SceneEntity,
SceneIconEntity,
],
namingStrategy: new SnakeNamingStrategy(),
synchronize: Boolean(JSON.parse(configService.get('DB_SYNC'))),

View File

@ -2,10 +2,15 @@ import { Module } from '@nestjs/common';
import { DeviceStatusFirebaseController } from './controllers/devices-status.controller';
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';
@Module({
providers: [DeviceStatusFirebaseService, DeviceRepository],
providers: [
DeviceStatusFirebaseService,
DeviceRepository,
DeviceStatusLogRepository,
],
controllers: [DeviceStatusFirebaseController],
exports: [DeviceStatusFirebaseService],
exports: [DeviceStatusFirebaseService, DeviceStatusLogRepository],
})
export class DeviceStatusFirebaseModule {}

View File

@ -35,4 +35,7 @@ export class AddDeviceStatusDto {
@ValidateNested({ each: true })
@Type(() => StatusDto)
status: StatusDto[];
@IsOptional()
log?: any;
}

View File

@ -11,6 +11,7 @@ import { TuyaContext } from '@tuya/tuya-connector-nodejs';
import { ConfigService } from '@nestjs/config';
import { firebaseDataBase } from '../../firebase.config';
import { Database, DataSnapshot, get, ref, set } from 'firebase/database';
import { DeviceStatusLogRepository } from '@app/common/modules/device-status-log/repositories';
@Injectable()
export class DeviceStatusFirebaseService {
private tuya: TuyaContext;
@ -18,6 +19,7 @@ export class DeviceStatusFirebaseService {
constructor(
private readonly configService: ConfigService,
private readonly deviceRepository: DeviceRepository,
private deviceStatusLogRepository: DeviceStatusLogRepository,
) {
const accessKey = this.configService.get<string>('auth-config.ACCESS_KEY');
const secretKey = this.configService.get<string>('auth-config.SECRET_KEY');
@ -175,6 +177,7 @@ export class DeviceStatusFirebaseService {
);
// Update or add status codes
for (const statusItem of addDeviceStatusDto.status) {
statusMap.set(statusItem.code, statusItem.value);
}
@ -184,7 +187,19 @@ export class DeviceStatusFirebaseService {
code,
value,
}));
const newLog = this.deviceStatusLogRepository.create({
deviceId: addDeviceStatusDto.deviceUuid,
deviceTuyaId: addDeviceStatusDto.deviceTuyaUuid,
productId: addDeviceStatusDto.log.productId,
log: addDeviceStatusDto.log,
code: existingData.status[0].code,
value: existingData.status[0].value,
eventId: addDeviceStatusDto.log.dataId,
eventTime: new Date(
addDeviceStatusDto.log.properties[0].time,
).toISOString(),
});
await this.deviceStatusLogRepository.save(newLog);
// Save the updated data to Firebase
await set(dataRef, existingData);

View File

@ -16,7 +16,7 @@ export class TuyaWebSocketService {
accessId: this.configService.get<string>('tuya-config.TUYA_ACCESS_ID'),
accessKey: this.configService.get<string>('tuya-config.TUYA_ACCESS_KEY'),
url: TuyaWebsocket.URL.EU,
env: TuyaWebsocket.env.TEST,
env: TuyaWebsocket.env.PROD,
maxRetryTimes: 100,
});
@ -40,6 +40,7 @@ export class TuyaWebSocketService {
await this.deviceStatusFirebaseService.addDeviceStatusToFirebase({
deviceTuyaUuid: message.payload.data.bizData.devId,
status: message.payload.data.bizData.properties,
log: message.payload.data.bizData,
});
this.client.ackMessage(message.messageId);

View File

@ -0,0 +1,43 @@
import { SourceType } from '@app/common/constants/source-type.enum';
import { Entity, Column, PrimaryColumn, Unique } from 'typeorm';
@Entity('device-status-log')
@Unique('event_time_idx', ['eventTime'])
export class DeviceStatusLogEntity {
@Column({ type: 'int', generated: true, unsigned: true })
id: number;
@Column({ type: 'text' })
eventId: string;
@PrimaryColumn({ type: 'timestamptz' })
eventTime: Date;
@Column({
type: 'enum',
enum: SourceType,
default: SourceType.Device,
})
eventFrom: SourceType;
@Column({ type: 'text' })
deviceId: string;
@Column({ type: 'text' })
deviceTuyaId: string;
@Column({ type: 'text' })
productId: string;
@Column({ type: 'text' })
code: any;
@Column({ type: 'text' })
value: any;
@Column({ type: 'jsonb' })
log: any;
@Column({ type: 'timestamptz', default: new Date() })
ingestionTime: Date;
}

View File

@ -0,0 +1 @@
export * from './device-status-log.entity';

View File

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

View File

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

View File

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

View File

@ -0,0 +1,30 @@
import { IsBoolean, IsNotEmpty, IsString } from 'class-validator';
export class SceneDto {
@IsString()
@IsNotEmpty()
public uuid: string;
@IsString()
@IsNotEmpty()
public sceneTuyaUuid: string;
@IsString()
@IsNotEmpty()
public unitUuid: string;
@IsString()
@IsNotEmpty()
public iconUuid: string;
@IsBoolean()
@IsNotEmpty()
public inHomePage: boolean;
}
export class SceneIconDto {
@IsString()
@IsNotEmpty()
public uuid: string;
@IsString()
@IsNotEmpty()
public icon: string;
}

View File

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

View File

@ -0,0 +1,65 @@
import { Column, Entity, ManyToOne, OneToMany } from 'typeorm';
import { SceneDto, SceneIconDto } from '../dtos';
import { AbstractEntity } from '../../abstract/entities/abstract.entity';
import { SceneIconType } from '@app/common/constants/secne-icon-type.enum';
// Define SceneIconEntity before SceneEntity
@Entity({ name: 'scene-icon' })
export class SceneIconEntity extends AbstractEntity<SceneIconDto> {
@Column({
nullable: true,
type: 'text',
})
public icon: string;
@Column({
type: 'enum',
enum: SceneIconType,
default: SceneIconType.Other,
})
iconType: SceneIconType;
@OneToMany(
() => SceneEntity,
(scenesIconEntity) => scenesIconEntity.sceneIcon,
)
scenesIconEntity: SceneEntity[];
constructor(partial: Partial<SceneIconEntity>) {
super();
Object.assign(this, partial);
}
}
@Entity({ name: 'scene' })
export class SceneEntity extends AbstractEntity<SceneDto> {
@Column({
type: 'uuid',
default: () => 'gen_random_uuid()',
nullable: false,
})
public uuid: string;
@Column({
nullable: false,
})
sceneTuyaUuid: string;
@Column({
nullable: false,
})
unitUuid: string;
@Column({
nullable: false,
})
showInHomePage: boolean;
@ManyToOne(() => SceneIconEntity, (icon) => icon.scenesIconEntity, {
nullable: false,
})
sceneIcon: SceneIconEntity;
constructor(partial: Partial<SceneEntity>) {
super();
Object.assign(this, partial);
}
}

View File

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

View File

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

View File

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

View File

@ -18,6 +18,8 @@ import { RegionSeeder } from './services/regions.seeder';
import { RegionRepository } from '../modules/region/repositories';
import { TimeZoneSeeder } from './services/timezone.seeder';
import { TimeZoneRepository } from '../modules/timezone/repositories';
import { SceneIconSeeder } from './services/scene.icon.seeder';
import { SceneIconRepository } from '../modules/scene/repositories';
@Global()
@Module({
providers: [
@ -35,6 +37,8 @@ import { TimeZoneRepository } from '../modules/timezone/repositories';
RegionRepository,
TimeZoneSeeder,
TimeZoneRepository,
SceneIconSeeder,
SceneIconRepository,
],
exports: [SeederService],
controllers: [],

View File

@ -0,0 +1,38 @@
import { Injectable } from '@nestjs/common';
import { SceneIconRepository } from '@app/common/modules/scene/repositories';
import { SceneIconType } from '@app/common/constants/secne-icon-type.enum';
import { defaultSceneIcon } from '@app/common/constants/default.scene.icon';
@Injectable()
export class SceneIconSeeder {
constructor(private readonly sceneIconRepository: SceneIconRepository) {}
async createSceneDefaultIconIfNotFound(): Promise<void> {
try {
const defaultSceneIconData = await this.sceneIconRepository.find({
where: { iconType: SceneIconType.Default },
});
if (defaultSceneIconData.length <= 0) {
console.log('Creating default scene icon...');
await this.createDefaultSceneIcon();
}
} catch (err) {
console.error('Error while checking default scene icon:', err);
throw err;
}
}
private async createDefaultSceneIcon(): Promise<void> {
try {
await this.sceneIconRepository.save({
icon: defaultSceneIcon,
iconType: SceneIconType.Default,
});
} catch (err) {
console.error('Error while creating default scene icon:', err);
throw err;
}
}
}

View File

@ -5,6 +5,7 @@ import { SpaceTypeSeeder } from './space.type.seeder';
import { SuperAdminSeeder } from './supper.admin.seeder';
import { RegionSeeder } from './regions.seeder';
import { TimeZoneSeeder } from './timezone.seeder';
import { SceneIconSeeder } from './scene.icon.seeder';
@Injectable()
export class SeederService {
constructor(
@ -14,6 +15,7 @@ export class SeederService {
private readonly regionSeeder: RegionSeeder,
private readonly timeZoneSeeder: TimeZoneSeeder,
private readonly superAdminSeeder: SuperAdminSeeder,
private readonly sceneIconSeeder: SceneIconSeeder,
) {}
async seed() {
@ -23,5 +25,6 @@ export class SeederService {
await this.regionSeeder.addRegionDataIfNotFound();
await this.timeZoneSeeder.addTimeZoneDataIfNotFound();
await this.superAdminSeeder.createSuperAdminIfNotFound();
await this.sceneIconSeeder.createSceneDefaultIconIfNotFound();
}
}