mirror of
https://github.com/SyncrowIOT/backend.git
synced 2025-07-10 15:17:41 +00:00
Compare commits
475 Commits
5129724a8a
...
refactor/a
Author | SHA1 | Date | |
---|---|---|---|
7ea53feddc | |||
c7a4ff1194 | |||
8a4633b158 | |||
f80d097ff8 | |||
04bd156df1 | |||
731819aeaa | |||
68d2d3b53d | |||
3fcfe2d92f | |||
c0a069b460 | |||
30724d7d37 | |||
324661e1ee | |||
a83424f45b | |||
71f6ccb4db | |||
68692b7c8b | |||
4d60c1ed54 | |||
27dbe04299 | |||
9bebcb2f3e | |||
43ab0030f0 | |||
c48adb73b5 | |||
d255e6811e | |||
e58d2d4831 | |||
147cf0b582 | |||
4e6b6f6ac5 | |||
932a3efd1c | |||
0a1ccad120 | |||
f337e6c681 | |||
f5bf857071 | |||
d1d4d529a8 | |||
37b582f521 | |||
cf19f08dca | |||
ff370b2baa | |||
04f64407e1 | |||
d7eef5d03e | |||
c8d691b380 | |||
75d03366c2 | |||
52cb69cc84 | |||
a6053b3971 | |||
60d2c8330b | |||
fddd06e06d | |||
3160773c2a | |||
110ed4157a | |||
aa9e90bf08 | |||
c5dd5e28fd | |||
603e74af09 | |||
0e36f32ed6 | |||
705ceeba29 | |||
a37d5bb299 | |||
689a38ee0c | |||
a91d0f22a4 | |||
0db060ae3f | |||
f2ed04f206 | |||
ea9a65178d | |||
8503ee728d | |||
4f5e1b23f6 | |||
2cb77504ca | |||
c86be27576 | |||
3a08f9f258 | |||
5c96a3b117 | |||
97e14e70f7 | |||
03d44cb14f | |||
0793441e06 | |||
b6321c2530 | |||
b8d34b0d9f | |||
c1065126aa | |||
1742454984 | |||
7eb13088ac | |||
7b97e50d2e | |||
4fb26fc131 | |||
ee0261d102 | |||
0d6de2df43 | |||
80e89dd035 | |||
466863e71f | |||
30aafdede6 | |||
01ce4d4b29 | |||
43dfaaa90d | |||
ea021ad228 | |||
cd3e9016f2 | |||
ef2245eae1 | |||
3ad81864d1 | |||
ab3efedc35 | |||
4a984ae5dd | |||
c39129f75b | |||
35ce13a67f | |||
12a9272b8b | |||
0fe6c80731 | |||
81e017430e | |||
191d0dfaf6 | |||
5b0135ba80 | |||
2fee8c055e | |||
59161d4049 | |||
b989338790 | |||
f5ed9d4fce | |||
3ac48183bd | |||
684205053d | |||
bfd92fdd87 | |||
dd54af5f46 | |||
90fc44ab53 | |||
efdf918159 | |||
25967d02f9 | |||
f44dc793a6 | |||
a7c4bf1c3d | |||
a8bb161ee2 | |||
fe891030aa | |||
f2e515b180 | |||
f7fd96afa1 | |||
5292271721 | |||
180d16eeb1 | |||
dca3db0c59 | |||
56e78683b3 | |||
e575e51c4c | |||
8750da7e62 | |||
e3e9fe82fc | |||
e253d1ca03 | |||
b50d7682f3 | |||
1bb3803229 | |||
92ee6ee951 | |||
c06be4736c | |||
5cb4295f8a | |||
67331aa92a | |||
7ec41f8311 | |||
4aa3d04478 | |||
799fcb6fb9 | |||
921770ea79 | |||
7ec4171e1a | |||
c0a6e9ab63 | |||
208281386d | |||
fb5084ba3a | |||
9c3abdd08a | |||
3535c1d8c5 | |||
2ba5700fdd | |||
1479c74423 | |||
8030644fee | |||
d43e860867 | |||
f8269df3fb | |||
c085514d27 | |||
fa3cb578df | |||
b4572beec2 | |||
303493ad45 | |||
dc06cfff37 | |||
b3e86ec56f | |||
45b8cdcaae | |||
10005c7897 | |||
59ffa233ee | |||
078de317e4 | |||
ab89a13f95 | |||
adf1c5e2e0 | |||
5ed59e4fcc | |||
91abfb41ab | |||
d40fb7a762 | |||
71f795babe | |||
0d48505eac | |||
e538f2b829 | |||
23af8e9de3 | |||
d197bf2bb4 | |||
2a1f1f52f6 | |||
606de2e0e3 | |||
76806f8df4 | |||
22436af903 | |||
e932d8a4a4 | |||
0fcd974af2 | |||
e64025b420 | |||
aee6b8df69 | |||
a12046eee2 | |||
46325def06 | |||
796f5c6c08 | |||
e365cb0b50 | |||
cc755e5640 | |||
ccba81ef1f | |||
25403d5e19 | |||
62f2a6c3c9 | |||
dfee2d6524 | |||
8040594dc6 | |||
3eb6e1040c | |||
588d4cb98e | |||
94881f0555 | |||
6b8aa6836d | |||
ff731ceea0 | |||
6de81333ce | |||
488943338b | |||
387862a6bb | |||
72e65882b1 | |||
1bdb13846f | |||
0ee26698ff | |||
96b911bfa1 | |||
f9e1219f55 | |||
e98633749d | |||
9844e13f42 | |||
2594c1229b | |||
04c2c42523 | |||
45eec4bb30 | |||
51bf4c0170 | |||
fa3f49af18 | |||
28ec0377bc | |||
881618a4ee | |||
f3fd6646a1 | |||
3c5b97f2f9 | |||
7249a0badb | |||
92f908c0fb | |||
7f43ef5de5 | |||
61a7e1c742 | |||
5490b5781d | |||
531f93d42c | |||
0749fab633 | |||
9da8214041 | |||
b8f283f5ce | |||
ea1201307c | |||
fde34dcf9c | |||
8228ccc293 | |||
38e9ce5a47 | |||
59d526103c | |||
516a885251 | |||
6bc068c5e6 | |||
d1bc723834 | |||
cb2056d1b3 | |||
cff947a84a | |||
e019774f58 | |||
6330f7823b | |||
fea5d4d828 | |||
8072812b4b | |||
ce7fc0114e | |||
dabf234349 | |||
055518d672 | |||
aa9a11217b | |||
2470c8e09a | |||
fcb27155d8 | |||
506f3dae29 | |||
acbfa450f6 | |||
1b3eb08fcb | |||
069cdf6f75 | |||
2f12189eef | |||
69f87b0999 | |||
be3c9f730d | |||
ed3c526efd | |||
2b449e61ea | |||
1e6503c072 | |||
d341c47286 | |||
c34011660f | |||
c677be400c | |||
25650ca91b | |||
eba3513e14 | |||
f2aad9c6be | |||
2010e631f2 | |||
4810cc6f35 | |||
d24e7be4ea | |||
5d379e0c36 | |||
78cb65d712 | |||
dbabd28624 | |||
32112930c8 | |||
30dd8318e3 | |||
9f3dce535d | |||
846b7e6463 | |||
f723b63a91 | |||
7ba8c78868 | |||
7be4e4eeef | |||
f71279ea30 | |||
303ea696cb | |||
777105fc28 | |||
3745962827 | |||
a3001c8bb8 | |||
5bc69f869d | |||
f9eee8e266 | |||
de09624db8 | |||
d11c6a88f1 | |||
bac978e2b6 | |||
9c676a5231 | |||
473f028b45 | |||
e04f68a7ac | |||
22d98fa177 | |||
5e2e95b098 | |||
36394ae214 | |||
c7fc4e3a5d | |||
cf8cf08bdc | |||
cbd3f5028b | |||
5f45876516 | |||
1a39d1c1bb | |||
cd05c9906d | |||
ef9cf6ad28 | |||
c5dac6c564 | |||
a4b743eb58 | |||
ee28d04c76 | |||
6785fb2b1e | |||
8efd8cfba2 | |||
2712ce673a | |||
794e12d5d3 | |||
fb2e0c6cba | |||
338b73ac7a | |||
d09bdd1f6e | |||
dd1229db9c | |||
9bc763bad3 | |||
b5469cb316 | |||
670c026cfd | |||
611cee79b3 | |||
b0a403b0cf | |||
1a313c103d | |||
30badcde67 | |||
770d08ce08 | |||
770ece21b3 | |||
ec851eda9d | |||
39ac2e6860 | |||
9902b02700 | |||
990bcffc2f | |||
a9045a458c | |||
9f30f0e2c2 | |||
70047dd337 | |||
89ff05b6ef | |||
a495563c42 | |||
1f25e09388 | |||
532ded3624 | |||
3d3dcf17dd | |||
378ff1751b | |||
76fd4b640f | |||
f8f4bf525d | |||
d24b1d88d7 | |||
8b3232b2f4 | |||
1aea072692 | |||
c6f314e5c4 | |||
ef39e9cfa7 | |||
8cbbb3a8ba | |||
537f20f8de | |||
8456eea5dc | |||
1ce2f3c3cc | |||
481ed5e7f9 | |||
67a78dbdfd | |||
5c47a3195f | |||
5b1c14300e | |||
1403a670e3 | |||
b6fa37b1a3 | |||
5204cd5504 | |||
fa009d6f6e | |||
9f83b4286c | |||
5434b8324d | |||
1ead195d52 | |||
7fae1bf407 | |||
4440a909f3 | |||
7cc5fd2b54 | |||
f9f9592603 | |||
c62c952544 | |||
f9878ff272 | |||
64f83cbda2 | |||
45a3020b39 | |||
6e329d096d | |||
eb42948d8e | |||
3367ca8fab | |||
9122137922 | |||
440be3d423 | |||
cacaa105ed | |||
7dc2a8d0c9 | |||
7e513f0d31 | |||
a8fbf2b510 | |||
04d64a6f38 | |||
b9f0987bb0 | |||
aa609266c7 | |||
f6d47d0e39 | |||
ea09f633ee | |||
404c0457a7 | |||
5e9de023ac | |||
c459cadb41 | |||
c8d72a90b6 | |||
283e9406b6 | |||
d1a976d152 | |||
3bbc39734b | |||
c6793a46a5 | |||
054df46936 | |||
08db0bd153 | |||
63f1f7a7c0 | |||
36612a40b9 | |||
1220ee395d | |||
226781e53f | |||
76d29bab16 | |||
cd781024fe | |||
dd56300b96 | |||
c400e6f9d6 | |||
d64e78f03e | |||
9fce11b8c1 | |||
31e84b4a25 | |||
107ec72e81 | |||
61fc699cf8 | |||
a68f4c1847 | |||
1f18f50923 | |||
772459a106 | |||
f7848a7394 | |||
5e6c7bef9e | |||
372d2c680d | |||
d0d1dd615a | |||
61692c70d1 | |||
07828eafd7 | |||
ed406addb8 | |||
6805ff226c | |||
6864e000b8 | |||
823cb6cf7a | |||
547e37dadb | |||
81a0bc8bbc | |||
0d4afc40f2 | |||
9c279d9655 | |||
6a4361515d | |||
1caecfe6d9 | |||
19c02da8ad | |||
0d3ec0bea1 | |||
553cdb28bf | |||
34f4b61ae0 | |||
d059171b72 | |||
4e43954175 | |||
2b6f6be149 | |||
b4c3ee486e | |||
5d5984da80 | |||
95ecbab165 | |||
221a2af32b | |||
8a5709b1c9 | |||
35e658a3f6 | |||
e17a3fdda8 | |||
810ca87301 | |||
e9cda53636 | |||
416329771b | |||
e90f9d44fc | |||
9250b08b17 | |||
1d71be4b06 | |||
d85b374f05 | |||
a9e5454b61 | |||
902ddbab50 | |||
b6c305a6f7 | |||
2582b88c8c | |||
7ddc39a7eb | |||
419a10e055 | |||
e3e2981673 | |||
cb6d359810 | |||
2a5b35a297 | |||
60a4fb8ea2 | |||
f98c3cd4ad | |||
5d962b3c6e | |||
25f5c62ecf | |||
9297f1efb3 | |||
6b20428719 | |||
8ecd368b16 | |||
8739edb6e9 | |||
aed9719178 | |||
ed1c7ff167 | |||
edf1cd4157 | |||
4326ac1900 | |||
cd8d368e21 | |||
2bdc406cf7 | |||
630b3ee2b9 | |||
bcd976e1b2 | |||
67ce73754b | |||
acc8f3ef4d | |||
4391339e5e | |||
d13da50fd7 | |||
394dd0dd6d | |||
1140709e80 | |||
a0790f0b48 | |||
c52d0981db | |||
6550ed68f6 | |||
c2a6012063 | |||
4adb1e683d | |||
6301da0665 | |||
c7ffba7290 | |||
0059562319 | |||
7ddd75041e | |||
07d31bb8bd | |||
61a85789d1 | |||
565b0f72b7 | |||
19ef10aa87 | |||
733ccee88d | |||
afec306681 | |||
6fbeef97df | |||
29d9909c8e | |||
2dcce3cce3 | |||
427a57501f | |||
b59230d5d8 | |||
e276d4651d | |||
9eb9b92be3 | |||
b2b8d02400 | |||
b793597711 | |||
a99b759882 | |||
0fe456aaed | |||
7546dbbf35 |
@ -21,6 +21,7 @@ module.exports = {
|
||||
'@typescript-eslint/explicit-function-return-type': 'off',
|
||||
'@typescript-eslint/explicit-module-boundary-types': 'off',
|
||||
'@typescript-eslint/no-explicit-any': 'off',
|
||||
"@typescript-eslint/no-unused-vars": 'warn',
|
||||
},
|
||||
settings: {
|
||||
'import/resolver': {
|
||||
|
84
.github/workflows/main_syncrow(staging).yml
vendored
84
.github/workflows/main_syncrow(staging).yml
vendored
@ -1,7 +1,4 @@
|
||||
# Docs for the Azure Web Apps Deploy action: https://github.com/Azure/webapps-deploy
|
||||
# More GitHub Actions for Azure: https://github.com/Azure/actions
|
||||
|
||||
name: Build and deploy container app to Azure Web App - syncrow(staging)
|
||||
name: Backend deployment to Azure App Service
|
||||
|
||||
on:
|
||||
push:
|
||||
@ -9,43 +6,50 @@ on:
|
||||
- main
|
||||
workflow_dispatch:
|
||||
|
||||
env:
|
||||
AZURE_WEB_APP_NAME: 'syncrow'
|
||||
AZURE_WEB_APP_SLOT_NAME: 'staging'
|
||||
ACR_REGISTRY: 'syncrow.azurecr.io'
|
||||
IMAGE_NAME: 'backend'
|
||||
IMAGE_TAG: 'latest'
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: 'ubuntu-latest'
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v2
|
||||
|
||||
- name: Log in to registry
|
||||
uses: docker/login-action@v2
|
||||
with:
|
||||
registry: https://syncrow.azurecr.io/
|
||||
username: ${{ secrets.AzureAppService_ContainerUsername_47395803300340b49931ea82f6d80be3 }}
|
||||
password: ${{ secrets.AzureAppService_ContainerPassword_e7b0ff54f54d44cba04a970a22384848 }}
|
||||
|
||||
- name: Build and push container image to registry
|
||||
uses: docker/build-push-action@v3
|
||||
with:
|
||||
push: true
|
||||
tags: syncrow.azurecr.io/${{ secrets.AzureAppService_ContainerUsername_47395803300340b49931ea82f6d80be3 }}/syncrow/backend:${{ github.sha }}
|
||||
file: ./Dockerfile
|
||||
|
||||
deploy:
|
||||
build_and_deploy:
|
||||
runs-on: ubuntu-latest
|
||||
needs: build
|
||||
environment:
|
||||
name: 'staging'
|
||||
url: ${{ steps.deploy-to-webapp.outputs.webapp-url }}
|
||||
|
||||
steps:
|
||||
- name: Deploy to Azure Web App
|
||||
id: deploy-to-webapp
|
||||
uses: azure/webapps-deploy@v2
|
||||
with:
|
||||
app-name: 'syncrow'
|
||||
slot-name: 'staging'
|
||||
publish-profile: ${{ secrets.AzureAppService_PublishProfile_44f7766441ec4796b74789e9761ef589 }}
|
||||
images: 'syncrow.azurecr.io/${{ secrets.AzureAppService_ContainerUsername_47395803300340b49931ea82f6d80be3 }}/syncrow/backend:${{ github.sha }}'
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Set up Node.js
|
||||
uses: actions/setup-node@v3
|
||||
with:
|
||||
node-version: '20'
|
||||
|
||||
- name: Install dependencies and build project
|
||||
run: |
|
||||
npm install
|
||||
npm run build
|
||||
|
||||
- name: Log in to Azure
|
||||
uses: azure/login@v1
|
||||
with:
|
||||
creds: ${{ secrets.AZURE_CREDENTIALS }}
|
||||
|
||||
- name: Log in to Azure Container Registry
|
||||
run: az acr login --name ${{ env.ACR_REGISTRY }}
|
||||
|
||||
- name: List build output
|
||||
run: ls -R dist/
|
||||
|
||||
- name: Build and push Docker image
|
||||
run: |
|
||||
docker build . -t ${{ env.ACR_REGISTRY }}/${{ env.IMAGE_NAME }}:${{ env.IMAGE_TAG }}
|
||||
docker push ${{ env.ACR_REGISTRY }}/${{ env.IMAGE_NAME }}:${{ env.IMAGE_TAG }}
|
||||
|
||||
- name: Set Web App with Docker container
|
||||
run: |
|
||||
az webapp config container set \
|
||||
--name ${{ env.AZURE_WEB_APP_NAME }} \
|
||||
--resource-group backend \
|
||||
--docker-custom-image-name ${{ env.ACR_REGISTRY }}/${{ env.IMAGE_NAME }}:${{ env.IMAGE_TAG }} \
|
||||
--docker-registry-server-url https://${{ env.ACR_REGISTRY }}
|
||||
|
3
.gitignore
vendored
3
.gitignore
vendored
@ -3,6 +3,9 @@
|
||||
/node_modules
|
||||
/build
|
||||
|
||||
#github
|
||||
/.github
|
||||
|
||||
# Logs
|
||||
logs
|
||||
*.log
|
||||
|
@ -5,4 +5,5 @@ export class AuthInterface {
|
||||
sessionId: string;
|
||||
id: number;
|
||||
role?: object;
|
||||
project?: object;
|
||||
}
|
||||
|
@ -1,18 +1,18 @@
|
||||
import { PlatformType } from '@app/common/constants/platform-type.enum';
|
||||
import { RoleType } from '@app/common/constants/role.type.enum';
|
||||
import {
|
||||
BadRequestException,
|
||||
Injectable,
|
||||
UnauthorizedException,
|
||||
} from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
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';
|
||||
import { OAuth2Client } from 'google-auth-library';
|
||||
import { PlatformType } from '@app/common/constants/platform-type.enum';
|
||||
import { RoleType } from '@app/common/constants/role.type.enum';
|
||||
import { UserSessionEntity } from '../../../../common/src/modules/session/entities';
|
||||
import { UserSessionRepository } from '../../../../common/src/modules/session/repositories/session.repository';
|
||||
import { UserRepository } from '../../../../common/src/modules/user/repositories';
|
||||
import { HelperHashService } from '../../helper/services';
|
||||
|
||||
@Injectable()
|
||||
export class AuthService {
|
||||
@ -38,18 +38,19 @@ export class AuthService {
|
||||
email,
|
||||
region: regionUuid ? { uuid: regionUuid } : undefined,
|
||||
},
|
||||
relations: ['roleType'],
|
||||
relations: ['roleType', 'project'],
|
||||
});
|
||||
if (
|
||||
platform === PlatformType.WEB &&
|
||||
(user.roleType.type === RoleType.SPACE_OWNER ||
|
||||
user.roleType.type === RoleType.SPACE_MEMBER)
|
||||
) {
|
||||
throw new UnauthorizedException('Access denied for web platform');
|
||||
}
|
||||
if (!user) {
|
||||
throw new BadRequestException('Invalid credentials');
|
||||
}
|
||||
if (
|
||||
platform === PlatformType.WEB &&
|
||||
[RoleType.SPACE_OWNER, RoleType.SPACE_MEMBER].includes(
|
||||
user.roleType.type as RoleType,
|
||||
)
|
||||
) {
|
||||
throw new UnauthorizedException('Access denied for web platform');
|
||||
}
|
||||
|
||||
if (!user.isUserVerified) {
|
||||
throw new BadRequestException('User is not verified');
|
||||
@ -77,21 +78,28 @@ export class AuthService {
|
||||
return await this.sessionRepository.save(data);
|
||||
}
|
||||
|
||||
async getTokens(payload) {
|
||||
async getTokens(
|
||||
payload,
|
||||
isRefreshToken = true,
|
||||
accessTokenExpiry = '24h',
|
||||
refreshTokenExpiry = '30d',
|
||||
) {
|
||||
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',
|
||||
expiresIn: accessTokenExpiry,
|
||||
}),
|
||||
isRefreshToken
|
||||
? this.jwtService.signAsync(payload, {
|
||||
secret: this.configService.get<string>('JWT_SECRET'),
|
||||
expiresIn: refreshTokenExpiry,
|
||||
})
|
||||
: null,
|
||||
]);
|
||||
|
||||
return {
|
||||
accessToken,
|
||||
refreshToken,
|
||||
...(isRefreshToken ? { refreshToken } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
@ -105,6 +113,7 @@ export class AuthService {
|
||||
googleCode: user.googleCode,
|
||||
hasAcceptedWebAgreement: user.hasAcceptedWebAgreement,
|
||||
hasAcceptedAppAgreement: user.hasAcceptedAppAgreement,
|
||||
project: user?.project,
|
||||
};
|
||||
if (payload.googleCode) {
|
||||
const profile = await this.getProfile(payload.googleCode);
|
||||
|
@ -32,6 +32,7 @@ export class JwtStrategy extends PassportStrategy(Strategy, 'jwt') {
|
||||
uuid: payload.uuid,
|
||||
sessionId: payload.sessionId,
|
||||
role: payload?.role,
|
||||
project: payload?.project,
|
||||
};
|
||||
} else {
|
||||
throw new BadRequestException('Unauthorized');
|
||||
|
@ -35,6 +35,7 @@ export class RefreshTokenStrategy extends PassportStrategy(
|
||||
uuid: payload.uuid,
|
||||
sessionId: payload.sessionId,
|
||||
role: payload?.role,
|
||||
project: payload?.project,
|
||||
};
|
||||
} else {
|
||||
throw new BadRequestException('Unauthorized');
|
||||
|
@ -19,5 +19,7 @@ export default registerAs(
|
||||
process.env.MAILTRAP_DELETE_USER_TEMPLATE_UUID,
|
||||
MAILTRAP_EDIT_USER_TEMPLATE_UUID:
|
||||
process.env.MAILTRAP_EDIT_USER_TEMPLATE_UUID,
|
||||
MAILTRAP_SEND_OTP_TEMPLATE_UUID:
|
||||
process.env.MAILTRAP_SEND_OTP_TEMPLATE_UUID,
|
||||
}),
|
||||
);
|
||||
|
4
libs/common/src/constants/batch-device.enum.ts
Normal file
4
libs/common/src/constants/batch-device.enum.ts
Normal file
@ -0,0 +1,4 @@
|
||||
export enum BatchDeviceTypeEnum {
|
||||
RESET = 'RESET',
|
||||
COMMAND = 'COMMAND',
|
||||
}
|
@ -1,4 +1,17 @@
|
||||
export class ControllerRoute {
|
||||
static CLIENT = class {
|
||||
public static readonly ROUTE = 'client';
|
||||
|
||||
static ACTIONS = class {
|
||||
public static readonly REGISTER_NEW_CLIENT_SUMMARY =
|
||||
'Register a new client';
|
||||
public static readonly REGISTER_NEW_CLIENT_DESCRIPTION =
|
||||
'This endpoint registers a new client in the system.';
|
||||
public static readonly LOGIN_CLIENT_SUMMARY = 'Login a client';
|
||||
public static readonly LOGIN_CLIENT_DESCRIPTION =
|
||||
'This endpoint allows a client to log in to the system.';
|
||||
};
|
||||
};
|
||||
static PROJECT = class {
|
||||
public static readonly ROUTE = 'projects';
|
||||
static ACTIONS = class {
|
||||
@ -30,6 +43,11 @@ export class ControllerRoute {
|
||||
'Get user by uuid in project';
|
||||
public static readonly GET_USER_BY_UUID_IN_PROJECT_DESCRIPTION =
|
||||
'This endpoint retrieves a user by their unique identifier (UUID) associated with a specific project.';
|
||||
|
||||
public static readonly EXPORT_STRUCTURE_CSV_SUMMARY =
|
||||
'Export project with their full structure to a CSV file';
|
||||
public static readonly EXPORT_STRUCTURE_CSV_DESCRIPTION =
|
||||
'This endpoint exports project along with their associated communities, spaces, and nested space hierarchy into a downloadable CSV file. Useful for backups, reports, or audits';
|
||||
};
|
||||
};
|
||||
static PROJECT_USER = class {
|
||||
@ -197,7 +215,16 @@ export class ControllerRoute {
|
||||
'retrieves all the spaces associated with a given community, organized into a hierarchical structure.';
|
||||
};
|
||||
};
|
||||
static SPACE_VALIDATION = class {
|
||||
public static readonly ROUTE = '/projects/:projectUuid/spaces';
|
||||
static ACTIONS = class {
|
||||
public static readonly VALIDATE_SPACE_WITH_DEVICES_OR_SUBSPACES_SUMMARY =
|
||||
'Check if a space has devices or sub-spaces';
|
||||
|
||||
public static readonly VALIDATE_SPACE_WITH_DEVICES_OR_SUBSPACES_DESCRIPTION =
|
||||
'Checks if a space has any devices or sub-spaces associated with it.';
|
||||
};
|
||||
};
|
||||
static SPACE_SCENE = class {
|
||||
public static readonly ROUTE =
|
||||
'/projects/:projectUuid/communities/:communityUuid/spaces/:spaceUuid/scenes';
|
||||
@ -292,7 +319,7 @@ export class ControllerRoute {
|
||||
public static readonly CREATE_SPACE_MODEL_DESCRIPTION =
|
||||
'This endpoint allows you to create a new space model within a specified project. A space model defines the structure of spaces, including subspaces, products, and product items, and is uniquely identifiable within the project.';
|
||||
|
||||
public static readonly GET_SPACE_MODEL_SUMMARY = 'Get a New Space Model';
|
||||
public static readonly GET_SPACE_MODEL_SUMMARY = 'Get a Space Model';
|
||||
public static readonly GET_SPACE_MODEL_DESCRIPTION =
|
||||
'Fetch a space model details';
|
||||
|
||||
@ -307,17 +334,38 @@ export class ControllerRoute {
|
||||
public static readonly DELETE_SPACE_MODEL_SUMMARY = 'Delete Space Model';
|
||||
public static readonly DELETE_SPACE_MODEL_DESCRIPTION =
|
||||
'This endpoint allows you to delete a specified Space Model within a project. Deleting a Space Model disables the model and all its associated subspaces and tags, ensuring they are no longer active but remain in the system for auditing.';
|
||||
|
||||
public static readonly LINK_SPACE_MODEL_SUMMARY =
|
||||
'Link a Space Model to spaces';
|
||||
public static readonly LINK_SPACE_MODEL_DESCRIPTION =
|
||||
'This endpoint allows you to link a specified Space Model within a project to multiple spaces. Linking a Space Model applies the model and all its associated subspaces and tags, to the spaces.';
|
||||
};
|
||||
};
|
||||
|
||||
static PRODUCT = class {
|
||||
public static readonly ROUTE = 'products';
|
||||
static ACTIONS = class {
|
||||
public static readonly CREATE_PRODUCT_SUMMARY = 'Create a new product';
|
||||
public static readonly CREATE_PRODUCT_DESCRIPTION =
|
||||
'This endpoint allows you to create a new product in the system.';
|
||||
public static readonly LIST_PRODUCT_SUMMARY = 'Retrieve all products';
|
||||
public static readonly LIST_PRODUCT_DESCRIPTION =
|
||||
'Fetches a list of all products along with their associated device details';
|
||||
};
|
||||
};
|
||||
|
||||
static TAG = class {
|
||||
public static readonly ROUTE = '/projects/:projectUuid/tags';
|
||||
static ACTIONS = class {
|
||||
public static readonly CREATE_TAG_SUMMARY = 'Create a new tag';
|
||||
public static readonly CREATE_TAG_DESCRIPTION =
|
||||
'Creates a new tag and assigns it to a specific project and product.';
|
||||
public static readonly GET_TAGS_BY_PROJECT_SUMMARY =
|
||||
'Get tags by project';
|
||||
public static readonly GET_TAGS_BY_PROJECT_DESCRIPTION =
|
||||
'Retrieves a list of tags associated with a specific project.';
|
||||
};
|
||||
};
|
||||
static USER = class {
|
||||
public static readonly ROUTE = '/user';
|
||||
|
||||
@ -417,7 +465,16 @@ export class ControllerRoute {
|
||||
'This endpoint retrieves the terms and conditions for the application.';
|
||||
};
|
||||
};
|
||||
static WEATHER = class {
|
||||
public static readonly ROUTE = 'weather';
|
||||
|
||||
static ACTIONS = class {
|
||||
public static readonly FETCH_WEATHER_DETAILS_SUMMARY =
|
||||
'Fetch Weather Details';
|
||||
public static readonly FETCH_WEATHER_DETAILS_DESCRIPTION =
|
||||
'This endpoint retrieves the current weather details for a specified location like temperature, humidity, etc.';
|
||||
};
|
||||
};
|
||||
static PRIVACY_POLICY = class {
|
||||
public static readonly ROUTE = 'policy';
|
||||
|
||||
@ -442,18 +499,52 @@ export class ControllerRoute {
|
||||
'This endpoint retrieves all devices in a specified group within a space, based on the group name and space UUID.';
|
||||
};
|
||||
};
|
||||
static DEVICE = class {
|
||||
public static readonly ROUTE = 'device';
|
||||
static PowerClamp = class {
|
||||
public static readonly ROUTE = 'power-clamp';
|
||||
|
||||
static ACTIONS = class {
|
||||
public static readonly ADD_DEVICE_TO_USER_SUMMARY = 'Add device to user';
|
||||
public static readonly ADD_DEVICE_TO_USER_DESCRIPTION =
|
||||
'This endpoint adds a device to a user in the system.';
|
||||
public static readonly GET_ENERGY_SUMMARY =
|
||||
'Get power clamp historical data';
|
||||
public static readonly GET_ENERGY_DESCRIPTION =
|
||||
'This endpoint retrieves the historical data of a power clamp device based on the provided parameters.';
|
||||
public static readonly GET_ENERGY_BY_COMMUNITY_OR_SPACE_SUMMARY =
|
||||
'Get power clamp historical data by community or space';
|
||||
public static readonly GET_ENERGY_BY_COMMUNITY_OR_SPACE_DESCRIPTION =
|
||||
'This endpoint retrieves the historical data of power clamp devices based on the provided community or space UUID.';
|
||||
};
|
||||
};
|
||||
|
||||
public static readonly GET_DEVICES_BY_USER_SUMMARY =
|
||||
'Get devices by user UUID';
|
||||
public static readonly GET_DEVICES_BY_USER_DESCRIPTION =
|
||||
'This endpoint retrieves all devices associated with a specific user.';
|
||||
static Occupancy = class {
|
||||
public static readonly ROUTE = 'occupancy';
|
||||
|
||||
static ACTIONS = class {
|
||||
public static readonly GET_OCCUPANCY_HEAT_MAP_SUMMARY =
|
||||
'Get occupancy heat map data';
|
||||
public static readonly GET_OCCUPANCY_HEAT_MAP_DESCRIPTION =
|
||||
'This endpoint retrieves the occupancy heat map data based on the provided parameters.';
|
||||
};
|
||||
};
|
||||
static AQI = class {
|
||||
public static readonly ROUTE = 'aqi';
|
||||
|
||||
static ACTIONS = class {
|
||||
public static readonly GET_AQI_RANGE_DATA_SUMMARY = 'Get AQI range data';
|
||||
public static readonly GET_AQI_RANGE_DATA_DESCRIPTION =
|
||||
'This endpoint retrieves the AQI (Air Quality Index) range data based on the provided parameters.';
|
||||
|
||||
public static readonly GET_AQI_DISTRIBUTION_DATA_SUMMARY =
|
||||
'Get AQI distribution data';
|
||||
public static readonly GET_AQI_DISTRIBUTION_DATA_DESCRIPTION =
|
||||
'This endpoint retrieves the AQI (Air Quality Index) distribution data based on the provided parameters.';
|
||||
};
|
||||
};
|
||||
static DEVICE = class {
|
||||
public static readonly ROUTE = 'devices';
|
||||
|
||||
static ACTIONS = class {
|
||||
public static readonly ADD_DEVICE_SUMMARY = 'Add new device';
|
||||
public static readonly ADD_DEVICE_DESCRIPTION =
|
||||
'This endpoint adds a new device in the system.';
|
||||
|
||||
public static readonly GET_DEVICES_BY_SPACE_UUID_SUMMARY =
|
||||
'Get devices by space UUID';
|
||||
@ -525,20 +616,48 @@ export class ControllerRoute {
|
||||
'This endpoint retrieves the status of a specific power clamp device.';
|
||||
|
||||
public static readonly ADD_SCENE_TO_DEVICE_SUMMARY =
|
||||
'Add scene to device (4 Scene and 6 Scene devices only)';
|
||||
'Add scene to device';
|
||||
public static readonly ADD_SCENE_TO_DEVICE_DESCRIPTION =
|
||||
'This endpoint adds a scene to a specific switch device.';
|
||||
|
||||
public static readonly GET_SCENES_BY_DEVICE_SUMMARY =
|
||||
'Get scenes by device (4 Scene and 6 Scene devices only)';
|
||||
'Get scenes by device';
|
||||
public static readonly GET_SCENES_BY_DEVICE_DESCRIPTION =
|
||||
'This endpoint retrieves all scenes associated with a specific switch device.';
|
||||
public static readonly DELETE_SCENES_BY_SWITCH_NAME_SUMMARY =
|
||||
'Delete scenes by device uuid and switch name (4 Scene and 6 Scene devices only)';
|
||||
'Delete scenes by device uuid and switch name';
|
||||
public static readonly DELETE_SCENES_BY_SWITCH_NAME_DESCRIPTION =
|
||||
'This endpoint deletes all scenes associated with a specific switch device.';
|
||||
};
|
||||
};
|
||||
static DEVICE_COMMISSION = class {
|
||||
public static readonly ROUTE = '/projects/:projectUuid/devices/commission';
|
||||
|
||||
static ACTIONS = class {
|
||||
public static readonly ADD_ALL_DEVICES_SUMMARY = 'Add all devices';
|
||||
public static readonly ADD_ALL_DEVICES_DESCRIPTION =
|
||||
'This endpoint add all devices in the system from tuya.';
|
||||
};
|
||||
};
|
||||
static DEVICE_PROJECT = class {
|
||||
public static readonly ROUTE = '/projects/:projectUuid/devices';
|
||||
static ACTIONS = class {
|
||||
public static readonly GET_ALL_DEVICES_SUMMARY = 'Get all devices';
|
||||
public static readonly GET_ALL_DEVICES_DESCRIPTION =
|
||||
'This endpoint retrieves all devices in the system.';
|
||||
};
|
||||
};
|
||||
static DEVICE_SPACE_COMMUNITY = class {
|
||||
public static readonly ROUTE = 'devices-space-community';
|
||||
|
||||
static ACTIONS = class {
|
||||
public static readonly GET_ALL_DEVICES_BY_SPACE_OR_COMMUNITY_WITH_RECURSIVE_CHILD_SUMMARY =
|
||||
'Get all devices by space or community with recursive child';
|
||||
|
||||
public static readonly GET_ALL_DEVICES_BY_SPACE_OR_COMMUNITY_WITH_RECURSIVE_CHILD_DESCRIPTION =
|
||||
'This endpoint retrieves all devices in the system by space or community with recursive child.';
|
||||
};
|
||||
};
|
||||
|
||||
static DEVICE_PERMISSION = class {
|
||||
public static readonly ROUTE = 'device-permission';
|
||||
@ -588,18 +707,13 @@ export class ControllerRoute {
|
||||
};
|
||||
|
||||
static AUTOMATION = class {
|
||||
public static readonly ROUTE = 'automation';
|
||||
public static readonly ROUTE = '/projects/:projectUuid/automations';
|
||||
|
||||
static ACTIONS = class {
|
||||
public static readonly ADD_AUTOMATION_SUMMARY = 'Add automation';
|
||||
public static readonly ADD_AUTOMATION_DESCRIPTION =
|
||||
'This endpoint creates a new automation based on the provided details.';
|
||||
|
||||
public static readonly GET_AUTOMATION_BY_SPACE_SUMMARY =
|
||||
'Get automation by space';
|
||||
public static readonly GET_AUTOMATION_BY_SPACE_DESCRIPTION =
|
||||
'This endpoint retrieves the automations associated with a particular space.';
|
||||
|
||||
public static readonly GET_AUTOMATION_DETAILS_SUMMARY =
|
||||
'Get automation details';
|
||||
public static readonly GET_AUTOMATION_DETAILS_DESCRIPTION =
|
||||
@ -620,6 +734,17 @@ export class ControllerRoute {
|
||||
};
|
||||
};
|
||||
|
||||
static AUTOMATION_SPACE = class {
|
||||
public static readonly ROUTE =
|
||||
'/projects/:projectUuid/communities/:communityUuid/spaces/:spaceUuid/automations';
|
||||
static ACTIONS = class {
|
||||
public static readonly GET_AUTOMATION_BY_SPACE_SUMMARY =
|
||||
'Get automation by space';
|
||||
public static readonly GET_AUTOMATION_BY_SPACE_DESCRIPTION =
|
||||
'This endpoint retrieves the automations associated with a particular space.';
|
||||
};
|
||||
};
|
||||
|
||||
static DOOR_LOCK = class {
|
||||
public static readonly ROUTE = 'door-lock';
|
||||
|
||||
@ -679,29 +804,15 @@ export class ControllerRoute {
|
||||
};
|
||||
};
|
||||
static VISITOR_PASSWORD = class {
|
||||
public static readonly ROUTE = 'visitor-password';
|
||||
public static readonly ROUTE = 'visitor-passwords';
|
||||
public static readonly PROJECT_ROUTE =
|
||||
'/projects/:projectUuid/visitor-password';
|
||||
|
||||
static ACTIONS = class {
|
||||
public static readonly ADD_ONLINE_TEMP_PASSWORD_MULTIPLE_TIME_SUMMARY =
|
||||
'Add online temporary passwords (multiple-time)';
|
||||
public static readonly ADD_ONLINE_TEMP_PASSWORD_MULTIPLE_TIME_DESCRIPTION =
|
||||
'This endpoint adds multiple online temporary passwords for door locks.';
|
||||
|
||||
public static readonly ADD_ONLINE_TEMP_PASSWORD_ONE_TIME_SUMMARY =
|
||||
'Add online temporary password (one-time)';
|
||||
public static readonly ADD_ONLINE_TEMP_PASSWORD_ONE_TIME_DESCRIPTION =
|
||||
'This endpoint adds a one-time online temporary password for a door lock.';
|
||||
|
||||
public static readonly ADD_OFFLINE_TEMP_PASSWORD_ONE_TIME_SUMMARY =
|
||||
'Add offline temporary password (one-time)';
|
||||
public static readonly ADD_OFFLINE_TEMP_PASSWORD_ONE_TIME_DESCRIPTION =
|
||||
'This endpoint adds a one-time offline temporary password for a door lock.';
|
||||
|
||||
public static readonly ADD_OFFLINE_TEMP_PASSWORD_MULTIPLE_TIME_SUMMARY =
|
||||
'Add offline temporary passwords (multiple-time)';
|
||||
public static readonly ADD_OFFLINE_TEMP_PASSWORD_MULTIPLE_TIME_DESCRIPTION =
|
||||
'This endpoint adds multiple offline temporary passwords for door locks.';
|
||||
|
||||
public static readonly ADD_VISITOR_PASSWORD_SUMMARY =
|
||||
'Add visitor password';
|
||||
public static readonly ADD_VISITOR_PASSWORD_DESCRIPTION =
|
||||
'This endpoint allows you to add a visitor password based on the operation type.';
|
||||
public static readonly GET_VISITOR_PASSWORD_SUMMARY =
|
||||
'Get visitor passwords';
|
||||
public static readonly GET_VISITOR_PASSWORD_DESCRIPTION =
|
||||
|
3
libs/common/src/constants/device-type.enum.ts
Normal file
3
libs/common/src/constants/device-type.enum.ts
Normal file
@ -0,0 +1,3 @@
|
||||
export enum DeviceTypeEnum {
|
||||
DOOR_LOCK = 'DOOR_LOCK',
|
||||
}
|
8
libs/common/src/constants/pollutants.enum.ts
Normal file
8
libs/common/src/constants/pollutants.enum.ts
Normal file
@ -0,0 +1,8 @@
|
||||
export enum PollutantType {
|
||||
AQI = 'aqi',
|
||||
PM25 = 'pm25',
|
||||
PM10 = 'pm10',
|
||||
VOC = 'voc',
|
||||
CO2 = 'co2',
|
||||
CH2O = 'ch2o',
|
||||
}
|
6
libs/common/src/constants/power.clamp.enargy.enum.ts
Normal file
6
libs/common/src/constants/power.clamp.enargy.enum.ts
Normal file
@ -0,0 +1,6 @@
|
||||
export enum PowerClampEnergyEnum {
|
||||
ENERGY_CONSUMED = 'EnergyConsumed',
|
||||
ENERGY_CONSUMED_A = 'EnergyConsumedA',
|
||||
ENERGY_CONSUMED_B = 'EnergyConsumedB',
|
||||
ENERGY_CONSUMED_C = 'EnergyConsumedC',
|
||||
}
|
4
libs/common/src/constants/presence.sensor.enum.ts
Normal file
4
libs/common/src/constants/presence.sensor.enum.ts
Normal file
@ -0,0 +1,4 @@
|
||||
export enum PresenceSensorEnum {
|
||||
PRESENCE_STATE = 'presence_state',
|
||||
SENSITIVITY = 'sensitivity',
|
||||
}
|
@ -15,8 +15,10 @@ export enum ProductType {
|
||||
WL = 'WL',
|
||||
GD = 'GD',
|
||||
CUR = 'CUR',
|
||||
CUR_2 = 'CUR_2',
|
||||
PC = 'PC',
|
||||
FOUR_S = '4S',
|
||||
SIX_S = '6S',
|
||||
SOS = 'SOS',
|
||||
AQI = 'AQI',
|
||||
}
|
||||
|
@ -3,12 +3,14 @@ import { RoleType } from './role.type.enum';
|
||||
export const RolePermissions = {
|
||||
[RoleType.SUPER_ADMIN]: [
|
||||
'DEVICE_SINGLE_CONTROL',
|
||||
'COMMISSION_DEVICE',
|
||||
'DEVICE_VIEW',
|
||||
'DEVICE_DELETE',
|
||||
'DEVICE_UPDATE',
|
||||
'DEVICE_BATCH_CONTROL',
|
||||
'DEVICE_LOCATION_VIEW',
|
||||
'DEVICE_LOCATION_UPDATE',
|
||||
'DEVICE_ADD',
|
||||
'COMMUNITY_VIEW',
|
||||
'COMMUNITY_ADD',
|
||||
'COMMUNITY_UPDATE',
|
||||
@ -23,6 +25,7 @@ export const RolePermissions = {
|
||||
'SPACE_MODEL_VIEW',
|
||||
'SPACE_MODEL_UPDATE',
|
||||
'SPACE_MODEL_DELETE',
|
||||
'SPACE_MODEL_LINK',
|
||||
'SPACE_ASSIGN_USER_TO_SPACE',
|
||||
'SPACE_DELETE_USER_FROM_SPACE',
|
||||
'SUBSPACE_VIEW',
|
||||
@ -52,12 +55,16 @@ export const RolePermissions = {
|
||||
'VISITOR_PASSWORD_DELETE',
|
||||
'USER_ADD',
|
||||
'SPACE_MEMBER_ADD',
|
||||
'COMMISSION_DEVICE',
|
||||
'PRODUCT_ADD',
|
||||
],
|
||||
[RoleType.ADMIN]: [
|
||||
'COMMISSION_DEVICE',
|
||||
'DEVICE_SINGLE_CONTROL',
|
||||
'DEVICE_VIEW',
|
||||
'DEVICE_DELETE',
|
||||
'DEVICE_UPDATE',
|
||||
'DEVICE_ADD',
|
||||
'DEVICE_BATCH_CONTROL',
|
||||
'DEVICE_LOCATION_VIEW',
|
||||
'DEVICE_LOCATION_UPDATE',
|
||||
@ -75,6 +82,7 @@ export const RolePermissions = {
|
||||
'SPACE_MODEL_VIEW',
|
||||
'SPACE_MODEL_UPDATE',
|
||||
'SPACE_MODEL_DELETE',
|
||||
'SPACE_MODEL_LINK',
|
||||
'SPACE_ASSIGN_USER_TO_SPACE',
|
||||
'SPACE_DELETE_USER_FROM_SPACE',
|
||||
'SUBSPACE_VIEW',
|
||||
@ -104,6 +112,8 @@ export const RolePermissions = {
|
||||
'VISITOR_PASSWORD_DELETE',
|
||||
'USER_ADD',
|
||||
'SPACE_MEMBER_ADD',
|
||||
'COMMISSION_DEVICE',
|
||||
'PRODUCT_ADD',
|
||||
],
|
||||
[RoleType.SPACE_MEMBER]: [
|
||||
'DEVICE_SINGLE_CONTROL',
|
||||
@ -119,6 +129,7 @@ export const RolePermissions = {
|
||||
'SCENES_CONTROL',
|
||||
],
|
||||
[RoleType.SPACE_OWNER]: [
|
||||
'COMMISSION_DEVICE',
|
||||
'DEVICE_SINGLE_CONTROL',
|
||||
'DEVICE_VIEW',
|
||||
'DEVICE_DELETE',
|
||||
@ -161,5 +172,6 @@ export const RolePermissions = {
|
||||
'VISITOR_PASSWORD_DELETE',
|
||||
'USER_ADD',
|
||||
'SPACE_MEMBER_ADD',
|
||||
'COMMISSION_DEVICE',
|
||||
],
|
||||
};
|
||||
|
2
libs/common/src/constants/sql-query-path.ts
Normal file
2
libs/common/src/constants/sql-query-path.ts
Normal file
@ -0,0 +1,2 @@
|
||||
export const SQL_QUERIES_PATH = 'libs/common/src/sql/queries';
|
||||
export const SQL_PROCEDURES_PATH = 'libs/common/src/sql/procedures';
|
6
libs/common/src/constants/visitor-password.enum.ts
Normal file
6
libs/common/src/constants/visitor-password.enum.ts
Normal file
@ -0,0 +1,6 @@
|
||||
export enum VisitorPasswordEnum {
|
||||
ONLINE_ONE_TIME = 'ONLINE_ONE_TIME',
|
||||
ONLINE_MULTIPLE_TIME = 'ONLINE_MULTIPLE_TIME',
|
||||
OFFLINE_ONE_TIME = 'OFFLINE_ONE_TIME',
|
||||
OFFLINE_MULTIPLE_TIME = 'OFFLINE_MULTIPLE_TIME',
|
||||
}
|
8
libs/common/src/context/request-context.ts
Normal file
8
libs/common/src/context/request-context.ts
Normal file
@ -0,0 +1,8 @@
|
||||
import { AsyncLocalStorage } from 'async_hooks';
|
||||
|
||||
export interface RequestContextStore {
|
||||
requestId?: string;
|
||||
userId?: string;
|
||||
}
|
||||
|
||||
export const requestContext = new AsyncLocalStorage<RequestContextStore>();
|
@ -1,113 +1,141 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { ConfigModule, ConfigService } from '@nestjs/config';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { SnakeNamingStrategy } from './strategies';
|
||||
import { UserEntity } from '../modules/user/entities/user.entity';
|
||||
import { UserSessionEntity } from '../modules/session/entities/session.entity';
|
||||
import { UserOtpEntity } from '../modules/user/entities';
|
||||
import { ProductEntity } from '../modules/product/entities';
|
||||
import { DeviceEntity } from '../modules/device/entities';
|
||||
import { PermissionTypeEntity } from '../modules/permission/entities';
|
||||
import { ProductEntity } from '../modules/product/entities';
|
||||
import { UserSessionEntity } from '../modules/session/entities/session.entity';
|
||||
import { UserOtpEntity } from '../modules/user/entities';
|
||||
import { UserEntity } from '../modules/user/entities/user.entity';
|
||||
import { SnakeNamingStrategy } from './strategies';
|
||||
|
||||
import { UserSpaceEntity } from '../modules/user/entities';
|
||||
import { DeviceUserPermissionEntity } from '../modules/device/entities';
|
||||
import { RoleTypeEntity } from '../modules/role-type/entities';
|
||||
import { UserNotificationEntity } from '../modules/user/entities';
|
||||
import { DeviceNotificationEntity } from '../modules/device/entities';
|
||||
import { RegionEntity } from '../modules/region/entities';
|
||||
import { TimeZoneEntity } from '../modules/timezone/entities';
|
||||
import { VisitorPasswordEntity } from '../modules/visitor-password/entities';
|
||||
import { TypeOrmWinstonLogger } from '@app/common/logger/services/typeorm.logger';
|
||||
import { createLogger } from 'winston';
|
||||
import { winstonLoggerOptions } from '../logger/services/winston.logger';
|
||||
import { AqiSpaceDailyPollutantStatsEntity } from '../modules/aqi/entities';
|
||||
import { AutomationEntity } from '../modules/automation/entities';
|
||||
import { ClientEntity } from '../modules/client/entities';
|
||||
import { CommunityEntity } from '../modules/community/entities';
|
||||
import { DeviceStatusLogEntity } from '../modules/device-status-log/entities';
|
||||
import { SceneEntity, SceneIconEntity } from '../modules/scene/entities';
|
||||
import { SceneDeviceEntity } from '../modules/scene-device/entities';
|
||||
import { ProjectEntity } from '../modules/project/entities';
|
||||
import {
|
||||
SpaceModelEntity,
|
||||
SubspaceModelEntity,
|
||||
TagModel,
|
||||
SpaceModelProductAllocationEntity,
|
||||
SubspaceModelProductAllocationEntity,
|
||||
} from '../modules/space-model/entities';
|
||||
DeviceNotificationEntity,
|
||||
DeviceUserPermissionEntity,
|
||||
} from '../modules/device/entities';
|
||||
import {
|
||||
InviteUserEntity,
|
||||
InviteUserSpaceEntity,
|
||||
} from '../modules/Invite-user/entities';
|
||||
import { SpaceDailyOccupancyDurationEntity } from '../modules/occupancy/entities';
|
||||
import {
|
||||
PowerClampDailyEntity,
|
||||
PowerClampHourlyEntity,
|
||||
PowerClampMonthlyEntity,
|
||||
} from '../modules/power-clamp/entities/power-clamp.entity';
|
||||
import {
|
||||
PresenceSensorDailyDeviceEntity,
|
||||
PresenceSensorDailySpaceEntity,
|
||||
} from '../modules/presence-sensor/entities';
|
||||
import { ProjectEntity } from '../modules/project/entities';
|
||||
import { RegionEntity } from '../modules/region/entities';
|
||||
import { RoleTypeEntity } from '../modules/role-type/entities';
|
||||
import { SceneDeviceEntity } from '../modules/scene-device/entities';
|
||||
import { SceneEntity, SceneIconEntity } from '../modules/scene/entities';
|
||||
import {
|
||||
SpaceModelEntity,
|
||||
SpaceModelProductAllocationEntity,
|
||||
SubspaceModelEntity,
|
||||
SubspaceModelProductAllocationEntity,
|
||||
} from '../modules/space-model/entities';
|
||||
import { InviteSpaceEntity } from '../modules/space/entities/invite-space.entity';
|
||||
import { AutomationEntity } from '../modules/automation/entities';
|
||||
import { SpaceProductAllocationEntity } from '../modules/space/entities/space-product-allocation.entity';
|
||||
import { NewTagEntity } from '../modules/tag/entities/tag.entity';
|
||||
import { SpaceEntity } from '../modules/space/entities/space.entity';
|
||||
import { SpaceLinkEntity } from '../modules/space/entities/space-link.entity';
|
||||
import { SubspaceProductAllocationEntity } from '../modules/space/entities/subspace/subspace-product-allocation.entity';
|
||||
import { SubspaceEntity } from '../modules/space/entities/subspace/subspace.entity';
|
||||
import { TagEntity } from '../modules/space/entities/tag.entity';
|
||||
import { NewTagEntity } from '../modules/tag/entities/tag.entity';
|
||||
import { TimeZoneEntity } from '../modules/timezone/entities';
|
||||
import {
|
||||
UserNotificationEntity,
|
||||
UserSpaceEntity,
|
||||
} from '../modules/user/entities';
|
||||
import { VisitorPasswordEntity } from '../modules/visitor-password/entities';
|
||||
@Module({
|
||||
imports: [
|
||||
TypeOrmModule.forRootAsync({
|
||||
imports: [ConfigModule],
|
||||
inject: [ConfigService],
|
||||
useFactory: (configService: ConfigService) => ({
|
||||
name: 'default',
|
||||
type: 'postgres',
|
||||
host: configService.get('DB_HOST'),
|
||||
port: configService.get('DB_PORT'),
|
||||
username: configService.get('DB_USER'),
|
||||
password: configService.get('DB_PASSWORD'),
|
||||
database: configService.get('DB_NAME'),
|
||||
entities: [
|
||||
NewTagEntity,
|
||||
ProjectEntity,
|
||||
UserEntity,
|
||||
UserSessionEntity,
|
||||
UserOtpEntity,
|
||||
ProductEntity,
|
||||
DeviceUserPermissionEntity,
|
||||
DeviceEntity,
|
||||
PermissionTypeEntity,
|
||||
CommunityEntity,
|
||||
SpaceEntity,
|
||||
SpaceLinkEntity,
|
||||
SubspaceEntity,
|
||||
TagEntity,
|
||||
UserSpaceEntity,
|
||||
DeviceUserPermissionEntity,
|
||||
RoleTypeEntity,
|
||||
UserNotificationEntity,
|
||||
DeviceNotificationEntity,
|
||||
RegionEntity,
|
||||
TimeZoneEntity,
|
||||
VisitorPasswordEntity,
|
||||
DeviceStatusLogEntity,
|
||||
SceneEntity,
|
||||
SceneIconEntity,
|
||||
SceneDeviceEntity,
|
||||
SpaceModelEntity,
|
||||
SubspaceModelEntity,
|
||||
TagModel,
|
||||
InviteUserEntity,
|
||||
InviteUserSpaceEntity,
|
||||
InviteSpaceEntity,
|
||||
AutomationEntity,
|
||||
SpaceModelProductAllocationEntity,
|
||||
SubspaceModelProductAllocationEntity,
|
||||
SpaceProductAllocationEntity,
|
||||
SubspaceProductAllocationEntity,
|
||||
],
|
||||
namingStrategy: new SnakeNamingStrategy(),
|
||||
synchronize: Boolean(JSON.parse(configService.get('DB_SYNC'))),
|
||||
logging: false,
|
||||
extra: {
|
||||
charset: 'utf8mb4',
|
||||
max: 20, // set pool max size
|
||||
idleTimeoutMillis: 5000, // close idle clients after 5 second
|
||||
connectionTimeoutMillis: 11_000, // return an error after 11 second if connection could not be established
|
||||
maxUses: 7500, // close (and replace) a connection after it has been used 7500 times (see below for discussion)
|
||||
},
|
||||
continuationLocalStorage: true,
|
||||
ssl: Boolean(JSON.parse(configService.get('DB_SSL'))),
|
||||
}),
|
||||
useFactory: (configService: ConfigService) => {
|
||||
const winstonLogger = createLogger(winstonLoggerOptions);
|
||||
const typeOrmLogger = new TypeOrmWinstonLogger(winstonLogger);
|
||||
return {
|
||||
name: 'default',
|
||||
type: 'postgres',
|
||||
host: configService.get('DB_HOST'),
|
||||
port: configService.get('DB_PORT'),
|
||||
username: configService.get('DB_USER'),
|
||||
password: configService.get('DB_PASSWORD'),
|
||||
database: configService.get('DB_NAME'),
|
||||
entities: [
|
||||
NewTagEntity,
|
||||
ProjectEntity,
|
||||
UserEntity,
|
||||
UserSessionEntity,
|
||||
UserOtpEntity,
|
||||
ProductEntity,
|
||||
DeviceUserPermissionEntity,
|
||||
DeviceEntity,
|
||||
PermissionTypeEntity,
|
||||
CommunityEntity,
|
||||
SpaceEntity,
|
||||
SubspaceEntity,
|
||||
UserSpaceEntity,
|
||||
DeviceUserPermissionEntity,
|
||||
RoleTypeEntity,
|
||||
UserNotificationEntity,
|
||||
DeviceNotificationEntity,
|
||||
RegionEntity,
|
||||
TimeZoneEntity,
|
||||
VisitorPasswordEntity,
|
||||
DeviceStatusLogEntity,
|
||||
SceneEntity,
|
||||
SceneIconEntity,
|
||||
SceneDeviceEntity,
|
||||
SpaceModelEntity,
|
||||
SubspaceModelEntity,
|
||||
InviteUserEntity,
|
||||
InviteUserSpaceEntity,
|
||||
InviteSpaceEntity,
|
||||
AutomationEntity,
|
||||
SpaceModelProductAllocationEntity,
|
||||
SubspaceModelProductAllocationEntity,
|
||||
SpaceProductAllocationEntity,
|
||||
SubspaceProductAllocationEntity,
|
||||
ClientEntity,
|
||||
PowerClampHourlyEntity,
|
||||
PowerClampDailyEntity,
|
||||
PowerClampMonthlyEntity,
|
||||
PresenceSensorDailyDeviceEntity,
|
||||
PresenceSensorDailySpaceEntity,
|
||||
AqiSpaceDailyPollutantStatsEntity,
|
||||
SpaceDailyOccupancyDurationEntity,
|
||||
],
|
||||
namingStrategy: new SnakeNamingStrategy(),
|
||||
synchronize: Boolean(JSON.parse(configService.get('DB_SYNC'))),
|
||||
logging: ['query', 'error', 'warn', 'schema', 'migration'],
|
||||
|
||||
logger: typeOrmLogger,
|
||||
extra: {
|
||||
charset: 'utf8mb4',
|
||||
max: 100, // set pool max size
|
||||
idleTimeoutMillis: 3000, // close idle clients after 5 second
|
||||
connectionTimeoutMillis: 12_000, // return an error after 11 second if connection could not be established
|
||||
maxUses: 7500, // close (and replace) a connection after it has been used 7500 times (see below for discussion)
|
||||
},
|
||||
continuationLocalStorage: true,
|
||||
ssl: Boolean(JSON.parse(configService.get('DB_SSL'))),
|
||||
};
|
||||
},
|
||||
}),
|
||||
],
|
||||
providers: [TypeOrmWinstonLogger],
|
||||
})
|
||||
export class DatabaseModule {}
|
||||
|
12
libs/common/src/dto/community-space.param.ts
Normal file
12
libs/common/src/dto/community-space.param.ts
Normal file
@ -0,0 +1,12 @@
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
import { ProjectParam } from './project-param.dto';
|
||||
import { IsUUID } from 'class-validator';
|
||||
|
||||
export class CommunityParam extends ProjectParam {
|
||||
@ApiProperty({
|
||||
description: 'UUID of the community this space belongs to',
|
||||
example: 'd290f1ee-6c54-4b01-90e6-d701748f0851',
|
||||
})
|
||||
@IsUUID()
|
||||
communityUuid: string;
|
||||
}
|
12
libs/common/src/dto/get.space.param.ts
Normal file
12
libs/common/src/dto/get.space.param.ts
Normal file
@ -0,0 +1,12 @@
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
import { IsUUID } from 'class-validator';
|
||||
import { CommunityParam } from './community-space.param';
|
||||
|
||||
export class GetSpaceParam extends CommunityParam {
|
||||
@ApiProperty({
|
||||
description: 'UUID of the Space',
|
||||
example: 'd290f1ee-6c54-4b01-90e6-d701748f0851',
|
||||
})
|
||||
@IsUUID()
|
||||
spaceUuid: string;
|
||||
}
|
13
libs/common/src/dto/pagination-with-search.request.dto.ts
Normal file
13
libs/common/src/dto/pagination-with-search.request.dto.ts
Normal file
@ -0,0 +1,13 @@
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
import { IsOptional } from 'class-validator';
|
||||
import { PaginationRequestGetListDto } from './pagination.request.dto';
|
||||
|
||||
export class PaginationRequestWithSearchGetListDto extends PaginationRequestGetListDto {
|
||||
@IsOptional()
|
||||
@ApiProperty({
|
||||
name: 'search',
|
||||
required: false,
|
||||
description: 'Search for community or space name',
|
||||
})
|
||||
search?: string;
|
||||
}
|
@ -1,11 +1,24 @@
|
||||
import { IsDate, IsOptional } from 'class-validator';
|
||||
import { IsPageRequestParam } from '../validators/is-page-request-param.validator';
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
import { IsSizeRequestParam } from '../validators/is-size-request-param.validator';
|
||||
import { Transform } from 'class-transformer';
|
||||
import { parseToDate } from '../util/parseToDate';
|
||||
import { IsBoolean, IsOptional } from 'class-validator';
|
||||
import { BooleanValues } from '../constants/boolean-values.enum';
|
||||
import { IsPageRequestParam } from '../validators/is-page-request-param.validator';
|
||||
import { IsSizeRequestParam } from '../validators/is-size-request-param.validator';
|
||||
|
||||
export class PaginationRequestGetListDto {
|
||||
@ApiProperty({
|
||||
example: true,
|
||||
description: 'include spaces',
|
||||
required: false,
|
||||
default: false,
|
||||
})
|
||||
@IsOptional()
|
||||
@IsBoolean()
|
||||
@Transform((value) => {
|
||||
return value.obj.includeSpaces === BooleanValues.TRUE;
|
||||
})
|
||||
public includeSpaces?: boolean = false;
|
||||
|
||||
@IsOptional()
|
||||
@IsPageRequestParam({
|
||||
message: 'Page must be bigger than 0',
|
||||
@ -27,40 +40,4 @@ export class PaginationRequestGetListDto {
|
||||
description: 'Size request',
|
||||
})
|
||||
size?: number;
|
||||
|
||||
@IsOptional()
|
||||
@ApiProperty({
|
||||
name: 'name',
|
||||
required: false,
|
||||
description: 'Name to be filtered',
|
||||
})
|
||||
name?: string;
|
||||
|
||||
@ApiProperty({
|
||||
name: 'from',
|
||||
required: false,
|
||||
type: Number,
|
||||
description: `Start time in UNIX timestamp format to filter`,
|
||||
example: 1674172800000,
|
||||
})
|
||||
@IsOptional()
|
||||
@Transform(({ value }) => parseToDate(value))
|
||||
@IsDate({
|
||||
message: `From must be in UNIX timestamp format in order to parse to Date instance`,
|
||||
})
|
||||
from?: Date;
|
||||
|
||||
@ApiProperty({
|
||||
name: 'to',
|
||||
required: false,
|
||||
type: Number,
|
||||
description: `End time in UNIX timestamp format to filter`,
|
||||
example: 1674259200000,
|
||||
})
|
||||
@IsOptional()
|
||||
@Transform(({ value }) => parseToDate(value))
|
||||
@IsDate({
|
||||
message: `To must be in UNIX timestamp format in order to parse to Date instance`,
|
||||
})
|
||||
to?: Date;
|
||||
}
|
||||
|
11
libs/common/src/dto/project-param.dto.ts
Normal file
11
libs/common/src/dto/project-param.dto.ts
Normal file
@ -0,0 +1,11 @@
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
import { IsUUID } from 'class-validator';
|
||||
|
||||
export class ProjectParam {
|
||||
@ApiProperty({
|
||||
description: 'UUID of the Project',
|
||||
example: 'd290f1ee-6c54-4b01-90e6-d701748f0851',
|
||||
})
|
||||
@IsUUID()
|
||||
projectUuid: string;
|
||||
}
|
@ -10,7 +10,13 @@ import { GetDeviceDetailsFunctionsStatusInterface } from 'src/device/interfaces/
|
||||
import { TuyaContext } from '@tuya/tuya-connector-nodejs';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { firebaseDataBase } from '../../firebase.config';
|
||||
import { Database, DataSnapshot, get, ref, set } from 'firebase/database';
|
||||
import {
|
||||
Database,
|
||||
DataSnapshot,
|
||||
get,
|
||||
ref,
|
||||
runTransaction,
|
||||
} from 'firebase/database';
|
||||
import { DeviceStatusLogRepository } from '@app/common/modules/device-status-log/repositories';
|
||||
@Injectable()
|
||||
export class DeviceStatusFirebaseService {
|
||||
@ -61,24 +67,94 @@ export class DeviceStatusFirebaseService {
|
||||
);
|
||||
}
|
||||
}
|
||||
async addBatchDeviceStatusToOurDb(
|
||||
batch: {
|
||||
deviceTuyaUuid: string;
|
||||
status: any;
|
||||
log: any;
|
||||
device: any;
|
||||
}[],
|
||||
): Promise<void> {
|
||||
const allLogs = [];
|
||||
|
||||
console.log(`🔁 Preparing logs from batch of ${batch.length} items...`);
|
||||
|
||||
for (const item of batch) {
|
||||
const device = item.device;
|
||||
if (!device?.uuid) {
|
||||
console.log(`⛔ Skipped unknown device: ${item.deviceTuyaUuid}`);
|
||||
continue;
|
||||
}
|
||||
|
||||
const logs = item.log.properties.map((property) =>
|
||||
this.deviceStatusLogRepository.create({
|
||||
deviceId: device.uuid,
|
||||
deviceTuyaId: item.deviceTuyaUuid,
|
||||
productId: item.log.productId,
|
||||
log: item.log,
|
||||
code: property.code,
|
||||
value: property.value,
|
||||
eventId: item.log.dataId,
|
||||
eventTime: new Date(property.time).toISOString(),
|
||||
}),
|
||||
);
|
||||
allLogs.push(...logs);
|
||||
}
|
||||
|
||||
console.log(`📝 Total logs to insert: ${allLogs.length}`);
|
||||
|
||||
const insertLogsPromise = (async () => {
|
||||
const chunkSize = 300;
|
||||
let insertedCount = 0;
|
||||
|
||||
for (let i = 0; i < allLogs.length; i += chunkSize) {
|
||||
const chunk = allLogs.slice(i, i + chunkSize);
|
||||
try {
|
||||
const result = await this.deviceStatusLogRepository
|
||||
.createQueryBuilder()
|
||||
.insert()
|
||||
.into('device-status-log') // or use DeviceStatusLogEntity
|
||||
.values(chunk)
|
||||
.orIgnore() // skip duplicates
|
||||
.execute();
|
||||
|
||||
insertedCount += result.identifiers.length;
|
||||
console.log(
|
||||
`✅ Inserted ${result.identifiers.length} / ${chunk.length} logs (chunk)`,
|
||||
);
|
||||
} catch (error) {
|
||||
console.error('❌ Insert error (skipped chunk):', error.message);
|
||||
}
|
||||
}
|
||||
|
||||
console.log(
|
||||
`✅ Total logs inserted: ${insertedCount} / ${allLogs.length}`,
|
||||
);
|
||||
})();
|
||||
|
||||
await insertLogsPromise;
|
||||
}
|
||||
|
||||
async addDeviceStatusToFirebase(
|
||||
addDeviceStatusDto: AddDeviceStatusDto,
|
||||
addDeviceStatusDto: AddDeviceStatusDto & { device?: any },
|
||||
): Promise<AddDeviceStatusDto | null> {
|
||||
try {
|
||||
const device = await this.getDeviceByDeviceTuyaUuid(
|
||||
addDeviceStatusDto.deviceTuyaUuid,
|
||||
);
|
||||
|
||||
let device = addDeviceStatusDto.device;
|
||||
if (!device) {
|
||||
device = await this.getDeviceByDeviceTuyaUuid(
|
||||
addDeviceStatusDto.deviceTuyaUuid,
|
||||
);
|
||||
}
|
||||
if (device?.uuid) {
|
||||
return await this.createDeviceStatusFirebase({
|
||||
deviceUuid: device.uuid,
|
||||
...addDeviceStatusDto,
|
||||
productType: device.productDevice?.prodType,
|
||||
});
|
||||
}
|
||||
// Return null if device not found or no UUID
|
||||
return null;
|
||||
} catch (error) {
|
||||
// Handle the error silently, perhaps log it internally or ignore it
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@ -92,6 +168,15 @@ export class DeviceStatusFirebaseService {
|
||||
relations: ['productDevice'],
|
||||
});
|
||||
}
|
||||
async getAllDevices() {
|
||||
return await this.deviceRepository.find({
|
||||
where: {
|
||||
isActive: true,
|
||||
},
|
||||
relations: ['productDevice'],
|
||||
});
|
||||
}
|
||||
|
||||
async getDevicesInstructionStatus(deviceUuid: string) {
|
||||
try {
|
||||
const deviceDetails = await this.getDeviceByDeviceUuid(deviceUuid);
|
||||
@ -154,56 +239,49 @@ export class DeviceStatusFirebaseService {
|
||||
this.firebaseDb,
|
||||
`device-status/${addDeviceStatusDto.deviceUuid}`,
|
||||
);
|
||||
const snapshot: DataSnapshot = await get(dataRef);
|
||||
const existingData = snapshot.val() || {};
|
||||
|
||||
// Assign default values if fields are not present
|
||||
if (!existingData.deviceTuyaUuid) {
|
||||
existingData.deviceTuyaUuid = addDeviceStatusDto.deviceTuyaUuid;
|
||||
}
|
||||
if (!existingData.productUuid) {
|
||||
existingData.productUuid = addDeviceStatusDto.productUuid;
|
||||
}
|
||||
if (!existingData.productType) {
|
||||
existingData.productType = addDeviceStatusDto.productType;
|
||||
}
|
||||
if (!existingData.status) {
|
||||
existingData.status = [];
|
||||
}
|
||||
// Use a transaction to handle concurrent updates
|
||||
await runTransaction(dataRef, (existingData) => {
|
||||
if (!existingData) {
|
||||
existingData = {};
|
||||
}
|
||||
|
||||
// Create a map to track existing status codes
|
||||
const statusMap = new Map(
|
||||
existingData.status.map((item) => [item.code, item.value]),
|
||||
);
|
||||
// Assign default values if fields are not present
|
||||
if (!existingData.deviceTuyaUuid) {
|
||||
existingData.deviceTuyaUuid = addDeviceStatusDto.deviceTuyaUuid;
|
||||
}
|
||||
if (!existingData.productUuid) {
|
||||
existingData.productUuid = addDeviceStatusDto.productUuid;
|
||||
}
|
||||
if (!existingData.productType) {
|
||||
existingData.productType = addDeviceStatusDto.productType;
|
||||
}
|
||||
if (!existingData.status) {
|
||||
existingData.status = [];
|
||||
}
|
||||
|
||||
// Update or add status codes
|
||||
// Create a map to track existing status codes
|
||||
const statusMap = new Map(
|
||||
existingData.status.map((item) => [item.code, item.value]),
|
||||
);
|
||||
|
||||
for (const statusItem of addDeviceStatusDto.status) {
|
||||
statusMap.set(statusItem.code, statusItem.value);
|
||||
}
|
||||
// Update or add status codes
|
||||
|
||||
// Convert the map back to an array format
|
||||
existingData.status = Array.from(statusMap, ([code, value]) => ({
|
||||
code,
|
||||
value,
|
||||
}));
|
||||
const newLogs = addDeviceStatusDto.log.properties.map((property) => {
|
||||
return this.deviceStatusLogRepository.create({
|
||||
deviceId: addDeviceStatusDto.deviceUuid,
|
||||
deviceTuyaId: addDeviceStatusDto.deviceTuyaUuid,
|
||||
productId: addDeviceStatusDto.log.productId,
|
||||
log: addDeviceStatusDto.log,
|
||||
code: property.code,
|
||||
value: property.value,
|
||||
eventId: addDeviceStatusDto.log.dataId,
|
||||
eventTime: new Date(property.time).toISOString(),
|
||||
});
|
||||
for (const statusItem of addDeviceStatusDto.status) {
|
||||
statusMap.set(statusItem.code, statusItem.value);
|
||||
}
|
||||
|
||||
// Convert the map back to an array format
|
||||
existingData.status = Array.from(statusMap, ([code, value]) => ({
|
||||
code,
|
||||
value,
|
||||
}));
|
||||
|
||||
return existingData;
|
||||
});
|
||||
await this.deviceStatusLogRepository.save(newLogs);
|
||||
// Save the updated data to Firebase
|
||||
await set(dataRef, existingData);
|
||||
|
||||
// Return the updated data
|
||||
return existingData;
|
||||
const snapshot: DataSnapshot = await get(dataRef);
|
||||
return snapshot.val();
|
||||
}
|
||||
}
|
||||
|
38
libs/common/src/helper/date-format.ts
Normal file
38
libs/common/src/helper/date-format.ts
Normal file
@ -0,0 +1,38 @@
|
||||
export function toDDMMYYYY(dateString?: string | null): string | null {
|
||||
if (!dateString) return null;
|
||||
|
||||
// Ensure dateString is valid format YYYY-MM-DD
|
||||
const regex = /^\d{4}-\d{2}-\d{2}$/;
|
||||
if (!regex.test(dateString)) {
|
||||
throw new Error(
|
||||
`Invalid date format: ${dateString}. Expected format is YYYY-MM-DD`,
|
||||
);
|
||||
}
|
||||
|
||||
const [year, month, day] = dateString.split('-');
|
||||
return `${day}-${month}-${year}`;
|
||||
}
|
||||
export function toMMYYYY(dateString?: string | null): string | null {
|
||||
if (!dateString) return null;
|
||||
|
||||
// Ensure dateString is valid format YYYY-MM
|
||||
const regex = /^\d{4}-\d{2}$/;
|
||||
if (!regex.test(dateString)) {
|
||||
throw new Error(
|
||||
`Invalid date format: ${dateString}. Expected format is YYYY-MM`,
|
||||
);
|
||||
}
|
||||
|
||||
const [year, month] = dateString.split('-');
|
||||
return `${month}-${year}`;
|
||||
}
|
||||
export function filterByMonth(data: any[], monthDate: string) {
|
||||
const [year, month] = monthDate.split('-').map(Number);
|
||||
|
||||
return data.filter((item) => {
|
||||
const itemDate = new Date(item.date);
|
||||
return (
|
||||
itemDate.getUTCFullYear() === year && itemDate.getUTCMonth() + 1 === month
|
||||
);
|
||||
});
|
||||
}
|
@ -8,10 +8,14 @@ import { TuyaWebSocketService } from './services/tuya.web.socket.service';
|
||||
import { OneSignalService } from './services/onesignal.service';
|
||||
import { DeviceMessagesService } from './services/device.messages.service';
|
||||
import { DeviceRepositoryModule } from '../modules/device/device.repository.module';
|
||||
import { DeviceNotificationRepository } from '../modules/device/repositories';
|
||||
import {
|
||||
DeviceNotificationRepository,
|
||||
DeviceRepository,
|
||||
} from '../modules/device/repositories';
|
||||
import { DeviceStatusFirebaseModule } from '../firebase/devices-status/devices-status.module';
|
||||
import { CommunityPermissionService } from './services/community.permission.service';
|
||||
import { CommunityRepository } from '../modules/community/repositories';
|
||||
import { SosHandlerService } from './services/sos.handler.service';
|
||||
|
||||
@Global()
|
||||
@Module({
|
||||
@ -25,6 +29,8 @@ import { CommunityRepository } from '../modules/community/repositories';
|
||||
DeviceMessagesService,
|
||||
DeviceNotificationRepository,
|
||||
CommunityRepository,
|
||||
SosHandlerService,
|
||||
DeviceRepository,
|
||||
],
|
||||
exports: [
|
||||
HelperHashService,
|
||||
|
66
libs/common/src/helper/services/aqi.data.service.ts
Normal file
66
libs/common/src/helper/services/aqi.data.service.ts
Normal file
@ -0,0 +1,66 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { DataSource } from 'typeorm';
|
||||
import { SQL_PROCEDURES_PATH } from '@app/common/constants/sql-query-path';
|
||||
import { SqlLoaderService } from './sql-loader.service';
|
||||
|
||||
@Injectable()
|
||||
export class AqiDataService {
|
||||
constructor(
|
||||
private readonly sqlLoader: SqlLoaderService,
|
||||
private readonly dataSource: DataSource,
|
||||
) {}
|
||||
|
||||
async updateAQISensorHistoricalData(): Promise<void> {
|
||||
try {
|
||||
const { dateStr } = this.getFormattedDates();
|
||||
|
||||
// Execute all procedures in parallel
|
||||
await Promise.all([
|
||||
this.executeProcedureWithRetry(
|
||||
'proceduce_update_daily_space_aqi',
|
||||
[dateStr],
|
||||
'fact_daily_space_aqi',
|
||||
),
|
||||
]);
|
||||
} catch (err) {
|
||||
console.error('Failed to update AQI sensor historical data:', err);
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
private getFormattedDates(): { dateStr: string } {
|
||||
const now = new Date();
|
||||
return {
|
||||
dateStr: now.toLocaleDateString('en-CA'), // YYYY-MM-DD
|
||||
};
|
||||
}
|
||||
private async executeProcedureWithRetry(
|
||||
procedureFileName: string,
|
||||
params: (string | number | null)[],
|
||||
folderName: string,
|
||||
retries = 3,
|
||||
): Promise<void> {
|
||||
try {
|
||||
const query = this.loadQuery(folderName, procedureFileName);
|
||||
await this.dataSource.query(query, params);
|
||||
console.log(`Procedure ${procedureFileName} executed successfully.`);
|
||||
} catch (err) {
|
||||
if (retries > 0) {
|
||||
const delayMs = 1000 * (4 - retries); // Exponential backoff
|
||||
console.warn(`Retrying ${procedureFileName} (${retries} retries left)`);
|
||||
await new Promise((resolve) => setTimeout(resolve, delayMs));
|
||||
return this.executeProcedureWithRetry(
|
||||
procedureFileName,
|
||||
params,
|
||||
folderName,
|
||||
retries - 1,
|
||||
);
|
||||
}
|
||||
console.error(`Failed to execute ${procedureFileName}:`, err);
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
private loadQuery(folderName: string, fileName: string): string {
|
||||
return this.sqlLoader.loadQuery(folderName, fileName, SQL_PROCEDURES_PATH);
|
||||
}
|
||||
}
|
71
libs/common/src/helper/services/occupancy.service.ts
Normal file
71
libs/common/src/helper/services/occupancy.service.ts
Normal file
@ -0,0 +1,71 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { DataSource } from 'typeorm';
|
||||
import { SQL_PROCEDURES_PATH } from '@app/common/constants/sql-query-path';
|
||||
import { SqlLoaderService } from './sql-loader.service';
|
||||
|
||||
@Injectable()
|
||||
export class OccupancyService {
|
||||
constructor(
|
||||
private readonly sqlLoader: SqlLoaderService,
|
||||
private readonly dataSource: DataSource,
|
||||
) {}
|
||||
|
||||
async updateOccupancyDataProcedures(): Promise<void> {
|
||||
try {
|
||||
const { dateStr } = this.getFormattedDates();
|
||||
|
||||
// Execute all procedures in parallel
|
||||
await Promise.all([
|
||||
this.executeProcedureWithRetry(
|
||||
'procedure_update_fact_space_occupancy',
|
||||
[dateStr],
|
||||
'fact_space_occupancy_count',
|
||||
),
|
||||
this.executeProcedureWithRetry(
|
||||
'procedure_update_daily_space_occupancy_duration',
|
||||
[dateStr],
|
||||
'fact_daily_space_occupancy_duration',
|
||||
),
|
||||
]);
|
||||
} catch (err) {
|
||||
console.error('Failed to update occupancy data:', err);
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
private getFormattedDates(): { dateStr: string } {
|
||||
const now = new Date();
|
||||
return {
|
||||
dateStr: now.toLocaleDateString('en-CA'), // YYYY-MM-DD
|
||||
};
|
||||
}
|
||||
private async executeProcedureWithRetry(
|
||||
procedureFileName: string,
|
||||
params: (string | number | null)[],
|
||||
folderName: string,
|
||||
retries = 3,
|
||||
): Promise<void> {
|
||||
try {
|
||||
const query = this.loadQuery(folderName, procedureFileName);
|
||||
await this.dataSource.query(query, params);
|
||||
console.log(`Procedure ${procedureFileName} executed successfully.`);
|
||||
} catch (err) {
|
||||
if (retries > 0) {
|
||||
const delayMs = 1000 * (4 - retries); // Exponential backoff
|
||||
console.warn(`Retrying ${procedureFileName} (${retries} retries left)`);
|
||||
await new Promise((resolve) => setTimeout(resolve, delayMs));
|
||||
return this.executeProcedureWithRetry(
|
||||
procedureFileName,
|
||||
params,
|
||||
folderName,
|
||||
retries - 1,
|
||||
);
|
||||
}
|
||||
console.error(`Failed to execute ${procedureFileName}:`, err);
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
private loadQuery(folderName: string, fileName: string): string {
|
||||
return this.sqlLoader.loadQuery(folderName, fileName, SQL_PROCEDURES_PATH);
|
||||
}
|
||||
}
|
84
libs/common/src/helper/services/power.clamp.service.ts
Normal file
84
libs/common/src/helper/services/power.clamp.service.ts
Normal file
@ -0,0 +1,84 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { DataSource } from 'typeorm';
|
||||
import { SQL_PROCEDURES_PATH } from '@app/common/constants/sql-query-path';
|
||||
import { SqlLoaderService } from './sql-loader.service';
|
||||
|
||||
@Injectable()
|
||||
export class PowerClampService {
|
||||
constructor(
|
||||
private readonly sqlLoader: SqlLoaderService,
|
||||
private readonly dataSource: DataSource,
|
||||
) {}
|
||||
|
||||
async updateEnergyConsumedHistoricalData(): Promise<void> {
|
||||
try {
|
||||
const { dateStr, monthYear } = this.getFormattedDates();
|
||||
|
||||
// Execute all procedures in parallel
|
||||
await Promise.all([
|
||||
this.executeProcedureWithRetry(
|
||||
'fact_hourly_device_energy_consumed_procedure',
|
||||
[dateStr],
|
||||
'fact_device_energy_consumed',
|
||||
),
|
||||
this.executeProcedureWithRetry(
|
||||
'fact_daily_device_energy_consumed_procedure',
|
||||
[dateStr],
|
||||
'fact_device_energy_consumed',
|
||||
),
|
||||
this.executeProcedureWithRetry(
|
||||
'fact_monthly_device_energy_consumed_procedure',
|
||||
[monthYear],
|
||||
'fact_device_energy_consumed',
|
||||
),
|
||||
]);
|
||||
} catch (err) {
|
||||
console.error('Failed to update energy consumption data:', err);
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
private getFormattedDates(): { dateStr: string; monthYear: string } {
|
||||
const now = new Date();
|
||||
return {
|
||||
dateStr: now.toLocaleDateString('en-CA'), // YYYY-MM-DD
|
||||
monthYear: now
|
||||
.toLocaleDateString('en-US', {
|
||||
month: '2-digit',
|
||||
year: 'numeric',
|
||||
})
|
||||
.replace('/', '-'), // MM-YYYY
|
||||
};
|
||||
}
|
||||
|
||||
private async executeProcedureWithRetry(
|
||||
procedureFileName: string,
|
||||
params: (string | number | null)[],
|
||||
folderName: string,
|
||||
retries = 3,
|
||||
): Promise<void> {
|
||||
try {
|
||||
const query = this.loadQuery(folderName, procedureFileName);
|
||||
await this.dataSource.query(query, params);
|
||||
console.log(`Procedure ${procedureFileName} executed successfully.`);
|
||||
} catch (err) {
|
||||
if (retries > 0) {
|
||||
const delayMs = 1000 * (4 - retries); // Exponential backoff
|
||||
console.warn(`Retrying ${procedureFileName} (${retries} retries left)`);
|
||||
await new Promise((resolve) => setTimeout(resolve, delayMs));
|
||||
return this.executeProcedureWithRetry(
|
||||
procedureFileName,
|
||||
params,
|
||||
folderName,
|
||||
retries - 1,
|
||||
);
|
||||
}
|
||||
console.error(`Failed to execute ${procedureFileName}:`, err);
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
private loadQuery(folderName: string, fileName: string): string {
|
||||
return this.sqlLoader.loadQuery(folderName, fileName, SQL_PROCEDURES_PATH);
|
||||
}
|
||||
}
|
67
libs/common/src/helper/services/sos.handler.service.ts
Normal file
67
libs/common/src/helper/services/sos.handler.service.ts
Normal file
@ -0,0 +1,67 @@
|
||||
import { Injectable, Logger } from '@nestjs/common';
|
||||
import { DeviceStatusFirebaseService } from '@app/common/firebase/devices-status/services/devices-status.service';
|
||||
|
||||
@Injectable()
|
||||
export class SosHandlerService {
|
||||
private readonly logger = new Logger(SosHandlerService.name);
|
||||
|
||||
constructor(
|
||||
private readonly deviceStatusFirebaseService: DeviceStatusFirebaseService,
|
||||
) {}
|
||||
|
||||
isSosTriggered(status: any): boolean {
|
||||
return (
|
||||
Array.isArray(status) &&
|
||||
status.some((item) => item.code === 'sos' && item.value === 'sos')
|
||||
);
|
||||
}
|
||||
|
||||
async handleSosEventFirebase(device: any, logData: any): Promise<void> {
|
||||
const sosTrueStatus = [{ code: 'sos', value: true }];
|
||||
const sosFalseStatus = [{ code: 'sos', value: false }];
|
||||
|
||||
try {
|
||||
// ✅ Send true status
|
||||
await this.deviceStatusFirebaseService.addDeviceStatusToFirebase({
|
||||
deviceTuyaUuid: device.deviceTuyaUuid,
|
||||
status: sosTrueStatus,
|
||||
log: logData,
|
||||
device,
|
||||
});
|
||||
|
||||
await this.deviceStatusFirebaseService.addBatchDeviceStatusToOurDb([
|
||||
{
|
||||
deviceTuyaUuid: device.deviceTuyaUuid,
|
||||
status: sosTrueStatus,
|
||||
log: logData,
|
||||
device,
|
||||
},
|
||||
]);
|
||||
|
||||
// ✅ Schedule false status
|
||||
setTimeout(async () => {
|
||||
try {
|
||||
await this.deviceStatusFirebaseService.addDeviceStatusToFirebase({
|
||||
deviceTuyaUuid: device.deviceTuyaUuid,
|
||||
status: sosFalseStatus,
|
||||
log: logData,
|
||||
device,
|
||||
});
|
||||
|
||||
await this.deviceStatusFirebaseService.addBatchDeviceStatusToOurDb([
|
||||
{
|
||||
deviceTuyaUuid: device.deviceTuyaUuid,
|
||||
status: sosFalseStatus,
|
||||
log: logData,
|
||||
device,
|
||||
},
|
||||
]);
|
||||
} catch (err) {
|
||||
this.logger.error('Failed to send SOS false value', err);
|
||||
}
|
||||
}, 2000);
|
||||
} catch (err) {
|
||||
this.logger.error('Failed to send SOS true value', err);
|
||||
}
|
||||
}
|
||||
}
|
22
libs/common/src/helper/services/sql-loader.service.ts
Normal file
22
libs/common/src/helper/services/sql-loader.service.ts
Normal file
@ -0,0 +1,22 @@
|
||||
import { Injectable, Logger } from '@nestjs/common';
|
||||
import { readFileSync } from 'fs';
|
||||
import { join } from 'path';
|
||||
|
||||
@Injectable()
|
||||
export class SqlLoaderService {
|
||||
private readonly logger = new Logger(SqlLoaderService.name);
|
||||
private readonly sqlRootPath = join(__dirname, '../sql/queries');
|
||||
|
||||
loadQuery(module: string, queryName: string, path: string): string {
|
||||
const filePath = join(process.cwd(), path, module, `${queryName}.sql`);
|
||||
try {
|
||||
return readFileSync(filePath, 'utf8');
|
||||
} catch (error) {
|
||||
this.logger.error(
|
||||
`Failed to load SQL query: ${module}/${queryName}`,
|
||||
error.stack,
|
||||
);
|
||||
throw new Error(`SQL query not found: ${module}/${queryName}`);
|
||||
}
|
||||
}
|
||||
}
|
@ -1,17 +1,33 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { Injectable, OnModuleInit } from '@nestjs/common';
|
||||
import TuyaWebsocket from '../../config/tuya-web-socket-config';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { DeviceStatusFirebaseService } from '@app/common/firebase/devices-status/services/devices-status.service';
|
||||
import { SosHandlerService } from './sos.handler.service';
|
||||
import * as NodeCache from 'node-cache';
|
||||
|
||||
@Injectable()
|
||||
export class TuyaWebSocketService {
|
||||
private client: any; // Adjust type according to your TuyaWebsocket client
|
||||
export class TuyaWebSocketService implements OnModuleInit {
|
||||
private client: any;
|
||||
private readonly isDevEnv: boolean;
|
||||
private readonly deviceCache = new NodeCache({ stdTTL: 7200 }); // TTL = 2 hour
|
||||
|
||||
private messageQueue: {
|
||||
devId: string;
|
||||
status: any;
|
||||
logData: any;
|
||||
device: any;
|
||||
}[] = [];
|
||||
|
||||
private isProcessing = false;
|
||||
|
||||
constructor(
|
||||
private readonly configService: ConfigService,
|
||||
private readonly deviceStatusFirebaseService: DeviceStatusFirebaseService,
|
||||
private readonly sosHandlerService: SosHandlerService,
|
||||
) {
|
||||
// Initialize the TuyaWebsocket client
|
||||
this.isDevEnv =
|
||||
this.configService.get<string>('NODE_ENV') === 'development';
|
||||
|
||||
this.client = new TuyaWebsocket({
|
||||
accessId: this.configService.get<string>('tuya-config.TUYA_ACCESS_ID'),
|
||||
accessKey: this.configService.get<string>('tuya-config.TUYA_ACCESS_KEY'),
|
||||
@ -21,34 +37,75 @@ export class TuyaWebSocketService {
|
||||
});
|
||||
|
||||
if (this.configService.get<string>('tuya-config.TRUN_ON_TUYA_SOCKET')) {
|
||||
// Set up event handlers
|
||||
this.setupEventHandlers();
|
||||
|
||||
// Start receiving messages
|
||||
this.client.start();
|
||||
}
|
||||
|
||||
// Run the queue processor every 15 seconds
|
||||
setInterval(() => this.processQueue(), 15000);
|
||||
|
||||
// Refresh the cache every 1 hour
|
||||
setInterval(() => this.initializeDeviceCache(), 30 * 60 * 1000); // 30 minutes
|
||||
}
|
||||
|
||||
async onModuleInit() {
|
||||
await this.initializeDeviceCache();
|
||||
}
|
||||
|
||||
private async initializeDeviceCache() {
|
||||
try {
|
||||
const allDevices = await this.deviceStatusFirebaseService.getAllDevices();
|
||||
allDevices.forEach((device) => {
|
||||
if (device.deviceTuyaUuid) {
|
||||
this.deviceCache.set(device.deviceTuyaUuid, device);
|
||||
}
|
||||
});
|
||||
console.log(`✅ Refreshed cache with ${allDevices.length} devices.`);
|
||||
} catch (error) {
|
||||
console.error('❌ Failed to initialize device cache:', error);
|
||||
}
|
||||
}
|
||||
|
||||
private setupEventHandlers() {
|
||||
// Event handlers
|
||||
this.client.open(() => {
|
||||
console.log('open');
|
||||
});
|
||||
|
||||
this.client.message(async (ws: WebSocket, message: any) => {
|
||||
try {
|
||||
await this.deviceStatusFirebaseService.addDeviceStatusToFirebase({
|
||||
deviceTuyaUuid: message.payload.data.bizData.devId,
|
||||
status: message.payload.data.bizData.properties,
|
||||
log: message.payload.data.bizData,
|
||||
});
|
||||
const { devId, status, logData } = this.extractMessageData(message);
|
||||
if (!Array.isArray(logData?.properties)) {
|
||||
this.client.ackMessage(message.messageId);
|
||||
return;
|
||||
}
|
||||
|
||||
const device = this.deviceCache.get(devId);
|
||||
if (!device) {
|
||||
// console.log(⛔ Unknown device: ${devId}, message ignored.);
|
||||
this.client.ackMessage(message.messageId);
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.sosHandlerService.isSosTriggered(status)) {
|
||||
await this.sosHandlerService.handleSosEventFirebase(devId, logData);
|
||||
} else {
|
||||
await this.deviceStatusFirebaseService.addDeviceStatusToFirebase({
|
||||
deviceTuyaUuid: devId,
|
||||
status,
|
||||
log: logData,
|
||||
device,
|
||||
});
|
||||
}
|
||||
|
||||
// Push to internal queue
|
||||
this.messageQueue.push({ devId, status, logData, device });
|
||||
|
||||
// Acknowledge the message
|
||||
this.client.ackMessage(message.messageId);
|
||||
} catch (error) {
|
||||
console.error('Error processing message:', error);
|
||||
console.error('❌ Error receiving message:', error);
|
||||
}
|
||||
});
|
||||
|
||||
this.client.reconnect(() => {
|
||||
console.log('reconnect');
|
||||
});
|
||||
@ -69,4 +126,62 @@ export class TuyaWebSocketService {
|
||||
console.error('WebSocket error:', error);
|
||||
});
|
||||
}
|
||||
private async processQueue() {
|
||||
if (this.isProcessing) {
|
||||
console.log('⏳ Skipping: still processing previous batch');
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.messageQueue.length === 0) return;
|
||||
|
||||
this.isProcessing = true;
|
||||
const batch = [...this.messageQueue];
|
||||
this.messageQueue = [];
|
||||
|
||||
console.log(`🔁 Processing batch of size: ${batch.length}`);
|
||||
|
||||
try {
|
||||
await this.deviceStatusFirebaseService.addBatchDeviceStatusToOurDb(
|
||||
batch.map((item) => ({
|
||||
deviceTuyaUuid: item.devId,
|
||||
status: item.status,
|
||||
log: item.logData,
|
||||
device: item.device,
|
||||
})),
|
||||
);
|
||||
} catch (error) {
|
||||
console.error('❌ Error processing batch:', error);
|
||||
this.messageQueue.unshift(...batch); // retry
|
||||
} finally {
|
||||
this.isProcessing = false;
|
||||
}
|
||||
}
|
||||
|
||||
private extractMessageData(message: any): {
|
||||
devId: string;
|
||||
status: any;
|
||||
logData: any;
|
||||
} {
|
||||
const payloadData = message.payload.data;
|
||||
|
||||
if (this.isDevEnv) {
|
||||
return {
|
||||
devId: payloadData.bizData?.devId,
|
||||
status: payloadData.bizData?.properties,
|
||||
logData: payloadData.bizData,
|
||||
};
|
||||
} else {
|
||||
return {
|
||||
devId: payloadData.devId,
|
||||
status: payloadData.status,
|
||||
logData: payloadData,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// private logDeviceData(devId: string, status: any, logData: any): void {
|
||||
// console.log('Device ID:', devId);
|
||||
// console.log('Status:', status);
|
||||
// console.log('Full Data:', logData);
|
||||
// }
|
||||
}
|
||||
|
12
libs/common/src/logger/logger.module.ts
Normal file
12
libs/common/src/logger/logger.module.ts
Normal file
@ -0,0 +1,12 @@
|
||||
// src/common/logger/logger.module.ts
|
||||
import { Module } from '@nestjs/common';
|
||||
import { WinstonModule } from 'nest-winston';
|
||||
import { winstonLoggerOptions } from './services/winston.logger';
|
||||
import { TypeOrmWinstonLogger } from './services/typeorm.logger';
|
||||
|
||||
@Module({
|
||||
imports: [WinstonModule.forRoot(winstonLoggerOptions)],
|
||||
providers: [TypeOrmWinstonLogger],
|
||||
exports: [TypeOrmWinstonLogger],
|
||||
})
|
||||
export class LoggerModule {}
|
72
libs/common/src/logger/services/typeorm.logger.ts
Normal file
72
libs/common/src/logger/services/typeorm.logger.ts
Normal file
@ -0,0 +1,72 @@
|
||||
import { Logger as WinstonLogger } from 'winston';
|
||||
import { Logger as TypeOrmLogger } from 'typeorm';
|
||||
import { requestContext } from '@app/common/context/request-context';
|
||||
|
||||
const ERROR_THRESHOLD = 2000;
|
||||
|
||||
export class TypeOrmWinstonLogger implements TypeOrmLogger {
|
||||
constructor(private readonly logger: WinstonLogger) {}
|
||||
|
||||
private getContext() {
|
||||
const context = requestContext.getStore();
|
||||
return {
|
||||
requestId: context?.requestId ?? 'N/A',
|
||||
userId: context?.userId ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
private extractTable(query: string): string {
|
||||
const match =
|
||||
query.match(/from\s+["`]?(\w+)["`]?/i) ||
|
||||
query.match(/into\s+["`]?(\w+)["`]?/i);
|
||||
return match?.[1] ?? 'unknown';
|
||||
}
|
||||
|
||||
logQuery(query: string, parameters?: any[]) {
|
||||
const context = this.getContext();
|
||||
this.logger.debug(`[DB][QUERY] ${query}`, {
|
||||
...context,
|
||||
table: this.extractTable(query),
|
||||
parameters,
|
||||
});
|
||||
}
|
||||
|
||||
logQueryError(error: string | Error, query: string, parameters?: any[]) {
|
||||
const context = this.getContext();
|
||||
this.logger.error(`[DB][ERROR] ${query}`, {
|
||||
...context,
|
||||
table: this.extractTable(query),
|
||||
parameters,
|
||||
error,
|
||||
});
|
||||
}
|
||||
|
||||
logQuerySlow(time: number, query: string, parameters?: any[]) {
|
||||
const context = this.getContext();
|
||||
const severity = time > ERROR_THRESHOLD ? 'error' : 'warn';
|
||||
const label = severity === 'error' ? 'VERY SLOW' : 'SLOW';
|
||||
|
||||
this.logger[severity](`[DB][${label} > ${time}ms] ${query}`, {
|
||||
...context,
|
||||
table: this.extractTable(query),
|
||||
parameters,
|
||||
duration: `${time}ms`,
|
||||
severity,
|
||||
});
|
||||
}
|
||||
|
||||
logSchemaBuild(message: string) {
|
||||
this.logger.info(`[DB][SCHEMA] ${message}`);
|
||||
}
|
||||
|
||||
logMigration(message: string) {
|
||||
this.logger.info(`[DB][MIGRATION] ${message}`);
|
||||
}
|
||||
|
||||
log(level: 'log' | 'info' | 'warn', message: any) {
|
||||
this.logger.log({
|
||||
level,
|
||||
message: `[DB] ${message}`,
|
||||
});
|
||||
}
|
||||
}
|
43
libs/common/src/logger/services/winston.logger.ts
Normal file
43
libs/common/src/logger/services/winston.logger.ts
Normal file
@ -0,0 +1,43 @@
|
||||
import { utilities as nestWinstonModuleUtilities } from 'nest-winston';
|
||||
import * as winston from 'winston';
|
||||
const environment = process.env.NODE_ENV || 'local';
|
||||
|
||||
export const winstonLoggerOptions: winston.LoggerOptions = {
|
||||
level:
|
||||
environment === 'local'
|
||||
? 'debug'
|
||||
: environment === 'development'
|
||||
? 'warn'
|
||||
: 'error',
|
||||
transports: [
|
||||
new winston.transports.Console({
|
||||
level:
|
||||
environment === 'local'
|
||||
? 'debug'
|
||||
: environment === 'development'
|
||||
? 'warn'
|
||||
: 'error',
|
||||
format: winston.format.combine(
|
||||
winston.format.timestamp(),
|
||||
nestWinstonModuleUtilities.format.nestLike('MyApp', {
|
||||
prettyPrint: environment === 'local',
|
||||
}),
|
||||
),
|
||||
}),
|
||||
// Only create file logs if NOT local
|
||||
...(environment !== 'local'
|
||||
? [
|
||||
new winston.transports.File({
|
||||
filename: 'logs/error.log',
|
||||
level: 'error',
|
||||
format: winston.format.json(),
|
||||
}),
|
||||
new winston.transports.File({
|
||||
filename: 'logs/combined.log',
|
||||
level: 'info',
|
||||
format: winston.format.json(),
|
||||
}),
|
||||
]
|
||||
: []),
|
||||
],
|
||||
};
|
14
libs/common/src/middleware/request-context.middleware.ts
Normal file
14
libs/common/src/middleware/request-context.middleware.ts
Normal file
@ -0,0 +1,14 @@
|
||||
import { Injectable, NestMiddleware } from '@nestjs/common';
|
||||
import { requestContext } from '../context/request-context';
|
||||
import { v4 as uuidv4 } from 'uuid';
|
||||
|
||||
@Injectable()
|
||||
export class RequestContextMiddleware implements NestMiddleware {
|
||||
use(req: any, res: any, next: () => void) {
|
||||
const context = {
|
||||
requestId: req.headers['x-request-id'] || uuidv4(),
|
||||
};
|
||||
|
||||
requestContext.run(context, () => next());
|
||||
}
|
||||
}
|
@ -16,7 +16,14 @@ export interface TypeORMCustomModelFindAllQuery {
|
||||
where?: { [key: string]: unknown };
|
||||
select?: string[];
|
||||
includeDisable?: boolean | string;
|
||||
includeSpaces?: boolean;
|
||||
}
|
||||
|
||||
export interface ExtendedTypeORMCustomModelFindAllQuery
|
||||
extends TypeORMCustomModelFindAllQuery {
|
||||
search?: string;
|
||||
}
|
||||
|
||||
interface CustomFindAllQuery {
|
||||
page?: number;
|
||||
size?: number;
|
||||
|
11
libs/common/src/modules/aqi/aqi.repository.module.ts
Normal file
11
libs/common/src/modules/aqi/aqi.repository.module.ts
Normal file
@ -0,0 +1,11 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { AqiSpaceDailyPollutantStatsEntity } from './entities/aqi.entity';
|
||||
|
||||
@Module({
|
||||
providers: [],
|
||||
exports: [],
|
||||
controllers: [],
|
||||
imports: [TypeOrmModule.forFeature([AqiSpaceDailyPollutantStatsEntity])],
|
||||
})
|
||||
export class AqiRepositoryModule {}
|
82
libs/common/src/modules/aqi/dtos/aqi.dto.ts
Normal file
82
libs/common/src/modules/aqi/dtos/aqi.dto.ts
Normal file
@ -0,0 +1,82 @@
|
||||
import { IsNotEmpty, IsNumber, IsString } from 'class-validator';
|
||||
|
||||
export class AqiSpaceDailyPollutantStatsDto {
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
public uuid: string;
|
||||
|
||||
@IsNotEmpty()
|
||||
@IsString()
|
||||
spaceUuid: string;
|
||||
|
||||
@IsNotEmpty()
|
||||
@IsString()
|
||||
eventDay: string;
|
||||
|
||||
@IsNotEmpty()
|
||||
@IsNumber()
|
||||
eventHour: number;
|
||||
|
||||
@IsNumber()
|
||||
pm1Min: number;
|
||||
|
||||
@IsNumber()
|
||||
pm1Avg: number;
|
||||
|
||||
@IsNumber()
|
||||
pm1Max: number;
|
||||
|
||||
@IsNumber()
|
||||
pm10Min: number;
|
||||
|
||||
@IsNumber()
|
||||
pm10Avg: number;
|
||||
|
||||
@IsNumber()
|
||||
pm10Max: number;
|
||||
|
||||
@IsNumber()
|
||||
pm25Min: number;
|
||||
|
||||
@IsNumber()
|
||||
pm25Avg: number;
|
||||
|
||||
@IsNumber()
|
||||
pm25Max: number;
|
||||
|
||||
@IsNumber()
|
||||
ch2oMin: number;
|
||||
|
||||
@IsNumber()
|
||||
ch2oAvg: number;
|
||||
|
||||
@IsNumber()
|
||||
ch2oMax: number;
|
||||
|
||||
@IsNumber()
|
||||
vocMin: number;
|
||||
|
||||
@IsNumber()
|
||||
vocAvg: number;
|
||||
|
||||
@IsNumber()
|
||||
vocMax: number;
|
||||
|
||||
@IsNumber()
|
||||
co2Min: number;
|
||||
|
||||
@IsNumber()
|
||||
co2Avg: number;
|
||||
|
||||
@IsNumber()
|
||||
co2Max: number;
|
||||
|
||||
@IsNumber()
|
||||
aqiMin: number;
|
||||
|
||||
@IsNumber()
|
||||
aqiAvg: number;
|
||||
|
||||
@IsNumber()
|
||||
aqiMax: number;
|
||||
}
|
1
libs/common/src/modules/aqi/dtos/index.ts
Normal file
1
libs/common/src/modules/aqi/dtos/index.ts
Normal file
@ -0,0 +1 @@
|
||||
export * from './aqi.dto';
|
184
libs/common/src/modules/aqi/entities/aqi.entity.ts
Normal file
184
libs/common/src/modules/aqi/entities/aqi.entity.ts
Normal file
@ -0,0 +1,184 @@
|
||||
import { Column, Entity, ManyToOne, Unique } from 'typeorm';
|
||||
import { AbstractEntity } from '../../abstract/entities/abstract.entity';
|
||||
import { SpaceEntity } from '../../space/entities/space.entity';
|
||||
import { AqiSpaceDailyPollutantStatsDto } from '../dtos';
|
||||
|
||||
@Entity({ name: 'space-daily-pollutant-stats' })
|
||||
@Unique(['spaceUuid', 'eventDate'])
|
||||
export class AqiSpaceDailyPollutantStatsEntity extends AbstractEntity<AqiSpaceDailyPollutantStatsDto> {
|
||||
@Column({ nullable: false })
|
||||
public spaceUuid: string;
|
||||
|
||||
@ManyToOne(() => SpaceEntity, (space) => space.aqiSensorDaily)
|
||||
space: SpaceEntity;
|
||||
|
||||
@Column({ type: 'date', nullable: false })
|
||||
public eventDate: Date;
|
||||
|
||||
@Column('float', { nullable: true })
|
||||
public goodAqiPercentage?: number;
|
||||
|
||||
@Column('float', { nullable: true })
|
||||
public moderateAqiPercentage?: number;
|
||||
|
||||
@Column('float', { nullable: true })
|
||||
public unhealthySensitiveAqiPercentage?: number;
|
||||
|
||||
@Column('float', { nullable: true })
|
||||
public unhealthyAqiPercentage?: number;
|
||||
|
||||
@Column('float', { nullable: true })
|
||||
public veryUnhealthyAqiPercentage?: number;
|
||||
|
||||
@Column('float', { nullable: true })
|
||||
public hazardousAqiPercentage?: number;
|
||||
|
||||
@Column('float', { nullable: true })
|
||||
public dailyAvgAqi?: number;
|
||||
|
||||
@Column('float', { nullable: true })
|
||||
public dailyMaxAqi?: number;
|
||||
|
||||
@Column('float', { nullable: true })
|
||||
public dailyMinAqi?: number;
|
||||
|
||||
@Column('float', { nullable: true })
|
||||
public goodPm25Percentage?: number;
|
||||
|
||||
@Column('float', { nullable: true })
|
||||
public moderatePm25Percentage?: number;
|
||||
|
||||
@Column('float', { nullable: true })
|
||||
public unhealthySensitivePm25Percentage?: number;
|
||||
|
||||
@Column('float', { nullable: true })
|
||||
public unhealthyPm25Percentage?: number;
|
||||
|
||||
@Column('float', { nullable: true })
|
||||
public veryUnhealthyPm25Percentage?: number;
|
||||
|
||||
@Column('float', { nullable: true })
|
||||
public hazardousPm25Percentage?: number;
|
||||
|
||||
@Column('float', { nullable: true })
|
||||
public dailyAvgPm25?: number;
|
||||
|
||||
@Column('float', { nullable: true })
|
||||
public dailyMaxPm25?: number;
|
||||
|
||||
@Column('float', { nullable: true })
|
||||
public dailyMinPm25?: number;
|
||||
|
||||
@Column('float', { nullable: true })
|
||||
public goodPm10Percentage?: number;
|
||||
|
||||
@Column('float', { nullable: true })
|
||||
public moderatePm10Percentage?: number;
|
||||
|
||||
@Column('float', { nullable: true })
|
||||
public unhealthySensitivePm10Percentage?: number;
|
||||
|
||||
@Column('float', { nullable: true })
|
||||
public unhealthyPm10Percentage?: number;
|
||||
|
||||
@Column('float', { nullable: true })
|
||||
public veryUnhealthyPm10Percentage?: number;
|
||||
|
||||
@Column('float', { nullable: true })
|
||||
public hazardousPm10Percentage?: number;
|
||||
|
||||
@Column('float', { nullable: true })
|
||||
public dailyAvgPm10?: number;
|
||||
|
||||
@Column('float', { nullable: true })
|
||||
public dailyMaxPm10?: number;
|
||||
|
||||
@Column('float', { nullable: true })
|
||||
public dailyMinPm10?: number;
|
||||
|
||||
@Column('float', { nullable: true })
|
||||
public goodVocPercentage?: number;
|
||||
|
||||
@Column('float', { nullable: true })
|
||||
public moderateVocPercentage?: number;
|
||||
|
||||
@Column('float', { nullable: true })
|
||||
public unhealthySensitiveVocPercentage?: number;
|
||||
|
||||
@Column('float', { nullable: true })
|
||||
public unhealthyVocPercentage?: number;
|
||||
|
||||
@Column('float', { nullable: true })
|
||||
public veryUnhealthyVocPercentage?: number;
|
||||
|
||||
@Column('float', { nullable: true })
|
||||
public hazardousVocPercentage?: number;
|
||||
|
||||
@Column('float', { nullable: true })
|
||||
public dailyAvgVoc?: number;
|
||||
|
||||
@Column('float', { nullable: true })
|
||||
public dailyMaxVoc?: number;
|
||||
|
||||
@Column('float', { nullable: true })
|
||||
public dailyMinVoc?: number;
|
||||
|
||||
@Column('float', { nullable: true })
|
||||
public goodCo2Percentage?: number;
|
||||
|
||||
@Column('float', { nullable: true })
|
||||
public moderateCo2Percentage?: number;
|
||||
|
||||
@Column('float', { nullable: true })
|
||||
public unhealthySensitiveCo2Percentage?: number;
|
||||
|
||||
@Column('float', { nullable: true })
|
||||
public unhealthyCo2Percentage?: number;
|
||||
|
||||
@Column('float', { nullable: true })
|
||||
public veryUnhealthyCo2Percentage?: number;
|
||||
|
||||
@Column('float', { nullable: true })
|
||||
public hazardousCo2Percentage?: number;
|
||||
|
||||
@Column('float', { nullable: true })
|
||||
public dailyAvgCo2?: number;
|
||||
|
||||
@Column('float', { nullable: true })
|
||||
public dailyMaxCo2?: number;
|
||||
|
||||
@Column('float', { nullable: true })
|
||||
public dailyMinCo2?: number;
|
||||
|
||||
@Column('float', { nullable: true })
|
||||
public goodCh2oPercentage?: number;
|
||||
|
||||
@Column('float', { nullable: true })
|
||||
public moderateCh2oPercentage?: number;
|
||||
|
||||
@Column('float', { nullable: true })
|
||||
public unhealthySensitiveCh2oPercentage?: number;
|
||||
|
||||
@Column('float', { nullable: true })
|
||||
public unhealthyCh2oPercentage?: number;
|
||||
|
||||
@Column('float', { nullable: true })
|
||||
public veryUnhealthyCh2oPercentage?: number;
|
||||
|
||||
@Column('float', { nullable: true })
|
||||
public hazardousCh2oPercentage?: number;
|
||||
|
||||
@Column('float', { nullable: true })
|
||||
public dailyAvgCh2o?: number;
|
||||
|
||||
@Column('float', { nullable: true })
|
||||
public dailyMaxCh2o?: number;
|
||||
|
||||
@Column('float', { nullable: true })
|
||||
public dailyMinCh2o?: number;
|
||||
|
||||
constructor(partial: Partial<AqiSpaceDailyPollutantStatsEntity>) {
|
||||
super();
|
||||
Object.assign(this, partial);
|
||||
}
|
||||
}
|
1
libs/common/src/modules/aqi/entities/index.ts
Normal file
1
libs/common/src/modules/aqi/entities/index.ts
Normal file
@ -0,0 +1 @@
|
||||
export * from './aqi.entity';
|
10
libs/common/src/modules/aqi/repositories/aqi.repository.ts
Normal file
10
libs/common/src/modules/aqi/repositories/aqi.repository.ts
Normal file
@ -0,0 +1,10 @@
|
||||
import { DataSource, Repository } from 'typeorm';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { AqiSpaceDailyPollutantStatsEntity } from '../entities';
|
||||
|
||||
@Injectable()
|
||||
export class AqiSpaceDailyPollutantStatsRepository extends Repository<AqiSpaceDailyPollutantStatsEntity> {
|
||||
constructor(private dataSource: DataSource) {
|
||||
super(AqiSpaceDailyPollutantStatsEntity, dataSource.createEntityManager());
|
||||
}
|
||||
}
|
1
libs/common/src/modules/aqi/repositories/index.ts
Normal file
1
libs/common/src/modules/aqi/repositories/index.ts
Normal file
@ -0,0 +1 @@
|
||||
export * from './aqi.repository';
|
@ -0,0 +1,9 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { ClientEntity } from './entities';
|
||||
|
||||
@Module({
|
||||
imports: [TypeOrmModule.forFeature([ClientEntity])],
|
||||
exports: [TypeOrmModule],
|
||||
})
|
||||
export class ClientRepositoryModule {}
|
20
libs/common/src/modules/client/dtos/client.dto.ts
Normal file
20
libs/common/src/modules/client/dtos/client.dto.ts
Normal file
@ -0,0 +1,20 @@
|
||||
import { IsArray, IsNotEmpty, IsString } from 'class-validator';
|
||||
|
||||
export class ClientDto {
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
public uuid: string;
|
||||
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
public clientId: string;
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
public clientSecret: string;
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
public redirectUri: string;
|
||||
@IsArray()
|
||||
@IsNotEmpty()
|
||||
public scopes: string[];
|
||||
}
|
1
libs/common/src/modules/client/dtos/index.ts
Normal file
1
libs/common/src/modules/client/dtos/index.ts
Normal file
@ -0,0 +1 @@
|
||||
export * from './client.dto';
|
46
libs/common/src/modules/client/entities/client.entity.ts
Normal file
46
libs/common/src/modules/client/entities/client.entity.ts
Normal file
@ -0,0 +1,46 @@
|
||||
import { Entity, Column, Unique, OneToMany } from 'typeorm';
|
||||
import { AbstractEntity } from '../../abstract/entities/abstract.entity';
|
||||
import { ClientDto } from '../dtos';
|
||||
import { UserEntity } from '../../user/entities';
|
||||
|
||||
@Entity({ name: 'clients' })
|
||||
@Unique(['clientId'])
|
||||
export class ClientEntity extends AbstractEntity<ClientDto> {
|
||||
@Column({
|
||||
type: 'uuid',
|
||||
default: () => 'gen_random_uuid()',
|
||||
nullable: false,
|
||||
})
|
||||
public uuid: string;
|
||||
|
||||
@Column({
|
||||
length: 255,
|
||||
nullable: false,
|
||||
})
|
||||
name: string;
|
||||
|
||||
@Column({
|
||||
length: 255,
|
||||
nullable: false,
|
||||
unique: true,
|
||||
})
|
||||
clientId: string;
|
||||
|
||||
@Column({
|
||||
length: 255,
|
||||
nullable: false,
|
||||
})
|
||||
clientSecret: string;
|
||||
|
||||
@Column({
|
||||
length: 255,
|
||||
nullable: false,
|
||||
})
|
||||
redirectUri: string;
|
||||
|
||||
@Column('simple-array')
|
||||
scopes: string[];
|
||||
|
||||
@OneToMany(() => UserEntity, (user) => user.client)
|
||||
users: UserEntity[];
|
||||
}
|
1
libs/common/src/modules/client/entities/index.ts
Normal file
1
libs/common/src/modules/client/entities/index.ts
Normal file
@ -0,0 +1 @@
|
||||
export * from './client.entity';
|
@ -0,0 +1,10 @@
|
||||
import { DataSource, Repository } from 'typeorm';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { ClientEntity } from '../entities';
|
||||
|
||||
@Injectable()
|
||||
export class ClientRepository extends Repository<ClientEntity> {
|
||||
constructor(private dataSource: DataSource) {
|
||||
super(ClientEntity, dataSource.createEntityManager());
|
||||
}
|
||||
}
|
1
libs/common/src/modules/client/repositories/index.ts
Normal file
1
libs/common/src/modules/client/repositories/index.ts
Normal file
@ -0,0 +1 @@
|
||||
export * from './client.repository';
|
@ -2,15 +2,15 @@ import { SourceType } from '@app/common/constants/source-type.enum';
|
||||
import { Entity, Column, PrimaryColumn, Unique } from 'typeorm';
|
||||
|
||||
@Entity('device-status-log')
|
||||
@Unique('event_time_idx', ['eventTime'])
|
||||
@Unique('event_time_idx', ['eventTime', 'deviceId', 'code', 'value'])
|
||||
export class DeviceStatusLogEntity {
|
||||
@Column({ type: 'int', generated: true, unsigned: true })
|
||||
@PrimaryColumn({ type: 'int', generated: true, unsigned: true })
|
||||
id: number;
|
||||
|
||||
@Column({ type: 'text' })
|
||||
eventId: string;
|
||||
|
||||
@PrimaryColumn({ type: 'timestamptz' })
|
||||
@Column({ type: 'timestamptz' })
|
||||
eventTime: Date;
|
||||
|
||||
@Column({
|
||||
|
@ -6,8 +6,6 @@ import {
|
||||
Unique,
|
||||
Index,
|
||||
JoinColumn,
|
||||
OneToOne,
|
||||
JoinTable,
|
||||
} from 'typeorm';
|
||||
import { AbstractEntity } from '../../abstract/entities/abstract.entity';
|
||||
import { DeviceDto, DeviceUserPermissionDto } from '../dtos/device.dto';
|
||||
@ -18,8 +16,9 @@ import { PermissionTypeEntity } from '../../permission/entities';
|
||||
import { SceneDeviceEntity } from '../../scene-device/entities';
|
||||
import { SpaceEntity } from '../../space/entities/space.entity';
|
||||
import { SubspaceEntity } from '../../space/entities/subspace/subspace.entity';
|
||||
import { TagEntity } from '../../space/entities/tag.entity';
|
||||
import { NewTagEntity } from '../../tag';
|
||||
import { PowerClampHourlyEntity } from '../../power-clamp/entities/power-clamp.entity';
|
||||
import { PresenceSensorDailyDeviceEntity } from '../../presence-sensor/entities';
|
||||
|
||||
@Entity({ name: 'device' })
|
||||
@Unique(['deviceTuyaUuid'])
|
||||
@ -35,10 +34,10 @@ export class DeviceEntity extends AbstractEntity<DeviceDto> {
|
||||
type: 'boolean',
|
||||
})
|
||||
isActive: boolean;
|
||||
|
||||
@ManyToOne(() => UserEntity, (user) => user.userSpaces, { nullable: false })
|
||||
user: UserEntity;
|
||||
|
||||
@Column({
|
||||
nullable: false,
|
||||
})
|
||||
name: string;
|
||||
@OneToMany(
|
||||
() => DeviceUserPermissionEntity,
|
||||
(permission) => permission.device,
|
||||
@ -79,15 +78,13 @@ export class DeviceEntity extends AbstractEntity<DeviceDto> {
|
||||
@OneToMany(() => SceneDeviceEntity, (sceneDevice) => sceneDevice.device, {})
|
||||
sceneDevices: SceneDeviceEntity[];
|
||||
|
||||
@OneToOne(() => TagEntity, (tag) => tag.device, {
|
||||
nullable: true,
|
||||
})
|
||||
tag: TagEntity;
|
||||
|
||||
@OneToMany(() => NewTagEntity, (tag) => tag.devices)
|
||||
@JoinTable({ name: 'device_tags' })
|
||||
public tags: NewTagEntity[];
|
||||
|
||||
@ManyToOne(() => NewTagEntity, (tag) => tag.devices)
|
||||
@JoinColumn({ name: 'tag_uuid' })
|
||||
public tag: NewTagEntity;
|
||||
@OneToMany(() => PowerClampHourlyEntity, (powerClamp) => powerClamp.device)
|
||||
powerClampHourly: PowerClampHourlyEntity[];
|
||||
@OneToMany(() => PresenceSensorDailyDeviceEntity, (sensor) => sensor.device)
|
||||
presenceSensorDaily: PresenceSensorDailyDeviceEntity[];
|
||||
constructor(partial: Partial<DeviceEntity>) {
|
||||
super();
|
||||
Object.assign(this, partial);
|
||||
|
1
libs/common/src/modules/occupancy/dtos/index.ts
Normal file
1
libs/common/src/modules/occupancy/dtos/index.ts
Normal file
@ -0,0 +1 @@
|
||||
export * from './occupancy.dto';
|
23
libs/common/src/modules/occupancy/dtos/occupancy.dto.ts
Normal file
23
libs/common/src/modules/occupancy/dtos/occupancy.dto.ts
Normal file
@ -0,0 +1,23 @@
|
||||
import { IsNotEmpty, IsNumber, IsString } from 'class-validator';
|
||||
|
||||
export class SpaceDailyOccupancyDurationDto {
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
public uuid: string;
|
||||
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
public spaceUuid: string;
|
||||
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
public eventDate: string;
|
||||
|
||||
@IsNumber()
|
||||
@IsNotEmpty()
|
||||
public occupancyPercentage: number;
|
||||
|
||||
@IsNumber()
|
||||
@IsNotEmpty()
|
||||
public occupiedSeconds: number;
|
||||
}
|
1
libs/common/src/modules/occupancy/entities/index.ts
Normal file
1
libs/common/src/modules/occupancy/entities/index.ts
Normal file
@ -0,0 +1 @@
|
||||
export * from './occupancy.entity';
|
@ -0,0 +1,32 @@
|
||||
import { Column, Entity, ManyToOne, Unique } from 'typeorm';
|
||||
import { AbstractEntity } from '../../abstract/entities/abstract.entity';
|
||||
import { SpaceEntity } from '../../space/entities/space.entity';
|
||||
import { SpaceDailyOccupancyDurationDto } from '../dtos';
|
||||
|
||||
@Entity({ name: 'space-daily-occupancy-duration' })
|
||||
@Unique(['spaceUuid', 'eventDate'])
|
||||
export class SpaceDailyOccupancyDurationEntity extends AbstractEntity<SpaceDailyOccupancyDurationDto> {
|
||||
@Column({ nullable: false })
|
||||
public spaceUuid: string;
|
||||
|
||||
@Column({ nullable: false, type: 'date' })
|
||||
public eventDate: string;
|
||||
|
||||
public CountTotalPresenceDetected: number;
|
||||
|
||||
@ManyToOne(() => SpaceEntity, (space) => space.presenceSensorDaily)
|
||||
space: SpaceEntity;
|
||||
|
||||
@Column({ type: 'int' })
|
||||
occupancyPercentage: number;
|
||||
|
||||
@Column({ type: 'int', nullable: true })
|
||||
occupiedSeconds?: number;
|
||||
|
||||
@Column({ type: 'int', nullable: true })
|
||||
deviceCount?: number;
|
||||
constructor(partial: Partial<SpaceDailyOccupancyDurationEntity>) {
|
||||
super();
|
||||
Object.assign(this, partial);
|
||||
}
|
||||
}
|
@ -0,0 +1,11 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { SpaceDailyOccupancyDurationEntity } from './entities/occupancy.entity';
|
||||
|
||||
@Module({
|
||||
providers: [],
|
||||
exports: [],
|
||||
controllers: [],
|
||||
imports: [TypeOrmModule.forFeature([SpaceDailyOccupancyDurationEntity])],
|
||||
})
|
||||
export class SpaceDailyOccupancyDurationRepositoryModule {}
|
1
libs/common/src/modules/occupancy/repositories/index.ts
Normal file
1
libs/common/src/modules/occupancy/repositories/index.ts
Normal file
@ -0,0 +1 @@
|
||||
export * from './occupancy.repository';
|
@ -0,0 +1,10 @@
|
||||
import { DataSource, Repository } from 'typeorm';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { SpaceDailyOccupancyDurationEntity } from '../entities/occupancy.entity';
|
||||
|
||||
@Injectable()
|
||||
export class SpaceDailyOccupancyDurationEntityRepository extends Repository<SpaceDailyOccupancyDurationEntity> {
|
||||
constructor(private dataSource: DataSource) {
|
||||
super(SpaceDailyOccupancyDurationEntity, dataSource.createEntityManager());
|
||||
}
|
||||
}
|
1
libs/common/src/modules/power-clamp/dtos/index.ts
Normal file
1
libs/common/src/modules/power-clamp/dtos/index.ts
Normal file
@ -0,0 +1 @@
|
||||
export * from './power-clamp.dto';
|
43
libs/common/src/modules/power-clamp/dtos/power-clamp.dto.ts
Normal file
43
libs/common/src/modules/power-clamp/dtos/power-clamp.dto.ts
Normal file
@ -0,0 +1,43 @@
|
||||
import { IsNotEmpty, IsOptional, IsString } from 'class-validator';
|
||||
|
||||
export class PowerClampDto {
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
public uuid: string;
|
||||
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
public deviceUuid: string;
|
||||
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
public hour?: string;
|
||||
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
public day?: string;
|
||||
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
public month?: string;
|
||||
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
public energyConsumedKw: string;
|
||||
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
public energyConsumedA: string;
|
||||
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
public energyConsumedB: string;
|
||||
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
public energyConsumedC: string;
|
||||
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
public prodType: string;
|
||||
}
|
1
libs/common/src/modules/power-clamp/entities/index.ts
Normal file
1
libs/common/src/modules/power-clamp/entities/index.ts
Normal file
@ -0,0 +1 @@
|
||||
export * from './power-clamp.entity';
|
@ -0,0 +1,95 @@
|
||||
import { Column, Entity, ManyToOne, Unique } from 'typeorm';
|
||||
import { AbstractEntity } from '../../abstract/entities/abstract.entity';
|
||||
import { PowerClampDto } from '../dtos';
|
||||
import { DeviceEntity } from '../../device/entities/device.entity';
|
||||
|
||||
@Entity({ name: 'power-clamp-energy-consumed-hourly' })
|
||||
@Unique(['deviceUuid', 'date', 'hour'])
|
||||
export class PowerClampHourlyEntity extends AbstractEntity<PowerClampDto> {
|
||||
@Column({ nullable: false })
|
||||
public deviceUuid: string;
|
||||
|
||||
@Column({ nullable: false })
|
||||
public hour: string;
|
||||
|
||||
@Column({ nullable: false, type: 'date' })
|
||||
public date: string;
|
||||
|
||||
@Column({ nullable: true })
|
||||
public energyConsumedKw: string;
|
||||
|
||||
@Column({ nullable: false })
|
||||
public energyConsumedA: string;
|
||||
|
||||
@Column({ nullable: false })
|
||||
public energyConsumedB: string;
|
||||
|
||||
@Column({ nullable: false })
|
||||
public energyConsumedC: string;
|
||||
|
||||
@ManyToOne(() => DeviceEntity, (device) => device.powerClampHourly)
|
||||
device: DeviceEntity;
|
||||
|
||||
constructor(partial: Partial<PowerClampHourlyEntity>) {
|
||||
super();
|
||||
Object.assign(this, partial);
|
||||
}
|
||||
}
|
||||
@Entity({ name: 'power-clamp-energy-consumed-daily' })
|
||||
@Unique(['deviceUuid', 'date'])
|
||||
export class PowerClampDailyEntity extends AbstractEntity<PowerClampDto> {
|
||||
@Column({ nullable: false })
|
||||
public deviceUuid: string;
|
||||
|
||||
@Column({ nullable: false, type: 'date' })
|
||||
public date: string;
|
||||
|
||||
@Column({ nullable: true })
|
||||
public energyConsumedKw: string;
|
||||
|
||||
@Column({ nullable: false })
|
||||
public energyConsumedA: string;
|
||||
|
||||
@Column({ nullable: false })
|
||||
public energyConsumedB: string;
|
||||
|
||||
@Column({ nullable: false })
|
||||
public energyConsumedC: string;
|
||||
|
||||
@ManyToOne(() => DeviceEntity, (device) => device.powerClampHourly)
|
||||
device: DeviceEntity;
|
||||
|
||||
constructor(partial: Partial<PowerClampHourlyEntity>) {
|
||||
super();
|
||||
Object.assign(this, partial);
|
||||
}
|
||||
}
|
||||
@Entity({ name: 'power-clamp-energy-consumed-monthly' })
|
||||
@Unique(['deviceUuid', 'month'])
|
||||
export class PowerClampMonthlyEntity extends AbstractEntity<PowerClampDto> {
|
||||
@Column({ nullable: false })
|
||||
public deviceUuid: string;
|
||||
|
||||
@Column({ nullable: false })
|
||||
public month: string;
|
||||
|
||||
@Column({ nullable: true })
|
||||
public energyConsumedKw: string;
|
||||
|
||||
@Column({ nullable: false })
|
||||
public energyConsumedA: string;
|
||||
|
||||
@Column({ nullable: false })
|
||||
public energyConsumedB: string;
|
||||
|
||||
@Column({ nullable: false })
|
||||
public energyConsumedC: string;
|
||||
|
||||
@ManyToOne(() => DeviceEntity, (device) => device.powerClampHourly)
|
||||
device: DeviceEntity;
|
||||
|
||||
constructor(partial: Partial<PowerClampHourlyEntity>) {
|
||||
super();
|
||||
Object.assign(this, partial);
|
||||
}
|
||||
}
|
@ -0,0 +1,11 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { PowerClampHourlyEntity } from './entities/power-clamp.entity';
|
||||
|
||||
@Module({
|
||||
providers: [],
|
||||
exports: [],
|
||||
controllers: [],
|
||||
imports: [TypeOrmModule.forFeature([PowerClampHourlyEntity])],
|
||||
})
|
||||
export class PowerClampRepositoryModule {}
|
@ -0,0 +1 @@
|
||||
export * from './power-clamp.repository';
|
@ -0,0 +1,28 @@
|
||||
import { DataSource, Repository } from 'typeorm';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import {
|
||||
PowerClampDailyEntity,
|
||||
PowerClampHourlyEntity,
|
||||
PowerClampMonthlyEntity,
|
||||
} from '../entities/power-clamp.entity';
|
||||
|
||||
@Injectable()
|
||||
export class PowerClampHourlyRepository extends Repository<PowerClampHourlyEntity> {
|
||||
constructor(private dataSource: DataSource) {
|
||||
super(PowerClampHourlyEntity, dataSource.createEntityManager());
|
||||
}
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class PowerClampDailyRepository extends Repository<PowerClampDailyEntity> {
|
||||
constructor(private dataSource: DataSource) {
|
||||
super(PowerClampDailyEntity, dataSource.createEntityManager());
|
||||
}
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class PowerClampMonthlyRepository extends Repository<PowerClampMonthlyEntity> {
|
||||
constructor(private dataSource: DataSource) {
|
||||
super(PowerClampMonthlyEntity, dataSource.createEntityManager());
|
||||
}
|
||||
}
|
1
libs/common/src/modules/presence-sensor/dtos/index.ts
Normal file
1
libs/common/src/modules/presence-sensor/dtos/index.ts
Normal file
@ -0,0 +1 @@
|
||||
export * from './presence-sensor.dto';
|
@ -0,0 +1,27 @@
|
||||
import { IsNotEmpty, IsNumber, IsString } from 'class-validator';
|
||||
|
||||
export class PresenceSensorDto {
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
public uuid: string;
|
||||
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
public deviceUuid: string;
|
||||
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
public eventDate: string;
|
||||
|
||||
@IsNumber()
|
||||
@IsNotEmpty()
|
||||
public CountMotionDetected: number;
|
||||
|
||||
@IsNumber()
|
||||
@IsNotEmpty()
|
||||
public CountPresenceDetected: number;
|
||||
|
||||
@IsNumber()
|
||||
@IsNotEmpty()
|
||||
public CountTotalPresenceDetected: number;
|
||||
}
|
@ -0,0 +1 @@
|
||||
export * from './presence-sensor.entity';
|
@ -0,0 +1,58 @@
|
||||
import { Column, Entity, ManyToOne, Unique } from 'typeorm';
|
||||
import { AbstractEntity } from '../../abstract/entities/abstract.entity';
|
||||
import { PresenceSensorDto } from '../dtos';
|
||||
import { DeviceEntity } from '../../device/entities/device.entity';
|
||||
import { SpaceEntity } from '../../space/entities/space.entity';
|
||||
|
||||
@Entity({ name: 'presence-sensor-daily-device-detection' })
|
||||
@Unique(['deviceUuid', 'eventDate'])
|
||||
export class PresenceSensorDailyDeviceEntity extends AbstractEntity<PresenceSensorDto> {
|
||||
@Column({ nullable: false })
|
||||
public deviceUuid: string;
|
||||
|
||||
@Column({ nullable: false, type: 'date' })
|
||||
public eventDate: string;
|
||||
|
||||
@Column({ nullable: false })
|
||||
public CountMotionDetected: number;
|
||||
|
||||
@Column({ nullable: false })
|
||||
public CountPresenceDetected: number;
|
||||
|
||||
@Column({ nullable: false })
|
||||
public CountTotalPresenceDetected: number;
|
||||
|
||||
@ManyToOne(() => DeviceEntity, (device) => device.presenceSensorDaily)
|
||||
device: DeviceEntity;
|
||||
|
||||
constructor(partial: Partial<PresenceSensorDailyDeviceEntity>) {
|
||||
super();
|
||||
Object.assign(this, partial);
|
||||
}
|
||||
}
|
||||
@Entity({ name: 'presence-sensor-daily-space-detection' })
|
||||
@Unique(['spaceUuid', 'eventDate'])
|
||||
export class PresenceSensorDailySpaceEntity extends AbstractEntity<PresenceSensorDto> {
|
||||
@Column({ nullable: false })
|
||||
public spaceUuid: string;
|
||||
|
||||
@Column({ nullable: false, type: 'date' })
|
||||
public eventDate: string;
|
||||
|
||||
@Column({ nullable: false })
|
||||
public CountMotionDetected: number;
|
||||
|
||||
@Column({ nullable: false })
|
||||
public CountPresenceDetected: number;
|
||||
|
||||
@Column({ nullable: false })
|
||||
public CountTotalPresenceDetected: number;
|
||||
|
||||
@ManyToOne(() => SpaceEntity, (space) => space.presenceSensorDaily)
|
||||
space: SpaceEntity;
|
||||
|
||||
constructor(partial: Partial<PresenceSensorDailySpaceEntity>) {
|
||||
super();
|
||||
Object.assign(this, partial);
|
||||
}
|
||||
}
|
@ -0,0 +1,19 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import {
|
||||
PresenceSensorDailyDeviceEntity,
|
||||
PresenceSensorDailySpaceEntity,
|
||||
} from './entities/presence-sensor.entity';
|
||||
|
||||
@Module({
|
||||
providers: [],
|
||||
exports: [],
|
||||
controllers: [],
|
||||
imports: [
|
||||
TypeOrmModule.forFeature([
|
||||
PresenceSensorDailyDeviceEntity,
|
||||
PresenceSensorDailySpaceEntity,
|
||||
]),
|
||||
],
|
||||
})
|
||||
export class PresenceSensorRepositoryModule {}
|
@ -0,0 +1 @@
|
||||
export * from './presence-sensor.repository';
|
@ -0,0 +1,19 @@
|
||||
import { DataSource, Repository } from 'typeorm';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import {
|
||||
PresenceSensorDailyDeviceEntity,
|
||||
PresenceSensorDailySpaceEntity,
|
||||
} from '../entities';
|
||||
|
||||
@Injectable()
|
||||
export class PresenceSensorDailyDeviceRepository extends Repository<PresenceSensorDailyDeviceEntity> {
|
||||
constructor(private dataSource: DataSource) {
|
||||
super(PresenceSensorDailyDeviceEntity, dataSource.createEntityManager());
|
||||
}
|
||||
}
|
||||
@Injectable()
|
||||
export class PresenceSensorDailySpaceRepository extends Repository<PresenceSensorDailySpaceEntity> {
|
||||
constructor(private dataSource: DataSource) {
|
||||
super(PresenceSensorDailySpaceEntity, dataSource.createEntityManager());
|
||||
}
|
||||
}
|
@ -1,10 +1,7 @@
|
||||
import { Column, Entity, OneToMany } from 'typeorm';
|
||||
import { ProductDto } from '../dtos';
|
||||
import { AbstractEntity } from '../../abstract/entities/abstract.entity';
|
||||
import { DeviceEntity } from '../../device/entities';
|
||||
import { TagModel } from '../../space-model';
|
||||
import { TagEntity } from '../../space/entities/tag.entity';
|
||||
import { NewTagEntity } from '../../tag/entities';
|
||||
import { ProductDto } from '../dtos';
|
||||
@Entity({ name: 'product' })
|
||||
export class ProductEntity extends AbstractEntity<ProductDto> {
|
||||
@Column({
|
||||
@ -28,15 +25,6 @@ export class ProductEntity extends AbstractEntity<ProductDto> {
|
||||
})
|
||||
public prodType: string;
|
||||
|
||||
@OneToMany(() => NewTagEntity, (tag) => tag.product, { cascade: true })
|
||||
public newTags: NewTagEntity[];
|
||||
|
||||
@OneToMany(() => TagModel, (tag) => tag.product)
|
||||
tagModels: TagModel[];
|
||||
|
||||
@OneToMany(() => TagEntity, (tag) => tag.product)
|
||||
tags: TagEntity[];
|
||||
|
||||
@OneToMany(
|
||||
() => DeviceEntity,
|
||||
(devicesProductEntity) => devicesProductEntity.productDevice,
|
||||
|
@ -12,6 +12,7 @@ export class RoleTypeEntity extends AbstractEntity<RoleTypeDto> {
|
||||
nullable: false,
|
||||
enum: Object.values(RoleType),
|
||||
})
|
||||
// why is this ts-type string not enum?
|
||||
type: string;
|
||||
@OneToMany(() => UserEntity, (inviteUser) => inviteUser.roleType, {
|
||||
nullable: true,
|
||||
|
@ -1,21 +0,0 @@
|
||||
import { IsNotEmpty, IsString } from 'class-validator';
|
||||
|
||||
export class TagModelDto {
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
public uuid: string;
|
||||
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
public name: string;
|
||||
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
public productUuid: string;
|
||||
|
||||
@IsString()
|
||||
spaceModelUuid: string;
|
||||
|
||||
@IsString()
|
||||
subspaceModelUuid: string;
|
||||
}
|
@ -1,4 +1,3 @@
|
||||
export * from './space-model-product-allocation.entity';
|
||||
export * from './space-model.entity';
|
||||
export * from './subspace-model';
|
||||
export * from './tag-model.entity';
|
||||
export * from './space-model-product-allocation.entity';
|
||||
|
@ -1,18 +1,12 @@
|
||||
import {
|
||||
Entity,
|
||||
Column,
|
||||
ManyToOne,
|
||||
ManyToMany,
|
||||
JoinTable,
|
||||
OneToMany,
|
||||
} from 'typeorm';
|
||||
import { SpaceModelEntity } from './space-model.entity';
|
||||
import { NewTagEntity } from '../../tag/entities/tag.entity';
|
||||
import { Column, Entity, ManyToOne, OneToMany, Unique } from 'typeorm';
|
||||
import { AbstractEntity } from '../../abstract/entities/abstract.entity';
|
||||
import { ProductEntity } from '../../product/entities/product.entity';
|
||||
import { SpaceProductAllocationEntity } from '../../space/entities/space-product-allocation.entity';
|
||||
import { AbstractEntity } from '../../abstract/entities/abstract.entity';
|
||||
import { NewTagEntity } from '../../tag/entities/tag.entity';
|
||||
import { SpaceModelEntity } from './space-model.entity';
|
||||
|
||||
@Entity({ name: 'space_model_product_allocation' })
|
||||
@Unique(['spaceModel', 'product', 'tag'])
|
||||
export class SpaceModelProductAllocationEntity extends AbstractEntity<SpaceModelProductAllocationEntity> {
|
||||
@Column({
|
||||
type: 'uuid',
|
||||
@ -31,9 +25,8 @@ export class SpaceModelProductAllocationEntity extends AbstractEntity<SpaceModel
|
||||
@ManyToOne(() => ProductEntity, { nullable: false, onDelete: 'CASCADE' })
|
||||
public product: ProductEntity;
|
||||
|
||||
@ManyToMany(() => NewTagEntity)
|
||||
@JoinTable({ name: 'space_model_product_tags' })
|
||||
public tags: NewTagEntity[];
|
||||
@ManyToOne(() => NewTagEntity, { nullable: true, onDelete: 'CASCADE' })
|
||||
public tag: NewTagEntity;
|
||||
|
||||
@OneToMany(
|
||||
() => SpaceProductAllocationEntity,
|
||||
|
@ -1,11 +1,10 @@
|
||||
import { Entity, Column, OneToMany, ManyToOne, JoinColumn } from 'typeorm';
|
||||
import { Column, Entity, JoinColumn, ManyToOne, OneToMany } from 'typeorm';
|
||||
import { AbstractEntity } from '../../abstract/entities/abstract.entity';
|
||||
import { SpaceModelDto } from '../dtos';
|
||||
import { SubspaceModelEntity } from './subspace-model';
|
||||
import { ProjectEntity } from '../../project/entities';
|
||||
import { TagModel } from './tag-model.entity';
|
||||
import { SpaceModelProductAllocationEntity } from './space-model-product-allocation.entity';
|
||||
import { SpaceEntity } from '../../space/entities/space.entity';
|
||||
import { SpaceModelDto } from '../dtos';
|
||||
import { SpaceModelProductAllocationEntity } from './space-model-product-allocation.entity';
|
||||
import { SubspaceModelEntity } from './subspace-model';
|
||||
|
||||
@Entity({ name: 'space-model' })
|
||||
export class SpaceModelEntity extends AbstractEntity<SpaceModelDto> {
|
||||
@ -49,9 +48,6 @@ export class SpaceModelEntity extends AbstractEntity<SpaceModelDto> {
|
||||
})
|
||||
public spaces: SpaceEntity[];
|
||||
|
||||
@OneToMany(() => TagModel, (tag) => tag.spaceModel)
|
||||
tags: TagModel[];
|
||||
|
||||
@OneToMany(
|
||||
() => SpaceModelProductAllocationEntity,
|
||||
(allocation) => allocation.spaceModel,
|
||||
|
@ -1,11 +1,12 @@
|
||||
import { Entity, Column, ManyToOne, ManyToMany, JoinTable } from 'typeorm';
|
||||
import { SubspaceModelEntity } from './subspace-model.entity';
|
||||
import { AbstractEntity } from '@app/common/modules/abstract/entities/abstract.entity';
|
||||
import { ProductEntity } from '@app/common/modules/product/entities/product.entity';
|
||||
import { NewTagEntity } from '@app/common/modules/tag/entities/tag.entity';
|
||||
import { Column, Entity, ManyToOne, Unique } from 'typeorm';
|
||||
import { SubspaceModelProductAllocationDto } from '../../dtos/subspace-model/subspace-model-product-allocation.dto';
|
||||
import { AbstractEntity } from '@app/common/modules/abstract/entities/abstract.entity';
|
||||
import { SubspaceModelEntity } from './subspace-model.entity';
|
||||
|
||||
@Entity({ name: 'subspace_model_product_allocation' })
|
||||
@Unique(['subspaceModel', 'product', 'tag'])
|
||||
export class SubspaceModelProductAllocationEntity extends AbstractEntity<SubspaceModelProductAllocationDto> {
|
||||
@Column({
|
||||
type: 'uuid',
|
||||
@ -27,9 +28,8 @@ export class SubspaceModelProductAllocationEntity extends AbstractEntity<Subspac
|
||||
@ManyToOne(() => ProductEntity, { nullable: false, onDelete: 'CASCADE' })
|
||||
public product: ProductEntity;
|
||||
|
||||
@ManyToMany(() => NewTagEntity, (tag) => tag.subspaceModelAllocations)
|
||||
@JoinTable({ name: 'subspace_model_product_tags' })
|
||||
public tags: NewTagEntity[];
|
||||
@ManyToOne(() => NewTagEntity, { nullable: true, onDelete: 'CASCADE' })
|
||||
public tag: NewTagEntity;
|
||||
|
||||
constructor(partial: Partial<SubspaceModelProductAllocationEntity>) {
|
||||
super();
|
||||
|
@ -1,10 +1,9 @@
|
||||
import { AbstractEntity } from '@app/common/modules/abstract/entities/abstract.entity';
|
||||
import { SubspaceEntity } from '@app/common/modules/space/entities/subspace/subspace.entity';
|
||||
import { Column, Entity, ManyToOne, OneToMany } from 'typeorm';
|
||||
import { SubSpaceModelDto } from '../../dtos';
|
||||
import { SpaceModelEntity } from '../space-model.entity';
|
||||
import { TagModel } from '../tag-model.entity';
|
||||
import { SubspaceModelProductAllocationEntity } from './subspace-model-product-allocation.entity';
|
||||
import { SubspaceEntity } from '@app/common/modules/space/entities/subspace/subspace.entity';
|
||||
|
||||
@Entity({ name: 'subspace-model' })
|
||||
export class SubspaceModelEntity extends AbstractEntity<SubSpaceModelDto> {
|
||||
@ -41,9 +40,6 @@ export class SubspaceModelEntity extends AbstractEntity<SubSpaceModelDto> {
|
||||
})
|
||||
public disabled: boolean;
|
||||
|
||||
@OneToMany(() => TagModel, (tag) => tag.subspaceModel)
|
||||
tags: TagModel[];
|
||||
|
||||
@OneToMany(
|
||||
() => SubspaceModelProductAllocationEntity,
|
||||
(allocation) => allocation.subspaceModel,
|
||||
|
@ -1,38 +0,0 @@
|
||||
import { Column, Entity, JoinColumn, ManyToOne, OneToMany } from 'typeorm';
|
||||
import { AbstractEntity } from '../../abstract/entities/abstract.entity';
|
||||
import { TagModelDto } from '../dtos/tag-model.dto';
|
||||
import { SpaceModelEntity } from './space-model.entity';
|
||||
import { SubspaceModelEntity } from './subspace-model';
|
||||
import { ProductEntity } from '../../product/entities';
|
||||
import { TagEntity } from '../../space/entities/tag.entity';
|
||||
|
||||
@Entity({ name: 'tag_model' })
|
||||
export class TagModel extends AbstractEntity<TagModelDto> {
|
||||
@Column({ type: 'varchar', length: 255 })
|
||||
tag: string;
|
||||
|
||||
@ManyToOne(() => ProductEntity, (product) => product.tagModels, {
|
||||
nullable: false,
|
||||
})
|
||||
@JoinColumn({ name: 'product_id' })
|
||||
product: ProductEntity;
|
||||
|
||||
@ManyToOne(() => SpaceModelEntity, (space) => space.tags, { nullable: true })
|
||||
@JoinColumn({ name: 'space_model_id' })
|
||||
spaceModel: SpaceModelEntity;
|
||||
|
||||
@ManyToOne(() => SubspaceModelEntity, (subspace) => subspace.tags, {
|
||||
nullable: true,
|
||||
})
|
||||
@JoinColumn({ name: 'subspace_model_id' })
|
||||
subspaceModel: SubspaceModelEntity;
|
||||
|
||||
@Column({
|
||||
nullable: false,
|
||||
default: false,
|
||||
})
|
||||
public disabled: boolean;
|
||||
|
||||
@OneToMany(() => TagEntity, (tag) => tag.model)
|
||||
tags: TagEntity[];
|
||||
}
|
@ -1,11 +1,10 @@
|
||||
import { DataSource, Repository } from 'typeorm';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { DataSource, Repository } from 'typeorm';
|
||||
import {
|
||||
SpaceModelEntity,
|
||||
SpaceModelProductAllocationEntity,
|
||||
SubspaceModelEntity,
|
||||
SubspaceModelProductAllocationEntity,
|
||||
TagModel,
|
||||
} from '../entities';
|
||||
|
||||
@Injectable()
|
||||
@ -21,13 +20,6 @@ export class SubspaceModelRepository extends Repository<SubspaceModelEntity> {
|
||||
}
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class TagModelRepository extends Repository<TagModel> {
|
||||
constructor(private dataSource: DataSource) {
|
||||
super(TagModel, dataSource.createEntityManager());
|
||||
}
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class SpaceModelProductAllocationRepoitory extends Repository<SpaceModelProductAllocationEntity> {
|
||||
constructor(private dataSource: DataSource) {
|
||||
|
@ -1,13 +1,11 @@
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { SpaceModelEntity, SubspaceModelEntity, TagModel } from './entities';
|
||||
import { Module } from '@nestjs/common';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { SpaceModelEntity, SubspaceModelEntity } from './entities';
|
||||
|
||||
@Module({
|
||||
providers: [],
|
||||
exports: [],
|
||||
controllers: [],
|
||||
imports: [
|
||||
TypeOrmModule.forFeature([SpaceModelEntity, SubspaceModelEntity, TagModel]),
|
||||
],
|
||||
imports: [TypeOrmModule.forFeature([SpaceModelEntity, SubspaceModelEntity])],
|
||||
})
|
||||
export class SpaceModelRepositoryModule {}
|
||||
|
@ -1,32 +1,3 @@
|
||||
import { Column, Entity, JoinColumn, ManyToOne } from 'typeorm';
|
||||
import { AbstractEntity } from '../../abstract/entities/abstract.entity';
|
||||
import { SpaceEntity } from './space.entity';
|
||||
import { Direction } from '@app/common/constants/direction.enum';
|
||||
|
||||
@Entity({ name: 'space-link' })
|
||||
export class SpaceLinkEntity extends AbstractEntity {
|
||||
@ManyToOne(() => SpaceEntity, { nullable: false, onDelete: 'CASCADE' })
|
||||
@JoinColumn({ name: 'start_space_id' })
|
||||
public startSpace: SpaceEntity;
|
||||
|
||||
@ManyToOne(() => SpaceEntity, { nullable: false, onDelete: 'CASCADE' })
|
||||
@JoinColumn({ name: 'end_space_id' })
|
||||
public endSpace: SpaceEntity;
|
||||
|
||||
@Column({
|
||||
nullable: false,
|
||||
default: false,
|
||||
})
|
||||
public disabled: boolean;
|
||||
|
||||
@Column({
|
||||
nullable: false,
|
||||
enum: Object.values(Direction),
|
||||
})
|
||||
direction: string;
|
||||
|
||||
constructor(partial: Partial<SpaceLinkEntity>) {
|
||||
super();
|
||||
Object.assign(this, partial);
|
||||
}
|
||||
}
|
||||
export class SpaceLinkEntity extends AbstractEntity {}
|
||||
|
@ -1,12 +1,13 @@
|
||||
import { Entity, Column, ManyToOne, ManyToMany, JoinTable } from 'typeorm';
|
||||
import { SpaceEntity } from './space.entity';
|
||||
import { SpaceModelProductAllocationEntity } from '../../space-model/entities/space-model-product-allocation.entity';
|
||||
import { ProductEntity } from '../../product/entities/product.entity';
|
||||
import { NewTagEntity } from '../../tag/entities/tag.entity';
|
||||
import { Column, Entity, ManyToOne, Unique } from 'typeorm';
|
||||
import { AbstractEntity } from '../../abstract/entities/abstract.entity';
|
||||
import { ProductEntity } from '../../product/entities/product.entity';
|
||||
import { SpaceModelProductAllocationEntity } from '../../space-model/entities/space-model-product-allocation.entity';
|
||||
import { NewTagEntity } from '../../tag/entities/tag.entity';
|
||||
import { SpaceProductAllocationDto } from '../dtos/space-product-allocation.dto';
|
||||
import { SpaceEntity } from './space.entity';
|
||||
|
||||
@Entity({ name: 'space_product_allocation' })
|
||||
@Unique(['space', 'product', 'tag'], {})
|
||||
export class SpaceProductAllocationEntity extends AbstractEntity<SpaceProductAllocationDto> {
|
||||
@Column({
|
||||
type: 'uuid',
|
||||
@ -30,9 +31,8 @@ export class SpaceProductAllocationEntity extends AbstractEntity<SpaceProductAll
|
||||
@ManyToOne(() => ProductEntity, { nullable: false, onDelete: 'CASCADE' })
|
||||
public product: ProductEntity;
|
||||
|
||||
@ManyToMany(() => NewTagEntity)
|
||||
@JoinTable({ name: 'space_product_tags' })
|
||||
public tags: NewTagEntity[];
|
||||
@ManyToOne(() => NewTagEntity, { nullable: true, onDelete: 'CASCADE' })
|
||||
public tag: NewTagEntity;
|
||||
|
||||
constructor(partial: Partial<SpaceProductAllocationEntity>) {
|
||||
super();
|
||||
|
@ -1,14 +1,15 @@
|
||||
import { Column, Entity, JoinColumn, ManyToOne, OneToMany } from 'typeorm';
|
||||
import { SpaceDto } from '../dtos';
|
||||
import { AbstractEntity } from '../../abstract/entities/abstract.entity';
|
||||
import { UserSpaceEntity } from '../../user/entities';
|
||||
import { DeviceEntity } from '../../device/entities';
|
||||
import { AqiSpaceDailyPollutantStatsEntity } from '../../aqi/entities';
|
||||
import { CommunityEntity } from '../../community/entities';
|
||||
import { SpaceLinkEntity } from './space-link.entity';
|
||||
import { DeviceEntity } from '../../device/entities';
|
||||
import { InviteUserSpaceEntity } from '../../Invite-user/entities';
|
||||
import { SpaceDailyOccupancyDurationEntity } from '../../occupancy/entities';
|
||||
import { PresenceSensorDailySpaceEntity } from '../../presence-sensor/entities';
|
||||
import { SceneEntity } from '../../scene/entities';
|
||||
import { SpaceModelEntity } from '../../space-model';
|
||||
import { InviteUserSpaceEntity } from '../../Invite-user/entities';
|
||||
import { TagEntity } from './tag.entity';
|
||||
import { UserSpaceEntity } from '../../user/entities';
|
||||
import { SpaceDto } from '../dtos';
|
||||
import { SpaceProductAllocationEntity } from './space-product-allocation.entity';
|
||||
import { SubspaceEntity } from './subspace/subspace.entity';
|
||||
|
||||
@ -73,16 +74,6 @@ export class SpaceEntity extends AbstractEntity<SpaceDto> {
|
||||
)
|
||||
devices: DeviceEntity[];
|
||||
|
||||
@OneToMany(() => SpaceLinkEntity, (connection) => connection.startSpace, {
|
||||
nullable: true,
|
||||
})
|
||||
public outgoingConnections: SpaceLinkEntity[];
|
||||
|
||||
@OneToMany(() => SpaceLinkEntity, (connection) => connection.endSpace, {
|
||||
nullable: true,
|
||||
})
|
||||
public incomingConnections: SpaceLinkEntity[];
|
||||
|
||||
@Column({
|
||||
nullable: true,
|
||||
type: 'text',
|
||||
@ -103,9 +94,6 @@ export class SpaceEntity extends AbstractEntity<SpaceDto> {
|
||||
)
|
||||
invitedUsers: InviteUserSpaceEntity[];
|
||||
|
||||
@OneToMany(() => TagEntity, (tag) => tag.space)
|
||||
tags: TagEntity[];
|
||||
|
||||
@OneToMany(
|
||||
() => SpaceProductAllocationEntity,
|
||||
(allocation) => allocation.space,
|
||||
@ -115,6 +103,18 @@ export class SpaceEntity extends AbstractEntity<SpaceDto> {
|
||||
)
|
||||
public productAllocations: SpaceProductAllocationEntity[];
|
||||
|
||||
@OneToMany(() => PresenceSensorDailySpaceEntity, (sensor) => sensor.space)
|
||||
presenceSensorDaily: PresenceSensorDailySpaceEntity[];
|
||||
|
||||
@OneToMany(() => AqiSpaceDailyPollutantStatsEntity, (aqi) => aqi.space)
|
||||
aqiSensorDaily: AqiSpaceDailyPollutantStatsEntity[];
|
||||
|
||||
@OneToMany(
|
||||
() => SpaceDailyOccupancyDurationEntity,
|
||||
(occupancy) => occupancy.space,
|
||||
)
|
||||
occupancyDaily: SpaceDailyOccupancyDurationEntity[];
|
||||
|
||||
constructor(partial: Partial<SpaceEntity>) {
|
||||
super();
|
||||
Object.assign(this, partial);
|
||||
|
@ -1,20 +1,13 @@
|
||||
import {
|
||||
Entity,
|
||||
Column,
|
||||
ManyToOne,
|
||||
ManyToMany,
|
||||
JoinTable,
|
||||
Unique,
|
||||
} from 'typeorm';
|
||||
import { SubspaceEntity } from './subspace.entity';
|
||||
import { AbstractEntity } from '@app/common/modules/abstract/entities/abstract.entity';
|
||||
import { ProductEntity } from '@app/common/modules/product/entities';
|
||||
import { SubspaceModelProductAllocationEntity } from '@app/common/modules/space-model';
|
||||
import { NewTagEntity } from '@app/common/modules/tag/entities/tag.entity';
|
||||
import { AbstractEntity } from '@app/common/modules/abstract/entities/abstract.entity';
|
||||
import { Column, Entity, ManyToOne, Unique } from 'typeorm';
|
||||
import { SubspaceProductAllocationDto } from '../../dtos/subspace-product-allocation.dto';
|
||||
import { SubspaceEntity } from './subspace.entity';
|
||||
|
||||
@Entity({ name: 'subspace_product_allocation' })
|
||||
@Unique(['subspace', 'product'])
|
||||
@Unique(['subspace', 'product', 'tag'])
|
||||
export class SubspaceProductAllocationEntity extends AbstractEntity<SubspaceProductAllocationDto> {
|
||||
@Column({
|
||||
type: 'uuid',
|
||||
@ -38,9 +31,8 @@ export class SubspaceProductAllocationEntity extends AbstractEntity<SubspaceProd
|
||||
@ManyToOne(() => ProductEntity, { nullable: false, onDelete: 'CASCADE' })
|
||||
public product: ProductEntity;
|
||||
|
||||
@ManyToMany(() => NewTagEntity)
|
||||
@JoinTable({ name: 'subspace_product_tags' })
|
||||
public tags: NewTagEntity[];
|
||||
@ManyToOne(() => NewTagEntity, { nullable: true, onDelete: 'CASCADE' })
|
||||
public tag: NewTagEntity;
|
||||
|
||||
constructor(partial: Partial<SubspaceProductAllocationEntity>) {
|
||||
super();
|
||||
|
@ -4,7 +4,6 @@ import { SubspaceModelEntity } from '@app/common/modules/space-model';
|
||||
import { Column, Entity, JoinColumn, ManyToOne, OneToMany } from 'typeorm';
|
||||
import { SubspaceDto } from '../../dtos';
|
||||
import { SpaceEntity } from '../space.entity';
|
||||
import { TagEntity } from '../tag.entity';
|
||||
import { SubspaceProductAllocationEntity } from './subspace-product-allocation.entity';
|
||||
|
||||
@Entity({ name: 'subspace' })
|
||||
@ -38,14 +37,11 @@ export class SubspaceEntity extends AbstractEntity<SubspaceDto> {
|
||||
})
|
||||
devices: DeviceEntity[];
|
||||
|
||||
@ManyToOne(() => SubspaceModelEntity, (subspace) => subspace.subspaceModel, {
|
||||
@ManyToOne(() => SubspaceModelEntity, (model) => model.subspace, {
|
||||
nullable: true,
|
||||
})
|
||||
subSpaceModel?: SubspaceModelEntity;
|
||||
|
||||
@OneToMany(() => TagEntity, (tag) => tag.subspace)
|
||||
tags: TagEntity[];
|
||||
|
||||
@OneToMany(
|
||||
() => SubspaceProductAllocationEntity,
|
||||
(allocation) => allocation.subspace,
|
||||
|
@ -1,45 +0,0 @@
|
||||
import { Entity, Column, ManyToOne, JoinColumn, OneToOne } from 'typeorm';
|
||||
import { AbstractEntity } from '../../abstract/entities/abstract.entity';
|
||||
import { ProductEntity } from '../../product/entities';
|
||||
import { TagDto } from '../dtos';
|
||||
import { TagModel } from '../../space-model/entities/tag-model.entity';
|
||||
import { SpaceEntity } from './space.entity';
|
||||
import { DeviceEntity } from '../../device/entities';
|
||||
import { SubspaceEntity } from './subspace/subspace.entity';
|
||||
|
||||
@Entity({ name: 'tag' })
|
||||
export class TagEntity extends AbstractEntity<TagDto> {
|
||||
@Column({ type: 'varchar', length: 255, nullable: true })
|
||||
tag: string;
|
||||
|
||||
@ManyToOne(() => TagModel, (model) => model.tags, {
|
||||
nullable: true,
|
||||
})
|
||||
model: TagModel;
|
||||
|
||||
@ManyToOne(() => ProductEntity, (product) => product.tags, {
|
||||
nullable: false,
|
||||
})
|
||||
product: ProductEntity;
|
||||
|
||||
@ManyToOne(() => SpaceEntity, (space) => space.tags, { nullable: true })
|
||||
space: SpaceEntity;
|
||||
|
||||
@ManyToOne(() => SubspaceEntity, (subspace) => subspace.tags, {
|
||||
nullable: true,
|
||||
})
|
||||
@JoinColumn({ name: 'subspace_id' })
|
||||
subspace: SubspaceEntity;
|
||||
|
||||
@Column({
|
||||
nullable: false,
|
||||
default: false,
|
||||
})
|
||||
public disabled: boolean;
|
||||
|
||||
@OneToOne(() => DeviceEntity, (device) => device.tag, {
|
||||
nullable: true,
|
||||
})
|
||||
@JoinColumn({ name: 'device_id' })
|
||||
device: DeviceEntity;
|
||||
}
|
@ -1,9 +1,8 @@
|
||||
import { DataSource, Repository } from 'typeorm';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { DataSource, Repository } from 'typeorm';
|
||||
import { InviteSpaceEntity } from '../entities/invite-space.entity';
|
||||
import { SpaceLinkEntity } from '../entities/space-link.entity';
|
||||
import { SpaceProductAllocationEntity } from '../entities/space-product-allocation.entity';
|
||||
import { SpaceEntity } from '../entities/space.entity';
|
||||
import { TagEntity } from '../entities/tag.entity';
|
||||
|
||||
@Injectable()
|
||||
export class SpaceRepository extends Repository<SpaceEntity> {
|
||||
@ -13,18 +12,7 @@ export class SpaceRepository extends Repository<SpaceEntity> {
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class SpaceLinkRepository extends Repository<SpaceLinkEntity> {
|
||||
constructor(private dataSource: DataSource) {
|
||||
super(SpaceLinkEntity, dataSource.createEntityManager());
|
||||
}
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class TagRepository extends Repository<TagEntity> {
|
||||
constructor(private dataSource: DataSource) {
|
||||
super(TagEntity, dataSource.createEntityManager());
|
||||
}
|
||||
}
|
||||
export class SpaceLinkRepository {}
|
||||
|
||||
@Injectable()
|
||||
export class InviteSpaceRepository extends Repository<InviteSpaceEntity> {
|
||||
@ -32,3 +20,9 @@ export class InviteSpaceRepository extends Repository<InviteSpaceEntity> {
|
||||
super(InviteSpaceEntity, dataSource.createEntityManager());
|
||||
}
|
||||
}
|
||||
@Injectable()
|
||||
export class SpaceProductAllocationRepository extends Repository<SpaceProductAllocationEntity> {
|
||||
constructor(private dataSource: DataSource) {
|
||||
super(SpaceProductAllocationEntity, dataSource.createEntityManager());
|
||||
}
|
||||
}
|
||||
|
@ -1,6 +1,7 @@
|
||||
import { DataSource, Repository } from 'typeorm';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { SubspaceEntity } from '../entities/subspace/subspace.entity';
|
||||
import { SubspaceProductAllocationEntity } from '../entities/subspace/subspace-product-allocation.entity';
|
||||
|
||||
@Injectable()
|
||||
export class SubspaceRepository extends Repository<SubspaceEntity> {
|
||||
@ -8,3 +9,9 @@ export class SubspaceRepository extends Repository<SubspaceEntity> {
|
||||
super(SubspaceEntity, dataSource.createEntityManager());
|
||||
}
|
||||
}
|
||||
@Injectable()
|
||||
export class SubspaceProductAllocationRepository extends Repository<SubspaceProductAllocationEntity> {
|
||||
constructor(private dataSource: DataSource) {
|
||||
super(SubspaceProductAllocationEntity, dataSource.createEntityManager());
|
||||
}
|
||||
}
|
||||
|
@ -6,7 +6,6 @@ import { SpaceProductAllocationEntity } from './entities/space-product-allocatio
|
||||
import { SpaceEntity } from './entities/space.entity';
|
||||
import { SubspaceProductAllocationEntity } from './entities/subspace/subspace-product-allocation.entity';
|
||||
import { SubspaceEntity } from './entities/subspace/subspace.entity';
|
||||
import { TagEntity } from './entities/tag.entity';
|
||||
|
||||
@Module({
|
||||
providers: [],
|
||||
@ -16,7 +15,6 @@ import { TagEntity } from './entities/tag.entity';
|
||||
TypeOrmModule.forFeature([
|
||||
SpaceEntity,
|
||||
SubspaceEntity,
|
||||
TagEntity,
|
||||
InviteSpaceEntity,
|
||||
SpaceProductAllocationEntity,
|
||||
SubspaceProductAllocationEntity,
|
||||
|
@ -1,18 +1,10 @@
|
||||
import {
|
||||
Entity,
|
||||
Column,
|
||||
ManyToOne,
|
||||
Unique,
|
||||
ManyToMany,
|
||||
OneToMany,
|
||||
} from 'typeorm';
|
||||
import { ProductEntity } from '../../product/entities';
|
||||
import { ProjectEntity } from '../../project/entities';
|
||||
import { Column, Entity, ManyToOne, OneToMany, Unique } from 'typeorm';
|
||||
import { AbstractEntity } from '../../abstract/entities/abstract.entity';
|
||||
import { NewTagDto } from '../dtos/tag.dto';
|
||||
import { DeviceEntity } from '../../device/entities/device.entity';
|
||||
import { ProjectEntity } from '../../project/entities';
|
||||
import { SpaceModelProductAllocationEntity } from '../../space-model/entities/space-model-product-allocation.entity';
|
||||
import { SubspaceModelProductAllocationEntity } from '../../space-model/entities/subspace-model/subspace-model-product-allocation.entity';
|
||||
import { DeviceEntity } from '../../device/entities/device.entity';
|
||||
import { NewTagDto } from '../dtos/tag.dto';
|
||||
|
||||
@Entity({ name: 'new_tag' })
|
||||
@Unique(['name', 'project'])
|
||||
@ -31,27 +23,21 @@ export class NewTagEntity extends AbstractEntity<NewTagDto> {
|
||||
})
|
||||
name: string;
|
||||
|
||||
@ManyToOne(() => ProductEntity, (product) => product.newTags, {
|
||||
nullable: false,
|
||||
onDelete: 'CASCADE',
|
||||
})
|
||||
public product: ProductEntity;
|
||||
|
||||
@ManyToOne(() => ProjectEntity, (project) => project.tags, {
|
||||
nullable: false,
|
||||
onDelete: 'CASCADE',
|
||||
})
|
||||
public project: ProjectEntity;
|
||||
|
||||
@ManyToMany(
|
||||
@OneToMany(
|
||||
() => SpaceModelProductAllocationEntity,
|
||||
(allocation) => allocation.tags,
|
||||
(allocation) => allocation.tag,
|
||||
)
|
||||
public spaceModelAllocations: SpaceModelProductAllocationEntity[];
|
||||
|
||||
@ManyToMany(
|
||||
@OneToMany(
|
||||
() => SubspaceModelProductAllocationEntity,
|
||||
(allocation) => allocation.tags,
|
||||
(allocation) => allocation.tag,
|
||||
)
|
||||
public subspaceModelAllocations: SubspaceModelProductAllocationEntity[];
|
||||
|
||||
|
@ -3,7 +3,7 @@ import { NewTagEntity } from '../entities';
|
||||
import { DataSource, Repository } from 'typeorm';
|
||||
|
||||
@Injectable()
|
||||
export class NewTagRepository extends Repository<NewTagRepository> {
|
||||
export class NewTagRepository extends Repository<NewTagEntity> {
|
||||
constructor(private dataSource: DataSource) {
|
||||
super(NewTagEntity, dataSource.createEntityManager());
|
||||
}
|
||||
|
@ -16,7 +16,6 @@ import {
|
||||
} from '../dtos';
|
||||
import { AbstractEntity } from '../../abstract/entities/abstract.entity';
|
||||
import {
|
||||
DeviceEntity,
|
||||
DeviceNotificationEntity,
|
||||
DeviceUserPermissionEntity,
|
||||
} from '../../device/entities';
|
||||
@ -29,6 +28,7 @@ import { VisitorPasswordEntity } from '../../visitor-password/entities';
|
||||
import { InviteUserEntity } from '../../Invite-user/entities';
|
||||
import { ProjectEntity } from '../../project/entities';
|
||||
import { SpaceEntity } from '../../space/entities/space.entity';
|
||||
import { ClientEntity } from '../../client/entities';
|
||||
|
||||
@Entity({ name: 'user' })
|
||||
export class UserEntity extends AbstractEntity<UserDto> {
|
||||
@ -97,9 +97,6 @@ export class UserEntity extends AbstractEntity<UserDto> {
|
||||
@OneToMany(() => UserSpaceEntity, (userSpace) => userSpace.user)
|
||||
userSpaces: UserSpaceEntity[];
|
||||
|
||||
@OneToMany(() => DeviceEntity, (userDevice) => userDevice.user)
|
||||
userDevice: DeviceEntity[];
|
||||
|
||||
@OneToMany(
|
||||
() => UserNotificationEntity,
|
||||
(userNotification) => userNotification.user,
|
||||
@ -143,6 +140,13 @@ export class UserEntity extends AbstractEntity<UserDto> {
|
||||
})
|
||||
@JoinColumn({ name: 'project_uuid' })
|
||||
public project: ProjectEntity;
|
||||
|
||||
@ManyToOne(() => ClientEntity, (client) => client.users, {
|
||||
nullable: true,
|
||||
})
|
||||
@JoinColumn({ name: 'client_uuid' })
|
||||
public client: ClientEntity;
|
||||
|
||||
constructor(partial: Partial<UserEntity>) {
|
||||
super();
|
||||
Object.assign(this, partial);
|
||||
|
@ -0,0 +1,39 @@
|
||||
WITH params AS (
|
||||
SELECT
|
||||
$1::uuid AS space_uuid,
|
||||
TO_DATE(NULLIF($2, ''), 'YYYY-MM') AS event_month
|
||||
)
|
||||
|
||||
SELECT
|
||||
sdp.space_uuid,
|
||||
sdp.event_date,
|
||||
sdp.good_aqi_percentage, sdp.moderate_aqi_percentage, sdp.unhealthy_sensitive_aqi_percentage, sdp.unhealthy_aqi_percentage,
|
||||
sdp.very_unhealthy_aqi_percentage, sdp.hazardous_aqi_percentage,
|
||||
sdp.daily_avg_aqi, sdp.daily_max_aqi, sdp.daily_min_aqi,
|
||||
|
||||
sdp.good_pm25_percentage, sdp.moderate_pm25_percentage, sdp.unhealthy_sensitive_pm25_percentage, sdp.unhealthy_pm25_percentage,
|
||||
sdp.very_unhealthy_pm25_percentage, sdp.hazardous_pm25_percentage,
|
||||
sdp.daily_avg_pm25, sdp.daily_max_pm25, sdp.daily_min_pm25,
|
||||
|
||||
sdp.good_pm10_percentage, sdp.moderate_pm10_percentage, sdp.unhealthy_sensitive_pm10_percentage, sdp.unhealthy_pm10_percentage,
|
||||
sdp.very_unhealthy_pm10_percentage, sdp.hazardous_pm10_percentage,
|
||||
sdp.daily_avg_pm10, sdp.daily_max_pm10, sdp.daily_min_pm10,
|
||||
|
||||
sdp.good_voc_percentage, sdp.moderate_voc_percentage, sdp.unhealthy_sensitive_voc_percentage, sdp.unhealthy_voc_percentage,
|
||||
sdp.very_unhealthy_voc_percentage, sdp.hazardous_voc_percentage,
|
||||
sdp.daily_avg_voc, sdp.daily_max_voc, sdp.daily_min_voc,
|
||||
|
||||
sdp.good_co2_percentage, sdp.moderate_co2_percentage, sdp.unhealthy_sensitive_co2_percentage, sdp.unhealthy_co2_percentage,
|
||||
sdp.very_unhealthy_co2_percentage, sdp.hazardous_co2_percentage,
|
||||
sdp.daily_avg_co2, sdp.daily_max_co2, sdp.daily_min_co2,
|
||||
|
||||
sdp.good_ch2o_percentage, sdp.moderate_ch2o_percentage, sdp.unhealthy_sensitive_ch2o_percentage, sdp.unhealthy_ch2o_percentage,
|
||||
sdp.very_unhealthy_ch2o_percentage, sdp.hazardous_ch2o_percentage,
|
||||
sdp.daily_avg_ch2o, sdp.daily_max_ch2o, sdp.daily_min_ch2o
|
||||
|
||||
FROM public."space-daily-pollutant-stats" AS sdp
|
||||
CROSS JOIN params p
|
||||
WHERE
|
||||
(p.space_uuid IS NULL OR sdp.space_uuid = p.space_uuid)
|
||||
AND (p.event_month IS NULL OR TO_CHAR(sdp.event_date, 'YYYY-MM') = TO_CHAR(p.event_month, 'YYYY-MM'))
|
||||
ORDER BY sdp.space_uuid, sdp.event_date;
|
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user