mirror of
https://github.com/SyncrowIOT/backend.git
synced 2026-03-10 22:31:44 +00:00
Compare commits
594 Commits
a99b759882
...
task/get-u
| Author | SHA1 | Date | |
|---|---|---|---|
| 97da07f80a | |||
| 331c8dffdc | |||
| 2aa6a40af7 | |||
| 7ae826eb71 | |||
| beed6fcfb7 | |||
| 015470b5ea | |||
| 36640b104b | |||
| d4af9eaccc | |||
| f447cfa065 | |||
| d065742d87 | |||
| 9d952d2fb0 | |||
| c0849c2252 | |||
| 9254db08f9 | |||
| b9c4308d1c | |||
| db95cc0dab | |||
| 87c380ab6f | |||
| 212d0d1974 | |||
| a060f92208 | |||
| 6d529ee0ae | |||
| 85687e7950 | |||
| 7e2c3136cf | |||
| 61348aa351 | |||
| dea942f11e | |||
| d62e620828 | |||
| f0556813ac | |||
| 6d2252a403 | |||
| 8d265c9105 | |||
| a4095c837b | |||
| 65d4a56135 | |||
| fffa27b6ee | |||
| 12579fcd6e | |||
| 036c8bea17 | |||
| e5970c02c1 | |||
| 2c3b985594 | |||
| a9cb1b6704 | |||
| a17a271213 | |||
| 712b7443ac | |||
| 945328c0ce | |||
| 009deaf403 | |||
| 3cfed2b452 | |||
| 09322c5b80 | |||
| 74d3620d0e | |||
| 83be80d9f6 | |||
| 2589e391ed | |||
| 5cf45c30f4 | |||
| 0bb178ed10 | |||
| 9971fb953d | |||
| 7a07f39f16 | |||
| 18b21d697c | |||
| 66391bafd8 | |||
| 25599b9fe2 | |||
| 807c5b7dd3 | |||
| 60bc03cf79 | |||
| a9eaf44d31 | |||
| d232c06ebe | |||
| 5c916ed445 | |||
| b2fb378e52 | |||
| c5f8f96977 | |||
| 8f9b15f49f | |||
| 0b9eef276e | |||
| b3f8b92826 | |||
| b9da00aaa6 | |||
| 5bf44a18e1 | |||
| 2b2772e4ca | |||
| 13c0f87fc6 | |||
| c9d794d988 | |||
| 5d4e5ca87e | |||
| f4e748d735 | |||
| f4f7999ae0 | |||
| 82c82d521c | |||
| c7a4ff1194 | |||
| 90ab291d83 | |||
| 8a4633b158 | |||
| f80d097ff8 | |||
| 04bd156df1 | |||
| 731819aeaa | |||
| 68d2d3b53d | |||
| 3fcfe2d92f | |||
| c0a069b460 | |||
| 5381a949bc | |||
| 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 | |||
| d3d84da5e3 | |||
| 110ed4157a | |||
| aa9e90bf08 | |||
| c5dd5e28fd | |||
| 603e74af09 | |||
| 6973e8b195 | |||
| 0e36f32ed6 | |||
| 705ceeba29 | |||
| 92d102d08f | |||
| 7dc28d0cb3 | |||
| d9ad431a23 | |||
| 4bf43dab2b | |||
| a37d5bb299 | |||
| 49cc762962 | |||
| a94d4610ed | |||
| 274cdf741f | |||
| df59e9a4a3 | |||
| 8c34c68ba6 | |||
| 689a38ee0c | |||
| 332b2f5851 | |||
| 8d44b66dd3 | |||
| 7520b8d9c7 | |||
| 72753b6dfb | |||
| 568eef8119 | |||
| 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 | |||
| a40560a0b1 | |||
| 7d6f1bb944 | |||
| 434316fe51 | |||
| 287bb4c5e4 | |||
| 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 | |||
| 85602fa952 | |||
| c085514d27 | |||
| fa3cb578df | |||
| 25a4d3e91b | |||
| d3a560d18f | |||
| ab99bb5afc | |||
| 67911d5ff1 | |||
| 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 | |||
| 13e3f3e213 | |||
| 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 | |||
| 327d678656 | |||
| 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 | |||
| dd5447fc5f | |||
| 8b3232b2f4 | |||
| 7df5b9ab08 | |||
| 06b4407b85 | |||
| 1aea072692 | |||
| c6f314e5c4 | |||
| 1d6f3b8e65 | |||
| ef39e9cfa7 | |||
| 8cbbb3a8ba | |||
| 537f20f8de | |||
| 80659f7a48 | |||
| 8456eea5dc | |||
| 1ce2f3c3cc | |||
| 481ed5e7f9 | |||
| 67a78dbdfd | |||
| 5c47a3195f | |||
| 5b1c14300e | |||
| 1403a670e3 | |||
| 4a5f2f3b9f | |||
| b6fa37b1a3 | |||
| 5204cd5504 | |||
| a57f4e1c65 | |||
| 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 | |||
| b2d52c7622 | |||
| 1140709e80 | |||
| a0790f0b48 | |||
| c9cbb2e085 | |||
| c52d0981db | |||
| 6550ed68f6 | |||
| c2a6012063 | |||
| 4adb1e683d | |||
| 8aa3de5fdc | |||
| bc1ee9a53b | |||
| 19356c3833 | |||
| 8737ee992b | |||
| e98a99be73 | |||
| 93efa15f3c | |||
| c305e39ff2 | |||
| 61e4d220dc | |||
| cd4bbe1788 | |||
| 6301da0665 | |||
| d770a0c732 | |||
| 030e6ae902 | |||
| 9d8287b82b | |||
| d741a6c1f3 | |||
| 6d55704dd4 | |||
| c7ffba7290 | |||
| 0059562319 | |||
| 7ddd75041e | |||
| 07d31bb8bd | |||
| 61a85789d1 | |||
| 565b0f72b7 | |||
| 19ef10aa87 | |||
| 733ccee88d | |||
| afec306681 | |||
| 6fbeef97df | |||
| 29d9909c8e | |||
| 2dcce3cce3 | |||
| 427a57501f | |||
| b59230d5d8 | |||
| e276d4651d | |||
| 9eb9b92be3 | |||
| b2b8d02400 | |||
| b793597711 | |||
| d8ad9e55ea |
@ -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': {
|
||||
|
||||
17
.github/pull_request_template.md
vendored
Normal file
17
.github/pull_request_template.md
vendored
Normal file
@ -0,0 +1,17 @@
|
||||
<!--
|
||||
Thanks for contributing!
|
||||
|
||||
Provide a description of your changes below and a general summary in the title.
|
||||
-->
|
||||
|
||||
## Jira Ticket
|
||||
|
||||
[SP-0000](https://syncrow.atlassian.net/browse/SP-0000)
|
||||
|
||||
## Description
|
||||
|
||||
<!--- Describe your changes in detail -->
|
||||
|
||||
## How to Test
|
||||
|
||||
<!--- Describe the created APIs / Logic -->
|
||||
46
.github/workflows/main_syncrow(staging).yml
vendored
46
.github/workflows/main_syncrow(staging).yml
vendored
@ -14,24 +14,24 @@ jobs:
|
||||
runs-on: 'ubuntu-latest'
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- uses: actions/checkout@v2
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@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: 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
|
||||
- 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:
|
||||
runs-on: ubuntu-latest
|
||||
@ -41,11 +41,11 @@ jobs:
|
||||
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 }}'
|
||||
- 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 }}'
|
||||
|
||||
73
.github/workflows/main_syncrow(stg).yml
vendored
Normal file
73
.github/workflows/main_syncrow(stg).yml
vendored
Normal file
@ -0,0 +1,73 @@
|
||||
# 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 Node.js app to Azure Web App - syncrow
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read #This is required for actions/checkout
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Set up Node.js version
|
||||
uses: actions/setup-node@v3
|
||||
with:
|
||||
node-version: '20.x'
|
||||
|
||||
- name: npm install, build, and test
|
||||
run: |
|
||||
npm install
|
||||
npm run build --if-present
|
||||
npm run test --if-present
|
||||
|
||||
- name: Zip artifact for deployment
|
||||
run: zip release.zip ./* -r
|
||||
|
||||
- name: Upload artifact for deployment job
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: node-app
|
||||
path: release.zip
|
||||
|
||||
deploy:
|
||||
runs-on: ubuntu-latest
|
||||
needs: build
|
||||
environment:
|
||||
name: 'stg'
|
||||
url: ${{ steps.deploy-to-webapp.outputs.webapp-url }}
|
||||
permissions:
|
||||
id-token: write #This is required for requesting the JWT
|
||||
contents: read #This is required for actions/checkout
|
||||
|
||||
steps:
|
||||
- name: Download artifact from build job
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: node-app
|
||||
|
||||
- name: Unzip artifact for deployment
|
||||
run: unzip release.zip
|
||||
|
||||
- name: Login to Azure
|
||||
uses: azure/login@v2
|
||||
with:
|
||||
client-id: ${{ secrets.AZUREAPPSERVICE_CLIENTID_515C8E782CFF431AB20448C85CA0FE58 }}
|
||||
tenant-id: ${{ secrets.AZUREAPPSERVICE_TENANTID_2AEFE5534424490387C08FAE41573CC2 }}
|
||||
subscription-id: ${{ secrets.AZUREAPPSERVICE_SUBSCRIPTIONID_00623C33023749FEA5F6BC36884F9C8A }}
|
||||
|
||||
- name: 'Deploy to Azure Web App'
|
||||
id: deploy-to-webapp
|
||||
uses: azure/webapps-deploy@v3
|
||||
with:
|
||||
app-name: 'syncrow'
|
||||
slot-name: 'stg'
|
||||
package: .
|
||||
64
.github/workflows/pr-description.yml
vendored
Normal file
64
.github/workflows/pr-description.yml
vendored
Normal file
@ -0,0 +1,64 @@
|
||||
name: 🤖 AI PR Description Commenter (100% Safe with jq)
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
types: [opened, edited]
|
||||
|
||||
jobs:
|
||||
generate-description:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- name: Checkout Repo
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Install GitHub CLI and jq
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install gh jq -y
|
||||
|
||||
- name: Fetch PR Commits
|
||||
id: fetch_commits
|
||||
run: |
|
||||
COMMITS=$(gh pr view ${{ github.event.pull_request.number }} --json commits --jq '.commits[].message' | sed 's/^/- /')
|
||||
echo "commits<<EOF" >> $GITHUB_ENV
|
||||
echo "$COMMITS" >> $GITHUB_ENV
|
||||
echo "EOF" >> $GITHUB_ENV
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GH_PERSONAL_TOKEN }}
|
||||
|
||||
- name: Generate PR Description with OpenAI (Safe JSON with jq)
|
||||
run: |
|
||||
REQUEST_BODY=$(jq -n \
|
||||
--arg model "gpt-4o" \
|
||||
--arg content "Given the following commit messages:\n\n${commits}\n\nGenerate a clear and professional pull request description." \
|
||||
'{
|
||||
model: $model,
|
||||
messages: [{ role: "user", content: $content }]
|
||||
}'
|
||||
)
|
||||
|
||||
RESPONSE=$(curl -s https://api.openai.com/v1/chat/completions \
|
||||
-H "Authorization: Bearer $OPENAI_API_KEY" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d "$REQUEST_BODY")
|
||||
|
||||
DESCRIPTION=$(echo "$RESPONSE" | jq -r '.choices[0].message.content')
|
||||
|
||||
echo "---------- OpenAI Raw Response ----------"
|
||||
echo "$RESPONSE"
|
||||
echo "---------- Extracted Description ----------"
|
||||
echo "$DESCRIPTION"
|
||||
|
||||
echo "description<<EOF" >> $GITHUB_ENV
|
||||
echo "$DESCRIPTION" >> $GITHUB_ENV
|
||||
echo "EOF" >> $GITHUB_ENV
|
||||
env:
|
||||
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
|
||||
commits: ${{ env.commits }}
|
||||
|
||||
- name: Post AI Generated Description as Comment
|
||||
run: |
|
||||
gh pr comment ${{ github.event.pull_request.number }} --body "${{ env.description }}"
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GH_PERSONAL_TOKEN }}
|
||||
3
.gitignore
vendored
3
.gitignore
vendored
@ -3,6 +3,9 @@
|
||||
/node_modules
|
||||
/build
|
||||
|
||||
#github
|
||||
/.github/workflows
|
||||
|
||||
# Logs
|
||||
logs
|
||||
*.log
|
||||
|
||||
@ -5,4 +5,5 @@ export class AuthInterface {
|
||||
sessionId: string;
|
||||
id: number;
|
||||
role?: object;
|
||||
project?: object;
|
||||
}
|
||||
|
||||
@ -1,18 +1,19 @@
|
||||
import { PlatformType } from '@app/common/constants/platform-type.enum';
|
||||
import { RoleType } from '@app/common/constants/role.type.enum';
|
||||
import { UserEntity } from '@app/common/modules/user/entities';
|
||||
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 {
|
||||
@ -32,24 +33,25 @@ export class AuthService {
|
||||
pass: string,
|
||||
regionUuid?: string,
|
||||
platform?: PlatformType,
|
||||
): Promise<any> {
|
||||
): Promise<Omit<UserEntity, 'password'>> {
|
||||
const user = await this.userRepository.findOne({
|
||||
where: {
|
||||
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');
|
||||
@ -69,29 +71,37 @@ export class AuthService {
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
const { password, ...result } = user;
|
||||
return result;
|
||||
// const { password, ...result } = user;
|
||||
delete user.password;
|
||||
return user;
|
||||
}
|
||||
|
||||
async createSession(data): Promise<UserSessionEntity> {
|
||||
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 +115,8 @@ export class AuthService {
|
||||
googleCode: user.googleCode,
|
||||
hasAcceptedWebAgreement: user.hasAcceptedWebAgreement,
|
||||
hasAcceptedAppAgreement: user.hasAcceptedAppAgreement,
|
||||
project: user?.project,
|
||||
bookingPoints: user?.bookingPoints,
|
||||
};
|
||||
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');
|
||||
|
||||
@ -1,12 +1,11 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { ConfigModule } from '@nestjs/config';
|
||||
import { ErrorMessageService } from 'src/error-message/error-message.service';
|
||||
import { AuthModule } from './auth/auth.module';
|
||||
import { CommonService } from './common.service';
|
||||
import config from './config';
|
||||
import { DatabaseModule } from './database/database.module';
|
||||
import { HelperModule } from './helper/helper.module';
|
||||
import { AuthModule } from './auth/auth.module';
|
||||
import { ConfigModule } from '@nestjs/config';
|
||||
import config from './config';
|
||||
import { EmailService } from './util/email.service';
|
||||
import { ErrorMessageService } from 'src/error-message/error-message.service';
|
||||
import { TuyaService } from './integrations/tuya/services/tuya.service';
|
||||
import { SceneDeviceRepository } from './modules/scene-device/repositories';
|
||||
import { SpaceRepository } from './modules/space';
|
||||
@ -15,6 +14,7 @@ import {
|
||||
SubspaceModelRepository,
|
||||
} from './modules/space-model';
|
||||
import { SubspaceRepository } from './modules/space/repositories/subspace.repository';
|
||||
import { EmailService } from './util/email/email.service';
|
||||
@Module({
|
||||
providers: [
|
||||
CommonService,
|
||||
|
||||
@ -10,6 +10,8 @@ export default registerAs(
|
||||
SMTP_USER: process.env.SMTP_USER,
|
||||
SMTP_SENDER: process.env.SMTP_SENDER,
|
||||
SMTP_PASSWORD: process.env.SMTP_PASSWORD,
|
||||
BATCH_EMAIL_API_URL: process.env.BATCH_EMAIL_API_URL,
|
||||
SEND_EMAIL_API_URL: process.env.SEND_EMAIL_API_URL,
|
||||
MAILTRAP_API_TOKEN: process.env.MAILTRAP_API_TOKEN,
|
||||
MAILTRAP_INVITATION_TEMPLATE_UUID:
|
||||
process.env.MAILTRAP_INVITATION_TEMPLATE_UUID,
|
||||
@ -19,5 +21,11 @@ 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,
|
||||
MAILTRAP_SEND_BOOKING_AVAILABILITY_UPDATE_TEMPLATE_UUID:
|
||||
process.env.MAILTRAP_SEND_BOOKING_AVAILABILITY_UPDATE_TEMPLATE_UUID,
|
||||
MAILTRAP_SEND_BOOKING_TIMING_UPDATE_TEMPLATE_UUID:
|
||||
process.env.MAILTRAP_SEND_BOOKING_TIMING_UPDATE_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 {
|
||||
@ -51,7 +69,47 @@ export class ControllerRoute {
|
||||
'Retrieve the list of all regions registered in Syncrow.';
|
||||
};
|
||||
};
|
||||
static BOOKABLE_SPACES = class {
|
||||
public static readonly ROUTE = 'bookable-spaces';
|
||||
static ACTIONS = class {
|
||||
public static readonly ADD_BOOKABLE_SPACES_SUMMARY =
|
||||
'Add new bookable spaces';
|
||||
|
||||
public static readonly ADD_BOOKABLE_SPACES_DESCRIPTION =
|
||||
'This endpoint allows you to add new bookable spaces by providing the required details.';
|
||||
|
||||
public static readonly GET_ALL_BOOKABLE_SPACES_SUMMARY =
|
||||
'Get all bookable spaces';
|
||||
|
||||
public static readonly GET_ALL_BOOKABLE_SPACES_DESCRIPTION =
|
||||
'This endpoint retrieves all bookable spaces.';
|
||||
|
||||
public static readonly UPDATE_BOOKABLE_SPACES_SUMMARY =
|
||||
'Update existing bookable spaces';
|
||||
|
||||
public static readonly UPDATE_BOOKABLE_SPACES_DESCRIPTION =
|
||||
'This endpoint allows you to update existing bookable spaces by providing the required details.';
|
||||
};
|
||||
};
|
||||
static BOOKING = class {
|
||||
public static readonly ROUTE = 'bookings';
|
||||
static ACTIONS = class {
|
||||
public static readonly ADD_BOOKING_SUMMARY = 'Add new booking';
|
||||
|
||||
public static readonly ADD_BOOKING_DESCRIPTION =
|
||||
'This endpoint allows you to add new booking by providing the required details.';
|
||||
|
||||
public static readonly GET_ALL_BOOKINGS_SUMMARY = 'Get all bookings';
|
||||
|
||||
public static readonly GET_ALL_BOOKINGS_DESCRIPTION =
|
||||
'This endpoint retrieves all bookings.';
|
||||
|
||||
public static readonly GET_MY_BOOKINGS_SUMMARY = 'Get my bookings';
|
||||
|
||||
public static readonly GET_MY_BOOKINGS_DESCRIPTION =
|
||||
'This endpoint retrieves all bookings for the authenticated user.';
|
||||
};
|
||||
};
|
||||
static COMMUNITY = class {
|
||||
public static readonly ROUTE = '/projects/:projectUuid/communities';
|
||||
static ACTIONS = class {
|
||||
@ -130,6 +188,11 @@ export class ControllerRoute {
|
||||
static SCENE = class {
|
||||
public static readonly ROUTE = 'scene';
|
||||
static ACTIONS = class {
|
||||
public static readonly GET_TAP_TO_RUN_SCENES_SUMMARY =
|
||||
'Get Tap-to-Run Scenes by spaces';
|
||||
public static readonly GET_TAP_TO_RUN_SCENES_DESCRIPTION =
|
||||
'Gets Tap-to-Run scenes by spaces';
|
||||
|
||||
public static readonly CREATE_TAP_TO_RUN_SCENE_SUMMARY =
|
||||
'Create a Tap-to-Run Scene';
|
||||
public static readonly CREATE_TAP_TO_RUN_SCENE_DESCRIPTION =
|
||||
@ -165,6 +228,10 @@ export class ControllerRoute {
|
||||
public static readonly CREATE_SPACE_DESCRIPTION =
|
||||
'This endpoint allows you to create a space in a specified community. Optionally, you can specify a parent space to nest the new space under it.';
|
||||
|
||||
public static readonly DUPLICATE_SPACE_SUMMARY = 'Duplicate a space';
|
||||
public static readonly DUPLICATE_SPACE_DESCRIPTION =
|
||||
'This endpoint allows you to create a copy of an existing space in a specified community.';
|
||||
|
||||
public static readonly LIST_SPACE_SUMMARY = 'List spaces in community';
|
||||
public static readonly LIST_SPACE_DESCRIPTION =
|
||||
'List spaces in specified community by community id';
|
||||
@ -181,6 +248,11 @@ export class ControllerRoute {
|
||||
public static readonly UPDATE_SPACE_DESCRIPTION =
|
||||
'Updates a space by its UUID and community ID. You can update the name, parent space, and other properties. If a parent space is provided and not already a parent, its `isParent` flag will be set to true.';
|
||||
|
||||
public static readonly UPDATE_CHILDREN_SPACES_ORDER_OF_A_SPACE_SUMMARY =
|
||||
'Update the order of child spaces under a specific parent space';
|
||||
public static readonly UPDATE_CHILDREN_SPACES_ORDER_OF_A_SPACE_DESCRIPTION =
|
||||
'Updates the order of child spaces under a specific parent space. You can provide a new order for the child spaces.';
|
||||
|
||||
public static readonly GET_HEIRARCHY_SUMMARY = 'Get space hierarchy';
|
||||
public static readonly GET_HEIRARCHY_DESCRIPTION =
|
||||
'This endpoint retrieves the hierarchical structure of spaces under a given space ID. It returns all the child spaces nested within the specified space, organized by their parent-child relationships. ';
|
||||
@ -197,7 +269,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 +373,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,12 +388,20 @@ 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';
|
||||
@ -320,7 +409,7 @@ export class ControllerRoute {
|
||||
};
|
||||
|
||||
static TAG = class {
|
||||
public static readonly ROUTE = 'tags';
|
||||
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 =
|
||||
@ -335,6 +424,10 @@ export class ControllerRoute {
|
||||
public static readonly ROUTE = '/user';
|
||||
|
||||
static ACTIONS = class {
|
||||
public static readonly GET_USERS_WITH_BOOKABLE_SPACES_SUMMARY =
|
||||
'Retrieve list of users that has bookable spaces';
|
||||
public static readonly GET_USERS_WITH_BOOKABLE_SPACES_DESCRIPTION =
|
||||
'This endpoint retrieves all the users that have access to bookable spaces, paginated & accepts sorting';
|
||||
public static readonly GET_USER_DETAILS_SUMMARY =
|
||||
'Retrieve user details by user UUID';
|
||||
public static readonly GET_USER_DETAILS_DESCRIPTION =
|
||||
@ -362,6 +455,11 @@ export class ControllerRoute {
|
||||
public static readonly DELETE_USER_SUMMARY = 'Delete user by UUID';
|
||||
public static readonly DELETE_USER_DESCRIPTION =
|
||||
'This endpoint deletes a user identified by their UUID. Accessible only by users with the Super Admin role.';
|
||||
|
||||
public static readonly DELETE_USER_PROFILE_SUMMARY =
|
||||
'Delete user profile by UUID';
|
||||
public static readonly DELETE_USER_PROFILE_DESCRIPTION =
|
||||
'This endpoint deletes a user profile identified by their UUID. Accessible only by users with the Super Admin role.';
|
||||
public static readonly UPDATE_USER_WEB_AGREEMENT_SUMMARY =
|
||||
'Update user web agreement by user UUID';
|
||||
public static readonly UPDATE_USER_WEB_AGREEMENT_DESCRIPTION =
|
||||
@ -430,7 +528,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';
|
||||
|
||||
@ -455,18 +562,51 @@ 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 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.';
|
||||
};
|
||||
};
|
||||
|
||||
static Occupancy = class {
|
||||
public static readonly ROUTE = 'occupancy';
|
||||
|
||||
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_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';
|
||||
|
||||
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 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';
|
||||
@ -538,18 +678,51 @@ 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.';
|
||||
|
||||
public static readonly POPULATE_TUYA_CONST_UUID_SUMMARY =
|
||||
'Populate Tuya const UUID';
|
||||
public static readonly POPULATE_TUYA_CONST_UUID_DESCRIPTION =
|
||||
'This endpoint populates the Tuya const UUID for all devices.';
|
||||
};
|
||||
};
|
||||
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.';
|
||||
};
|
||||
};
|
||||
|
||||
@ -601,17 +774,16 @@ 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_SUMMARY = 'Get all automations';
|
||||
public static readonly GET_AUTOMATION_DESCRIPTION =
|
||||
'This endpoint retrieves automations data';
|
||||
|
||||
public static readonly GET_AUTOMATION_DETAILS_SUMMARY =
|
||||
'Get automation details';
|
||||
@ -633,6 +805,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';
|
||||
|
||||
@ -692,29 +875,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',
|
||||
}
|
||||
@ -1,3 +0,0 @@
|
||||
export const SEND_EMAIL_API_URL_PROD = 'https://send.api.mailtrap.io/api/send/';
|
||||
export const SEND_EMAIL_API_URL_DEV =
|
||||
'https://sandbox.api.mailtrap.io/api/send/2634012';
|
||||
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,145 @@
|
||||
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 { BookableSpaceEntity } from '../modules/booking/entities/bookable-space.entity';
|
||||
import { BookingEntity } from '../modules/booking/entities/booking.entity';
|
||||
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,
|
||||
BookableSpaceEntity,
|
||||
BookingEntity,
|
||||
],
|
||||
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;
|
||||
}
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
import { IsUUID } from 'class-validator';
|
||||
|
||||
export class GetTagsParam {
|
||||
export class ProjectParam {
|
||||
@ApiProperty({
|
||||
description: 'UUID of the Project',
|
||||
example: 'd290f1ee-6c54-4b01-90e6-d701748f0851',
|
||||
@ -13,6 +13,7 @@ class StatusDto {
|
||||
|
||||
@IsNotEmpty()
|
||||
value: any;
|
||||
t?: string | number | Date;
|
||||
}
|
||||
|
||||
export class AddDeviceStatusDto {
|
||||
|
||||
@ -1,21 +1,29 @@
|
||||
import { DeviceStatusLogRepository } from '@app/common/modules/device-status-log/repositories';
|
||||
import { DeviceRepository } from '@app/common/modules/device/repositories';
|
||||
import {
|
||||
HttpException,
|
||||
HttpStatus,
|
||||
Injectable,
|
||||
NotFoundException,
|
||||
} from '@nestjs/common';
|
||||
import { AddDeviceStatusDto } from '../dtos/add.devices-status.dto';
|
||||
import { DeviceRepository } from '@app/common/modules/device/repositories';
|
||||
import { GetDeviceDetailsFunctionsStatusInterface } from 'src/device/interfaces/get.device.interface';
|
||||
import { TuyaContext } from '@tuya/tuya-connector-nodejs';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { TuyaContext } from '@tuya/tuya-connector-nodejs';
|
||||
import {
|
||||
Database,
|
||||
DataSnapshot,
|
||||
get,
|
||||
ref,
|
||||
runTransaction,
|
||||
} from 'firebase/database';
|
||||
import { GetDeviceDetailsFunctionsStatusInterface } from 'src/device/interfaces/get.device.interface';
|
||||
import { firebaseDataBase } from '../../firebase.config';
|
||||
import { Database, DataSnapshot, get, ref, set } from 'firebase/database';
|
||||
import { DeviceStatusLogRepository } from '@app/common/modules/device-status-log/repositories';
|
||||
import { AddDeviceStatusDto } from '../dtos/add.devices-status.dto';
|
||||
@Injectable()
|
||||
export class DeviceStatusFirebaseService {
|
||||
private tuya: TuyaContext;
|
||||
private firebaseDb: Database;
|
||||
private readonly isDevEnv: boolean;
|
||||
|
||||
constructor(
|
||||
private readonly configService: ConfigService,
|
||||
private readonly deviceRepository: DeviceRepository,
|
||||
@ -32,6 +40,8 @@ export class DeviceStatusFirebaseService {
|
||||
|
||||
// Initialize firebaseDb using firebaseDataBase function
|
||||
this.firebaseDb = firebaseDataBase(this.configService);
|
||||
this.isDevEnv =
|
||||
this.configService.get<string>('NODE_ENV') === 'development';
|
||||
}
|
||||
async addDeviceStatusByDeviceUuid(
|
||||
deviceTuyaUuid: string,
|
||||
@ -46,7 +56,7 @@ export class DeviceStatusFirebaseService {
|
||||
const deviceStatusSaved = await this.createDeviceStatusFirebase({
|
||||
deviceUuid: device.uuid,
|
||||
deviceTuyaUuid: deviceTuyaUuid,
|
||||
status: deviceStatus.status,
|
||||
status: deviceStatus?.status,
|
||||
productUuid: deviceStatus.productUuid,
|
||||
productType: deviceStatus.productType,
|
||||
});
|
||||
@ -61,24 +71,107 @@ export class DeviceStatusFirebaseService {
|
||||
);
|
||||
}
|
||||
}
|
||||
async addDeviceStatusToFirebase(
|
||||
addDeviceStatusDto: AddDeviceStatusDto,
|
||||
): Promise<AddDeviceStatusDto | null> {
|
||||
try {
|
||||
const device = await this.getDeviceByDeviceTuyaUuid(
|
||||
addDeviceStatusDto.deviceTuyaUuid,
|
||||
async addBatchDeviceStatusToOurDb(
|
||||
batch: {
|
||||
deviceTuyaUuid: string;
|
||||
status: any;
|
||||
log: any;
|
||||
device: any;
|
||||
}[],
|
||||
): Promise<void> {
|
||||
console.log(`🔁 Preparing logs from batch of ${batch.length} items...`);
|
||||
|
||||
const allLogs = [];
|
||||
|
||||
for (const item of batch) {
|
||||
const device = item.device;
|
||||
|
||||
if (!device?.uuid) {
|
||||
console.log(`⛔ Skipped unknown device: ${item.deviceTuyaUuid}`);
|
||||
continue;
|
||||
}
|
||||
|
||||
// Determine properties based on environment
|
||||
const properties =
|
||||
this.isDevEnv && Array.isArray(item.log?.properties)
|
||||
? item.log.properties
|
||||
: Array.isArray(item.status)
|
||||
? item.status
|
||||
: null;
|
||||
|
||||
if (!properties) {
|
||||
console.log(
|
||||
`⛔ Skipped invalid status/properties for device: ${item.deviceTuyaUuid}`,
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
const logs = properties.map((property) =>
|
||||
this.deviceStatusLogRepository.create({
|
||||
deviceId: device.uuid,
|
||||
deviceTuyaId: item.deviceTuyaUuid,
|
||||
productId: device.productDevice?.uuid,
|
||||
log: item.log,
|
||||
code: property.code,
|
||||
value: property.value,
|
||||
eventId: item.log?.dataId,
|
||||
eventTime: new Date(
|
||||
this.isDevEnv ? property.time : property.t,
|
||||
).toISOString(),
|
||||
}),
|
||||
);
|
||||
|
||||
allLogs.push(...logs);
|
||||
}
|
||||
|
||||
console.log(`📝 Total logs to insert: ${allLogs.length}`);
|
||||
|
||||
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')
|
||||
.values(chunk)
|
||||
.orIgnore()
|
||||
.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}`);
|
||||
}
|
||||
|
||||
async addDeviceStatusToFirebase(
|
||||
addDeviceStatusDto: AddDeviceStatusDto & { device?: any },
|
||||
): Promise<AddDeviceStatusDto | null> {
|
||||
try {
|
||||
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 +185,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);
|
||||
@ -106,7 +208,7 @@ export class DeviceStatusFirebaseService {
|
||||
return {
|
||||
productUuid: deviceDetails.productDevice.uuid,
|
||||
productType: deviceDetails.productDevice.prodType,
|
||||
status: deviceStatus.result[0].status,
|
||||
status: deviceStatus.result[0]?.status,
|
||||
};
|
||||
} catch (error) {
|
||||
throw new HttpException(
|
||||
@ -154,56 +256,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 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 { Injectable, OnModuleInit } from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import * as NodeCache from 'node-cache';
|
||||
import TuyaWebsocket from '../../config/tuya-web-socket-config';
|
||||
import { SosHandlerService } from './sos.handler.service';
|
||||
|
||||
@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,80 @@ 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);
|
||||
// console.log(
|
||||
// `📬 Received message for device: ${devId}, status:`,
|
||||
// status,
|
||||
// logData,
|
||||
// );
|
||||
if (!Array.isArray(status)) {
|
||||
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 +131,64 @@ 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;
|
||||
} {
|
||||
// console.log('Received message:', message);
|
||||
|
||||
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);
|
||||
// }
|
||||
}
|
||||
|
||||
5
libs/common/src/helper/timeToMinutes.ts
Normal file
5
libs/common/src/helper/timeToMinutes.ts
Normal file
@ -0,0 +1,5 @@
|
||||
// Convert time string (HH:mm) to minutes
|
||||
export function timeToMinutes(time: string): number {
|
||||
const [hours, minutes] = time.split(':').map(Number);
|
||||
return hours * 60 + minutes;
|
||||
}
|
||||
@ -49,12 +49,12 @@ export class TuyaService {
|
||||
path,
|
||||
});
|
||||
|
||||
if (!response.success) {
|
||||
throw new HttpException(
|
||||
`Error fetching device details: ${response.msg}`,
|
||||
HttpStatus.BAD_REQUEST,
|
||||
);
|
||||
}
|
||||
// if (!response.success) {
|
||||
// throw new HttpException(
|
||||
// `Error fetching device details: ${response.msg}`,
|
||||
// HttpStatus.BAD_REQUEST,
|
||||
// );
|
||||
// }
|
||||
|
||||
return response.result;
|
||||
}
|
||||
|
||||
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}`,
|
||||
});
|
||||
}
|
||||
}
|
||||
26
libs/common/src/logger/services/winston.logger.ts
Normal file
26
libs/common/src/logger/services/winston.logger.ts
Normal file
@ -0,0 +1,26 @@
|
||||
import { utilities as nestWinstonModuleUtilities } from 'nest-winston';
|
||||
import * as winston from 'winston';
|
||||
|
||||
export const winstonLoggerOptions: winston.LoggerOptions = {
|
||||
level:
|
||||
process.env.AZURE_POSTGRESQL_DATABASE === 'development' ? 'debug' : 'error',
|
||||
transports: [
|
||||
new winston.transports.Console({
|
||||
format: winston.format.combine(
|
||||
winston.format.timestamp(),
|
||||
nestWinstonModuleUtilities.format.nestLike('MyApp', {
|
||||
prettyPrint: true,
|
||||
}),
|
||||
),
|
||||
}),
|
||||
new winston.transports.File({
|
||||
filename: 'logs/error.log',
|
||||
level: 'error',
|
||||
format: winston.format.json(),
|
||||
}),
|
||||
new winston.transports.File({
|
||||
filename: 'logs/combined.log',
|
||||
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;
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
import { RoleType } from '@app/common/constants/role.type.enum';
|
||||
import { UserStatusEnum } from '@app/common/constants/user-status.enum';
|
||||
import { IsEnum, IsNotEmpty, IsString } from 'class-validator';
|
||||
import { IsEnum, IsNotEmpty, IsOptional, IsString } from 'class-validator';
|
||||
|
||||
export class InviteUserDto {
|
||||
@IsString()
|
||||
@ -12,8 +12,12 @@ export class InviteUserDto {
|
||||
public email: string;
|
||||
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
public jobTitle: string;
|
||||
@IsOptional()
|
||||
public jobTitle?: string;
|
||||
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
public companyName?: string;
|
||||
|
||||
@IsEnum(UserStatusEnum)
|
||||
@IsNotEmpty()
|
||||
|
||||
@ -8,14 +8,14 @@ import {
|
||||
Unique,
|
||||
} from 'typeorm';
|
||||
|
||||
import { AbstractEntity } from '../../abstract/entities/abstract.entity';
|
||||
import { RoleTypeEntity } from '../../role-type/entities';
|
||||
import { UserStatusEnum } from '@app/common/constants/user-status.enum';
|
||||
import { UserEntity } from '../../user/entities';
|
||||
import { RoleType } from '@app/common/constants/role.type.enum';
|
||||
import { InviteUserDto, InviteUserSpaceDto } from '../dtos';
|
||||
import { UserStatusEnum } from '@app/common/constants/user-status.enum';
|
||||
import { AbstractEntity } from '../../abstract/entities/abstract.entity';
|
||||
import { ProjectEntity } from '../../project/entities';
|
||||
import { RoleTypeEntity } from '../../role-type/entities';
|
||||
import { SpaceEntity } from '../../space/entities/space.entity';
|
||||
import { UserEntity } from '../../user/entities';
|
||||
import { InviteUserDto, InviteUserSpaceDto } from '../dtos';
|
||||
|
||||
@Entity({ name: 'invite-user' })
|
||||
@Unique(['email', 'project'])
|
||||
@ -37,6 +37,11 @@ export class InviteUserEntity extends AbstractEntity<InviteUserDto> {
|
||||
})
|
||||
jobTitle: string;
|
||||
|
||||
@Column({
|
||||
nullable: true,
|
||||
})
|
||||
companyName: string;
|
||||
|
||||
@Column({
|
||||
nullable: false,
|
||||
enum: Object.values(UserStatusEnum),
|
||||
@ -82,7 +87,10 @@ export class InviteUserEntity extends AbstractEntity<InviteUserDto> {
|
||||
onDelete: 'CASCADE',
|
||||
})
|
||||
public roleType: RoleTypeEntity;
|
||||
@OneToOne(() => UserEntity, (user) => user.inviteUser, { nullable: true })
|
||||
@OneToOne(() => UserEntity, (user) => user.inviteUser, {
|
||||
nullable: true,
|
||||
onDelete: 'CASCADE',
|
||||
})
|
||||
@JoinColumn({ name: 'user_uuid' })
|
||||
user: UserEntity;
|
||||
@OneToMany(
|
||||
@ -112,7 +120,9 @@ export class InviteUserSpaceEntity extends AbstractEntity<InviteUserSpaceDto> {
|
||||
})
|
||||
public uuid: string;
|
||||
|
||||
@ManyToOne(() => InviteUserEntity, (inviteUser) => inviteUser.spaces)
|
||||
@ManyToOne(() => InviteUserEntity, (inviteUser) => inviteUser.spaces, {
|
||||
onDelete: 'CASCADE',
|
||||
})
|
||||
@JoinColumn({ name: 'invite_user_uuid' })
|
||||
public inviteUser: InviteUserEntity;
|
||||
|
||||
|
||||
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';
|
||||
12
libs/common/src/modules/booking/booking.repository.module.ts
Normal file
12
libs/common/src/modules/booking/booking.repository.module.ts
Normal file
@ -0,0 +1,12 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { BookableSpaceEntity } from './entities/bookable-space.entity';
|
||||
import { BookingEntity } from './entities/booking.entity';
|
||||
|
||||
@Module({
|
||||
providers: [],
|
||||
exports: [],
|
||||
controllers: [],
|
||||
imports: [TypeOrmModule.forFeature([BookableSpaceEntity, BookingEntity])],
|
||||
})
|
||||
export class BookingRepositoryModule {}
|
||||
@ -0,0 +1,51 @@
|
||||
import { DaysEnum } from '@app/common/constants/days.enum';
|
||||
import {
|
||||
Column,
|
||||
CreateDateColumn,
|
||||
Entity,
|
||||
JoinColumn,
|
||||
OneToOne,
|
||||
UpdateDateColumn,
|
||||
} from 'typeorm';
|
||||
import { AbstractEntity } from '../../abstract/entities/abstract.entity';
|
||||
import { SpaceEntity } from '../../space/entities/space.entity';
|
||||
|
||||
@Entity('bookable-space')
|
||||
export class BookableSpaceEntity extends AbstractEntity {
|
||||
@Column({
|
||||
type: 'uuid',
|
||||
default: () => 'gen_random_uuid()',
|
||||
nullable: false,
|
||||
})
|
||||
public uuid: string;
|
||||
|
||||
@OneToOne(() => SpaceEntity, (space) => space.bookableConfig)
|
||||
@JoinColumn({ name: 'space_uuid' })
|
||||
space: SpaceEntity;
|
||||
|
||||
@Column({
|
||||
type: 'enum',
|
||||
enum: DaysEnum,
|
||||
array: true,
|
||||
nullable: false,
|
||||
})
|
||||
daysAvailable: DaysEnum[];
|
||||
|
||||
@Column({ type: 'time' })
|
||||
startTime: string;
|
||||
|
||||
@Column({ type: 'time' })
|
||||
endTime: string;
|
||||
|
||||
@Column({ type: Boolean, default: true })
|
||||
active: boolean;
|
||||
|
||||
@Column({ type: 'int', default: null })
|
||||
points?: number;
|
||||
|
||||
@CreateDateColumn()
|
||||
createdAt: Date;
|
||||
|
||||
@UpdateDateColumn()
|
||||
updatedAt: Date;
|
||||
}
|
||||
44
libs/common/src/modules/booking/entities/booking.entity.ts
Normal file
44
libs/common/src/modules/booking/entities/booking.entity.ts
Normal file
@ -0,0 +1,44 @@
|
||||
import {
|
||||
Column,
|
||||
CreateDateColumn,
|
||||
Entity,
|
||||
ManyToOne,
|
||||
UpdateDateColumn,
|
||||
} from 'typeorm';
|
||||
import { AbstractEntity } from '../../abstract/entities/abstract.entity';
|
||||
import { SpaceEntity } from '../../space/entities/space.entity';
|
||||
import { UserEntity } from '../../user/entities';
|
||||
|
||||
@Entity('booking')
|
||||
export class BookingEntity extends AbstractEntity {
|
||||
@Column({
|
||||
type: 'uuid',
|
||||
default: () => 'gen_random_uuid()',
|
||||
nullable: false,
|
||||
})
|
||||
public uuid: string;
|
||||
|
||||
@ManyToOne(() => SpaceEntity, (space) => space.bookableConfig)
|
||||
space: SpaceEntity;
|
||||
|
||||
@ManyToOne(() => UserEntity, (user) => user.bookings)
|
||||
user: UserEntity;
|
||||
|
||||
@Column({ type: Date, nullable: false })
|
||||
date: Date;
|
||||
|
||||
@Column({ type: 'time' })
|
||||
startTime: string;
|
||||
|
||||
@Column({ type: 'time' })
|
||||
endTime: string;
|
||||
|
||||
@Column({ type: 'int', default: null })
|
||||
cost?: number;
|
||||
|
||||
@CreateDateColumn()
|
||||
createdAt: Date;
|
||||
|
||||
@UpdateDateColumn()
|
||||
updatedAt: Date;
|
||||
}
|
||||
@ -0,0 +1,10 @@
|
||||
import { DataSource, Repository } from 'typeorm';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { BookableSpaceEntity } from '../entities/bookable-space.entity';
|
||||
|
||||
@Injectable()
|
||||
export class BookableSpaceEntityRepository extends Repository<BookableSpaceEntity> {
|
||||
constructor(private dataSource: DataSource) {
|
||||
super(BookableSpaceEntity, dataSource.createEntityManager());
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,10 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { DataSource, Repository } from 'typeorm';
|
||||
import { BookingEntity } from '../entities/booking.entity';
|
||||
|
||||
@Injectable()
|
||||
export class BookingEntityRepository extends Repository<BookingEntity> {
|
||||
constructor(private dataSource: DataSource) {
|
||||
super(BookingEntity, dataSource.createEntityManager());
|
||||
}
|
||||
}
|
||||
@ -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({
|
||||
|
||||
@ -1,25 +1,24 @@
|
||||
import {
|
||||
Column,
|
||||
Entity,
|
||||
Index,
|
||||
JoinColumn,
|
||||
ManyToOne,
|
||||
OneToMany,
|
||||
Unique,
|
||||
Index,
|
||||
JoinColumn,
|
||||
OneToOne,
|
||||
JoinTable,
|
||||
} from 'typeorm';
|
||||
import { AbstractEntity } from '../../abstract/entities/abstract.entity';
|
||||
import { DeviceDto, DeviceUserPermissionDto } from '../dtos/device.dto';
|
||||
import { ProductEntity } from '../../product/entities';
|
||||
import { UserEntity } from '../../user/entities';
|
||||
import { DeviceNotificationDto } from '../dtos';
|
||||
import { PermissionTypeEntity } from '../../permission/entities';
|
||||
import { PowerClampHourlyEntity } from '../../power-clamp/entities/power-clamp.entity';
|
||||
import { PresenceSensorDailyDeviceEntity } from '../../presence-sensor/entities';
|
||||
import { ProductEntity } from '../../product/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 { UserEntity } from '../../user/entities';
|
||||
import { DeviceNotificationDto } from '../dtos';
|
||||
import { DeviceDto, DeviceUserPermissionDto } from '../dtos/device.dto';
|
||||
|
||||
@Entity({ name: 'device' })
|
||||
@Unique(['deviceTuyaUuid'])
|
||||
@ -29,16 +28,21 @@ export class DeviceEntity extends AbstractEntity<DeviceDto> {
|
||||
})
|
||||
deviceTuyaUuid: string;
|
||||
|
||||
@Column({
|
||||
nullable: true,
|
||||
})
|
||||
deviceTuyaConstUuid: string;
|
||||
|
||||
@Column({
|
||||
nullable: true,
|
||||
default: true,
|
||||
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 +83,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);
|
||||
@ -114,6 +116,7 @@ export class DeviceNotificationEntity extends AbstractEntity<DeviceNotificationD
|
||||
|
||||
@ManyToOne(() => UserEntity, (user) => user.userPermission, {
|
||||
nullable: false,
|
||||
onDelete: 'CASCADE',
|
||||
})
|
||||
user: UserEntity;
|
||||
|
||||
@ -152,6 +155,7 @@ export class DeviceUserPermissionEntity extends AbstractEntity<DeviceUserPermiss
|
||||
|
||||
@ManyToOne(() => UserEntity, (user) => user.userPermission, {
|
||||
nullable: false,
|
||||
onDelete: 'CASCADE',
|
||||
})
|
||||
user: UserEntity;
|
||||
constructor(partial: Partial<DeviceUserPermissionEntity>) {
|
||||
|
||||
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[];
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user