Compare commits
393 Commits
0.1.1
...
Mobile-Enh
| Author | SHA1 | Date | |
|---|---|---|---|
| a05b48cd4c | |||
| 191bc6f428 | |||
| 87bdd30a19 | |||
| bae5578afb | |||
| 676e09aef5 | |||
| b40e4f3ec7 | |||
| b4ff7d4686 | |||
| 171e3b3137 | |||
| dd2ac19e4a | |||
| 18ba9b576c | |||
| 6c85677e1b | |||
| adb5e3e137 | |||
| 1749c3e617 | |||
| 52ee36be44 | |||
| 0cc327a9c4 | |||
| ef3cbbf370 | |||
| 209d0cdf0f | |||
| ab6c6f9acd | |||
| 95200b7970 | |||
| ae2c4d27bc | |||
| adc9da6a40 | |||
| a988545dda | |||
| 54dcb9d389 | |||
| c34f8beea9 | |||
| a239b7e204 | |||
| 19db5a8ca5 | |||
| 4611de4b0d | |||
| 86d069651c | |||
| 82d746fee1 | |||
| ae13cdebb3 | |||
| 90db7de843 | |||
| a1996419d6 | |||
| 4d87ff4925 | |||
| 2e944231a5 | |||
| 947c657e92 | |||
| f1695e3a00 | |||
| c7d79ae586 | |||
| 545b317caa | |||
| bd8f6ba84b | |||
| 9be1d953bf | |||
| 5106b72e24 | |||
| 34ce7d1e14 | |||
| ab9bb99987 | |||
| 69c7e7ed7e | |||
| 5d2ad6099c | |||
| dc10f05254 | |||
| 2759167ce6 | |||
| 0f29dabeee | |||
| 1372d4d285 | |||
| c27cd80dfd | |||
| 410daafa9e | |||
| 921e74f188 | |||
| cf880ed124 | |||
| f77f5b5a7f | |||
| 2789b79b82 | |||
| 76bf93b790 | |||
| d6bb2863c2 | |||
| 1101f0eb59 | |||
| d321c83f49 | |||
| 2a64577e2d | |||
| 59783ee93a | |||
| bb01d08622 | |||
| 3dc5461783 | |||
| d8455ccaa3 | |||
| 7ca617a51c | |||
| 0e2c5f8318 | |||
| 6811dc461c | |||
| 6f11bdb01d | |||
| dd440a4e75 | |||
| 2f7276a6c6 | |||
| c18ef9aa8d | |||
| 3a5f9eb6f0 | |||
| ab31b6e9f2 | |||
| 9ec30be6fb | |||
| 0c58e4045f | |||
| ca23675dd1 | |||
| e8805616c7 | |||
| 1f9511139f | |||
| d8fbaed538 | |||
| edbd18744d | |||
| 76ca516bf6 | |||
| c4f46eeffd | |||
| a7c8380c16 | |||
| ea23589162 | |||
| 32933f195e | |||
| 6f57e12a42 | |||
| 321cb80c06 | |||
| d0839ed51d | |||
| ec4a35729f | |||
| 686838e9bf | |||
| 7445dbf9f8 | |||
| bd0820ffc8 | |||
| a95b36da21 | |||
| fb8b82724d | |||
| efbc845ee2 | |||
| e022a33b69 | |||
| dd95adec3f | |||
| 9728a6c09a | |||
| 6e189796fa | |||
| 2a187e65ed | |||
| 22eaba6f90 | |||
| c646254616 | |||
| 67562f56aa | |||
| 8415e27ff3 | |||
| 083ddc345b | |||
| b4fcb1a366 | |||
| 7017c2427c | |||
| 7c7cbef3f3 | |||
| 1d6f17b725 | |||
| f9f1593b46 | |||
| f087461e09 | |||
| a0a405de85 | |||
| f26b285a88 | |||
| d9732830bb | |||
| 2c2936b01f | |||
| ce093af58e | |||
| 9baf2b97b9 | |||
| 4069b7274d | |||
| 30a97082a1 | |||
| aa7f11cb97 | |||
| b8c6590159 | |||
| 52bea200c8 | |||
| 7fff220053 | |||
| afbb771061 | |||
| cdf8f57eb5 | |||
| 3ff28de269 | |||
| f26a334487 | |||
| 0e37a8bc9c | |||
| 045de2fe98 | |||
| a1ca07e6fd | |||
| b60e5ae28b | |||
| c14475258d | |||
| dd21d12dd5 | |||
| a4f762e793 | |||
| fafacbefc3 | |||
| 19eb2be252 | |||
| 1c1358f9d0 | |||
| 5fdb0b45f0 | |||
| f58d0114eb | |||
| f4abc51198 | |||
| 7d5e9c33bf | |||
| 81bac9bcfb | |||
| d9c721791e | |||
| 0a3ed7b569 | |||
| ec886f986f | |||
| 82e3140499 | |||
| 2fc11a0589 | |||
| 318762e1b4 | |||
| d962b88d73 | |||
| 1348d01b9d | |||
| dbca679964 | |||
| ab247d720d | |||
| b94504bb69 | |||
| 9b16ff429a | |||
| 8b1f30611c | |||
| 08aa87de5b | |||
| ac82a80c1c | |||
| 9f895a202d | |||
| 510d4a13ac | |||
| 6139f12e13 | |||
| cf8f0fbc34 | |||
| d101bf9686 | |||
| 46988f1921 | |||
| 42b96d58a0 | |||
| 0e6a3c4a01 | |||
| c02e4e2851 | |||
| 5f3d78afde | |||
| aae47003cf | |||
| dcf3b208d8 | |||
| 40e53c52b4 | |||
| eb92dcafda | |||
| 7fb8852ac0 | |||
| 275fba292c | |||
| 17018b4bc9 | |||
| 3a09030193 | |||
| d872d342b2 | |||
| 569902e11c | |||
| 6acd423557 | |||
| e6e09f8c3e | |||
| e177723767 | |||
| dae6d142f2 | |||
| 593b91aa7d | |||
| af723c99c9 | |||
| efb5508a8d | |||
| 4fbbed446e | |||
| 3c689fbb30 | |||
| 7661b3c8d5 | |||
| 3848eb939a | |||
| a52f5cd31a | |||
| 46d1a0c286 | |||
| 6c2b88352d | |||
| 71f9240088 | |||
| e35b61d06b | |||
| dc3430aa2e | |||
| ff5371d867 | |||
| 8903baef52 | |||
| 871277882d | |||
| bb4d6a3a1a | |||
| 8f16d5190c | |||
| 80786f996f | |||
| f124e41630 | |||
| a699c20f9b | |||
| e01e742c07 | |||
| 1db75ee773 | |||
| f0624a64bd | |||
| 8c04d2cf05 | |||
| 3b261bc18e | |||
| 9a9cbc323e | |||
| 072c82f578 | |||
| 5e06e38a0d | |||
| b8750f1e8e | |||
| 00f8d583cc | |||
| f3e35f3f6a | |||
| d7b099ac75 | |||
| a6b521a89c | |||
| 6d83a2d342 | |||
| 43763853f8 | |||
| ad4d28b5dd | |||
| ac22e36202 | |||
| 3180097aa7 | |||
| 4476dd6d74 | |||
| 9ec6d65a4d | |||
| 65f8527cc5 | |||
| bded69345f | |||
| 6f7a0bf3b2 | |||
| 50a94ae86f | |||
| 5b61687cd9 | |||
| 1cf6b35021 | |||
| 18d08af91d | |||
| a95dbe2623 | |||
| 6f3ab2da73 | |||
| 8f397131d4 | |||
| 9139a06f4c | |||
| a7c2ed7dff | |||
| 637968552d | |||
| 9953e2765a | |||
| f2acf86dd8 | |||
| 2127a48a83 | |||
| 6cb53deee3 | |||
| b6a9b6f855 | |||
| 2f7eb37771 | |||
| 0cfc5ce12b | |||
| 044dc78122 | |||
| 2e31b9bce4 | |||
| fd6a1822f4 | |||
| d484c357fb | |||
| 278690e094 | |||
| f9e5dacda8 | |||
| 0a2c6785c6 | |||
| dac4de236b | |||
| 5e1351d033 | |||
| 5f6c17361b | |||
| eca4a75a6e | |||
| 9196a86570 | |||
| e0d9eeae92 | |||
| 05e6030626 | |||
| d01881f0af | |||
| 7990c86a86 | |||
| 5f03820891 | |||
| e9cce2571a | |||
| 905a975327 | |||
| 5659f053ba | |||
| 52b0e3e86d | |||
| e949e32189 | |||
| e9fadc724e | |||
| 7dc93c9802 | |||
| 0969d96e82 | |||
| 89ee1899e0 | |||
| 754ddd11d4 | |||
| 2902404d2e | |||
| 8006f4f737 | |||
| f7f2d1be8b | |||
| 5cbe0e6c7f | |||
| 04ad7a8f14 | |||
| cf37e5d01c | |||
| ee7d70bbe0 | |||
| 9e469013c7 | |||
| 627f6bfe3d | |||
| 94fac645af | |||
| 1eef9145a4 | |||
| fd94a5f261 | |||
| 2a0d7c2ff2 | |||
| 8aaaea5ed0 | |||
| 45aa59d54a | |||
| cf8113000f | |||
| 90e7a925ec | |||
| 10fea0982f | |||
| cdabd66986 | |||
| fd99ec73b3 | |||
| bc51ca1fcf | |||
| 826943c1a3 | |||
| 8409d971c1 | |||
| 6e2edc0096 | |||
| 1dfdb6bd0e | |||
| 618c290318 | |||
| 7f98d52634 | |||
| a73431f622 | |||
| 4670b568a5 | |||
| 82c9681dfa | |||
| 34469ee5af | |||
| ca4bb9fe2d | |||
| a335ce862d | |||
| b99d6653f8 | |||
| a6002dadb5 | |||
| 7ac83b532b | |||
| 2ee769dfdb | |||
| b2209ef870 | |||
| ed9190b298 | |||
| 412001b1b4 | |||
| 011439fb19 | |||
| 81ae9ebea1 | |||
| 2a2c2e1cb5 | |||
| 9b337e6813 | |||
| 0a2748f144 | |||
| 9c903509ed | |||
| 134fcf32d3 | |||
| f46ffafa4b | |||
| da6b4f46a7 | |||
| 5edce9b6fd | |||
| 15810097bb | |||
| 7aaeab5243 | |||
| 84392591d1 | |||
| af984cddbd | |||
| 359fcbb412 | |||
| e45e08ad91 | |||
| 0c3f166f71 | |||
| 9229475836 | |||
| b91ecacb60 | |||
| 7c4e8d7db8 | |||
| e7b73f9e73 | |||
| 533e315642 | |||
| 93e8f3b3d2 | |||
| 82eb6b7bbf | |||
| 2ea355d9d8 | |||
| 4d19f26f01 | |||
| 8aad3c67c7 | |||
| 445c15b797 | |||
| 406f61a612 | |||
| f7daa1bb19 | |||
| 8a7ca9c2f9 | |||
| 1730714737 | |||
| 8dc11ee34d | |||
| 2a841ebf27 | |||
| d7908570b2 | |||
| 629fd59a7c | |||
| d0322dc62e | |||
| 333bf20d86 | |||
| bd3c3564a9 | |||
| 6c688a86ea | |||
| 26ccae9078 | |||
| dc88126b6c | |||
| c74b5b280b | |||
| 0a1704b60b | |||
| 97119dec97 | |||
| a6d54e0b73 | |||
| 79d80be1bf | |||
| 0919997e0f | |||
| a5d4941d00 | |||
| 3835f22940 | |||
| f0ac2dca02 | |||
| 710b24e5a7 | |||
| bcde81093d | |||
| a3216ba5ab | |||
| 7ab06b6a4c | |||
| 9d217aafaf | |||
| 87c472e98e | |||
| dcb4720129 | |||
| 8cdbb99d6f | |||
| 2821bc62c4 | |||
| dd472a5283 | |||
| 92c0d657ea | |||
| 7a6020febb | |||
| fb64b35807 | |||
| a8165e2ae5 | |||
| 79cf77dc63 | |||
| 62defe5b6d | |||
| 5354fa85f1 | |||
| f5a0df7795 | |||
| e22f164097 | |||
| ae9c7c89b1 | |||
| dab0a7543c | |||
| 63267ac679 | |||
| 4a65596283 | |||
| e61bd1c5a1 | |||
| df89d9bf67 | |||
| 4ab803ec72 | |||
| 6a55846f19 | |||
| f6c4c3e508 | |||
| 67ce112934 | |||
| 33eca18e82 | |||
| 6b29501d59 | |||
| 8670b50b56 | |||
| 4445f5dd92 |
@@ -1,11 +1,11 @@
|
|||||||
name: Continuous Integration
|
name: Testing Site CD
|
||||||
on:
|
on:
|
||||||
push:
|
push:
|
||||||
branches:
|
branches:
|
||||||
- main
|
- main
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
Deploy:
|
deploy-testing-cd:
|
||||||
name: Update Development
|
name: Update Development
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
container:
|
container:
|
||||||
@@ -40,14 +40,20 @@ jobs:
|
|||||||
- name: Token Copy
|
- name: Token Copy
|
||||||
run: |
|
run: |
|
||||||
cd /var/www/html/milsim-site-v4
|
cd /var/www/html/milsim-site-v4
|
||||||
cp /workspace/17th-Ranger-Battalion-ORG/milsim-site-v4/.git/config .git/config
|
cp ${{ gitea.workspace }}/.git/config .git/config
|
||||||
chown nginx:nginx .git/config
|
chown nginx:nginx .git/config
|
||||||
|
|
||||||
- name: Update Application Code
|
- name: Update Application Code
|
||||||
run: |
|
run: |
|
||||||
cd /var/www/html/milsim-site-v4
|
cd /var/www/html/milsim-site-v4
|
||||||
|
version=`git log -1 --format=%H`
|
||||||
|
echo "Current Revision: $version"
|
||||||
|
echo "Updating to: ${{ github.sha }}"
|
||||||
sudo -u nginx git reset --hard
|
sudo -u nginx git reset --hard
|
||||||
|
sudo -u nginx git fetch --tags
|
||||||
sudo -u nginx git pull origin main
|
sudo -u nginx git pull origin main
|
||||||
|
new_version=`git log -1 --format=%H`
|
||||||
|
echo "Successfully updated to: $new_version"
|
||||||
|
|
||||||
- name: Update Shared Dependencies and Fix Permissions
|
- name: Update Shared Dependencies and Fix Permissions
|
||||||
run: |
|
run: |
|
||||||
@@ -83,6 +89,12 @@ jobs:
|
|||||||
sed -i "s/APPLICATION_VERSION=.*/APPLICATION_VERSION=$version/" .env
|
sed -i "s/APPLICATION_VERSION=.*/APPLICATION_VERSION=$version/" .env
|
||||||
chown -R nginx:nginx .
|
chown -R nginx:nginx .
|
||||||
|
|
||||||
|
- name: Run Database Migrations
|
||||||
|
run: |
|
||||||
|
cd /var/www/html/milsim-site-v4/api
|
||||||
|
npx db-migrate up -e prod
|
||||||
|
chown -R nginx:nginx .
|
||||||
|
|
||||||
- name: Reset File Permissions
|
- name: Reset File Permissions
|
||||||
run: |
|
run: |
|
||||||
sudo chown -R nginx:nginx /var/www/html/milsim-site-v4
|
sudo chown -R nginx:nginx /var/www/html/milsim-site-v4
|
||||||
@@ -1,11 +1,11 @@
|
|||||||
name: Continuous Deployment
|
name: Live Site CD
|
||||||
on:
|
on:
|
||||||
push:
|
push:
|
||||||
tags:
|
tags:
|
||||||
- '*'
|
- '*'
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
Deploy:
|
deploy-live-cd:
|
||||||
name: Update Deployment
|
name: Update Deployment
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
container:
|
container:
|
||||||
@@ -40,7 +40,7 @@ jobs:
|
|||||||
- name: Token Copy
|
- name: Token Copy
|
||||||
run: |
|
run: |
|
||||||
cd /var/www/html/milsim-site-v4
|
cd /var/www/html/milsim-site-v4
|
||||||
cp /workspace/17th-Ranger-Battalion-ORG/milsim-site-v4/.git/config .git/config
|
cp ${{ gitea.workspace }}/.git/config .git/config
|
||||||
chown nginx:nginx .git/config
|
chown nginx:nginx .git/config
|
||||||
|
|
||||||
- name: Update Application Code
|
- name: Update Application Code
|
||||||
@@ -48,12 +48,12 @@ jobs:
|
|||||||
cd /var/www/html/milsim-site-v4
|
cd /var/www/html/milsim-site-v4
|
||||||
version=`git log -1 --format=%H`
|
version=`git log -1 --format=%H`
|
||||||
echo "Current Revision: $version"
|
echo "Current Revision: $version"
|
||||||
echo "Updating to: ${{ github.sha }}
|
echo "Updating to: ${{ github.sha }}"
|
||||||
sudo -u nginx git reset --hard
|
sudo -u nginx git reset --hard
|
||||||
sudo -u nginx git pull origin main
|
sudo -u nginx git fetch --tags
|
||||||
sudo -u nginx git pull origin main
|
sudo -u nginx git pull origin main
|
||||||
new_version=`git log -1 --format=%H`
|
new_version=`git log -1 --format=%H`
|
||||||
echo "Sucessfully updated to: $new_version
|
echo "Successfully updated to: $new_version"
|
||||||
|
|
||||||
- name: Update Shared Dependencies and Fix Permissions
|
- name: Update Shared Dependencies and Fix Permissions
|
||||||
run: |
|
run: |
|
||||||
@@ -89,6 +89,12 @@ jobs:
|
|||||||
sed -i "s/APPLICATION_VERSION=.*/APPLICATION_VERSION=$version/" .env
|
sed -i "s/APPLICATION_VERSION=.*/APPLICATION_VERSION=$version/" .env
|
||||||
chown -R nginx:nginx .
|
chown -R nginx:nginx .
|
||||||
|
|
||||||
|
- name: Run Database Migrations
|
||||||
|
run: |
|
||||||
|
cd /var/www/html/milsim-site-v4/api
|
||||||
|
npx db-migrate up -e prod
|
||||||
|
chown -R nginx:nginx .
|
||||||
|
|
||||||
- name: Reset File Permissions
|
- name: Reset File Permissions
|
||||||
run: |
|
run: |
|
||||||
sudo chown -R nginx:nginx /var/www/html/milsim-site-v4
|
sudo chown -R nginx:nginx /var/www/html/milsim-site-v4
|
||||||
58
.gitea/workflows/pull-request.yaml
Normal file
58
.gitea/workflows/pull-request.yaml
Normal file
@@ -0,0 +1,58 @@
|
|||||||
|
name: Pull Request CI
|
||||||
|
on:
|
||||||
|
pull_request:
|
||||||
|
branches:
|
||||||
|
- main
|
||||||
|
types:
|
||||||
|
- opened
|
||||||
|
- synchronize
|
||||||
|
- reopened
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
build:
|
||||||
|
name: Merge Check
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
container:
|
||||||
|
steps:
|
||||||
|
- name: Update Node Environment
|
||||||
|
uses: actions/setup-node@v6
|
||||||
|
with:
|
||||||
|
node-version: 20.19
|
||||||
|
|
||||||
|
- name: Verify Local Environment
|
||||||
|
run: |
|
||||||
|
which npm
|
||||||
|
npm -v
|
||||||
|
which node
|
||||||
|
node -v
|
||||||
|
|
||||||
|
- name: Checkout
|
||||||
|
uses: actions/checkout@v5
|
||||||
|
with:
|
||||||
|
fetch-depth: 0
|
||||||
|
ref: 'main'
|
||||||
|
|
||||||
|
- name: Install Shared Dependencies
|
||||||
|
run: |
|
||||||
|
cd ${{ gitea.workspace }}/shared
|
||||||
|
npm install
|
||||||
|
|
||||||
|
- name: Install UI Dependencies
|
||||||
|
run: |
|
||||||
|
cd ${{ gitea.workspace }}/ui
|
||||||
|
npm install
|
||||||
|
|
||||||
|
- name: Install API Dependencies
|
||||||
|
run: |
|
||||||
|
cd ${{ gitea.workspace }}/api
|
||||||
|
npm install
|
||||||
|
|
||||||
|
- name: Build UI
|
||||||
|
run: |
|
||||||
|
cd ${{ gitea.workspace }}/ui
|
||||||
|
npm run build
|
||||||
|
|
||||||
|
- name: Build API
|
||||||
|
run: |
|
||||||
|
cd ${{ gitea.workspace }}/api
|
||||||
|
npm run build
|
||||||
2
.gitignore
vendored
2
.gitignore
vendored
@@ -32,3 +32,5 @@ coverage
|
|||||||
*.sql
|
*.sql
|
||||||
.env
|
.env
|
||||||
*.db
|
*.db
|
||||||
|
|
||||||
|
db_data
|
||||||
@@ -21,7 +21,19 @@ CLIENT_URL= # This is whatever URL the client web app is served on
|
|||||||
CLIENT_DOMAIN= #whatever.com
|
CLIENT_DOMAIN= #whatever.com
|
||||||
APPLICATION_VERSION= # Should match release tag
|
APPLICATION_VERSION= # Should match release tag
|
||||||
APPLICATION_ENVIRONMENT= # dev / prod
|
APPLICATION_ENVIRONMENT= # dev / prod
|
||||||
|
CONFIG_ID= # config version
|
||||||
|
|
||||||
|
# webhooks/integrations
|
||||||
|
DISCORD_APPLICATIONS_WEBHOOK=
|
||||||
|
|
||||||
|
# Logger
|
||||||
|
LOG_DEPTH= # normal / verbose / profiling
|
||||||
|
|
||||||
# Glitchtip
|
# Glitchtip
|
||||||
GLITCHTIP_DSN=
|
GLITCHTIP_DSN=
|
||||||
DISABLE_GLITCHTIP= # true/false
|
DISABLE_GLITCHTIP= # true/false
|
||||||
|
|
||||||
|
# Bookstack
|
||||||
|
DOC_HOST= # https://bookstack.whatever.com/
|
||||||
|
DOC_TOKEN_SECRET=
|
||||||
|
DOC_TOKEN_ID=
|
||||||
2
api/.gitignore
vendored
2
api/.gitignore
vendored
@@ -1 +1,3 @@
|
|||||||
built
|
built
|
||||||
|
|
||||||
|
!migrations/*/*.sql
|
||||||
20
api/database.json
Normal file
20
api/database.json
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
{
|
||||||
|
"dev": {
|
||||||
|
"driver": "mysql",
|
||||||
|
"user": "root",
|
||||||
|
"password": "root",
|
||||||
|
"host": "localhost",
|
||||||
|
"database": "ranger_unit_tracker",
|
||||||
|
"port": "3306",
|
||||||
|
"multipleStatements": true
|
||||||
|
},
|
||||||
|
"prod": {
|
||||||
|
"driver": "mysql",
|
||||||
|
"user": {"ENV" : "DB_USERNAME"},
|
||||||
|
"password": {"ENV" : "DB_PASSWORD"},
|
||||||
|
"host": {"ENV" : "DB_HOST"},
|
||||||
|
"database": {"ENV" : "DB_DATABASE"},
|
||||||
|
"port": {"ENV" : "DB_PORT"},
|
||||||
|
"multipleStatements": true
|
||||||
|
}
|
||||||
|
}
|
||||||
53
api/migrations/20260201154439-initial.js
Normal file
53
api/migrations/20260201154439-initial.js
Normal file
@@ -0,0 +1,53 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
var dbm;
|
||||||
|
var type;
|
||||||
|
var seed;
|
||||||
|
var fs = require('fs');
|
||||||
|
var path = require('path');
|
||||||
|
var Promise;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* We receive the dbmigrate dependency from dbmigrate initially.
|
||||||
|
* This enables us to not have to rely on NODE_PATH.
|
||||||
|
*/
|
||||||
|
exports.setup = function(options, seedLink) {
|
||||||
|
dbm = options.dbmigrate;
|
||||||
|
type = dbm.dataType;
|
||||||
|
seed = seedLink;
|
||||||
|
Promise = options.Promise;
|
||||||
|
};
|
||||||
|
|
||||||
|
exports.up = function(db) {
|
||||||
|
var filePath = path.join(__dirname, 'sqls', '20260201154439-initial-up.sql');
|
||||||
|
return new Promise( function( resolve, reject ) {
|
||||||
|
fs.readFile(filePath, {encoding: 'utf-8'}, function(err,data){
|
||||||
|
if (err) return reject(err);
|
||||||
|
console.log('received data: ' + data);
|
||||||
|
|
||||||
|
resolve(data);
|
||||||
|
});
|
||||||
|
})
|
||||||
|
.then(function(data) {
|
||||||
|
return db.runSql(data);
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
exports.down = function(db) {
|
||||||
|
var filePath = path.join(__dirname, 'sqls', '20260201154439-initial-down.sql');
|
||||||
|
return new Promise( function( resolve, reject ) {
|
||||||
|
fs.readFile(filePath, {encoding: 'utf-8'}, function(err,data){
|
||||||
|
if (err) return reject(err);
|
||||||
|
console.log('received data: ' + data);
|
||||||
|
|
||||||
|
resolve(data);
|
||||||
|
});
|
||||||
|
})
|
||||||
|
.then(function(data) {
|
||||||
|
return db.runSql(data);
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
exports._meta = {
|
||||||
|
"version": 1
|
||||||
|
};
|
||||||
53
api/migrations/20260204025935-remove-unused-tables.js
Normal file
53
api/migrations/20260204025935-remove-unused-tables.js
Normal file
@@ -0,0 +1,53 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
var dbm;
|
||||||
|
var type;
|
||||||
|
var seed;
|
||||||
|
var fs = require('fs');
|
||||||
|
var path = require('path');
|
||||||
|
var Promise;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* We receive the dbmigrate dependency from dbmigrate initially.
|
||||||
|
* This enables us to not have to rely on NODE_PATH.
|
||||||
|
*/
|
||||||
|
exports.setup = function(options, seedLink) {
|
||||||
|
dbm = options.dbmigrate;
|
||||||
|
type = dbm.dataType;
|
||||||
|
seed = seedLink;
|
||||||
|
Promise = options.Promise;
|
||||||
|
};
|
||||||
|
|
||||||
|
exports.up = function(db) {
|
||||||
|
var filePath = path.join(__dirname, 'sqls', '20260204025935-remove-unused-tables-up.sql');
|
||||||
|
return new Promise( function( resolve, reject ) {
|
||||||
|
fs.readFile(filePath, {encoding: 'utf-8'}, function(err,data){
|
||||||
|
if (err) return reject(err);
|
||||||
|
console.log('received data: ' + data);
|
||||||
|
|
||||||
|
resolve(data);
|
||||||
|
});
|
||||||
|
})
|
||||||
|
.then(function(data) {
|
||||||
|
return db.runSql(data);
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
exports.down = function(db) {
|
||||||
|
var filePath = path.join(__dirname, 'sqls', '20260204025935-remove-unused-tables-down.sql');
|
||||||
|
return new Promise( function( resolve, reject ) {
|
||||||
|
fs.readFile(filePath, {encoding: 'utf-8'}, function(err,data){
|
||||||
|
if (err) return reject(err);
|
||||||
|
console.log('received data: ' + data);
|
||||||
|
|
||||||
|
resolve(data);
|
||||||
|
});
|
||||||
|
})
|
||||||
|
.then(function(data) {
|
||||||
|
return db.runSql(data);
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
exports._meta = {
|
||||||
|
"version": 1
|
||||||
|
};
|
||||||
53
api/migrations/20260204140912-state-history-suspensions.js
Normal file
53
api/migrations/20260204140912-state-history-suspensions.js
Normal file
@@ -0,0 +1,53 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
var dbm;
|
||||||
|
var type;
|
||||||
|
var seed;
|
||||||
|
var fs = require('fs');
|
||||||
|
var path = require('path');
|
||||||
|
var Promise;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* We receive the dbmigrate dependency from dbmigrate initially.
|
||||||
|
* This enables us to not have to rely on NODE_PATH.
|
||||||
|
*/
|
||||||
|
exports.setup = function(options, seedLink) {
|
||||||
|
dbm = options.dbmigrate;
|
||||||
|
type = dbm.dataType;
|
||||||
|
seed = seedLink;
|
||||||
|
Promise = options.Promise;
|
||||||
|
};
|
||||||
|
|
||||||
|
exports.up = function(db) {
|
||||||
|
var filePath = path.join(__dirname, 'sqls', '20260204140912-state-history-suspensions-up.sql');
|
||||||
|
return new Promise( function( resolve, reject ) {
|
||||||
|
fs.readFile(filePath, {encoding: 'utf-8'}, function(err,data){
|
||||||
|
if (err) return reject(err);
|
||||||
|
console.log('received data: ' + data);
|
||||||
|
|
||||||
|
resolve(data);
|
||||||
|
});
|
||||||
|
})
|
||||||
|
.then(function(data) {
|
||||||
|
return db.runSql(data);
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
exports.down = function(db) {
|
||||||
|
var filePath = path.join(__dirname, 'sqls', '20260204140912-state-history-suspensions-down.sql');
|
||||||
|
return new Promise( function( resolve, reject ) {
|
||||||
|
fs.readFile(filePath, {encoding: 'utf-8'}, function(err,data){
|
||||||
|
if (err) return reject(err);
|
||||||
|
console.log('received data: ' + data);
|
||||||
|
|
||||||
|
resolve(data);
|
||||||
|
});
|
||||||
|
})
|
||||||
|
.then(function(data) {
|
||||||
|
return db.runSql(data);
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
exports._meta = {
|
||||||
|
"version": 1
|
||||||
|
};
|
||||||
53
api/migrations/20260212052346-state-reason-detailed.js
Normal file
53
api/migrations/20260212052346-state-reason-detailed.js
Normal file
@@ -0,0 +1,53 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
var dbm;
|
||||||
|
var type;
|
||||||
|
var seed;
|
||||||
|
var fs = require('fs');
|
||||||
|
var path = require('path');
|
||||||
|
var Promise;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* We receive the dbmigrate dependency from dbmigrate initially.
|
||||||
|
* This enables us to not have to rely on NODE_PATH.
|
||||||
|
*/
|
||||||
|
exports.setup = function(options, seedLink) {
|
||||||
|
dbm = options.dbmigrate;
|
||||||
|
type = dbm.dataType;
|
||||||
|
seed = seedLink;
|
||||||
|
Promise = options.Promise;
|
||||||
|
};
|
||||||
|
|
||||||
|
exports.up = function(db) {
|
||||||
|
var filePath = path.join(__dirname, 'sqls', '20260212052346-state-reason-detailed-up.sql');
|
||||||
|
return new Promise( function( resolve, reject ) {
|
||||||
|
fs.readFile(filePath, {encoding: 'utf-8'}, function(err,data){
|
||||||
|
if (err) return reject(err);
|
||||||
|
console.log('received data: ' + data);
|
||||||
|
|
||||||
|
resolve(data);
|
||||||
|
});
|
||||||
|
})
|
||||||
|
.then(function(data) {
|
||||||
|
return db.runSql(data);
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
exports.down = function(db) {
|
||||||
|
var filePath = path.join(__dirname, 'sqls', '20260212052346-state-reason-detailed-down.sql');
|
||||||
|
return new Promise( function( resolve, reject ) {
|
||||||
|
fs.readFile(filePath, {encoding: 'utf-8'}, function(err,data){
|
||||||
|
if (err) return reject(err);
|
||||||
|
console.log('received data: ' + data);
|
||||||
|
|
||||||
|
resolve(data);
|
||||||
|
});
|
||||||
|
})
|
||||||
|
.then(function(data) {
|
||||||
|
return db.runSql(data);
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
exports._meta = {
|
||||||
|
"version": 1
|
||||||
|
};
|
||||||
53
api/migrations/20260212165353-audit-log.js
Normal file
53
api/migrations/20260212165353-audit-log.js
Normal file
@@ -0,0 +1,53 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
var dbm;
|
||||||
|
var type;
|
||||||
|
var seed;
|
||||||
|
var fs = require('fs');
|
||||||
|
var path = require('path');
|
||||||
|
var Promise;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* We receive the dbmigrate dependency from dbmigrate initially.
|
||||||
|
* This enables us to not have to rely on NODE_PATH.
|
||||||
|
*/
|
||||||
|
exports.setup = function(options, seedLink) {
|
||||||
|
dbm = options.dbmigrate;
|
||||||
|
type = dbm.dataType;
|
||||||
|
seed = seedLink;
|
||||||
|
Promise = options.Promise;
|
||||||
|
};
|
||||||
|
|
||||||
|
exports.up = function(db) {
|
||||||
|
var filePath = path.join(__dirname, 'sqls', '20260212165353-audit-log-up.sql');
|
||||||
|
return new Promise( function( resolve, reject ) {
|
||||||
|
fs.readFile(filePath, {encoding: 'utf-8'}, function(err,data){
|
||||||
|
if (err) return reject(err);
|
||||||
|
console.log('received data: ' + data);
|
||||||
|
|
||||||
|
resolve(data);
|
||||||
|
});
|
||||||
|
})
|
||||||
|
.then(function(data) {
|
||||||
|
return db.runSql(data);
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
exports.down = function(db) {
|
||||||
|
var filePath = path.join(__dirname, 'sqls', '20260212165353-audit-log-down.sql');
|
||||||
|
return new Promise( function( resolve, reject ) {
|
||||||
|
fs.readFile(filePath, {encoding: 'utf-8'}, function(err,data){
|
||||||
|
if (err) return reject(err);
|
||||||
|
console.log('received data: ' + data);
|
||||||
|
|
||||||
|
resolve(data);
|
||||||
|
});
|
||||||
|
})
|
||||||
|
.then(function(data) {
|
||||||
|
return db.runSql(data);
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
exports._meta = {
|
||||||
|
"version": 1
|
||||||
|
};
|
||||||
112185
api/migrations/seed.sql
Normal file
112185
api/migrations/seed.sql
Normal file
File diff suppressed because it is too large
Load Diff
1
api/migrations/sqls/20260201154439-initial-down.sql
Normal file
1
api/migrations/sqls/20260201154439-initial-down.sql
Normal file
@@ -0,0 +1 @@
|
|||||||
|
/* Replace with your SQL commands */
|
||||||
1338
api/migrations/sqls/20260201154439-initial-up.sql
Normal file
1338
api/migrations/sqls/20260201154439-initial-up.sql
Normal file
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1 @@
|
|||||||
|
/* Replace with your SQL commands */
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
/* Replace with your SQL commands */
|
||||||
|
|
||||||
|
DROP PROCEDURE `sp_update_member_rank_Backup_1-27-2026`;
|
||||||
|
DROP PROCEDURE `sp_update_member_status_Backup_1-27-2026`;
|
||||||
|
DROP PROCEDURE `sp_update_member_unit_Backup_1-27-2026`;
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
/* Replace with your SQL commands */
|
||||||
|
UPDATE members m
|
||||||
|
JOIN account_states s ON m.state_id = s.id
|
||||||
|
SET m.state_legacy = s.name;
|
||||||
|
|
||||||
|
ALTER TABLE members DROP FOREIGN KEY fk_members_state_id,
|
||||||
|
DROP INDEX idx_members_state_id,
|
||||||
|
DROP COLUMN state_id;
|
||||||
|
|
||||||
|
ALTER TABLE members
|
||||||
|
RENAME COLUMN state_legacy TO state;
|
||||||
|
|
||||||
|
DROP TABLE IF EXISTS member_state_history;
|
||||||
|
DROP TABLE IF EXISTS account_states;
|
||||||
@@ -0,0 +1,57 @@
|
|||||||
|
/* Replace with your SQL commands */
|
||||||
|
CREATE TABLE IF NOT EXISTS account_states (
|
||||||
|
id INT AUTO_INCREMENT PRIMARY KEY,
|
||||||
|
name VARCHAR(50) NOT NULL,
|
||||||
|
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||||
|
UNIQUE KEY uq_account_states_name (name)
|
||||||
|
);
|
||||||
|
INSERT IGNORE INTO account_states (name)
|
||||||
|
VALUES ('guest'),
|
||||||
|
('applicant'),
|
||||||
|
('member'),
|
||||||
|
('retired'),
|
||||||
|
('discharged'),
|
||||||
|
('suspended'),
|
||||||
|
('banned'),
|
||||||
|
('denied');
|
||||||
|
ALTER TABLE members
|
||||||
|
RENAME COLUMN state TO state_legacy;
|
||||||
|
ALTER TABLE members
|
||||||
|
ADD COLUMN state INT NOT NULL DEFAULT 1,
|
||||||
|
ADD INDEX idx_members_state (state),
|
||||||
|
ADD CONSTRAINT fk_members_state_id FOREIGN KEY (state) REFERENCES account_states(id);
|
||||||
|
CREATE TABLE IF NOT EXISTS member_state_history (
|
||||||
|
id INT AUTO_INCREMENT PRIMARY KEY,
|
||||||
|
member_id INT NOT NULL,
|
||||||
|
state_id INT NOT NULL,
|
||||||
|
reason VARCHAR(255),
|
||||||
|
created_by_id INT,
|
||||||
|
start_date DATE,
|
||||||
|
end_date DATE,
|
||||||
|
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||||
|
INDEX idx_member_state_history_member_id (member_id),
|
||||||
|
CONSTRAINT fk_member_state_history_member FOREIGN KEY (member_id) REFERENCES members(id),
|
||||||
|
CONSTRAINT fk_member_state_type FOREIGN KEY (state_id) REFERENCES account_states(id),
|
||||||
|
CONSTRAINT fk_member_state_history_created_by FOREIGN KEY (created_by_id) REFERENCES members(id)
|
||||||
|
);
|
||||||
|
-- Convert member states to new system
|
||||||
|
UPDATE members m
|
||||||
|
JOIN account_states s ON m.state_legacy = s.name
|
||||||
|
SET m.state = s.id;
|
||||||
|
|
||||||
|
-- Initial history population
|
||||||
|
INSERT INTO member_state_history (
|
||||||
|
member_id,
|
||||||
|
state_id,
|
||||||
|
reason,
|
||||||
|
start_date,
|
||||||
|
created_at
|
||||||
|
)
|
||||||
|
SELECT id,
|
||||||
|
state,
|
||||||
|
'history start',
|
||||||
|
CURDATE(),
|
||||||
|
NOW()
|
||||||
|
FROM members;
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
/* Replace with your SQL commands */
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
/* Replace with your SQL commands */
|
||||||
|
|
||||||
|
ALTER TABLE member_state_history ADD reason_detailed TEXT;
|
||||||
1
api/migrations/sqls/20260212165353-audit-log-down.sql
Normal file
1
api/migrations/sqls/20260212165353-audit-log-down.sql
Normal file
@@ -0,0 +1 @@
|
|||||||
|
/* Replace with your SQL commands */
|
||||||
17
api/migrations/sqls/20260212165353-audit-log-up.sql
Normal file
17
api/migrations/sqls/20260212165353-audit-log-up.sql
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
CREATE TABLE audit_log (
|
||||||
|
id INT PRIMARY KEY AUTO_INCREMENT,
|
||||||
|
-- "area.action" (e.g., 'calendarEvent.create', 'member.update_rank')
|
||||||
|
action_type VARCHAR(100) NOT NULL,
|
||||||
|
-- The JSON blob containing detailed information
|
||||||
|
payload JSON DEFAULT NULL,
|
||||||
|
-- Identifying the actor
|
||||||
|
created_by INT,
|
||||||
|
-- The ID of the resource being acted upon
|
||||||
|
target_id INT DEFAULT NULL,
|
||||||
|
|
||||||
|
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
CONSTRAINT fk_created_by FOREIGN KEY (created_by) REFERENCES members(id) ON DELETE
|
||||||
|
SET NULL,
|
||||||
|
INDEX idx_action (action_type),
|
||||||
|
INDEX idx_target (target_id)
|
||||||
|
);
|
||||||
906
api/package-lock.json
generated
906
api/package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@@ -9,25 +9,33 @@
|
|||||||
"scripts": {
|
"scripts": {
|
||||||
"test": "echo \"Error: no test specified\" && exit 1",
|
"test": "echo \"Error: no test specified\" && exit 1",
|
||||||
"dev": "tsc && tsc-alias && node ./built/api/src/index.js",
|
"dev": "tsc && tsc-alias && node ./built/api/src/index.js",
|
||||||
"build": "tsc && tsc-alias"
|
"prod": "tsc && tsc-alias && node ./built/api/src/index.js",
|
||||||
|
"build": "tsc && tsc-alias",
|
||||||
|
"seed": "node ./scripts/seed.js"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
|
"@rsol/hashmig": "^1.0.7",
|
||||||
"@sentry/node": "^10.27.0",
|
"@sentry/node": "^10.27.0",
|
||||||
|
"@types/express-session": "^1.18.2",
|
||||||
"connect-sqlite3": "^0.9.16",
|
"connect-sqlite3": "^0.9.16",
|
||||||
"cors": "^2.8.5",
|
"cors": "^2.8.5",
|
||||||
"dotenv": "^17.2.1",
|
"db-migrate": "^0.11.14",
|
||||||
|
"db-migrate-mysql": "^3.0.0",
|
||||||
|
"dotenv": "16.6.1",
|
||||||
"express": "^5.1.0",
|
"express": "^5.1.0",
|
||||||
"express-session": "^1.18.2",
|
"express-session": "^1.18.2",
|
||||||
"mariadb": "^3.4.5",
|
"mariadb": "^3.4.5",
|
||||||
"morgan": "^1.10.1",
|
"morgan": "^1.10.1",
|
||||||
"mysql2": "^3.14.3",
|
"mysql2": "^3.14.3",
|
||||||
"passport": "^0.7.0",
|
"passport": "^0.7.0",
|
||||||
|
"passport-custom": "^1.1.1",
|
||||||
"passport-openidconnect": "^0.1.2"
|
"passport-openidconnect": "^0.1.2"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@types/express": "^5.0.3",
|
"@types/express": "^5.0.3",
|
||||||
"@types/morgan": "^1.9.10",
|
"@types/morgan": "^1.9.10",
|
||||||
"@types/node": "^24.8.1",
|
"@types/node": "^24.8.1",
|
||||||
|
"cross-env": "^10.1.0",
|
||||||
"tsc-alias": "^1.8.16",
|
"tsc-alias": "^1.8.16",
|
||||||
"typescript": "^5.9.3"
|
"typescript": "^5.9.3"
|
||||||
}
|
}
|
||||||
|
|||||||
29
api/scripts/migrate.js
Normal file
29
api/scripts/migrate.js
Normal file
@@ -0,0 +1,29 @@
|
|||||||
|
const dotenv = require('dotenv');
|
||||||
|
const path = require('path');
|
||||||
|
const { execSync } = require('child_process');
|
||||||
|
|
||||||
|
dotenv.config({ path: path.resolve(process.cwd(), `.env`) });
|
||||||
|
|
||||||
|
const db = {
|
||||||
|
user: process.env.DB_USERNAME,
|
||||||
|
pass: process.env.DB_PASSWORD,
|
||||||
|
host: process.env.DB_MIGRATION_HOST,
|
||||||
|
port: process.env.DB_PORT,
|
||||||
|
name: process.env.DB_DATABASE,
|
||||||
|
};
|
||||||
|
const dbUrl = `mysql://${db.user}:${db.pass}@tcp(${db.host}:${db.port})/${db.name}`;
|
||||||
|
|
||||||
|
const args = process.argv.slice(2).join(" ");
|
||||||
|
const migrations = path.join(process.cwd(), "migrations");
|
||||||
|
|
||||||
|
const cmd = [
|
||||||
|
"docker run --rm",
|
||||||
|
`-v "${migrations}:/migrations"`,
|
||||||
|
"migrate/migrate",
|
||||||
|
"-path=/migrations",
|
||||||
|
`-database "mysql://${db.user}:${db.pass}@tcp(${db.host}:${db.port})/${db.name}"`, // Use double quotes
|
||||||
|
args,
|
||||||
|
].join(" ");
|
||||||
|
|
||||||
|
console.log(cmd);
|
||||||
|
execSync(cmd, { stdio: "inherit" });
|
||||||
33
api/scripts/seed.js
Normal file
33
api/scripts/seed.js
Normal file
@@ -0,0 +1,33 @@
|
|||||||
|
const dotenv = require("dotenv");
|
||||||
|
const path = require("path");
|
||||||
|
const mariadb = require("mariadb");
|
||||||
|
const fs = require("fs");
|
||||||
|
|
||||||
|
dotenv.config({ path: path.resolve(process.cwd(), `.env`) });
|
||||||
|
|
||||||
|
const { DB_HOST, DB_PORT, DB_USERNAME, DB_PASSWORD, DB_DATABASE, APPLICATION_ENVIRONMENT } = process.env;
|
||||||
|
|
||||||
|
//do not accidentally seed prod pls
|
||||||
|
if (APPLICATION_ENVIRONMENT !== "dev") {
|
||||||
|
console.log("PLEASE DO NOT SEED PROD!!!!");
|
||||||
|
process.exit(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
(async () => {
|
||||||
|
const conn = await mariadb.createConnection({
|
||||||
|
host: DB_HOST,
|
||||||
|
port: DB_PORT,
|
||||||
|
user: DB_USERNAME,
|
||||||
|
password: DB_PASSWORD,
|
||||||
|
database: DB_DATABASE,
|
||||||
|
multipleStatements: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
const seedFile = path.join(process.cwd(), "migrations", "seed.sql");
|
||||||
|
const sql = fs.readFileSync(seedFile, "utf8");
|
||||||
|
|
||||||
|
await conn.query(sql);
|
||||||
|
await conn.end();
|
||||||
|
|
||||||
|
console.log("Seeded");
|
||||||
|
})();
|
||||||
@@ -1,8 +1,5 @@
|
|||||||
// const mariadb = require('mariadb')
|
// const mariadb = require('mariadb')
|
||||||
import * as mariadb from 'mariadb';
|
import * as mariadb from 'mariadb';
|
||||||
const dotenv = require('dotenv')
|
|
||||||
dotenv.config();
|
|
||||||
|
|
||||||
|
|
||||||
const pool = mariadb.createPool({
|
const pool = mariadb.createPool({
|
||||||
host: process.env.DB_HOST,
|
host: process.env.DB_HOST,
|
||||||
@@ -12,7 +9,7 @@ const pool = mariadb.createPool({
|
|||||||
connectionLimit: 5,
|
connectionLimit: 5,
|
||||||
connectTimeout: 10000, // give it more breathing room
|
connectTimeout: 10000, // give it more breathing room
|
||||||
acquireTimeout: 15000,
|
acquireTimeout: 15000,
|
||||||
database: 'ranger_unit_tracker',
|
database: process.env.DB_DATABASE,
|
||||||
ssl: false,
|
ssl: false,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -1,86 +0,0 @@
|
|||||||
const dotenv = require('dotenv')
|
|
||||||
dotenv.config();
|
|
||||||
|
|
||||||
const express = require('express')
|
|
||||||
const cors = require('cors')
|
|
||||||
const morgan = require('morgan')
|
|
||||||
const app = express()
|
|
||||||
app.use(morgan('dev'))
|
|
||||||
|
|
||||||
app.use(cors({
|
|
||||||
origin: [process.env.CLIENT_URL], // your SPA origins
|
|
||||||
credentials: true
|
|
||||||
}));
|
|
||||||
|
|
||||||
app.use(express.json())
|
|
||||||
|
|
||||||
app.set('trust proxy', 1);
|
|
||||||
|
|
||||||
const port = process.env.SERVER_PORT;
|
|
||||||
|
|
||||||
//glitchtip setup
|
|
||||||
const sentry = require('@sentry/node');
|
|
||||||
if (process.env.DISABLE_GLITCHTIP === "true") {
|
|
||||||
console.log("Glitchtip disabled")
|
|
||||||
} else {
|
|
||||||
let dsn = process.env.GLITCHTIP_DSN;
|
|
||||||
let release = process.env.APPLICATION_VERSION;
|
|
||||||
let environment = process.env.APPLICATION_ENVIRONMENT;
|
|
||||||
console.log(release, environment)
|
|
||||||
sentry.init({ dsn: dsn, release: release, environment: environment });
|
|
||||||
console.log("Glitchtip initialized");
|
|
||||||
}
|
|
||||||
|
|
||||||
//session setup
|
|
||||||
const path = require('path')
|
|
||||||
const session = require('express-session')
|
|
||||||
const passport = require('passport')
|
|
||||||
const SQLiteStore = require('connect-sqlite3')(session);
|
|
||||||
|
|
||||||
app.use(session({
|
|
||||||
secret: 'whatever',
|
|
||||||
resave: false,
|
|
||||||
saveUninitialized: false,
|
|
||||||
store: new SQLiteStore({ db: 'sessions.db', dir: './' }),
|
|
||||||
cookie: {
|
|
||||||
httpOnly: true,
|
|
||||||
sameSite: 'lax',
|
|
||||||
domain: process.env.CLIENT_DOMAIN
|
|
||||||
}
|
|
||||||
}));
|
|
||||||
app.use(passport.authenticate('session'));
|
|
||||||
|
|
||||||
// Mount route modules
|
|
||||||
const applicationsRouter = require('./routes/applications');
|
|
||||||
const { memberRanks, ranks } = require('./routes/ranks');
|
|
||||||
const members = require('./routes/members');
|
|
||||||
const loaHandler = require('./routes/loa')
|
|
||||||
const { status, memberStatus } = require('./routes/statuses')
|
|
||||||
const authRouter = require('./routes/auth')
|
|
||||||
const { roles, memberRoles } = require('./routes/roles');
|
|
||||||
const { courseRouter, eventRouter } = require('./routes/course');
|
|
||||||
const { calendarRouter } = require('./routes/calendar')
|
|
||||||
const morgan = require('morgan');
|
|
||||||
const { env } = require('process');
|
|
||||||
|
|
||||||
app.use('/application', applicationsRouter);
|
|
||||||
app.use('/ranks', ranks);
|
|
||||||
app.use('/memberRanks', memberRanks);
|
|
||||||
app.use('/members', members);
|
|
||||||
app.use('/loa', loaHandler);
|
|
||||||
app.use('/status', status)
|
|
||||||
app.use('/memberStatus', memberStatus)
|
|
||||||
app.use('/roles', roles)
|
|
||||||
app.use('/memberRoles', memberRoles)
|
|
||||||
app.use('/course', courseRouter)
|
|
||||||
app.use('/courseEvent', eventRouter)
|
|
||||||
app.use('/calendar', calendarRouter)
|
|
||||||
app.use('/', authRouter)
|
|
||||||
|
|
||||||
app.get('/ping', (req, res) => {
|
|
||||||
res.status(200).json({ message: 'pong' });
|
|
||||||
});
|
|
||||||
|
|
||||||
app.listen(port, () => {
|
|
||||||
console.log(`Example app listening on port ${port} `)
|
|
||||||
})
|
|
||||||
131
api/src/index.ts
Normal file
131
api/src/index.ts
Normal file
@@ -0,0 +1,131 @@
|
|||||||
|
import dotenv = require('dotenv');
|
||||||
|
dotenv.config({ quiet: true });
|
||||||
|
|
||||||
|
import express = require('express');
|
||||||
|
import cors = require('cors');
|
||||||
|
import morgan = require('morgan');
|
||||||
|
import { logger, LogHeader, LogPayload } from './services/logging/logger';
|
||||||
|
|
||||||
|
const app = express()
|
||||||
|
|
||||||
|
app.use(morgan((tokens: morgan.TokenIndexer, req: express.Request, res: express.Response) => {
|
||||||
|
|
||||||
|
const head: LogHeader = {
|
||||||
|
type: 'http',
|
||||||
|
level: 'info',
|
||||||
|
depth: 'normal',
|
||||||
|
timestamp: new Date().toISOString(),
|
||||||
|
}
|
||||||
|
|
||||||
|
const payload: LogPayload = {
|
||||||
|
message: `${tokens.method(req, res)} ${tokens.url(req, res)}`,
|
||||||
|
// message: 'HTTP request completed',
|
||||||
|
data: {
|
||||||
|
method: tokens.method(req, res),
|
||||||
|
path: tokens.url(req, res),
|
||||||
|
status: Number(tokens.status(req, res)),
|
||||||
|
response_time_ms: Number(tokens['response-time'](req, res)),
|
||||||
|
user_id: req.user?.id,
|
||||||
|
user_name: req.user?.name,
|
||||||
|
user_agent: req.headers['user-agent'],
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.log(head.level, head.type, payload.message, payload.data, head.depth)
|
||||||
|
return '';
|
||||||
|
}, {
|
||||||
|
skip: (req: express.Request) => {
|
||||||
|
return req.originalUrl === '/members/me' || req.originalUrl === '/ping';
|
||||||
|
}
|
||||||
|
}))
|
||||||
|
|
||||||
|
app.use(cors({
|
||||||
|
origin: [process.env.CLIENT_URL], // your SPA origins
|
||||||
|
credentials: true
|
||||||
|
}));
|
||||||
|
|
||||||
|
app.use(express.json())
|
||||||
|
|
||||||
|
app.set('trust proxy', 1);
|
||||||
|
|
||||||
|
const port = process.env.SERVER_PORT;
|
||||||
|
|
||||||
|
//glitchtip setup
|
||||||
|
import sentry = require('@sentry/node');
|
||||||
|
if (process.env.DISABLE_GLITCHTIP === "true") {
|
||||||
|
logger.info('app', 'Glitchtip disabled', null, 'normal')
|
||||||
|
} else {
|
||||||
|
let dsn = process.env.GLITCHTIP_DSN;
|
||||||
|
let release = process.env.APPLICATION_VERSION;
|
||||||
|
let environment = process.env.APPLICATION_ENVIRONMENT;
|
||||||
|
sentry.init({ dsn: dsn, release: release, environment: environment, integrations: [sentry.captureConsoleIntegration({ levels: ['error'] })] });
|
||||||
|
logger.info('app', 'Glitchtip initialized', null, 'normal')
|
||||||
|
}
|
||||||
|
|
||||||
|
//session setup
|
||||||
|
import path = require('path');
|
||||||
|
// import session = require('express-session');
|
||||||
|
import session = require('express-session');
|
||||||
|
import passport = require('passport');
|
||||||
|
const SQLiteStore = require('connect-sqlite3')(session);
|
||||||
|
|
||||||
|
const cookieOptions: session.CookieOptions = {
|
||||||
|
httpOnly: true,
|
||||||
|
sameSite: 'lax',
|
||||||
|
domain: process.env.CLIENT_DOMAIN,
|
||||||
|
maxAge: 1000 * 60 * 60 * 24 * 30, //30 days
|
||||||
|
}
|
||||||
|
const sessionOptions: session.SessionOptions = {
|
||||||
|
secret: 'whatever',
|
||||||
|
resave: false,
|
||||||
|
saveUninitialized: false,
|
||||||
|
store: new SQLiteStore({ db: 'sessions.db', dir: './' }),
|
||||||
|
rolling: true,
|
||||||
|
cookie: cookieOptions
|
||||||
|
}
|
||||||
|
|
||||||
|
import { initializeDiscordIntegrations } from './services/integrations/discord';
|
||||||
|
|
||||||
|
//event bus setup
|
||||||
|
initializeDiscordIntegrations();
|
||||||
|
|
||||||
|
app.use(session(sessionOptions));
|
||||||
|
app.use(passport.authenticate('session'));
|
||||||
|
|
||||||
|
// Mount route modules
|
||||||
|
import { applicationRouter } from './routes/applications';
|
||||||
|
import { memberRanks, ranks } from './routes/ranks';
|
||||||
|
import { memberRouter } from './routes/members';
|
||||||
|
import { loaRouter } from './routes/loa';
|
||||||
|
import { status, memberStatus } from './routes/statuses';
|
||||||
|
import { authRouter } from './routes/auth';
|
||||||
|
import { roles, memberRoles } from './routes/roles';
|
||||||
|
import { courseRouter, eventRouter } from './routes/course';
|
||||||
|
import { calendarRouter } from './routes/calendar';
|
||||||
|
import { docsRouter } from './routes/docs';
|
||||||
|
import { memberUnits, units } from './routes/units';
|
||||||
|
|
||||||
|
app.use('/application', applicationRouter);
|
||||||
|
app.use('/ranks', ranks);
|
||||||
|
app.use('/memberRanks', memberRanks);
|
||||||
|
app.use('/members', memberRouter);
|
||||||
|
app.use('/loa', loaRouter);
|
||||||
|
app.use('/status', status)
|
||||||
|
app.use('/memberStatus', memberStatus)
|
||||||
|
app.use('/roles', roles)
|
||||||
|
app.use('/memberRoles', memberRoles)
|
||||||
|
app.use('/course', courseRouter)
|
||||||
|
app.use('/courseEvent', eventRouter)
|
||||||
|
app.use('/calendar', calendarRouter)
|
||||||
|
app.use('/units', units)
|
||||||
|
app.use('/memberUnits', memberUnits);
|
||||||
|
app.use('/docs', docsRouter)
|
||||||
|
app.use('/', authRouter)
|
||||||
|
|
||||||
|
app.get('/ping', (req, res) => {
|
||||||
|
res.status(200).json({ message: 'pong' });
|
||||||
|
});
|
||||||
|
|
||||||
|
app.listen(port, () => {
|
||||||
|
logger.info('app', `Example app listening on port ${port} `)
|
||||||
|
})
|
||||||
49
api/src/middleware/auth.ts
Normal file
49
api/src/middleware/auth.ts
Normal file
@@ -0,0 +1,49 @@
|
|||||||
|
import { MemberState } from "@app/shared/types/member";
|
||||||
|
import { NextFunction, Request, Response } from "express";
|
||||||
|
import { stat } from "fs";
|
||||||
|
|
||||||
|
export const requireLogin = function (req: Request, res: Response, next: NextFunction) {
|
||||||
|
if (req.user?.id)
|
||||||
|
next();
|
||||||
|
else
|
||||||
|
res.sendStatus(401)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function requireMemberState(state: MemberState) {
|
||||||
|
return function (req: Request, res: Response, next: NextFunction) {
|
||||||
|
if (req.user?.state === state)
|
||||||
|
next();
|
||||||
|
else
|
||||||
|
res.status(403).send(`You must be a ${state} of the 17th RBN to access this resource`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function requireRole(requiredRoles: string | string[]) {
|
||||||
|
// Normalize the input to always be an array of lowercase required roles
|
||||||
|
const normalizedRequiredRoles: string[] = Array.isArray(requiredRoles)
|
||||||
|
? requiredRoles.map(role => role.toLowerCase())
|
||||||
|
: [requiredRoles.toLowerCase()];
|
||||||
|
|
||||||
|
const DEV_ROLE = 'dev';
|
||||||
|
|
||||||
|
return function (req: Request, res: Response, next: NextFunction) {
|
||||||
|
if (!req.user || !req.user.roles) {
|
||||||
|
// User is not authenticated or has no roles array
|
||||||
|
return res.sendStatus(401);
|
||||||
|
}
|
||||||
|
|
||||||
|
const userRolesLowercase = req.user.roles.map(role => role.name.toLowerCase());
|
||||||
|
|
||||||
|
// Check if the user has *any* of the required roles OR the 'dev' role
|
||||||
|
const hasAccess = userRolesLowercase.some(userRole =>
|
||||||
|
userRole === DEV_ROLE || normalizedRequiredRoles.includes(userRole)
|
||||||
|
);
|
||||||
|
|
||||||
|
if (hasAccess) {
|
||||||
|
return next();
|
||||||
|
} else {
|
||||||
|
// User is authenticated but does not have the necessary permissions
|
||||||
|
return res.sendStatus(403);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -2,50 +2,137 @@ const express = require('express');
|
|||||||
const router = express.Router();
|
const router = express.Router();
|
||||||
|
|
||||||
import pool from '../db';
|
import pool from '../db';
|
||||||
import { approveApplication, createApplication, getApplicationByID, getApplicationComments, getApplicationList, getMemberApplication } from '../services/applicationService';
|
import { approveApplication, createApplication, denyApplication, getAllMemberApplications, getApplicationByID, getApplicationComments, getApplicationList, getMemberApplication } from '../services/db/applicationService';
|
||||||
import { MemberState, setUserState } from '../services/memberService';
|
import { setUserState } from '../services/db/memberService';
|
||||||
import { getRankByName, insertMemberRank } from '../services/rankService';
|
import { MemberState } from '@app/shared/types/member';
|
||||||
|
import { getRankByName, insertMemberRank } from '../services/db/rankService';
|
||||||
import { ApplicationFull, CommentRow } from "@app/shared/types/application"
|
import { ApplicationFull, CommentRow } from "@app/shared/types/application"
|
||||||
import { assignUserToStatus } from '../services/statusService';
|
import { assignUserToStatus } from '../services/db/statusService';
|
||||||
|
import { Request, response, Response } from 'express';
|
||||||
|
import { getUserRoles } from '../services/db/rolesService';
|
||||||
|
import { requireLogin, requireRole } from '../middleware/auth';
|
||||||
|
import { logger } from '../services/logging/logger';
|
||||||
|
import { audit, AuditContext } from '../services/logging/auditLog';
|
||||||
|
import { bus } from '../services/events/eventBus';
|
||||||
|
|
||||||
// POST /application
|
//get CoC
|
||||||
router.post('/', async (req, res) => {
|
router.get('/coc', async (req: Request, res: Response) => {
|
||||||
try {
|
try {
|
||||||
const App = req.body?.App || {};
|
const response = await fetch(`${process.env.DOC_HOST}/api/pages/714`, {
|
||||||
const memberID = req.user.id;
|
headers: {
|
||||||
|
Authorization: `Token ${process.env.DOC_TOKEN_ID}:${process.env.DOC_TOKEN_SECRET}`,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
const appVersion = 1;
|
if (!response.ok) {
|
||||||
|
const text = await response.text();
|
||||||
|
logger.error('app', 'Failed to fetch LOA policy from Bookstack', {
|
||||||
|
status: response.status,
|
||||||
|
statusText: response.statusText,
|
||||||
|
body: text,
|
||||||
|
});
|
||||||
|
return res.sendStatus(500);
|
||||||
|
}
|
||||||
|
|
||||||
createApplication(memberID, appVersion, JSON.stringify(App))
|
const out = await response.json();
|
||||||
setUserState(memberID, MemberState.Applicant);
|
res.status(200).json(out.html);
|
||||||
|
|
||||||
res.sendStatus(201);
|
} catch (error) {
|
||||||
} catch (err) {
|
logger.error('app', 'Error fetching LOA policy from Bookstack', {
|
||||||
console.error('Insert failed:', err);
|
error: error instanceof Error ? error.message : String(error),
|
||||||
res.status(500).json({ error: 'Failed to save application' });
|
});
|
||||||
|
res.sendStatus(500);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
||||||
|
// POST /application
|
||||||
|
router.post('/', [requireLogin], async (req: Request, res: Response) => {
|
||||||
|
const memberID = req.user.id;
|
||||||
|
const App = req.body?.App || {};
|
||||||
|
const appVersion = 1;
|
||||||
|
|
||||||
|
try {
|
||||||
|
let appID = await createApplication(memberID, appVersion, JSON.stringify(App));
|
||||||
|
|
||||||
|
await setUserState(memberID, MemberState.Applicant, "Application Submitted", memberID);
|
||||||
|
|
||||||
|
res.sendStatus(201);
|
||||||
|
|
||||||
|
audit.application('created', { actorId: memberID, targetId: appID });
|
||||||
|
|
||||||
|
bus.emit("application.create", { application: appID, member_name: req.user.name, member_discord_id: req.user.discord_id || null })
|
||||||
|
|
||||||
|
logger.info('app', 'Application Posted', {
|
||||||
|
user: memberID,
|
||||||
|
app: appID
|
||||||
|
})
|
||||||
|
} catch (err) {
|
||||||
|
logger.error(
|
||||||
|
'app',
|
||||||
|
'Failed to create application',
|
||||||
|
{
|
||||||
|
memberID,
|
||||||
|
error: err instanceof Error ? err.message : String(err),
|
||||||
|
stack: err instanceof Error ? err.stack : undefined,
|
||||||
|
}
|
||||||
|
);
|
||||||
|
res.status(500).json({ error: 'Failed to create application' });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
|
||||||
// GET /application/all
|
// GET /application/all
|
||||||
router.get('/all', async (req, res) => {
|
router.get('/all', [requireLogin, requireRole("Recruiter")], async (req, res) => {
|
||||||
try {
|
try {
|
||||||
const rows = await getApplicationList();
|
const rows = await getApplicationList();
|
||||||
res.status(200).json(rows);
|
res.status(200).json(rows);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error(err);
|
logger.error(
|
||||||
|
'app',
|
||||||
|
'Failed to get applications',
|
||||||
|
{
|
||||||
|
error: err instanceof Error ? err.message : String(err),
|
||||||
|
stack: err instanceof Error ? err.stack : undefined,
|
||||||
|
}
|
||||||
|
);
|
||||||
res.status(500);
|
res.status(500);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
router.get('/me', async (req, res) => {
|
router.get('/meList', async (req, res) => {
|
||||||
|
|
||||||
|
let userID = req.user.id;
|
||||||
|
|
||||||
|
try {
|
||||||
|
let application = await getAllMemberApplications(userID);
|
||||||
|
|
||||||
|
return res.status(200).json(application);
|
||||||
|
} catch (error) {
|
||||||
|
logger.error(
|
||||||
|
'app',
|
||||||
|
'Failed to get applications for user',
|
||||||
|
{
|
||||||
|
user: userID,
|
||||||
|
error: error instanceof Error ? error.message : String(error),
|
||||||
|
stack: error instanceof Error ? error.stack : undefined,
|
||||||
|
}
|
||||||
|
);
|
||||||
|
return res.status(500);
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
router.get('/me', [requireLogin], async (req, res) => {
|
||||||
|
|
||||||
let userID = req.user.id;
|
let userID = req.user.id;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
let application = await getMemberApplication(userID);
|
let application = await getMemberApplication(userID);
|
||||||
|
|
||||||
if (application === undefined)
|
if (application === undefined) {
|
||||||
res.sendStatus(204);
|
res.sendStatus(204);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
const comments: CommentRow[] = await getApplicationComments(application.id);
|
const comments: CommentRow[] = await getApplicationComments(application.id);
|
||||||
|
|
||||||
@@ -56,19 +143,30 @@ router.get('/me', async (req, res) => {
|
|||||||
|
|
||||||
return res.status(200).json(output);
|
return res.status(200).json(output);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Failed to load application:', error);
|
logger.error(
|
||||||
|
'app',
|
||||||
|
'Failed to load application',
|
||||||
|
{
|
||||||
|
user: userID,
|
||||||
|
error: error instanceof Error ? error.message : String(error),
|
||||||
|
stack: error instanceof Error ? error.stack : undefined,
|
||||||
|
}
|
||||||
|
);
|
||||||
return res.status(500).json(error);
|
return res.status(500).json(error);
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
// GET /application/:id
|
// GET /me/:id
|
||||||
router.get('/:id', async (req, res) => {
|
router.get('/me/:id', [requireLogin], async (req: Request, res: Response) => {
|
||||||
let appID = req.params.id;
|
let appID = Number(req.params.id);
|
||||||
console.log("HELLO")
|
let member = req.user.id;
|
||||||
try {
|
try {
|
||||||
const application = await getApplicationByID(appID);
|
const application = await getApplicationByID(appID);
|
||||||
if (application === undefined)
|
if (application === undefined)
|
||||||
return res.sendStatus(204);
|
return res.sendStatus(204);
|
||||||
|
if (application.member_id != member) {
|
||||||
|
return res.sendStatus(403);
|
||||||
|
}
|
||||||
|
|
||||||
const comments: CommentRow[] = await getApplicationComments(appID);
|
const comments: CommentRow[] = await getApplicationComments(appID);
|
||||||
|
|
||||||
@@ -78,78 +176,137 @@ router.get('/:id', async (req, res) => {
|
|||||||
}
|
}
|
||||||
return res.status(200).json(output);
|
return res.status(200).json(output);
|
||||||
}
|
}
|
||||||
catch (err) {
|
catch (error) {
|
||||||
console.error('Query failed:', err);
|
logger.error(
|
||||||
return res.status(500).json({ error: 'Failed to load application' });
|
'app',
|
||||||
|
'Failed to load application',
|
||||||
|
{
|
||||||
|
application: appID,
|
||||||
|
user: member,
|
||||||
|
error: error instanceof Error ? error.message : String(error),
|
||||||
|
stack: error instanceof Error ? error.stack : undefined,
|
||||||
|
}
|
||||||
|
);
|
||||||
|
return res.status(500);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// GET /application/:id
|
||||||
|
router.get('/:id', [requireLogin, requireRole("Recruiter")], async (req: Request, res: Response) => {
|
||||||
|
let appID = Number(req.params.id);
|
||||||
|
let asAdmin = !!req.query.admin || false;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const application = await getApplicationByID(appID);
|
||||||
|
if (application === undefined)
|
||||||
|
return res.sendStatus(204);
|
||||||
|
|
||||||
|
const comments: CommentRow[] = await getApplicationComments(appID, asAdmin);
|
||||||
|
|
||||||
|
const output: ApplicationFull = {
|
||||||
|
application,
|
||||||
|
comments,
|
||||||
|
}
|
||||||
|
return res.status(200).json(output);
|
||||||
|
}
|
||||||
|
catch (error) {
|
||||||
|
logger.error(
|
||||||
|
'app',
|
||||||
|
'Failed to load application',
|
||||||
|
{
|
||||||
|
application: appID,
|
||||||
|
error: error instanceof Error ? error.message : String(error),
|
||||||
|
stack: error instanceof Error ? error.stack : undefined,
|
||||||
|
}
|
||||||
|
);
|
||||||
|
return res.status(500);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
// POST /application/approve/:id
|
// POST /application/approve/:id
|
||||||
router.post('/approve/:id', async (req, res) => {
|
router.post('/approve/:id', [requireLogin, requireRole("Recruiter")], async (req: Request, res: Response) => {
|
||||||
const appID = req.params.id;
|
const appID = Number(req.params.id);
|
||||||
|
const approved_by = req.user.id;
|
||||||
|
|
||||||
|
const app = await getApplicationByID(appID);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const app = await getApplicationByID(appID);
|
var con = await pool.getConnection();
|
||||||
const result = await approveApplication(appID);
|
|
||||||
|
|
||||||
console.log("START");
|
con.beginTransaction();
|
||||||
console.log(app, result);
|
|
||||||
|
|
||||||
//guard against failures
|
await approveApplication(appID, approved_by, con);
|
||||||
if (result.affectedRows != 1) {
|
|
||||||
throw new Error("Something went wrong approving the application");
|
|
||||||
}
|
|
||||||
|
|
||||||
console.log(app.member_id);
|
|
||||||
//update user profile
|
//update user profile
|
||||||
await setUserState(app.member_id, MemberState.Member);
|
await setUserState(app.member_id, MemberState.Member, "Application Accepted", approved_by, con);
|
||||||
|
|
||||||
|
await con.query('CALL sp_accept_new_recruit_validation(?, ?, ?, ?)', [Number(process.env.CONFIG_ID), app.member_id, approved_by, approved_by])
|
||||||
|
|
||||||
|
con.commit();
|
||||||
|
logger.info('app', "Member application approved", {
|
||||||
|
application: app.id,
|
||||||
|
applicant: app.member_id,
|
||||||
|
approver: approved_by
|
||||||
|
})
|
||||||
|
|
||||||
|
audit.application('approved', { actorId: approved_by, targetId: appID }, { applicantId: app.member_id });
|
||||||
|
|
||||||
let nextRank = await getRankByName('Recruit')
|
|
||||||
await insertMemberRank(app.member_id, nextRank.id);
|
|
||||||
//assign user to "pending basic"
|
|
||||||
await assignUserToStatus(app.member_id, 1);
|
|
||||||
res.sendStatus(200);
|
res.sendStatus(200);
|
||||||
} catch (err) {
|
} catch (error) {
|
||||||
console.error('Approve failed:', err);
|
|
||||||
|
con.rollback();
|
||||||
|
|
||||||
|
logger.error(
|
||||||
|
'app',
|
||||||
|
'Failed to approve application',
|
||||||
|
{
|
||||||
|
application: appID,
|
||||||
|
error: error instanceof Error ? error.message : String(error),
|
||||||
|
stack: error instanceof Error ? error.stack : undefined,
|
||||||
|
}
|
||||||
|
);
|
||||||
res.status(500).json({ error: 'Failed to approve application' });
|
res.status(500).json({ error: 'Failed to approve application' });
|
||||||
|
} finally {
|
||||||
|
if (con) con.release();
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
// POST /application/deny/:id
|
// POST /application/deny/:id
|
||||||
router.post('/deny/:id', async (req, res) => {
|
router.post('/deny/:id', [requireLogin, requireRole("Recruiter")], async (req: Request, res: Response) => {
|
||||||
const appID = req.params.id;
|
const appID = Number(req.params.id);
|
||||||
|
const approver = Number(req.user.id);
|
||||||
|
|
||||||
const sql = `
|
|
||||||
UPDATE applications
|
|
||||||
SET denied_at = NOW()
|
|
||||||
WHERE id = ?
|
|
||||||
AND approved_at IS NULL
|
|
||||||
AND denied_at IS NULL
|
|
||||||
`;
|
|
||||||
try {
|
try {
|
||||||
const result = await pool.execute(sql, appID);
|
const app = await getApplicationByID(appID);
|
||||||
|
await denyApplication(appID, approver);
|
||||||
|
await setUserState(app.member_id, MemberState.Denied, "Application Denied", approver);
|
||||||
|
|
||||||
console.log(result);
|
logger.info('app', "Member application approved", {
|
||||||
|
application: app.id,
|
||||||
if (result.affectedRows === 0) {
|
applicant: app.member_id,
|
||||||
res.status(400).json('Something went wrong denying the application');
|
approver: approver
|
||||||
}
|
})
|
||||||
|
audit.application('denied', { actorId: approver, targetId: appID }, { applicantId: app.member_id });
|
||||||
if (result.affectedRows == 1) {
|
|
||||||
res.sendStatus(200);
|
res.sendStatus(200);
|
||||||
|
} catch (error) {
|
||||||
|
logger.error(
|
||||||
|
'app',
|
||||||
|
'Failed to deny application',
|
||||||
|
{
|
||||||
|
application: appID,
|
||||||
|
error: error instanceof Error ? error.message : String(error),
|
||||||
|
stack: error instanceof Error ? error.stack : undefined,
|
||||||
}
|
}
|
||||||
|
);
|
||||||
} catch (err) {
|
|
||||||
console.error('Approve failed:', err);
|
|
||||||
res.status(500).json({ error: 'Failed to deny application' });
|
res.status(500).json({ error: 'Failed to deny application' });
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
// POST /application/:id/comment
|
// POST /application/:id/comment
|
||||||
router.post('/:id/comment', async (req, res) => {
|
router.post('/:id/comment', [requireLogin], async (req: Request, res: Response) => {
|
||||||
const appID = req.params.id;
|
const appID = Number(req.params.id);
|
||||||
const data = req.body.message;
|
const data = req.body.message;
|
||||||
const user = 1;
|
const user = req.user;
|
||||||
|
|
||||||
const sql = `INSERT INTO application_comments(
|
const sql = `INSERT INTO application_comments(
|
||||||
application_id,
|
application_id,
|
||||||
@@ -158,11 +315,11 @@ router.post('/:id/comment', async (req, res) => {
|
|||||||
)
|
)
|
||||||
VALUES(?, ?, ?);`
|
VALUES(?, ?, ?);`
|
||||||
|
|
||||||
try {
|
|
||||||
const conn = await pool.getConnection();
|
|
||||||
|
|
||||||
const result = await conn.query(sql, [appID, user, data])
|
try {
|
||||||
console.log(result)
|
var conn = await pool.getConnection();
|
||||||
|
|
||||||
|
const result = await conn.query(sql, [appID, user.id, data])
|
||||||
if (result.affectedRows !== 1) {
|
if (result.affectedRows !== 1) {
|
||||||
conn.release();
|
conn.release();
|
||||||
throw new Error("Insert Failure")
|
throw new Error("Insert Failure")
|
||||||
@@ -178,12 +335,114 @@ VALUES(?, ?, ?);`
|
|||||||
INNER JOIN members AS member ON member.id = app.poster_id
|
INNER JOIN members AS member ON member.id = app.poster_id
|
||||||
WHERE app.id = ?; `;
|
WHERE app.id = ?; `;
|
||||||
const comment = await conn.query(getSQL, [result.insertId])
|
const comment = await conn.query(getSQL, [result.insertId])
|
||||||
|
|
||||||
|
audit.record('application', 'comment_added', { actorId: user.id, targetId: appID }, { commentId: Number(result.insertId) });
|
||||||
|
|
||||||
|
logger.info('app', "Application comment posted", {
|
||||||
|
application: appID,
|
||||||
|
poster: user.id,
|
||||||
|
comment: Number(result.insertId),
|
||||||
|
})
|
||||||
|
|
||||||
res.status(201).json(comment[0]);
|
res.status(201).json(comment[0]);
|
||||||
|
|
||||||
} catch (err) {
|
} catch (error) {
|
||||||
console.error('Comment failed:', err);
|
logger.error(
|
||||||
|
'app',
|
||||||
|
'Failed to post comment',
|
||||||
|
{
|
||||||
|
application: appID,
|
||||||
|
error: error instanceof Error ? error.message : String(error),
|
||||||
|
stack: error instanceof Error ? error.stack : undefined,
|
||||||
|
}
|
||||||
|
);
|
||||||
res.status(500).json({ error: 'Could not post comment' });
|
res.status(500).json({ error: 'Could not post comment' });
|
||||||
|
} finally {
|
||||||
|
conn.release();
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
module.exports = router;
|
// POST /application/:id/comment
|
||||||
|
router.post('/:id/adminComment', [requireLogin, requireRole("Recruiter")], async (req: Request, res: Response) => {
|
||||||
|
const appID = Number(req.params.id);
|
||||||
|
const data = req.body.message;
|
||||||
|
const user = req.user;
|
||||||
|
|
||||||
|
const sql = `INSERT INTO application_comments(
|
||||||
|
application_id,
|
||||||
|
poster_id,
|
||||||
|
post_content,
|
||||||
|
admin_only
|
||||||
|
)
|
||||||
|
VALUES(?, ?, ?, 1);`
|
||||||
|
|
||||||
|
try {
|
||||||
|
var conn = await pool.getConnection();
|
||||||
|
|
||||||
|
const result = await conn.query(sql, [appID, user.id, data])
|
||||||
|
if (result.affectedRows !== 1) {
|
||||||
|
conn.release();
|
||||||
|
throw new Error("Insert Failure")
|
||||||
|
}
|
||||||
|
|
||||||
|
const getSQL = `SELECT app.id AS comment_id,
|
||||||
|
app.post_content,
|
||||||
|
app.poster_id,
|
||||||
|
app.post_time,
|
||||||
|
app.last_modified,
|
||||||
|
app.admin_only,
|
||||||
|
member.name AS poster_name
|
||||||
|
FROM application_comments AS app
|
||||||
|
INNER JOIN members AS member ON member.id = app.poster_id
|
||||||
|
WHERE app.id = ?; `;
|
||||||
|
const comment = await conn.query(getSQL, [result.insertId])
|
||||||
|
audit.record('application', 'comment_added', { actorId: user.id, targetId: appID }, { commentId: Number(result.insertId) });
|
||||||
|
logger.info('app', "Admin application comment posted", {
|
||||||
|
application: appID,
|
||||||
|
poster: user.id,
|
||||||
|
comment: Number(result.insertId),
|
||||||
|
})
|
||||||
|
|
||||||
|
res.status(201).json(comment[0]);
|
||||||
|
} catch (error) {
|
||||||
|
logger.error(
|
||||||
|
'app',
|
||||||
|
'Failed to post comment',
|
||||||
|
{
|
||||||
|
application: appID,
|
||||||
|
error: error instanceof Error ? error.message : String(error),
|
||||||
|
stack: error instanceof Error ? error.stack : undefined,
|
||||||
|
}
|
||||||
|
);
|
||||||
|
res.status(500).json({ error: 'Could not post comment' });
|
||||||
|
} finally {
|
||||||
|
conn.release();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
router.post('/restart', async (req: Request, res: Response) => {
|
||||||
|
const user = req.user.id;
|
||||||
|
try {
|
||||||
|
await setUserState(user, MemberState.Guest, "Restarted Application", user);
|
||||||
|
|
||||||
|
audit.application('restarted', { actorId: user, targetId: user });
|
||||||
|
logger.info('app', "Member restarted application", {
|
||||||
|
user: user
|
||||||
|
})
|
||||||
|
|
||||||
|
res.sendStatus(200);
|
||||||
|
} catch (error) {
|
||||||
|
logger.error(
|
||||||
|
'app',
|
||||||
|
'Failed to restart application',
|
||||||
|
{
|
||||||
|
user: user,
|
||||||
|
error: error instanceof Error ? error.message : String(error),
|
||||||
|
stack: error instanceof Error ? error.stack : undefined,
|
||||||
|
}
|
||||||
|
);
|
||||||
|
res.status(500).json({ error: 'Could not rester application' });
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
export const applicationRouter = router;
|
||||||
|
|||||||
@@ -1,132 +0,0 @@
|
|||||||
const passport = require('passport');
|
|
||||||
const OpenIDConnectStrategy = require('passport-openidconnect');
|
|
||||||
const dotenv = require('dotenv');
|
|
||||||
dotenv.config();
|
|
||||||
|
|
||||||
const express = require('express');
|
|
||||||
const { param } = require('./applications');
|
|
||||||
const router = express.Router();
|
|
||||||
import pool from '../db';
|
|
||||||
const querystring = require('querystring');
|
|
||||||
|
|
||||||
|
|
||||||
passport.use(new OpenIDConnectStrategy({
|
|
||||||
issuer: process.env.AUTH_ISSUER,
|
|
||||||
authorizationURL: process.env.AUTH_DOMAIN + '/authorize/',
|
|
||||||
tokenURL: process.env.AUTH_DOMAIN + '/token/',
|
|
||||||
userInfoURL: process.env.AUTH_DOMAIN + '/userinfo/',
|
|
||||||
clientID: process.env.AUTH_CLIENT_ID,
|
|
||||||
clientSecret: process.env.AUTH_CLIENT_SECRET,
|
|
||||||
callbackURL: process.env.AUTH_REDIRECT_URI,
|
|
||||||
scope: ['openid', 'profile']
|
|
||||||
}, async function verify(issuer, sub, profile, jwtClaims, accessToken, refreshToken, params, cb) {
|
|
||||||
|
|
||||||
console.log('--- OIDC verify() called ---');
|
|
||||||
console.log('issuer:', issuer);
|
|
||||||
console.log('sub:', sub);
|
|
||||||
// console.log('profile:', JSON.stringify(profile, null, 2));
|
|
||||||
console.log('profile:', profile);
|
|
||||||
console.log('id_token claims:', JSON.stringify(jwtClaims, null, 2));
|
|
||||||
console.log('preferred_username:', jwtClaims?.preferred_username);
|
|
||||||
|
|
||||||
const con = await pool.getConnection();
|
|
||||||
try {
|
|
||||||
await con.beginTransaction();
|
|
||||||
|
|
||||||
//lookup existing user
|
|
||||||
const existing = await con.query(`SELECT id FROM members WHERE authentik_issuer = ? AND authentik_sub = ? LIMIT 1;`, [issuer, sub]);
|
|
||||||
let memberId;
|
|
||||||
//if member exists
|
|
||||||
if (existing.length > 0) {
|
|
||||||
memberId = existing[0].id;
|
|
||||||
} else {
|
|
||||||
//otherwise: create account
|
|
||||||
const username = sub.username;
|
|
||||||
|
|
||||||
const result = await con.query(
|
|
||||||
`INSERT INTO members (name, authentik_sub, authentik_issuer) VALUES (?, ?, ?)`,
|
|
||||||
[username, sub, issuer]
|
|
||||||
)
|
|
||||||
memberId = Number(result.insertId);
|
|
||||||
}
|
|
||||||
await con.commit();
|
|
||||||
return cb(null, { memberId });
|
|
||||||
} catch (error) {
|
|
||||||
await con.rollback();
|
|
||||||
return cb(error);
|
|
||||||
} finally {
|
|
||||||
con.release();
|
|
||||||
}
|
|
||||||
}));
|
|
||||||
|
|
||||||
router.get('/login', (req, res, next) => {
|
|
||||||
// Store redirect target in session if provided
|
|
||||||
req.session.redirectTo = req.query.redirect;
|
|
||||||
|
|
||||||
next();
|
|
||||||
}, passport.authenticate('openidconnect'));
|
|
||||||
|
|
||||||
// router.get('/callback', (req, res, next) => {
|
|
||||||
// passport.authenticate('openidconnect', {
|
|
||||||
// successRedirect: req.session.redirectTo,
|
|
||||||
// failureRedirect: process.env.CLIENT_URL
|
|
||||||
// })
|
|
||||||
// });
|
|
||||||
|
|
||||||
router.get('/callback', (req, res, next) => {
|
|
||||||
const redirectURI = req.session.redirectTo;
|
|
||||||
passport.authenticate('openidconnect', (err, user) => {
|
|
||||||
if (err) return next(err);
|
|
||||||
if (!user) return res.redirect(process.env.CLIENT_URL);
|
|
||||||
|
|
||||||
req.logIn(user, err => {
|
|
||||||
if (err) return next(err);
|
|
||||||
|
|
||||||
// Use redirect saved from session
|
|
||||||
const redirectTo = redirectURI || process.env.CLIENT_URL;
|
|
||||||
delete req.session.redirectTo;
|
|
||||||
return res.redirect(redirectTo);
|
|
||||||
});
|
|
||||||
})(req, res, next);
|
|
||||||
});
|
|
||||||
|
|
||||||
router.get('/logout', function (req, res, next) {
|
|
||||||
req.logout(function (err) {
|
|
||||||
if (err) { return next(err); }
|
|
||||||
var params = {
|
|
||||||
client_id: process.env.AUTH_CLIENT_ID,
|
|
||||||
returnTo: process.env.CLIENT_URL
|
|
||||||
};
|
|
||||||
res.redirect(process.env.AUTH_END_SESSION_URI + '?' + querystring.stringify(params));
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
passport.serializeUser(function (user, cb) {
|
|
||||||
process.nextTick(function () {
|
|
||||||
cb(null, user);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
passport.deserializeUser(function (user, cb) {
|
|
||||||
process.nextTick(async function () {
|
|
||||||
|
|
||||||
const memberID = user.memberId;
|
|
||||||
|
|
||||||
const con = await pool.getConnection();
|
|
||||||
|
|
||||||
var userData;
|
|
||||||
try {
|
|
||||||
let userResults = await con.query(`SELECT id, name FROM members WHERE id = ?;`, [memberID])
|
|
||||||
userData = userResults[0];
|
|
||||||
|
|
||||||
} catch (error) {
|
|
||||||
console.error(error)
|
|
||||||
} finally {
|
|
||||||
con.release();
|
|
||||||
}
|
|
||||||
return cb(null, userData);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
|
|
||||||
module.exports = router;
|
|
||||||
339
api/src/routes/auth.ts
Normal file
339
api/src/routes/auth.ts
Normal file
@@ -0,0 +1,339 @@
|
|||||||
|
const passport = require('passport');
|
||||||
|
const OpenIDConnectStrategy = require('passport-openidconnect');
|
||||||
|
|
||||||
|
const express = require('express');
|
||||||
|
const { param } = require('./applications');
|
||||||
|
const router = express.Router();
|
||||||
|
import { Role } from '@app/shared/types/roles';
|
||||||
|
import pool from '../db';
|
||||||
|
import { requireLogin } from '../middleware/auth';
|
||||||
|
import { getUserRoles } from '../services/db/rolesService';
|
||||||
|
import { getUserState, mapDiscordtoID } from '../services/db/memberService';
|
||||||
|
import { MemberState } from '@app/shared/types/member';
|
||||||
|
import { toDateTime } from '@app/shared/utils/time';
|
||||||
|
import { logger } from '../services/logging/logger';
|
||||||
|
const querystring = require('querystring');
|
||||||
|
import { performance } from 'perf_hooks';
|
||||||
|
import { CacheService } from '../services/cache/cache';
|
||||||
|
import { Strategy as CustomStrategy } from 'passport-custom';
|
||||||
|
|
||||||
|
|
||||||
|
function parseJwt(token) {
|
||||||
|
return JSON.parse(Buffer.from(token.split('.')[1], 'base64').toString());
|
||||||
|
}
|
||||||
|
|
||||||
|
const devLogin = (req: any, res: any, next: any) => {
|
||||||
|
// The object here must match what your 'verify' function returns: { memberId }
|
||||||
|
const devUser = { memberId: 1 }; // Hardcoded ID
|
||||||
|
|
||||||
|
req.logIn(devUser, (err: any) => {
|
||||||
|
if (err) return next(err);
|
||||||
|
const redirectTo = req.session.redirectTo || process.env.CLIENT_URL;
|
||||||
|
delete req.session.redirectTo;
|
||||||
|
return res.redirect(redirectTo);
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
if (process.env.AUTH_MODE === "mock") {
|
||||||
|
passport.use('mock', new CustomStrategy(async (req, done) => {
|
||||||
|
const mockUser = { memberId: 1 };
|
||||||
|
return done(null, mockUser);
|
||||||
|
}))
|
||||||
|
} else {
|
||||||
|
passport.use('oidc', new OpenIDConnectStrategy({
|
||||||
|
issuer: process.env.AUTH_ISSUER,
|
||||||
|
authorizationURL: process.env.AUTH_DOMAIN + '/authorize/',
|
||||||
|
tokenURL: process.env.AUTH_DOMAIN + '/token/',
|
||||||
|
userInfoURL: process.env.AUTH_DOMAIN + '/userinfo/',
|
||||||
|
clientID: process.env.AUTH_CLIENT_ID,
|
||||||
|
clientSecret: process.env.AUTH_CLIENT_SECRET,
|
||||||
|
callbackURL: process.env.AUTH_REDIRECT_URI,
|
||||||
|
scope: ['openid', 'profile', 'discord']
|
||||||
|
}, async function verify(issuer, sub, profile, jwtClaims, accessToken, refreshToken, params, cb) {
|
||||||
|
|
||||||
|
// console.log('--- OIDC verify() called ---');
|
||||||
|
// console.log('issuer:', issuer);
|
||||||
|
// console.log('sub:', sub);
|
||||||
|
// // console.log('discord:', discord);
|
||||||
|
// console.log('profile:', profile);
|
||||||
|
// console.log('jwt: ', parseJwt(jwtClaims));
|
||||||
|
// console.log('params:', params);
|
||||||
|
let con;
|
||||||
|
|
||||||
|
try {
|
||||||
|
con = await pool.getConnection();
|
||||||
|
|
||||||
|
await con.beginTransaction();
|
||||||
|
|
||||||
|
//lookup existing user
|
||||||
|
const existing = await con.query(`SELECT id FROM members WHERE authentik_issuer = ? AND authentik_sub = ? LIMIT 1;`, [issuer, sub]);
|
||||||
|
let memberId: number | null = null;
|
||||||
|
//if member exists
|
||||||
|
if (existing.length > 0) {
|
||||||
|
//login
|
||||||
|
memberId = existing[0].id;
|
||||||
|
logger.info('auth', `Existing member login`, {
|
||||||
|
memberId,
|
||||||
|
issuer,
|
||||||
|
});
|
||||||
|
|
||||||
|
} else {
|
||||||
|
//otherwise: create account mode
|
||||||
|
const jwt = parseJwt(jwtClaims);
|
||||||
|
const discordID = jwt.discord?.id as number;
|
||||||
|
|
||||||
|
//check if account is available to claim
|
||||||
|
if (discordID)
|
||||||
|
memberId = await mapDiscordtoID(discordID);
|
||||||
|
|
||||||
|
if (discordID && memberId) {
|
||||||
|
// claim account
|
||||||
|
const result = await con.query(
|
||||||
|
`UPDATE members SET authentik_sub = ?, authentik_issuer = ? WHERE id = ?;`,
|
||||||
|
[sub, issuer, memberId]
|
||||||
|
)
|
||||||
|
logger.info('auth', `Existing member claimed via Discord`, {
|
||||||
|
memberId,
|
||||||
|
discordID,
|
||||||
|
issuer,
|
||||||
|
});
|
||||||
|
|
||||||
|
} else {
|
||||||
|
// new account
|
||||||
|
const username = sub.username;
|
||||||
|
const result = await con.query(
|
||||||
|
`INSERT INTO members (name, authentik_sub, authentik_issuer) VALUES (?, ?, ?)`,
|
||||||
|
[username, sub, issuer]
|
||||||
|
)
|
||||||
|
memberId = Number(result.insertId);
|
||||||
|
|
||||||
|
logger.info('auth', `New member account created`, {
|
||||||
|
memberId,
|
||||||
|
username,
|
||||||
|
issuer,
|
||||||
|
});
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
await con.query(`UPDATE members SET last_login = ? WHERE id = ?`, [toDateTime(new Date()), memberId])
|
||||||
|
|
||||||
|
await con.commit();
|
||||||
|
return cb(null, { memberId });
|
||||||
|
} catch (error) {
|
||||||
|
logger.error('auth', `Authentication transaction failed`, {
|
||||||
|
issuer,
|
||||||
|
error: error instanceof Error ? error.message : String(error),
|
||||||
|
stack: error instanceof Error ? error.stack : undefined,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (con) {
|
||||||
|
try {
|
||||||
|
await con.rollback();
|
||||||
|
} catch (rollbackError) {
|
||||||
|
logger.error('auth', `Rollback failed`, {
|
||||||
|
error: rollbackError instanceof Error
|
||||||
|
? rollbackError.message
|
||||||
|
: String(rollbackError),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return cb(error);
|
||||||
|
} finally {
|
||||||
|
if (con) con.release();
|
||||||
|
}
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
router.get('/login', (req, res, next) => {
|
||||||
|
req.session.redirectTo = req.query.redirect as string;
|
||||||
|
|
||||||
|
const strategy = process.env.AUTH_MODE === 'mock' ? 'mock' : 'oidc';
|
||||||
|
|
||||||
|
passport.authenticate(strategy, {
|
||||||
|
successRedirect: (req.session.redirectTo || process.env.CLIENT_URL),
|
||||||
|
failureRedirect: '/login'
|
||||||
|
})(req, res, next);
|
||||||
|
});
|
||||||
|
|
||||||
|
router.get('/callback', (req, res, next) => {
|
||||||
|
|
||||||
|
//escape if mocked
|
||||||
|
if (process.env.AUTH_MODE === 'mock') {
|
||||||
|
return res.redirect(process.env.CLIENT_URL || '/');
|
||||||
|
}
|
||||||
|
|
||||||
|
const redirectURI = req.session.redirectTo;
|
||||||
|
passport.authenticate('oidc', (err, user) => {
|
||||||
|
if (err) return next(err);
|
||||||
|
if (!user) return res.redirect(process.env.CLIENT_URL);
|
||||||
|
|
||||||
|
req.logIn(user, err => {
|
||||||
|
if (err) return next(err);
|
||||||
|
|
||||||
|
// Use redirect saved from session
|
||||||
|
const redirectTo = redirectURI || process.env.CLIENT_URL;
|
||||||
|
delete req.session.redirectTo;
|
||||||
|
return res.redirect(redirectTo);
|
||||||
|
});
|
||||||
|
})(req, res, next);
|
||||||
|
});
|
||||||
|
|
||||||
|
router.get('/logout', [requireLogin], function (req, res, next) {
|
||||||
|
req.logout(function (err) {
|
||||||
|
|
||||||
|
if (err) { return next(err); }
|
||||||
|
|
||||||
|
req.session.destroy((err) => {
|
||||||
|
if (err) { return next(err); }
|
||||||
|
|
||||||
|
res.clearCookie('connect.sid', {
|
||||||
|
path: '/',
|
||||||
|
domain: process.env.CLIENT_DOMAIN,
|
||||||
|
httpOnly: true,
|
||||||
|
sameSite: 'lax'
|
||||||
|
});
|
||||||
|
|
||||||
|
if (process.env.AUTH_MODE === 'mock') {
|
||||||
|
return res.redirect(process.env.CLIENT_URL || '/');
|
||||||
|
}
|
||||||
|
|
||||||
|
var params = {
|
||||||
|
client_id: process.env.AUTH_CLIENT_ID,
|
||||||
|
returnTo: process.env.CLIENT_URL
|
||||||
|
};
|
||||||
|
|
||||||
|
const endSessionUri = process.env.AUTH_END_SESSION_URI;
|
||||||
|
if (endSessionUri) {
|
||||||
|
return res.redirect(endSessionUri + '?' + querystring.stringify(params));
|
||||||
|
} else {
|
||||||
|
return res.redirect(process.env.CLIENT_URL || '/');
|
||||||
|
}
|
||||||
|
})
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
passport.serializeUser(function (user, cb) {
|
||||||
|
process.nextTick(function () {
|
||||||
|
cb(null, user);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
passport.deserializeUser(function (user, cb) {
|
||||||
|
const start = performance.now();
|
||||||
|
const timings: Record<string, number> = {};
|
||||||
|
|
||||||
|
process.nextTick(async function () {
|
||||||
|
const memberID = user.memberId as number;
|
||||||
|
let con;
|
||||||
|
|
||||||
|
try {
|
||||||
|
//cache lookup
|
||||||
|
let t = performance.now();
|
||||||
|
const cachedData: UserData | undefined = userCache.Get(memberID);
|
||||||
|
timings.cache_lookup = performance.now() - t;
|
||||||
|
|
||||||
|
if (cachedData) {
|
||||||
|
timings.total = performance.now() - start;
|
||||||
|
|
||||||
|
logger.info(
|
||||||
|
'profiling',
|
||||||
|
'passport.deserializeUser (cache hit)',
|
||||||
|
{
|
||||||
|
memberId: memberID,
|
||||||
|
cache_hit: true,
|
||||||
|
source: 'cache',
|
||||||
|
total_ms: timings.total,
|
||||||
|
breakdown_ms: timings,
|
||||||
|
},
|
||||||
|
'profiling'
|
||||||
|
);
|
||||||
|
|
||||||
|
return cb(null, cachedData);
|
||||||
|
}
|
||||||
|
|
||||||
|
//cache miss, db load
|
||||||
|
t = performance.now();
|
||||||
|
con = await pool.getConnection();
|
||||||
|
timings.getConnection = performance.now() - t;
|
||||||
|
|
||||||
|
t = performance.now();
|
||||||
|
const userResults = await con.query(
|
||||||
|
`SELECT id, name, discord_id FROM members WHERE id = ?;`,
|
||||||
|
[memberID]
|
||||||
|
);
|
||||||
|
timings.memberQuery = performance.now() - t;
|
||||||
|
|
||||||
|
const userData: UserData = userResults[0];
|
||||||
|
|
||||||
|
t = performance.now();
|
||||||
|
userData.roles = await getUserRoles(memberID) || [];
|
||||||
|
timings.roles = performance.now() - t;
|
||||||
|
|
||||||
|
t = performance.now();
|
||||||
|
userData.state = await getUserState(memberID);
|
||||||
|
timings.state = performance.now() - t;
|
||||||
|
|
||||||
|
t = performance.now();
|
||||||
|
userCache.Set(userData.id, userData);
|
||||||
|
timings.cache_set = performance.now() - t;
|
||||||
|
|
||||||
|
timings.total = performance.now() - start;
|
||||||
|
|
||||||
|
logger.info(
|
||||||
|
'profiling',
|
||||||
|
'passport.deserializeUser (db load)',
|
||||||
|
{
|
||||||
|
memberId: memberID,
|
||||||
|
cache_hit: false,
|
||||||
|
source: 'db',
|
||||||
|
total_ms: timings.total,
|
||||||
|
breakdown_ms: timings,
|
||||||
|
},
|
||||||
|
'profiling'
|
||||||
|
);
|
||||||
|
|
||||||
|
return cb(null, userData);
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
logger.error(
|
||||||
|
'profiling',
|
||||||
|
'passport.deserializeUser failed',
|
||||||
|
{
|
||||||
|
memberId: memberID,
|
||||||
|
error: error instanceof Error ? error.message : String(error),
|
||||||
|
}
|
||||||
|
);
|
||||||
|
return cb(error);
|
||||||
|
} finally {
|
||||||
|
if (con) con.release();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
declare global {
|
||||||
|
namespace Express {
|
||||||
|
interface Request {
|
||||||
|
user: {
|
||||||
|
id: number;
|
||||||
|
name: string;
|
||||||
|
discord_id: string;
|
||||||
|
roles: Role[];
|
||||||
|
state: MemberState;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface UserData {
|
||||||
|
id: number;
|
||||||
|
name: string;
|
||||||
|
roles: Role[];
|
||||||
|
state: MemberState;
|
||||||
|
discord_id?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
const userCache = new CacheService<number, UserData>();
|
||||||
|
|
||||||
|
export const authRouter = router;
|
||||||
|
export const memberCache = userCache;
|
||||||
@@ -1,6 +1,10 @@
|
|||||||
import { Request, Response } from "express";
|
import { Request, Response } from "express";
|
||||||
import { createEvent, getEventAttendance, getEventDetails, getShortEventsInRange, setAttendanceStatus, setEventCancelled, updateEvent } from "../services/calendarService";
|
import { createEvent, getEventAttendance, getEventDetails, getShortEventsInRange, setAttendanceStatus, setEventCancelled, updateEvent } from "../services/db/calendarService";
|
||||||
import { CalendarAttendance, CalendarEvent } from "@app/shared/types/calendar";
|
import { CalendarAttendance, CalendarEvent } from "@app/shared/types/calendar";
|
||||||
|
import { requireLogin, requireMemberState, requireRole } from "../middleware/auth";
|
||||||
|
import { MemberState } from "@app/shared/types/member";
|
||||||
|
import { logger } from "../services/logging/logger";
|
||||||
|
import { audit } from "../services/logging/auditLog";
|
||||||
|
|
||||||
const express = require('express');
|
const express = require('express');
|
||||||
const r = express.Router();
|
const r = express.Router();
|
||||||
@@ -26,7 +30,14 @@ r.get('/', async (req, res) => {
|
|||||||
|
|
||||||
res.status(200).json(events);
|
res.status(200).json(events);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Error fetching calendar events:', error);
|
logger.error(
|
||||||
|
'app',
|
||||||
|
'Failed to get calendar events',
|
||||||
|
{
|
||||||
|
error: error instanceof Error ? error.message : String(error),
|
||||||
|
stack: error instanceof Error ? error.stack : undefined,
|
||||||
|
}
|
||||||
|
);
|
||||||
res.status(500).send('Error fetching calendar events');
|
res.status(500).send('Error fetching calendar events');
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
@@ -35,40 +46,84 @@ r.get('/upcoming', async (req, res) => {
|
|||||||
res.sendStatus(501);
|
res.sendStatus(501);
|
||||||
})
|
})
|
||||||
|
|
||||||
r.post('/:id/cancel', async (req: Request, res: Response) => {
|
r.post('/:id/cancel', [requireLogin, requireMemberState(MemberState.Member)], async (req: Request, res: Response) => {
|
||||||
|
let member = req.user.id;
|
||||||
try {
|
try {
|
||||||
const eventID = Number(req.params.id);
|
const eventID = Number(req.params.id);
|
||||||
setEventCancelled(eventID, true);
|
await setEventCancelled(eventID, true);
|
||||||
|
|
||||||
|
audit.calendar('cancelled', { actorId: member, targetId: eventID });
|
||||||
|
logger.info('app', 'Calendar event cancelled', {
|
||||||
|
event: eventID,
|
||||||
|
user: req.user.id
|
||||||
|
})
|
||||||
res.sendStatus(200);
|
res.sendStatus(200);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Error setting cancel status:', error);
|
logger.error(
|
||||||
|
'app',
|
||||||
|
'Failed to get cancel calendar event',
|
||||||
|
{
|
||||||
|
error: error instanceof Error ? error.message : String(error),
|
||||||
|
stack: error instanceof Error ? error.stack : undefined,
|
||||||
|
}
|
||||||
|
);
|
||||||
res.status(500).send('Error setting cancel status');
|
res.status(500).send('Error setting cancel status');
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
r.post('/:id/uncancel', async (req: Request, res: Response) => {
|
r.post('/:id/uncancel', [requireLogin, requireMemberState(MemberState.Member)], async (req: Request, res: Response) => {
|
||||||
|
let member = req.user.id;
|
||||||
try {
|
try {
|
||||||
const eventID = Number(req.params.id);
|
const eventID = Number(req.params.id);
|
||||||
setEventCancelled(eventID, false);
|
setEventCancelled(eventID, false);
|
||||||
|
|
||||||
|
audit.calendar('un-cancelled', { actorId: member, targetId: eventID });
|
||||||
|
logger.info('app', 'Calendar event un-cancelled', {
|
||||||
|
event: eventID,
|
||||||
|
user: req.user.id
|
||||||
|
})
|
||||||
res.sendStatus(200);
|
res.sendStatus(200);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Error setting cancel status:', error);
|
logger.error(
|
||||||
|
'app',
|
||||||
|
'Failed to uncancel calendar event',
|
||||||
|
{
|
||||||
|
error: error instanceof Error ? error.message : String(error),
|
||||||
|
stack: error instanceof Error ? error.stack : undefined,
|
||||||
|
}
|
||||||
|
);
|
||||||
res.status(500).send('Error setting cancel status');
|
res.status(500).send('Error setting cancel status');
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|
||||||
r.post('/:id/attendance', async (req: Request, res: Response) => {
|
r.post('/:id/attendance', [requireLogin, requireMemberState(MemberState.Member)], async (req: Request, res: Response) => {
|
||||||
try {
|
try {
|
||||||
let member = req.user.id;
|
let member = req.user.id;
|
||||||
let event = Number(req.params.id);
|
let event = Number(req.params.id);
|
||||||
let state = req.query.state as CalendarAttendance;
|
let state = req.query.state as CalendarAttendance;
|
||||||
setAttendanceStatus(member, event, state);
|
await setAttendanceStatus(member, event, state);
|
||||||
|
|
||||||
|
audit.calendar('attendance_set', { actorId: member, targetId: event }, { attendanceState: state });
|
||||||
|
logger.info('app', 'Member set calendar event attendance', {
|
||||||
|
event: event,
|
||||||
|
user: req.user.id,
|
||||||
|
state: state
|
||||||
|
})
|
||||||
|
|
||||||
res.sendStatus(200);
|
res.sendStatus(200);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Failed to set attendance:', error);
|
logger.error(
|
||||||
|
'app',
|
||||||
|
'Failed to set attendance',
|
||||||
|
{
|
||||||
|
error: error instanceof Error ? error.message : String(error),
|
||||||
|
stack: error instanceof Error ? error.stack : undefined,
|
||||||
|
}
|
||||||
|
);
|
||||||
res.status(500).json(error);
|
res.status(500).json(error);
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
//get event details
|
//get event details
|
||||||
r.get('/:id', async (req: Request, res: Response) => {
|
r.get('/:id', async (req: Request, res: Response) => {
|
||||||
try {
|
try {
|
||||||
@@ -77,42 +132,75 @@ r.get('/:id', async (req: Request, res: Response) => {
|
|||||||
let details: CalendarEvent = await getEventDetails(eventID);
|
let details: CalendarEvent = await getEventDetails(eventID);
|
||||||
details.eventSignups = await getEventAttendance(eventID);
|
details.eventSignups = await getEventAttendance(eventID);
|
||||||
res.status(200).json(details);
|
res.status(200).json(details);
|
||||||
} catch (err) {
|
} catch (error) {
|
||||||
console.error('Insert failed:', err);
|
logger.error(
|
||||||
res.status(500).json(err);
|
'app',
|
||||||
|
'Failed to get calendar event details',
|
||||||
|
{
|
||||||
|
error: error instanceof Error ? error.message : String(error),
|
||||||
|
stack: error instanceof Error ? error.stack : undefined,
|
||||||
|
}
|
||||||
|
);
|
||||||
|
res.status(500);
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|
||||||
//post a new calendar event
|
//post a new calendar event
|
||||||
r.post('/', async (req: Request, res: Response) => {
|
r.post('/', [requireLogin, requireMemberState(MemberState.Member)], async (req: Request, res: Response) => {
|
||||||
try {
|
try {
|
||||||
const member = req.user.id;
|
const member = req.user.id;
|
||||||
let event: CalendarEvent = req.body;
|
let event: CalendarEvent = req.body;
|
||||||
event.creator_id = member;
|
event.creator_id = member;
|
||||||
event.start = new Date(event.start);
|
event.start = new Date(event.start);
|
||||||
event.end = new Date(event.end);
|
event.end = new Date(event.end);
|
||||||
createEvent(event);
|
let eventID = await createEvent(event);
|
||||||
|
audit.calendar('event_created', { actorId: member, targetId: eventID });
|
||||||
|
logger.info('app', 'Calendar event posted', {
|
||||||
|
event: event.id,
|
||||||
|
user: req.user.id
|
||||||
|
})
|
||||||
|
|
||||||
res.sendStatus(200);
|
res.sendStatus(200);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Failed to create event:', error);
|
logger.error(
|
||||||
|
'app',
|
||||||
|
'Failed to create calendar event',
|
||||||
|
{
|
||||||
|
error: error instanceof Error ? error.message : String(error),
|
||||||
|
stack: error instanceof Error ? error.stack : undefined,
|
||||||
|
}
|
||||||
|
);
|
||||||
res.status(500).json(error);
|
res.status(500).json(error);
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
r.put('/', async (req: Request, res: Response) => {
|
r.put('/', [requireLogin, requireMemberState(MemberState.Member)], async (req: Request, res: Response) => {
|
||||||
|
let member = req.user.id;
|
||||||
try {
|
try {
|
||||||
let event: CalendarEvent = req.body;
|
let event: CalendarEvent = req.body;
|
||||||
event.start = new Date(event.start);
|
event.start = new Date(event.start);
|
||||||
event.end = new Date(event.end);
|
event.end = new Date(event.end);
|
||||||
console.log(event);
|
|
||||||
updateEvent(event);
|
updateEvent(event);
|
||||||
|
|
||||||
|
audit.calendar('event_updated', { actorId: member, targetId: event.id });
|
||||||
|
logger.info('app', 'Calendar event updated', {
|
||||||
|
event: event.id,
|
||||||
|
user: req.user.id
|
||||||
|
})
|
||||||
|
|
||||||
res.sendStatus(200);
|
res.sendStatus(200);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Failed to update event:', error);
|
logger.error(
|
||||||
|
'app',
|
||||||
|
'Failed to update calendar event',
|
||||||
|
{
|
||||||
|
error: error instanceof Error ? error.message : String(error),
|
||||||
|
stack: error instanceof Error ? error.stack : undefined,
|
||||||
|
}
|
||||||
|
);
|
||||||
res.status(500).json(error);
|
res.status(500).json(error);
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
|
export const calendarRouter = r;
|
||||||
module.exports.calendarRouter = r;
|
|
||||||
|
|||||||
@@ -1,36 +1,64 @@
|
|||||||
import { CourseAttendee, CourseEventDetails } from "@app/shared/types/course";
|
import { CourseAttendee, CourseEventDetails } from "@app/shared/types/course";
|
||||||
import { getAllCourses, getCourseEventAttendees, getCourseEventDetails, getCourseEventRoles, getCourseEvents, insertCourseEvent } from "../services/CourseSerivce";
|
import { getAllCourses, getCourseEventAttendees, getCourseEventDetails, getCourseEventRoles, getCourseEvents, insertCourseEvent } from "../services/db/CourseSerivce";
|
||||||
import { Request, Response, Router } from "express";
|
import { Request, Response, Router } from "express";
|
||||||
|
import { requireLogin, requireMemberState } from "../middleware/auth";
|
||||||
|
import { MemberState } from "@app/shared/types/member";
|
||||||
|
import { logger } from "../services/logging/logger";
|
||||||
|
import { audit } from "../services/logging/auditLog";
|
||||||
|
|
||||||
const courseRouter = Router();
|
const cr = Router();
|
||||||
const eventRouter = Router();
|
const er = Router();
|
||||||
|
|
||||||
courseRouter.get('/', async (req, res) => {
|
cr.use(requireLogin)
|
||||||
|
er.use(requireLogin)
|
||||||
|
cr.use(requireMemberState(MemberState.Member))
|
||||||
|
er.use(requireMemberState(MemberState.Member))
|
||||||
|
|
||||||
|
cr.get('/', async (req, res) => {
|
||||||
try {
|
try {
|
||||||
const courses = await getAllCourses();
|
const courses = await getAllCourses();
|
||||||
res.status(200).json(courses);
|
res.status(200).json(courses);
|
||||||
} catch (err) {
|
} catch (error) {
|
||||||
console.error('failed to fetch courses', err);
|
logger.error(
|
||||||
res.status(500).json('failed to fetch courses\n' + err);
|
'app',
|
||||||
|
'Failed to fetch courses',
|
||||||
|
{
|
||||||
|
error: error instanceof Error ? error.message : String(error),
|
||||||
|
stack: error instanceof Error ? error.stack : undefined,
|
||||||
|
}
|
||||||
|
);
|
||||||
|
res.status(500).json('failed to fetch courses');
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
courseRouter.get('/roles', async (req, res) => {
|
cr.get('/roles', async (req, res) => {
|
||||||
try {
|
try {
|
||||||
const roles = await getCourseEventRoles();
|
const roles = await getCourseEventRoles();
|
||||||
res.status(200).json(roles);
|
res.status(200).json(roles);
|
||||||
} catch (err) {
|
} catch (error) {
|
||||||
console.error('failed to fetch course roles', err);
|
logger.error(
|
||||||
res.status(500).json('failed to fetch course roles\n' + err);
|
'app',
|
||||||
|
'Failed to fetch course roles',
|
||||||
|
{
|
||||||
|
error: error instanceof Error ? error.message : String(error),
|
||||||
|
stack: error instanceof Error ? error.stack : undefined,
|
||||||
|
}
|
||||||
|
);
|
||||||
|
res.status(500).json('failed to fetch course roles');
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
eventRouter.get('/', async (req: Request, res: Response) => {
|
//get event list
|
||||||
|
er.get('/', async (req: Request, res: Response) => {
|
||||||
|
try {
|
||||||
const allowedSorts = new Map([
|
const allowedSorts = new Map([
|
||||||
["ascending", "ASC"],
|
["ascending", "ASC"],
|
||||||
["descending", "DESC"]
|
["descending", "DESC"]
|
||||||
]);
|
]);
|
||||||
|
|
||||||
|
const page = Number(req.query.page) || undefined;
|
||||||
|
const pageSize = Number(req.query.pageSize) || undefined;
|
||||||
|
|
||||||
const sort = String(req.query.sort || "").toLowerCase();
|
const sort = String(req.query.sort || "").toLowerCase();
|
||||||
const search = String(req.query.search || "").toLowerCase();
|
const search = String(req.query.search || "").toLowerCase();
|
||||||
if (!allowedSorts.has(sort)) {
|
if (!allowedSorts.has(sort)) {
|
||||||
@@ -41,49 +69,79 @@ eventRouter.get('/', async (req: Request, res: Response) => {
|
|||||||
|
|
||||||
const sortDir = allowedSorts.get(sort);
|
const sortDir = allowedSorts.get(sort);
|
||||||
|
|
||||||
try {
|
let events = await getCourseEvents(sortDir, search, page, pageSize);
|
||||||
let events = await getCourseEvents(sortDir, search);
|
|
||||||
res.status(200).json(events);
|
res.status(200).json(events);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('failed to fetch reports', error);
|
logger.error(
|
||||||
|
'app',
|
||||||
|
'Failed to fetch course events',
|
||||||
|
{
|
||||||
|
error: error instanceof Error ? error.message : String(error),
|
||||||
|
stack: error instanceof Error ? error.stack : undefined,
|
||||||
|
}
|
||||||
|
);
|
||||||
res.status(500).json(error);
|
res.status(500).json(error);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
eventRouter.get('/:id', async (req: Request, res: Response) => {
|
er.get('/:id', async (req: Request, res: Response) => {
|
||||||
try {
|
try {
|
||||||
let out = await getCourseEventDetails(Number(req.params.id));
|
let out = await getCourseEventDetails(Number(req.params.id));
|
||||||
res.status(200).json(out);
|
res.status(200).json(out);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('failed to fetch report', error);
|
logger.error(
|
||||||
|
'app',
|
||||||
|
'Failed to fetch course event',
|
||||||
|
{
|
||||||
|
error: error instanceof Error ? error.message : String(error),
|
||||||
|
stack: error instanceof Error ? error.stack : undefined,
|
||||||
|
}
|
||||||
|
);
|
||||||
res.status(500).json(error);
|
res.status(500).json(error);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
eventRouter.get('/attendees/:id', async (req: Request, res: Response) => {
|
er.get('/attendees/:id', async (req: Request, res: Response) => {
|
||||||
try {
|
try {
|
||||||
const attendees: CourseAttendee[] = await getCourseEventAttendees(Number(req.params.id));
|
const attendees: CourseAttendee[] = await getCourseEventAttendees(Number(req.params.id));
|
||||||
res.status(200).json(attendees);
|
res.status(200).json(attendees);
|
||||||
} catch (err) {
|
} catch (error) {
|
||||||
console.error('failed to fetch attendees', err);
|
logger.error(
|
||||||
res.status(500).json("failed to fetch attendees\n" + err);
|
'app',
|
||||||
|
'Failed to fetch course event attendees',
|
||||||
|
{
|
||||||
|
error: error instanceof Error ? error.message : String(error),
|
||||||
|
stack: error instanceof Error ? error.stack : undefined,
|
||||||
|
}
|
||||||
|
);
|
||||||
|
res.status(500).json("failed to fetch attendees");
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
eventRouter.post('/', async (req: Request, res: Response) => {
|
er.post('/', async (req: Request, res: Response) => {
|
||||||
const posterID: number = req.user.id;
|
const posterID: number = req.user.id;
|
||||||
try {
|
try {
|
||||||
console.log();
|
|
||||||
let data: CourseEventDetails = req.body;
|
let data: CourseEventDetails = req.body;
|
||||||
data.created_by = posterID;
|
data.created_by = posterID;
|
||||||
data.event_date = new Date(data.event_date);
|
data.event_date = new Date(data.event_date);
|
||||||
const id = await insertCourseEvent(data);
|
const id = await insertCourseEvent(data);
|
||||||
|
|
||||||
|
audit.course('report_created', { actorId: posterID, targetId: id });
|
||||||
|
logger.info('app', 'Training report posted', { user: posterID, report: id })
|
||||||
res.status(201).json(id);
|
res.status(201).json(id);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('failed to post training', error);
|
logger.error(
|
||||||
|
'app',
|
||||||
|
'Failed to post training report',
|
||||||
|
{
|
||||||
|
user: posterID,
|
||||||
|
error: error instanceof Error ? error.message : String(error),
|
||||||
|
stack: error instanceof Error ? error.stack : undefined,
|
||||||
|
}
|
||||||
|
);
|
||||||
res.status(500).json("failed to post training\n" + error)
|
res.status(500).json("failed to post training\n" + error)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
module.exports.courseRouter = courseRouter;
|
export const courseRouter = cr;
|
||||||
module.exports.eventRouter = eventRouter;
|
export const eventRouter = er;
|
||||||
|
|||||||
57
api/src/routes/docs.ts
Normal file
57
api/src/routes/docs.ts
Normal file
@@ -0,0 +1,57 @@
|
|||||||
|
const express = require('express');
|
||||||
|
const router = express.Router();
|
||||||
|
|
||||||
|
import { Request, Response } from 'express';
|
||||||
|
import { requireLogin } from '../middleware/auth';
|
||||||
|
import { logger } from '../services/logging/logger';
|
||||||
|
|
||||||
|
// GET /welcome
|
||||||
|
router.get('/welcome', [requireLogin], async (req: Request, res: Response) => {
|
||||||
|
const t0 = performance.now(); // optional profiling start
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await fetch(`${process.env.DOC_HOST}/api/pages/717`, {
|
||||||
|
headers: {
|
||||||
|
Authorization: `Token ${process.env.DOC_TOKEN_ID}:${process.env.DOC_TOKEN_SECRET}`,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
const text = await response.text();
|
||||||
|
logger.error('app', 'Failed to fetch welcome page from Bookstack', {
|
||||||
|
status: response.status,
|
||||||
|
statusText: response.statusText,
|
||||||
|
body: text,
|
||||||
|
userId: req.user?.id,
|
||||||
|
});
|
||||||
|
return res.sendStatus(500);
|
||||||
|
}
|
||||||
|
|
||||||
|
const out = await response.json();
|
||||||
|
res.status(200).json(out.html);
|
||||||
|
|
||||||
|
// optional profiling log
|
||||||
|
const duration = performance.now() - t0;
|
||||||
|
logger.info(
|
||||||
|
'profiling',
|
||||||
|
'GET /welcome completed',
|
||||||
|
{
|
||||||
|
userId: req.user?.id,
|
||||||
|
total_ms: duration,
|
||||||
|
},
|
||||||
|
'profiling'
|
||||||
|
);
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
logger.error('app', 'Error fetching welcome page from Bookstack', {
|
||||||
|
error: error instanceof Error ? error.message : String(error),
|
||||||
|
stack: error instanceof Error ? error.stack : undefined,
|
||||||
|
userId: req.user?.id,
|
||||||
|
});
|
||||||
|
res.sendStatus(500);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
export const docsRouter = router;
|
||||||
@@ -1,56 +0,0 @@
|
|||||||
const express = require('express');
|
|
||||||
const router = express.Router();
|
|
||||||
|
|
||||||
import pool from '../db';
|
|
||||||
|
|
||||||
//post a new LOA
|
|
||||||
router.post("/", async (req, res) => {
|
|
||||||
const { member_id, filed_date, start_date, end_date, reason } = req.body;
|
|
||||||
|
|
||||||
if (!member_id || !filed_date || !start_date || !end_date) {
|
|
||||||
return res.status(400).json({ error: "Missing required fields" });
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
const result = await pool.query(
|
|
||||||
`INSERT INTO leave_of_absences
|
|
||||||
(member_id, filed_date, start_date, end_date, reason)
|
|
||||||
VALUES (?, ?, ?, ?, ?)`,
|
|
||||||
[member_id, filed_date, start_date, end_date, reason]
|
|
||||||
);
|
|
||||||
res.sendStatus(201);
|
|
||||||
} catch (error) {
|
|
||||||
console.error(error);
|
|
||||||
res.status(500).send('Something went wrong', error);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
//get my current LOA
|
|
||||||
router.get("/me", async (req, res) => {
|
|
||||||
//TODO: implement current user getter
|
|
||||||
const user = 89;
|
|
||||||
|
|
||||||
try {
|
|
||||||
const result = await pool.query("SELECT * FROM leave_of_absences WHERE member_id = ?", [user])
|
|
||||||
res.status(200).json(result)
|
|
||||||
} catch (error) {
|
|
||||||
console.error(error);
|
|
||||||
res.status(500).send(error);
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
router.get('/all', async (req, res) => {
|
|
||||||
try {
|
|
||||||
const result = await pool.query(
|
|
||||||
`SELECT loa.*, members.name
|
|
||||||
FROM leave_of_absences AS loa
|
|
||||||
INNER JOIN members ON loa.member_id = members.id;
|
|
||||||
`);
|
|
||||||
res.status(200).json(result)
|
|
||||||
} catch (error) {
|
|
||||||
console.error(error);
|
|
||||||
res.status(500).send(error);
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
module.exports = router;
|
|
||||||
313
api/src/routes/loa.ts
Normal file
313
api/src/routes/loa.ts
Normal file
@@ -0,0 +1,313 @@
|
|||||||
|
const express = require('express');
|
||||||
|
const router = express.Router();
|
||||||
|
|
||||||
|
import { Request, Response } from 'express';
|
||||||
|
import pool from '../db';
|
||||||
|
import { closeLOA, createNewLOA, getAllLOA, getLOAbyID, getLoaTypes, getUserLOA, setLOAExtension } from '../services/db/loaService';
|
||||||
|
import { LOARequest } from '@app/shared/types/loa';
|
||||||
|
import { requireLogin, requireRole } from '../middleware/auth';
|
||||||
|
import { logger } from '../services/logging/logger';
|
||||||
|
import { audit } from '../services/logging/auditLog';
|
||||||
|
|
||||||
|
router.use(requireLogin);
|
||||||
|
|
||||||
|
//member posts LOA
|
||||||
|
router.post("/", async (req: Request, res: Response) => {
|
||||||
|
let LOARequest = req.body as LOARequest;
|
||||||
|
LOARequest.member_id = req.user.id;
|
||||||
|
LOARequest.created_by = req.user.id;
|
||||||
|
LOARequest.filed_date = new Date();
|
||||||
|
|
||||||
|
try {
|
||||||
|
let loaID = await createNewLOA(LOARequest);
|
||||||
|
|
||||||
|
audit.leaveOfAbsence('created', { actorId: req.user.id, targetId: loaID })
|
||||||
|
logger.info('app', 'LOA Posted', { poster: req.user.id, user: LOARequest.member_id })
|
||||||
|
res.sendStatus(201);
|
||||||
|
} catch (error) {
|
||||||
|
logger.error(
|
||||||
|
'app',
|
||||||
|
'Failed to post LOA',
|
||||||
|
{
|
||||||
|
error: error instanceof Error ? error.message : String(error),
|
||||||
|
stack: error instanceof Error ? error.stack : undefined,
|
||||||
|
}
|
||||||
|
);
|
||||||
|
res.status(500).send(error);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
//admin posts LOA
|
||||||
|
router.post("/admin", [requireRole(['17th Administrator', '17th HQ', '17th Command'])], async (req: Request, res: Response) => {
|
||||||
|
let LOARequest = req.body as LOARequest;
|
||||||
|
LOARequest.created_by = req.user.id;
|
||||||
|
LOARequest.filed_date = new Date();
|
||||||
|
try {
|
||||||
|
let loaID = await createNewLOA(LOARequest);
|
||||||
|
audit.leaveOfAbsence('admin_created', { actorId: req.user.id, targetId: loaID }, { for: LOARequest.member_id })
|
||||||
|
logger.info('app', 'LOA Posted', { poster: req.user.id, user: LOARequest.member_id })
|
||||||
|
res.sendStatus(201);
|
||||||
|
} catch (error) {
|
||||||
|
logger.error(
|
||||||
|
'app',
|
||||||
|
'Failed to post LOA',
|
||||||
|
{
|
||||||
|
error: error instanceof Error ? error.message : String(error),
|
||||||
|
stack: error instanceof Error ? error.stack : undefined,
|
||||||
|
}
|
||||||
|
); res.status(500).send(error);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
//get my current LOA
|
||||||
|
router.get("/me", async (req: Request, res: Response) => {
|
||||||
|
const user = req.user.id;
|
||||||
|
try {
|
||||||
|
const result = await getUserLOA(user);
|
||||||
|
res.status(200).json(result)
|
||||||
|
} catch (error) {
|
||||||
|
logger.error(
|
||||||
|
'app',
|
||||||
|
'Failed to get user current LOA',
|
||||||
|
{
|
||||||
|
error: error instanceof Error ? error.message : String(error),
|
||||||
|
stack: error instanceof Error ? error.stack : undefined,
|
||||||
|
}
|
||||||
|
);
|
||||||
|
res.status(500).send(error);
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
//get my LOA history
|
||||||
|
router.get("/history", async (req: Request, res: Response) => {
|
||||||
|
try {
|
||||||
|
const user = req.user.id;
|
||||||
|
|
||||||
|
const page = Number(req.query.page) || undefined;
|
||||||
|
const pageSize = Number(req.query.pageSize) || undefined;
|
||||||
|
|
||||||
|
const result = await getUserLOA(user, page, pageSize);
|
||||||
|
res.status(200).json(result)
|
||||||
|
} catch (error) {
|
||||||
|
logger.error(
|
||||||
|
'app',
|
||||||
|
'Failed to get user LOA history',
|
||||||
|
{
|
||||||
|
error: error instanceof Error ? error.message : String(error),
|
||||||
|
stack: error instanceof Error ? error.stack : undefined,
|
||||||
|
}
|
||||||
|
);
|
||||||
|
res.status(500).send(error);
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
router.get('/all', [requireRole(['17th Administrator', '17th HQ', '17th Command'])], async (req: Request, res: Response) => {
|
||||||
|
try {
|
||||||
|
const page = Number(req.query.page) || undefined;
|
||||||
|
const pageSize = Number(req.query.pageSize) || undefined;
|
||||||
|
const result = await getAllLOA(page, pageSize);
|
||||||
|
res.status(200).json(result)
|
||||||
|
} catch (error) {
|
||||||
|
logger.error(
|
||||||
|
'app',
|
||||||
|
'Failed to get full LOA history',
|
||||||
|
{
|
||||||
|
error: error instanceof Error ? error.message : String(error),
|
||||||
|
stack: error instanceof Error ? error.stack : undefined,
|
||||||
|
}
|
||||||
|
);
|
||||||
|
res.status(500).send(error);
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
router.get('/types', async (req: Request, res: Response) => {
|
||||||
|
try {
|
||||||
|
let out = await getLoaTypes();
|
||||||
|
res.status(200).json(out);
|
||||||
|
} catch (error) {
|
||||||
|
logger.error(
|
||||||
|
'app',
|
||||||
|
'Failed to get LOA types',
|
||||||
|
{
|
||||||
|
error: error instanceof Error ? error.message : String(error),
|
||||||
|
stack: error instanceof Error ? error.stack : undefined,
|
||||||
|
}
|
||||||
|
);
|
||||||
|
res.status(500).json(error);
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
router.post('/cancel/:id', async (req: Request, res: Response) => {
|
||||||
|
let closer = req.user.id;
|
||||||
|
let id = Number(req.params.id);
|
||||||
|
try {
|
||||||
|
let loa = await getLOAbyID(id);
|
||||||
|
if (loa.member_id != closer) {
|
||||||
|
return res.sendStatus(403);
|
||||||
|
}
|
||||||
|
|
||||||
|
await closeLOA(Number(req.params.id), closer);
|
||||||
|
|
||||||
|
audit.leaveOfAbsence('ended', { actorId: req.user.id, targetId: id });
|
||||||
|
logger.info('app', 'LOA Closed', { closed_by: closer, LOA: id })
|
||||||
|
|
||||||
|
res.sendStatus(200);
|
||||||
|
} catch (error) {
|
||||||
|
logger.error(
|
||||||
|
'app',
|
||||||
|
'Failed to cancel LOA',
|
||||||
|
{
|
||||||
|
error: error instanceof Error ? error.message : String(error),
|
||||||
|
stack: error instanceof Error ? error.stack : undefined,
|
||||||
|
}
|
||||||
|
);
|
||||||
|
res.status(500).json(error);
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
//TODO: enforce admin only
|
||||||
|
router.post('/adminCancel/:id', [requireRole(['17th Administrator', '17th HQ', '17th Command'])], async (req: Request, res: Response) => {
|
||||||
|
let closer = req.user.id;
|
||||||
|
try {
|
||||||
|
await closeLOA(Number(req.params.id), closer);
|
||||||
|
|
||||||
|
audit.leaveOfAbsence('admin_ended', { actorId: req.user.id, targetId: Number(req.params.id) });
|
||||||
|
logger.info('app', 'LOA Closed', { closed_by: closer, LOA: req.params.id })
|
||||||
|
|
||||||
|
res.sendStatus(200);
|
||||||
|
} catch (error) {
|
||||||
|
logger.error(
|
||||||
|
'app',
|
||||||
|
'Failed to cancel LOA',
|
||||||
|
{
|
||||||
|
error: error instanceof Error ? error.message : String(error),
|
||||||
|
stack: error instanceof Error ? error.stack : undefined,
|
||||||
|
}
|
||||||
|
);
|
||||||
|
res.status(500).json(error);
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
// extend LOA
|
||||||
|
router.post('/extend/:id', async (req: Request, res: Response) => {
|
||||||
|
const to: Date = req.body.to;
|
||||||
|
|
||||||
|
const member = req.user.id;
|
||||||
|
|
||||||
|
let LOA = await getLOAbyID(Number(req.params.id));
|
||||||
|
if (!LOA) {
|
||||||
|
return res.status(404).send("LOA not found");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (LOA.member_id !== member) {
|
||||||
|
return res.status(403).send("You do not have permission to extend this LOA");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (LOA.extended_till !== null) {
|
||||||
|
return res.status(409).send("You must contact the administration team to extend your LOA again");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!to) {
|
||||||
|
return res.status(400).send("Extension length is required");
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
await setLOAExtension(Number(req.params.id), to);
|
||||||
|
|
||||||
|
audit.leaveOfAbsence('extended', { actorId: req.user.id, targetId: Number(req.params.id) });
|
||||||
|
logger.info('app', 'LOA Extended', { extended_by: req.user.id, LOA: req.params.id })
|
||||||
|
|
||||||
|
res.sendStatus(200);
|
||||||
|
} catch (error) {
|
||||||
|
logger.error(
|
||||||
|
'app',
|
||||||
|
'Failed to extend LOA',
|
||||||
|
{
|
||||||
|
error: error instanceof Error ? error.message : String(error),
|
||||||
|
stack: error instanceof Error ? error.stack : undefined,
|
||||||
|
}
|
||||||
|
);
|
||||||
|
res.status(500).json(error);
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
// admin extend LOA
|
||||||
|
router.post('/extendAdmin/:id', [requireRole(['17th Administrator', '17th HQ', '17th Command'])], async (req: Request, res: Response) => {
|
||||||
|
const to: Date = req.body.to;
|
||||||
|
|
||||||
|
if (!to) {
|
||||||
|
res.status(400).send("Extension length is required");
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
await setLOAExtension(Number(req.params.id), to);
|
||||||
|
|
||||||
|
audit.leaveOfAbsence('extended', { actorId: req.user.id, targetId: Number(req.params.id) });
|
||||||
|
logger.info('app', 'LOA Extended', { extended_by: req.user.id, LOA: req.params.id })
|
||||||
|
|
||||||
|
res.sendStatus(200);
|
||||||
|
} catch (error) {
|
||||||
|
logger.error(
|
||||||
|
'app',
|
||||||
|
'Failed to extend LOA',
|
||||||
|
{
|
||||||
|
error: error instanceof Error ? error.message : String(error),
|
||||||
|
stack: error instanceof Error ? error.stack : undefined,
|
||||||
|
}
|
||||||
|
);
|
||||||
|
res.status(500).json(error);
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
// GET /policy
|
||||||
|
router.get('/policy', async (req: Request, res: Response) => {
|
||||||
|
const t0 = performance.now();
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await fetch(`${process.env.DOC_HOST}/api/pages/42`, {
|
||||||
|
headers: {
|
||||||
|
Authorization: `Token ${process.env.DOC_TOKEN_ID}:${process.env.DOC_TOKEN_SECRET}`,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
const text = await response.text();
|
||||||
|
|
||||||
|
logger.error('app', 'Failed to fetch policy page from Bookstack', {
|
||||||
|
pageId: 42,
|
||||||
|
status: response.status,
|
||||||
|
statusText: response.statusText,
|
||||||
|
body: text,
|
||||||
|
userId: req.user?.id,
|
||||||
|
});
|
||||||
|
|
||||||
|
return res.sendStatus(500);
|
||||||
|
}
|
||||||
|
|
||||||
|
const out = await response.json();
|
||||||
|
res.status(200).json(out.html);
|
||||||
|
|
||||||
|
logger.info(
|
||||||
|
'profiling',
|
||||||
|
'GET /policy completed',
|
||||||
|
{
|
||||||
|
pageId: 42,
|
||||||
|
total_ms: performance.now() - t0,
|
||||||
|
},
|
||||||
|
'profiling'
|
||||||
|
);
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
logger.error('app', 'Error fetching policy page from Bookstack', {
|
||||||
|
pageId: 42,
|
||||||
|
error: error instanceof Error ? error.message : String(error),
|
||||||
|
stack: error instanceof Error ? error.stack : undefined,
|
||||||
|
userId: req.user?.id,
|
||||||
|
});
|
||||||
|
|
||||||
|
res.sendStatus(500);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
|
||||||
|
export const loaRouter = router;
|
||||||
@@ -1,84 +0,0 @@
|
|||||||
const express = require('express');
|
|
||||||
const router = express.Router();
|
|
||||||
|
|
||||||
import pool from '../db';
|
|
||||||
import { getUserData } from '../services/memberService';
|
|
||||||
import { getUserRoles } from '../services/rolesService';
|
|
||||||
|
|
||||||
router.use((req, res, next) => {
|
|
||||||
console.log(req.user);
|
|
||||||
console.log('Time:', Date.now())
|
|
||||||
next()
|
|
||||||
})
|
|
||||||
|
|
||||||
//get all users
|
|
||||||
router.get('/', async (req, res) => {
|
|
||||||
try {
|
|
||||||
const result = await pool.query(
|
|
||||||
`SELECT
|
|
||||||
v.*,
|
|
||||||
CASE
|
|
||||||
WHEN EXISTS (
|
|
||||||
SELECT 1
|
|
||||||
FROM leave_of_absences l
|
|
||||||
WHERE l.member_id = v.member_id
|
|
||||||
AND l.deleted = 0
|
|
||||||
AND UTC_TIMESTAMP() BETWEEN l.start_date AND l.end_date
|
|
||||||
) THEN 1 ELSE 0
|
|
||||||
END AS on_loa
|
|
||||||
FROM view_member_rank_status_all v;`);
|
|
||||||
return res.status(200).json(result);
|
|
||||||
} catch (err) {
|
|
||||||
console.error('Error fetching users:', err);
|
|
||||||
return res.status(500).json({ error: 'Failed to fetch users' });
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
router.get('/me', async (req, res) => {
|
|
||||||
if (req.user === undefined)
|
|
||||||
return res.sendStatus(401)
|
|
||||||
|
|
||||||
try {
|
|
||||||
const { id, name, state } = await getUserData(req.user.id);
|
|
||||||
const LOAData = await pool.query(
|
|
||||||
`SELECT *
|
|
||||||
FROM leave_of_absences
|
|
||||||
WHERE member_id = ?
|
|
||||||
AND deleted = 0
|
|
||||||
AND UTC_TIMESTAMP() BETWEEN start_date AND end_date;`, req.user.id);
|
|
||||||
|
|
||||||
const roleData = await getUserRoles(req.user.id);
|
|
||||||
|
|
||||||
const userDataFull = { id, name, state, LOAData, roleData };
|
|
||||||
console.log(userDataFull)
|
|
||||||
res.status(200).json(userDataFull);
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Error fetching user data:', error);
|
|
||||||
return res.status(500).json({ error: 'Failed to fetch user data' });
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
router.get('/:id', async (req, res) => {
|
|
||||||
try {
|
|
||||||
const userId = req.params.id;
|
|
||||||
const result = await pool.query('SELECT * FROM view_member_rank_status_all WHERE id = $1;', [userId]);
|
|
||||||
if (result.rows.length === 0) {
|
|
||||||
return res.status(404).json({ error: 'User not found' });
|
|
||||||
}
|
|
||||||
return res.status(200).json(result.rows[0]);
|
|
||||||
} catch (err) {
|
|
||||||
console.error('Error fetching user:', err);
|
|
||||||
return res.status(500).json({ error: 'Failed to fetch user' });
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
//update a user's display name (stub)
|
|
||||||
router.put('/:id/displayname', async (req, res) => {
|
|
||||||
// Stub: not implemented yet
|
|
||||||
return res.status(501).json({ error: 'Update display name not implemented' });
|
|
||||||
});
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
module.exports = router;
|
|
||||||
344
api/src/routes/members.ts
Normal file
344
api/src/routes/members.ts
Normal file
@@ -0,0 +1,344 @@
|
|||||||
|
const express = require('express');
|
||||||
|
const router = express.Router();
|
||||||
|
|
||||||
|
import { Request, Response } from 'express';
|
||||||
|
import pool from '../db';
|
||||||
|
import { requireLogin, requireMemberState, requireRole } from '../middleware/auth';
|
||||||
|
import { getUserActiveLOA } from '../services/db/loaService';
|
||||||
|
import { getAllMembersLite, getMemberSettings, getMembersFull, getMembersLite, getUserData, getUserState, setUserSettings, getFilteredMembers, setUserState, getLastNonSuspendedState } from '../services/db/memberService';
|
||||||
|
import { getUserRoles, stripUserRoles } from '../services/db/rolesService';
|
||||||
|
import { memberSettings, MemberState, myData, UserCacheBustResult } from '@app/shared/types/member';
|
||||||
|
import { Discharge } from '@app/shared/schemas/dischargeSchema';
|
||||||
|
|
||||||
|
import { Performance } from 'perf_hooks';
|
||||||
|
import { logger } from '../services/logging/logger';
|
||||||
|
import { memberCache } from './auth';
|
||||||
|
import { cancelLatestRank } from '../services/db/rankService';
|
||||||
|
import { cancelLatestUnit } from '../services/db/unitService';
|
||||||
|
import { audit } from '../services/logging/auditLog';
|
||||||
|
|
||||||
|
//get all users
|
||||||
|
router.get('/', [requireLogin, requireMemberState(MemberState.Member)], async (req, res) => {
|
||||||
|
try {
|
||||||
|
const result = await pool.query(
|
||||||
|
`SELECT
|
||||||
|
v.*,
|
||||||
|
CASE
|
||||||
|
WHEN EXISTS (
|
||||||
|
SELECT 1
|
||||||
|
FROM leave_of_absences l
|
||||||
|
WHERE l.member_id = v.member_id
|
||||||
|
AND l.deleted = 0
|
||||||
|
AND UTC_TIMESTAMP() BETWEEN l.start_date AND l.end_date
|
||||||
|
) THEN 1 ELSE 0
|
||||||
|
END AS on_loa
|
||||||
|
FROM view_member_rank_unit_status_latest v;`);
|
||||||
|
return res.status(200).json(result);
|
||||||
|
} catch (error) {
|
||||||
|
logger.error(
|
||||||
|
'app',
|
||||||
|
'Failed to get all users',
|
||||||
|
{
|
||||||
|
error: error instanceof Error ? error.message : String(error),
|
||||||
|
stack: error instanceof Error ? error.stack : undefined,
|
||||||
|
}
|
||||||
|
);
|
||||||
|
return res.status(500).json({ error: 'Failed to fetch users' });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
router.get('/filtered', [requireLogin, requireMemberState(MemberState.Member)], async (req, res) => {
|
||||||
|
try {
|
||||||
|
// Extract Query Parameters
|
||||||
|
const page = parseInt(req.query.page as string) || 1;
|
||||||
|
const pageSize = parseInt(req.query.pageSize as string) || 15;
|
||||||
|
const search = req.query.search as string | undefined;
|
||||||
|
const status = req.query.status as string | undefined;
|
||||||
|
const unitId = req.query.unitId as string | undefined;
|
||||||
|
|
||||||
|
// Call the service function
|
||||||
|
const result = await getFilteredMembers(page, pageSize, search, status, unitId);
|
||||||
|
|
||||||
|
return res.status(200).json(result);
|
||||||
|
} catch (error) {
|
||||||
|
logger.error('app', 'Failed to get filtered users', {
|
||||||
|
error: error instanceof Error ? error.message : String(error),
|
||||||
|
});
|
||||||
|
return res.status(500).json({ error: 'Failed to fetch users' });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
router.get('/me', [requireLogin], async (req: Request, res) => {
|
||||||
|
if (!req.user) return res.sendStatus(401);
|
||||||
|
|
||||||
|
const routeStart = performance.now();
|
||||||
|
const timings: Record<string, number> = {};
|
||||||
|
|
||||||
|
try {
|
||||||
|
let t;
|
||||||
|
|
||||||
|
t = performance.now();
|
||||||
|
const memData = await getUserData(req.user.id);
|
||||||
|
timings.member = performance.now() - t;
|
||||||
|
|
||||||
|
t = performance.now();
|
||||||
|
const LOAData = await getUserActiveLOA(req.user.id);
|
||||||
|
timings.loa = performance.now() - t;
|
||||||
|
|
||||||
|
t = performance.now();
|
||||||
|
const memState = await getUserState(req.user.id);
|
||||||
|
timings.state = performance.now() - t;
|
||||||
|
|
||||||
|
t = performance.now();
|
||||||
|
const roleData = await getUserRoles(req.user.id);
|
||||||
|
timings.roles = performance.now() - t;
|
||||||
|
|
||||||
|
const userDataFull: myData = {
|
||||||
|
member: memData,
|
||||||
|
LOAs: LOAData,
|
||||||
|
roles: roleData,
|
||||||
|
state: memState,
|
||||||
|
};
|
||||||
|
|
||||||
|
res.status(200).json(userDataFull);
|
||||||
|
|
||||||
|
logger.info('profiling', 'GET /members/me completed', {
|
||||||
|
userId: req.user.id,
|
||||||
|
total_ms: performance.now() - routeStart,
|
||||||
|
breakdown_ms: timings,
|
||||||
|
}, 'profiling');
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
logger.error('profiling', 'GET /members/me failed', {
|
||||||
|
userId: req.user?.id,
|
||||||
|
error: error instanceof Error ? error.message : String(error),
|
||||||
|
});
|
||||||
|
|
||||||
|
return res.status(500).json({ error: 'Failed to fetch user data' });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
|
||||||
|
router.get('/settings', [requireLogin], async (req: Request, res: Response) => {
|
||||||
|
try {
|
||||||
|
let user = req.user.id;
|
||||||
|
let output = await getMemberSettings(user);
|
||||||
|
res.status(200).json(output);
|
||||||
|
} catch (error) {
|
||||||
|
logger.error(
|
||||||
|
'app',
|
||||||
|
'Failed to get member settings',
|
||||||
|
{
|
||||||
|
error: error instanceof Error ? error.message : String(error),
|
||||||
|
stack: error instanceof Error ? error.stack : undefined,
|
||||||
|
}
|
||||||
|
);
|
||||||
|
res.status(500).json(error);
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
router.put('/settings', [requireLogin], async (req: Request, res: Response) => {
|
||||||
|
try {
|
||||||
|
let user = req.user.id;
|
||||||
|
let settings: memberSettings = req.body;
|
||||||
|
await setUserSettings(user, settings);
|
||||||
|
logger.info('app', 'User updated profile settings', { user: user })
|
||||||
|
res.sendStatus(200);
|
||||||
|
} catch (error) {
|
||||||
|
logger.error(
|
||||||
|
'app',
|
||||||
|
'Failed to update user settings',
|
||||||
|
{
|
||||||
|
error: error instanceof Error ? error.message : String(error),
|
||||||
|
stack: error instanceof Error ? error.stack : undefined,
|
||||||
|
}
|
||||||
|
); res.status(500).json(error);
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
router.get('/lite', [requireLogin], async (req: Request, res: Response) => {
|
||||||
|
try {
|
||||||
|
let activeOnly = Boolean(req.query.active);
|
||||||
|
console.log(activeOnly);
|
||||||
|
let out = await getAllMembersLite(activeOnly);
|
||||||
|
res.status(200).json(out);
|
||||||
|
} catch (error) {
|
||||||
|
logger.error(
|
||||||
|
'app',
|
||||||
|
'Failed to get lite users',
|
||||||
|
{
|
||||||
|
error: error instanceof Error ? error.message : String(error),
|
||||||
|
stack: error instanceof Error ? error.stack : undefined,
|
||||||
|
}
|
||||||
|
);
|
||||||
|
res.status(500).json(error);
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
router.post('/lite/bulk', async (req: Request, res: Response) => {
|
||||||
|
try {
|
||||||
|
let ids = req.body.ids;
|
||||||
|
let out = await getMembersLite(ids);
|
||||||
|
res.status(200).json(out);
|
||||||
|
} catch (error) {
|
||||||
|
logger.error(
|
||||||
|
'app',
|
||||||
|
'Failed to get batch lite users',
|
||||||
|
{
|
||||||
|
error: error instanceof Error ? error.message : String(error),
|
||||||
|
stack: error instanceof Error ? error.stack : undefined,
|
||||||
|
}
|
||||||
|
);
|
||||||
|
res.status(500).json(error);
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
|
||||||
|
router.post('/full/bulk', async (req: Request, res: Response) => {
|
||||||
|
try {
|
||||||
|
let ids = req.body.ids;
|
||||||
|
let out = await getMembersFull(ids);
|
||||||
|
res.status(200).json(out);
|
||||||
|
} catch (error) {
|
||||||
|
logger.error(
|
||||||
|
'app',
|
||||||
|
'Failed to get batch full users',
|
||||||
|
{
|
||||||
|
error: error instanceof Error ? error.message : String(error),
|
||||||
|
stack: error instanceof Error ? error.stack : undefined,
|
||||||
|
}
|
||||||
|
); res.status(500).json(error);
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
router.post('/cache/user/bust', [requireLogin, requireMemberState(MemberState.Member), requireRole('dev')], async (req: Request, res: Response) => {
|
||||||
|
try {
|
||||||
|
const clearedEntries = memberCache.Clear();
|
||||||
|
const payload: UserCacheBustResult = {
|
||||||
|
success: true,
|
||||||
|
clearedEntries,
|
||||||
|
bustedAt: new Date().toISOString(),
|
||||||
|
};
|
||||||
|
|
||||||
|
logger.info('app', 'User cache manually busted', {
|
||||||
|
actor: req.user.id,
|
||||||
|
clearedEntries,
|
||||||
|
});
|
||||||
|
|
||||||
|
return res.status(200).json(payload);
|
||||||
|
} catch (error) {
|
||||||
|
logger.error('app', 'Failed to bust user cache', {
|
||||||
|
caller: req.user?.id,
|
||||||
|
error: error instanceof Error ? error.message : String(error),
|
||||||
|
stack: error instanceof Error ? error.stack : undefined,
|
||||||
|
});
|
||||||
|
|
||||||
|
return res.status(500).json({ error: 'Failed to bust user cache' });
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
router.get('/:id', [requireLogin], async (req, res) => {
|
||||||
|
const userId = req.params.id;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const result = await pool.query('SELECT * FROM view_member_rank_unit_status_latest WHERE id = $1;', [userId]);
|
||||||
|
if (result.rows.length === 0) {
|
||||||
|
return res.status(404).json({ error: 'User not found' });
|
||||||
|
}
|
||||||
|
return res.status(200).json(result.rows[0]);
|
||||||
|
} catch (error) {
|
||||||
|
logger.error(
|
||||||
|
'app',
|
||||||
|
'Failed to get user',
|
||||||
|
{
|
||||||
|
user: userId,
|
||||||
|
error: error instanceof Error ? error.message : String(error),
|
||||||
|
stack: error instanceof Error ? error.stack : undefined,
|
||||||
|
}
|
||||||
|
); return res.status(500).json({ error: 'Failed to fetch user' });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
//update a user's display name (stub)
|
||||||
|
router.put('/:id/displayname', async (req, res) => {
|
||||||
|
// Stub: not implemented yet
|
||||||
|
return res.status(501);
|
||||||
|
});
|
||||||
|
|
||||||
|
//discharge member
|
||||||
|
router.post('/discharge', [requireLogin, requireMemberState(MemberState.Member), requireRole("17th Administrator")], async (req: Request, res: Response) => {
|
||||||
|
try {
|
||||||
|
var con = await pool.getConnection();
|
||||||
|
let author = req.user.id;
|
||||||
|
|
||||||
|
con.beginTransaction();
|
||||||
|
|
||||||
|
var data: Discharge = req.body;
|
||||||
|
setUserState(data.userID, MemberState.Discharged, "Member Discharged", author, con, data.reason);
|
||||||
|
stripUserRoles(data.userID, con);
|
||||||
|
cancelLatestRank(data.userID, con);
|
||||||
|
cancelLatestUnit(data.userID, con);
|
||||||
|
con.commit();
|
||||||
|
memberCache.Invalidate(data.userID);
|
||||||
|
|
||||||
|
|
||||||
|
audit.member('discharged', { actorId: req.user.id, targetId: data.userID }, { reason: data.reason });
|
||||||
|
|
||||||
|
res.sendStatus(200);
|
||||||
|
} catch (error) {
|
||||||
|
logger.error('app', 'Failed to discharge user', {
|
||||||
|
data: data,
|
||||||
|
caller: req.user.id,
|
||||||
|
error: error instanceof Error ? error.message : String(error),
|
||||||
|
stack: error instanceof Error ? error.stack : undefined,
|
||||||
|
})
|
||||||
|
res.sendStatus(500);
|
||||||
|
} finally {
|
||||||
|
if (con)
|
||||||
|
con.release();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
//suspend member
|
||||||
|
router.post('/suspend', [requireLogin, requireMemberState(MemberState.Member), requireRole("17th Administrator")], async (req: Request, res: Response) => {
|
||||||
|
let author = req.user.id;
|
||||||
|
let target = Number(req.query.target);
|
||||||
|
try {
|
||||||
|
await setUserState(target, MemberState.Suspended, "Member Suspended", author, null);
|
||||||
|
|
||||||
|
audit.member('suspension_added', { actorId: author, targetId: target });
|
||||||
|
|
||||||
|
res.sendStatus(200);
|
||||||
|
} catch (error) {
|
||||||
|
logger.error('app', 'Failed to suspend user', {
|
||||||
|
target: target,
|
||||||
|
caller: req.user.id,
|
||||||
|
error: error instanceof Error ? error.message : String(error),
|
||||||
|
stack: error instanceof Error ? error.stack : undefined,
|
||||||
|
})
|
||||||
|
res.sendStatus(500);
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
//unsuspend member
|
||||||
|
router.post('/unsuspend', [requireLogin, requireMemberState(MemberState.Member), requireRole("17th Administrator")], async (req: Request, res: Response) => {
|
||||||
|
let author = req.user.id;
|
||||||
|
let target = Number(req.query.target);
|
||||||
|
try {
|
||||||
|
let prevState = await getLastNonSuspendedState(target);
|
||||||
|
await setUserState(target, prevState, "Member Suspension Removed", author, null);
|
||||||
|
audit.member('suspension_removed', { actorId: author, targetId: target });
|
||||||
|
|
||||||
|
res.sendStatus(200);
|
||||||
|
} catch (error) {
|
||||||
|
logger.error('app', 'Failed to suspend user', {
|
||||||
|
target: target,
|
||||||
|
caller: req.user.id,
|
||||||
|
error: error instanceof Error ? error.message : String(error),
|
||||||
|
stack: error instanceof Error ? error.stack : undefined,
|
||||||
|
})
|
||||||
|
res.sendStatus(500);
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
export const memberRouter = router;
|
||||||
@@ -1,31 +0,0 @@
|
|||||||
const express = require('express');
|
|
||||||
const r = express.Router();
|
|
||||||
const ur = express.Router();
|
|
||||||
const { getAllRanks, insertMemberRank } = require('../services/rankService')
|
|
||||||
|
|
||||||
//insert a new latest rank for a user
|
|
||||||
ur.post('/', async (req, res) => {3
|
|
||||||
try {
|
|
||||||
const change = req.body?.change;
|
|
||||||
await insertMemberRank(change.member_id, change.rank_id, change.date);
|
|
||||||
|
|
||||||
res.sendStatus(201);
|
|
||||||
} catch (err) {
|
|
||||||
console.error('Insert failed:', err);
|
|
||||||
res.status(500).json({ error: 'Failed to update ranks' });
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
//get all ranks
|
|
||||||
r.get('/', async (req, res) => {
|
|
||||||
try {
|
|
||||||
const ranks = await getAllRanks();
|
|
||||||
res.json(ranks);
|
|
||||||
} catch (err) {
|
|
||||||
console.error(err);
|
|
||||||
res.status(500).json({ error: 'Internal server error' });
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
module.exports.ranks = r;
|
|
||||||
module.exports.memberRanks = ur;
|
|
||||||
99
api/src/routes/ranks.ts
Normal file
99
api/src/routes/ranks.ts
Normal file
@@ -0,0 +1,99 @@
|
|||||||
|
import { MemberState } from "@app/shared/types/member";
|
||||||
|
import { requireLogin, requireMemberState, requireRole } from "../middleware/auth";
|
||||||
|
import { batchInsertMemberRank, getAllRanks, getPromotionHistorySummary, getPromotionsOnDay, insertMemberRank } from "../services/db/rankService";
|
||||||
|
import { BatchPromotion, BatchPromotionMember } from '@app/shared/schemas/promotionSchema'
|
||||||
|
|
||||||
|
import express = require('express');
|
||||||
|
import { logger } from "../services/logging/logger";
|
||||||
|
import { audit } from "../services/logging/auditLog";
|
||||||
|
const r = express.Router();
|
||||||
|
const ur = express.Router();
|
||||||
|
|
||||||
|
|
||||||
|
r.use(requireLogin)
|
||||||
|
ur.use(requireLogin)
|
||||||
|
|
||||||
|
//insert a new latest rank for a user
|
||||||
|
ur.post('/', [requireRole(["17th Command", "17th Administrator", "17th HQ"]), requireMemberState(MemberState.Member)], async (req: express.Request, res: express.Response) => {
|
||||||
|
try {
|
||||||
|
const change = req.body.promotions as BatchPromotionMember[];
|
||||||
|
const approver = req.body.approver as number;
|
||||||
|
const author = req.user.id;
|
||||||
|
if (!change) res.sendStatus(400);
|
||||||
|
|
||||||
|
await batchInsertMemberRank(change, author, approver);
|
||||||
|
|
||||||
|
audit.member('update_rank', { actorId: author, targetId: null }, { changes: change.length });
|
||||||
|
logger.info('app', 'Promotion batch submitted', { author: author })
|
||||||
|
res.sendStatus(201);
|
||||||
|
} catch (error) {
|
||||||
|
logger.error(
|
||||||
|
'app',
|
||||||
|
'Failed to post rank change',
|
||||||
|
{
|
||||||
|
error: error instanceof Error ? error.message : String(error),
|
||||||
|
stack: error instanceof Error ? error.stack : undefined,
|
||||||
|
}
|
||||||
|
);
|
||||||
|
res.status(500).json({ error: 'Failed to update ranks' });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
ur.get('/', async (req: express.Request, res: express.Response) => {
|
||||||
|
try {
|
||||||
|
const promos = await getPromotionHistorySummary();
|
||||||
|
res.status(200).json(promos);
|
||||||
|
} catch (error) {
|
||||||
|
logger.error(
|
||||||
|
'app',
|
||||||
|
'Failed to get rank change history',
|
||||||
|
{
|
||||||
|
error: error instanceof Error ? error.message : String(error),
|
||||||
|
stack: error instanceof Error ? error.stack : undefined,
|
||||||
|
}
|
||||||
|
);
|
||||||
|
res.sendStatus(500);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
ur.get('/:day', async (req: express.Request, res: express.Response) => {
|
||||||
|
try {
|
||||||
|
if (!req.params.day) res.sendStatus(400);
|
||||||
|
|
||||||
|
var day = new Date(req.params.day)
|
||||||
|
const promos = await getPromotionsOnDay(day);
|
||||||
|
res.status(200).json(promos);
|
||||||
|
} catch (error) {
|
||||||
|
logger.error(
|
||||||
|
'app',
|
||||||
|
'Failed to get rank change history on day',
|
||||||
|
{
|
||||||
|
day: day,
|
||||||
|
error: error instanceof Error ? error.message : String(error),
|
||||||
|
stack: error instanceof Error ? error.stack : undefined,
|
||||||
|
}
|
||||||
|
);
|
||||||
|
res.sendStatus(500);
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
//get all ranks
|
||||||
|
r.get('/', async (req, res) => {
|
||||||
|
try {
|
||||||
|
const ranks = await getAllRanks();
|
||||||
|
res.json(ranks);
|
||||||
|
} catch (error) {
|
||||||
|
logger.error(
|
||||||
|
'app',
|
||||||
|
'Failed to get all ranks',
|
||||||
|
{
|
||||||
|
error: error instanceof Error ? error.message : String(error),
|
||||||
|
stack: error instanceof Error ? error.stack : undefined,
|
||||||
|
}
|
||||||
|
);
|
||||||
|
res.status(500).json({ error: 'Internal server error' });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
export const ranks = r;
|
||||||
|
export const memberRanks = ur;
|
||||||
@@ -1,116 +0,0 @@
|
|||||||
const express = require('express');
|
|
||||||
const r = express.Router();
|
|
||||||
const ur = express.Router();
|
|
||||||
|
|
||||||
import pool from '../db';
|
|
||||||
import { assignUserGroup, createGroup } from '../services/rolesService';
|
|
||||||
|
|
||||||
//manually assign a member to a group
|
|
||||||
ur.post('/', async (req, res) => {
|
|
||||||
try {
|
|
||||||
const body = req.body;
|
|
||||||
|
|
||||||
assignUserGroup(body.member_id, body.role_id);
|
|
||||||
|
|
||||||
res.sendStatus(201);
|
|
||||||
} catch (err) {
|
|
||||||
console.error('Insert failed:', err);
|
|
||||||
res.status(500).json({ error: 'Failed to add to group' });
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
//manually remove member from group
|
|
||||||
ur.delete('/', async (req, res) => {
|
|
||||||
try {
|
|
||||||
const body = req.body;
|
|
||||||
console.log(body);
|
|
||||||
|
|
||||||
const sql = 'DELETE FROM members_roles WHERE member_id = ? AND role_id = ?'
|
|
||||||
await pool.query(sql, [body.member_id, body.role_id])
|
|
||||||
|
|
||||||
res.sendStatus(200);
|
|
||||||
}
|
|
||||||
catch (err) {
|
|
||||||
console.error("delete failed: ", err)
|
|
||||||
res.status(500).json({ error: 'Failed to remove from group' });
|
|
||||||
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
//get all roles
|
|
||||||
r.get('/', async (req, res) => {
|
|
||||||
try {
|
|
||||||
const con = await pool.getConnection();
|
|
||||||
|
|
||||||
// Get all roles
|
|
||||||
const roles = await con.query('SELECT * FROM roles;');
|
|
||||||
|
|
||||||
// Get all members for each role
|
|
||||||
const membersRoles = await con.query(`
|
|
||||||
SELECT mr.role_id, v.*
|
|
||||||
FROM members_roles mr
|
|
||||||
JOIN view_member_rank_status_all v ON mr.member_id = v.member_id
|
|
||||||
`);
|
|
||||||
|
|
||||||
|
|
||||||
// Group members by role_id
|
|
||||||
const roleIdToMembers = {};
|
|
||||||
for (const row of membersRoles) {
|
|
||||||
if (!roleIdToMembers[row.role_id]) roleIdToMembers[row.role_id] = [];
|
|
||||||
// Remove role_id from member object
|
|
||||||
const { role_id, ...member } = row;
|
|
||||||
roleIdToMembers[role_id].push(member);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Attach members to each role
|
|
||||||
const result = roles.map(role => ({
|
|
||||||
...role,
|
|
||||||
members: roleIdToMembers[role.id] || []
|
|
||||||
}));
|
|
||||||
|
|
||||||
con.release();
|
|
||||||
res.json(result);
|
|
||||||
} catch (err) {
|
|
||||||
console.error(err);
|
|
||||||
res.status(500).json({ error: 'Internal server error' });
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
//create a new role
|
|
||||||
r.post('/', async (req, res) => {
|
|
||||||
try {
|
|
||||||
const { name, color, description } = req.body;
|
|
||||||
console.log('Creating role:', { name, color, description });
|
|
||||||
if (!name || !color) {
|
|
||||||
return res.status(400).json({ error: 'Name and color are required' });
|
|
||||||
}
|
|
||||||
|
|
||||||
const hexColorRegex = /^#([0-9A-Fa-f]{6})$/;
|
|
||||||
if (!hexColorRegex.test(color)) {
|
|
||||||
return res.status(400).json({ error: 'Color must be a valid hex color (#ffffff)' });
|
|
||||||
}
|
|
||||||
|
|
||||||
await createGroup(name, color, description);
|
|
||||||
|
|
||||||
res.sendStatus(201);
|
|
||||||
} catch (err) {
|
|
||||||
console.error('Insert failed:', err);
|
|
||||||
res.status(500).json({ error: 'Failed to create role' });
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
r.delete('/:id', async (req, res) => {
|
|
||||||
try {
|
|
||||||
const id = req.params.id;
|
|
||||||
|
|
||||||
const sql = 'DELETE FROM roles WHERE id = ?';
|
|
||||||
const res = await pool.query(sql, [id]);
|
|
||||||
res.sendStatus(200);
|
|
||||||
} catch (error) {
|
|
||||||
console.log(error);
|
|
||||||
res.sendStatus(500);
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
module.exports.roles = r;
|
|
||||||
module.exports.memberRoles = ur;
|
|
||||||
178
api/src/routes/roles.ts
Normal file
178
api/src/routes/roles.ts
Normal file
@@ -0,0 +1,178 @@
|
|||||||
|
const express = require('express');
|
||||||
|
const r = express.Router();
|
||||||
|
const ur = express.Router();
|
||||||
|
|
||||||
|
import { MemberState } from '@app/shared/types/member';
|
||||||
|
import pool from '../db';
|
||||||
|
import { requireLogin, requireMemberState, requireRole } from '../middleware/auth';
|
||||||
|
import { assignUserGroup, createGroup, getAllRoles, getRole, getUsersWithRole } from '../services/db/rolesService';
|
||||||
|
import { Request, Response } from 'express';
|
||||||
|
import { logger } from '../services/logging/logger';
|
||||||
|
import { audit } from '../services/logging/auditLog';
|
||||||
|
|
||||||
|
r.use(requireLogin)
|
||||||
|
ur.use(requireLogin)
|
||||||
|
|
||||||
|
//manually assign a member to a group
|
||||||
|
ur.post('/', [requireMemberState(MemberState.Member), requireRole("17th Administrator")], async (req: Request, res) => {
|
||||||
|
const body = req.body;
|
||||||
|
|
||||||
|
try {
|
||||||
|
|
||||||
|
await assignUserGroup(body.member_id, body.role_id);
|
||||||
|
|
||||||
|
logger.info('app', 'User assigned role', { user: body.member_id, role: body.role_id, assigner: req.user.id })
|
||||||
|
res.sendStatus(201);
|
||||||
|
audit.roles('add_member', { actorId: req.user.id, targetId: body.role_id }, { member: body.member_id, role: body.role_id });
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
if (error?.code === 'ER_DUP_ENTRY') {
|
||||||
|
return res.status(400).json({
|
||||||
|
error: 'Member already has this role',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.error(
|
||||||
|
'app',
|
||||||
|
'Failed to assign role',
|
||||||
|
{
|
||||||
|
user: body.member_id,
|
||||||
|
role: body.role_id,
|
||||||
|
assigner: req.user.id,
|
||||||
|
error: error instanceof Error ? error.message : String(error),
|
||||||
|
stack: error instanceof Error ? error.stack : undefined,
|
||||||
|
}
|
||||||
|
);
|
||||||
|
res.status(500).json({ error: 'Failed to add to group' });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
//manually remove member from group
|
||||||
|
ur.delete('/', [requireMemberState(MemberState.Member), requireRole("17th Administrator")], async (req: Request, res: Response) => {
|
||||||
|
const body = req.body;
|
||||||
|
|
||||||
|
try {
|
||||||
|
|
||||||
|
const sql = 'DELETE FROM members_roles WHERE member_id = ? AND role_id = ?'
|
||||||
|
await pool.query(sql, [body.member_id, body.role_id])
|
||||||
|
|
||||||
|
logger.info('app', 'User removed role', { user: body.member_id, role: body.role_id, assigner: req.user.id })
|
||||||
|
audit.roles('remove_member', { actorId: req.user.id, targetId: body.role_id }, { member: body.member_id, role: body.role_id });
|
||||||
|
|
||||||
|
res.sendStatus(200);
|
||||||
|
}
|
||||||
|
catch (error) {
|
||||||
|
logger.error(
|
||||||
|
'app',
|
||||||
|
'Failed to remove role',
|
||||||
|
{
|
||||||
|
user: body.member_id,
|
||||||
|
role: body.role_id,
|
||||||
|
assigner: req.user.id,
|
||||||
|
error: error instanceof Error ? error.message : String(error),
|
||||||
|
stack: error instanceof Error ? error.stack : undefined,
|
||||||
|
}
|
||||||
|
);
|
||||||
|
res.status(500).json({ error: 'Failed to remove from group' });
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
//get all roles
|
||||||
|
r.get('/', [requireMemberState(MemberState.Member)], async (req, res) => {
|
||||||
|
try {
|
||||||
|
const roles = await getAllRoles();
|
||||||
|
|
||||||
|
res.status(200).json(roles);
|
||||||
|
} catch (error) {
|
||||||
|
logger.error(
|
||||||
|
'app',
|
||||||
|
'Failed to get all roles',
|
||||||
|
{
|
||||||
|
error: error instanceof Error ? error.message : String(error),
|
||||||
|
stack: error instanceof Error ? error.stack : undefined,
|
||||||
|
}
|
||||||
|
);
|
||||||
|
res.sendStatus(500);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
r.get('/:id/members', [requireMemberState(MemberState.Member)], async (req: Request, res: Response) => {
|
||||||
|
try {
|
||||||
|
const members = await getUsersWithRole(Number(req.params.id));
|
||||||
|
res.status(200).json(members);
|
||||||
|
} catch (error) {
|
||||||
|
logger.error(
|
||||||
|
'app',
|
||||||
|
'Failed to get role members',
|
||||||
|
{
|
||||||
|
role: req.params.id,
|
||||||
|
error: error instanceof Error ? error.message : String(error),
|
||||||
|
stack: error instanceof Error ? error.stack : undefined,
|
||||||
|
}
|
||||||
|
);
|
||||||
|
res.sendStatus(500);
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
|
||||||
|
r.get('/:id', [requireMemberState(MemberState.Member)], async (req: Request, res: Response) => {
|
||||||
|
try {
|
||||||
|
const role = await getRole(Number(req.params.id));
|
||||||
|
res.status(200).json(role);
|
||||||
|
} catch (error) {
|
||||||
|
logger.error(
|
||||||
|
'app',
|
||||||
|
'Failed to get role members',
|
||||||
|
{
|
||||||
|
role: req.params.id,
|
||||||
|
error: error instanceof Error ? error.message : String(error),
|
||||||
|
stack: error instanceof Error ? error.stack : undefined,
|
||||||
|
}
|
||||||
|
);
|
||||||
|
res.sendStatus(500);
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
//create a new role
|
||||||
|
r.post('/', [requireMemberState(MemberState.Member), requireRole("dev")], async (req, res) => {
|
||||||
|
try {
|
||||||
|
const { name, color, description } = req.body;
|
||||||
|
if (!name || !color) {
|
||||||
|
return res.status(400).json({ error: 'Name and color are required' });
|
||||||
|
}
|
||||||
|
|
||||||
|
const hexColorRegex = /^#([0-9A-Fa-f]{6})$/;
|
||||||
|
if (!hexColorRegex.test(color)) {
|
||||||
|
return res.status(400).json({ error: 'Color must be a valid hex color (#ffffff)' });
|
||||||
|
}
|
||||||
|
|
||||||
|
let out = await createGroup(name, color, description);
|
||||||
|
audit.roles('create', { actorId: req.user.id, targetId: out.id });
|
||||||
|
|
||||||
|
res.sendStatus(201);
|
||||||
|
} catch (err) {
|
||||||
|
console.error('Insert failed:', err);
|
||||||
|
res.status(500).json({ error: 'Failed to create role' });
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
r.delete('/:id', [requireMemberState(MemberState.Member), requireRole("dev")], async (req, res) => {
|
||||||
|
try {
|
||||||
|
const id = req.params.id;
|
||||||
|
|
||||||
|
const sql = 'DELETE FROM roles WHERE id = ?';
|
||||||
|
const res = await pool.query(sql, [id]);
|
||||||
|
|
||||||
|
audit.roles('delete', { actorId: req.user.id, targetId: id });
|
||||||
|
|
||||||
|
res.sendStatus(200);
|
||||||
|
} catch (error) {
|
||||||
|
console.error(error);
|
||||||
|
res.sendStatus(500);
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
export const roles = r;
|
||||||
|
export const memberRoles = ur;
|
||||||
@@ -1,11 +1,16 @@
|
|||||||
const express = require('express');
|
import express = require('express');
|
||||||
const status = express.Router();
|
const statusR = express.Router();
|
||||||
const memberStatus = express.Router();
|
const memberStatusR = express.Router();
|
||||||
|
|
||||||
import pool from '../db';
|
import pool from '../db';
|
||||||
|
import { requireLogin } from '../middleware/auth';
|
||||||
|
import { logger } from '../services/logging/logger';
|
||||||
|
|
||||||
|
statusR.use(requireLogin);
|
||||||
|
memberStatusR.use(requireLogin);
|
||||||
|
|
||||||
//insert a new latest rank for a user
|
//insert a new latest rank for a user
|
||||||
memberStatus.post('/', async (req, res) => {
|
memberStatusR.post('/', async (req, res) => {
|
||||||
// try {
|
// try {
|
||||||
// const App = req.body?.App || {};
|
// const App = req.body?.App || {};
|
||||||
|
|
||||||
@@ -30,17 +35,25 @@ memberStatus.post('/', async (req, res) => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
//get all statuses
|
//get all statuses
|
||||||
status.get('/', async (req, res) => {
|
statusR.get('/', async (req, res) => {
|
||||||
try {
|
try {
|
||||||
const result = await pool.query('SELECT * FROM statuses;');
|
const result = await pool.query('SELECT * FROM statuses;');
|
||||||
res.json(result);
|
res.json(result);
|
||||||
} catch (err) {
|
} catch (error) {
|
||||||
console.error(err);
|
logger.error(
|
||||||
res.status(500).json({ error: 'Internal server error' });
|
'app',
|
||||||
|
'Failed to get all statuses',
|
||||||
|
{
|
||||||
|
error: error instanceof Error ? error.message : String(error),
|
||||||
|
stack: error instanceof Error ? error.stack : undefined,
|
||||||
|
}
|
||||||
|
);
|
||||||
|
res.sendStatus(500);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
module.exports.status = status;
|
export const status = statusR;
|
||||||
module.exports.memberStatus = memberStatus;
|
export const memberStatus = memberStatusR;
|
||||||
|
|
||||||
|
|
||||||
// TODO, implement get all ranks route with SQL stirng SELECT id, name, short_name, category, sort_id FROM ranks;
|
// TODO, implement get all ranks route with SQL stirng SELECT id, name, short_name, category, sort_id FROM ranks;
|
||||||
73
api/src/routes/units.ts
Normal file
73
api/src/routes/units.ts
Normal file
@@ -0,0 +1,73 @@
|
|||||||
|
import express = require('express');
|
||||||
|
const unitsRouter = express.Router();
|
||||||
|
const memberUnitsRouter = express.Router();
|
||||||
|
|
||||||
|
import { Request, Response } from 'express';
|
||||||
|
|
||||||
|
import pool from '../db';
|
||||||
|
import { requireLogin, requireMemberState, requireRole } from '../middleware/auth';
|
||||||
|
import { logger } from '../services/logging/logger';
|
||||||
|
import { Unit } from '@app/shared/types/units';
|
||||||
|
import { MemberState } from '@app/shared/types/member';
|
||||||
|
import { assignNewUnit } from '../services/db/unitService';
|
||||||
|
import { audit } from '../services/logging/auditLog';
|
||||||
|
import { forceInsertMemberRank, insertMemberRank } from '../services/db/rankService';
|
||||||
|
|
||||||
|
unitsRouter.use(requireLogin);
|
||||||
|
|
||||||
|
//get all units
|
||||||
|
unitsRouter.get('/', async (req, res) => {
|
||||||
|
try {
|
||||||
|
const result: Unit[] = await pool.query('SELECT * FROM units WHERE active = 1;');
|
||||||
|
res.json(result);
|
||||||
|
} catch (error) {
|
||||||
|
logger.error(
|
||||||
|
'app',
|
||||||
|
'Failed to get all units',
|
||||||
|
{
|
||||||
|
error: error instanceof Error ? error.message : String(error),
|
||||||
|
stack: error instanceof Error ? error.stack : undefined,
|
||||||
|
}
|
||||||
|
);
|
||||||
|
res.sendStatus(500);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
memberUnitsRouter.post('/admin', [requireMemberState(MemberState.Member), requireRole("17th Administrator")], async (req: Request, res: Response) => {
|
||||||
|
const memberId = Number(req.query.memberId);
|
||||||
|
const unitId = Number(req.query.unitId);
|
||||||
|
const rankId = Number(req.query.rankId);
|
||||||
|
const reason = req.query.reason as string;
|
||||||
|
|
||||||
|
try {
|
||||||
|
|
||||||
|
if (!memberId || !unitId) {
|
||||||
|
return res.status(400).json({ error: 'memberId and unitId query parameters are required' });
|
||||||
|
}
|
||||||
|
|
||||||
|
await assignNewUnit(memberId, unitId, req.user.id, req.user.id, reason);
|
||||||
|
await forceInsertMemberRank(memberId, rankId, req.user.id, req.user.id, reason);
|
||||||
|
logger.info('app', 'Member force assigned unit', {
|
||||||
|
member: memberId,
|
||||||
|
unit: unitId,
|
||||||
|
rank: rankId,
|
||||||
|
caller: req.user.id,
|
||||||
|
});
|
||||||
|
audit.member('update_unit', { actorId: req.user.id, targetId: memberId }, { unit: unitId, rank: rankId, reason: reason });
|
||||||
|
|
||||||
|
res.sendStatus(200);
|
||||||
|
} catch (error) {
|
||||||
|
logger.error('app', 'Failed to force assign unit', {
|
||||||
|
member: memberId,
|
||||||
|
unit: unitId,
|
||||||
|
caller: req.user.id,
|
||||||
|
error: error instanceof Error ? error.message : String(error),
|
||||||
|
stack: error instanceof Error ? error.stack : undefined,
|
||||||
|
})
|
||||||
|
|
||||||
|
res.sendStatus(500);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
export const units = unitsRouter;
|
||||||
|
export const memberUnits = memberUnitsRouter;
|
||||||
@@ -1,71 +0,0 @@
|
|||||||
import { ApplicationListRow, ApplicationRow, CommentRow } from "@app/shared/types/application";
|
|
||||||
import pool from "../db";
|
|
||||||
|
|
||||||
export async function createApplication(memberID: number, appVersion: number, app: string) {
|
|
||||||
const sql = `INSERT INTO applications (member_id, app_version, app_data) VALUES (?, ?, ?);`;
|
|
||||||
const params = [memberID, appVersion, JSON.stringify(app)]
|
|
||||||
return await pool.query(sql, params);
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function getMemberApplication(memberID: number): Promise<ApplicationRow> {
|
|
||||||
const sql = `SELECT app.*,
|
|
||||||
member.name AS member_name
|
|
||||||
FROM applications AS app
|
|
||||||
INNER JOIN members AS member ON member.id = app.member_id
|
|
||||||
WHERE app.member_id = ?;`;
|
|
||||||
|
|
||||||
let app: ApplicationRow[] = await pool.query(sql, [memberID]);
|
|
||||||
return app[0];
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function getApplicationByID(appID: number): Promise<ApplicationRow> {
|
|
||||||
const sql =
|
|
||||||
`SELECT app.*,
|
|
||||||
member.name AS member_name
|
|
||||||
FROM applications AS app
|
|
||||||
INNER JOIN members AS member ON member.id = app.member_id
|
|
||||||
WHERE app.id = ?;`;
|
|
||||||
let app: ApplicationRow[] = await pool.query(sql, [appID]);
|
|
||||||
return app[0];
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function getApplicationList(): Promise<ApplicationListRow[]> {
|
|
||||||
const sql = `SELECT
|
|
||||||
member.name AS member_name,
|
|
||||||
app.id,
|
|
||||||
app.member_id,
|
|
||||||
app.submitted_at,
|
|
||||||
app.app_status
|
|
||||||
FROM applications AS app
|
|
||||||
LEFT JOIN members AS member
|
|
||||||
ON member.id = app.member_id;`
|
|
||||||
|
|
||||||
const rows: ApplicationListRow[] = await pool.query(sql);
|
|
||||||
return rows;
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function approveApplication(id) {
|
|
||||||
const sql = `
|
|
||||||
UPDATE applications
|
|
||||||
SET approved_at = NOW()
|
|
||||||
WHERE id = ?
|
|
||||||
AND approved_at IS NULL
|
|
||||||
AND denied_at IS NULL
|
|
||||||
`;
|
|
||||||
|
|
||||||
const result = await pool.execute(sql, id);
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function getApplicationComments(appID: number): Promise<CommentRow[]> {
|
|
||||||
return await pool.query(`SELECT app.id AS comment_id,
|
|
||||||
app.post_content,
|
|
||||||
app.poster_id,
|
|
||||||
app.post_time,
|
|
||||||
app.last_modified,
|
|
||||||
member.name AS poster_name
|
|
||||||
FROM application_comments AS app
|
|
||||||
INNER JOIN members AS member ON member.id = app.poster_id
|
|
||||||
WHERE app.application_id = ?;`,
|
|
||||||
[appID]);
|
|
||||||
}
|
|
||||||
29
api/src/services/cache/cache.ts
vendored
Normal file
29
api/src/services/cache/cache.ts
vendored
Normal file
@@ -0,0 +1,29 @@
|
|||||||
|
export class CacheService<Key, Value> {
|
||||||
|
private cacheMap: Map<Key, Value>
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
this.cacheMap = new Map<Key, Value>();
|
||||||
|
}
|
||||||
|
|
||||||
|
public Get(key: Key): Value {
|
||||||
|
return this.cacheMap.get(key)
|
||||||
|
}
|
||||||
|
|
||||||
|
public Set(key: Key, value: Value) {
|
||||||
|
this.cacheMap.set(key, value);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Invalidate(key: Key): boolean {
|
||||||
|
return this.cacheMap.delete(key);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Size(): number {
|
||||||
|
return this.cacheMap.size;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Clear(): number {
|
||||||
|
const priorSize = this.cacheMap.size;
|
||||||
|
this.cacheMap.clear();
|
||||||
|
return priorSize;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
import pool from "../db"
|
import pool from "../../db"
|
||||||
import { Course, CourseAttendee, CourseAttendeeRole, CourseEventDetails, CourseEventSummary, RawAttendeeRow } from "@app/shared/types/course"
|
import { Course, CourseAttendee, CourseAttendeeRole, CourseEventDetails, CourseEventSummary, RawAttendeeRow } from "@app/shared/types/course"
|
||||||
|
import { PagedData } from "@app/shared/types/pagination";
|
||||||
import { toDateTime } from "@app/shared/utils/time";
|
import { toDateTime } from "@app/shared/utils/time";
|
||||||
export async function getAllCourses(): Promise<Course[]> {
|
export async function getAllCourses(): Promise<Course[]> {
|
||||||
const sql = "SELECT * FROM courses WHERE deleted = false ORDER BY name ASC;"
|
const sql = "SELECT * FROM courses WHERE deleted = false ORDER BY name ASC;"
|
||||||
@@ -79,11 +80,13 @@ export async function getCourseEventDetails(id: number): Promise<CourseEventDeta
|
|||||||
}
|
}
|
||||||
|
|
||||||
export async function insertCourseEvent(event: CourseEventDetails): Promise<number> {
|
export async function insertCourseEvent(event: CourseEventDetails): Promise<number> {
|
||||||
console.log(event);
|
|
||||||
const con = await pool.getConnection();
|
|
||||||
try {
|
try {
|
||||||
|
var con = await pool.getConnection();
|
||||||
|
|
||||||
|
let course: Course = await getCourseByID(event.course_id);
|
||||||
|
|
||||||
await con.beginTransaction();
|
await con.beginTransaction();
|
||||||
const res = await con.query("INSERT INTO course_events (course_id, event_date, remarks, created_by) VALUES (?, ?, ?, ?);", [event.course_id, toDateTime(event.event_date), event.remarks, event.created_by]);
|
const res = await con.query("INSERT INTO course_events (course_id, event_date, remarks, created_by, hasBookwork, hasQual) VALUES (?, ?, ?, ?, ?, ?);", [event.course_id, toDateTime(event.event_date), event.remarks, event.created_by, course.hasBookwork, course.hasQual]);
|
||||||
var eventID: number = res.insertId;
|
var eventID: number = res.insertId;
|
||||||
|
|
||||||
for (const attendee of event.attendees) {
|
for (const attendee of event.attendees) {
|
||||||
@@ -98,16 +101,17 @@ export async function insertCourseEvent(event: CourseEventDetails): Promise<numb
|
|||||||
VALUES (?, ?, ?, ?, ?, ?);`, [attendee.attendee_id, eventID, attendee.attendee_role_id, attendee.passed_bookwork, attendee.passed_qual, attendee.remarks]);
|
VALUES (?, ?, ?, ?, ?, ?);`, [attendee.attendee_id, eventID, attendee.attendee_role_id, attendee.passed_bookwork, attendee.passed_qual, attendee.remarks]);
|
||||||
}
|
}
|
||||||
await con.commit();
|
await con.commit();
|
||||||
await con.release();
|
|
||||||
return Number(eventID);
|
return Number(eventID);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
await con.rollback();
|
if (con) await con.rollback();
|
||||||
await con.release();
|
|
||||||
throw error;
|
throw error;
|
||||||
|
} finally {
|
||||||
|
if (con) await con.release();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function getCourseEvents(sortDir: string, search: string = ""): Promise<CourseEventSummary[]> {
|
export async function getCourseEvents(sortDir: string, search: string = "", page = 1, pageSize = 10): Promise<PagedData<CourseEventSummary>> {
|
||||||
|
const offset = (page - 1) * pageSize;
|
||||||
|
|
||||||
let params = [];
|
let params = [];
|
||||||
let searchString = "";
|
let searchString = "";
|
||||||
@@ -133,11 +137,23 @@ export async function getCourseEvents(sortDir: string, search: string = ""): Pro
|
|||||||
LEFT JOIN members AS M
|
LEFT JOIN members AS M
|
||||||
ON E.created_by = M.id
|
ON E.created_by = M.id
|
||||||
${searchString}
|
${searchString}
|
||||||
ORDER BY E.event_date ${sortDir};`;
|
ORDER BY E.event_date ${sortDir}
|
||||||
console.log(sql)
|
LIMIT ? OFFSET ?;`;
|
||||||
console.log(params)
|
|
||||||
let events: CourseEventSummary[] = await pool.query(sql, params);
|
let countSQL = `SELECT COUNT(*) AS count
|
||||||
return events;
|
FROM course_events AS E
|
||||||
|
LEFT JOIN courses AS C
|
||||||
|
ON E.course_id = C.id
|
||||||
|
LEFT JOIN members AS M
|
||||||
|
ON E.created_by = M.id ${searchString};`
|
||||||
|
let recordCount = Number((await pool.query(countSQL, [...params]))[0].count);
|
||||||
|
let pageCount = recordCount / pageSize;
|
||||||
|
|
||||||
|
let events: CourseEventSummary[] = await pool.query(sql, [...params, pageSize, offset]);
|
||||||
|
|
||||||
|
let output: PagedData<CourseEventSummary> = { data: events, pagination: { page: page, pageSize: pageSize, total: recordCount, totalPages: pageCount } }
|
||||||
|
|
||||||
|
return output;
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function getCourseEventRoles(): Promise<CourseAttendeeRole[]> {
|
export async function getCourseEventRoles(): Promise<CourseAttendeeRole[]> {
|
||||||
127
api/src/services/db/applicationService.ts
Normal file
127
api/src/services/db/applicationService.ts
Normal file
@@ -0,0 +1,127 @@
|
|||||||
|
import { ApplicationListRow, ApplicationRow, CommentRow } from "@app/shared/types/application";
|
||||||
|
import pool from "../../db";
|
||||||
|
import { error } from "console";
|
||||||
|
import * as mariadb from 'mariadb';
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create an application in the db
|
||||||
|
* @param memberID
|
||||||
|
* @param appVersion
|
||||||
|
* @param app
|
||||||
|
* @returns ID of the created application
|
||||||
|
*/
|
||||||
|
export async function createApplication(memberID: number, appVersion: number, app: string): Promise<number> {
|
||||||
|
const sql = `INSERT INTO applications (member_id, app_version, app_data) VALUES (?, ?, ?);`;
|
||||||
|
const params = [memberID, appVersion, JSON.stringify(app)]
|
||||||
|
|
||||||
|
let result = await pool.query(sql, params);
|
||||||
|
return Number(result.insertId);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getMemberApplication(memberID: number): Promise<ApplicationRow> {
|
||||||
|
const sql = `SELECT app.*,
|
||||||
|
member.name AS member_name
|
||||||
|
FROM applications AS app
|
||||||
|
INNER JOIN members AS member ON member.id = app.member_id
|
||||||
|
WHERE app.member_id = ? ORDER BY submitted_at DESC LIMIT 1;`;
|
||||||
|
|
||||||
|
let app: ApplicationRow[] = await pool.query(sql, [memberID]);
|
||||||
|
return app[0];
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
export async function getApplicationByID(appID: number): Promise<ApplicationRow> {
|
||||||
|
const sql =
|
||||||
|
`SELECT app.*,
|
||||||
|
member.name AS member_name
|
||||||
|
FROM applications AS app
|
||||||
|
INNER JOIN members AS member ON member.id = app.member_id
|
||||||
|
WHERE app.id = ?;`;
|
||||||
|
let app: ApplicationRow[] = await pool.query(sql, [appID]);
|
||||||
|
return app[0];
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getApplicationList(page: number = 1, pageSize: number = 25): Promise<ApplicationListRow[]> {
|
||||||
|
const offset = (page - 1) * pageSize;
|
||||||
|
|
||||||
|
const sql = `SELECT
|
||||||
|
member.name AS member_name,
|
||||||
|
app.id,
|
||||||
|
app.member_id,
|
||||||
|
app.submitted_at,
|
||||||
|
app.app_status
|
||||||
|
FROM applications AS app
|
||||||
|
LEFT JOIN members AS member
|
||||||
|
ON member.id = app.member_id
|
||||||
|
ORDER BY app.submitted_at DESC
|
||||||
|
LIMIT ? OFFSET ?;`
|
||||||
|
|
||||||
|
const rows: ApplicationListRow[] = await pool.query(sql, [pageSize, offset]);
|
||||||
|
return rows;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getAllMemberApplications(memberID: number): Promise<ApplicationListRow[]> {
|
||||||
|
const sql = `SELECT
|
||||||
|
app.id,
|
||||||
|
app.member_id,
|
||||||
|
app.submitted_at,
|
||||||
|
app.app_status
|
||||||
|
FROM applications AS app WHERE app.member_id = ? ORDER BY submitted_at DESC;`;
|
||||||
|
|
||||||
|
const rows: ApplicationListRow[] = await pool.query(sql, [memberID])
|
||||||
|
return rows;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
export async function approveApplication(id: number, approver: number, con: mariadb.Connection | mariadb.Pool = pool) {
|
||||||
|
const sql = `
|
||||||
|
UPDATE applications
|
||||||
|
SET approved_at = NOW(), approved_by = ?
|
||||||
|
WHERE id = ?
|
||||||
|
AND approved_at IS NULL
|
||||||
|
AND denied_at IS NULL
|
||||||
|
`;
|
||||||
|
|
||||||
|
const result = await con.query(sql, [approver, id]);
|
||||||
|
if (result.affectedRows == 1) {
|
||||||
|
return
|
||||||
|
} else {
|
||||||
|
throw new Error(`"Something went wrong approving application with ID ${id}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function denyApplication(id: number, approver: number) {
|
||||||
|
const sql = `
|
||||||
|
UPDATE applications
|
||||||
|
SET denied_at = NOW(), approved_by = ?
|
||||||
|
WHERE id = ?
|
||||||
|
AND approved_at IS NULL
|
||||||
|
AND denied_at IS NULL
|
||||||
|
`;
|
||||||
|
|
||||||
|
const result = await pool.execute(sql, [approver, id]);
|
||||||
|
if (result.affectedRows == 1) {
|
||||||
|
return
|
||||||
|
} else {
|
||||||
|
throw new Error(`"Something went wrong denying application with ID ${id}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getApplicationComments(appID: number, admin: boolean = false): Promise<CommentRow[]> {
|
||||||
|
const excludeAdmin = ' AND app.admin_only = false';
|
||||||
|
|
||||||
|
const whereClause = `WHERE app.application_id = ?${!admin ? excludeAdmin : ''}`;
|
||||||
|
|
||||||
|
return await pool.query(`SELECT app.id AS comment_id,
|
||||||
|
app.post_content,
|
||||||
|
app.poster_id,
|
||||||
|
app.post_time,
|
||||||
|
app.last_modified,
|
||||||
|
app.admin_only,
|
||||||
|
member.name AS poster_name
|
||||||
|
FROM application_comments AS app
|
||||||
|
INNER JOIN members AS member ON member.id = app.poster_id
|
||||||
|
${whereClause}`,
|
||||||
|
[appID]);
|
||||||
|
}
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
import pool from '../db';
|
import pool from '../../db';
|
||||||
import { CalendarEventShort, CalendarSignup, CalendarEvent, CalendarAttendance } from "@app/shared/types/calendar"
|
import { CalendarEventShort, CalendarSignup, CalendarEvent, CalendarAttendance } from "@app/shared/types/calendar"
|
||||||
import { toDateTime } from "@app/shared/utils/time"
|
import { toDateTime } from "@app/shared/utils/time"
|
||||||
|
|
||||||
@@ -19,7 +19,8 @@ export async function createEvent(eventObject: Omit<CalendarEvent, 'id' | 'creat
|
|||||||
];
|
];
|
||||||
|
|
||||||
const result = await pool.query(sql, params);
|
const result = await pool.query(sql, params);
|
||||||
return { id: result.insertId, ...eventObject };
|
let id = Number(result.insertId);
|
||||||
|
return id;
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function updateEvent(eventObject: CalendarEvent) {
|
export async function updateEvent(eventObject: CalendarEvent) {
|
||||||
@@ -126,6 +127,5 @@ export async function getEventAttendance(eventID: number): Promise<CalendarSignu
|
|||||||
|
|
||||||
const sql = "CALL `sp_GetCalendarEventSignups`(?)"
|
const sql = "CALL `sp_GetCalendarEventSignups`(?)"
|
||||||
const res = await pool.query(sql, [eventID]);
|
const res = await pool.query(sql, [eventID]);
|
||||||
console.log(res[0]);
|
|
||||||
return res[0];
|
return res[0];
|
||||||
}
|
}
|
||||||
110
api/src/services/db/loaService.ts
Normal file
110
api/src/services/db/loaService.ts
Normal file
@@ -0,0 +1,110 @@
|
|||||||
|
import { toDateTime } from "@app/shared/utils/time";
|
||||||
|
import pool from "../../db";
|
||||||
|
import { LOARequest, LOAType } from '@app/shared/types/loa'
|
||||||
|
import { PagedData } from '@app/shared/types/pagination'
|
||||||
|
|
||||||
|
export async function getLoaTypes(): Promise<LOAType[]> {
|
||||||
|
return await pool.query('SELECT * FROM leave_of_absences_types;');
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getAllLOA(page = 1, pageSize = 10): Promise<PagedData<LOARequest>> {
|
||||||
|
const offset = (page - 1) * pageSize;
|
||||||
|
|
||||||
|
const sql = `
|
||||||
|
SELECT loa.*, members.name, t.name AS type_name
|
||||||
|
FROM leave_of_absences AS loa
|
||||||
|
LEFT JOIN members ON loa.member_id = members.id
|
||||||
|
LEFT JOIN leave_of_absences_types AS t ON loa.type_id = t.id
|
||||||
|
ORDER BY
|
||||||
|
CASE
|
||||||
|
WHEN loa.closed IS NULL
|
||||||
|
AND NOW() > COALESCE(loa.extended_till, loa.end_date) THEN 1
|
||||||
|
WHEN loa.closed IS NULL
|
||||||
|
AND NOW() BETWEEN loa.start_date AND COALESCE(loa.extended_till, loa.end_date) THEN 2
|
||||||
|
WHEN loa.closed IS NULL AND NOW() < loa.start_date THEN 3
|
||||||
|
WHEN loa.closed IS NOT NULL THEN 4
|
||||||
|
END,
|
||||||
|
loa.start_date DESC
|
||||||
|
LIMIT ? OFFSET ?;
|
||||||
|
`;
|
||||||
|
let loaList: LOARequest[] = await pool.query(sql, [pageSize, offset]) as LOARequest[];
|
||||||
|
|
||||||
|
let loaCount = Number((await pool.query(`SELECT COUNT(*) as count FROM leave_of_absences;`))[0].count);
|
||||||
|
let pageCount = loaCount / pageSize;
|
||||||
|
|
||||||
|
let output: PagedData<LOARequest> = { data: loaList, pagination: { page: page, pageSize: pageSize, total: loaCount, totalPages: pageCount } }
|
||||||
|
return output;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getUserLOA(userId: number, page = 1, pageSize = 10): Promise<PagedData<LOARequest>> {
|
||||||
|
|
||||||
|
const offset = (page - 1) * pageSize;
|
||||||
|
|
||||||
|
const result: LOARequest[] = await pool.query(`
|
||||||
|
SELECT loa.*, members.name, t.name AS type_name
|
||||||
|
FROM leave_of_absences AS loa
|
||||||
|
LEFT JOIN members ON loa.member_id = members.id
|
||||||
|
LEFT JOIN leave_of_absences_types AS t ON loa.type_id = t.id
|
||||||
|
WHERE member_id = ?
|
||||||
|
ORDER BY
|
||||||
|
CASE
|
||||||
|
WHEN loa.closed IS NULL
|
||||||
|
AND NOW() > COALESCE(loa.extended_till, loa.end_date) THEN 1
|
||||||
|
WHEN loa.closed IS NULL
|
||||||
|
AND NOW() BETWEEN loa.start_date AND COALESCE(loa.extended_till, loa.end_date) THEN 2
|
||||||
|
WHEN loa.closed IS NULL AND NOW() < loa.start_date THEN 3
|
||||||
|
WHEN loa.closed IS NOT NULL THEN 4
|
||||||
|
END,
|
||||||
|
loa.start_date DESC
|
||||||
|
LIMIT ? OFFSET ?;`, [userId, pageSize, offset])
|
||||||
|
|
||||||
|
let loaCount = Number((await pool.query(`SELECT COUNT(*) as count FROM leave_of_absences WHERE member_id = ?;`, [userId]))[0].count);
|
||||||
|
let pageCount = loaCount / pageSize;
|
||||||
|
let output: PagedData<LOARequest> = { data: result, pagination: { page: page, pageSize: pageSize, total: loaCount, totalPages: pageCount } }
|
||||||
|
return output;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getUserActiveLOA(userId: number): Promise<LOARequest[]> {
|
||||||
|
const sql = `SELECT *
|
||||||
|
FROM leave_of_absences
|
||||||
|
WHERE member_id = ?
|
||||||
|
AND closed IS NULL
|
||||||
|
AND UTC_TIMESTAMP() > start_date;`
|
||||||
|
const LOAData = await pool.query(sql, [userId]);
|
||||||
|
return LOAData;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function createNewLOA(data: LOARequest): Promise<number> {
|
||||||
|
const sql = `INSERT INTO leave_of_absences
|
||||||
|
(member_id, filed_date, start_date, end_date, type_id, reason)
|
||||||
|
VALUES (?, ?, ?, ?, ?, ?)`;
|
||||||
|
let out = await pool.query(sql, [data.member_id, toDateTime(data.filed_date), toDateTime(data.start_date), toDateTime(data.end_date), data.type_id, data.reason])
|
||||||
|
|
||||||
|
return Number(out.insertId);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function closeLOA(id: number, closer: number) {
|
||||||
|
const sql = `UPDATE leave_of_absences
|
||||||
|
SET closed = 1,
|
||||||
|
closed_by = ?,
|
||||||
|
ended_at = NOW()
|
||||||
|
WHERE leave_of_absences.id = ?`;
|
||||||
|
let out = await pool.query(sql, [closer, id]);
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getLOAbyID(id: number): Promise<LOARequest> {
|
||||||
|
let res = await pool.query(`SELECT * FROM leave_of_absences WHERE id = ?`, [id]);
|
||||||
|
if (res.length != 1)
|
||||||
|
throw new Error(`LOA with id ${id} not found`);
|
||||||
|
return res[0];
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function setLOAExtension(id: number, extendTo: Date) {
|
||||||
|
let res = await pool.query(`UPDATE leave_of_absences
|
||||||
|
SET extended_till = ?
|
||||||
|
WHERE leave_of_absences.id = ? `, [toDateTime(extendTo), id]);
|
||||||
|
if (res.affectedRows != 1)
|
||||||
|
throw new Error(`Could not extend LOA`);
|
||||||
|
return res[0];
|
||||||
|
}
|
||||||
286
api/src/services/db/memberService.ts
Normal file
286
api/src/services/db/memberService.ts
Normal file
@@ -0,0 +1,286 @@
|
|||||||
|
import { Role } from "@app/shared/types/roles";
|
||||||
|
import pool from "../../db";
|
||||||
|
import { Member, MemberCardDetails, MemberLight, memberSettings, MemberState, PaginatedMembers } from '@app/shared/types/member'
|
||||||
|
import { logger } from "../logging/logger";
|
||||||
|
import { memberCache } from "../../routes/auth";
|
||||||
|
import * as mariadb from 'mariadb';
|
||||||
|
|
||||||
|
export async function getFilteredMembers(
|
||||||
|
page: number = 1,
|
||||||
|
pageSize: number = 15,
|
||||||
|
search?: string,
|
||||||
|
status?: string,
|
||||||
|
unitId?: string
|
||||||
|
): Promise<PaginatedMembers> {
|
||||||
|
try {
|
||||||
|
const offset = (page - 1) * pageSize;
|
||||||
|
const whereClauses: string[] = [];
|
||||||
|
const params: any[] = [];
|
||||||
|
|
||||||
|
if (status && status !== 'all') {
|
||||||
|
whereClauses.push(`m.state = ?`);
|
||||||
|
params.push(status);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (search) {
|
||||||
|
whereClauses.push(`(v.member_name LIKE ? OR v.displayName LIKE ?)`);
|
||||||
|
params.push(`%${search}%`);
|
||||||
|
params.push(`%${search}%`);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (unitId && unitId !== 'all') {
|
||||||
|
whereClauses.push(`v.unit = ?`);
|
||||||
|
params.push(unitId);
|
||||||
|
}
|
||||||
|
|
||||||
|
const whereClause = whereClauses.length > 0
|
||||||
|
? ` WHERE ${whereClauses.join(' AND ')}`
|
||||||
|
: '';
|
||||||
|
|
||||||
|
// COUNT QUERY
|
||||||
|
const countQuery = `SELECT COUNT(*) as total FROM view_member_rank_unit_status_latest v INNER JOIN members m ON v.member_id = m.id ${whereClause}`;
|
||||||
|
const [countResults]: any[] = await pool.query(countQuery, params);
|
||||||
|
const total = Number(countResults?.total) || 0;
|
||||||
|
|
||||||
|
// DATA QUERY
|
||||||
|
const dataQuery = `
|
||||||
|
SELECT
|
||||||
|
v.*,
|
||||||
|
CASE
|
||||||
|
WHEN EXISTS (
|
||||||
|
SELECT 1 FROM leave_of_absences l
|
||||||
|
WHERE l.member_id = v.member_id
|
||||||
|
AND l.deleted = 0
|
||||||
|
AND UTC_TIMESTAMP() BETWEEN l.start_date AND l.end_date
|
||||||
|
) THEN 1 ELSE 0
|
||||||
|
END AS on_loa
|
||||||
|
FROM view_member_rank_unit_status_latest v
|
||||||
|
INNER JOIN members m ON v.member_id = m.id
|
||||||
|
${whereClause} -- Added back correctly
|
||||||
|
ORDER BY v.member_name ASC
|
||||||
|
LIMIT ? OFFSET ?
|
||||||
|
`;
|
||||||
|
|
||||||
|
const rows: any[] = await pool.query(dataQuery, [...params, pageSize, offset]);
|
||||||
|
|
||||||
|
// Map rows to Member type
|
||||||
|
const members: Member[] = rows.map(row => ({
|
||||||
|
member_id: Number(row.member_id),
|
||||||
|
member_name: row.member_name,
|
||||||
|
displayName: row.displayName,
|
||||||
|
rank: row.rank,
|
||||||
|
rank_date: row.rank_date,
|
||||||
|
unit: row.unit,
|
||||||
|
unit_date: row.unit_date,
|
||||||
|
status: row.status,
|
||||||
|
status_date: row.status_date,
|
||||||
|
loa_until: row.loa_until ? new Date(row.loa_until) : undefined,
|
||||||
|
member_state: row.member_state
|
||||||
|
}));
|
||||||
|
|
||||||
|
return {
|
||||||
|
data: members,
|
||||||
|
pagination: {
|
||||||
|
page,
|
||||||
|
pageSize,
|
||||||
|
total,
|
||||||
|
totalPages: Math.ceil(total / pageSize),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
} catch (error) {
|
||||||
|
logger.error('app', 'Error fetching filtered members', {
|
||||||
|
error: error instanceof Error ? error.message : String(error),
|
||||||
|
});
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getUserData(userID: number): Promise<Member> {
|
||||||
|
const sql = `SELECT * FROM view_member_rank_unit_status_latest WHERE member_id = ?`;
|
||||||
|
const res: Member = await pool.query(sql, [userID]);
|
||||||
|
return res[0] ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function setUserState(userID: number, state: MemberState, reason: string, creatorID: number, externalCon?: mariadb.PoolConnection, details: string = "", endPrevious: boolean = true, createHistory: boolean = true) {
|
||||||
|
const isInternalConn = !externalCon;
|
||||||
|
if (isInternalConn)
|
||||||
|
var con = await pool.getConnection();
|
||||||
|
else
|
||||||
|
var con = externalCon;
|
||||||
|
|
||||||
|
try {
|
||||||
|
if (isInternalConn) await con.beginTransaction();
|
||||||
|
|
||||||
|
if (endPrevious)
|
||||||
|
await endLatestMemberState(userID, con);
|
||||||
|
|
||||||
|
const sql = `UPDATE members SET state = ? WHERE id = ?;`;
|
||||||
|
await con.query(sql, [state, userID]);
|
||||||
|
|
||||||
|
if (createHistory) {
|
||||||
|
const insertHistorySql = `INSERT INTO member_state_history
|
||||||
|
(member_id, state_id, reason, created_by_id, start_date, end_date, reason_detailed)
|
||||||
|
VALUES (?, ?, ?, ?, NOW(), NULL, ?);`;
|
||||||
|
await con.query(insertHistorySql, [userID, state, reason, creatorID, details]);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isInternalConn) await con.commit();
|
||||||
|
} catch (error) {
|
||||||
|
if (isInternalConn) {
|
||||||
|
await con.rollback();
|
||||||
|
}
|
||||||
|
logger.error('app', 'Error setting user state', error);
|
||||||
|
throw error;
|
||||||
|
} finally {
|
||||||
|
memberCache.Invalidate(userID);
|
||||||
|
if (isInternalConn && con) con.release();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getUserState(user: number): Promise<MemberState> {
|
||||||
|
let out = await pool.query(`SELECT state FROM members WHERE id = ?`, [user]);
|
||||||
|
return (out[0].state as MemberState);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getMemberSettings(id: number): Promise<memberSettings> {
|
||||||
|
const sql = `SELECT * FROM view_member_settings WHERE id = ?`;
|
||||||
|
let out: memberSettings[] = await pool.query(sql, [id]);
|
||||||
|
|
||||||
|
if (out.length != 1)
|
||||||
|
throw new Error("Could not get user settings");
|
||||||
|
|
||||||
|
return out[0];
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function setUserSettings(id: number, settings: memberSettings) {
|
||||||
|
const sql = `UPDATE view_member_settings SET
|
||||||
|
displayName = ?
|
||||||
|
WHERE id = ?;`;
|
||||||
|
let result = await pool.query(sql, [settings.displayName, id])
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getMembersLite(ids: number[]): Promise<MemberLight[]> {
|
||||||
|
const sql = `SELECT m.member_id AS id,
|
||||||
|
m.member_name AS username,
|
||||||
|
m.displayName,
|
||||||
|
u.color
|
||||||
|
FROM view_member_rank_unit_status_latest m
|
||||||
|
LEFT JOIN units u ON u.name = m.unit
|
||||||
|
WHERE member_id IN (?);`;
|
||||||
|
const res: MemberLight[] = await pool.query(sql, [ids]);
|
||||||
|
return res;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getAllMembersLite(activeOnly: boolean): Promise<MemberLight[]> {
|
||||||
|
|
||||||
|
const filter = activeOnly ? `\nWHERE member_state = ${MemberState.Member}` : ''
|
||||||
|
const sql = `SELECT m.member_id AS id,
|
||||||
|
m.member_name AS username,
|
||||||
|
m.displayName,
|
||||||
|
u.color
|
||||||
|
FROM view_member_rank_unit_status_latest m
|
||||||
|
LEFT JOIN units u ON u.name = m.unit ${filter};`;
|
||||||
|
console.log(sql);
|
||||||
|
const res: MemberLight[] = await pool.query(sql);
|
||||||
|
return res;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getMembersFull(ids: number[]): Promise<MemberCardDetails[]> {
|
||||||
|
const sql = `
|
||||||
|
SELECT
|
||||||
|
m.*,
|
||||||
|
(
|
||||||
|
SELECT COALESCE(JSON_ARRAYAGG(JSON_OBJECT(
|
||||||
|
'id', r.id,
|
||||||
|
'name', r.name,
|
||||||
|
'color', r.color,
|
||||||
|
'description', r.description
|
||||||
|
)), JSON_ARRAY())
|
||||||
|
FROM members_roles mr
|
||||||
|
JOIN roles r ON mr.role_id = r.id
|
||||||
|
WHERE mr.member_id = m.member_id
|
||||||
|
) AS roles
|
||||||
|
FROM view_member_rank_unit_status_latest m
|
||||||
|
WHERE m.member_id IN (?);
|
||||||
|
`;
|
||||||
|
|
||||||
|
const rows: any[] = await pool.query(sql, [ids]);
|
||||||
|
|
||||||
|
return rows.map(row => {
|
||||||
|
const member: Member = {
|
||||||
|
member_id: row.member_id,
|
||||||
|
member_name: row.member_name,
|
||||||
|
displayName: row.displayName,
|
||||||
|
rank: row.rank,
|
||||||
|
rank_date: row.rank_date,
|
||||||
|
unit: row.unit,
|
||||||
|
unit_date: row.unit_date,
|
||||||
|
status: row.status,
|
||||||
|
status_date: row.status_date,
|
||||||
|
loa_until: row.loa_until ? new Date(row.loa_until) : undefined,
|
||||||
|
};
|
||||||
|
// roles comes as array of strings; parse each one
|
||||||
|
const roles: Role[] =
|
||||||
|
typeof row.roles === "string"
|
||||||
|
? JSON.parse(row.roles)
|
||||||
|
: row.roles;
|
||||||
|
|
||||||
|
return { member, roles };
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function mapDiscordtoID(id: number): Promise<number | null> {
|
||||||
|
const sql = `SELECT id FROM members WHERE discord_id = ?;`
|
||||||
|
let res = await pool.query(sql, [id]);
|
||||||
|
return res.length > 0 ? res[0].id : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function endLatestMemberState(memberID: number, con: mariadb.Pool | mariadb.Connection = pool) {
|
||||||
|
const sql = `UPDATE member_state_history
|
||||||
|
SET end_date = NOW(),
|
||||||
|
updated_at = NOW()
|
||||||
|
WHERE id = (
|
||||||
|
SELECT id
|
||||||
|
FROM (
|
||||||
|
SELECT id
|
||||||
|
FROM member_state_history
|
||||||
|
WHERE member_id = ?
|
||||||
|
AND end_date IS NULL
|
||||||
|
ORDER BY start_date DESC,
|
||||||
|
created_at DESC
|
||||||
|
LIMIT 1
|
||||||
|
) AS x
|
||||||
|
);`;
|
||||||
|
|
||||||
|
try {
|
||||||
|
let res = await con.query(sql, [memberID]);
|
||||||
|
console.log(res);
|
||||||
|
return;
|
||||||
|
} catch (error) {
|
||||||
|
logger.error('app', 'Error ending latest member state', {
|
||||||
|
error: error instanceof Error ? error.message : String(error),
|
||||||
|
});
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
// let res = await pool.query(sql, [memberID]);
|
||||||
|
// console.log(res);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getLastNonSuspendedState(memberID: number): Promise<MemberState> {
|
||||||
|
try {
|
||||||
|
const sql = `SELECT state_id
|
||||||
|
FROM member_state_history
|
||||||
|
WHERE member_id = ?
|
||||||
|
AND state_id != ?
|
||||||
|
ORDER BY start_date DESC, id DESC
|
||||||
|
LIMIT 1;`
|
||||||
|
const res = await pool.query(sql, [memberID, MemberState.Suspended]);
|
||||||
|
console.log(res as MemberState[])
|
||||||
|
if (res.length)
|
||||||
|
return res[0].state_id as MemberState;
|
||||||
|
} catch (error) {
|
||||||
|
logger.error('app', 'Error ending latest member state', {
|
||||||
|
error: error instanceof Error ? error.message : String(error),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
129
api/src/services/db/rankService.ts
Normal file
129
api/src/services/db/rankService.ts
Normal file
@@ -0,0 +1,129 @@
|
|||||||
|
import { BatchPromotion, BatchPromotionMember } from "@app/shared/schemas/promotionSchema";
|
||||||
|
import { PromotionDetails, PromotionSummary } from "@app/shared/types/rank"
|
||||||
|
import pool from "../../db";
|
||||||
|
import { PagedData } from "@app/shared/types/pagination";
|
||||||
|
import { toDate, toDateIgnoreZone, toDateTime } from "@app/shared/utils/time";
|
||||||
|
import * as mariadb from 'mariadb';
|
||||||
|
|
||||||
|
export async function getAllRanks() {
|
||||||
|
const rows = await pool.query(
|
||||||
|
'SELECT id, name, short_name, sort_id FROM ranks;'
|
||||||
|
);
|
||||||
|
return rows;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getRankByName(name: string) {
|
||||||
|
const rows = await pool.query(`SELECT id, name, short_name, sort_id FROM ranks WHERE name = ?`, [name]);
|
||||||
|
|
||||||
|
if (rows.length === 0)
|
||||||
|
throw new Error("Could not find rank: " + name);
|
||||||
|
|
||||||
|
return rows[0];
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function insertMemberRank(member_id: number, rank_id: number, date: Date): Promise<void>;
|
||||||
|
export async function insertMemberRank(member_id: number, rank_id: number): Promise<void>;
|
||||||
|
|
||||||
|
export async function insertMemberRank(member_id: number, rank_id: number, date?: Date): Promise<void> {
|
||||||
|
const sql = date
|
||||||
|
? `INSERT INTO members_ranks (member_id, rank_id, start_date) VALUES (?, ?, ?);`
|
||||||
|
: `INSERT INTO members_ranks (member_id, rank_id, start_date) VALUES (?, ?, NOW());`;
|
||||||
|
|
||||||
|
const params = date
|
||||||
|
? [member_id, rank_id, date]
|
||||||
|
: [member_id, rank_id];
|
||||||
|
|
||||||
|
await pool.query(sql, params);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function forceInsertMemberRank(member_id: number, rank_id: number, authorized: number, creator: number, reason: string) {
|
||||||
|
const sql = `CALL sp_update_member_rank(?, ?, ?, ?, ?, NOW())`;
|
||||||
|
|
||||||
|
const result = await pool.query(sql, [member_id, rank_id, authorized, creator, reason]);
|
||||||
|
|
||||||
|
if (!result || result.affectedRows === 0) {
|
||||||
|
throw new Error("Failed to update member rank");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
export async function batchInsertMemberRank(promos: BatchPromotionMember[], author: number, approver: number) {
|
||||||
|
try {
|
||||||
|
var con = await pool.getConnection();
|
||||||
|
promos.forEach(p => {
|
||||||
|
con.query(`CALL sp_update_member_rank(?, ?, ?, ?, ?, ?)`, [p.member_id, p.rank_id, approver, author, "Rank Change", toDateIgnoreZone(new Date(p.start_date))])
|
||||||
|
});
|
||||||
|
|
||||||
|
con.commit();
|
||||||
|
return
|
||||||
|
} catch (error) {
|
||||||
|
throw error; //pass it up
|
||||||
|
} finally {
|
||||||
|
con.release();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getPromotionHistorySummary(page: number = 1, pageSize: number = 15): Promise<PagedData<PromotionSummary>> {
|
||||||
|
|
||||||
|
const offset = (page - 1) * pageSize;
|
||||||
|
|
||||||
|
let sql = `SELECT
|
||||||
|
DATE(start_date) AS entry_day
|
||||||
|
FROM
|
||||||
|
members_ranks
|
||||||
|
WHERE reason = 'Rank Change'
|
||||||
|
GROUP BY
|
||||||
|
entry_day
|
||||||
|
ORDER BY
|
||||||
|
entry_day DESC
|
||||||
|
LIMIT ? OFFSET ?;`
|
||||||
|
|
||||||
|
let promoList: PromotionSummary[] = await pool.query(sql, [pageSize, offset]) as PromotionSummary[];
|
||||||
|
|
||||||
|
let rowCount = Number((await pool.query(`SELECT
|
||||||
|
COUNT(*) AS total_grouped_days_count
|
||||||
|
FROM
|
||||||
|
(
|
||||||
|
SELECT DISTINCT DATE(start_date)
|
||||||
|
FROM members_ranks
|
||||||
|
WHERE reason = 'Rank Change'
|
||||||
|
) AS grouped_days;`))[0]);
|
||||||
|
|
||||||
|
let pageCount = rowCount / pageSize;
|
||||||
|
|
||||||
|
let output: PagedData<PromotionSummary> = { data: promoList, pagination: { page: page, pageSize: pageSize, total: rowCount, totalPages: pageCount } }
|
||||||
|
return output;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getPromotionsOnDay(day: Date): Promise<PromotionDetails[]> {
|
||||||
|
|
||||||
|
const dayString = toDateTime(day);
|
||||||
|
|
||||||
|
// SQL query to fetch all records from members_unit for the specified day
|
||||||
|
let sql = `
|
||||||
|
SELECT
|
||||||
|
mr.id AS promo_id,
|
||||||
|
mr.member_id,
|
||||||
|
mr.created_by_id,
|
||||||
|
mr.authorized_by_id,
|
||||||
|
r.short_name
|
||||||
|
FROM members_ranks AS mr
|
||||||
|
LEFT JOIN ranks AS r ON r.id = mr.rank_id
|
||||||
|
WHERE DATE(mr.start_date) = ? && mr.reason = 'Rank Change'
|
||||||
|
ORDER BY mr.start_date ASC;
|
||||||
|
`;
|
||||||
|
|
||||||
|
let batchPromotion = await pool.query(sql, [dayString]) as PromotionDetails[];
|
||||||
|
|
||||||
|
return batchPromotion;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function cancelLatestRank(userID: number, con: mariadb.Pool | mariadb.Connection = pool): Promise<boolean> {
|
||||||
|
try {
|
||||||
|
let sql = `CALL sp_end_member_rank(?,NOW())`;
|
||||||
|
con.query(sql, [userID]);
|
||||||
|
return true;
|
||||||
|
} catch (error) {
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
78
api/src/services/db/rolesService.ts
Normal file
78
api/src/services/db/rolesService.ts
Normal file
@@ -0,0 +1,78 @@
|
|||||||
|
import { MemberLight } from '@app/shared/types/member';
|
||||||
|
import pool from '../../db';
|
||||||
|
import { Role, RoleSummary } from '@app/shared/types/roles'
|
||||||
|
import { logger } from '../logging/logger';
|
||||||
|
import { memberCache } from '../../routes/auth';
|
||||||
|
import * as mariadb from 'mariadb';
|
||||||
|
|
||||||
|
export async function assignUserGroup(userID: number, roleID: number) {
|
||||||
|
try {
|
||||||
|
const sql = `INSERT INTO members_roles (member_id, role_id) VALUES (?, ?);`;
|
||||||
|
const params = [userID, roleID];
|
||||||
|
|
||||||
|
return await pool.query(sql, params);
|
||||||
|
} catch (error) {
|
||||||
|
logger.error('app', 'Failed to assign user group', error);
|
||||||
|
} finally {
|
||||||
|
memberCache.Invalidate(userID);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function createGroup(name: string, color: string, description: string) {
|
||||||
|
const sql = `INSERT INTO roles (name, color, description) VALUES (?, ?, ?)`;
|
||||||
|
const params = [name, color, description];
|
||||||
|
|
||||||
|
const result = await pool.query(sql, params);
|
||||||
|
return { id: result.insertId, name, color, description };
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getUserRoles(userID: number): Promise<Role[]> {
|
||||||
|
const sql = `SELECT r.id, r.name
|
||||||
|
FROM members_roles mr
|
||||||
|
INNER JOIN roles r ON mr.role_id = r.id
|
||||||
|
WHERE mr.member_id = ?;`;
|
||||||
|
|
||||||
|
return await pool.query(sql, [userID]);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getRole(id: number): Promise<Role> {
|
||||||
|
let res = await pool.query(`SELECT * FROM roles WHERE id = ?`, [id])
|
||||||
|
return res[0] as Role;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getAllRoles(): Promise<RoleSummary> {
|
||||||
|
return await pool.query(`SELECT id, name, color FROM roles`);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getUsersWithRole(roleId: number): Promise<MemberLight[]> {
|
||||||
|
const out = await pool.query(
|
||||||
|
`
|
||||||
|
SELECT
|
||||||
|
m.member_id AS id,
|
||||||
|
m.member_name AS username,
|
||||||
|
m.displayName,
|
||||||
|
u.color
|
||||||
|
FROM members_roles mr
|
||||||
|
JOIN view_member_rank_unit_status_latest m
|
||||||
|
ON m.member_id = mr.member_id
|
||||||
|
LEFT JOIN units u
|
||||||
|
ON u.name = m.unit
|
||||||
|
WHERE mr.role_id = ?
|
||||||
|
`,
|
||||||
|
[roleId]
|
||||||
|
)
|
||||||
|
|
||||||
|
return out as MemberLight[]
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function stripUserRoles(userID: number, con: mariadb.Pool | mariadb.Connection = pool) {
|
||||||
|
try {
|
||||||
|
const out = await con.query(`DELETE FROM members_roles WHERE member_id = ?;`, [userID]);
|
||||||
|
return { success: true, affectedRows: out.affectedRows };
|
||||||
|
} catch (error) {
|
||||||
|
logger.error('app', 'Failed to strip user roles', error);
|
||||||
|
throw error;
|
||||||
|
} finally {
|
||||||
|
memberCache.Invalidate(userID);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
import pool from "../db"
|
import pool from "../../db"
|
||||||
|
|
||||||
export async function assignUserToStatus(userID: number, statusID: number) {
|
export async function assignUserToStatus(userID: number, statusID: number) {
|
||||||
const sql = `INSERT INTO members_statuses (member_id, status_id, event_date) VALUES (?, ?, NOW())`
|
const sql = `INSERT INTO members_statuses (member_id, status_id, start_date) VALUES (?, ?, NOW())`
|
||||||
await pool.execute(sql, [userID, statusID]);
|
await pool.execute(sql, [userID, statusID]);
|
||||||
}
|
}
|
||||||
22
api/src/services/db/unitService.ts
Normal file
22
api/src/services/db/unitService.ts
Normal file
@@ -0,0 +1,22 @@
|
|||||||
|
import pool from "../../db";
|
||||||
|
import * as mariadb from 'mariadb';
|
||||||
|
|
||||||
|
|
||||||
|
export async function cancelLatestUnit(userID: number, con: mariadb.Pool | mariadb.Connection = pool): Promise<boolean> {
|
||||||
|
try {
|
||||||
|
let sql = `CALL sp_end_member_unit(?,NOW())`;
|
||||||
|
con.query(sql, [userID]);
|
||||||
|
return true;
|
||||||
|
} catch (error) {
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function assignNewUnit(memberID: number, unitID: number, authorizedID: number, creatorID: number, reason: string) {
|
||||||
|
let sql = `CALL sp_update_member_unit(?, ?, ?, ?, ?, NOW())`;
|
||||||
|
|
||||||
|
const result = await pool.query(sql, [memberID, unitID, authorizedID, creatorID, reason]);
|
||||||
|
if (!result || result.affectedRows === 0) {
|
||||||
|
throw new Error('Record was not updated');
|
||||||
|
}
|
||||||
|
}
|
||||||
56
api/src/services/events/eventBus.ts
Normal file
56
api/src/services/events/eventBus.ts
Normal file
@@ -0,0 +1,56 @@
|
|||||||
|
import { randomUUID } from "crypto";
|
||||||
|
import { logger } from "../logging/logger";
|
||||||
|
|
||||||
|
interface Event {
|
||||||
|
id: string
|
||||||
|
type: string
|
||||||
|
occurredAt: string
|
||||||
|
payload?: Record<string, any>
|
||||||
|
}
|
||||||
|
|
||||||
|
type EventHandler = (event: Event) => void | Promise<void>;
|
||||||
|
|
||||||
|
class EventBus {
|
||||||
|
private handlers: Map<string, EventHandler[]> = new Map();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Register event listener
|
||||||
|
* @param type
|
||||||
|
* @param handler
|
||||||
|
*/
|
||||||
|
on(type: string, handler: EventHandler) {
|
||||||
|
const handlers = this.handlers.get(type) ?? [];
|
||||||
|
handlers.push(handler);
|
||||||
|
this.handlers.set(type, handlers);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Emit event of given type
|
||||||
|
* @param type
|
||||||
|
* @param payload
|
||||||
|
*/
|
||||||
|
async emit(type: string, payload?: Record<string, any>) {
|
||||||
|
const event: Event = {
|
||||||
|
id: randomUUID(),
|
||||||
|
type,
|
||||||
|
occurredAt: new Date().toISOString(),
|
||||||
|
payload
|
||||||
|
}
|
||||||
|
|
||||||
|
const handlers = this.handlers.get(type) ?? []
|
||||||
|
|
||||||
|
for (const h of handlers) {
|
||||||
|
try {
|
||||||
|
await h(event)
|
||||||
|
} catch (error) {
|
||||||
|
logger.error('app', 'Event handler failed', {
|
||||||
|
type: event.type,
|
||||||
|
id: event.id,
|
||||||
|
error: error instanceof Error ? error.message : String(error),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export const bus = new EventBus();
|
||||||
39
api/src/services/integrations/discord.ts
Normal file
39
api/src/services/integrations/discord.ts
Normal file
@@ -0,0 +1,39 @@
|
|||||||
|
import { bus } from "../events/eventBus";
|
||||||
|
import { logger } from "../logging/logger";
|
||||||
|
|
||||||
|
export function initializeDiscordIntegrations() {
|
||||||
|
bus.on('application.create', async (event) => {
|
||||||
|
|
||||||
|
if (!process.env.DISCORD_APPLICATIONS_WEBHOOK) {
|
||||||
|
logger.error("app", 'Discord Applications Webhook is not defined')
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let applicantName = event.payload.member_discord_id || event.payload.member_name;
|
||||||
|
if (event.payload.member_discord_id) {
|
||||||
|
applicantName = `<@${event.payload.member_discord_id}>`;
|
||||||
|
}
|
||||||
|
const link = `${process.env.CLIENT_URL}/administration/applications/${event.payload.application}`;
|
||||||
|
|
||||||
|
const embed = {
|
||||||
|
title: "Application Posted",
|
||||||
|
description: `[View Application](${link})`,
|
||||||
|
color: 0x00ff00, // optional: green color
|
||||||
|
timestamp: new Date().toISOString(), // <-- Discord expects ISO8601
|
||||||
|
fields: [
|
||||||
|
{
|
||||||
|
name: "Submitted By",
|
||||||
|
value: applicantName,
|
||||||
|
inline: false,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
|
||||||
|
// send to Discord webhook
|
||||||
|
await fetch(process.env.DISCORD_APPLICATIONS_WEBHOOK!, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({ embeds: [embed] }),
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
61
api/src/services/logging/auditLog.ts
Normal file
61
api/src/services/logging/auditLog.ts
Normal file
@@ -0,0 +1,61 @@
|
|||||||
|
import pool from "../../db";
|
||||||
|
import { logger } from "./logger";
|
||||||
|
|
||||||
|
export type AuditArea = 'member' | 'calendar' | 'roles' | 'auth' | 'leave_of_absence' | 'application' | 'course';
|
||||||
|
|
||||||
|
export interface AuditContext {
|
||||||
|
actorId: number; // The person doing the action (created_by)
|
||||||
|
targetId?: number; // The ID of the thing being changed (target_id)
|
||||||
|
}
|
||||||
|
|
||||||
|
class AuditLogger {
|
||||||
|
async record(
|
||||||
|
area: AuditArea,
|
||||||
|
action: string,
|
||||||
|
context: AuditContext,
|
||||||
|
data: Record<string, any> = {} // Already optional with default {}
|
||||||
|
) {
|
||||||
|
const actionType = `${area}.${action}`;
|
||||||
|
|
||||||
|
try {
|
||||||
|
await pool.query(
|
||||||
|
`INSERT INTO audit_log (action_type, payload, target_id, created_by)
|
||||||
|
VALUES (?, ?, ?, ?)`, // Fixed: removed extra comma/placeholder
|
||||||
|
[
|
||||||
|
actionType,
|
||||||
|
JSON.stringify(data),
|
||||||
|
context.targetId || null,
|
||||||
|
context.actorId,
|
||||||
|
]
|
||||||
|
);
|
||||||
|
} catch (err) {
|
||||||
|
logger.error('audit', `AUDIT_FAILURE: Failed to log ${actionType}`, { error: err });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
member(action: 'update_rank'| 'update_unit' | 'suspension_added' | 'suspension_removed' | 'discharged', context: AuditContext, data: any = {}) {
|
||||||
|
return this.record('member', action, context, data);
|
||||||
|
}
|
||||||
|
|
||||||
|
roles(action: 'add_member' | 'remove_member' | 'create' | 'delete', context: AuditContext, data: any = {}) {
|
||||||
|
return this.record('roles', action, context, data);
|
||||||
|
}
|
||||||
|
|
||||||
|
leaveOfAbsence(action: 'created' | 'admin_created' | 'ended' | 'admin_ended' | 'extended', context: AuditContext, data: any = {}) {
|
||||||
|
return this.record('leave_of_absence', action, context, data);
|
||||||
|
}
|
||||||
|
|
||||||
|
calendar(action: 'event_created' | 'event_updated' | 'attendance_set' | 'cancelled' | 'un-cancelled', context: AuditContext, data: any = {}) {
|
||||||
|
return this.record('calendar', action, context, data);
|
||||||
|
}
|
||||||
|
|
||||||
|
application(action: 'created' | 'approved' | 'denied' | 'restarted', context: AuditContext, data: any = {}) {
|
||||||
|
return this.record('application', action, context, data);
|
||||||
|
}
|
||||||
|
|
||||||
|
course(action: 'report_created' | 'report_edited', context: AuditContext, data: any = {}) {
|
||||||
|
return this.record('course', action, context, data);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export const audit = new AuditLogger();
|
||||||
72
api/src/services/logging/logger.ts
Normal file
72
api/src/services/logging/logger.ts
Normal file
@@ -0,0 +1,72 @@
|
|||||||
|
export type LogLevel = 'debug' | 'info' | 'warn' | 'error';
|
||||||
|
export type LogDepth = 'normal' | 'verbose' | 'profiling';
|
||||||
|
export type LogType = 'http' | 'app' | 'auth' | 'profiling' | 'audit';
|
||||||
|
|
||||||
|
export interface LogHeader {
|
||||||
|
timestamp: string;
|
||||||
|
level: LogLevel;
|
||||||
|
depth: LogDepth;
|
||||||
|
type: LogType; // 'http', 'app', 'db', etc.
|
||||||
|
user_id?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface LogPayload {
|
||||||
|
message?: string; // short human-friendly description
|
||||||
|
data?: Record<string, any>; // type-specific rich data
|
||||||
|
}
|
||||||
|
|
||||||
|
// Environment defaults
|
||||||
|
const CURRENT_DEPTH: LogDepth = (process.env.LOG_DEPTH as LogDepth) || 'normal';
|
||||||
|
|
||||||
|
const DEPTH_ORDER: Record<LogDepth, number> = { normal: 0, verbose: 1, profiling: 2 };
|
||||||
|
|
||||||
|
function shouldLog(depth: LogDepth) {
|
||||||
|
let should = DEPTH_ORDER[depth] <= DEPTH_ORDER[CURRENT_DEPTH]
|
||||||
|
return should;
|
||||||
|
}
|
||||||
|
|
||||||
|
function emitLog(header: LogHeader, payload: LogPayload = {}) {
|
||||||
|
if (!shouldLog(header.depth)) return;
|
||||||
|
|
||||||
|
const logLine = { ...header, ...payload };
|
||||||
|
|
||||||
|
if (header.level === 'error')
|
||||||
|
console.error(JSON.stringify(logLine))
|
||||||
|
else
|
||||||
|
console.log(JSON.stringify(logLine));
|
||||||
|
}
|
||||||
|
|
||||||
|
export const logger = {
|
||||||
|
log(level: LogLevel, type: LogType, message: string, data?: Record<string, any>, depth: LogDepth = 'normal', context?: Partial<LogHeader>) {
|
||||||
|
const header: LogHeader = {
|
||||||
|
timestamp: new Date().toISOString(),
|
||||||
|
level,
|
||||||
|
depth,
|
||||||
|
type,
|
||||||
|
...context,
|
||||||
|
};
|
||||||
|
|
||||||
|
const payload: LogPayload = {
|
||||||
|
message,
|
||||||
|
data,
|
||||||
|
};
|
||||||
|
|
||||||
|
emitLog(header, payload);
|
||||||
|
},
|
||||||
|
|
||||||
|
info(type: LogType, message: string, data?: Record<string, any>, depth: LogDepth = 'normal', context?: Partial<LogHeader>) {
|
||||||
|
this.log('info', type, message, data, depth, context);
|
||||||
|
},
|
||||||
|
|
||||||
|
debug(type: LogType, message: string, data?: Record<string, any>, depth: LogDepth = 'normal', context?: Partial<LogHeader>) {
|
||||||
|
this.log('debug', type, message, data, depth, context);
|
||||||
|
},
|
||||||
|
|
||||||
|
warn(type: LogType, message: string, data?: Record<string, any>, depth: LogDepth = 'normal', context?: Partial<LogHeader>) {
|
||||||
|
this.log('warn', type, message, data, depth, context);
|
||||||
|
},
|
||||||
|
|
||||||
|
error(type: LogType, message: string, data?: Record<string, any>, depth: LogDepth = 'normal', context?: Partial<LogHeader>) {
|
||||||
|
this.log('error', type, message, data, depth, context);
|
||||||
|
},
|
||||||
|
}
|
||||||
@@ -1,34 +0,0 @@
|
|||||||
import pool from "../db";
|
|
||||||
|
|
||||||
export enum MemberState {
|
|
||||||
Guest = "guest",
|
|
||||||
Applicant = "applicant",
|
|
||||||
Member = "member",
|
|
||||||
Retired = "retired",
|
|
||||||
Banned = "banned",
|
|
||||||
Denied = "denied"
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function getUserData(userID: number) {
|
|
||||||
const sql = `SELECT * FROM members WHERE id = ?`;
|
|
||||||
const res = await pool.query(sql, [userID]);
|
|
||||||
return res[0] ?? null;
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function setUserState(userID: number, state: MemberState) {
|
|
||||||
const sql = `UPDATE members
|
|
||||||
SET state = ?
|
|
||||||
WHERE id = ?;`;
|
|
||||||
return await pool.query(sql, [state, userID]);
|
|
||||||
}
|
|
||||||
|
|
||||||
declare global {
|
|
||||||
namespace Express {
|
|
||||||
interface Request {
|
|
||||||
user: {
|
|
||||||
id: number;
|
|
||||||
name: string;
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,32 +0,0 @@
|
|||||||
import pool from "../db";
|
|
||||||
|
|
||||||
export async function getAllRanks() {
|
|
||||||
const rows = await pool.query(
|
|
||||||
'SELECT id, name, short_name, sort_id FROM ranks;'
|
|
||||||
);
|
|
||||||
return rows;
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function getRankByName(name: string) {
|
|
||||||
const rows = await pool.query(`SELECT id, name, short_name, sort_id FROM ranks WHERE name = ?`, [name]);
|
|
||||||
|
|
||||||
if (rows.length === 0)
|
|
||||||
throw new Error("Could not find rank: " + name);
|
|
||||||
|
|
||||||
return rows[0];
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function insertMemberRank(member_id: number, rank_id: number, date: Date): Promise<void>;
|
|
||||||
export async function insertMemberRank(member_id: number, rank_id: number): Promise<void>;
|
|
||||||
|
|
||||||
export async function insertMemberRank(member_id: number, rank_id: number, date?: Date): Promise<void> {
|
|
||||||
const sql = date
|
|
||||||
? `INSERT INTO members_ranks (member_id, rank_id, event_date) VALUES (?, ?, ?);`
|
|
||||||
: `INSERT INTO members_ranks (member_id, rank_id, event_date) VALUES (?, ?, NOW());`;
|
|
||||||
|
|
||||||
const params = date
|
|
||||||
? [member_id, rank_id, date]
|
|
||||||
: [member_id, rank_id];
|
|
||||||
|
|
||||||
await pool.query(sql, params);
|
|
||||||
}
|
|
||||||
@@ -1,27 +0,0 @@
|
|||||||
import pool from '../db';
|
|
||||||
import { Role } from '@app/shared/types/roles'
|
|
||||||
|
|
||||||
export async function assignUserGroup(userID: number, roleID: number) {
|
|
||||||
|
|
||||||
const sql = `INSERT INTO members_roles (member_id, role_id) VALUES (?, ?);`;
|
|
||||||
const params = [userID, roleID];
|
|
||||||
|
|
||||||
return await pool.query(sql, params);
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function createGroup(name: string, color: string, description: string) {
|
|
||||||
const sql = `INSERT INTO roles (name, color, description) VALUES (?, ?, ?)`;
|
|
||||||
const params = [name, color, description];
|
|
||||||
|
|
||||||
const result = await pool.query(sql, params);
|
|
||||||
return { id: result.insertId, name, color, description };
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function getUserRoles(userID: number): Promise<Role[]> {
|
|
||||||
const sql = `SELECT r.id, r.name
|
|
||||||
FROM members_roles mr
|
|
||||||
INNER JOIN roles r ON mr.role_id = r.id
|
|
||||||
WHERE mr.member_id = 190;`;
|
|
||||||
|
|
||||||
return await pool.query(sql, [userID]);
|
|
||||||
}
|
|
||||||
@@ -7,6 +7,7 @@
|
|||||||
"node",
|
"node",
|
||||||
"express"
|
"express"
|
||||||
],
|
],
|
||||||
|
"sourceMap": true,
|
||||||
"paths": {
|
"paths": {
|
||||||
"@app/shared/*": ["../shared/*"]
|
"@app/shared/*": ["../shared/*"]
|
||||||
}
|
}
|
||||||
|
|||||||
13
docker-compose.dev.yml
Normal file
13
docker-compose.dev.yml
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
version: "3.9"
|
||||||
|
services:
|
||||||
|
db:
|
||||||
|
image: mariadb:10.6.23-ubi9
|
||||||
|
environment:
|
||||||
|
MARIADB_ROOT_PASSWORD: root
|
||||||
|
MARIADB_DATABASE: ranger_unit_tracker
|
||||||
|
MARIADB_USER: dev
|
||||||
|
MARIADB_PASSWORD: dev
|
||||||
|
ports:
|
||||||
|
- "3306:3306"
|
||||||
|
volumes:
|
||||||
|
- ./db_data:/var/lib/mysql
|
||||||
54
readme.md
Normal file
54
readme.md
Normal file
@@ -0,0 +1,54 @@
|
|||||||
|
## Prerequs
|
||||||
|
|
||||||
|
* Node.js
|
||||||
|
* npm
|
||||||
|
* Docker + Docker Compose
|
||||||
|
|
||||||
|
## Installation
|
||||||
|
|
||||||
|
Install dependencies in each workspace:
|
||||||
|
|
||||||
|
```
|
||||||
|
cd ui && npm install
|
||||||
|
cd ../api && npm install
|
||||||
|
cd ../shared && npm install
|
||||||
|
```
|
||||||
|
|
||||||
|
## Local Development Setup
|
||||||
|
|
||||||
|
From the project root, start required services:
|
||||||
|
|
||||||
|
```
|
||||||
|
docker compose -f docker-compose.dev.yml up
|
||||||
|
```
|
||||||
|
|
||||||
|
Run database setup from `/api`:
|
||||||
|
|
||||||
|
```
|
||||||
|
npm run migrate:up
|
||||||
|
npm run migrate:seed
|
||||||
|
```
|
||||||
|
|
||||||
|
## Running the App
|
||||||
|
|
||||||
|
Start the frontend:
|
||||||
|
|
||||||
|
```
|
||||||
|
cd ui
|
||||||
|
npm run dev
|
||||||
|
```
|
||||||
|
|
||||||
|
Start the API:
|
||||||
|
|
||||||
|
```
|
||||||
|
cd api
|
||||||
|
npm run dev
|
||||||
|
```
|
||||||
|
|
||||||
|
* UI runs via Vite
|
||||||
|
* API runs on Node after TypeScript build
|
||||||
|
|
||||||
|
## Notes
|
||||||
|
|
||||||
|
* `shared` must have its dependencies installed for both UI and API to work
|
||||||
|
* `docker-compose.dev.yml` is required for local dev dependencies (e.g. database)
|
||||||
10
shared/schemas/dischargeSchema.ts
Normal file
10
shared/schemas/dischargeSchema.ts
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
import z from "zod";
|
||||||
|
|
||||||
|
export const dischargeSchema = z.object({
|
||||||
|
reason: z.string().min(1, "Please provide a valid reason for discharge").max(200),
|
||||||
|
// effectiveDate: z.string().min(1, "Date is required"),
|
||||||
|
})
|
||||||
|
|
||||||
|
export type Discharge = z.infer<typeof dischargeSchema> & {
|
||||||
|
userID: number;
|
||||||
|
};
|
||||||
51
shared/schemas/loaSchema.ts
Normal file
51
shared/schemas/loaSchema.ts
Normal file
@@ -0,0 +1,51 @@
|
|||||||
|
import * as z from "zod";
|
||||||
|
import { LOAType } from "../types/loa";
|
||||||
|
|
||||||
|
export const loaTypeSchema = z.object({
|
||||||
|
id: z.number(),
|
||||||
|
name: z.string(),
|
||||||
|
max_length_days: z.number(),
|
||||||
|
});
|
||||||
|
|
||||||
|
export const loaSchema = z.object({
|
||||||
|
member_id: z.number(),
|
||||||
|
start_date: z.date(),
|
||||||
|
end_date: z.date(),
|
||||||
|
type: loaTypeSchema,
|
||||||
|
reason: z.string(),
|
||||||
|
})
|
||||||
|
.superRefine((data, ctx) => {
|
||||||
|
const { start_date, end_date, type } = data;
|
||||||
|
|
||||||
|
const today = new Date();
|
||||||
|
today.setHours(0, 0, 0, 0);
|
||||||
|
|
||||||
|
if (start_date < today) {
|
||||||
|
ctx.addIssue({
|
||||||
|
code: z.ZodIssueCode.custom,
|
||||||
|
path: ["start_date"],
|
||||||
|
message: "Start date cannot be in the past.",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// 1. end > start
|
||||||
|
if (end_date <= start_date) {
|
||||||
|
ctx.addIssue({
|
||||||
|
code: z.ZodIssueCode.custom,
|
||||||
|
path: ["end_date"],
|
||||||
|
message: "End date must be after start date.",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. calculate max
|
||||||
|
const maxEnd = new Date(start_date);
|
||||||
|
maxEnd.setDate(maxEnd.getDate() + type.max_length_days);
|
||||||
|
|
||||||
|
if (end_date > maxEnd) {
|
||||||
|
ctx.addIssue({
|
||||||
|
code: z.ZodIssueCode.custom,
|
||||||
|
path: ["end_date"],
|
||||||
|
message: `This LOA type allows a maximum of ${type.max_length_days} days.`,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
32
shared/schemas/promotionSchema.ts
Normal file
32
shared/schemas/promotionSchema.ts
Normal file
@@ -0,0 +1,32 @@
|
|||||||
|
import { z } from "zod";
|
||||||
|
|
||||||
|
export const batchPromotionMemberSchema = z.object({
|
||||||
|
member_id: z.number({ invalid_type_error: "Must select a member" }).int().positive(),
|
||||||
|
rank_id: z.number({ invalid_type_error: "Must select a rank" }).int().positive(),
|
||||||
|
start_date: z.string().refine((val) => !isNaN(Date.parse(val)), {
|
||||||
|
message: "Must be a valid date",
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
export const batchPromotionSchema = z.object({
|
||||||
|
promotions: z.array(batchPromotionMemberSchema, { message: "At least one promotion is required" }).nonempty({ message: "At least one promotion is required" }),
|
||||||
|
approver: z.number({ invalid_type_error: "Must select a member" }).int().positive()
|
||||||
|
})
|
||||||
|
.superRefine((data, ctx) => {
|
||||||
|
// optional: check for duplicate member_ids
|
||||||
|
const memberCounts = new Map<number, number>();
|
||||||
|
data.promotions.forEach((p, index) => {
|
||||||
|
memberCounts.set(p.member_id, (memberCounts.get(p.member_id) ?? 0) + 1);
|
||||||
|
if (memberCounts.get(p.member_id)! > 1) {
|
||||||
|
ctx.addIssue({
|
||||||
|
code: z.ZodIssueCode.custom,
|
||||||
|
path: ["promotions", index, "member_id"],
|
||||||
|
message: "Duplicate member in batch is not allowed",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
|
||||||
|
export type BatchPromotion = z.infer<typeof batchPromotionSchema>;
|
||||||
|
export type BatchPromotionMember = z.infer<typeof batchPromotionMemberSchema>;
|
||||||
@@ -40,6 +40,7 @@ export interface CommentRow {
|
|||||||
post_time: string;
|
post_time: string;
|
||||||
last_modified: string | null;
|
last_modified: string | null;
|
||||||
poster_name: string;
|
poster_name: string;
|
||||||
|
admin_only: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface ApplicationFull {
|
export interface ApplicationFull {
|
||||||
|
|||||||
@@ -26,7 +26,7 @@ export interface CalendarSignup {
|
|||||||
eventID: number;
|
eventID: number;
|
||||||
status: CalendarAttendance;
|
status: CalendarAttendance;
|
||||||
member_name?: string;
|
member_name?: string;
|
||||||
member_unit?: string;
|
unit_name?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface CalendarEventShort {
|
export interface CalendarEventShort {
|
||||||
|
|||||||
24
shared/types/loa.ts
Normal file
24
shared/types/loa.ts
Normal file
@@ -0,0 +1,24 @@
|
|||||||
|
export interface LOARequest {
|
||||||
|
id?: number;
|
||||||
|
member_id?: number;
|
||||||
|
filed_date?: Date; // ISO 8601 string
|
||||||
|
start_date: Date; // ISO 8601 string
|
||||||
|
end_date: Date; // ISO 8601 string
|
||||||
|
extended_till?: Date;
|
||||||
|
type_id?: number;
|
||||||
|
reason?: string;
|
||||||
|
expired?: boolean;
|
||||||
|
closed?: boolean;
|
||||||
|
closed_by?: number;
|
||||||
|
created_by?: number;
|
||||||
|
|
||||||
|
name?: string; //member name
|
||||||
|
type_name?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export interface LOAType {
|
||||||
|
id: number;
|
||||||
|
name: string;
|
||||||
|
max_length_days: number;
|
||||||
|
extendable: boolean;
|
||||||
|
}
|
||||||
59
shared/types/member.ts
Normal file
59
shared/types/member.ts
Normal file
@@ -0,0 +1,59 @@
|
|||||||
|
import { LOARequest } from "./loa";
|
||||||
|
import { Role } from "./roles";
|
||||||
|
import { PagedData } from "./pagination";
|
||||||
|
|
||||||
|
export interface memberSettings {
|
||||||
|
displayName: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type PaginatedMembers = PagedData<Member>;
|
||||||
|
|
||||||
|
export enum MemberState {
|
||||||
|
Guest = 1,
|
||||||
|
Applicant = 2,
|
||||||
|
Member = 3,
|
||||||
|
Retired = 4,
|
||||||
|
Discharged = 5,
|
||||||
|
Suspended = 6,
|
||||||
|
Banned = 7,
|
||||||
|
Denied = 8
|
||||||
|
}
|
||||||
|
|
||||||
|
export type Member = {
|
||||||
|
member_id: number;
|
||||||
|
member_name: string;
|
||||||
|
displayName?: string;
|
||||||
|
rank: string | null;
|
||||||
|
rank_date: string | null;
|
||||||
|
unit: string | null;
|
||||||
|
unit_date: string | null;
|
||||||
|
status: string | null;
|
||||||
|
status_date: string | null;
|
||||||
|
loa_until?: Date;
|
||||||
|
member_state?: MemberState;
|
||||||
|
};
|
||||||
|
|
||||||
|
export interface MemberLight {
|
||||||
|
id: number
|
||||||
|
displayName: string
|
||||||
|
username: string
|
||||||
|
color: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface MemberCardDetails {
|
||||||
|
member: Member;
|
||||||
|
roles: Role[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface myData {
|
||||||
|
member: Member;
|
||||||
|
LOAs: LOARequest[];
|
||||||
|
roles: Role[];
|
||||||
|
state: MemberState;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface UserCacheBustResult {
|
||||||
|
success: boolean;
|
||||||
|
clearedEntries: number;
|
||||||
|
bustedAt: string;
|
||||||
|
}
|
||||||
11
shared/types/pagination.ts
Normal file
11
shared/types/pagination.ts
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
export interface PagedData<T> {
|
||||||
|
data: T[]
|
||||||
|
pagination: pagination
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface pagination {
|
||||||
|
page: number
|
||||||
|
pageSize: number
|
||||||
|
total: number
|
||||||
|
totalPages: number
|
||||||
|
}
|
||||||
19
shared/types/rank.ts
Normal file
19
shared/types/rank.ts
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
export type Rank = {
|
||||||
|
id: number
|
||||||
|
name: string
|
||||||
|
short_name: string
|
||||||
|
category: string
|
||||||
|
sortOrder: number
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface PromotionSummary {
|
||||||
|
entry_day: Date;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface PromotionDetails {
|
||||||
|
promo_id: number;
|
||||||
|
member_id: number;
|
||||||
|
short_name: string;
|
||||||
|
created_by_id: number;
|
||||||
|
authorized_by_id: number;
|
||||||
|
}
|
||||||
@@ -1,6 +1,14 @@
|
|||||||
|
import { MemberLight } from "./member";
|
||||||
|
|
||||||
export interface Role {
|
export interface Role {
|
||||||
id: number;
|
id: number;
|
||||||
name: string;
|
name: string;
|
||||||
color?: string;
|
color?: string;
|
||||||
description?: string;
|
description?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface RoleSummary {
|
||||||
|
id: number;
|
||||||
|
name: string;
|
||||||
|
color?: string;
|
||||||
|
}
|
||||||
7
shared/types/units.ts
Normal file
7
shared/types/units.ts
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
export interface Unit {
|
||||||
|
id: number;
|
||||||
|
name: string;
|
||||||
|
description?: string;
|
||||||
|
active: boolean;
|
||||||
|
color?: string;
|
||||||
|
}
|
||||||
@@ -1,5 +1,7 @@
|
|||||||
export function toDateTime(date: Date): string {
|
export function toDateTime(date: Date): string {
|
||||||
console.log(date);
|
if (typeof date === 'string') {
|
||||||
|
date = new Date(date);
|
||||||
|
}
|
||||||
// This produces a CST-local time because server runs in CST
|
// This produces a CST-local time because server runs in CST
|
||||||
const year = date.getFullYear();
|
const year = date.getFullYear();
|
||||||
const month = (date.getMonth() + 1).toString().padStart(2, "0");
|
const month = (date.getMonth() + 1).toString().padStart(2, "0");
|
||||||
@@ -10,3 +12,25 @@ export function toDateTime(date: Date): string {
|
|||||||
|
|
||||||
return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
|
return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function toDateIgnoreZone(date: Date): string {
|
||||||
|
if (typeof date === 'string') {
|
||||||
|
date = new Date(date);
|
||||||
|
}
|
||||||
|
return date.toISOString().split('T')[0];
|
||||||
|
}
|
||||||
|
|
||||||
|
export function toDate(date: Date): string {
|
||||||
|
if (typeof date === 'string') {
|
||||||
|
date = new Date(date);
|
||||||
|
}
|
||||||
|
console.log(date);
|
||||||
|
// This produces a CST-local date because server runs in CST
|
||||||
|
const year = date.getFullYear();
|
||||||
|
const month = (date.getMonth() + 1).toString().padStart(2, "0");
|
||||||
|
const day = date.getDate().toString().padStart(2, "0");
|
||||||
|
let out = `${year}-${month}-${day}`;
|
||||||
|
|
||||||
|
console.log(out);
|
||||||
|
return out;
|
||||||
|
}
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
# SITE SETTINGS
|
# SITE SETTINGS
|
||||||
VITE_APIHOST=
|
VITE_APIHOST=
|
||||||
|
VITE_DOCHOST= # https://bookstack.whatever.com/api
|
||||||
VITE_ENVIRONMENT= # dev / prod
|
VITE_ENVIRONMENT= # dev / prod
|
||||||
VITE_APPLICATION_VERSION= # Should match release tag
|
VITE_APPLICATION_VERSION= # Should match release tag
|
||||||
|
|
||||||
|
|||||||
@@ -4,7 +4,7 @@
|
|||||||
<meta charset="UTF-8">
|
<meta charset="UTF-8">
|
||||||
<link rel="icon" href="/favicon.ico">
|
<link rel="icon" href="/favicon.ico">
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
<title>Vite App</title>
|
<title>17th Ranger Battalion</title>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<div id="app"></div>
|
<div id="app"></div>
|
||||||
|
|||||||
108
ui/package-lock.json
generated
108
ui/package-lock.json
generated
@@ -35,7 +35,8 @@
|
|||||||
"@types/node": "^24.2.1",
|
"@types/node": "^24.2.1",
|
||||||
"@vitejs/plugin-vue": "^6.0.1",
|
"@vitejs/plugin-vue": "^6.0.1",
|
||||||
"vite": "^7.0.6",
|
"vite": "^7.0.6",
|
||||||
"vite-plugin-vue-devtools": "^8.0.0"
|
"vite-plugin-vue-devtools": "^8.0.0",
|
||||||
|
"vue-tsc": "^3.2.4"
|
||||||
},
|
},
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": "^20.19.0 || >=22.12.0"
|
"node": "^20.19.0 || >=22.12.0"
|
||||||
@@ -1884,6 +1885,35 @@
|
|||||||
"vue": "^3.2.25"
|
"vue": "^3.2.25"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/@volar/language-core": {
|
||||||
|
"version": "2.4.27",
|
||||||
|
"resolved": "https://registry.npmjs.org/@volar/language-core/-/language-core-2.4.27.tgz",
|
||||||
|
"integrity": "sha512-DjmjBWZ4tJKxfNC1F6HyYERNHPYS7L7OPFyCrestykNdUZMFYzI9WTyvwPcaNaHlrEUwESHYsfEw3isInncZxQ==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@volar/source-map": "2.4.27"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@volar/source-map": {
|
||||||
|
"version": "2.4.27",
|
||||||
|
"resolved": "https://registry.npmjs.org/@volar/source-map/-/source-map-2.4.27.tgz",
|
||||||
|
"integrity": "sha512-ynlcBReMgOZj2i6po+qVswtDUeeBRCTgDurjMGShbm8WYZgJ0PA4RmtebBJ0BCYol1qPv3GQF6jK7C9qoVc7lg==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
|
"node_modules/@volar/typescript": {
|
||||||
|
"version": "2.4.27",
|
||||||
|
"resolved": "https://registry.npmjs.org/@volar/typescript/-/typescript-2.4.27.tgz",
|
||||||
|
"integrity": "sha512-eWaYCcl/uAPInSK2Lze6IqVWaBu/itVqR5InXcHXFyles4zO++Mglt3oxdgj75BDcv1Knr9Y93nowS8U3wqhxg==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@volar/language-core": "2.4.27",
|
||||||
|
"path-browserify": "^1.0.1",
|
||||||
|
"vscode-uri": "^3.0.8"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/@vue/babel-helper-vue-transform-on": {
|
"node_modules/@vue/babel-helper-vue-transform-on": {
|
||||||
"version": "1.5.0",
|
"version": "1.5.0",
|
||||||
"resolved": "https://registry.npmjs.org/@vue/babel-helper-vue-transform-on/-/babel-helper-vue-transform-on-1.5.0.tgz",
|
"resolved": "https://registry.npmjs.org/@vue/babel-helper-vue-transform-on/-/babel-helper-vue-transform-on-1.5.0.tgz",
|
||||||
@@ -2083,6 +2113,22 @@
|
|||||||
"rfdc": "^1.4.1"
|
"rfdc": "^1.4.1"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/@vue/language-core": {
|
||||||
|
"version": "3.2.4",
|
||||||
|
"resolved": "https://registry.npmjs.org/@vue/language-core/-/language-core-3.2.4.tgz",
|
||||||
|
"integrity": "sha512-bqBGuSG4KZM45KKTXzGtoCl9cWju5jsaBKaJJe3h5hRAAWpZUuj5G+L+eI01sPIkm4H6setKRlw7E85wLdDNew==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@volar/language-core": "2.4.27",
|
||||||
|
"@vue/compiler-dom": "^3.5.0",
|
||||||
|
"@vue/shared": "^3.5.0",
|
||||||
|
"alien-signals": "^3.0.0",
|
||||||
|
"muggle-string": "^0.4.1",
|
||||||
|
"path-browserify": "^1.0.1",
|
||||||
|
"picomatch": "^4.0.2"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/@vue/reactivity": {
|
"node_modules/@vue/reactivity": {
|
||||||
"version": "3.5.18",
|
"version": "3.5.18",
|
||||||
"resolved": "https://registry.npmjs.org/@vue/reactivity/-/reactivity-3.5.18.tgz",
|
"resolved": "https://registry.npmjs.org/@vue/reactivity/-/reactivity-3.5.18.tgz",
|
||||||
@@ -2171,6 +2217,13 @@
|
|||||||
"vue": "^3.5.0"
|
"vue": "^3.5.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/alien-signals": {
|
||||||
|
"version": "3.1.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/alien-signals/-/alien-signals-3.1.2.tgz",
|
||||||
|
"integrity": "sha512-d9dYqZTS90WLiU0I5c6DHj/HcKkF8ZyGN3G5x8wSbslulz70KOxaqCT0hQCo9KOyhVqzqGojvNdJXoTumZOtcw==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
"node_modules/ansis": {
|
"node_modules/ansis": {
|
||||||
"version": "4.1.0",
|
"version": "4.1.0",
|
||||||
"resolved": "https://registry.npmjs.org/ansis/-/ansis-4.1.0.tgz",
|
"resolved": "https://registry.npmjs.org/ansis/-/ansis-4.1.0.tgz",
|
||||||
@@ -3123,6 +3176,13 @@
|
|||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
|
"node_modules/muggle-string": {
|
||||||
|
"version": "0.4.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/muggle-string/-/muggle-string-0.4.1.tgz",
|
||||||
|
"integrity": "sha512-VNTrAak/KhO2i8dqqnqnAHOa3cYBwXEZe9h+D5h/1ZqFSTEFHdM65lR7RoIqq3tBBYavsOXV84NoHXZ0AkPyqQ==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
"node_modules/nanoid": {
|
"node_modules/nanoid": {
|
||||||
"version": "3.3.11",
|
"version": "3.3.11",
|
||||||
"resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.11.tgz",
|
"resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.11.tgz",
|
||||||
@@ -3216,6 +3276,13 @@
|
|||||||
"url": "https://github.com/sponsors/sindresorhus"
|
"url": "https://github.com/sponsors/sindresorhus"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/path-browserify": {
|
||||||
|
"version": "1.0.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/path-browserify/-/path-browserify-1.0.1.tgz",
|
||||||
|
"integrity": "sha512-b7uo2UCUOYZcnF/3ID0lulOJi/bafxa1xPe7ZPsammBSpjSWQkjNxlt635YGS2MiR9GjvuXCtz2emr3jbsz98g==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
"node_modules/path-key": {
|
"node_modules/path-key": {
|
||||||
"version": "3.1.1",
|
"version": "3.1.1",
|
||||||
"resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz",
|
"resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz",
|
||||||
@@ -3646,6 +3713,21 @@
|
|||||||
"url": "https://github.com/sponsors/sindresorhus"
|
"url": "https://github.com/sponsors/sindresorhus"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/typescript": {
|
||||||
|
"version": "5.9.3",
|
||||||
|
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",
|
||||||
|
"integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",
|
||||||
|
"devOptional": true,
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"peer": true,
|
||||||
|
"bin": {
|
||||||
|
"tsc": "bin/tsc",
|
||||||
|
"tsserver": "bin/tsserver"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=14.17"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/undici-types": {
|
"node_modules/undici-types": {
|
||||||
"version": "7.10.0",
|
"version": "7.10.0",
|
||||||
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.10.0.tgz",
|
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.10.0.tgz",
|
||||||
@@ -3932,6 +4014,13 @@
|
|||||||
"vite": "^3.0.0-0 || ^4.0.0-0 || ^5.0.0-0 || ^6.0.0-0 || ^7.0.0-0"
|
"vite": "^3.0.0-0 || ^4.0.0-0 || ^5.0.0-0 || ^6.0.0-0 || ^7.0.0-0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/vscode-uri": {
|
||||||
|
"version": "3.1.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/vscode-uri/-/vscode-uri-3.1.0.tgz",
|
||||||
|
"integrity": "sha512-/BpdSx+yCQGnCvecbyXdxHDkuk55/G3xwnC0GqY4gmQ3j+A+g8kzzgB4Nk/SINjqn6+waqw3EgbVF2QKExkRxQ==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
"node_modules/vue": {
|
"node_modules/vue": {
|
||||||
"version": "3.5.18",
|
"version": "3.5.18",
|
||||||
"resolved": "https://registry.npmjs.org/vue/-/vue-3.5.18.tgz",
|
"resolved": "https://registry.npmjs.org/vue/-/vue-3.5.18.tgz",
|
||||||
@@ -3974,6 +4063,23 @@
|
|||||||
"integrity": "sha512-sGhTPMuXqZ1rVOk32RylztWkfXTRhuS7vgAKv0zjqk8gbsHkJ7xfFf+jbySxt7tWObEJwyKaHMikV/WGDiQm8g==",
|
"integrity": "sha512-sGhTPMuXqZ1rVOk32RylztWkfXTRhuS7vgAKv0zjqk8gbsHkJ7xfFf+jbySxt7tWObEJwyKaHMikV/WGDiQm8g==",
|
||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
|
"node_modules/vue-tsc": {
|
||||||
|
"version": "3.2.4",
|
||||||
|
"resolved": "https://registry.npmjs.org/vue-tsc/-/vue-tsc-3.2.4.tgz",
|
||||||
|
"integrity": "sha512-xj3YCvSLNDKt1iF9OcImWHhmYcihVu9p4b9s4PGR/qp6yhW+tZJaypGxHScRyOrdnHvaOeF+YkZOdKwbgGvp5g==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@volar/typescript": "2.4.27",
|
||||||
|
"@vue/language-core": "3.2.4"
|
||||||
|
},
|
||||||
|
"bin": {
|
||||||
|
"vue-tsc": "bin/vue-tsc.js"
|
||||||
|
},
|
||||||
|
"peerDependencies": {
|
||||||
|
"typescript": ">=5.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/which": {
|
"node_modules/which": {
|
||||||
"version": "2.0.2",
|
"version": "2.0.2",
|
||||||
"resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz",
|
"resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz",
|
||||||
|
|||||||
@@ -39,6 +39,7 @@
|
|||||||
"@types/node": "^24.2.1",
|
"@types/node": "^24.2.1",
|
||||||
"@vitejs/plugin-vue": "^6.0.1",
|
"@vitejs/plugin-vue": "^6.0.1",
|
||||||
"vite": "^7.0.6",
|
"vite": "^7.0.6",
|
||||||
"vite-plugin-vue-devtools": "^8.0.0"
|
"vite-plugin-vue-devtools": "^8.0.0",
|
||||||
|
"vue-tsc": "^3.2.4"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
BIN
ui/public/bg.jpg
Normal file
BIN
ui/public/bg.jpg
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 543 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 4.2 KiB After Width: | Height: | Size: 15 KiB |
@@ -1,10 +1,11 @@
|
|||||||
<script setup>
|
<script setup lang="ts">
|
||||||
import { RouterView } from 'vue-router';
|
import { RouterView } from 'vue-router';
|
||||||
import Button from './components/ui/button/Button.vue';
|
import Button from './components/ui/button/Button.vue';
|
||||||
import { useUserStore } from './stores/user';
|
import { useUserStore } from './stores/user';
|
||||||
import Alert from './components/ui/alert/Alert.vue';
|
import Alert from './components/ui/alert/Alert.vue';
|
||||||
import AlertDescription from './components/ui/alert/AlertDescription.vue';
|
import AlertDescription from './components/ui/alert/AlertDescription.vue';
|
||||||
import Navbar from './components/Navigation/Navbar.vue';
|
import Navbar from './components/Navigation/Navbar.vue';
|
||||||
|
import { cancelLOA } from './api/loa';
|
||||||
|
|
||||||
const userStore = useUserStore();
|
const userStore = useUserStore();
|
||||||
|
|
||||||
@@ -17,22 +18,38 @@ function formatDate(dateStr) {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//@ts-ignore
|
||||||
const environment = import.meta.env.VITE_ENVIRONMENT;
|
const environment = import.meta.env.VITE_ENVIRONMENT;
|
||||||
|
//@ts-ignore
|
||||||
|
const version = import.meta.env.VITE_APPLICATION_VERSION;
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<div class="flex flex-col min-h-screen">
|
<div class="flex flex-col min-h-screen" style="background-image: linear-gradient(rgba(0, 0, 0, 0.25), rgba(0, 0, 0, 0.25)), url('/bg.jpg');
|
||||||
|
background-size: contain;
|
||||||
|
background-attachment: fixed;
|
||||||
|
background-position: center;">
|
||||||
<div class="sticky top-0 bg-background z-50">
|
<div class="sticky top-0 bg-background z-50">
|
||||||
<Navbar class="flex"></Navbar>
|
<Navbar class="flex"></Navbar>
|
||||||
<Alert v-if="environment == 'dev'" class="m-2 mx-auto w-5xl" variant="info">
|
<Alert v-if="environment == 'dev'" class="m-2 mx-auto max-w-5xl" variant="info">
|
||||||
<AlertDescription class="flex flex-row items-center text-nowrap gap-5 mx-auto">
|
<AlertDescription class="flex flex-row items-center text-wrap gap-5 mx-auto">
|
||||||
<p>This is a development build of the application. Some features will be unavailable or unstable.</p>
|
<p>Development environment (v{{ version }}). Features may be incomplete or unavailable.</p>
|
||||||
</AlertDescription>
|
</AlertDescription>
|
||||||
</Alert>
|
</Alert>
|
||||||
<Alert v-if="userStore.user?.loa?.[0]" class="m-2 mx-auto w-5xl" variant="info">
|
<Alert v-if="userStore.user?.LOAs?.[0]" class="m-2 mx-auto max-w-5xl" variant="info">
|
||||||
<AlertDescription class="flex flex-row items-center text-nowrap gap-5 mx-auto">
|
<AlertDescription class="flex flex-row items-center text-nowrap gap-5 mx-auto">
|
||||||
<p>You are on LOA until <strong>{{ formatDate(userStore.user?.loa?.[0].end_date) }}</strong></p>
|
<p
|
||||||
<Button variant="secondary">End LOA</Button>
|
v-if="new Date(userStore.user?.LOAs?.[0].extended_till || userStore.user?.LOAs?.[0].end_date) > new Date()">
|
||||||
|
LOA until <strong>{{ formatDate(userStore.user?.LOAs?.[0].extended_till ||
|
||||||
|
userStore.user?.LOAs?.[0].end_date) }}</strong>
|
||||||
|
</p>
|
||||||
|
<p v-else>
|
||||||
|
LOA expired on <strong>{{ formatDate(userStore.user?.LOAs?.[0].extended_till ||
|
||||||
|
userStore.user?.LOAs?.[0].end_date) }}</strong>
|
||||||
|
</p>
|
||||||
|
<Button variant="secondary"
|
||||||
|
@click="async () => { await cancelLOA(userStore.user.LOAs?.[0].id); userStore.loadUser(); }">End
|
||||||
|
LOA</Button>
|
||||||
</AlertDescription>
|
</AlertDescription>
|
||||||
</Alert>
|
</Alert>
|
||||||
</div>
|
</div>
|
||||||
@@ -40,5 +57,3 @@ const environment = import.meta.env.VITE_ENVIRONMENT;
|
|||||||
<RouterView class="flex-1 min-h-0"></RouterView>
|
<RouterView class="flex-1 min-h-0"></RouterView>
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<style scoped></style>
|
|
||||||
|
|||||||
@@ -1,80 +1,11 @@
|
|||||||
export type ApplicationDto = Partial<{
|
import { ApplicationFull } from "@shared/types/application";
|
||||||
age: number | string
|
|
||||||
name: string
|
|
||||||
playtime: number | string
|
|
||||||
hobbies: string
|
|
||||||
military: boolean
|
|
||||||
communities: string
|
|
||||||
joinReason: string
|
|
||||||
milsimAttraction: string
|
|
||||||
referral: string
|
|
||||||
steamProfile: string
|
|
||||||
timezone: string
|
|
||||||
canAttendSaturday: boolean
|
|
||||||
interests: string
|
|
||||||
aknowledgeRules: boolean
|
|
||||||
}>
|
|
||||||
|
|
||||||
export interface ApplicationData {
|
|
||||||
dob: string;
|
|
||||||
name: string;
|
|
||||||
playtime: number;
|
|
||||||
hobbies: string;
|
|
||||||
military: boolean;
|
|
||||||
communities: string;
|
|
||||||
joinReason: string;
|
|
||||||
milsimAttraction: string;
|
|
||||||
referral: string;
|
|
||||||
steamProfile: string;
|
|
||||||
timezone: string;
|
|
||||||
canAttendSaturday: boolean;
|
|
||||||
interests: string;
|
|
||||||
aknowledgeRules: boolean;
|
|
||||||
}
|
|
||||||
|
|
||||||
//reflects how applications are stored in the database
|
|
||||||
export interface ApplicationRow {
|
|
||||||
id: number;
|
|
||||||
member_id: number;
|
|
||||||
app_version: number;
|
|
||||||
app_data: ApplicationData;
|
|
||||||
|
|
||||||
submitted_at: string; // ISO datetime from DB (e.g., "2025-08-25T18:04:29.000Z")
|
|
||||||
updated_at: string | null;
|
|
||||||
approved_at: string | null;
|
|
||||||
denied_at: string | null;
|
|
||||||
|
|
||||||
app_status: ApplicationStatus; // generated column
|
|
||||||
decision_at: string | null; // generated column
|
|
||||||
|
|
||||||
// present when you join members (e.g., SELECT a.*, m.name AS member_name)
|
|
||||||
member_name: string;
|
|
||||||
}
|
|
||||||
export interface CommentRow {
|
|
||||||
comment_id: number;
|
|
||||||
post_content: string;
|
|
||||||
poster_id: number;
|
|
||||||
post_time: string;
|
|
||||||
last_modified: string | null;
|
|
||||||
poster_name: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface ApplicationFull {
|
|
||||||
application: ApplicationRow;
|
|
||||||
comments: CommentRow[];
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
export enum ApplicationStatus {
|
|
||||||
Pending = "Pending",
|
|
||||||
Accepted = "Accepted",
|
|
||||||
Denied = "Denied",
|
|
||||||
}
|
|
||||||
// @ts-ignore
|
// @ts-ignore
|
||||||
const addr = import.meta.env.VITE_APIHOST;
|
const addr = import.meta.env.VITE_APIHOST;
|
||||||
|
|
||||||
export async function loadApplication(id: number | string): Promise<ApplicationFull | null> {
|
export async function loadApplication(id: number | string, asAdmin: boolean = false): Promise<ApplicationFull | null> {
|
||||||
const res = await fetch(`${addr}/application/${id}`, { credentials: 'include' })
|
const res = await fetch(`${addr}/application/${id}?admin=${asAdmin}`, { credentials: 'include' })
|
||||||
if (res.status === 204) return null
|
if (res.status === 204) return null
|
||||||
if (!res.ok) throw new Error('Failed to load application')
|
if (!res.ok) throw new Error('Failed to load application')
|
||||||
const json = await res.json()
|
const json = await res.json()
|
||||||
@@ -104,6 +35,22 @@ export async function postChatMessage(message: any, post_id: number) {
|
|||||||
|
|
||||||
const response = await fetch(`${addr}/application/${post_id}/comment`, {
|
const response = await fetch(`${addr}/application/${post_id}/comment`, {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
|
credentials: 'include',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify(out),
|
||||||
|
})
|
||||||
|
|
||||||
|
return await response.json();
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function postAdminChatMessage(message: any, post_id: number) {
|
||||||
|
const out = {
|
||||||
|
message: message
|
||||||
|
}
|
||||||
|
|
||||||
|
const response = await fetch(`${addr}/application/${post_id}/adminComment`, {
|
||||||
|
method: 'POST',
|
||||||
|
credentials: 'include',
|
||||||
headers: { 'Content-Type': 'application/json' },
|
headers: { 'Content-Type': 'application/json' },
|
||||||
body: JSON.stringify(out),
|
body: JSON.stringify(out),
|
||||||
})
|
})
|
||||||
@@ -112,7 +59,9 @@ export async function postChatMessage(message: any, post_id: number) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export async function getAllApplications(): Promise<ApplicationFull> {
|
export async function getAllApplications(): Promise<ApplicationFull> {
|
||||||
const res = await fetch(`${addr}/application/all`)
|
const res = await fetch(`${addr}/application/all`, {
|
||||||
|
credentials: 'include',
|
||||||
|
})
|
||||||
|
|
||||||
if (res.ok) {
|
if (res.ok) {
|
||||||
return res.json()
|
return res.json()
|
||||||
@@ -121,18 +70,67 @@ export async function getAllApplications(): Promise<ApplicationFull> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function approveApplication(id: Number) {
|
export async function loadMyApplications(): Promise<ApplicationFull> {
|
||||||
const res = await fetch(`${addr}/application/approve/${id}`, { method: 'POST' })
|
const res = await fetch(`${addr}/application/meList`, { credentials: 'include' })
|
||||||
|
|
||||||
if (!res.ok) {
|
if (res.ok) {
|
||||||
|
return res.json()
|
||||||
|
} else {
|
||||||
console.error("Something went wrong approving the application")
|
console.error("Something went wrong approving the application")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function denyApplication(id: Number) {
|
export async function getMyApplication(id: number): Promise<ApplicationFull> {
|
||||||
const res = await fetch(`${addr}/application/deny/${id}`, { method: 'POST' })
|
const res = await fetch(`${addr}/application/me/${id}`, { credentials: 'include' })
|
||||||
|
if (res.status === 204) return null
|
||||||
|
if (res.status === 403) throw new Error("Unauthorized");
|
||||||
|
if (!res.ok) throw new Error('Failed to load application')
|
||||||
|
const json = await res.json()
|
||||||
|
// Accept either the object at root or under `application`
|
||||||
|
return json;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function approveApplication(id: Number) {
|
||||||
|
const res = await fetch(`${addr}/application/approve/${id}`, { method: 'POST', credentials: 'include' })
|
||||||
|
|
||||||
if (!res.ok) {
|
if (!res.ok) {
|
||||||
console.error("Something went wrong denying the application")
|
throw new Error("Something went wrong approving the application");
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function denyApplication(id: Number) {
|
||||||
|
const res = await fetch(`${addr}/application/deny/${id}`, { method: 'POST', credentials: 'include' })
|
||||||
|
|
||||||
|
if (!res.ok) {
|
||||||
|
throw new Error("Something went wrong denyting the application");
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function restartApplication() {
|
||||||
|
const res = await fetch(`${addr}/application/restart`, {
|
||||||
|
method: 'POST',
|
||||||
|
credentials: 'include'
|
||||||
|
})
|
||||||
|
|
||||||
|
if (!res.ok) {
|
||||||
|
console.error("Something went wrong restarting your application")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getCoC(): Promise<string> {
|
||||||
|
const res = await fetch(`${addr}/application/coc`, {
|
||||||
|
method: "GET",
|
||||||
|
credentials: 'include',
|
||||||
|
});
|
||||||
|
if (res.ok) {
|
||||||
|
const out = res.json();
|
||||||
|
if (!out) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
} else {
|
||||||
|
return null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -100,7 +100,6 @@ export async function editCalendarEvent(eventData: CalendarEvent) {
|
|||||||
export async function setCancelCalendarEvent(eventID: number, cancel: boolean) {
|
export async function setCancelCalendarEvent(eventID: number, cancel: boolean) {
|
||||||
let route = cancel ? "cancel" : "uncancel";
|
let route = cancel ? "cancel" : "uncancel";
|
||||||
|
|
||||||
console.log(route);
|
|
||||||
let res = await fetch(`${addr}/calendar/${eventID}/${route}`, {
|
let res = await fetch(`${addr}/calendar/${eventID}/${route}`, {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
credentials: "include"
|
credentials: "include"
|
||||||
|
|||||||
18
ui/src/api/docs.ts
Normal file
18
ui/src/api/docs.ts
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
// @ts-ignore
|
||||||
|
const addr = import.meta.env.VITE_APIHOST;
|
||||||
|
|
||||||
|
export async function getWelcomeMessage(): Promise<string> {
|
||||||
|
const res = await fetch(`${addr}/docs/welcome`, {
|
||||||
|
method: "GET",
|
||||||
|
credentials: 'include',
|
||||||
|
});
|
||||||
|
if (res.ok) {
|
||||||
|
const out = res.json();
|
||||||
|
if (!out) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
} else {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,12 +1,5 @@
|
|||||||
export type LOARequest = {
|
import { LOARequest, LOAType } from '@shared/types/loa'
|
||||||
id?: number;
|
import { PagedData } from '@shared/types/pagination'
|
||||||
name?: string;
|
|
||||||
member_id: number;
|
|
||||||
filed_date: string; // ISO 8601 string
|
|
||||||
start_date: string; // ISO 8601 string
|
|
||||||
end_date: string; // ISO 8601 string
|
|
||||||
reason?: string;
|
|
||||||
};
|
|
||||||
// @ts-ignore
|
// @ts-ignore
|
||||||
const addr = import.meta.env.VITE_APIHOST;
|
const addr = import.meta.env.VITE_APIHOST;
|
||||||
|
|
||||||
@@ -17,21 +10,41 @@ export async function submitLOA(request: LOARequest): Promise<{ id?: number; err
|
|||||||
"Content-Type": "application/json",
|
"Content-Type": "application/json",
|
||||||
},
|
},
|
||||||
body: JSON.stringify(request),
|
body: JSON.stringify(request),
|
||||||
|
credentials: 'include',
|
||||||
});
|
});
|
||||||
|
|
||||||
if (res.ok) {
|
if (res.ok) {
|
||||||
return res.json();
|
return;
|
||||||
} else {
|
} else {
|
||||||
return { error: "Failed to submit LOA" };
|
throw new Error("Failed to submit LOA");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export async function adminSubmitLOA(request: LOARequest): Promise<{ id?: number; error?: string }> {
|
||||||
|
const res = await fetch(`${addr}/loa/admin`, {
|
||||||
|
method: "POST",
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
},
|
||||||
|
body: JSON.stringify(request),
|
||||||
|
credentials: 'include',
|
||||||
|
});
|
||||||
|
|
||||||
|
if (res.ok) {
|
||||||
|
return
|
||||||
|
} else {
|
||||||
|
throw new Error("Failed to submit LOA");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
export async function getMyLOA(): Promise<LOARequest | null> {
|
export async function getMyLOA(): Promise<LOARequest | null> {
|
||||||
const res = await fetch(`${addr}/loa/me`, {
|
const res = await fetch(`${addr}/loa/me`, {
|
||||||
method: "GET",
|
method: "GET",
|
||||||
headers: {
|
headers: {
|
||||||
"Content-Type": "application/json",
|
"Content-Type": "application/json",
|
||||||
},
|
},
|
||||||
|
credentials: 'include',
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
||||||
@@ -46,12 +59,49 @@ export async function getMyLOA(): Promise<LOARequest | null> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export function getAllLOAs(): Promise<LOARequest[]> {
|
export async function getAllLOAs(page?: number, pageSize?: number): Promise<PagedData<LOARequest>> {
|
||||||
return fetch(`${addr}/loa/all`, {
|
const params = new URLSearchParams();
|
||||||
|
|
||||||
|
if (page !== undefined) {
|
||||||
|
params.set("page", page.toString());
|
||||||
|
}
|
||||||
|
|
||||||
|
if (pageSize !== undefined) {
|
||||||
|
params.set("pageSize", pageSize.toString());
|
||||||
|
}
|
||||||
|
|
||||||
|
return fetch(`${addr}/loa/all?${params}`, {
|
||||||
method: "GET",
|
method: "GET",
|
||||||
headers: {
|
headers: {
|
||||||
"Content-Type": "application/json",
|
"Content-Type": "application/json",
|
||||||
},
|
},
|
||||||
|
credentials: 'include',
|
||||||
|
}).then((res) => {
|
||||||
|
if (res.ok) {
|
||||||
|
return res.json();
|
||||||
|
} else {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getMyLOAs(page?: number, pageSize?: number): Promise<PagedData<LOARequest>> {
|
||||||
|
const params = new URLSearchParams();
|
||||||
|
|
||||||
|
if (page !== undefined) {
|
||||||
|
params.set("page", page.toString());
|
||||||
|
}
|
||||||
|
|
||||||
|
if (pageSize !== undefined) {
|
||||||
|
params.set("pageSize", pageSize.toString());
|
||||||
|
}
|
||||||
|
|
||||||
|
return fetch(`${addr}/loa/history?${params}`, {
|
||||||
|
method: "GET",
|
||||||
|
credentials: 'include',
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
},
|
||||||
}).then((res) => {
|
}).then((res) => {
|
||||||
if (res.ok) {
|
if (res.ok) {
|
||||||
return res.json();
|
return res.json();
|
||||||
@@ -59,4 +109,86 @@ export function getAllLOAs(): Promise<LOARequest[]> {
|
|||||||
return [];
|
return [];
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getLoaTypes(): Promise<LOAType[]> {
|
||||||
|
const res = await fetch(`${addr}/loa/types`, {
|
||||||
|
method: "GET",
|
||||||
|
credentials: 'include',
|
||||||
|
});
|
||||||
|
|
||||||
|
if (res.ok) {
|
||||||
|
const out = res.json();
|
||||||
|
if (!out) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
} else {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
export async function getLoaPolicy(): Promise<string> {
|
||||||
|
const res = await fetch(`${addr}/loa/policy`, {
|
||||||
|
method: "GET",
|
||||||
|
credentials: 'include',
|
||||||
|
});
|
||||||
|
if (res.ok) {
|
||||||
|
const out = res.json();
|
||||||
|
if (!out) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
} else {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function cancelLOA(id: number, admin: boolean = false) {
|
||||||
|
let route = admin ? 'adminCancel' : 'cancel';
|
||||||
|
const res = await fetch(`${addr}/loa/${route}/${id}`, {
|
||||||
|
method: "POST",
|
||||||
|
credentials: 'include',
|
||||||
|
});
|
||||||
|
|
||||||
|
if (res.ok) {
|
||||||
|
return
|
||||||
|
} else {
|
||||||
|
throw new Error("Could not cancel LOA");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function extendLOA(id: number, to: Date) {
|
||||||
|
const res = await fetch(`${addr}/loa/extend/${id}`, {
|
||||||
|
method: "POST",
|
||||||
|
credentials: 'include',
|
||||||
|
body: JSON.stringify({ to }),
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
if (res.ok) {
|
||||||
|
return
|
||||||
|
} else {
|
||||||
|
throw new Error("Could not extend LOA");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function adminExtendLOA(id: number, to: Date) {
|
||||||
|
const res = await fetch(`${addr}/loa/extendAdmin/${id}`, {
|
||||||
|
method: "POST",
|
||||||
|
credentials: 'include',
|
||||||
|
body: JSON.stringify({ to }),
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
if (res.ok) {
|
||||||
|
return
|
||||||
|
} else {
|
||||||
|
throw new Error("Could not extend LOA");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -1,12 +1,5 @@
|
|||||||
export type Member = {
|
import { Discharge } from "@shared/schemas/dischargeSchema";
|
||||||
member_id: number;
|
import { memberSettings, Member, MemberLight, MemberCardDetails, PaginatedMembers, MemberState, UserCacheBustResult } from "@shared/types/member";
|
||||||
member_name: string;
|
|
||||||
rank: string | null;
|
|
||||||
rank_date: string | null;
|
|
||||||
status: string | null;
|
|
||||||
status_date: string | null;
|
|
||||||
on_loa: boolean | null;
|
|
||||||
};
|
|
||||||
|
|
||||||
// @ts-ignore
|
// @ts-ignore
|
||||||
const addr = import.meta.env.VITE_APIHOST;
|
const addr = import.meta.env.VITE_APIHOST;
|
||||||
@@ -20,3 +13,161 @@ export async function getMembers(): Promise<Member[]> {
|
|||||||
}
|
}
|
||||||
return response.json();
|
return response.json();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export async function getMembersFiltered(params: {
|
||||||
|
page?: number;
|
||||||
|
pageSize?: number;
|
||||||
|
search?: string;
|
||||||
|
status?: string | MemberState;
|
||||||
|
unitId?: string;
|
||||||
|
} = {}): Promise<PaginatedMembers> {
|
||||||
|
|
||||||
|
// Construct the query string dynamically
|
||||||
|
const query = new URLSearchParams();
|
||||||
|
if (params.page) query.append('page', params.page.toString());
|
||||||
|
if (params.pageSize) query.append('pageSize', params.pageSize.toString());
|
||||||
|
if (params.search) query.append('search', params.search);
|
||||||
|
if (params.status && params.status !== 'all') query.append('status', String(params.status));
|
||||||
|
if (params.unitId && params.unitId !== 'all') query.append('unitId', params.unitId);
|
||||||
|
|
||||||
|
const response = await fetch(`${addr}/members/filtered?${query.toString()}`, {
|
||||||
|
credentials: 'include'
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error("Failed to fetch members");
|
||||||
|
}
|
||||||
|
|
||||||
|
return response.json();
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getMemberSettings(): Promise<memberSettings> {
|
||||||
|
const response = await fetch(`${addr}/members/settings`, {
|
||||||
|
credentials: 'include'
|
||||||
|
});
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error("Failed to fetch settings");
|
||||||
|
}
|
||||||
|
return response.json();
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function setMemberSettings(settings: memberSettings) {
|
||||||
|
const response = await fetch(`${addr}/members/settings`, {
|
||||||
|
credentials: 'include',
|
||||||
|
method: 'PUT',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'Application/json',
|
||||||
|
},
|
||||||
|
body: JSON.stringify(settings)
|
||||||
|
});
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error("Failed to fetch settings");
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getAllLightMembers(activeOnly: boolean = true): Promise<MemberLight[]> {
|
||||||
|
const response = await fetch(`${addr}/members/lite${activeOnly ? '?active=true' : '?active=false'}`, {
|
||||||
|
credentials: 'include',
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error("Failed to fetch light members");
|
||||||
|
}
|
||||||
|
return response.json();
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getLightMembers(ids: number[]): Promise<MemberLight[]> {
|
||||||
|
|
||||||
|
if (ids.length === 0) return [];
|
||||||
|
|
||||||
|
const response = await fetch(`${addr}/members/lite/bulk`, {
|
||||||
|
credentials: 'include',
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
},
|
||||||
|
body: JSON.stringify({ ids })
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error("Failed to fetch light members");
|
||||||
|
}
|
||||||
|
return response.json();
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getFullMembers(ids: number[]): Promise<MemberCardDetails[]> {
|
||||||
|
|
||||||
|
if (ids.length === 0) return [];
|
||||||
|
|
||||||
|
const response = await fetch(`${addr}/members/full/bulk`, {
|
||||||
|
credentials: 'include',
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
},
|
||||||
|
body: JSON.stringify({ ids })
|
||||||
|
});
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error("Failed to fetch settings");
|
||||||
|
}
|
||||||
|
return response.json();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Requests for the given member to be discharged
|
||||||
|
* @param data discharge packet
|
||||||
|
* @returns true on success
|
||||||
|
*/
|
||||||
|
export async function dischargeMember(data: Discharge): Promise<boolean> {
|
||||||
|
const response = await fetch(`${addr}/members/discharge`, {
|
||||||
|
credentials: 'include',
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
},
|
||||||
|
body: JSON.stringify(data)
|
||||||
|
});
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error("Failed to discharge member");
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function suspendMember(memberID: number): Promise<boolean> {
|
||||||
|
const response = await fetch(`${addr}/members/suspend?target=${memberID}`, {
|
||||||
|
credentials: 'include',
|
||||||
|
method: 'POST',
|
||||||
|
});
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error("Failed to discharge member");
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function unsuspendMember(memberID: number): Promise<boolean> {
|
||||||
|
const response = await fetch(`${addr}/members/unsuspend?target=${memberID}`, {
|
||||||
|
credentials: 'include',
|
||||||
|
method: 'POST',
|
||||||
|
});
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error("Failed to discharge member");
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function bustUserCache(): Promise<UserCacheBustResult> {
|
||||||
|
const response = await fetch(`${addr}/members/cache/user/bust`, {
|
||||||
|
credentials: 'include',
|
||||||
|
method: 'POST',
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error('Failed to bust user cache');
|
||||||
|
}
|
||||||
|
|
||||||
|
return response.json();
|
||||||
|
}
|
||||||
@@ -1,38 +1,73 @@
|
|||||||
export type Rank = {
|
import { BatchPromotion, BatchPromotionMember } from '@shared/schemas/promotionSchema';
|
||||||
id: number
|
import { PagedData } from '@shared/types/pagination';
|
||||||
name: string
|
import { PromotionDetails, PromotionSummary, Rank } from '@shared/types/rank'
|
||||||
short_name: string
|
|
||||||
sortOrder: number
|
|
||||||
}
|
|
||||||
|
|
||||||
// @ts-ignore
|
// @ts-ignore
|
||||||
const addr = import.meta.env.VITE_APIHOST;
|
const addr = import.meta.env.VITE_APIHOST;
|
||||||
|
|
||||||
export async function getRanks(): Promise<Rank[]> {
|
export async function getAllRanks(): Promise<Rank[]> {
|
||||||
const res = await fetch(`${addr}/ranks`)
|
const res = await fetch(`${addr}/ranks`, {
|
||||||
|
credentials: 'include'
|
||||||
|
})
|
||||||
|
|
||||||
if (res.ok) {
|
if (res.ok) {
|
||||||
return res.json()
|
return res.json()
|
||||||
} else {
|
} else {
|
||||||
console.error("Something went wrong approving the application")
|
console.error("Something went wrong approving the application")
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Placeholder: submit a rank change
|
export async function submitRankChange(promo: BatchPromotion) {
|
||||||
export async function submitRankChange(member_id: number, rank_id: number, date: string): Promise<{ ok: boolean }> {
|
|
||||||
const res = await fetch(`${addr}/memberRanks`, {
|
const res = await fetch(`${addr}/memberRanks`, {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: {
|
headers: {
|
||||||
"Content-Type": "application/json",
|
"Content-Type": "application/json",
|
||||||
},
|
},
|
||||||
body: JSON.stringify({ change: { member_id, rank_id, date } }),
|
credentials: 'include',
|
||||||
|
body: JSON.stringify(promo),
|
||||||
})
|
})
|
||||||
|
|
||||||
if (res.ok) {
|
if (res.ok) {
|
||||||
return { ok: true }
|
return
|
||||||
} else {
|
} else {
|
||||||
console.error("Failed to submit rank change")
|
throw new Error("Failed to submit rank change: Server error");
|
||||||
return { ok: false }
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getPromoHistory(page?: number, pageSize?: number): Promise<PagedData<PromotionSummary>> {
|
||||||
|
const params = new URLSearchParams();
|
||||||
|
|
||||||
|
if (page !== undefined) {
|
||||||
|
params.set("page", page.toString());
|
||||||
|
}
|
||||||
|
|
||||||
|
if (pageSize !== undefined) {
|
||||||
|
params.set("pageSize", pageSize.toString());
|
||||||
|
}
|
||||||
|
|
||||||
|
return fetch(`${addr}/memberRanks?${params}`, {
|
||||||
|
method: "GET",
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
},
|
||||||
|
credentials: 'include',
|
||||||
|
}).then((res) => {
|
||||||
|
if (res.ok) {
|
||||||
|
return res.json();
|
||||||
|
} else {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getPromotionsOnDay(day: Date): Promise<PromotionDetails[]> {
|
||||||
|
const res = await fetch(`${addr}/memberRanks/${day.toISOString()}`, {
|
||||||
|
credentials: 'include',
|
||||||
|
})
|
||||||
|
|
||||||
|
if (res.ok) {
|
||||||
|
return await res.json();
|
||||||
|
} else {
|
||||||
|
throw new Error("Failed to submit rank change: Server error");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,16 +1,13 @@
|
|||||||
export type Role = {
|
import { Member, MemberLight } from "@shared/types/member";
|
||||||
id: number;
|
import { Role } from "@shared/types/roles";
|
||||||
name: string;
|
|
||||||
color: string;
|
|
||||||
description: string | null;
|
|
||||||
members: any[];
|
|
||||||
};
|
|
||||||
|
|
||||||
// @ts-ignore
|
// @ts-ignore
|
||||||
const addr = import.meta.env.VITE_APIHOST;
|
const addr = import.meta.env.VITE_APIHOST;
|
||||||
|
|
||||||
export async function getRoles(): Promise<Role[]> {
|
export async function getRoles(): Promise<Role[]> {
|
||||||
const res = await fetch(`${addr}/roles`)
|
const res = await fetch(`${addr}/roles`, {
|
||||||
|
credentials: 'include',
|
||||||
|
})
|
||||||
|
|
||||||
if (res.ok) {
|
if (res.ok) {
|
||||||
return res.json() as Promise<Role[]>;
|
return res.json() as Promise<Role[]>;
|
||||||
@@ -20,17 +17,42 @@ export async function getRoles(): Promise<Role[]> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export async function getRoleDetails(id: number): Promise<Role> {
|
||||||
|
const res = await fetch(`${addr}/roles/${id}`, {
|
||||||
|
credentials: 'include',
|
||||||
|
})
|
||||||
|
|
||||||
|
if (res.ok) {
|
||||||
|
return res.json() as Promise<Role>;
|
||||||
|
} else {
|
||||||
|
throw new Error("Could not load role");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getRoleMembers(id: number): Promise<MemberLight[]> {
|
||||||
|
const res = await fetch(`${addr}/roles/${id}/members`, {
|
||||||
|
credentials: 'include',
|
||||||
|
})
|
||||||
|
|
||||||
|
if (res.ok) {
|
||||||
|
return res.json();
|
||||||
|
} else {
|
||||||
|
throw new Error("Could not load members");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
export async function createRole(name: string, color: string, description: string | null): Promise<Role | null> {
|
export async function createRole(name: string, color: string, description: string | null): Promise<Role | null> {
|
||||||
const res = await fetch(`${addr}/roles`, {
|
const res = await fetch(`${addr}/roles`, {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: {
|
headers: {
|
||||||
"Content-Type": "application/json"
|
"Content-Type": "application/json"
|
||||||
},
|
},
|
||||||
|
credentials: 'include',
|
||||||
body: JSON.stringify({
|
body: JSON.stringify({
|
||||||
name,
|
name,
|
||||||
color,
|
color,
|
||||||
description
|
description
|
||||||
})
|
}),
|
||||||
});
|
});
|
||||||
|
|
||||||
if (res.ok) {
|
if (res.ok) {
|
||||||
@@ -47,6 +69,7 @@ export async function addMemberToRole(member_id: number, role_id: number): Promi
|
|||||||
headers: {
|
headers: {
|
||||||
"Content-Type": "application/json"
|
"Content-Type": "application/json"
|
||||||
},
|
},
|
||||||
|
credentials: 'include',
|
||||||
body: JSON.stringify({
|
body: JSON.stringify({
|
||||||
member_id,
|
member_id,
|
||||||
role_id
|
role_id
|
||||||
@@ -64,6 +87,7 @@ export async function addMemberToRole(member_id: number, role_id: number): Promi
|
|||||||
export async function removeMemberFromRole(member_id: number, role_id: number): Promise<boolean> {
|
export async function removeMemberFromRole(member_id: number, role_id: number): Promise<boolean> {
|
||||||
const res = await fetch(`${addr}/memberRoles`, {
|
const res = await fetch(`${addr}/memberRoles`, {
|
||||||
method: "DELETE",
|
method: "DELETE",
|
||||||
|
credentials: 'include',
|
||||||
headers: {
|
headers: {
|
||||||
"Content-Type": "application/json"
|
"Content-Type": "application/json"
|
||||||
},
|
},
|
||||||
@@ -83,7 +107,8 @@ export async function removeMemberFromRole(member_id: number, role_id: number):
|
|||||||
|
|
||||||
export async function deleteRole(role_id: number): Promise<boolean> {
|
export async function deleteRole(role_id: number): Promise<boolean> {
|
||||||
const res = await fetch(`${addr}/roles/${role_id}`, {
|
const res = await fetch(`${addr}/roles/${role_id}`, {
|
||||||
method: "DELETE"
|
method: "DELETE",
|
||||||
|
credentials: 'include',
|
||||||
});
|
});
|
||||||
|
|
||||||
if (res.ok) {
|
if (res.ok) {
|
||||||
|
|||||||
@@ -1,13 +1,34 @@
|
|||||||
import { Course, CourseAttendeeRole, CourseEventDetails, CourseEventSummary } from '@shared/types/course'
|
import { Course, CourseAttendeeRole, CourseEventDetails, CourseEventSummary } from '@shared/types/course'
|
||||||
|
import { PagedData } from '@shared/types/pagination';
|
||||||
|
|
||||||
//@ts-ignore
|
//@ts-ignore
|
||||||
const addr = import.meta.env.VITE_APIHOST;
|
const addr = import.meta.env.VITE_APIHOST;
|
||||||
|
|
||||||
export async function getTrainingReports(sortMode: string, search: string): Promise<CourseEventSummary[]> {
|
export async function getTrainingReports(sortMode?: string, search?: string, page?: number, pageSize?: number): Promise<PagedData<CourseEventSummary>> {
|
||||||
const res = await fetch(`${addr}/courseEvent?sort=${sortMode}&search=${search}`);
|
const params = new URLSearchParams();
|
||||||
|
|
||||||
|
if (page !== undefined) {
|
||||||
|
params.set("page", page.toString());
|
||||||
|
}
|
||||||
|
|
||||||
|
if (pageSize !== undefined) {
|
||||||
|
params.set("pageSize", pageSize.toString());
|
||||||
|
}
|
||||||
|
|
||||||
|
if (sortMode !== undefined) {
|
||||||
|
params.set("sort", sortMode.toString());
|
||||||
|
}
|
||||||
|
|
||||||
|
if (search !== undefined || search !== "") {
|
||||||
|
params.set("search", search.toString());
|
||||||
|
}
|
||||||
|
|
||||||
|
const res = await fetch(`${addr}/courseEvent?${params}`, {
|
||||||
|
credentials: 'include',
|
||||||
|
});
|
||||||
|
|
||||||
if (res.ok) {
|
if (res.ok) {
|
||||||
return await res.json() as Promise<CourseEventSummary[]>;
|
return await res.json() as Promise<PagedData<CourseEventSummary>>;
|
||||||
} else {
|
} else {
|
||||||
console.error("Something went wrong");
|
console.error("Something went wrong");
|
||||||
throw new Error("Failed to load training reports");
|
throw new Error("Failed to load training reports");
|
||||||
@@ -15,7 +36,9 @@ export async function getTrainingReports(sortMode: string, search: string): Prom
|
|||||||
}
|
}
|
||||||
|
|
||||||
export async function getTrainingReport(id: number): Promise<CourseEventDetails> {
|
export async function getTrainingReport(id: number): Promise<CourseEventDetails> {
|
||||||
const res = await fetch(`${addr}/courseEvent/${id}`);
|
const res = await fetch(`${addr}/courseEvent/${id}`, {
|
||||||
|
credentials: 'include',
|
||||||
|
});
|
||||||
|
|
||||||
if (res.ok) {
|
if (res.ok) {
|
||||||
return await res.json() as Promise<CourseEventDetails>;
|
return await res.json() as Promise<CourseEventDetails>;
|
||||||
@@ -26,7 +49,9 @@ export async function getTrainingReport(id: number): Promise<CourseEventDetails>
|
|||||||
}
|
}
|
||||||
|
|
||||||
export async function getAllTrainings(): Promise<Course[]> {
|
export async function getAllTrainings(): Promise<Course[]> {
|
||||||
const res = await fetch(`${addr}/course`);
|
const res = await fetch(`${addr}/course`, {
|
||||||
|
credentials: 'include',
|
||||||
|
});
|
||||||
|
|
||||||
if (res.ok) {
|
if (res.ok) {
|
||||||
return await res.json() as Promise<Course[]>;
|
return await res.json() as Promise<Course[]>;
|
||||||
@@ -37,7 +62,9 @@ export async function getAllTrainings(): Promise<Course[]> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export async function getAllAttendeeRoles(): Promise<CourseAttendeeRole[]> {
|
export async function getAllAttendeeRoles(): Promise<CourseAttendeeRole[]> {
|
||||||
const res = await fetch(`${addr}/course/roles`);
|
const res = await fetch(`${addr}/course/roles`, {
|
||||||
|
credentials: 'include',
|
||||||
|
});
|
||||||
|
|
||||||
if (res.ok) {
|
if (res.ok) {
|
||||||
return await res.json() as Promise<CourseAttendeeRole[]>;
|
return await res.json() as Promise<CourseAttendeeRole[]>;
|
||||||
|
|||||||
26
ui/src/api/units.ts
Normal file
26
ui/src/api/units.ts
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
import { memberSettings, Member, MemberLight, MemberCardDetails } from "@shared/types/member";
|
||||||
|
import { Unit } from "@shared/types/units";
|
||||||
|
|
||||||
|
// @ts-ignore
|
||||||
|
const addr = import.meta.env.VITE_APIHOST;
|
||||||
|
|
||||||
|
export async function getUnits(): Promise<Unit[]> {
|
||||||
|
const response = await fetch(`${addr}/units`, {
|
||||||
|
credentials: 'include'
|
||||||
|
});
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error("Failed to fetch units");
|
||||||
|
}
|
||||||
|
return response.json();
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function adminAssignUnit(member: number, unit: number, rank: number, reason: string) {
|
||||||
|
const response = await fetch(`${addr}/memberUnits/admin?memberId=${member}&unitId=${unit}&rankId=${rank}&reason=${encodeURIComponent(reason)}`, {
|
||||||
|
method: 'POST',
|
||||||
|
credentials: 'include'
|
||||||
|
});
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error("Failed to assign unit");
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
@@ -4,7 +4,7 @@
|
|||||||
@custom-variant dark (&:is(.dark *));
|
@custom-variant dark (&:is(.dark *));
|
||||||
|
|
||||||
:root {
|
:root {
|
||||||
--background: oklch(0.2046 0 0);
|
--background: oklch(19.125% 0.00002 271.152);
|
||||||
--foreground: oklch(0.9219 0 0);
|
--foreground: oklch(0.9219 0 0);
|
||||||
--card: oklch(23.075% 0.00003 271.152);
|
--card: oklch(23.075% 0.00003 271.152);
|
||||||
--card-foreground: oklch(0.9219 0 0);
|
--card-foreground: oklch(0.9219 0 0);
|
||||||
@@ -166,3 +166,111 @@
|
|||||||
@apply bg-background text-foreground;
|
@apply bg-background text-foreground;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* Root container */
|
||||||
|
.bookstack-container {
|
||||||
|
font-family: var(--font-sans, system-ui), sans-serif;
|
||||||
|
color: var(--foreground);
|
||||||
|
line-height: 1.45;
|
||||||
|
max-width: 760px;
|
||||||
|
margin: 0 auto;
|
||||||
|
font-size: 0.9rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Headers */
|
||||||
|
.bookstack-container h4 {
|
||||||
|
margin: 0.9rem 0 0.4rem 0;
|
||||||
|
font-weight: 600;
|
||||||
|
line-height: 1.35;
|
||||||
|
font-size: 1.05rem;
|
||||||
|
color: var(--foreground);
|
||||||
|
}
|
||||||
|
|
||||||
|
.bookstack-container h5 {
|
||||||
|
margin: 0.9rem 0 0.4rem 0;
|
||||||
|
font-weight: 600;
|
||||||
|
line-height: 1.35;
|
||||||
|
font-size: 0.95rem;
|
||||||
|
color: var(--foreground);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Lists */
|
||||||
|
.bookstack-container ul {
|
||||||
|
list-style-type: disc;
|
||||||
|
margin-left: 1.1rem;
|
||||||
|
margin-bottom: 0.6rem;
|
||||||
|
padding-left: 0.6rem;
|
||||||
|
color: var(--muted-foreground);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Nested lists */
|
||||||
|
.bookstack-container ul ul {
|
||||||
|
list-style-type: circle;
|
||||||
|
margin-left: 0.9rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* List items */
|
||||||
|
.bookstack-container li {
|
||||||
|
margin: 0.15rem 0;
|
||||||
|
padding-left: 0.1rem;
|
||||||
|
color: var(--muted-foreground);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Bullet color */
|
||||||
|
.bookstack-container li::marker {
|
||||||
|
color: var(--muted-foreground);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Inline elements */
|
||||||
|
.bookstack-container li p,
|
||||||
|
.bookstack-container li span,
|
||||||
|
.bookstack-container p {
|
||||||
|
display: inline;
|
||||||
|
margin: 0;
|
||||||
|
padding: 0;
|
||||||
|
color: var(--muted-foreground);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Top-level spacing */
|
||||||
|
.bookstack-container>ul>li {
|
||||||
|
margin-top: 0.3rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* links */
|
||||||
|
.bookstack-container a {
|
||||||
|
color: var(--color-primary);
|
||||||
|
margin-top: 0.3rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.bookstack-container a:hover {
|
||||||
|
text-decoration: underline;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Scrollbar stuff */
|
||||||
|
/* Firefox */
|
||||||
|
.scrollbar-themed {
|
||||||
|
scrollbar-width: thin;
|
||||||
|
scrollbar-color: #555 #1f1f1f;
|
||||||
|
padding-right: 6px;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Chrome, Edge, Safari */
|
||||||
|
.scrollbar-themed::-webkit-scrollbar {
|
||||||
|
width: 10px;
|
||||||
|
/* slightly wider to allow padding look */
|
||||||
|
}
|
||||||
|
|
||||||
|
.scrollbar-themed::-webkit-scrollbar-track {
|
||||||
|
background: #1f1f1f;
|
||||||
|
margin-left: 6px;
|
||||||
|
/* ❗ adds space between content + scrollbar */
|
||||||
|
}
|
||||||
|
|
||||||
|
.scrollbar-themed::-webkit-scrollbar-thumb {
|
||||||
|
background: #555;
|
||||||
|
border-radius: 9999px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.scrollbar-themed::-webkit-scrollbar-thumb:hover {
|
||||||
|
background: #777;
|
||||||
|
}
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { RouterLink } from 'vue-router';
|
import { RouterLink, useRouter } from 'vue-router';
|
||||||
import Separator from '../ui/separator/Separator.vue';
|
import Separator from '../ui/separator/Separator.vue';
|
||||||
import { Popover, PopoverContent, PopoverTrigger } from '../ui/popover';
|
import { Popover, PopoverContent, PopoverTrigger } from '../ui/popover';
|
||||||
import {
|
import {
|
||||||
@@ -18,13 +18,19 @@ import NavigationMenuTrigger from '../ui/navigation-menu/NavigationMenuTrigger.v
|
|||||||
import NavigationMenuContent from '../ui/navigation-menu/NavigationMenuContent.vue';
|
import NavigationMenuContent from '../ui/navigation-menu/NavigationMenuContent.vue';
|
||||||
import { navigationMenuTriggerStyle } from '../ui/navigation-menu/'
|
import { navigationMenuTriggerStyle } from '../ui/navigation-menu/'
|
||||||
import { useAuth } from '@/composables/useAuth';
|
import { useAuth } from '@/composables/useAuth';
|
||||||
import { CircleArrowOutUpRight } from 'lucide-vue-next';
|
import { ArrowUpRight, ChevronDown, ChevronUp, CircleArrowOutUpRight, LogIn, LogOut, Menu, Settings, X } from 'lucide-vue-next';
|
||||||
|
import DropdownMenuGroup from '../ui/dropdown-menu/DropdownMenuGroup.vue';
|
||||||
|
import DropdownMenuSeparator from '../ui/dropdown-menu/DropdownMenuSeparator.vue';
|
||||||
|
import { MemberState } from '@shared/types/member';
|
||||||
|
import { computed, nextTick, ref } from 'vue';
|
||||||
|
|
||||||
const userStore = useUserStore();
|
const userStore = useUserStore();
|
||||||
const auth = useAuth();
|
const auth = useAuth();
|
||||||
|
|
||||||
//@ts-ignore
|
//@ts-ignore
|
||||||
const APIHOST = import.meta.env.VITE_APIHOST;
|
const APIHOST = import.meta.env.VITE_APIHOST;
|
||||||
|
//@ts-ignore
|
||||||
|
const DOCHOST = import.meta.env.VITE_DOCHOST;
|
||||||
|
|
||||||
async function logout() {
|
async function logout() {
|
||||||
userStore.user = null;
|
userStore.user = null;
|
||||||
@@ -36,18 +42,152 @@ function blurAfter() {
|
|||||||
(document.activeElement as HTMLElement)?.blur();
|
(document.activeElement as HTMLElement)?.blur();
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type NavItem = {
|
||||||
|
title: string;
|
||||||
|
to?: string;
|
||||||
|
href?: string;
|
||||||
|
status?: 'member' | 'guest';
|
||||||
|
isExternal?: boolean;
|
||||||
|
roles?: string[];
|
||||||
|
items?: NavItem[];
|
||||||
|
};
|
||||||
|
|
||||||
|
const navConfig: NavItem[] = [
|
||||||
|
{
|
||||||
|
title: 'Calendar',
|
||||||
|
to: '/calendar',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: 'Documents',
|
||||||
|
href: 'https://docs.iceberg-gaming.com',
|
||||||
|
status: 'member',
|
||||||
|
isExternal: true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: 'Forms',
|
||||||
|
status: 'member',
|
||||||
|
items: [
|
||||||
|
{ title: 'Leave of Absence', to: '/loa' },
|
||||||
|
{ title: 'Training Report', to: '/trainingReport' },
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: 'Administration',
|
||||||
|
status: 'member',
|
||||||
|
roles: ['17th Administrator', '17th HQ', '17th Command', 'Recruiter'],
|
||||||
|
items: [
|
||||||
|
{
|
||||||
|
title: 'Leave of Absence',
|
||||||
|
to: '/administration/loa',
|
||||||
|
roles: ['17th Administrator', '17th HQ', '17th Command']
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: 'Promotions',
|
||||||
|
to: '/administration/rankChange',
|
||||||
|
roles: ['17th Administrator', '17th HQ', '17th Command']
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: 'Recruitment',
|
||||||
|
to: '/administration/applications',
|
||||||
|
roles: ['Recruiter']
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: 'Member Management',
|
||||||
|
to: '/administration/members',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: 'Role Management',
|
||||||
|
to: '/administration/roles',
|
||||||
|
roles: ['17th Administrator']
|
||||||
|
},
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: 'Developer',
|
||||||
|
to: '/developer',
|
||||||
|
roles: ['Dev']
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: 'Join',
|
||||||
|
to: '/join',
|
||||||
|
status: 'guest',
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
const filteredNav = computed(() => {
|
||||||
|
return navConfig.flatMap(item => {
|
||||||
|
const filtered: NavItem[] = [];
|
||||||
|
|
||||||
|
// 1. Check Login Requirements
|
||||||
|
const isLoggedIn = userStore.isLoggedIn;
|
||||||
|
|
||||||
|
// 2. Determine visibility based on status
|
||||||
|
let shouldShow = false;
|
||||||
|
|
||||||
|
if (!item.status) {
|
||||||
|
// Public items - always show
|
||||||
|
shouldShow = true;
|
||||||
|
} else if (item.status === 'guest') {
|
||||||
|
// Show if NOT logged in OR logged in as guest (but NOT a member)
|
||||||
|
shouldShow = !isLoggedIn || auth.accountStatus.value === MemberState.Guest;
|
||||||
|
} else if (item.status === 'member') {
|
||||||
|
// Show ONLY if logged in as member
|
||||||
|
shouldShow = isLoggedIn && auth.accountStatus.value === MemberState.Member;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. Check Role Requirements (if status check passed)
|
||||||
|
if (shouldShow && item.roles) {
|
||||||
|
shouldShow = auth.hasAnyRole(item.roles);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (shouldShow) {
|
||||||
|
if (item.items) {
|
||||||
|
const filteredItems = item.items.filter(subItem =>
|
||||||
|
!subItem.roles || auth.hasAnyRole(subItem.roles)
|
||||||
|
);
|
||||||
|
filtered.push({ ...item, items: filteredItems });
|
||||||
|
} else {
|
||||||
|
filtered.push(item);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return filtered;
|
||||||
|
});
|
||||||
|
})
|
||||||
|
|
||||||
|
const isMobileMenuOpen = ref(false);
|
||||||
|
const expandedMenu = ref(null);
|
||||||
|
|
||||||
|
const router = useRouter();
|
||||||
|
|
||||||
|
function openMobileMenu() {
|
||||||
|
expandedMenu.value = null;
|
||||||
|
isMobileMenuOpen.value = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
function closeMobileMenu() {
|
||||||
|
isMobileMenuOpen.value = false;
|
||||||
|
expandedMenu.value = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function mobileNavigateTo(to: string) {
|
||||||
|
closeMobileMenu();
|
||||||
|
router.push(to);
|
||||||
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<div class="w-full border-b">
|
<div class="w-full border-b">
|
||||||
<div class="max-w-screen-3xl w-full mx-auto flex items-center justify-between pr-10 pl-7">
|
<div class="hidden lg:flex max-w-screen-3xl w-full mx-auto items-center justify-between pr-10 pl-7">
|
||||||
<!-- left side -->
|
<!-- left side -->
|
||||||
<div class="flex items-center gap-7">
|
<div class="flex items-center gap-7">
|
||||||
<RouterLink to="/">
|
<RouterLink to="/">
|
||||||
<img src="/17RBN_Logo.png" class="w-10 h-10 object-contain"></img>
|
<img src="/17RBN_Logo.png" class="w-10 h-10 object-contain"></img>
|
||||||
</RouterLink>
|
</RouterLink>
|
||||||
<!-- Member navigation -->
|
<!-- Member navigation -->
|
||||||
<div v-if="auth.accountStatus.value == 'member'" class="h-15 flex items-center justify-center">
|
<div v-if="auth.accountStatus.value == MemberState.Member"
|
||||||
|
class="h-15 flex items-center justify-center">
|
||||||
<NavigationMenu>
|
<NavigationMenu>
|
||||||
<NavigationMenuList class="gap-3">
|
<NavigationMenuList class="gap-3">
|
||||||
|
|
||||||
@@ -58,10 +198,15 @@ function blurAfter() {
|
|||||||
</NavigationMenuLink>
|
</NavigationMenuLink>
|
||||||
</NavigationMenuItem>
|
</NavigationMenuItem>
|
||||||
|
|
||||||
<!-- Members -->
|
<!-- Docs -->
|
||||||
<NavigationMenuItem>
|
<NavigationMenuItem>
|
||||||
<NavigationMenuLink as-child :class="navigationMenuTriggerStyle()">
|
<NavigationMenuLink as-child :class="navigationMenuTriggerStyle()">
|
||||||
<RouterLink to="/" @click="blurAfter">Documents</RouterLink>
|
<a href="https://docs.iceberg-gaming.com" target="_blank">
|
||||||
|
<span class="flex items-center gap-1">
|
||||||
|
Documents
|
||||||
|
<ArrowUpRight class="h-4 w-4" />
|
||||||
|
</span>
|
||||||
|
</a>
|
||||||
</NavigationMenuLink>
|
</NavigationMenuLink>
|
||||||
</NavigationMenuItem>
|
</NavigationMenuItem>
|
||||||
|
|
||||||
@@ -76,11 +221,11 @@ function blurAfter() {
|
|||||||
</RouterLink>
|
</RouterLink>
|
||||||
</NavigationMenuLink>
|
</NavigationMenuLink>
|
||||||
|
|
||||||
<NavigationMenuLink as-child :class="navigationMenuTriggerStyle()">
|
<!-- <NavigationMenuLink as-child :class="navigationMenuTriggerStyle()">
|
||||||
<RouterLink to="/transfer" @click="blurAfter">
|
<RouterLink to="/transfer" @click="blurAfter">
|
||||||
Transfer Request
|
Transfer Request
|
||||||
</RouterLink>
|
</RouterLink>
|
||||||
</NavigationMenuLink>
|
</NavigationMenuLink> -->
|
||||||
|
|
||||||
<NavigationMenuLink as-child :class="navigationMenuTriggerStyle()">
|
<NavigationMenuLink as-child :class="navigationMenuTriggerStyle()">
|
||||||
<RouterLink to="/trainingReport" @click="blurAfter">
|
<RouterLink to="/trainingReport" @click="blurAfter">
|
||||||
@@ -98,13 +243,13 @@ function blurAfter() {
|
|||||||
<NavigationMenuContent
|
<NavigationMenuContent
|
||||||
class="grid gap-1 p-2 text-left [&_a]:w-full [&_a]:block [&_a]:whitespace-nowrap *:bg-transparent">
|
class="grid gap-1 p-2 text-left [&_a]:w-full [&_a]:block [&_a]:whitespace-nowrap *:bg-transparent">
|
||||||
|
|
||||||
<NavigationMenuLink
|
<!-- <NavigationMenuLink
|
||||||
v-if="auth.hasAnyRole(['17th Administrator', '17th HQ', '17th Command'])"
|
v-if="auth.hasAnyRole(['17th Administrator', '17th HQ', '17th Command'])"
|
||||||
as-child :class="navigationMenuTriggerStyle()">
|
as-child :class="navigationMenuTriggerStyle()">
|
||||||
<RouterLink to="/administration/rankChange" @click="blurAfter">
|
<RouterLink to="/administration/rankChange" @click="blurAfter">
|
||||||
Promotions
|
Promotions
|
||||||
</RouterLink>
|
</RouterLink>
|
||||||
</NavigationMenuLink>
|
</NavigationMenuLink> -->
|
||||||
|
|
||||||
<NavigationMenuLink
|
<NavigationMenuLink
|
||||||
v-if="auth.hasAnyRole(['17th Administrator', '17th HQ', '17th Command'])"
|
v-if="auth.hasAnyRole(['17th Administrator', '17th HQ', '17th Command'])"
|
||||||
@@ -117,8 +262,8 @@ function blurAfter() {
|
|||||||
<NavigationMenuLink
|
<NavigationMenuLink
|
||||||
v-if="auth.hasAnyRole(['17th Administrator', '17th HQ', '17th Command'])"
|
v-if="auth.hasAnyRole(['17th Administrator', '17th HQ', '17th Command'])"
|
||||||
as-child :class="navigationMenuTriggerStyle()">
|
as-child :class="navigationMenuTriggerStyle()">
|
||||||
<RouterLink to="/administration/transfer" @click="blurAfter">
|
<RouterLink to="/administration/rankChange" @click="blurAfter">
|
||||||
Transfer Requests
|
Promotions
|
||||||
</RouterLink>
|
</RouterLink>
|
||||||
</NavigationMenuLink>
|
</NavigationMenuLink>
|
||||||
|
|
||||||
@@ -129,6 +274,12 @@ function blurAfter() {
|
|||||||
</RouterLink>
|
</RouterLink>
|
||||||
</NavigationMenuLink>
|
</NavigationMenuLink>
|
||||||
|
|
||||||
|
<NavigationMenuItem as-child :class="navigationMenuTriggerStyle()">
|
||||||
|
<RouterLink to="/administration/members" @click="blurAfter">
|
||||||
|
Member Management
|
||||||
|
</RouterLink>
|
||||||
|
</NavigationMenuItem>
|
||||||
|
|
||||||
<NavigationMenuLink v-if="auth.hasRole('17th Administrator')" as-child
|
<NavigationMenuLink v-if="auth.hasRole('17th Administrator')" as-child
|
||||||
:class="navigationMenuTriggerStyle()">
|
:class="navigationMenuTriggerStyle()">
|
||||||
<RouterLink to="/administration/roles" @click="blurAfter">
|
<RouterLink to="/administration/roles" @click="blurAfter">
|
||||||
@@ -138,12 +289,11 @@ function blurAfter() {
|
|||||||
</NavigationMenuContent>
|
</NavigationMenuContent>
|
||||||
</NavigationMenuItem>
|
</NavigationMenuItem>
|
||||||
|
|
||||||
<NavigationMenuItem as-child :class="navigationMenuTriggerStyle()">
|
<NavigationMenuItem v-if="auth.hasRole('Dev')">
|
||||||
<RouterLink to="/members" @click="blurAfter">
|
<NavigationMenuLink as-child :class="navigationMenuTriggerStyle()">
|
||||||
Members (debug)
|
<RouterLink to="/developer" @click="blurAfter">Developer</RouterLink>
|
||||||
</RouterLink>
|
</NavigationMenuLink>
|
||||||
</NavigationMenuItem>
|
</NavigationMenuItem>
|
||||||
|
|
||||||
</NavigationMenuList>
|
</NavigationMenuList>
|
||||||
</NavigationMenu>
|
</NavigationMenu>
|
||||||
</div>
|
</div>
|
||||||
@@ -170,18 +320,126 @@ function blurAfter() {
|
|||||||
<div>
|
<div>
|
||||||
<DropdownMenu v-if="userStore.isLoggedIn">
|
<DropdownMenu v-if="userStore.isLoggedIn">
|
||||||
<DropdownMenuTrigger class="cursor-pointer">
|
<DropdownMenuTrigger class="cursor-pointer">
|
||||||
<p>{{ userStore.user.name }}</p>
|
<Button variant="ghost" class="px-4">
|
||||||
|
{{ userStore.displayName }}
|
||||||
|
</Button>
|
||||||
</DropdownMenuTrigger>
|
</DropdownMenuTrigger>
|
||||||
<DropdownMenuContent>
|
<DropdownMenuContent>
|
||||||
<!-- <DropdownMenuItem>My Profile</DropdownMenuItem> -->
|
<DropdownMenuItem @click="$router.push('/profile')">My Profile</DropdownMenuItem>
|
||||||
|
<DropdownMenuSeparator></DropdownMenuSeparator>
|
||||||
<!-- <DropdownMenuItem>Settings</DropdownMenuItem> -->
|
<!-- <DropdownMenuItem>Settings</DropdownMenuItem> -->
|
||||||
<DropdownMenuItem @click="$router.push('/join')">My Application</DropdownMenuItem>
|
<DropdownMenuItem @click="$router.push('/join')">My Application</DropdownMenuItem>
|
||||||
|
<DropdownMenuItem @click="$router.push('/applications')">Application History</DropdownMenuItem>
|
||||||
|
<DropdownMenuSeparator></DropdownMenuSeparator>
|
||||||
<DropdownMenuItem :variant="'destructive'" @click="logout()">Logout</DropdownMenuItem>
|
<DropdownMenuItem :variant="'destructive'" @click="logout()">Logout</DropdownMenuItem>
|
||||||
</DropdownMenuContent>
|
</DropdownMenuContent>
|
||||||
</DropdownMenu>
|
</DropdownMenu>
|
||||||
<a v-else :href="APIHOST + '/login'">Login</a>
|
<a v-else :href="APIHOST + '/login'">Login</a>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<!-- <Separator></Separator> -->
|
|
||||||
|
<!-- mobile navigation -->
|
||||||
|
<div class="flex flex-col lg:hidden w-full" :class="isMobileMenuOpen ? 'h-screen' : ''">
|
||||||
|
<div class="flex items-center justify-between w-full p-2">
|
||||||
|
<!-- <RouterLink to="/">
|
||||||
|
<img src="/17RBN_Logo.png" class="w-10 h-10 object-contain"></img>
|
||||||
|
</RouterLink> -->
|
||||||
|
<button @click="mobileNavigateTo('/')">
|
||||||
|
<img src="/17RBN_Logo.png" class="w-10 h-10 object-contain"></img>
|
||||||
|
</button>
|
||||||
|
|
||||||
|
<Button v-if="!isMobileMenuOpen" variant="ghost" size="icon" @click="openMobileMenu()">
|
||||||
|
<Menu class="size-7" />
|
||||||
|
</Button>
|
||||||
|
<Button v-else variant="ghost" size="icon" @click="closeMobileMenu()">
|
||||||
|
<X class="size-7" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
<div v-if="isMobileMenuOpen" class="flex flex-col h-[calc(100vh-60px)] overflow-hidden">
|
||||||
|
<div class="flex-1 overflow-y-auto px-2 py-3 space-y-0.5">
|
||||||
|
<div v-for="navItem in filteredNav" :key="navItem.title" class="group">
|
||||||
|
|
||||||
|
<template v-if="!navItem.items">
|
||||||
|
<a v-if="navItem.isExternal" :href="navItem.href" target="_blank"
|
||||||
|
class="flex items-center justify-between w-full px-4 py-2.5 text-base font-medium rounded-md hover:bg-accent active:bg-accent transition-colors">
|
||||||
|
<span class="flex items-center gap-2">
|
||||||
|
{{ navItem.title }}
|
||||||
|
<ArrowUpRight class="h-3.5 w-3.5 opacity-50" />
|
||||||
|
</span>
|
||||||
|
</a>
|
||||||
|
<button v-else @click="mobileNavigateTo(navItem.to)"
|
||||||
|
class="w-full text-left px-4 py-2.5 text-base font-medium rounded-md hover:bg-accent active:bg-accent transition-colors">
|
||||||
|
{{ navItem.title }}
|
||||||
|
</button>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<div v-else class="space-y-0.5">
|
||||||
|
<button @click="expandedMenu = expandedMenu === navItem.title ? null : navItem.title"
|
||||||
|
class="flex items-center justify-between w-full px-4 py-2.5 text-base font-medium rounded-md transition-colors"
|
||||||
|
:class="expandedMenu === navItem.title ? 'bg-accent/50 text-primary' : 'hover:bg-accent'">
|
||||||
|
{{ navItem.title }}
|
||||||
|
<ChevronDown class="h-4 w-4 transition-transform duration-200"
|
||||||
|
:class="expandedMenu === navItem.title ? 'rotate-180' : ''" />
|
||||||
|
</button>
|
||||||
|
|
||||||
|
<div v-if="expandedMenu === navItem.title"
|
||||||
|
class="ml-4 mr-2 border-l border-border space-y-0.5">
|
||||||
|
<button v-for="subNavItem in navItem.items" :key="subNavItem.title"
|
||||||
|
@click="mobileNavigateTo(subNavItem.to)"
|
||||||
|
class="w-full text-left px-6 py-2 text-sm text-muted-foreground hover:text-foreground active:text-primary transition-colors">
|
||||||
|
{{ subNavItem.title }}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="p-3 border-t bg-background mt-auto">
|
||||||
|
<div v-if="userStore.isLoggedIn" class="space-y-3">
|
||||||
|
<div class="flex items-center justify-between px-2">
|
||||||
|
<div class="flex gap-3">
|
||||||
|
<!-- <div
|
||||||
|
class="size-8 rounded-full bg-primary/10 flex items-center justify-center text-xs font-bold text-primary">
|
||||||
|
{{ userStore.displayName?.charAt(0) }}
|
||||||
|
</div> -->
|
||||||
|
<div class="flex flex-col leading-tight">
|
||||||
|
<span class="text-sm font-semibold">
|
||||||
|
{{ userStore.displayName || userStore.user.member.member_name }}
|
||||||
|
</span>
|
||||||
|
<span v-if="userStore.displayName"
|
||||||
|
class="text-[10px] uppercase tracking-wider text-muted-foreground">
|
||||||
|
{{ userStore.user.member.member_name }}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="flex items-center gap-3">
|
||||||
|
<Button variant="ghost" size="icon" @click="mobileNavigateTo('/profile')">
|
||||||
|
<Settings class="size-6"></Settings>
|
||||||
|
</Button>
|
||||||
|
<Button variant="ghost" size="icon" @click="logout()">
|
||||||
|
<LogOut class="size-6 text-destructive"></LogOut>
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="flex gap-2">
|
||||||
|
<!-- <Button variant="outline" size="xs" class="flex-1 h-8 text-xs"
|
||||||
|
@click="mobileNavigateTo('/profile')">Profile</Button> -->
|
||||||
|
<Button variant="secondary" size="xs" class="flex-1 h-8 text-xs"
|
||||||
|
@click="mobileNavigateTo('/join')">My
|
||||||
|
Application</Button>
|
||||||
|
<Button variant="secondary" size="xs" class="flex-1 h-8 text-xs"
|
||||||
|
@click="mobileNavigateTo('/applications')">Application History</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<a v-else :href="APIHOST + '/login'" class="block">
|
||||||
|
<Button class="w-full text-sm h-10">
|
||||||
|
<LogIn></LogIn> Login
|
||||||
|
</Button>
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
@@ -11,13 +11,22 @@ import {
|
|||||||
import Textarea from '@/components/ui/textarea/Textarea.vue'
|
import Textarea from '@/components/ui/textarea/Textarea.vue'
|
||||||
import { toTypedSchema } from '@vee-validate/zod'
|
import { toTypedSchema } from '@vee-validate/zod'
|
||||||
import * as z from 'zod'
|
import * as z from 'zod'
|
||||||
|
import { useAuth } from '@/composables/useAuth'
|
||||||
|
import { CommentRow } from '@shared/types/application'
|
||||||
|
import { Dot } from 'lucide-vue-next'
|
||||||
|
import { ref } from 'vue'
|
||||||
|
import MemberCard from '../members/MemberCard.vue'
|
||||||
|
|
||||||
const props = defineProps<{
|
const props = withDefaults(defineProps<{
|
||||||
messages: Array<Record<string, any>>
|
messages: CommentRow[]
|
||||||
}>()
|
adminMode?: boolean
|
||||||
|
}>(), {
|
||||||
|
adminMode: false,
|
||||||
|
})
|
||||||
|
|
||||||
const emit = defineEmits<{
|
const emit = defineEmits<{
|
||||||
(e: 'post', text: string): void
|
(e: 'post', text: string): void
|
||||||
|
(e: 'postInternal', text: string): void
|
||||||
}>()
|
}>()
|
||||||
|
|
||||||
const commentSchema = toTypedSchema(
|
const commentSchema = toTypedSchema(
|
||||||
@@ -26,8 +35,13 @@ const commentSchema = toTypedSchema(
|
|||||||
})
|
})
|
||||||
)
|
)
|
||||||
|
|
||||||
|
const submitMode = ref("public");
|
||||||
|
|
||||||
// vee-validate passes (values, actions) to @submit
|
// vee-validate passes (values, actions) to @submit
|
||||||
function onSubmit(values: { text: string }, { resetForm }: { resetForm: () => void }) {
|
function onSubmit(values: { text: string }, { resetForm }: { resetForm: () => void }) {
|
||||||
|
if (submitMode.value === "internal")
|
||||||
|
emit('postInternal', values.text.trim())
|
||||||
|
else
|
||||||
emit('post', values.text.trim())
|
emit('post', values.text.trim())
|
||||||
resetForm()
|
resetForm()
|
||||||
}
|
}
|
||||||
@@ -48,18 +62,24 @@ function onSubmit(values: { text: string }, { resetForm }: { resetForm: () => vo
|
|||||||
</FormField>
|
</FormField>
|
||||||
|
|
||||||
<!-- Button below, right-aligned -->
|
<!-- Button below, right-aligned -->
|
||||||
<div class="mt-2 flex justify-end">
|
<div class="mt-2 flex justify-end gap-2">
|
||||||
<Button type="submit">Post</Button>
|
<Button v-if="adminMode" type="submit" @click="submitMode = 'internal'" variant="outline">Post (Internal)</Button>
|
||||||
|
<Button type="submit" @click="submitMode = 'public'">{{ adminMode ? 'Post (Public)' : 'Post' }}</Button>
|
||||||
</div>
|
</div>
|
||||||
</Form>
|
</Form>
|
||||||
|
|
||||||
<!-- Existing posts -->
|
<!-- Existing posts -->
|
||||||
<div class="space-y-3">
|
<div class="space-y-3">
|
||||||
<div v-for="(message, i) in props.messages" :key="message.id ?? i"
|
<div v-for="(message, i) in props.messages" :key="message.comment_id ?? i" class="rounded-md border p-3 space-y-5"
|
||||||
class="rounded-md border border-neutral-800 p-3 space-y-5">
|
:class="message.admin_only ? 'border-amber-300/70' : 'border-neutral-800'">
|
||||||
<!-- Comment header -->
|
<!-- Comment header -->
|
||||||
<div class="flex justify-between">
|
<div class="flex justify-between">
|
||||||
<p>{{ message.poster_name }}</p>
|
<div class="flex">
|
||||||
|
<MemberCard :member-id="message.poster_id"></MemberCard>
|
||||||
|
<p v-if="message.admin_only" class="flex">
|
||||||
|
<Dot /><span class="text-amber-300">Internal</span>
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
<p class="text-muted-foreground">{{ new Date(message.post_time).toLocaleString("EN-us", {
|
<p class="text-muted-foreground">{{ new Date(message.post_time).toLocaleString("EN-us", {
|
||||||
year: "numeric",
|
year: "numeric",
|
||||||
month: "long",
|
month: "long",
|
||||||
|
|||||||
@@ -1,38 +1,50 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import Button from '@/components/ui/button/Button.vue';
|
import Button from '@/components/ui/button/Button.vue';
|
||||||
import Checkbox from '@/components/ui/checkbox/Checkbox.vue';
|
import Checkbox from '@/components/ui/checkbox/Checkbox.vue';
|
||||||
|
import { useForm, Field as VeeField } from 'vee-validate';
|
||||||
import {
|
import {
|
||||||
FormControl,
|
Field,
|
||||||
FormDescription,
|
FieldContent,
|
||||||
FormField,
|
FieldDescription,
|
||||||
FormItem,
|
FieldGroup,
|
||||||
FormLabel,
|
FieldLabel,
|
||||||
FormMessage,
|
} from '@/components/ui/field'
|
||||||
} from '@/components/ui/form'
|
import FieldError from '@/components/ui/field/FieldError.vue';
|
||||||
import Input from '@/components/ui/input/Input.vue';
|
import Input from '@/components/ui/input/Input.vue';
|
||||||
import Textarea from '@/components/ui/textarea/Textarea.vue';
|
import Textarea from '@/components/ui/textarea/Textarea.vue';
|
||||||
import { toTypedSchema } from '@vee-validate/zod';
|
import { toTypedSchema } from '@vee-validate/zod';
|
||||||
import { Form } from 'vee-validate';
|
import { nextTick, onMounted, ref, watch } from 'vue';
|
||||||
import { onMounted, ref } from 'vue';
|
|
||||||
import * as z from 'zod';
|
import * as z from 'zod';
|
||||||
import DateInput from '../form/DateInput.vue';
|
import DateInput from '../form/DateInput.vue';
|
||||||
import { ApplicationData } from '@/api/application';
|
import { ApplicationData } from '@shared/types/application';
|
||||||
|
import Dialog from '../ui/dialog/Dialog.vue';
|
||||||
|
import DialogTrigger from '../ui/dialog/DialogTrigger.vue';
|
||||||
|
import DialogContent from '../ui/dialog/DialogContent.vue';
|
||||||
|
import DialogHeader from '../ui/dialog/DialogHeader.vue';
|
||||||
|
import DialogTitle from '../ui/dialog/DialogTitle.vue';
|
||||||
|
import DialogDescription from '../ui/dialog/DialogDescription.vue';
|
||||||
|
import { getCoC } from '@/api/application';
|
||||||
|
import { startBrowserTracingPageLoadSpan } from '@sentry/vue';
|
||||||
|
|
||||||
|
const regexA = /^https?:\/\/steamcommunity\.com\/id\/[A-Za-z0-9_]+\/?$/;
|
||||||
|
const regexB = /^https?:\/\/steamcommunity\.com\/profiles\/\d+\/?$/;
|
||||||
|
|
||||||
|
|
||||||
const formSchema = toTypedSchema(z.object({
|
const formSchema = toTypedSchema(z.object({
|
||||||
dob: z.string().refine(v => v, { message: "A date of birth is required." }),
|
dob: z.string().refine(v => v, { message: "A date of birth is required." }),
|
||||||
name: z.string(),
|
name: z.string().nonempty(),
|
||||||
playtime: z.coerce.number({ invalid_type_error: "Must be a number", }).min(0, "Cannot be less than 0"),
|
playtime: z.preprocess((v) => (v === "" ? undefined : String(v)), z.string({ required_error: "Required" }).regex(/^\d+(\.\d+)?$/, "Must be a number").transform(Number).refine((n) => n >= 0, "Cannot be less than 0")),
|
||||||
hobbies: z.string(),
|
hobbies: z.string().nonempty(),
|
||||||
military: z.boolean(),
|
military: z.boolean(),
|
||||||
communities: z.string(),
|
communities: z.string().nonempty(),
|
||||||
joinReason: z.string(),
|
joinReason: z.string().nonempty(),
|
||||||
milsimAttraction: z.string(),
|
milsimAttraction: z.string().nonempty(),
|
||||||
referral: z.string(),
|
referral: z.string().nonempty(),
|
||||||
steamProfile: z.string(),
|
steamProfile: z.string().nonempty().refine((val) => regexA.test(val) || regexB.test(val), { message: "Invalid Steam profile URL." }),
|
||||||
timezone: z.string(),
|
timezone: z.string().nonempty(),
|
||||||
canAttendSaturday: z.boolean(),
|
canAttendSaturday: z.boolean(),
|
||||||
interests: z.string(),
|
interests: z.string().nonempty(),
|
||||||
aknowledgeRules: z.literal(true, {
|
acknowledgeRules: z.literal(true, {
|
||||||
errorMap: () => ({ message: "Required" })
|
errorMap: () => ({ message: "Required" })
|
||||||
}),
|
}),
|
||||||
}))
|
}))
|
||||||
@@ -41,23 +53,32 @@ const formSchema = toTypedSchema(z.object({
|
|||||||
const fallbackInitials = {
|
const fallbackInitials = {
|
||||||
military: false,
|
military: false,
|
||||||
canAttendSaturday: false,
|
canAttendSaturday: false,
|
||||||
aknowledgeRules: false,
|
acknowledgeRules: false,
|
||||||
}
|
}
|
||||||
|
|
||||||
const props = defineProps<{
|
const props = defineProps<{
|
||||||
readOnly: boolean,
|
readOnly: boolean,
|
||||||
data: ApplicationData,
|
data: ApplicationData | null,
|
||||||
}>()
|
}>()
|
||||||
|
|
||||||
const emit = defineEmits(['submit']);
|
const emit = defineEmits(['submit']);
|
||||||
|
|
||||||
const initialValues = ref<Record<string, unknown> | null>(null);
|
const initialValues = ref<Record<string, unknown> | null>(null);
|
||||||
|
|
||||||
|
const { handleSubmit, resetForm, values } = useForm({
|
||||||
|
validationSchema: formSchema,
|
||||||
|
validateOnMount: false,
|
||||||
|
});
|
||||||
|
|
||||||
|
const submitForm = handleSubmit(async (val) => {
|
||||||
|
await onSubmit(val);
|
||||||
|
});
|
||||||
|
|
||||||
async function onSubmit(val: any) {
|
async function onSubmit(val: any) {
|
||||||
emit('submit', val);
|
emit('submit', val);
|
||||||
}
|
}
|
||||||
|
|
||||||
onMounted(() => {
|
onMounted(async () => {
|
||||||
if (props.data !== null) {
|
if (props.data !== null) {
|
||||||
const parsed = typeof props.data === "string"
|
const parsed = typeof props.data === "string"
|
||||||
? JSON.parse(props.data)
|
? JSON.parse(props.data)
|
||||||
@@ -67,192 +88,279 @@ onMounted(() => {
|
|||||||
} else {
|
} else {
|
||||||
initialValues.value = { ...fallbackInitials };
|
initialValues.value = { ...fallbackInitials };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// apply the initial values to the vee-validate form
|
||||||
|
resetForm({ values: initialValues.value });
|
||||||
|
|
||||||
|
// CoCbox.value.innerHTML = await getCoC()
|
||||||
|
CoCString.value = await getCoC();
|
||||||
})
|
})
|
||||||
|
|
||||||
|
const showCoC = ref(false);
|
||||||
|
const CoCbox = ref<HTMLElement>();
|
||||||
|
const CoCString = ref<string>();
|
||||||
|
|
||||||
|
async function onDialogToggle(state: boolean) {
|
||||||
|
showCoC.value = state;
|
||||||
|
}
|
||||||
|
|
||||||
|
function enforceExternalLinks() {
|
||||||
|
if (!CoCbox.value) return;
|
||||||
|
|
||||||
|
const links = CoCbox.value.querySelectorAll("a");
|
||||||
|
links.forEach(a => {
|
||||||
|
a.setAttribute("target", "_blank");
|
||||||
|
a.setAttribute("rel", "noopener noreferrer");
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
watch(() => showCoC.value, async () => {
|
||||||
|
if (showCoC.value) {
|
||||||
|
await nextTick(); // wait for v-html to update
|
||||||
|
enforceExternalLinks();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
function convertToAge(dob: string) {
|
||||||
|
|
||||||
|
if (dob === undefined) return "";
|
||||||
|
const [month, day, year] = dob.split('/').map(Number);
|
||||||
|
|
||||||
|
let dobDate = new Date(year, month - 1, day);
|
||||||
|
|
||||||
|
let out = Math.floor(
|
||||||
|
(Date.now() - dobDate.getTime()) / (1000 * 60 * 60 * 24 * 365.2425)
|
||||||
|
);
|
||||||
|
|
||||||
|
return Number.isNaN(out) ? "" : out;
|
||||||
|
}
|
||||||
|
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<Form v-if="initialValues" :validation-schema="formSchema" :initial-values="initialValues" @submit="onSubmit"
|
<form v-if="initialValues" @submit.prevent="submitForm" class="space-y-6">
|
||||||
class="space-y-6">
|
|
||||||
<!-- Age -->
|
<!-- Age -->
|
||||||
<FormField name="dob" v-slot="{ value, handleChange }">
|
<VeeField name="dob" v-slot="{ field, errors }">
|
||||||
<FormItem>
|
<Field>
|
||||||
<FormLabel>What is your date of birth?</FormLabel>
|
<FieldLabel>What is your date of birth?</FieldLabel>
|
||||||
<FormControl>
|
<FieldContent>
|
||||||
<DateInput :model-value="(value as string) ?? ''" :disabled="readOnly" @update:model-value="handleChange" />
|
<div class="flex items-center gap-10">
|
||||||
</FormControl>
|
<DateInput :model-value="(field.value as string) ?? ''" :disabled="readOnly" @update:model-value="field.onChange" />
|
||||||
<FormMessage />
|
<p v-if="props.readOnly" class="text-muted-foreground">Age: {{ convertToAge(field.value) }}</p>
|
||||||
</FormItem>
|
</div>
|
||||||
</FormField>
|
</FieldContent>
|
||||||
|
<div class="h-4">
|
||||||
|
<FieldError v-if="errors.length" :errors="errors" />
|
||||||
|
</div>
|
||||||
|
</Field>
|
||||||
|
</VeeField>
|
||||||
|
|
||||||
<!-- Name -->
|
<!-- Name -->
|
||||||
<FormField name="name" v-slot="{ value, handleChange }">
|
<VeeField name="name" v-slot="{ field, errors }">
|
||||||
<FormItem>
|
<Field>
|
||||||
<FormLabel>What name will you be going by within the community?</FormLabel>
|
<FieldLabel>What name will you be going by within the community?</FieldLabel>
|
||||||
<FormDescription>This name must be consistent across platforms.</FormDescription>
|
<FieldDescription>This name must be consistent across platforms.</FieldDescription>
|
||||||
<FormControl>
|
<FieldContent>
|
||||||
<Input :model-value="value" @update:model-value="handleChange" :disabled="readOnly" />
|
<Input :model-value="field.value" @update:model-value="field.onChange" :disabled="readOnly" />
|
||||||
</FormControl>
|
</FieldContent>
|
||||||
<FormMessage />
|
<div class="h-4">
|
||||||
</FormItem>
|
<FieldError v-if="errors.length" :errors="errors" />
|
||||||
</FormField>
|
</div>
|
||||||
|
</Field>
|
||||||
|
</VeeField>
|
||||||
|
|
||||||
<!-- Playtime -->
|
<!-- Playtime -->
|
||||||
<FormField name="playtime" v-slot="{ value, handleChange }">
|
<VeeField name="playtime" v-slot="{ field, errors }">
|
||||||
<FormItem>
|
<Field>
|
||||||
<FormLabel>How long have you played Arma 3 for (in hours)?</FormLabel>
|
<FieldLabel>How long have you played Arma 3 for (in hours)?</FieldLabel>
|
||||||
<FormControl>
|
<FieldContent>
|
||||||
<Input type="number" :model-value="value" @update:model-value="handleChange" :disabled="readOnly" />
|
<Input type="number" :model-value="field.value" @update:model-value="field.onChange" :disabled="readOnly" />
|
||||||
</FormControl>
|
</FieldContent>
|
||||||
<FormMessage />
|
<div class="h-4">
|
||||||
</FormItem>
|
<FieldError v-if="errors.length" :errors="errors" />
|
||||||
</FormField>
|
</div>
|
||||||
|
</Field>
|
||||||
|
</VeeField>
|
||||||
|
|
||||||
<!-- Hobbies -->
|
<!-- Hobbies -->
|
||||||
<FormField name="hobbies" v-slot="{ value, handleChange }">
|
<VeeField name="hobbies" v-slot="{ field, errors }">
|
||||||
<FormItem>
|
<Field>
|
||||||
<FormLabel>What hobbies do you like to participate in outside of gaming?</FormLabel>
|
<FieldLabel>What hobbies do you like to participate in outside of gaming?</FieldLabel>
|
||||||
<FormControl>
|
<FieldContent>
|
||||||
<Textarea rows="4" class="resize-none" :model-value="value" @update:model-value="handleChange"
|
<Textarea rows="4" class="resize-none" :model-value="field.value" @update:model-value="field.onChange"
|
||||||
:disabled="readOnly" />
|
:disabled="readOnly" />
|
||||||
</FormControl>
|
</FieldContent>
|
||||||
<FormMessage />
|
<div class="h-4">
|
||||||
</FormItem>
|
<FieldError v-if="errors.length" :errors="errors" />
|
||||||
</FormField>
|
</div>
|
||||||
|
</Field>
|
||||||
|
</VeeField>
|
||||||
|
|
||||||
<!-- Military (boolean) -->
|
<!-- Military (boolean) -->
|
||||||
<FormField name="military" v-slot="{ value, handleChange }">
|
<VeeField name="military" v-slot="{ field, errors }">
|
||||||
<FormItem>
|
<Field>
|
||||||
<FormLabel>Have you ever served in the military?</FormLabel>
|
<FieldLabel>Have you ever served in the military?</FieldLabel>
|
||||||
<FormControl>
|
<FieldContent>
|
||||||
<div class="flex items-center gap-2">
|
<div class="flex items-center gap-2">
|
||||||
<Checkbox :checked="value ?? false" @update:checked="handleChange" :disabled="readOnly" />
|
<Checkbox :model-value="field.value" @update:model-value="field.onChange" :disabled="readOnly" />
|
||||||
<span>Yes (checked) / No (unchecked)</span>
|
<span>Yes (checked) / No (unchecked)</span>
|
||||||
</div>
|
</div>
|
||||||
</FormControl>
|
</FieldContent>
|
||||||
<FormMessage />
|
<div class="h-4">
|
||||||
</FormItem>
|
<FieldError v-if="errors.length" :errors="errors" />
|
||||||
</FormField>
|
</div>
|
||||||
|
</Field>
|
||||||
|
</VeeField>
|
||||||
|
|
||||||
<!-- Other communities (freeform) -->
|
<!-- Other communities (freeform) -->
|
||||||
<FormField name="communities" v-slot="{ value, handleChange }">
|
<VeeField name="communities" v-slot="{ field, errors }">
|
||||||
<FormItem>
|
<Field>
|
||||||
<FormLabel>Are you a part of any other communities? If so, which ones? If none, type "No"</FormLabel>
|
<FieldLabel>Are you a part of any other communities? If so, which ones? If none, type "No"</FieldLabel>
|
||||||
<FormControl>
|
<FieldContent>
|
||||||
<Input :model-value="value" @update:model-value="handleChange" :disabled="readOnly" />
|
<Input :model-value="field.value" @update:model-value="field.onChange" :disabled="readOnly" />
|
||||||
</FormControl>
|
</FieldContent>
|
||||||
<FormMessage />
|
<div class="h-4">
|
||||||
</FormItem>
|
<FieldError v-if="errors.length" :errors="errors" />
|
||||||
</FormField>
|
</div>
|
||||||
|
</Field>
|
||||||
|
</VeeField>
|
||||||
|
|
||||||
<!-- Why join -->
|
<!-- Why join -->
|
||||||
<FormField name="joinReason" v-slot="{ value, handleChange }">
|
<VeeField name="joinReason" v-slot="{ field, errors }">
|
||||||
<FormItem>
|
<Field>
|
||||||
<FormLabel>Why do you want to join our community?</FormLabel>
|
<FieldLabel>Why do you want to join our community?</FieldLabel>
|
||||||
<FormControl>
|
<FieldContent>
|
||||||
<Textarea rows="4" class="resize-none" :model-value="value" @update:model-value="handleChange"
|
<Textarea rows="4" class="resize-none" :model-value="field.value" @update:model-value="field.onChange"
|
||||||
:disabled="readOnly" />
|
:disabled="readOnly" />
|
||||||
</FormControl>
|
</FieldContent>
|
||||||
<FormMessage />
|
<div class="h-4">
|
||||||
</FormItem>
|
<FieldError v-if="errors.length" :errors="errors" />
|
||||||
</FormField>
|
</div>
|
||||||
|
</Field>
|
||||||
|
</VeeField>
|
||||||
|
|
||||||
<!-- Attraction to milsim -->
|
<!-- Attraction to milsim -->
|
||||||
<FormField name="milsimAttraction" v-slot="{ value, handleChange }">
|
<VeeField name="milsimAttraction" v-slot="{ field, errors }">
|
||||||
<FormItem>
|
<Field>
|
||||||
<FormLabel>What attracts you to the Arma 3 milsim playstyle?</FormLabel>
|
<FieldLabel>What attracts you to the Arma 3 milsim playstyle?</FieldLabel>
|
||||||
<FormControl>
|
<FieldContent>
|
||||||
<Textarea rows="4" class="resize-none" :model-value="value" @update:model-value="handleChange"
|
<Textarea rows="4" class="resize-none" :model-value="field.value" @update:model-value="field.onChange"
|
||||||
:disabled="readOnly" />
|
:disabled="readOnly" />
|
||||||
</FormControl>
|
</FieldContent>
|
||||||
<FormMessage />
|
<div class="h-4">
|
||||||
</FormItem>
|
<FieldError v-if="errors.length" :errors="errors" />
|
||||||
</FormField>
|
</div>
|
||||||
|
</Field>
|
||||||
|
</VeeField>
|
||||||
|
|
||||||
<!-- Referral (freeform) -->
|
<!-- Referral (freeform) -->
|
||||||
<FormField name="referral" v-slot="{ value, handleChange }">
|
<VeeField name="referral" v-slot="{ field, errors }">
|
||||||
<FormItem>
|
<Field>
|
||||||
<FormLabel>Where did you hear about us? (If another member, who?)</FormLabel>
|
<FieldLabel>Where did you hear about us? (If another member, who?)</FieldLabel>
|
||||||
<FormControl>
|
<FieldContent>
|
||||||
<Input placeholder="e.g., Reddit / Member: Alice" :model-value="value" @update:model-value="handleChange"
|
<Input placeholder="e.g., Reddit / Member: Alice" :model-value="field.value" @update:model-value="field.onChange"
|
||||||
:disabled="readOnly" />
|
:disabled="readOnly" />
|
||||||
</FormControl>
|
</FieldContent>
|
||||||
<FormMessage />
|
<div class="h-4">
|
||||||
</FormItem>
|
<FieldError v-if="errors.length" :errors="errors" />
|
||||||
</FormField>
|
</div>
|
||||||
|
</Field>
|
||||||
|
</VeeField>
|
||||||
|
|
||||||
<!-- Steam profile -->
|
<!-- Steam profile -->
|
||||||
<FormField name="steamProfile" v-slot="{ value, handleChange }">
|
<VeeField name="steamProfile" v-slot="{ field, errors }">
|
||||||
<FormItem>
|
<Field>
|
||||||
<FormLabel>Steam profile link</FormLabel>
|
<FieldLabel>Steam profile link</FieldLabel>
|
||||||
<FormDescription>
|
<FieldDescription>
|
||||||
Format: <code>https://steamcommunity.com/id/USER/</code> or
|
Format: <code>https://steamcommunity.com/id/USER/</code> or
|
||||||
<code>https://steamcommunity.com/profiles/STEAMID64/</code>
|
<code>https://steamcommunity.com/profiles/STEAMID64/</code>
|
||||||
</FormDescription>
|
</FieldDescription>
|
||||||
<FormControl>
|
<FieldContent>
|
||||||
<Input type="url" placeholder="https://steamcommunity.com/profiles/7656119..." :model-value="value"
|
<Input type="url" placeholder="https://steamcommunity.com/profiles/7656119..." :model-value="field.value"
|
||||||
@update:model-value="handleChange" :disabled="readOnly" />
|
@update:model-value="field.onChange" :disabled="readOnly" />
|
||||||
</FormControl>
|
</FieldContent>
|
||||||
<FormMessage />
|
<div class="h-4">
|
||||||
</FormItem>
|
<FieldError v-if="errors.length" :errors="errors" />
|
||||||
</FormField>
|
</div>
|
||||||
|
</Field>
|
||||||
|
</VeeField>
|
||||||
|
|
||||||
<!-- Timezone -->
|
<!-- Timezone -->
|
||||||
<FormField name="timezone" v-slot="{ value, handleChange }">
|
<VeeField name="timezone" v-slot="{ field, errors }">
|
||||||
<FormItem>
|
<Field>
|
||||||
<FormLabel>What time zone are you in?</FormLabel>
|
<FieldLabel>What time zone are you in?</FieldLabel>
|
||||||
<FormControl>
|
<FieldContent>
|
||||||
<Input placeholder="e.g., AEST, EST, UTC+10" :model-value="value" @update:model-value="handleChange"
|
<Input placeholder="e.g., AEST, EST, UTC+10" :model-value="field.value" @update:model-value="field.onChange"
|
||||||
:disabled="readOnly" />
|
:disabled="readOnly" />
|
||||||
</FormControl>
|
</FieldContent>
|
||||||
<FormMessage />
|
<div class="h-4">
|
||||||
</FormItem>
|
<FieldError v-if="errors.length" :errors="errors" />
|
||||||
</FormField>
|
</div>
|
||||||
|
</Field>
|
||||||
|
</VeeField>
|
||||||
|
|
||||||
<!-- Attendance (boolean) -->
|
<!-- Attendance (boolean) -->
|
||||||
<FormField name="canAttendSaturday" v-slot="{ value, handleChange }">
|
<VeeField name="canAttendSaturday" v-slot="{ field, errors }">
|
||||||
<FormItem>
|
<Field>
|
||||||
<FormLabel>Are you able to attend weekly operations Saturdays @ 7pm CST?</FormLabel>
|
<FieldLabel>Are you able to attend weekly operations Saturdays @ 7pm CST?</FieldLabel>
|
||||||
<FormControl>
|
<FieldContent>
|
||||||
<div class="flex items-center gap-2">
|
<div class="flex items-center gap-2">
|
||||||
<Checkbox :model-value="value ?? false" @update:model-value="handleChange" :disabled="readOnly" />
|
<Checkbox :model-value="field.value ?? false" @update:model-value="field.onChange" :disabled="readOnly" />
|
||||||
<span>Yes (checked) / No (unchecked)</span>
|
<span>Yes (checked) / No (unchecked)</span>
|
||||||
</div>
|
</div>
|
||||||
</FormControl>
|
</FieldContent>
|
||||||
<FormMessage />
|
<div class="h-4">
|
||||||
</FormItem>
|
<FieldError v-if="errors.length" :errors="errors" />
|
||||||
</FormField>
|
</div>
|
||||||
|
</Field>
|
||||||
|
</VeeField>
|
||||||
|
|
||||||
<!-- Interests / Playstyle (freeform) -->
|
<!-- Interests / Playstyle (freeform) -->
|
||||||
<FormField name="interests" v-slot="{ value, handleChange }">
|
<VeeField name="interests" v-slot="{ field, errors }">
|
||||||
<FormItem>
|
<Field>
|
||||||
<FormLabel>Which playstyles interest you?</FormLabel>
|
<FieldLabel>Which playstyles interest you?</FieldLabel>
|
||||||
<FormControl>
|
<FieldContent>
|
||||||
<Input placeholder="e.g., Rifleman; Medic; Pilot" :model-value="value" @update:model-value="handleChange"
|
<Input placeholder="e.g., Rifleman; Medic; Pilot" :model-value="field.value" @update:model-value="field.onChange"
|
||||||
:disabled="readOnly" />
|
:disabled="readOnly" />
|
||||||
</FormControl>
|
</FieldContent>
|
||||||
<FormMessage />
|
<div class="h-4">
|
||||||
</FormItem>
|
<FieldError v-if="errors.length" :errors="errors" />
|
||||||
</FormField>
|
</div>
|
||||||
|
</Field>
|
||||||
|
</VeeField>
|
||||||
|
|
||||||
<!-- Code of Conduct (boolean, field name kept as-is) -->
|
<!-- Code of Conduct (boolean, field name kept as-is) -->
|
||||||
<FormField name="aknowledgeRules" v-slot="{ value, handleChange }">
|
<VeeField name="acknowledgeRules" v-slot="{ field, errors }">
|
||||||
<FormItem>
|
<Field>
|
||||||
<FormLabel>Community Code of Conduct</FormLabel>
|
<FieldLabel>Community Code of Conduct</FieldLabel>
|
||||||
<FormControl>
|
<FieldContent>
|
||||||
<div class="flex items-center gap-2">
|
<div class="flex items-center gap-2">
|
||||||
<Checkbox :model-value="value" @update:model-value="handleChange" :disabled="readOnly" />
|
<Checkbox :model-value="field.value" @update:model-value="field.onChange" :disabled="readOnly" />
|
||||||
<span>By checking this box, you accept the <Button variant="link" class="p-0">Code of
|
<span>By checking this box, you accept the <Button variant="link" class="p-0 h-min"
|
||||||
|
@click.prevent.stop="showCoC = true">Code of
|
||||||
Conduct</Button>.</span>
|
Conduct</Button>.</span>
|
||||||
</div>
|
</div>
|
||||||
</FormControl>
|
</FieldContent>
|
||||||
<FormMessage />
|
<div class="h-4">
|
||||||
</FormItem>
|
<FieldError v-if="errors.length" :errors="errors" />
|
||||||
</FormField>
|
</div>
|
||||||
|
</Field>
|
||||||
|
</VeeField>
|
||||||
|
|
||||||
<div class="pt-2" v-if="!readOnly">
|
<div class="pt-2" v-if="!readOnly">
|
||||||
<Button type="submit" :onClick="() => console.log('hi')" :disabled="readOnly">Submit Application</Button>
|
<Button type="submit" :disabled="readOnly">Submit Application</Button>
|
||||||
</div>
|
</div>
|
||||||
</Form>
|
|
||||||
|
<Dialog :open="showCoC" @update:open="onDialogToggle">
|
||||||
|
<DialogContent class="sm:max-w-fit">
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle>Community Code of Conduct</DialogTitle>
|
||||||
|
<DialogDescription class="w-full max-h-[75vh] overflow-y-auto scrollbar-themed">
|
||||||
|
<div v-html="CoCString" ref="CoCbox" class="bookstack-container w-full"></div>
|
||||||
|
</DialogDescription>
|
||||||
|
</DialogHeader>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
|
||||||
|
</form>
|
||||||
</template>
|
</template>
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user