mirror of
https://github.com/SyncrowIOT/backend.git
synced 2025-11-26 08:54:54 +00:00
Merge pull request #23 from SyncrowIOT/feat/device_permissions
Feat/device permissions
This commit is contained in:
@ -1,28 +1,28 @@
|
||||
import { PassportModule } from '@nestjs/passport';
|
||||
import { JwtModule } from '@nestjs/jwt';
|
||||
import { ConfigModule, ConfigService } from '@nestjs/config';
|
||||
import { ConfigModule } from '@nestjs/config';
|
||||
import { Module } from '@nestjs/common';
|
||||
import { HelperModule } from '../helper/helper.module';
|
||||
import { JwtStrategy } from './strategies/jwt.strategy';
|
||||
import { UserSessionRepository } from '../modules/session/repositories/session.repository';
|
||||
import { AuthService } from './services/auth.service';
|
||||
import { UserRepository } from '../modules/user/repositories';
|
||||
import { RefreshTokenStrategy } from './strategies/refresh-token.strategy';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
ConfigModule.forRoot(),
|
||||
PassportModule,
|
||||
JwtModule.registerAsync({
|
||||
imports: [ConfigModule],
|
||||
inject: [ConfigService],
|
||||
useFactory: async (configService: ConfigService) => ({
|
||||
secret: configService.get('JWT_SECRET'),
|
||||
signOptions: { expiresIn: configService.get('JWT_EXPIRE_TIME') },
|
||||
}),
|
||||
}),
|
||||
JwtModule.register({}),
|
||||
HelperModule,
|
||||
],
|
||||
providers: [JwtStrategy, UserSessionRepository, AuthService, UserRepository],
|
||||
providers: [
|
||||
JwtStrategy,
|
||||
RefreshTokenStrategy,
|
||||
UserSessionRepository,
|
||||
AuthService,
|
||||
UserRepository,
|
||||
],
|
||||
exports: [AuthService],
|
||||
})
|
||||
export class AuthModule {}
|
||||
|
||||
@ -1,9 +1,11 @@
|
||||
import { BadRequestException, Injectable } from '@nestjs/common';
|
||||
import { JwtService } from '@nestjs/jwt';
|
||||
import * as argon2 from 'argon2';
|
||||
import { HelperHashService } from '../../helper/services';
|
||||
import { UserRepository } from '../../../../common/src/modules/user/repositories';
|
||||
import { UserSessionRepository } from '../../../../common/src/modules/session/repositories/session.repository';
|
||||
import { UserSessionEntity } from '../../../../common/src/modules/session/entities';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
|
||||
@Injectable()
|
||||
export class AuthService {
|
||||
@ -12,6 +14,7 @@ export class AuthService {
|
||||
private readonly userRepository: UserRepository,
|
||||
private readonly sessionRepository: UserSessionRepository,
|
||||
private readonly helperHashService: HelperHashService,
|
||||
private readonly configService: ConfigService,
|
||||
) {}
|
||||
|
||||
async validateUser(email: string, pass: string): Promise<any> {
|
||||
@ -40,6 +43,24 @@ export class AuthService {
|
||||
return await this.sessionRepository.save(data);
|
||||
}
|
||||
|
||||
async getTokens(payload) {
|
||||
const [accessToken, refreshToken] = await Promise.all([
|
||||
this.jwtService.signAsync(payload, {
|
||||
secret: this.configService.get<string>('JWT_SECRET'),
|
||||
expiresIn: '24h',
|
||||
}),
|
||||
this.jwtService.signAsync(payload, {
|
||||
secret: this.configService.get<string>('JWT_SECRET'),
|
||||
expiresIn: '7d',
|
||||
}),
|
||||
]);
|
||||
|
||||
return {
|
||||
accessToken,
|
||||
refreshToken,
|
||||
};
|
||||
}
|
||||
|
||||
async login(user: any) {
|
||||
const payload = {
|
||||
email: user.email,
|
||||
@ -48,8 +69,22 @@ export class AuthService {
|
||||
type: user.type,
|
||||
sessionId: user.sessionId,
|
||||
};
|
||||
return {
|
||||
access_token: this.jwtService.sign(payload),
|
||||
};
|
||||
const tokens = await this.getTokens(payload);
|
||||
await this.updateRefreshToken(user.uuid, tokens.refreshToken);
|
||||
return tokens;
|
||||
}
|
||||
|
||||
async updateRefreshToken(userId: string, refreshToken: string) {
|
||||
const hashedRefreshToken = await this.hashData(refreshToken);
|
||||
await this.userRepository.update(
|
||||
{ uuid: userId },
|
||||
{
|
||||
refreshToken: hashedRefreshToken,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
hashData(data: string) {
|
||||
return argon2.hash(data);
|
||||
}
|
||||
}
|
||||
|
||||
@ -6,7 +6,7 @@ import { UserSessionRepository } from '../../../src/modules/session/repositories
|
||||
import { AuthInterface } from '../interfaces/auth.interface';
|
||||
|
||||
@Injectable()
|
||||
export class JwtStrategy extends PassportStrategy(Strategy) {
|
||||
export class JwtStrategy extends PassportStrategy(Strategy, 'jwt') {
|
||||
constructor(
|
||||
private readonly sessionRepository: UserSessionRepository,
|
||||
private readonly configService: ConfigService,
|
||||
|
||||
42
libs/common/src/auth/strategies/refresh-token.strategy.ts
Normal file
42
libs/common/src/auth/strategies/refresh-token.strategy.ts
Normal file
@ -0,0 +1,42 @@
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { ExtractJwt, Strategy } from 'passport-jwt';
|
||||
import { PassportStrategy } from '@nestjs/passport';
|
||||
import { BadRequestException, Injectable } from '@nestjs/common';
|
||||
import { UserSessionRepository } from '../../../src/modules/session/repositories/session.repository';
|
||||
import { AuthInterface } from '../interfaces/auth.interface';
|
||||
|
||||
@Injectable()
|
||||
export class RefreshTokenStrategy extends PassportStrategy(
|
||||
Strategy,
|
||||
'jwt-refresh',
|
||||
) {
|
||||
constructor(
|
||||
private readonly sessionRepository: UserSessionRepository,
|
||||
private readonly configService: ConfigService,
|
||||
) {
|
||||
super({
|
||||
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
|
||||
ignoreExpiration: false,
|
||||
secretOrKey: configService.get('JWT_SECRET'),
|
||||
});
|
||||
}
|
||||
|
||||
async validate(payload: AuthInterface) {
|
||||
const validateUser = await this.sessionRepository.findOne({
|
||||
where: {
|
||||
uuid: payload.sessionId,
|
||||
isLoggedOut: false,
|
||||
},
|
||||
});
|
||||
if (validateUser) {
|
||||
return {
|
||||
email: payload.email,
|
||||
userId: payload.id,
|
||||
uuid: payload.uuid,
|
||||
sessionId: payload.sessionId,
|
||||
};
|
||||
} else {
|
||||
throw new BadRequestException('Unauthorized');
|
||||
}
|
||||
}
|
||||
}
|
||||
4
libs/common/src/constants/permission-type.enum.ts
Normal file
4
libs/common/src/constants/permission-type.enum.ts
Normal file
@ -0,0 +1,4 @@
|
||||
export enum PermissionType {
|
||||
READ = 'READ',
|
||||
CONTROLLABLE = 'CONTROLLABLE',
|
||||
}
|
||||
@ -7,8 +7,16 @@ import { UserSessionEntity } from '../modules/session/entities/session.entity';
|
||||
import { UserOtpEntity } from '../modules/user-otp/entities';
|
||||
import { HomeEntity } from '../modules/home/entities';
|
||||
import { ProductEntity } from '../modules/product/entities';
|
||||
import {
|
||||
DeviceEntity,
|
||||
DeviceUserPermissionEntity,
|
||||
} from '../modules/device/entities';
|
||||
import { PermissionTypeEntity } from '../modules/permission/entities';
|
||||
import { SpaceEntity } from '../modules/space/entities';
|
||||
import { SpaceTypeEntity } from '../modules/space-type/entities';
|
||||
import { UserSpaceEntity } from '../modules/user-space/entities';
|
||||
import { GroupEntity } from '../modules/group/entities';
|
||||
import { GroupDeviceEntity } from '../modules/group-device/entities';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
@ -29,8 +37,14 @@ import { SpaceTypeEntity } from '../modules/space-type/entities';
|
||||
UserOtpEntity,
|
||||
HomeEntity,
|
||||
ProductEntity,
|
||||
DeviceUserPermissionEntity,
|
||||
DeviceEntity,
|
||||
PermissionTypeEntity,
|
||||
SpaceEntity,
|
||||
SpaceTypeEntity,
|
||||
UserSpaceEntity,
|
||||
GroupEntity,
|
||||
GroupDeviceEntity,
|
||||
],
|
||||
namingStrategy: new SnakeNamingStrategy(),
|
||||
synchronize: Boolean(JSON.parse(configService.get('DB_SYNC'))),
|
||||
|
||||
11
libs/common/src/guards/jwt-refresh.auth.guard.ts
Normal file
11
libs/common/src/guards/jwt-refresh.auth.guard.ts
Normal file
@ -0,0 +1,11 @@
|
||||
import { UnauthorizedException } from '@nestjs/common';
|
||||
import { AuthGuard } from '@nestjs/passport';
|
||||
|
||||
export class RefreshTokenGuard extends AuthGuard('jwt-refresh') {
|
||||
handleRequest(err, user) {
|
||||
if (err || !user) {
|
||||
throw err || new UnauthorizedException();
|
||||
}
|
||||
return user;
|
||||
}
|
||||
}
|
||||
13
libs/common/src/modules/device/device.repository.module.ts
Normal file
13
libs/common/src/modules/device/device.repository.module.ts
Normal file
@ -0,0 +1,13 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { DeviceEntity, DeviceUserPermissionEntity } from './entities';
|
||||
|
||||
@Module({
|
||||
providers: [],
|
||||
exports: [],
|
||||
controllers: [],
|
||||
imports: [
|
||||
TypeOrmModule.forFeature([DeviceEntity, DeviceUserPermissionEntity]),
|
||||
],
|
||||
})
|
||||
export class DeviceRepositoryModule {}
|
||||
19
libs/common/src/modules/device/dtos/device-user-type.dto.ts
Normal file
19
libs/common/src/modules/device/dtos/device-user-type.dto.ts
Normal file
@ -0,0 +1,19 @@
|
||||
import { IsNotEmpty, IsString } from 'class-validator';
|
||||
|
||||
export class DeviceUserTypeDto {
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
public uuid: string;
|
||||
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
public userUuid: string;
|
||||
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
public deviceUuid: string;
|
||||
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
public permissionTypeUuid: string;
|
||||
}
|
||||
19
libs/common/src/modules/device/dtos/device.dto.ts
Normal file
19
libs/common/src/modules/device/dtos/device.dto.ts
Normal file
@ -0,0 +1,19 @@
|
||||
import { IsNotEmpty, IsString } from 'class-validator';
|
||||
|
||||
export class DeviceDto {
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
public uuid: string;
|
||||
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
spaceUuid: string;
|
||||
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
deviceTuyaUuid: string;
|
||||
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
productUuid: string;
|
||||
}
|
||||
2
libs/common/src/modules/device/dtos/index.ts
Normal file
2
libs/common/src/modules/device/dtos/index.ts
Normal file
@ -0,0 +1,2 @@
|
||||
export * from './device.dto';
|
||||
export * from './device-user-type.dto';
|
||||
@ -0,0 +1,42 @@
|
||||
import { Column, Entity, JoinColumn, ManyToOne } from 'typeorm';
|
||||
import { AbstractEntity } from '../../abstract/entities/abstract.entity';
|
||||
import { DeviceUserTypeDto } from '../dtos/device-user-type.dto';
|
||||
import { DeviceEntity } from './device.entity';
|
||||
import { PermissionTypeEntity } from '../../permission/entities';
|
||||
|
||||
@Entity({ name: 'device-user-permission' })
|
||||
export class DeviceUserPermissionEntity extends AbstractEntity<DeviceUserTypeDto> {
|
||||
@Column({
|
||||
nullable: false,
|
||||
})
|
||||
public userUuid: string;
|
||||
|
||||
@Column({
|
||||
nullable: false,
|
||||
})
|
||||
deviceUuid: string;
|
||||
|
||||
@Column({
|
||||
nullable: false,
|
||||
})
|
||||
public permissionTypeUuid: string;
|
||||
|
||||
@ManyToOne(() => DeviceEntity, {
|
||||
onDelete: 'CASCADE',
|
||||
onUpdate: 'CASCADE',
|
||||
})
|
||||
@JoinColumn({ name: 'device_uuid', referencedColumnName: 'uuid' })
|
||||
device: DeviceEntity;
|
||||
|
||||
@ManyToOne(() => PermissionTypeEntity, {
|
||||
onDelete: 'CASCADE',
|
||||
onUpdate: 'CASCADE',
|
||||
})
|
||||
@JoinColumn({ name: 'permission_type_uuid', referencedColumnName: 'uuid' })
|
||||
type: PermissionTypeEntity;
|
||||
|
||||
constructor(partial: Partial<DeviceUserPermissionEntity>) {
|
||||
super();
|
||||
Object.assign(this, partial);
|
||||
}
|
||||
}
|
||||
51
libs/common/src/modules/device/entities/device.entity.ts
Normal file
51
libs/common/src/modules/device/entities/device.entity.ts
Normal file
@ -0,0 +1,51 @@
|
||||
import { Column, Entity, OneToMany } from 'typeorm';
|
||||
import { AbstractEntity } from '../../abstract/entities/abstract.entity';
|
||||
import { DeviceDto } from '../dtos/device.dto';
|
||||
import { DeviceUserPermissionEntity } from './device-user-type.entity';
|
||||
import { GroupDeviceEntity } from '../../group-device/entities';
|
||||
|
||||
@Entity({ name: 'device' })
|
||||
export class DeviceEntity extends AbstractEntity<DeviceDto> {
|
||||
@Column({
|
||||
nullable: false,
|
||||
})
|
||||
public spaceUuid: string;
|
||||
|
||||
@Column({
|
||||
nullable: false,
|
||||
})
|
||||
deviceTuyaUuid: string;
|
||||
|
||||
@Column({
|
||||
nullable: false,
|
||||
})
|
||||
public productUuid: string;
|
||||
|
||||
@Column({
|
||||
nullable: true,
|
||||
default: true,
|
||||
})
|
||||
isActive: true;
|
||||
|
||||
@OneToMany(
|
||||
() => DeviceUserPermissionEntity,
|
||||
(permission) => permission.device,
|
||||
{
|
||||
nullable: true,
|
||||
onDelete: 'CASCADE',
|
||||
onUpdate: 'CASCADE',
|
||||
},
|
||||
)
|
||||
permission: DeviceUserPermissionEntity[];
|
||||
|
||||
@OneToMany(
|
||||
() => GroupDeviceEntity,
|
||||
(userGroupDevices) => userGroupDevices.device,
|
||||
)
|
||||
userGroupDevices: GroupDeviceEntity[];
|
||||
|
||||
constructor(partial: Partial<DeviceEntity>) {
|
||||
super();
|
||||
Object.assign(this, partial);
|
||||
}
|
||||
}
|
||||
2
libs/common/src/modules/device/entities/index.ts
Normal file
2
libs/common/src/modules/device/entities/index.ts
Normal file
@ -0,0 +1,2 @@
|
||||
export * from './device.entity';
|
||||
export * from './device-user-type.entity';
|
||||
1
libs/common/src/modules/device/index.ts
Normal file
1
libs/common/src/modules/device/index.ts
Normal file
@ -0,0 +1 @@
|
||||
export * from './device.repository.module';
|
||||
@ -0,0 +1,10 @@
|
||||
import { DataSource, Repository } from 'typeorm';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { DeviceUserPermissionEntity } from '../entities';
|
||||
|
||||
@Injectable()
|
||||
export class DeviceUserTypeRepository extends Repository<DeviceUserPermissionEntity> {
|
||||
constructor(private dataSource: DataSource) {
|
||||
super(DeviceUserPermissionEntity, dataSource.createEntityManager());
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,10 @@
|
||||
import { DataSource, Repository } from 'typeorm';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { DeviceEntity } from '../entities';
|
||||
|
||||
@Injectable()
|
||||
export class DeviceRepository extends Repository<DeviceEntity> {
|
||||
constructor(private dataSource: DataSource) {
|
||||
super(DeviceEntity, dataSource.createEntityManager());
|
||||
}
|
||||
}
|
||||
2
libs/common/src/modules/device/repositories/index.ts
Normal file
2
libs/common/src/modules/device/repositories/index.ts
Normal file
@ -0,0 +1,2 @@
|
||||
export * from './device.repository';
|
||||
export * from './device-user-type.repository';
|
||||
@ -0,0 +1,15 @@
|
||||
import { IsNotEmpty, IsString } from 'class-validator';
|
||||
|
||||
export class GroupDeviceDto {
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
public uuid: string;
|
||||
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
public deviceUuid: string;
|
||||
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
public groupUuid: string;
|
||||
}
|
||||
1
libs/common/src/modules/group-device/dtos/index.ts
Normal file
1
libs/common/src/modules/group-device/dtos/index.ts
Normal file
@ -0,0 +1 @@
|
||||
export * from './group.device.dto';
|
||||
@ -0,0 +1,48 @@
|
||||
import { Column, Entity, ManyToOne, Unique } from 'typeorm';
|
||||
import { GroupDeviceDto } from '../dtos';
|
||||
import { AbstractEntity } from '../../abstract/entities/abstract.entity';
|
||||
import { DeviceEntity } from '../../device/entities';
|
||||
import { GroupEntity } from '../../group/entities';
|
||||
|
||||
@Entity({ name: 'group-device' })
|
||||
@Unique(['device', 'group'])
|
||||
export class GroupDeviceEntity extends AbstractEntity<GroupDeviceDto> {
|
||||
@Column({
|
||||
type: 'uuid',
|
||||
default: () => 'gen_random_uuid()', // Use gen_random_uuid() for default value
|
||||
nullable: false,
|
||||
})
|
||||
public uuid: string;
|
||||
|
||||
@Column({
|
||||
type: 'string',
|
||||
nullable: false,
|
||||
})
|
||||
deviceUuid: string;
|
||||
|
||||
@Column({
|
||||
type: 'string',
|
||||
nullable: false,
|
||||
})
|
||||
groupUuid: string;
|
||||
|
||||
@ManyToOne(() => DeviceEntity, (device) => device.userGroupDevices, {
|
||||
nullable: false,
|
||||
})
|
||||
device: DeviceEntity;
|
||||
|
||||
@ManyToOne(() => GroupEntity, (group) => group.groupDevices, {
|
||||
nullable: false,
|
||||
})
|
||||
group: GroupEntity;
|
||||
|
||||
@Column({
|
||||
nullable: true,
|
||||
default: true,
|
||||
})
|
||||
public isActive: boolean;
|
||||
constructor(partial: Partial<GroupDeviceEntity>) {
|
||||
super();
|
||||
Object.assign(this, partial);
|
||||
}
|
||||
}
|
||||
1
libs/common/src/modules/group-device/entities/index.ts
Normal file
1
libs/common/src/modules/group-device/entities/index.ts
Normal file
@ -0,0 +1 @@
|
||||
export * from './group.device.entity';
|
||||
@ -0,0 +1,11 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { GroupDeviceEntity } from './entities/group.device.entity';
|
||||
|
||||
@Module({
|
||||
providers: [],
|
||||
exports: [],
|
||||
controllers: [],
|
||||
imports: [TypeOrmModule.forFeature([GroupDeviceEntity])],
|
||||
})
|
||||
export class GroupDeviceRepositoryModule {}
|
||||
@ -0,0 +1,10 @@
|
||||
import { DataSource, Repository } from 'typeorm';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { GroupDeviceEntity } from '../entities/group.device.entity';
|
||||
|
||||
@Injectable()
|
||||
export class GroupDeviceRepository extends Repository<GroupDeviceEntity> {
|
||||
constructor(private dataSource: DataSource) {
|
||||
super(GroupDeviceEntity, dataSource.createEntityManager());
|
||||
}
|
||||
}
|
||||
@ -0,0 +1 @@
|
||||
export * from './group.device.repository';
|
||||
11
libs/common/src/modules/group/dtos/group.dto.ts
Normal file
11
libs/common/src/modules/group/dtos/group.dto.ts
Normal file
@ -0,0 +1,11 @@
|
||||
import { IsNotEmpty, IsString } from 'class-validator';
|
||||
|
||||
export class GroupDto {
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
public uuid: string;
|
||||
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
public groupName: string;
|
||||
}
|
||||
1
libs/common/src/modules/group/dtos/index.ts
Normal file
1
libs/common/src/modules/group/dtos/index.ts
Normal file
@ -0,0 +1 @@
|
||||
export * from './group.dto';
|
||||
35
libs/common/src/modules/group/entities/group.entity.ts
Normal file
35
libs/common/src/modules/group/entities/group.entity.ts
Normal file
@ -0,0 +1,35 @@
|
||||
import { Column, Entity, OneToMany } from 'typeorm';
|
||||
import { GroupDto } from '../dtos';
|
||||
import { AbstractEntity } from '../../abstract/entities/abstract.entity';
|
||||
import { GroupDeviceEntity } from '../../group-device/entities';
|
||||
|
||||
@Entity({ name: 'group' })
|
||||
export class GroupEntity extends AbstractEntity<GroupDto> {
|
||||
@Column({
|
||||
type: 'uuid',
|
||||
default: () => 'gen_random_uuid()', // Use gen_random_uuid() for default value
|
||||
nullable: false,
|
||||
})
|
||||
public uuid: string;
|
||||
|
||||
@Column({
|
||||
nullable: false,
|
||||
})
|
||||
public groupName: string;
|
||||
|
||||
@OneToMany(() => GroupDeviceEntity, (groupDevice) => groupDevice.group, {
|
||||
cascade: true,
|
||||
onDelete: 'CASCADE',
|
||||
})
|
||||
groupDevices: GroupDeviceEntity[];
|
||||
|
||||
@Column({
|
||||
nullable: true,
|
||||
default: true,
|
||||
})
|
||||
public isActive: boolean;
|
||||
constructor(partial: Partial<GroupEntity>) {
|
||||
super();
|
||||
Object.assign(this, partial);
|
||||
}
|
||||
}
|
||||
1
libs/common/src/modules/group/entities/index.ts
Normal file
1
libs/common/src/modules/group/entities/index.ts
Normal file
@ -0,0 +1 @@
|
||||
export * from './group.entity';
|
||||
11
libs/common/src/modules/group/group.repository.module.ts
Normal file
11
libs/common/src/modules/group/group.repository.module.ts
Normal file
@ -0,0 +1,11 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { GroupEntity } from './entities/group.entity';
|
||||
|
||||
@Module({
|
||||
providers: [],
|
||||
exports: [],
|
||||
controllers: [],
|
||||
imports: [TypeOrmModule.forFeature([GroupEntity])],
|
||||
})
|
||||
export class GroupRepositoryModule {}
|
||||
@ -0,0 +1,10 @@
|
||||
import { DataSource, Repository } from 'typeorm';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { GroupEntity } from '../entities/group.entity';
|
||||
|
||||
@Injectable()
|
||||
export class GroupRepository extends Repository<GroupEntity> {
|
||||
constructor(private dataSource: DataSource) {
|
||||
super(GroupEntity, dataSource.createEntityManager());
|
||||
}
|
||||
}
|
||||
1
libs/common/src/modules/group/repositories/index.ts
Normal file
1
libs/common/src/modules/group/repositories/index.ts
Normal file
@ -0,0 +1 @@
|
||||
export * from './group.repository';
|
||||
1
libs/common/src/modules/permission/dtos/index.ts
Normal file
1
libs/common/src/modules/permission/dtos/index.ts
Normal file
@ -0,0 +1 @@
|
||||
export * from './permission.dto';
|
||||
11
libs/common/src/modules/permission/dtos/permission.dto.ts
Normal file
11
libs/common/src/modules/permission/dtos/permission.dto.ts
Normal file
@ -0,0 +1,11 @@
|
||||
import { PermissionType } from '@app/common/constants/permission-type.enum';
|
||||
import { IsEnum, IsNotEmpty, IsString } from 'class-validator';
|
||||
|
||||
export class PermissionTypeDto {
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
public uuid: string;
|
||||
|
||||
@IsEnum(PermissionType)
|
||||
public type: PermissionType;
|
||||
}
|
||||
1
libs/common/src/modules/permission/entities/index.ts
Normal file
1
libs/common/src/modules/permission/entities/index.ts
Normal file
@ -0,0 +1 @@
|
||||
export * from './permission.entity';
|
||||
@ -0,0 +1,30 @@
|
||||
import { Column, Entity, OneToMany } from 'typeorm';
|
||||
import { AbstractEntity } from '../../abstract/entities/abstract.entity';
|
||||
import { PermissionType } from '@app/common/constants/permission-type.enum';
|
||||
import { PermissionTypeDto } from '../dtos/permission.dto';
|
||||
import { DeviceUserPermissionEntity } from '../../device/entities';
|
||||
|
||||
@Entity({ name: 'permission-type' })
|
||||
export class PermissionTypeEntity extends AbstractEntity<PermissionTypeDto> {
|
||||
@Column({
|
||||
nullable: false,
|
||||
enum: Object.values(PermissionType),
|
||||
})
|
||||
type: string;
|
||||
|
||||
@OneToMany(
|
||||
() => DeviceUserPermissionEntity,
|
||||
(permission) => permission.type,
|
||||
{
|
||||
nullable: true,
|
||||
onDelete: 'CASCADE',
|
||||
onUpdate: 'CASCADE',
|
||||
},
|
||||
)
|
||||
permission: DeviceUserPermissionEntity[];
|
||||
|
||||
constructor(partial: Partial<PermissionTypeEntity>) {
|
||||
super();
|
||||
Object.assign(this, partial);
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,11 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { PermissionTypeEntity } from './entities/permission.entity';
|
||||
|
||||
@Module({
|
||||
providers: [],
|
||||
exports: [],
|
||||
controllers: [],
|
||||
imports: [TypeOrmModule.forFeature([PermissionTypeEntity])],
|
||||
})
|
||||
export class PermissionTypeRepositoryModule {}
|
||||
1
libs/common/src/modules/permission/repositories/index.ts
Normal file
1
libs/common/src/modules/permission/repositories/index.ts
Normal file
@ -0,0 +1 @@
|
||||
export * from './permission.repository';
|
||||
@ -0,0 +1,10 @@
|
||||
import { DataSource, Repository } from 'typeorm';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { PermissionTypeEntity } from '../entities/permission.entity';
|
||||
|
||||
@Injectable()
|
||||
export class PermissionTypeRepository extends Repository<PermissionTypeEntity> {
|
||||
constructor(private dataSource: DataSource) {
|
||||
super(PermissionTypeEntity, dataSource.createEntityManager());
|
||||
}
|
||||
}
|
||||
@ -2,6 +2,7 @@ import { Column, Entity, ManyToOne, OneToMany } from 'typeorm';
|
||||
import { SpaceDto } from '../dtos';
|
||||
import { AbstractEntity } from '../../abstract/entities/abstract.entity';
|
||||
import { SpaceTypeEntity } from '../../space-type/entities';
|
||||
import { UserSpaceEntity } from '../../user-space/entities';
|
||||
|
||||
@Entity({ name: 'space' })
|
||||
export class SpaceEntity extends AbstractEntity<SpaceDto> {
|
||||
@ -26,6 +27,9 @@ export class SpaceEntity extends AbstractEntity<SpaceDto> {
|
||||
})
|
||||
spaceType: SpaceTypeEntity;
|
||||
|
||||
@OneToMany(() => UserSpaceEntity, (userSpace) => userSpace.space)
|
||||
userSpaces: UserSpaceEntity[];
|
||||
|
||||
constructor(partial: Partial<SpaceEntity>) {
|
||||
super();
|
||||
Object.assign(this, partial);
|
||||
|
||||
1
libs/common/src/modules/user-space/dtos/index.ts
Normal file
1
libs/common/src/modules/user-space/dtos/index.ts
Normal file
@ -0,0 +1 @@
|
||||
export * from './user.space.dto';
|
||||
15
libs/common/src/modules/user-space/dtos/user.space.dto.ts
Normal file
15
libs/common/src/modules/user-space/dtos/user.space.dto.ts
Normal file
@ -0,0 +1,15 @@
|
||||
import { IsNotEmpty, IsString } from 'class-validator';
|
||||
|
||||
export class UserSpaceDto {
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
public uuid: string;
|
||||
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
public spaceUuid: string;
|
||||
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
public userUuid: string;
|
||||
}
|
||||
1
libs/common/src/modules/user-space/entities/index.ts
Normal file
1
libs/common/src/modules/user-space/entities/index.ts
Normal file
@ -0,0 +1 @@
|
||||
export * from './user.space.entity';
|
||||
@ -0,0 +1,29 @@
|
||||
import { Column, Entity, ManyToOne, Unique } from 'typeorm';
|
||||
import { UserSpaceDto } from '../dtos';
|
||||
import { AbstractEntity } from '../../abstract/entities/abstract.entity';
|
||||
import { SpaceEntity } from '../../space/entities';
|
||||
import { UserEntity } from '../../user/entities';
|
||||
|
||||
@Entity({ name: 'user-space' })
|
||||
@Unique(['user', 'space'])
|
||||
export class UserSpaceEntity extends AbstractEntity<UserSpaceDto> {
|
||||
@Column({
|
||||
type: 'uuid',
|
||||
default: () => 'gen_random_uuid()', // Use gen_random_uuid() for default value
|
||||
nullable: false,
|
||||
})
|
||||
public uuid: string;
|
||||
|
||||
@ManyToOne(() => UserEntity, (user) => user.userSpaces, { nullable: false })
|
||||
user: UserEntity;
|
||||
|
||||
@ManyToOne(() => SpaceEntity, (space) => space.userSpaces, {
|
||||
nullable: false,
|
||||
})
|
||||
space: SpaceEntity;
|
||||
|
||||
constructor(partial: Partial<UserSpaceEntity>) {
|
||||
super();
|
||||
Object.assign(this, partial);
|
||||
}
|
||||
}
|
||||
1
libs/common/src/modules/user-space/repositories/index.ts
Normal file
1
libs/common/src/modules/user-space/repositories/index.ts
Normal file
@ -0,0 +1 @@
|
||||
export * from './user.space.repository';
|
||||
@ -0,0 +1,10 @@
|
||||
import { DataSource, Repository } from 'typeorm';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { UserSpaceEntity } from '../entities/user.space.entity';
|
||||
|
||||
@Injectable()
|
||||
export class UserSpaceRepository extends Repository<UserSpaceEntity> {
|
||||
constructor(private dataSource: DataSource) {
|
||||
super(UserSpaceEntity, dataSource.createEntityManager());
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,11 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { UserSpaceEntity } from './entities/user.space.entity';
|
||||
|
||||
@Module({
|
||||
providers: [],
|
||||
exports: [],
|
||||
controllers: [],
|
||||
imports: [TypeOrmModule.forFeature([UserSpaceEntity])],
|
||||
})
|
||||
export class UserSpaceRepositoryModule {}
|
||||
@ -0,0 +1 @@
|
||||
export * from './user.entity';
|
||||
|
||||
@ -1,6 +1,7 @@
|
||||
import { Column, Entity } from 'typeorm';
|
||||
import { Column, Entity, OneToMany } from 'typeorm';
|
||||
import { UserDto } from '../dtos';
|
||||
import { AbstractEntity } from '../../abstract/entities/abstract.entity';
|
||||
import { UserSpaceEntity } from '../../user-space/entities';
|
||||
|
||||
@Entity({ name: 'user' })
|
||||
export class UserEntity extends AbstractEntity<UserDto> {
|
||||
@ -30,12 +31,26 @@ export class UserEntity extends AbstractEntity<UserDto> {
|
||||
})
|
||||
public lastName: string;
|
||||
|
||||
@Column({
|
||||
nullable: true,
|
||||
})
|
||||
public refreshToken: string;
|
||||
|
||||
@Column({
|
||||
nullable: true,
|
||||
default: false,
|
||||
})
|
||||
public isUserVerified: boolean;
|
||||
|
||||
@Column({
|
||||
nullable: false,
|
||||
default: true,
|
||||
})
|
||||
public isActive: boolean;
|
||||
|
||||
@OneToMany(() => UserSpaceEntity, (userSpace) => userSpace.user)
|
||||
userSpaces: UserSpaceEntity[];
|
||||
|
||||
constructor(partial: Partial<UserEntity>) {
|
||||
super();
|
||||
Object.assign(this, partial);
|
||||
|
||||
41
package-lock.json
generated
41
package-lock.json
generated
@ -18,6 +18,7 @@
|
||||
"@nestjs/swagger": "^7.3.0",
|
||||
"@nestjs/typeorm": "^10.0.2",
|
||||
"@tuya/tuya-connector-nodejs": "^2.1.2",
|
||||
"argon2": "^0.40.1",
|
||||
"axios": "^1.6.7",
|
||||
"bcryptjs": "^2.4.3",
|
||||
"class-transformer": "^0.5.1",
|
||||
@ -2111,6 +2112,14 @@
|
||||
"npm": ">=5.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@phc/format": {
|
||||
"version": "1.0.0",
|
||||
"resolved": "https://registry.npmjs.org/@phc/format/-/format-1.0.0.tgz",
|
||||
"integrity": "sha512-m7X9U6BG2+J+R1lSOdCiITLLrxm+cWlNI3HUFA92oLO77ObGNzaKdh8pMLqdZcshtkKuV84olNNXDfMc4FezBQ==",
|
||||
"engines": {
|
||||
"node": ">=10"
|
||||
}
|
||||
},
|
||||
"node_modules/@pkgjs/parseargs": {
|
||||
"version": "0.11.0",
|
||||
"resolved": "https://registry.npmjs.org/@pkgjs/parseargs/-/parseargs-0.11.0.tgz",
|
||||
@ -3032,6 +3041,20 @@
|
||||
"integrity": "sha512-58S9QDqG0Xx27YwPSt9fJxivjYl432YCwfDMfZ+71RAqUrZef7LrKQZ3LHLOwCS4FLNBplP533Zx895SeOCHvA==",
|
||||
"devOptional": true
|
||||
},
|
||||
"node_modules/argon2": {
|
||||
"version": "0.40.1",
|
||||
"resolved": "https://registry.npmjs.org/argon2/-/argon2-0.40.1.tgz",
|
||||
"integrity": "sha512-DjtHDwd7pm12qeWyfihHoM8Bn5vGcgH6sKwgPqwNYroRmxlrzadHEvMyuvQxN/V8YSyRRKD5x6ito09q1e9OyA==",
|
||||
"hasInstallScript": true,
|
||||
"dependencies": {
|
||||
"@phc/format": "^1.0.0",
|
||||
"node-addon-api": "^7.1.0",
|
||||
"node-gyp-build": "^4.8.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=16.17.0"
|
||||
}
|
||||
},
|
||||
"node_modules/argparse": {
|
||||
"version": "2.0.1",
|
||||
"resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz",
|
||||
@ -7168,6 +7191,14 @@
|
||||
"integrity": "sha512-AGK2yQKIjRuqnc6VkX2Xj5d+QW8xZ87pa1UK6yA6ouUyuxfHuMP6umE5QK7UmTeOAymo+Zx1Fxiuw9rVx8taHQ==",
|
||||
"dev": true
|
||||
},
|
||||
"node_modules/node-addon-api": {
|
||||
"version": "7.1.0",
|
||||
"resolved": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-7.1.0.tgz",
|
||||
"integrity": "sha512-mNcltoe1R8o7STTegSOHdnJNN7s5EUvhoS7ShnTHDyOSd+8H+UdWODq6qSv67PjC8Zc5JRT8+oLAMCr0SIXw7g==",
|
||||
"engines": {
|
||||
"node": "^16 || ^18 || >= 20"
|
||||
}
|
||||
},
|
||||
"node_modules/node-emoji": {
|
||||
"version": "1.11.0",
|
||||
"resolved": "https://registry.npmjs.org/node-emoji/-/node-emoji-1.11.0.tgz",
|
||||
@ -7196,6 +7227,16 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/node-gyp-build": {
|
||||
"version": "4.8.0",
|
||||
"resolved": "https://registry.npmjs.org/node-gyp-build/-/node-gyp-build-4.8.0.tgz",
|
||||
"integrity": "sha512-u6fs2AEUljNho3EYTJNBfImO5QTo/J/1Etd+NVdCj7qWKUSN/bSLkZwhDv7I+w/MSC6qJ4cknepkAYykDdK8og==",
|
||||
"bin": {
|
||||
"node-gyp-build": "bin.js",
|
||||
"node-gyp-build-optional": "optional.js",
|
||||
"node-gyp-build-test": "build-test.js"
|
||||
}
|
||||
},
|
||||
"node_modules/node-int64": {
|
||||
"version": "0.4.0",
|
||||
"resolved": "https://registry.npmjs.org/node-int64/-/node-int64-0.4.0.tgz",
|
||||
|
||||
@ -29,6 +29,7 @@
|
||||
"@nestjs/swagger": "^7.3.0",
|
||||
"@nestjs/typeorm": "^10.0.2",
|
||||
"@tuya/tuya-connector-nodejs": "^2.1.2",
|
||||
"argon2": "^0.40.1",
|
||||
"axios": "^1.6.7",
|
||||
"bcryptjs": "^2.4.3",
|
||||
"class-transformer": "^0.5.1",
|
||||
|
||||
@ -8,6 +8,7 @@ import { HomeModule } from './home/home.module';
|
||||
import { RoomModule } from './room/room.module';
|
||||
import { GroupModule } from './group/group.module';
|
||||
import { DeviceModule } from './device/device.module';
|
||||
import { UserDevicePermissionModule } from './user-device-permission/user-device-permission.module';
|
||||
import { CommunityModule } from './community/community.module';
|
||||
import { BuildingModule } from './building/building.module';
|
||||
import { FloorModule } from './floor/floor.module';
|
||||
@ -28,6 +29,7 @@ import { UnitModule } from './unit/unit.module';
|
||||
RoomModule,
|
||||
GroupModule,
|
||||
DeviceModule,
|
||||
UserDevicePermissionModule,
|
||||
],
|
||||
controllers: [AuthenticationController],
|
||||
})
|
||||
|
||||
@ -2,9 +2,11 @@ import {
|
||||
Body,
|
||||
Controller,
|
||||
Delete,
|
||||
Get,
|
||||
HttpStatus,
|
||||
Param,
|
||||
Post,
|
||||
Req,
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import { UserAuthService } from '../services/user-auth.service';
|
||||
@ -14,6 +16,7 @@ import { ResponseMessage } from '../../../libs/common/src/response/response.deco
|
||||
import { UserLoginDto } from '../dtos/user-login.dto';
|
||||
import { JwtAuthGuard } from '../../../libs/common/src/guards/jwt.auth.guard';
|
||||
import { ForgetPasswordDto, UserOtpDto, VerifyOtpDto } from '../dtos';
|
||||
import { RefreshTokenGuard } from '@app/common/guards/jwt-refresh.auth.guard';
|
||||
|
||||
@Controller({
|
||||
version: '1',
|
||||
@ -93,4 +96,33 @@ export class UserAuthController {
|
||||
message: 'Password changed successfully',
|
||||
};
|
||||
}
|
||||
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@Get('user/list')
|
||||
async userList() {
|
||||
const userList = await this.userAuthService.userList();
|
||||
return {
|
||||
statusCode: HttpStatus.OK,
|
||||
data: userList,
|
||||
message: 'User List Fetched Successfully',
|
||||
};
|
||||
}
|
||||
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(RefreshTokenGuard)
|
||||
@Get('refresh-token')
|
||||
async refreshToken(@Req() req) {
|
||||
const refreshToken = await this.userAuthService.refreshToken(
|
||||
req.user.uuid,
|
||||
req.headers.authorization,
|
||||
req.user.type,
|
||||
req.user.sessionId,
|
||||
);
|
||||
return {
|
||||
statusCode: HttpStatus.OK,
|
||||
data: refreshToken,
|
||||
message: 'Refresh Token added Successfully',
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,6 +1,7 @@
|
||||
import { UserRepository } from '../../../libs/common/src/modules/user/repositories';
|
||||
import {
|
||||
BadRequestException,
|
||||
ForbiddenException,
|
||||
Injectable,
|
||||
UnauthorizedException,
|
||||
} from '@nestjs/common';
|
||||
@ -14,7 +15,7 @@ import { ForgetPasswordDto, UserOtpDto, VerifyOtpDto } from '../dtos';
|
||||
import { EmailService } from '../../../libs/common/src/util/email.service';
|
||||
import { OtpType } from '../../../libs/common/src/constants/otp-type.enum';
|
||||
import { UserEntity } from '../../../libs/common/src/modules/user/entities/user.entity';
|
||||
import { ILoginResponse } from '../constants/login.response.constant';
|
||||
import * as argon2 from 'argon2';
|
||||
|
||||
@Injectable()
|
||||
export class UserAuthService {
|
||||
@ -64,7 +65,7 @@ export class UserAuthService {
|
||||
);
|
||||
}
|
||||
|
||||
async userLogin(data: UserLoginDto): Promise<ILoginResponse> {
|
||||
async userLogin(data: UserLoginDto) {
|
||||
const user = await this.authService.validateUser(data.email, data.password);
|
||||
if (!user) {
|
||||
throw new UnauthorizedException('Invalid login credentials.');
|
||||
@ -86,7 +87,7 @@ export class UserAuthService {
|
||||
|
||||
return await this.authService.login({
|
||||
email: user.email,
|
||||
userId: user.id,
|
||||
userId: user.uuid,
|
||||
uuid: user.uuid,
|
||||
sessionId: session[1].uuid,
|
||||
});
|
||||
@ -97,7 +98,7 @@ export class UserAuthService {
|
||||
if (!user) {
|
||||
throw new BadRequestException('User does not found');
|
||||
}
|
||||
return await this.userRepository.delete({ uuid });
|
||||
return await this.userRepository.update({ uuid }, { isActive: false });
|
||||
}
|
||||
|
||||
async findOneById(id: string): Promise<UserEntity> {
|
||||
@ -148,4 +149,41 @@ export class UserAuthService {
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
async userList(): Promise<UserEntity[]> {
|
||||
return await this.userRepository.find({
|
||||
where: { isActive: true },
|
||||
select: {
|
||||
firstName: true,
|
||||
lastName: true,
|
||||
email: true,
|
||||
isActive: true,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async refreshToken(
|
||||
userId: string,
|
||||
refreshToken: string,
|
||||
type: string,
|
||||
sessionId: string,
|
||||
) {
|
||||
const user = await this.userRepository.findOne({ where: { uuid: userId } });
|
||||
if (!user || !user.refreshToken)
|
||||
throw new ForbiddenException('Access Denied');
|
||||
const refreshTokenMatches = await argon2.verify(
|
||||
user.refreshToken,
|
||||
refreshToken,
|
||||
);
|
||||
if (!refreshTokenMatches) throw new ForbiddenException('Access Denied');
|
||||
const tokens = await this.authService.getTokens({
|
||||
email: user.email,
|
||||
userId: user.uuid,
|
||||
uuid: user.uuid,
|
||||
type,
|
||||
sessionId,
|
||||
});
|
||||
await this.authService.updateRefreshToken(user.uuid, tokens.refreshToken);
|
||||
return tokens;
|
||||
}
|
||||
}
|
||||
|
||||
@ -6,11 +6,27 @@ import { SpaceRepositoryModule } from '@app/common/modules/space/space.repositor
|
||||
import { SpaceRepository } from '@app/common/modules/space/repositories';
|
||||
import { SpaceTypeRepositoryModule } from '@app/common/modules/space-type/space.type.repository.module';
|
||||
import { SpaceTypeRepository } from '@app/common/modules/space-type/repositories';
|
||||
import { UserSpaceRepositoryModule } from '@app/common/modules/user-space/user.space.repository.module';
|
||||
import { UserSpaceRepository } from '@app/common/modules/user-space/repositories';
|
||||
import { UserRepository } from '@app/common/modules/user/repositories';
|
||||
import { UserRepositoryModule } from '@app/common/modules/user/user.repository.module';
|
||||
|
||||
@Module({
|
||||
imports: [ConfigModule, SpaceRepositoryModule, SpaceTypeRepositoryModule],
|
||||
imports: [
|
||||
ConfigModule,
|
||||
SpaceRepositoryModule,
|
||||
SpaceTypeRepositoryModule,
|
||||
UserSpaceRepositoryModule,
|
||||
UserRepositoryModule,
|
||||
],
|
||||
controllers: [BuildingController],
|
||||
providers: [BuildingService, SpaceRepository, SpaceTypeRepository],
|
||||
providers: [
|
||||
BuildingService,
|
||||
SpaceRepository,
|
||||
SpaceTypeRepository,
|
||||
UserSpaceRepository,
|
||||
UserRepository,
|
||||
],
|
||||
exports: [BuildingService],
|
||||
})
|
||||
export class BuildingModule {}
|
||||
|
||||
@ -13,10 +13,11 @@ import {
|
||||
} from '@nestjs/common';
|
||||
import { ApiTags, ApiBearerAuth } from '@nestjs/swagger';
|
||||
import { JwtAuthGuard } from '../../../libs/common/src/guards/jwt.auth.guard';
|
||||
import { AddBuildingDto } from '../dtos/add.building.dto';
|
||||
import { AddBuildingDto, AddUserBuildingDto } from '../dtos/add.building.dto';
|
||||
import { GetBuildingChildDto } from '../dtos/get.building.dto';
|
||||
import { UpdateBuildingNameDto } from '../dtos/update.building.dto';
|
||||
import { CheckCommunityTypeGuard } from 'src/guards/community.type.guard';
|
||||
import { CheckUserBuildingGuard } from 'src/guards/user.building.guard';
|
||||
|
||||
@ApiTags('Building Module')
|
||||
@Controller({
|
||||
@ -92,6 +93,34 @@ export class BuildingController {
|
||||
);
|
||||
}
|
||||
}
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard, CheckUserBuildingGuard)
|
||||
@Post('user')
|
||||
async addUserBuilding(@Body() addUserBuildingDto: AddUserBuildingDto) {
|
||||
try {
|
||||
await this.buildingService.addUserBuilding(addUserBuildingDto);
|
||||
return { message: 'user building added successfully' };
|
||||
} catch (error) {
|
||||
throw new HttpException(
|
||||
error.message || 'Internal server error',
|
||||
error.status || HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
}
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@Get('user/:userUuid')
|
||||
async getBuildingsByUserId(@Param('userUuid') userUuid: string) {
|
||||
try {
|
||||
return await this.buildingService.getBuildingsByUserId(userUuid);
|
||||
} catch (error) {
|
||||
throw new HttpException(
|
||||
error.message || 'Internal server error',
|
||||
error.status || HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@Put('rename/:buildingUuid')
|
||||
|
||||
@ -21,3 +21,22 @@ export class AddBuildingDto {
|
||||
Object.assign(this, dto);
|
||||
}
|
||||
}
|
||||
export class AddUserBuildingDto {
|
||||
@ApiProperty({
|
||||
description: 'buildingUuid',
|
||||
required: true,
|
||||
})
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
public buildingUuid: string;
|
||||
@ApiProperty({
|
||||
description: 'userUuid',
|
||||
required: true,
|
||||
})
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
public userUuid: string;
|
||||
constructor(dto: Partial<AddUserBuildingDto>) {
|
||||
Object.assign(this, dto);
|
||||
}
|
||||
}
|
||||
|
||||
@ -24,3 +24,8 @@ export interface RenameBuildingByUuidInterface {
|
||||
name: string;
|
||||
type: string;
|
||||
}
|
||||
export interface GetBuildingByUserUuidInterface {
|
||||
uuid: string;
|
||||
name: string;
|
||||
type: string;
|
||||
}
|
||||
|
||||
@ -7,21 +7,24 @@ import {
|
||||
BadRequestException,
|
||||
} from '@nestjs/common';
|
||||
import { SpaceRepository } from '@app/common/modules/space/repositories';
|
||||
import { AddBuildingDto } from '../dtos';
|
||||
import { AddBuildingDto, AddUserBuildingDto } from '../dtos';
|
||||
import {
|
||||
BuildingChildInterface,
|
||||
BuildingParentInterface,
|
||||
GetBuildingByUserUuidInterface,
|
||||
GetBuildingByUuidInterface,
|
||||
RenameBuildingByUuidInterface,
|
||||
} from '../interface/building.interface';
|
||||
import { SpaceEntity } from '@app/common/modules/space/entities';
|
||||
import { UpdateBuildingNameDto } from '../dtos/update.building.dto';
|
||||
import { UserSpaceRepository } from '@app/common/modules/user-space/repositories';
|
||||
|
||||
@Injectable()
|
||||
export class BuildingService {
|
||||
constructor(
|
||||
private readonly spaceRepository: SpaceRepository,
|
||||
private readonly spaceTypeRepository: SpaceTypeRepository,
|
||||
private readonly userSpaceRepository: UserSpaceRepository,
|
||||
) {}
|
||||
|
||||
async addBuilding(addBuildingDto: AddBuildingDto) {
|
||||
@ -210,6 +213,58 @@ export class BuildingService {
|
||||
}
|
||||
}
|
||||
|
||||
async getBuildingsByUserId(
|
||||
userUuid: string,
|
||||
): Promise<GetBuildingByUserUuidInterface[]> {
|
||||
try {
|
||||
const buildings = await this.userSpaceRepository.find({
|
||||
relations: ['space', 'space.spaceType'],
|
||||
where: {
|
||||
user: { uuid: userUuid },
|
||||
space: { spaceType: { type: 'building' } },
|
||||
},
|
||||
});
|
||||
|
||||
if (buildings.length === 0) {
|
||||
throw new HttpException(
|
||||
'this user has no buildings',
|
||||
HttpStatus.NOT_FOUND,
|
||||
);
|
||||
}
|
||||
const spaces = buildings.map((building) => ({
|
||||
uuid: building.space.uuid,
|
||||
name: building.space.spaceName,
|
||||
type: building.space.spaceType.type,
|
||||
}));
|
||||
|
||||
return spaces;
|
||||
} catch (err) {
|
||||
if (err instanceof HttpException) {
|
||||
throw err;
|
||||
} else {
|
||||
throw new HttpException('user not found', HttpStatus.NOT_FOUND);
|
||||
}
|
||||
}
|
||||
}
|
||||
async addUserBuilding(addUserBuildingDto: AddUserBuildingDto) {
|
||||
try {
|
||||
await this.userSpaceRepository.save({
|
||||
user: { uuid: addUserBuildingDto.userUuid },
|
||||
space: { uuid: addUserBuildingDto.buildingUuid },
|
||||
});
|
||||
} catch (err) {
|
||||
if (err.code === '23505') {
|
||||
throw new HttpException(
|
||||
'User already belongs to this building',
|
||||
HttpStatus.BAD_REQUEST,
|
||||
);
|
||||
}
|
||||
throw new HttpException(
|
||||
err.message || 'Internal Server Error',
|
||||
HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
}
|
||||
async renameBuildingByUuid(
|
||||
buildingUuid: string,
|
||||
updateBuildingNameDto: UpdateBuildingNameDto,
|
||||
|
||||
@ -6,11 +6,27 @@ import { SpaceRepositoryModule } from '@app/common/modules/space/space.repositor
|
||||
import { SpaceRepository } from '@app/common/modules/space/repositories';
|
||||
import { SpaceTypeRepositoryModule } from '@app/common/modules/space-type/space.type.repository.module';
|
||||
import { SpaceTypeRepository } from '@app/common/modules/space-type/repositories';
|
||||
import { UserSpaceRepositoryModule } from '@app/common/modules/user-space/user.space.repository.module';
|
||||
import { UserSpaceRepository } from '@app/common/modules/user-space/repositories';
|
||||
import { UserRepositoryModule } from '@app/common/modules/user/user.repository.module';
|
||||
import { UserRepository } from '@app/common/modules/user/repositories';
|
||||
|
||||
@Module({
|
||||
imports: [ConfigModule, SpaceRepositoryModule, SpaceTypeRepositoryModule],
|
||||
imports: [
|
||||
ConfigModule,
|
||||
SpaceRepositoryModule,
|
||||
SpaceTypeRepositoryModule,
|
||||
UserSpaceRepositoryModule,
|
||||
UserRepositoryModule,
|
||||
],
|
||||
controllers: [CommunityController],
|
||||
providers: [CommunityService, SpaceRepository, SpaceTypeRepository],
|
||||
providers: [
|
||||
CommunityService,
|
||||
SpaceRepository,
|
||||
SpaceTypeRepository,
|
||||
UserSpaceRepository,
|
||||
UserRepository,
|
||||
],
|
||||
exports: [CommunityService],
|
||||
})
|
||||
export class CommunityModule {}
|
||||
|
||||
@ -13,9 +13,13 @@ import {
|
||||
} from '@nestjs/common';
|
||||
import { ApiTags, ApiBearerAuth } from '@nestjs/swagger';
|
||||
import { JwtAuthGuard } from '../../../libs/common/src/guards/jwt.auth.guard';
|
||||
import { AddCommunityDto } from '../dtos/add.community.dto';
|
||||
import {
|
||||
AddCommunityDto,
|
||||
AddUserCommunityDto,
|
||||
} from '../dtos/add.community.dto';
|
||||
import { GetCommunityChildDto } from '../dtos/get.community.dto';
|
||||
import { UpdateCommunityNameDto } from '../dtos/update.community.dto';
|
||||
import { CheckUserCommunityGuard } from 'src/guards/user.community.guard';
|
||||
|
||||
@ApiTags('Community Module')
|
||||
@Controller({
|
||||
@ -77,6 +81,33 @@ export class CommunityController {
|
||||
}
|
||||
}
|
||||
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@Get('user/:userUuid')
|
||||
async getCommunitiesByUserId(@Param('userUuid') userUuid: string) {
|
||||
try {
|
||||
return await this.communityService.getCommunitiesByUserId(userUuid);
|
||||
} catch (error) {
|
||||
throw new HttpException(
|
||||
error.message || 'Internal server error',
|
||||
error.status || HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
}
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard, CheckUserCommunityGuard)
|
||||
@Post('user')
|
||||
async addUserCommunity(@Body() addUserCommunityDto: AddUserCommunityDto) {
|
||||
try {
|
||||
await this.communityService.addUserCommunity(addUserCommunityDto);
|
||||
return { message: 'user community added successfully' };
|
||||
} catch (error) {
|
||||
throw new HttpException(
|
||||
error.message || 'Internal server error',
|
||||
error.status || HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
}
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@Put('rename/:communityUuid')
|
||||
|
||||
@ -14,3 +14,22 @@ export class AddCommunityDto {
|
||||
Object.assign(this, dto);
|
||||
}
|
||||
}
|
||||
export class AddUserCommunityDto {
|
||||
@ApiProperty({
|
||||
description: 'communityUuid',
|
||||
required: true,
|
||||
})
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
public communityUuid: string;
|
||||
@ApiProperty({
|
||||
description: 'userUuid',
|
||||
required: true,
|
||||
})
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
public userUuid: string;
|
||||
constructor(dto: Partial<AddUserCommunityDto>) {
|
||||
Object.assign(this, dto);
|
||||
}
|
||||
}
|
||||
|
||||
@ -18,3 +18,9 @@ export interface RenameCommunityByUuidInterface {
|
||||
name: string;
|
||||
type: string;
|
||||
}
|
||||
|
||||
export interface GetCommunityByUserUuidInterface {
|
||||
uuid: string;
|
||||
name: string;
|
||||
type: string;
|
||||
}
|
||||
|
||||
@ -7,20 +7,23 @@ import {
|
||||
BadRequestException,
|
||||
} from '@nestjs/common';
|
||||
import { SpaceRepository } from '@app/common/modules/space/repositories';
|
||||
import { AddCommunityDto } from '../dtos';
|
||||
import { AddCommunityDto, AddUserCommunityDto } from '../dtos';
|
||||
import {
|
||||
CommunityChildInterface,
|
||||
GetCommunityByUserUuidInterface,
|
||||
GetCommunityByUuidInterface,
|
||||
RenameCommunityByUuidInterface,
|
||||
} from '../interface/community.interface';
|
||||
import { SpaceEntity } from '@app/common/modules/space/entities';
|
||||
import { UpdateCommunityNameDto } from '../dtos/update.community.dto';
|
||||
import { UserSpaceRepository } from '@app/common/modules/user-space/repositories';
|
||||
|
||||
@Injectable()
|
||||
export class CommunityService {
|
||||
constructor(
|
||||
private readonly spaceRepository: SpaceRepository,
|
||||
private readonly spaceTypeRepository: SpaceTypeRepository,
|
||||
private readonly userSpaceRepository: UserSpaceRepository,
|
||||
) {}
|
||||
|
||||
async addCommunity(addCommunityDto: AddCommunityDto) {
|
||||
@ -151,6 +154,60 @@ export class CommunityService {
|
||||
|
||||
return childHierarchies;
|
||||
}
|
||||
|
||||
async getCommunitiesByUserId(
|
||||
userUuid: string,
|
||||
): Promise<GetCommunityByUserUuidInterface[]> {
|
||||
try {
|
||||
const communities = await this.userSpaceRepository.find({
|
||||
relations: ['space', 'space.spaceType'],
|
||||
where: {
|
||||
user: { uuid: userUuid },
|
||||
space: { spaceType: { type: 'community' } },
|
||||
},
|
||||
});
|
||||
|
||||
if (communities.length === 0) {
|
||||
throw new HttpException(
|
||||
'this user has no communities',
|
||||
HttpStatus.NOT_FOUND,
|
||||
);
|
||||
}
|
||||
const spaces = communities.map((community) => ({
|
||||
uuid: community.space.uuid,
|
||||
name: community.space.spaceName,
|
||||
type: community.space.spaceType.type,
|
||||
}));
|
||||
|
||||
return spaces;
|
||||
} catch (err) {
|
||||
if (err instanceof HttpException) {
|
||||
throw err;
|
||||
} else {
|
||||
throw new HttpException('user not found', HttpStatus.NOT_FOUND);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async addUserCommunity(addUserCommunityDto: AddUserCommunityDto) {
|
||||
try {
|
||||
await this.userSpaceRepository.save({
|
||||
user: { uuid: addUserCommunityDto.userUuid },
|
||||
space: { uuid: addUserCommunityDto.communityUuid },
|
||||
});
|
||||
} catch (err) {
|
||||
if (err.code === '23505') {
|
||||
throw new HttpException(
|
||||
'User already belongs to this community',
|
||||
HttpStatus.BAD_REQUEST,
|
||||
);
|
||||
}
|
||||
throw new HttpException(
|
||||
err.message || 'Internal Server Error',
|
||||
HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
}
|
||||
async renameCommunityByUuid(
|
||||
communityUuid: string,
|
||||
updateCommunityDto: UpdateCommunityNameDto,
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
import AuthConfig from './auth.config';
|
||||
import AppConfig from './app.config';
|
||||
|
||||
export default [AuthConfig, AppConfig];
|
||||
import JwtConfig from './jwt.config';
|
||||
export default [AuthConfig, AppConfig, JwtConfig];
|
||||
|
||||
@ -19,6 +19,8 @@ import {
|
||||
GetDeviceByRoomIdDto,
|
||||
} from '../dtos/get.device.dto';
|
||||
import { ControlDeviceDto } from '../dtos/control.device.dto';
|
||||
import { AuthGuardWithRoles } from 'src/guards/device.permission.guard';
|
||||
import { PermissionType } from '@app/common/constants/permission-type.enum';
|
||||
|
||||
@ApiTags('Device Module')
|
||||
@Controller({
|
||||
@ -29,7 +31,7 @@ export class DeviceController {
|
||||
constructor(private readonly deviceService: DeviceService) {}
|
||||
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@AuthGuardWithRoles(PermissionType.READ)
|
||||
@Get('room')
|
||||
async getDevicesByRoomId(
|
||||
@Query() getDeviceByRoomIdDto: GetDeviceByRoomIdDto,
|
||||
@ -41,7 +43,7 @@ export class DeviceController {
|
||||
}
|
||||
}
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@AuthGuardWithRoles(PermissionType.READ)
|
||||
@Get('group')
|
||||
async getDevicesByGroupId(
|
||||
@Query() getDeviceByGroupIdDto: GetDeviceByGroupIdDto,
|
||||
@ -55,7 +57,7 @@ export class DeviceController {
|
||||
}
|
||||
}
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@AuthGuardWithRoles(PermissionType.READ)
|
||||
@Get(':deviceId')
|
||||
async getDeviceDetailsByDeviceId(@Param('deviceId') deviceId: string) {
|
||||
try {
|
||||
@ -65,7 +67,7 @@ export class DeviceController {
|
||||
}
|
||||
}
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@AuthGuardWithRoles(PermissionType.READ)
|
||||
@Get(':deviceId/functions')
|
||||
async getDeviceInstructionByDeviceId(@Param('deviceId') deviceId: string) {
|
||||
try {
|
||||
@ -75,7 +77,7 @@ export class DeviceController {
|
||||
}
|
||||
}
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@AuthGuardWithRoles(PermissionType.READ)
|
||||
@Get(':deviceId/functions/status')
|
||||
async getDevicesInstructionStatus(@Param('deviceId') deviceId: string) {
|
||||
try {
|
||||
@ -85,7 +87,7 @@ export class DeviceController {
|
||||
}
|
||||
}
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@AuthGuardWithRoles(PermissionType.CONTROLLABLE)
|
||||
@Post('room')
|
||||
async addDeviceInRoom(@Body() addDeviceInRoomDto: AddDeviceInRoomDto) {
|
||||
try {
|
||||
@ -95,7 +97,7 @@ export class DeviceController {
|
||||
}
|
||||
}
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@AuthGuardWithRoles(PermissionType.CONTROLLABLE)
|
||||
@Post('group')
|
||||
async addDeviceInGroup(@Body() addDeviceInGroupDto: AddDeviceInGroupDto) {
|
||||
try {
|
||||
@ -105,7 +107,7 @@ export class DeviceController {
|
||||
}
|
||||
}
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@AuthGuardWithRoles(PermissionType.CONTROLLABLE)
|
||||
@Post('control')
|
||||
async controlDevice(@Body() controlDeviceDto: ControlDeviceDto) {
|
||||
try {
|
||||
|
||||
@ -4,10 +4,23 @@ import { DeviceController } from './controllers/device.controller';
|
||||
import { ConfigModule } from '@nestjs/config';
|
||||
import { ProductRepositoryModule } from '@app/common/modules/product/product.repository.module';
|
||||
import { ProductRepository } from '@app/common/modules/product/repositories';
|
||||
import { DeviceRepositoryModule } from '@app/common/modules/device';
|
||||
import { DeviceRepository, DeviceUserTypeRepository } from '@app/common/modules/device/repositories';
|
||||
import { PermissionTypeRepository } from '@app/common/modules/permission/repositories';
|
||||
import { SpaceRepository } from '@app/common/modules/space/repositories';
|
||||
import { GroupDeviceRepository } from '@app/common/modules/group-device/repositories';
|
||||
@Module({
|
||||
imports: [ConfigModule, ProductRepositoryModule],
|
||||
imports: [ConfigModule, ProductRepositoryModule, DeviceRepositoryModule],
|
||||
controllers: [DeviceController],
|
||||
providers: [DeviceService, ProductRepository],
|
||||
providers: [
|
||||
DeviceService,
|
||||
ProductRepository,
|
||||
DeviceUserTypeRepository,
|
||||
PermissionTypeRepository,
|
||||
SpaceRepository,
|
||||
DeviceRepository,
|
||||
GroupDeviceRepository
|
||||
],
|
||||
exports: [DeviceService],
|
||||
})
|
||||
export class DeviceModule {}
|
||||
|
||||
@ -8,7 +8,7 @@ export interface GetDeviceDetailsInterface {
|
||||
export interface GetDevicesByRoomIdInterface {
|
||||
success: boolean;
|
||||
msg: string;
|
||||
result: [];
|
||||
result:any;
|
||||
}
|
||||
|
||||
export interface GetDevicesByGroupIdInterface {
|
||||
|
||||
@ -1,4 +1,9 @@
|
||||
import { Injectable, HttpException, HttpStatus } from '@nestjs/common';
|
||||
import {
|
||||
Injectable,
|
||||
HttpException,
|
||||
HttpStatus,
|
||||
NotFoundException,
|
||||
} from '@nestjs/common';
|
||||
import { TuyaContext } from '@tuya/tuya-connector-nodejs';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import {
|
||||
@ -23,6 +28,9 @@ import {
|
||||
import { ControlDeviceDto } from '../dtos/control.device.dto';
|
||||
import { convertKeysToCamelCase } from '@app/common/helper/camelCaseConverter';
|
||||
import { ProductRepository } from '@app/common/modules/product/repositories';
|
||||
import { SpaceRepository } from '@app/common/modules/space/repositories';
|
||||
import { DeviceRepository } from '@app/common/modules/device/repositories';
|
||||
import { GroupDeviceRepository } from '@app/common/modules/group-device/repositories';
|
||||
|
||||
@Injectable()
|
||||
export class DeviceService {
|
||||
@ -30,6 +38,9 @@ export class DeviceService {
|
||||
constructor(
|
||||
private readonly configService: ConfigService,
|
||||
private readonly productRepository: ProductRepository,
|
||||
private readonly spaceRepository: SpaceRepository,
|
||||
private readonly deviceRepository: DeviceRepository,
|
||||
private readonly groupDeviceRepository: GroupDeviceRepository,
|
||||
) {
|
||||
const accessKey = this.configService.get<string>('auth-config.ACCESS_KEY');
|
||||
const secretKey = this.configService.get<string>('auth-config.SECRET_KEY');
|
||||
@ -42,6 +53,15 @@ export class DeviceService {
|
||||
|
||||
async getDevicesByRoomId(getDeviceByRoomIdDto: GetDeviceByRoomIdDto) {
|
||||
try {
|
||||
const findRoom = await this.spaceRepository.findOne({
|
||||
where: {
|
||||
uuid: getDeviceByRoomIdDto.roomId,
|
||||
},
|
||||
});
|
||||
if (!findRoom) {
|
||||
throw new NotFoundException('Room Details Not Found');
|
||||
}
|
||||
|
||||
const response = await this.getDevicesByRoomIdTuya(getDeviceByRoomIdDto);
|
||||
|
||||
return {
|
||||
@ -62,7 +82,12 @@ export class DeviceService {
|
||||
): Promise<GetDevicesByRoomIdInterface> {
|
||||
try {
|
||||
const path = `/v2.0/cloud/thing/space/device`;
|
||||
const response = await this.tuya.request({
|
||||
const getDeviceByRoomId = await this.deviceRepository.find({
|
||||
where: {
|
||||
deviceTuyaUuid: getDeviceByRoomIdDto.roomId,
|
||||
},
|
||||
});
|
||||
const response:any = await this.tuya.request({
|
||||
method: 'GET',
|
||||
path,
|
||||
query: {
|
||||
@ -70,7 +95,26 @@ export class DeviceService {
|
||||
page_size: getDeviceByRoomIdDto.pageSize,
|
||||
},
|
||||
});
|
||||
return response as GetDevicesByRoomIdInterface;
|
||||
if (!getDeviceByRoomId.length) {
|
||||
throw new NotFoundException('Devices Not Found');
|
||||
}
|
||||
|
||||
const matchingRecords = [];
|
||||
|
||||
getDeviceByRoomId.forEach((item1) => {
|
||||
const matchingItem = response.find(
|
||||
(item2) => item1.deviceTuyaUuid === item2.uuid,
|
||||
);
|
||||
if (matchingItem) {
|
||||
matchingRecords.push({...matchingItem });
|
||||
}
|
||||
});
|
||||
|
||||
return {
|
||||
success:true,
|
||||
msg:'Device Tuya Details Fetched successfully',
|
||||
result:matchingRecords
|
||||
};
|
||||
} catch (error) {
|
||||
throw new HttpException(
|
||||
'Error fetching devices by room from Tuya',
|
||||
@ -126,7 +170,27 @@ export class DeviceService {
|
||||
}
|
||||
|
||||
async addDeviceInRoom(addDeviceInRoomDto: AddDeviceInRoomDto) {
|
||||
const response = await this.addDeviceInRoomTuya(addDeviceInRoomDto);
|
||||
const [deviceDetails, roomDetails] = await Promise.all([
|
||||
this.deviceRepository.findOne({
|
||||
where: {
|
||||
uuid: addDeviceInRoomDto.deviceId,
|
||||
},
|
||||
}),
|
||||
this.spaceRepository.findOne({
|
||||
where: {
|
||||
uuid: addDeviceInRoomDto.roomId,
|
||||
},
|
||||
}),
|
||||
]);
|
||||
|
||||
if (!roomDetails) {
|
||||
throw new NotFoundException('Room Details Not Found');
|
||||
}
|
||||
|
||||
if (!deviceDetails) {
|
||||
throw new NotFoundException('Device Details Not Found');
|
||||
}
|
||||
const response = await this.addDeviceInRooms(addDeviceInRoomDto);
|
||||
|
||||
if (response.success) {
|
||||
return {
|
||||
@ -141,7 +205,7 @@ export class DeviceService {
|
||||
);
|
||||
}
|
||||
}
|
||||
async addDeviceInRoomTuya(
|
||||
async addDeviceInRooms(
|
||||
addDeviceInRoomDto: AddDeviceInRoomDto,
|
||||
): Promise<addDeviceInRoomInterface> {
|
||||
try {
|
||||
@ -153,7 +217,6 @@ export class DeviceService {
|
||||
space_id: addDeviceInRoomDto.roomId,
|
||||
},
|
||||
});
|
||||
|
||||
return response as addDeviceInRoomInterface;
|
||||
} catch (error) {
|
||||
throw new HttpException(
|
||||
@ -163,7 +226,17 @@ export class DeviceService {
|
||||
}
|
||||
}
|
||||
async addDeviceInGroup(addDeviceInGroupDto: AddDeviceInGroupDto) {
|
||||
const response = await this.addDeviceInGroupTuya(addDeviceInGroupDto);
|
||||
const deviceDetails = this.deviceRepository.findOne({
|
||||
where: {
|
||||
uuid: addDeviceInGroupDto.deviceId,
|
||||
},
|
||||
});
|
||||
|
||||
if (!deviceDetails) {
|
||||
throw new NotFoundException('Device Details Not Found');
|
||||
}
|
||||
|
||||
const response = await this.addDeviceInGroups(addDeviceInGroupDto);
|
||||
|
||||
if (response.success) {
|
||||
return {
|
||||
@ -178,21 +251,20 @@ export class DeviceService {
|
||||
);
|
||||
}
|
||||
}
|
||||
async addDeviceInGroupTuya(
|
||||
async addDeviceInGroups(
|
||||
addDeviceInGroupDto: AddDeviceInGroupDto,
|
||||
): Promise<addDeviceInRoomInterface> {
|
||||
try {
|
||||
const path = `/v2.0/cloud/thing/group/${addDeviceInGroupDto.groupId}/device`;
|
||||
const response = await this.tuya.request({
|
||||
method: 'PUT',
|
||||
path,
|
||||
body: {
|
||||
space_id: addDeviceInGroupDto.homeId,
|
||||
device_ids: addDeviceInGroupDto.deviceId,
|
||||
},
|
||||
await this.groupDeviceRepository.create({
|
||||
deviceUuid: addDeviceInGroupDto.deviceId,
|
||||
groupUuid: addDeviceInGroupDto.groupId,
|
||||
});
|
||||
|
||||
return response as addDeviceInRoomInterface;
|
||||
return {
|
||||
success: true,
|
||||
msg: 'Group is Added to Specific Device',
|
||||
result: true,
|
||||
} as addDeviceInRoomInterface;
|
||||
} catch (error) {
|
||||
throw new HttpException(
|
||||
'Error adding device in group from Tuya',
|
||||
@ -239,6 +311,15 @@ export class DeviceService {
|
||||
|
||||
async getDeviceDetailsByDeviceId(deviceId: string) {
|
||||
try {
|
||||
const deviceDetails = await this.deviceRepository.findOne({
|
||||
where: {
|
||||
uuid: deviceId,
|
||||
},
|
||||
});
|
||||
if (!deviceDetails) {
|
||||
throw new NotFoundException('Device Details Not Found');
|
||||
}
|
||||
|
||||
const response = await this.getDeviceDetailsByDeviceIdTuya(deviceId);
|
||||
|
||||
return {
|
||||
@ -335,6 +416,15 @@ export class DeviceService {
|
||||
deviceId: string,
|
||||
): Promise<DeviceInstructionResponse> {
|
||||
try {
|
||||
const deviceDetails = await this.deviceRepository.findOne({
|
||||
where: {
|
||||
uuid: deviceId,
|
||||
},
|
||||
});
|
||||
if (!deviceDetails) {
|
||||
throw new NotFoundException('Device Details Not Found');
|
||||
}
|
||||
|
||||
const response = await this.getDeviceInstructionByDeviceIdTuya(deviceId);
|
||||
|
||||
const productId: string = await this.getProductIdByDeviceId(deviceId);
|
||||
@ -383,6 +473,14 @@ export class DeviceService {
|
||||
}
|
||||
async getDevicesInstructionStatus(deviceId: string) {
|
||||
try {
|
||||
const deviceDetails = await this.deviceRepository.findOne({
|
||||
where: {
|
||||
uuid: deviceId,
|
||||
},
|
||||
});
|
||||
if (!deviceDetails) {
|
||||
throw new NotFoundException('Device Details Not Found');
|
||||
}
|
||||
const deviceStatus = await this.getDevicesInstructionStatusTuya(deviceId);
|
||||
const productId: string = await this.getProductIdByDeviceId(deviceId);
|
||||
const productType: string =
|
||||
|
||||
@ -13,10 +13,11 @@ import {
|
||||
} from '@nestjs/common';
|
||||
import { ApiTags, ApiBearerAuth } from '@nestjs/swagger';
|
||||
import { JwtAuthGuard } from '../../../libs/common/src/guards/jwt.auth.guard';
|
||||
import { AddFloorDto } from '../dtos/add.floor.dto';
|
||||
import { AddFloorDto, AddUserFloorDto } from '../dtos/add.floor.dto';
|
||||
import { GetFloorChildDto } from '../dtos/get.floor.dto';
|
||||
import { UpdateFloorNameDto } from '../dtos/update.floor.dto';
|
||||
import { CheckBuildingTypeGuard } from 'src/guards/building.type.guard';
|
||||
import { CheckUserFloorGuard } from 'src/guards/user.floor.guard';
|
||||
|
||||
@ApiTags('Floor Module')
|
||||
@Controller({
|
||||
@ -91,6 +92,35 @@ export class FloorController {
|
||||
}
|
||||
}
|
||||
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard, CheckUserFloorGuard)
|
||||
@Post('user')
|
||||
async addUserFloor(@Body() addUserFloorDto: AddUserFloorDto) {
|
||||
try {
|
||||
await this.floorService.addUserFloor(addUserFloorDto);
|
||||
return { message: 'user floor added successfully' };
|
||||
} catch (error) {
|
||||
throw new HttpException(
|
||||
error.message || 'Internal server error',
|
||||
error.status || HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@Get('user/:userUuid')
|
||||
async getFloorsByUserId(@Param('userUuid') userUuid: string) {
|
||||
try {
|
||||
return await this.floorService.getFloorsByUserId(userUuid);
|
||||
} catch (error) {
|
||||
throw new HttpException(
|
||||
error.message || 'Internal server error',
|
||||
error.status || HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@Put('rename/:floorUuid')
|
||||
|
||||
@ -21,3 +21,22 @@ export class AddFloorDto {
|
||||
Object.assign(this, dto);
|
||||
}
|
||||
}
|
||||
export class AddUserFloorDto {
|
||||
@ApiProperty({
|
||||
description: 'floorUuid',
|
||||
required: true,
|
||||
})
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
public floorUuid: string;
|
||||
@ApiProperty({
|
||||
description: 'userUuid',
|
||||
required: true,
|
||||
})
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
public userUuid: string;
|
||||
constructor(dto: Partial<AddUserFloorDto>) {
|
||||
Object.assign(this, dto);
|
||||
}
|
||||
}
|
||||
|
||||
@ -6,11 +6,27 @@ import { SpaceRepositoryModule } from '@app/common/modules/space/space.repositor
|
||||
import { SpaceRepository } from '@app/common/modules/space/repositories';
|
||||
import { SpaceTypeRepositoryModule } from '@app/common/modules/space-type/space.type.repository.module';
|
||||
import { SpaceTypeRepository } from '@app/common/modules/space-type/repositories';
|
||||
import { UserSpaceRepositoryModule } from '@app/common/modules/user-space/user.space.repository.module';
|
||||
import { UserSpaceRepository } from '@app/common/modules/user-space/repositories';
|
||||
import { UserRepositoryModule } from '@app/common/modules/user/user.repository.module';
|
||||
import { UserRepository } from '@app/common/modules/user/repositories';
|
||||
|
||||
@Module({
|
||||
imports: [ConfigModule, SpaceRepositoryModule, SpaceTypeRepositoryModule],
|
||||
imports: [
|
||||
ConfigModule,
|
||||
SpaceRepositoryModule,
|
||||
SpaceTypeRepositoryModule,
|
||||
UserSpaceRepositoryModule,
|
||||
UserRepositoryModule,
|
||||
],
|
||||
controllers: [FloorController],
|
||||
providers: [FloorService, SpaceRepository, SpaceTypeRepository],
|
||||
providers: [
|
||||
FloorService,
|
||||
SpaceRepository,
|
||||
SpaceTypeRepository,
|
||||
UserSpaceRepository,
|
||||
UserRepository,
|
||||
],
|
||||
exports: [FloorService],
|
||||
})
|
||||
export class FloorModule {}
|
||||
|
||||
@ -24,3 +24,9 @@ export interface RenameFloorByUuidInterface {
|
||||
name: string;
|
||||
type: string;
|
||||
}
|
||||
|
||||
export interface GetFloorByUserUuidInterface {
|
||||
uuid: string;
|
||||
name: string;
|
||||
type: string;
|
||||
}
|
||||
|
||||
@ -7,21 +7,24 @@ import {
|
||||
BadRequestException,
|
||||
} from '@nestjs/common';
|
||||
import { SpaceRepository } from '@app/common/modules/space/repositories';
|
||||
import { AddFloorDto } from '../dtos';
|
||||
import { AddFloorDto, AddUserFloorDto } from '../dtos';
|
||||
import {
|
||||
FloorChildInterface,
|
||||
FloorParentInterface,
|
||||
GetFloorByUserUuidInterface,
|
||||
GetFloorByUuidInterface,
|
||||
RenameFloorByUuidInterface,
|
||||
} from '../interface/floor.interface';
|
||||
import { SpaceEntity } from '@app/common/modules/space/entities';
|
||||
import { UpdateFloorNameDto } from '../dtos/update.floor.dto';
|
||||
import { UserSpaceRepository } from '@app/common/modules/user-space/repositories';
|
||||
|
||||
@Injectable()
|
||||
export class FloorService {
|
||||
constructor(
|
||||
private readonly spaceRepository: SpaceRepository,
|
||||
private readonly spaceTypeRepository: SpaceTypeRepository,
|
||||
private readonly userSpaceRepository: UserSpaceRepository,
|
||||
) {}
|
||||
|
||||
async addFloor(addFloorDto: AddFloorDto) {
|
||||
@ -195,6 +198,58 @@ export class FloorService {
|
||||
}
|
||||
}
|
||||
|
||||
async getFloorsByUserId(
|
||||
userUuid: string,
|
||||
): Promise<GetFloorByUserUuidInterface[]> {
|
||||
try {
|
||||
const floors = await this.userSpaceRepository.find({
|
||||
relations: ['space', 'space.spaceType'],
|
||||
where: {
|
||||
user: { uuid: userUuid },
|
||||
space: { spaceType: { type: 'floor' } },
|
||||
},
|
||||
});
|
||||
|
||||
if (floors.length === 0) {
|
||||
throw new HttpException(
|
||||
'this user has no floors',
|
||||
HttpStatus.NOT_FOUND,
|
||||
);
|
||||
}
|
||||
const spaces = floors.map((floor) => ({
|
||||
uuid: floor.space.uuid,
|
||||
name: floor.space.spaceName,
|
||||
type: floor.space.spaceType.type,
|
||||
}));
|
||||
|
||||
return spaces;
|
||||
} catch (err) {
|
||||
if (err instanceof HttpException) {
|
||||
throw err;
|
||||
} else {
|
||||
throw new HttpException('user not found', HttpStatus.NOT_FOUND);
|
||||
}
|
||||
}
|
||||
}
|
||||
async addUserFloor(addUserFloorDto: AddUserFloorDto) {
|
||||
try {
|
||||
await this.userSpaceRepository.save({
|
||||
user: { uuid: addUserFloorDto.userUuid },
|
||||
space: { uuid: addUserFloorDto.floorUuid },
|
||||
});
|
||||
} catch (err) {
|
||||
if (err.code === '23505') {
|
||||
throw new HttpException(
|
||||
'User already belongs to this floor',
|
||||
HttpStatus.BAD_REQUEST,
|
||||
);
|
||||
}
|
||||
throw new HttpException(
|
||||
err.message || 'Internal Server Error',
|
||||
HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
}
|
||||
async renameFloorByUuid(
|
||||
floorUuid: string,
|
||||
updateFloorDto: UpdateFloorNameDto,
|
||||
|
||||
@ -5,17 +5,18 @@ import {
|
||||
Get,
|
||||
Post,
|
||||
UseGuards,
|
||||
Query,
|
||||
Param,
|
||||
Put,
|
||||
Delete,
|
||||
HttpException,
|
||||
HttpStatus,
|
||||
} from '@nestjs/common';
|
||||
import { ApiTags, ApiBearerAuth } from '@nestjs/swagger';
|
||||
import { JwtAuthGuard } from '../../../libs/common/src/guards/jwt.auth.guard';
|
||||
import { AddGroupDto } from '../dtos/add.group.dto';
|
||||
import { GetGroupDto } from '../dtos/get.group.dto';
|
||||
import { ControlGroupDto } from '../dtos/control.group.dto';
|
||||
import { RenameGroupDto } from '../dtos/rename.group.dto copy';
|
||||
import { CheckProductUuidForAllDevicesGuard } from 'src/guards/device.product.guard';
|
||||
|
||||
@ApiTags('Group Module')
|
||||
@Controller({
|
||||
@ -27,32 +28,41 @@ export class GroupController {
|
||||
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@Get()
|
||||
async getGroupsByHomeId(@Query() getGroupsDto: GetGroupDto) {
|
||||
@Get('space/:spaceUuid')
|
||||
async getGroupsBySpaceUuid(@Param('spaceUuid') spaceUuid: string) {
|
||||
try {
|
||||
return await this.groupService.getGroupsByHomeId(getGroupsDto);
|
||||
} catch (err) {
|
||||
throw new Error(err);
|
||||
return await this.groupService.getGroupsBySpaceUuid(spaceUuid);
|
||||
} catch (error) {
|
||||
throw new HttpException(
|
||||
error.message || 'Internal server error',
|
||||
error.status || HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
}
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@Get(':groupId')
|
||||
async getGroupsByGroupId(@Param('groupId') groupId: number) {
|
||||
@Get(':groupUuid')
|
||||
async getGroupsByGroupId(@Param('groupUuid') groupUuid: string) {
|
||||
try {
|
||||
return await this.groupService.getGroupsByGroupId(groupId);
|
||||
} catch (err) {
|
||||
throw new Error(err);
|
||||
return await this.groupService.getGroupsByGroupUuid(groupUuid);
|
||||
} catch (error) {
|
||||
throw new HttpException(
|
||||
error.message || 'Internal server error',
|
||||
error.status || HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
}
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@UseGuards(JwtAuthGuard, CheckProductUuidForAllDevicesGuard)
|
||||
@Post()
|
||||
async addGroup(@Body() addGroupDto: AddGroupDto) {
|
||||
try {
|
||||
return await this.groupService.addGroup(addGroupDto);
|
||||
} catch (err) {
|
||||
throw new Error(err);
|
||||
} catch (error) {
|
||||
throw new HttpException(
|
||||
error.message || 'Internal server error',
|
||||
error.status || HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@ -62,30 +72,45 @@ export class GroupController {
|
||||
async controlGroup(@Body() controlGroupDto: ControlGroupDto) {
|
||||
try {
|
||||
return await this.groupService.controlGroup(controlGroupDto);
|
||||
} catch (err) {
|
||||
throw new Error(err);
|
||||
} catch (error) {
|
||||
throw new HttpException(
|
||||
error.message || 'Internal server error',
|
||||
error.status || HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@Put('rename')
|
||||
async renameGroup(@Body() renameGroupDto: RenameGroupDto) {
|
||||
@Put('rename/:groupUuid')
|
||||
async renameGroupByUuid(
|
||||
@Param('groupUuid') groupUuid: string,
|
||||
@Body() renameGroupDto: RenameGroupDto,
|
||||
) {
|
||||
try {
|
||||
return await this.groupService.renameGroup(renameGroupDto);
|
||||
} catch (err) {
|
||||
throw new Error(err);
|
||||
return await this.groupService.renameGroupByUuid(
|
||||
groupUuid,
|
||||
renameGroupDto,
|
||||
);
|
||||
} catch (error) {
|
||||
throw new HttpException(
|
||||
error.message || 'Internal server error',
|
||||
error.status || HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@Delete(':groupId')
|
||||
async deleteGroup(@Param('groupId') groupId: number) {
|
||||
@Delete(':groupUuid')
|
||||
async deleteGroup(@Param('groupUuid') groupUuid: string) {
|
||||
try {
|
||||
return await this.groupService.deleteGroup(groupId);
|
||||
} catch (err) {
|
||||
throw new Error(err);
|
||||
return await this.groupService.deleteGroup(groupUuid);
|
||||
} catch (error) {
|
||||
throw new HttpException(
|
||||
error.message || 'Internal server error',
|
||||
error.status || HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,5 +1,5 @@
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
import { IsNotEmpty, IsString, IsNumberString } from 'class-validator';
|
||||
import { IsNotEmpty, IsString, IsArray } from 'class-validator';
|
||||
|
||||
export class AddGroupDto {
|
||||
@ApiProperty({
|
||||
@ -11,26 +11,10 @@ export class AddGroupDto {
|
||||
public groupName: string;
|
||||
|
||||
@ApiProperty({
|
||||
description: 'homeId',
|
||||
description: 'deviceUuids',
|
||||
required: true,
|
||||
})
|
||||
@IsNumberString()
|
||||
@IsArray()
|
||||
@IsNotEmpty()
|
||||
public homeId: string;
|
||||
|
||||
@ApiProperty({
|
||||
description: 'productId',
|
||||
required: true,
|
||||
})
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
public productId: string;
|
||||
|
||||
@ApiProperty({
|
||||
description: 'The list of up to 20 device IDs, separated with commas (,)',
|
||||
required: true,
|
||||
})
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
public deviceIds: string;
|
||||
public deviceUuids: [string];
|
||||
}
|
||||
|
||||
@ -1,20 +1,26 @@
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
import { IsNotEmpty, IsObject, IsNumberString } from 'class-validator';
|
||||
import { IsNotEmpty, IsString } from 'class-validator';
|
||||
|
||||
export class ControlGroupDto {
|
||||
@ApiProperty({
|
||||
description: 'groupId',
|
||||
description: 'groupUuid',
|
||||
required: true,
|
||||
})
|
||||
@IsNumberString()
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
public groupId: string;
|
||||
public groupUuid: string;
|
||||
|
||||
@ApiProperty({
|
||||
description: 'example {"switch_1":true,"add_ele":300}',
|
||||
description: 'code',
|
||||
required: true,
|
||||
})
|
||||
@IsObject()
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
public properties: object;
|
||||
public code: string;
|
||||
@ApiProperty({
|
||||
description: 'value',
|
||||
required: true,
|
||||
})
|
||||
@IsNotEmpty()
|
||||
public value: any;
|
||||
}
|
||||
|
||||
@ -1,28 +0,0 @@
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
import { IsNotEmpty, IsNumberString } from 'class-validator';
|
||||
|
||||
export class GetGroupDto {
|
||||
@ApiProperty({
|
||||
description: 'homeId',
|
||||
required: true,
|
||||
})
|
||||
@IsNumberString()
|
||||
@IsNotEmpty()
|
||||
public homeId: string;
|
||||
|
||||
@ApiProperty({
|
||||
description: 'pageSize',
|
||||
required: true,
|
||||
})
|
||||
@IsNumberString()
|
||||
@IsNotEmpty()
|
||||
public pageSize: number;
|
||||
|
||||
@ApiProperty({
|
||||
description: 'pageNo',
|
||||
required: true,
|
||||
})
|
||||
@IsNumberString()
|
||||
@IsNotEmpty()
|
||||
public pageNo: number;
|
||||
}
|
||||
@ -1,15 +1,7 @@
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
import { IsNotEmpty, IsString, IsNumberString } from 'class-validator';
|
||||
import { IsNotEmpty, IsString } from 'class-validator';
|
||||
|
||||
export class RenameGroupDto {
|
||||
@ApiProperty({
|
||||
description: 'groupId',
|
||||
required: true,
|
||||
})
|
||||
@IsNumberString()
|
||||
@IsNotEmpty()
|
||||
public groupId: string;
|
||||
|
||||
@ApiProperty({
|
||||
description: 'groupName',
|
||||
required: true,
|
||||
|
||||
@ -2,10 +2,26 @@ import { Module } from '@nestjs/common';
|
||||
import { GroupService } from './services/group.service';
|
||||
import { GroupController } from './controllers/group.controller';
|
||||
import { ConfigModule } from '@nestjs/config';
|
||||
import { GroupRepositoryModule } from '@app/common/modules/group/group.repository.module';
|
||||
import { GroupRepository } from '@app/common/modules/group/repositories';
|
||||
import { GroupDeviceRepositoryModule } from '@app/common/modules/group-device/group.device.repository.module';
|
||||
import { GroupDeviceRepository } from '@app/common/modules/group-device/repositories';
|
||||
import { DeviceRepositoryModule } from '@app/common/modules/device';
|
||||
import { DeviceRepository } from '@app/common/modules/device/repositories';
|
||||
@Module({
|
||||
imports: [ConfigModule],
|
||||
imports: [
|
||||
ConfigModule,
|
||||
GroupRepositoryModule,
|
||||
GroupDeviceRepositoryModule,
|
||||
DeviceRepositoryModule,
|
||||
],
|
||||
controllers: [GroupController],
|
||||
providers: [GroupService],
|
||||
providers: [
|
||||
GroupService,
|
||||
GroupRepository,
|
||||
GroupDeviceRepository,
|
||||
DeviceRepository,
|
||||
],
|
||||
exports: [GroupService],
|
||||
})
|
||||
export class GroupModule {}
|
||||
|
||||
@ -1,25 +1,15 @@
|
||||
export class GetGroupDetailsInterface {
|
||||
result: {
|
||||
id: string;
|
||||
name: string;
|
||||
};
|
||||
export interface GetGroupDetailsInterface {
|
||||
groupUuid: string;
|
||||
groupName: string;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
}
|
||||
export class GetGroupsInterface {
|
||||
result: {
|
||||
count: number;
|
||||
data_list: [];
|
||||
};
|
||||
export interface GetGroupsBySpaceUuidInterface {
|
||||
groupUuid: string;
|
||||
groupName: string;
|
||||
}
|
||||
|
||||
export class addGroupInterface {
|
||||
success: boolean;
|
||||
msg: string;
|
||||
result: {
|
||||
id: string;
|
||||
};
|
||||
}
|
||||
|
||||
export class controlGroupInterface {
|
||||
export interface controlGroupInterface {
|
||||
success: boolean;
|
||||
result: boolean;
|
||||
msg: string;
|
||||
|
||||
@ -1,21 +1,31 @@
|
||||
import { Injectable, HttpException, HttpStatus } from '@nestjs/common';
|
||||
import {
|
||||
Injectable,
|
||||
HttpException,
|
||||
HttpStatus,
|
||||
BadRequestException,
|
||||
} from '@nestjs/common';
|
||||
import { TuyaContext } from '@tuya/tuya-connector-nodejs';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { AddGroupDto } from '../dtos/add.group.dto';
|
||||
import {
|
||||
GetGroupDetailsInterface,
|
||||
GetGroupsInterface,
|
||||
addGroupInterface,
|
||||
controlGroupInterface,
|
||||
GetGroupsBySpaceUuidInterface,
|
||||
} from '../interfaces/get.group.interface';
|
||||
import { GetGroupDto } from '../dtos/get.group.dto';
|
||||
import { ControlGroupDto } from '../dtos/control.group.dto';
|
||||
import { RenameGroupDto } from '../dtos/rename.group.dto copy';
|
||||
import { GroupRepository } from '@app/common/modules/group/repositories';
|
||||
import { GroupDeviceRepository } from '@app/common/modules/group-device/repositories';
|
||||
import { controlDeviceInterface } from 'src/device/interfaces/get.device.interface';
|
||||
import { ControlDeviceDto } from 'src/device/dtos';
|
||||
|
||||
@Injectable()
|
||||
export class GroupService {
|
||||
private tuya: TuyaContext;
|
||||
constructor(private readonly configService: ConfigService) {
|
||||
constructor(
|
||||
private readonly configService: ConfigService,
|
||||
private readonly groupRepository: GroupRepository,
|
||||
private readonly groupDeviceRepository: GroupDeviceRepository,
|
||||
) {
|
||||
const accessKey = this.configService.get<string>('auth-config.ACCESS_KEY');
|
||||
const secretKey = this.configService.get<string>('auth-config.SECRET_KEY');
|
||||
// const clientId = this.configService.get<string>('auth-config.CLIENT_ID');
|
||||
@ -26,88 +36,100 @@ export class GroupService {
|
||||
});
|
||||
}
|
||||
|
||||
async getGroupsByHomeId(getGroupDto: GetGroupDto) {
|
||||
async getGroupsBySpaceUuid(
|
||||
spaceUuid: string,
|
||||
): Promise<GetGroupsBySpaceUuidInterface[]> {
|
||||
try {
|
||||
const response = await this.getGroupsTuya(getGroupDto);
|
||||
|
||||
const groups = response.result.data_list.map((group: any) => ({
|
||||
groupId: group.id,
|
||||
groupName: group.name,
|
||||
}));
|
||||
|
||||
return {
|
||||
count: response.result.count,
|
||||
groups: groups,
|
||||
};
|
||||
} catch (error) {
|
||||
throw new HttpException(
|
||||
'Error fetching groups',
|
||||
HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async getGroupsTuya(getGroupDto: GetGroupDto): Promise<GetGroupsInterface> {
|
||||
try {
|
||||
const path = `/v2.0/cloud/thing/group`;
|
||||
const response = await this.tuya.request({
|
||||
method: 'GET',
|
||||
path,
|
||||
query: {
|
||||
space_id: getGroupDto.homeId,
|
||||
page_size: getGroupDto.pageSize,
|
||||
page_no: getGroupDto.pageNo,
|
||||
const groupDevices = await this.groupDeviceRepository.find({
|
||||
relations: ['group', 'device'],
|
||||
where: {
|
||||
device: { spaceUuid },
|
||||
isActive: true,
|
||||
},
|
||||
});
|
||||
return response as unknown as GetGroupsInterface;
|
||||
|
||||
// Extract and return only the group entities
|
||||
const groups = groupDevices.map((groupDevice) => {
|
||||
return {
|
||||
groupUuid: groupDevice.uuid,
|
||||
groupName: groupDevice.group.groupName,
|
||||
};
|
||||
});
|
||||
if (groups.length > 0) {
|
||||
return groups;
|
||||
} else {
|
||||
throw new HttpException(
|
||||
'this space has no groups',
|
||||
HttpStatus.NOT_FOUND,
|
||||
);
|
||||
}
|
||||
} catch (error) {
|
||||
throw new HttpException(
|
||||
'Error fetching groups ',
|
||||
HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
error.message || 'Error fetching groups',
|
||||
error.status || HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async addGroup(addGroupDto: AddGroupDto) {
|
||||
const response = await this.addGroupTuya(addGroupDto);
|
||||
|
||||
if (response.success) {
|
||||
return {
|
||||
success: true,
|
||||
groupId: response.result.id,
|
||||
};
|
||||
} else {
|
||||
throw new HttpException(
|
||||
response.msg || 'Unknown error',
|
||||
HttpStatus.BAD_REQUEST,
|
||||
);
|
||||
}
|
||||
}
|
||||
async addGroupTuya(addGroupDto: AddGroupDto): Promise<addGroupInterface> {
|
||||
try {
|
||||
const path = `/v2.0/cloud/thing/group`;
|
||||
const response = await this.tuya.request({
|
||||
method: 'POST',
|
||||
path,
|
||||
body: {
|
||||
space_id: addGroupDto.homeId,
|
||||
name: addGroupDto.groupName,
|
||||
product_id: addGroupDto.productId,
|
||||
device_ids: addGroupDto.deviceIds,
|
||||
},
|
||||
const group = await this.groupRepository.save({
|
||||
groupName: addGroupDto.groupName,
|
||||
});
|
||||
|
||||
return response as addGroupInterface;
|
||||
} catch (error) {
|
||||
const groupDevicePromises = addGroupDto.deviceUuids.map(
|
||||
async (deviceUuid) => {
|
||||
await this.saveGroupDevice(group.uuid, deviceUuid);
|
||||
},
|
||||
);
|
||||
|
||||
await Promise.all(groupDevicePromises);
|
||||
} catch (err) {
|
||||
if (err.code === '23505') {
|
||||
throw new HttpException(
|
||||
'User already belongs to this group',
|
||||
HttpStatus.BAD_REQUEST,
|
||||
);
|
||||
}
|
||||
throw new HttpException(
|
||||
'Error adding group',
|
||||
err.message || 'Internal Server Error',
|
||||
HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async controlGroup(controlGroupDto: ControlGroupDto) {
|
||||
const response = await this.controlGroupTuya(controlGroupDto);
|
||||
private async saveGroupDevice(groupUuid: string, deviceUuid: string) {
|
||||
try {
|
||||
await this.groupDeviceRepository.save({
|
||||
group: {
|
||||
uuid: groupUuid,
|
||||
},
|
||||
device: {
|
||||
uuid: deviceUuid,
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
async getDevicesByGroupUuid(groupUuid: string) {
|
||||
try {
|
||||
const devices = await this.groupDeviceRepository.find({
|
||||
relations: ['device'],
|
||||
where: {
|
||||
group: {
|
||||
uuid: groupUuid,
|
||||
},
|
||||
isActive: true,
|
||||
},
|
||||
});
|
||||
return devices;
|
||||
} catch (error) {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
async controlDevice(controlDeviceDto: ControlDeviceDto) {
|
||||
const response = await this.controlDeviceTuya(controlDeviceDto);
|
||||
|
||||
if (response.success) {
|
||||
return response;
|
||||
@ -118,128 +140,120 @@ export class GroupService {
|
||||
);
|
||||
}
|
||||
}
|
||||
async controlGroupTuya(
|
||||
controlGroupDto: ControlGroupDto,
|
||||
): Promise<controlGroupInterface> {
|
||||
async controlDeviceTuya(
|
||||
controlDeviceDto: ControlDeviceDto,
|
||||
): Promise<controlDeviceInterface> {
|
||||
try {
|
||||
const path = `/v2.0/cloud/thing/group/properties`;
|
||||
const path = `/v1.0/iot-03/devices/${controlDeviceDto.deviceId}/commands`;
|
||||
const response = await this.tuya.request({
|
||||
method: 'POST',
|
||||
path,
|
||||
body: {
|
||||
group_id: controlGroupDto.groupId,
|
||||
properties: controlGroupDto.properties,
|
||||
commands: [
|
||||
{ code: controlDeviceDto.code, value: controlDeviceDto.value },
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
return response as controlGroupInterface;
|
||||
return response as controlDeviceInterface;
|
||||
} catch (error) {
|
||||
throw new HttpException(
|
||||
'Error control group',
|
||||
'Error control device from Tuya',
|
||||
HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
}
|
||||
async controlGroup(controlGroupDto: ControlGroupDto) {
|
||||
const devices = await this.getDevicesByGroupUuid(controlGroupDto.groupUuid);
|
||||
|
||||
try {
|
||||
await Promise.all(
|
||||
devices.map(async (device) => {
|
||||
return this.controlDevice({
|
||||
deviceId: device.device.deviceTuyaUuid,
|
||||
code: controlGroupDto.code,
|
||||
value: controlGroupDto.value,
|
||||
});
|
||||
}),
|
||||
);
|
||||
} catch (error) {
|
||||
throw new HttpException(
|
||||
'Error controlling devices',
|
||||
HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async renameGroup(renameGroupDto: RenameGroupDto) {
|
||||
const response = await this.renameGroupTuya(renameGroupDto);
|
||||
|
||||
if (response.success) {
|
||||
return {
|
||||
success: response.success,
|
||||
result: response.result,
|
||||
msg: response.msg,
|
||||
};
|
||||
} else {
|
||||
throw new HttpException(
|
||||
response.msg || 'Unknown error',
|
||||
HttpStatus.BAD_REQUEST,
|
||||
);
|
||||
}
|
||||
}
|
||||
async renameGroupTuya(
|
||||
async renameGroupByUuid(
|
||||
groupUuid: string,
|
||||
renameGroupDto: RenameGroupDto,
|
||||
): Promise<controlGroupInterface> {
|
||||
): Promise<GetGroupsBySpaceUuidInterface> {
|
||||
try {
|
||||
const path = `/v2.0/cloud/thing/group/${renameGroupDto.groupId}/${renameGroupDto.groupName}`;
|
||||
const response = await this.tuya.request({
|
||||
method: 'PUT',
|
||||
path,
|
||||
await this.groupRepository.update(
|
||||
{ uuid: groupUuid },
|
||||
{ groupName: renameGroupDto.groupName },
|
||||
);
|
||||
|
||||
// Fetch the updated floor
|
||||
const updatedGroup = await this.groupRepository.findOneOrFail({
|
||||
where: { uuid: groupUuid },
|
||||
});
|
||||
|
||||
return response as controlGroupInterface;
|
||||
} catch (error) {
|
||||
throw new HttpException(
|
||||
'Error rename group',
|
||||
HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async deleteGroup(groupId: number) {
|
||||
const response = await this.deleteGroupTuya(groupId);
|
||||
|
||||
if (response.success) {
|
||||
return {
|
||||
success: response.success,
|
||||
result: response.result,
|
||||
msg: response.msg,
|
||||
};
|
||||
} else {
|
||||
throw new HttpException(
|
||||
response.msg || 'Unknown error',
|
||||
HttpStatus.BAD_REQUEST,
|
||||
);
|
||||
}
|
||||
}
|
||||
async deleteGroupTuya(groupId: number): Promise<controlGroupInterface> {
|
||||
try {
|
||||
const path = `/v2.0/cloud/thing/group/${groupId}`;
|
||||
const response = await this.tuya.request({
|
||||
method: 'DELETE',
|
||||
path,
|
||||
});
|
||||
|
||||
return response as controlGroupInterface;
|
||||
} catch (error) {
|
||||
throw new HttpException(
|
||||
'Error delete group',
|
||||
HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async getGroupsByGroupId(groupId: number) {
|
||||
try {
|
||||
const response = await this.getGroupsByGroupIdTuya(groupId);
|
||||
|
||||
return {
|
||||
groupId: response.result.id,
|
||||
groupName: response.result.name,
|
||||
groupUuid: updatedGroup.uuid,
|
||||
groupName: updatedGroup.groupName,
|
||||
};
|
||||
} catch (error) {
|
||||
throw new HttpException('Group not found', HttpStatus.NOT_FOUND);
|
||||
}
|
||||
}
|
||||
|
||||
async deleteGroup(groupUuid: string) {
|
||||
try {
|
||||
const group = await this.getGroupsByGroupUuid(groupUuid);
|
||||
|
||||
if (!group) {
|
||||
throw new HttpException('Group not found', HttpStatus.NOT_FOUND);
|
||||
}
|
||||
|
||||
await this.groupRepository.update(
|
||||
{ uuid: groupUuid },
|
||||
{ isActive: false },
|
||||
);
|
||||
|
||||
return { message: 'Group deleted successfully' };
|
||||
} catch (error) {
|
||||
throw new HttpException(
|
||||
'Error fetching group',
|
||||
HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
error.message || 'Error deleting group',
|
||||
error.status || HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async getGroupsByGroupIdTuya(
|
||||
groupId: number,
|
||||
async getGroupsByGroupUuid(
|
||||
groupUuid: string,
|
||||
): Promise<GetGroupDetailsInterface> {
|
||||
try {
|
||||
const path = `/v2.0/cloud/thing/group/${groupId}`;
|
||||
const response = await this.tuya.request({
|
||||
method: 'GET',
|
||||
path,
|
||||
const group = await this.groupRepository.findOne({
|
||||
where: {
|
||||
uuid: groupUuid,
|
||||
isActive: true,
|
||||
},
|
||||
});
|
||||
return response as GetGroupDetailsInterface;
|
||||
} catch (error) {
|
||||
throw new HttpException(
|
||||
'Error fetching group ',
|
||||
HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
if (!group) {
|
||||
throw new BadRequestException('Invalid group UUID');
|
||||
}
|
||||
return {
|
||||
groupUuid: group.uuid,
|
||||
groupName: group.groupName,
|
||||
createdAt: group.createdAt,
|
||||
updatedAt: group.updatedAt,
|
||||
};
|
||||
} catch (err) {
|
||||
if (err instanceof BadRequestException) {
|
||||
throw err; // Re-throw BadRequestException
|
||||
} else {
|
||||
throw new HttpException('Group not found', HttpStatus.NOT_FOUND);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
97
src/guards/device.permission.guard.ts
Normal file
97
src/guards/device.permission.guard.ts
Normal file
@ -0,0 +1,97 @@
|
||||
import { PermissionType } from '@app/common/constants/permission-type.enum';
|
||||
import { JwtAuthGuard } from '@app/common/guards/jwt.auth.guard';
|
||||
import { DeviceUserTypeRepository } from '@app/common/modules/device/repositories';
|
||||
import { PermissionTypeRepository } from '@app/common/modules/permission/repositories';
|
||||
import {
|
||||
Injectable,
|
||||
CanActivate,
|
||||
HttpStatus,
|
||||
ExecutionContext,
|
||||
BadRequestException,
|
||||
applyDecorators,
|
||||
SetMetadata,
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import { Reflector } from '@nestjs/core';
|
||||
|
||||
@Injectable()
|
||||
export class DevicePermissionGuard implements CanActivate {
|
||||
constructor(
|
||||
private reflector: Reflector,
|
||||
private readonly deviceUserTypeRepository: DeviceUserTypeRepository,
|
||||
private readonly permissionTypeRepository: PermissionTypeRepository,
|
||||
) {}
|
||||
|
||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
const req = context.switchToHttp().getRequest();
|
||||
try {
|
||||
const { deviceId } = req.headers;
|
||||
const userId = req.user.uuid;
|
||||
|
||||
const requirePermission =
|
||||
this.reflector.getAllAndOverride<PermissionType>('permission', [
|
||||
context.getHandler(),
|
||||
context.getClass(),
|
||||
]);
|
||||
|
||||
if (!requirePermission) {
|
||||
return true;
|
||||
}
|
||||
await this.checkDevicePermission(deviceId, userId, requirePermission);
|
||||
|
||||
return true;
|
||||
} catch (error) {
|
||||
this.handleGuardError(error, context);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async checkDevicePermission(
|
||||
deviceId: string,
|
||||
userId: string,
|
||||
requirePermission,
|
||||
) {
|
||||
const [userPermissionDetails, permissionDetails] = await Promise.all([
|
||||
this.deviceUserTypeRepository.findOne({
|
||||
where: { deviceUuid: deviceId, userUuid: userId },
|
||||
}),
|
||||
this.permissionTypeRepository.findOne({
|
||||
where: {
|
||||
type: requirePermission,
|
||||
},
|
||||
}),
|
||||
]);
|
||||
if (!userPermissionDetails) {
|
||||
throw new BadRequestException('User Permission Details Not Found');
|
||||
}
|
||||
if (userPermissionDetails.permissionTypeUuid !== permissionDetails.uuid) {
|
||||
throw new BadRequestException(
|
||||
`User Does not have a ${requirePermission}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private handleGuardError(error: Error, context: ExecutionContext) {
|
||||
const response = context.switchToHttp().getResponse();
|
||||
console.error(error);
|
||||
|
||||
if (error instanceof BadRequestException) {
|
||||
response
|
||||
.status(HttpStatus.BAD_REQUEST)
|
||||
.json({ statusCode: HttpStatus.BAD_REQUEST, message: error.message });
|
||||
} else {
|
||||
response.status(HttpStatus.NOT_FOUND).json({
|
||||
statusCode: HttpStatus.NOT_FOUND,
|
||||
message: 'User Permission not found',
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function AuthGuardWithRoles(permission?: string) {
|
||||
return applyDecorators(
|
||||
SetMetadata('permission', permission),
|
||||
UseGuards(JwtAuthGuard),
|
||||
UseGuards(DevicePermissionGuard),
|
||||
);
|
||||
}
|
||||
71
src/guards/device.product.guard.ts
Normal file
71
src/guards/device.product.guard.ts
Normal file
@ -0,0 +1,71 @@
|
||||
import { DeviceRepository } from '@app/common/modules/device/repositories';
|
||||
import {
|
||||
Injectable,
|
||||
CanActivate,
|
||||
HttpStatus,
|
||||
BadRequestException,
|
||||
ExecutionContext,
|
||||
} from '@nestjs/common';
|
||||
|
||||
@Injectable()
|
||||
export class CheckProductUuidForAllDevicesGuard implements CanActivate {
|
||||
constructor(private readonly deviceRepository: DeviceRepository) {}
|
||||
|
||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
const req = context.switchToHttp().getRequest();
|
||||
|
||||
try {
|
||||
const { deviceUuids } = req.body;
|
||||
console.log(deviceUuids);
|
||||
|
||||
await this.checkAllDevicesHaveSameProductUuid(deviceUuids);
|
||||
|
||||
return true;
|
||||
} catch (error) {
|
||||
this.handleGuardError(error, context);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async checkAllDevicesHaveSameProductUuid(deviceUuids: string[]) {
|
||||
const firstDevice = await this.deviceRepository.findOne({
|
||||
where: { uuid: deviceUuids[0] },
|
||||
});
|
||||
|
||||
if (!firstDevice) {
|
||||
throw new BadRequestException('First device not found');
|
||||
}
|
||||
|
||||
const firstProductUuid = firstDevice.productUuid;
|
||||
|
||||
for (let i = 1; i < deviceUuids.length; i++) {
|
||||
const device = await this.deviceRepository.findOne({
|
||||
where: { uuid: deviceUuids[i] },
|
||||
});
|
||||
|
||||
if (!device) {
|
||||
throw new BadRequestException(`Device ${deviceUuids[i]} not found`);
|
||||
}
|
||||
|
||||
if (device.productUuid !== firstProductUuid) {
|
||||
throw new BadRequestException(`Devices have different product UUIDs`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private handleGuardError(error: Error, context: ExecutionContext) {
|
||||
const response = context.switchToHttp().getResponse();
|
||||
console.error(error);
|
||||
|
||||
if (error instanceof BadRequestException) {
|
||||
response
|
||||
.status(HttpStatus.BAD_REQUEST)
|
||||
.json({ statusCode: HttpStatus.BAD_REQUEST, message: error.message });
|
||||
} else {
|
||||
response.status(HttpStatus.NOT_FOUND).json({
|
||||
statusCode: HttpStatus.NOT_FOUND,
|
||||
message: 'Device not found',
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
70
src/guards/user.building.guard.ts
Normal file
70
src/guards/user.building.guard.ts
Normal file
@ -0,0 +1,70 @@
|
||||
import {
|
||||
CanActivate,
|
||||
ExecutionContext,
|
||||
Injectable,
|
||||
HttpStatus,
|
||||
} from '@nestjs/common';
|
||||
import { SpaceRepository } from '@app/common/modules/space/repositories';
|
||||
import { BadRequestException, NotFoundException } from '@nestjs/common';
|
||||
import { UserRepository } from '@app/common/modules/user/repositories';
|
||||
|
||||
@Injectable()
|
||||
export class CheckUserBuildingGuard implements CanActivate {
|
||||
constructor(
|
||||
private readonly spaceRepository: SpaceRepository,
|
||||
private readonly userRepository: UserRepository,
|
||||
) {}
|
||||
|
||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
const req = context.switchToHttp().getRequest();
|
||||
|
||||
try {
|
||||
const { userUuid, buildingUuid } = req.body;
|
||||
|
||||
await this.checkUserIsFound(userUuid);
|
||||
|
||||
await this.checkBuildingIsFound(buildingUuid);
|
||||
|
||||
return true;
|
||||
} catch (error) {
|
||||
this.handleGuardError(error, context);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private async checkUserIsFound(userUuid: string) {
|
||||
const userData = await this.userRepository.findOne({
|
||||
where: { uuid: userUuid },
|
||||
});
|
||||
if (!userData) {
|
||||
throw new NotFoundException('User not found');
|
||||
}
|
||||
}
|
||||
|
||||
private async checkBuildingIsFound(spaceUuid: string) {
|
||||
const spaceData = await this.spaceRepository.findOne({
|
||||
where: { uuid: spaceUuid, spaceType: { type: 'building' } },
|
||||
relations: ['spaceType'],
|
||||
});
|
||||
if (!spaceData) {
|
||||
throw new NotFoundException('Building not found');
|
||||
}
|
||||
}
|
||||
|
||||
private handleGuardError(error: Error, context: ExecutionContext) {
|
||||
const response = context.switchToHttp().getResponse();
|
||||
if (
|
||||
error instanceof BadRequestException ||
|
||||
error instanceof NotFoundException
|
||||
) {
|
||||
response
|
||||
.status(HttpStatus.NOT_FOUND)
|
||||
.json({ statusCode: HttpStatus.NOT_FOUND, message: error.message });
|
||||
} else {
|
||||
response.status(HttpStatus.BAD_REQUEST).json({
|
||||
statusCode: HttpStatus.BAD_REQUEST,
|
||||
message: 'invalid userUuid or buildingUuid',
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
70
src/guards/user.community.guard.ts
Normal file
70
src/guards/user.community.guard.ts
Normal file
@ -0,0 +1,70 @@
|
||||
import {
|
||||
CanActivate,
|
||||
ExecutionContext,
|
||||
Injectable,
|
||||
HttpStatus,
|
||||
} from '@nestjs/common';
|
||||
import { SpaceRepository } from '@app/common/modules/space/repositories';
|
||||
import { BadRequestException, NotFoundException } from '@nestjs/common';
|
||||
import { UserRepository } from '@app/common/modules/user/repositories';
|
||||
|
||||
@Injectable()
|
||||
export class CheckUserCommunityGuard implements CanActivate {
|
||||
constructor(
|
||||
private readonly spaceRepository: SpaceRepository,
|
||||
private readonly userRepository: UserRepository,
|
||||
) {}
|
||||
|
||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
const req = context.switchToHttp().getRequest();
|
||||
|
||||
try {
|
||||
const { userUuid, communityUuid } = req.body;
|
||||
|
||||
await this.checkUserIsFound(userUuid);
|
||||
|
||||
await this.checkCommunityIsFound(communityUuid);
|
||||
|
||||
return true;
|
||||
} catch (error) {
|
||||
this.handleGuardError(error, context);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private async checkUserIsFound(userUuid: string) {
|
||||
const userData = await this.userRepository.findOne({
|
||||
where: { uuid: userUuid },
|
||||
});
|
||||
if (!userData) {
|
||||
throw new NotFoundException('User not found');
|
||||
}
|
||||
}
|
||||
|
||||
private async checkCommunityIsFound(spaceUuid: string) {
|
||||
const spaceData = await this.spaceRepository.findOne({
|
||||
where: { uuid: spaceUuid, spaceType: { type: 'community' } },
|
||||
relations: ['spaceType'],
|
||||
});
|
||||
if (!spaceData) {
|
||||
throw new NotFoundException('Community not found');
|
||||
}
|
||||
}
|
||||
|
||||
private handleGuardError(error: Error, context: ExecutionContext) {
|
||||
const response = context.switchToHttp().getResponse();
|
||||
if (
|
||||
error instanceof BadRequestException ||
|
||||
error instanceof NotFoundException
|
||||
) {
|
||||
response
|
||||
.status(HttpStatus.NOT_FOUND)
|
||||
.json({ statusCode: HttpStatus.NOT_FOUND, message: error.message });
|
||||
} else {
|
||||
response.status(HttpStatus.BAD_REQUEST).json({
|
||||
statusCode: HttpStatus.BAD_REQUEST,
|
||||
message: 'invalid userUuid or communityUuid',
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
70
src/guards/user.floor.guard.ts
Normal file
70
src/guards/user.floor.guard.ts
Normal file
@ -0,0 +1,70 @@
|
||||
import {
|
||||
CanActivate,
|
||||
ExecutionContext,
|
||||
Injectable,
|
||||
HttpStatus,
|
||||
} from '@nestjs/common';
|
||||
import { SpaceRepository } from '@app/common/modules/space/repositories';
|
||||
import { BadRequestException, NotFoundException } from '@nestjs/common';
|
||||
import { UserRepository } from '@app/common/modules/user/repositories';
|
||||
|
||||
@Injectable()
|
||||
export class CheckUserFloorGuard implements CanActivate {
|
||||
constructor(
|
||||
private readonly spaceRepository: SpaceRepository,
|
||||
private readonly userRepository: UserRepository,
|
||||
) {}
|
||||
|
||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
const req = context.switchToHttp().getRequest();
|
||||
|
||||
try {
|
||||
const { userUuid, floorUuid } = req.body;
|
||||
|
||||
await this.checkUserIsFound(userUuid);
|
||||
|
||||
await this.checkFloorIsFound(floorUuid);
|
||||
|
||||
return true;
|
||||
} catch (error) {
|
||||
this.handleGuardError(error, context);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private async checkUserIsFound(userUuid: string) {
|
||||
const userData = await this.userRepository.findOne({
|
||||
where: { uuid: userUuid },
|
||||
});
|
||||
if (!userData) {
|
||||
throw new NotFoundException('User not found');
|
||||
}
|
||||
}
|
||||
|
||||
private async checkFloorIsFound(spaceUuid: string) {
|
||||
const spaceData = await this.spaceRepository.findOne({
|
||||
where: { uuid: spaceUuid, spaceType: { type: 'floor' } },
|
||||
relations: ['spaceType'],
|
||||
});
|
||||
if (!spaceData) {
|
||||
throw new NotFoundException('Floor not found');
|
||||
}
|
||||
}
|
||||
|
||||
private handleGuardError(error: Error, context: ExecutionContext) {
|
||||
const response = context.switchToHttp().getResponse();
|
||||
if (
|
||||
error instanceof BadRequestException ||
|
||||
error instanceof NotFoundException
|
||||
) {
|
||||
response
|
||||
.status(HttpStatus.NOT_FOUND)
|
||||
.json({ statusCode: HttpStatus.NOT_FOUND, message: error.message });
|
||||
} else {
|
||||
response.status(HttpStatus.BAD_REQUEST).json({
|
||||
statusCode: HttpStatus.BAD_REQUEST,
|
||||
message: 'invalid userUuid or floorUuid',
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
70
src/guards/user.room.guard.ts
Normal file
70
src/guards/user.room.guard.ts
Normal file
@ -0,0 +1,70 @@
|
||||
import {
|
||||
CanActivate,
|
||||
ExecutionContext,
|
||||
Injectable,
|
||||
HttpStatus,
|
||||
} from '@nestjs/common';
|
||||
import { SpaceRepository } from '@app/common/modules/space/repositories';
|
||||
import { BadRequestException, NotFoundException } from '@nestjs/common';
|
||||
import { UserRepository } from '@app/common/modules/user/repositories';
|
||||
|
||||
@Injectable()
|
||||
export class CheckUserRoomGuard implements CanActivate {
|
||||
constructor(
|
||||
private readonly spaceRepository: SpaceRepository,
|
||||
private readonly userRepository: UserRepository,
|
||||
) {}
|
||||
|
||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
const req = context.switchToHttp().getRequest();
|
||||
|
||||
try {
|
||||
const { userUuid, roomUuid } = req.body;
|
||||
|
||||
await this.checkUserIsFound(userUuid);
|
||||
|
||||
await this.checkRoomIsFound(roomUuid);
|
||||
|
||||
return true;
|
||||
} catch (error) {
|
||||
this.handleGuardError(error, context);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private async checkUserIsFound(userUuid: string) {
|
||||
const userData = await this.userRepository.findOne({
|
||||
where: { uuid: userUuid },
|
||||
});
|
||||
if (!userData) {
|
||||
throw new NotFoundException('User not found');
|
||||
}
|
||||
}
|
||||
|
||||
private async checkRoomIsFound(spaceUuid: string) {
|
||||
const spaceData = await this.spaceRepository.findOne({
|
||||
where: { uuid: spaceUuid, spaceType: { type: 'room' } },
|
||||
relations: ['spaceType'],
|
||||
});
|
||||
if (!spaceData) {
|
||||
throw new NotFoundException('Room not found');
|
||||
}
|
||||
}
|
||||
|
||||
private handleGuardError(error: Error, context: ExecutionContext) {
|
||||
const response = context.switchToHttp().getResponse();
|
||||
if (
|
||||
error instanceof BadRequestException ||
|
||||
error instanceof NotFoundException
|
||||
) {
|
||||
response
|
||||
.status(HttpStatus.NOT_FOUND)
|
||||
.json({ statusCode: HttpStatus.NOT_FOUND, message: error.message });
|
||||
} else {
|
||||
response.status(HttpStatus.BAD_REQUEST).json({
|
||||
statusCode: HttpStatus.BAD_REQUEST,
|
||||
message: 'invalid userUuid or roomUuid',
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
70
src/guards/user.unit.guard.ts
Normal file
70
src/guards/user.unit.guard.ts
Normal file
@ -0,0 +1,70 @@
|
||||
import {
|
||||
CanActivate,
|
||||
ExecutionContext,
|
||||
Injectable,
|
||||
HttpStatus,
|
||||
} from '@nestjs/common';
|
||||
import { SpaceRepository } from '@app/common/modules/space/repositories';
|
||||
import { BadRequestException, NotFoundException } from '@nestjs/common';
|
||||
import { UserRepository } from '@app/common/modules/user/repositories';
|
||||
|
||||
@Injectable()
|
||||
export class CheckUserUnitGuard implements CanActivate {
|
||||
constructor(
|
||||
private readonly spaceRepository: SpaceRepository,
|
||||
private readonly userRepository: UserRepository,
|
||||
) {}
|
||||
|
||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
const req = context.switchToHttp().getRequest();
|
||||
|
||||
try {
|
||||
const { userUuid, unitUuid } = req.body;
|
||||
|
||||
await this.checkUserIsFound(userUuid);
|
||||
|
||||
await this.checkUnitIsFound(unitUuid);
|
||||
|
||||
return true;
|
||||
} catch (error) {
|
||||
this.handleGuardError(error, context);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private async checkUserIsFound(userUuid: string) {
|
||||
const userData = await this.userRepository.findOne({
|
||||
where: { uuid: userUuid },
|
||||
});
|
||||
if (!userData) {
|
||||
throw new NotFoundException('User not found');
|
||||
}
|
||||
}
|
||||
|
||||
private async checkUnitIsFound(spaceUuid: string) {
|
||||
const spaceData = await this.spaceRepository.findOne({
|
||||
where: { uuid: spaceUuid, spaceType: { type: 'unit' } },
|
||||
relations: ['spaceType'],
|
||||
});
|
||||
if (!spaceData) {
|
||||
throw new NotFoundException('Unit not found');
|
||||
}
|
||||
}
|
||||
|
||||
private handleGuardError(error: Error, context: ExecutionContext) {
|
||||
const response = context.switchToHttp().getResponse();
|
||||
if (
|
||||
error instanceof BadRequestException ||
|
||||
error instanceof NotFoundException
|
||||
) {
|
||||
response
|
||||
.status(HttpStatus.NOT_FOUND)
|
||||
.json({ statusCode: HttpStatus.NOT_FOUND, message: error.message });
|
||||
} else {
|
||||
response.status(HttpStatus.BAD_REQUEST).json({
|
||||
statusCode: HttpStatus.BAD_REQUEST,
|
||||
message: 'invalid userUuid or unitUuid',
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -12,9 +12,10 @@ import {
|
||||
} from '@nestjs/common';
|
||||
import { ApiTags, ApiBearerAuth } from '@nestjs/swagger';
|
||||
import { JwtAuthGuard } from '../../../libs/common/src/guards/jwt.auth.guard';
|
||||
import { AddRoomDto } from '../dtos/add.room.dto';
|
||||
import { AddRoomDto, AddUserRoomDto } from '../dtos/add.room.dto';
|
||||
import { UpdateRoomNameDto } from '../dtos/update.room.dto';
|
||||
import { CheckUnitTypeGuard } from 'src/guards/unit.type.guard';
|
||||
import { CheckUserRoomGuard } from 'src/guards/user.room.guard';
|
||||
|
||||
@ApiTags('Room Module')
|
||||
@Controller({
|
||||
@ -68,6 +69,33 @@ export class RoomController {
|
||||
);
|
||||
}
|
||||
}
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard, CheckUserRoomGuard)
|
||||
@Post('user')
|
||||
async addUserRoom(@Body() addUserRoomDto: AddUserRoomDto) {
|
||||
try {
|
||||
await this.roomService.addUserRoom(addUserRoomDto);
|
||||
return { message: 'user room added successfully' };
|
||||
} catch (error) {
|
||||
throw new HttpException(
|
||||
error.message || 'Internal server error',
|
||||
error.status || HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
}
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@Get('user/:userUuid')
|
||||
async getRoomsByUserId(@Param('userUuid') userUuid: string) {
|
||||
try {
|
||||
return await this.roomService.getRoomsByUserId(userUuid);
|
||||
} catch (error) {
|
||||
throw new HttpException(
|
||||
error.message || 'Internal server error',
|
||||
error.status || HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard)
|
||||
|
||||
@ -21,3 +21,22 @@ export class AddRoomDto {
|
||||
Object.assign(this, dto);
|
||||
}
|
||||
}
|
||||
export class AddUserRoomDto {
|
||||
@ApiProperty({
|
||||
description: 'roomUuid',
|
||||
required: true,
|
||||
})
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
public roomUuid: string;
|
||||
@ApiProperty({
|
||||
description: 'userUuid',
|
||||
required: true,
|
||||
})
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
public userUuid: string;
|
||||
constructor(dto: Partial<AddUserRoomDto>) {
|
||||
Object.assign(this, dto);
|
||||
}
|
||||
}
|
||||
|
||||
@ -17,3 +17,8 @@ export interface RenameRoomByUuidInterface {
|
||||
name: string;
|
||||
type: string;
|
||||
}
|
||||
export interface GetRoomByUserUuidInterface {
|
||||
uuid: string;
|
||||
name: string;
|
||||
type: string;
|
||||
}
|
||||
|
||||
@ -6,11 +6,27 @@ import { SpaceRepositoryModule } from '@app/common/modules/space/space.repositor
|
||||
import { SpaceRepository } from '@app/common/modules/space/repositories';
|
||||
import { SpaceTypeRepositoryModule } from '@app/common/modules/space-type/space.type.repository.module';
|
||||
import { SpaceTypeRepository } from '@app/common/modules/space-type/repositories';
|
||||
import { UserSpaceRepositoryModule } from '@app/common/modules/user-space/user.space.repository.module';
|
||||
import { UserSpaceRepository } from '@app/common/modules/user-space/repositories';
|
||||
import { UserRepositoryModule } from '@app/common/modules/user/user.repository.module';
|
||||
import { UserRepository } from '@app/common/modules/user/repositories';
|
||||
|
||||
@Module({
|
||||
imports: [ConfigModule, SpaceRepositoryModule, SpaceTypeRepositoryModule],
|
||||
imports: [
|
||||
ConfigModule,
|
||||
SpaceRepositoryModule,
|
||||
SpaceTypeRepositoryModule,
|
||||
UserSpaceRepositoryModule,
|
||||
UserRepositoryModule,
|
||||
],
|
||||
controllers: [RoomController],
|
||||
providers: [RoomService, SpaceRepository, SpaceTypeRepository],
|
||||
providers: [
|
||||
RoomService,
|
||||
SpaceRepository,
|
||||
SpaceTypeRepository,
|
||||
UserSpaceRepository,
|
||||
UserRepository,
|
||||
],
|
||||
exports: [RoomService],
|
||||
})
|
||||
export class RoomModule {}
|
||||
|
||||
@ -6,19 +6,22 @@ import {
|
||||
BadRequestException,
|
||||
} from '@nestjs/common';
|
||||
import { SpaceRepository } from '@app/common/modules/space/repositories';
|
||||
import { AddRoomDto } from '../dtos';
|
||||
import { AddRoomDto, AddUserRoomDto } from '../dtos';
|
||||
import {
|
||||
RoomParentInterface,
|
||||
GetRoomByUuidInterface,
|
||||
RenameRoomByUuidInterface,
|
||||
GetRoomByUserUuidInterface,
|
||||
} from '../interface/room.interface';
|
||||
import { UpdateRoomNameDto } from '../dtos/update.room.dto';
|
||||
import { UserSpaceRepository } from '@app/common/modules/user-space/repositories';
|
||||
|
||||
@Injectable()
|
||||
export class RoomService {
|
||||
constructor(
|
||||
private readonly spaceRepository: SpaceRepository,
|
||||
private readonly spaceTypeRepository: SpaceTypeRepository,
|
||||
private readonly userSpaceRepository: UserSpaceRepository,
|
||||
) {}
|
||||
|
||||
async addRoom(addRoomDto: AddRoomDto) {
|
||||
@ -103,6 +106,56 @@ export class RoomService {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async getRoomsByUserId(
|
||||
userUuid: string,
|
||||
): Promise<GetRoomByUserUuidInterface[]> {
|
||||
try {
|
||||
const rooms = await this.userSpaceRepository.find({
|
||||
relations: ['space', 'space.spaceType'],
|
||||
where: {
|
||||
user: { uuid: userUuid },
|
||||
space: { spaceType: { type: 'room' } },
|
||||
},
|
||||
});
|
||||
|
||||
if (rooms.length === 0) {
|
||||
throw new HttpException('this user has no rooms', HttpStatus.NOT_FOUND);
|
||||
}
|
||||
const spaces = rooms.map((room) => ({
|
||||
uuid: room.space.uuid,
|
||||
name: room.space.spaceName,
|
||||
type: room.space.spaceType.type,
|
||||
}));
|
||||
|
||||
return spaces;
|
||||
} catch (err) {
|
||||
if (err instanceof HttpException) {
|
||||
throw err;
|
||||
} else {
|
||||
throw new HttpException('user not found', HttpStatus.NOT_FOUND);
|
||||
}
|
||||
}
|
||||
}
|
||||
async addUserRoom(addUserRoomDto: AddUserRoomDto) {
|
||||
try {
|
||||
await this.userSpaceRepository.save({
|
||||
user: { uuid: addUserRoomDto.userUuid },
|
||||
space: { uuid: addUserRoomDto.roomUuid },
|
||||
});
|
||||
} catch (err) {
|
||||
if (err.code === '23505') {
|
||||
throw new HttpException(
|
||||
'User already belongs to this room',
|
||||
HttpStatus.BAD_REQUEST,
|
||||
);
|
||||
}
|
||||
throw new HttpException(
|
||||
err.message || 'Internal Server Error',
|
||||
HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
}
|
||||
async renameRoomByUuid(
|
||||
roomUuid: string,
|
||||
updateRoomNameDto: UpdateRoomNameDto,
|
||||
|
||||
@ -13,10 +13,11 @@ import {
|
||||
} from '@nestjs/common';
|
||||
import { ApiTags, ApiBearerAuth } from '@nestjs/swagger';
|
||||
import { JwtAuthGuard } from '../../../libs/common/src/guards/jwt.auth.guard';
|
||||
import { AddUnitDto } from '../dtos/add.unit.dto';
|
||||
import { AddUnitDto, AddUserUnitDto } from '../dtos/add.unit.dto';
|
||||
import { GetUnitChildDto } from '../dtos/get.unit.dto';
|
||||
import { UpdateUnitNameDto } from '../dtos/update.unit.dto';
|
||||
import { CheckFloorTypeGuard } from 'src/guards/floor.type.guard';
|
||||
import { CheckUserUnitGuard } from 'src/guards/user.unit.guard';
|
||||
|
||||
@ApiTags('Unit Module')
|
||||
@Controller({
|
||||
@ -87,6 +88,33 @@ export class UnitController {
|
||||
);
|
||||
}
|
||||
}
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard, CheckUserUnitGuard)
|
||||
@Post('user')
|
||||
async addUserUnit(@Body() addUserUnitDto: AddUserUnitDto) {
|
||||
try {
|
||||
await this.unitService.addUserUnit(addUserUnitDto);
|
||||
return { message: 'user unit added successfully' };
|
||||
} catch (error) {
|
||||
throw new HttpException(
|
||||
error.message || 'Internal server error',
|
||||
error.status || HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
}
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@Get('user/:userUuid')
|
||||
async getUnitsByUserId(@Param('userUuid') userUuid: string) {
|
||||
try {
|
||||
return await this.unitService.getUnitsByUserId(userUuid);
|
||||
} catch (error) {
|
||||
throw new HttpException(
|
||||
error.message || 'Internal server error',
|
||||
error.status || HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard)
|
||||
|
||||
@ -21,3 +21,22 @@ export class AddUnitDto {
|
||||
Object.assign(this, dto);
|
||||
}
|
||||
}
|
||||
export class AddUserUnitDto {
|
||||
@ApiProperty({
|
||||
description: 'unitUuid',
|
||||
required: true,
|
||||
})
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
public unitUuid: string;
|
||||
@ApiProperty({
|
||||
description: 'userUuid',
|
||||
required: true,
|
||||
})
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
public userUuid: string;
|
||||
constructor(dto: Partial<AddUserUnitDto>) {
|
||||
Object.assign(this, dto);
|
||||
}
|
||||
}
|
||||
|
||||
@ -49,3 +49,12 @@ export class GetUnitChildDto {
|
||||
})
|
||||
public includeSubSpaces: boolean = false;
|
||||
}
|
||||
export class GetUnitByUserIdDto {
|
||||
@ApiProperty({
|
||||
description: 'userUuid',
|
||||
required: true,
|
||||
})
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
public userUuid: string;
|
||||
}
|
||||
|
||||
@ -24,3 +24,8 @@ export interface RenameUnitByUuidInterface {
|
||||
name: string;
|
||||
type: string;
|
||||
}
|
||||
export interface GetUnitByUserUuidInterface {
|
||||
uuid: string;
|
||||
name: string;
|
||||
type: string;
|
||||
}
|
||||
|
||||
@ -7,21 +7,24 @@ import {
|
||||
BadRequestException,
|
||||
} from '@nestjs/common';
|
||||
import { SpaceRepository } from '@app/common/modules/space/repositories';
|
||||
import { AddUnitDto } from '../dtos';
|
||||
import { AddUnitDto, AddUserUnitDto } from '../dtos';
|
||||
import {
|
||||
UnitChildInterface,
|
||||
UnitParentInterface,
|
||||
GetUnitByUuidInterface,
|
||||
RenameUnitByUuidInterface,
|
||||
GetUnitByUserUuidInterface,
|
||||
} from '../interface/unit.interface';
|
||||
import { SpaceEntity } from '@app/common/modules/space/entities';
|
||||
import { UpdateUnitNameDto } from '../dtos/update.unit.dto';
|
||||
import { UserSpaceRepository } from '@app/common/modules/user-space/repositories';
|
||||
|
||||
@Injectable()
|
||||
export class UnitService {
|
||||
constructor(
|
||||
private readonly spaceRepository: SpaceRepository,
|
||||
private readonly spaceTypeRepository: SpaceTypeRepository,
|
||||
private readonly userSpaceRepository: UserSpaceRepository,
|
||||
) {}
|
||||
|
||||
async addUnit(addUnitDto: AddUnitDto) {
|
||||
@ -195,7 +198,56 @@ export class UnitService {
|
||||
}
|
||||
}
|
||||
}
|
||||
async getUnitsByUserId(
|
||||
userUuid: string,
|
||||
): Promise<GetUnitByUserUuidInterface[]> {
|
||||
try {
|
||||
const units = await this.userSpaceRepository.find({
|
||||
relations: ['space', 'space.spaceType'],
|
||||
where: {
|
||||
user: { uuid: userUuid },
|
||||
space: { spaceType: { type: 'unit' } },
|
||||
},
|
||||
});
|
||||
|
||||
if (units.length === 0) {
|
||||
throw new HttpException('this user has no units', HttpStatus.NOT_FOUND);
|
||||
}
|
||||
const spaces = units.map((unit) => ({
|
||||
uuid: unit.space.uuid,
|
||||
name: unit.space.spaceName,
|
||||
type: unit.space.spaceType.type,
|
||||
}));
|
||||
|
||||
return spaces;
|
||||
} catch (err) {
|
||||
if (err instanceof HttpException) {
|
||||
throw err;
|
||||
} else {
|
||||
throw new HttpException('user not found', HttpStatus.NOT_FOUND);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async addUserUnit(addUserUnitDto: AddUserUnitDto) {
|
||||
try {
|
||||
await this.userSpaceRepository.save({
|
||||
user: { uuid: addUserUnitDto.userUuid },
|
||||
space: { uuid: addUserUnitDto.unitUuid },
|
||||
});
|
||||
} catch (err) {
|
||||
if (err.code === '23505') {
|
||||
throw new HttpException(
|
||||
'User already belongs to this unit',
|
||||
HttpStatus.BAD_REQUEST,
|
||||
);
|
||||
}
|
||||
throw new HttpException(
|
||||
err.message || 'Internal Server Error',
|
||||
HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
}
|
||||
async renameUnitByUuid(
|
||||
unitUuid: string,
|
||||
updateUnitNameDto: UpdateUnitNameDto,
|
||||
|
||||
@ -6,11 +6,27 @@ import { SpaceRepositoryModule } from '@app/common/modules/space/space.repositor
|
||||
import { SpaceRepository } from '@app/common/modules/space/repositories';
|
||||
import { SpaceTypeRepositoryModule } from '@app/common/modules/space-type/space.type.repository.module';
|
||||
import { SpaceTypeRepository } from '@app/common/modules/space-type/repositories';
|
||||
import { UserSpaceRepositoryModule } from '@app/common/modules/user-space/user.space.repository.module';
|
||||
import { UserSpaceRepository } from '@app/common/modules/user-space/repositories';
|
||||
import { UserRepositoryModule } from '@app/common/modules/user/user.repository.module';
|
||||
import { UserRepository } from '@app/common/modules/user/repositories';
|
||||
|
||||
@Module({
|
||||
imports: [ConfigModule, SpaceRepositoryModule, SpaceTypeRepositoryModule],
|
||||
imports: [
|
||||
ConfigModule,
|
||||
SpaceRepositoryModule,
|
||||
SpaceTypeRepositoryModule,
|
||||
UserSpaceRepositoryModule,
|
||||
UserRepositoryModule,
|
||||
],
|
||||
controllers: [UnitController],
|
||||
providers: [UnitService, SpaceRepository, SpaceTypeRepository],
|
||||
providers: [
|
||||
UnitService,
|
||||
SpaceRepository,
|
||||
SpaceTypeRepository,
|
||||
UserSpaceRepository,
|
||||
UserRepository,
|
||||
],
|
||||
exports: [UnitService],
|
||||
})
|
||||
export class UnitModule {}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user