Compare commits
1 Commits
1.2.0
...
Matomo-Int
| Author | SHA1 | Date | |
|---|---|---|---|
| 0382acbb25 |
@@ -1,101 +0,0 @@
|
|||||||
name: Testing Site CD
|
|
||||||
on:
|
|
||||||
push:
|
|
||||||
branches:
|
|
||||||
- main
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
deploy-testing-cd:
|
|
||||||
name: Update Development
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
container:
|
|
||||||
volumes:
|
|
||||||
- /var/www/html/milsim-site-v4-dev:/var/www/html/milsim-site-v4:z
|
|
||||||
steps:
|
|
||||||
- name: Setup Local Environment
|
|
||||||
run: |
|
|
||||||
groupadd -g 989 nginx || true
|
|
||||||
useradd nginx -u 990 -g nginx -m || true
|
|
||||||
|
|
||||||
- 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
|
|
||||||
which sed
|
|
||||||
sed --version
|
|
||||||
|
|
||||||
- name: Checkout
|
|
||||||
uses: actions/checkout@v5
|
|
||||||
with:
|
|
||||||
fetch-depth: 0
|
|
||||||
ref: 'main'
|
|
||||||
|
|
||||||
- name: Token Copy
|
|
||||||
run: |
|
|
||||||
cd /var/www/html/milsim-site-v4
|
|
||||||
cp ${{ gitea.workspace }}/.git/config .git/config
|
|
||||||
chown nginx:nginx .git/config
|
|
||||||
|
|
||||||
- name: Update Application Code
|
|
||||||
run: |
|
|
||||||
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 fetch --tags
|
|
||||||
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
|
|
||||||
run: |
|
|
||||||
cd /var/www/html/milsim-site-v4/shared
|
|
||||||
npm install
|
|
||||||
chown -R nginx:nginx .
|
|
||||||
|
|
||||||
- name: Update UI Dependencies and Fix Permissions
|
|
||||||
run: |
|
|
||||||
cd /var/www/html/milsim-site-v4/ui
|
|
||||||
npm install
|
|
||||||
chown -R nginx:nginx .
|
|
||||||
|
|
||||||
- name: Update API Dependencies and Fix Permissions
|
|
||||||
run: |
|
|
||||||
cd /var/www/html/milsim-site-v4/api
|
|
||||||
npm install
|
|
||||||
chown -R nginx:nginx .
|
|
||||||
|
|
||||||
- name: Build UI / Update Version / Fix Permissions
|
|
||||||
run: |
|
|
||||||
cd /var/www/html/milsim-site-v4/ui
|
|
||||||
npm run build
|
|
||||||
version=`git rev-parse --short=10 HEAD`
|
|
||||||
sed -i "s/VITE_APPLICATION_VERSION=.*/VITE_APPLICATION_VERSION=$version/" .env
|
|
||||||
chown -R nginx:nginx .
|
|
||||||
|
|
||||||
- name: Build API / Update Version / Fix Permissions
|
|
||||||
run: |
|
|
||||||
cd /var/www/html/milsim-site-v4/api
|
|
||||||
npm run build
|
|
||||||
version=`git rev-parse --short=10 HEAD`
|
|
||||||
sed -i "s/APPLICATION_VERSION=.*/APPLICATION_VERSION=$version/" .env
|
|
||||||
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
|
|
||||||
run: |
|
|
||||||
sudo chown -R nginx:nginx /var/www/html/milsim-site-v4
|
|
||||||
sudo chmod -R u+w /var/www/html/milsim-site-v4
|
|
||||||
@@ -1,101 +0,0 @@
|
|||||||
name: Live Site CD
|
|
||||||
on:
|
|
||||||
push:
|
|
||||||
tags:
|
|
||||||
- '*'
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
deploy-live-cd:
|
|
||||||
name: Update Deployment
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
container:
|
|
||||||
volumes:
|
|
||||||
- /var/www/html/milsim-site-v4:/var/www/html/milsim-site-v4:z
|
|
||||||
steps:
|
|
||||||
- name: Setup Local Environment
|
|
||||||
run: |
|
|
||||||
groupadd -g 989 nginx || true
|
|
||||||
useradd nginx -u 990 -g nginx -m || true
|
|
||||||
|
|
||||||
- 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
|
|
||||||
which sed
|
|
||||||
sed --version
|
|
||||||
|
|
||||||
- name: Checkout
|
|
||||||
uses: actions/checkout@v5
|
|
||||||
with:
|
|
||||||
fetch-depth: 0
|
|
||||||
ref: 'main'
|
|
||||||
|
|
||||||
- name: Token Copy
|
|
||||||
run: |
|
|
||||||
cd /var/www/html/milsim-site-v4
|
|
||||||
cp ${{ gitea.workspace }}/.git/config .git/config
|
|
||||||
chown nginx:nginx .git/config
|
|
||||||
|
|
||||||
- name: Update Application Code
|
|
||||||
run: |
|
|
||||||
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 fetch --tags
|
|
||||||
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
|
|
||||||
run: |
|
|
||||||
cd /var/www/html/milsim-site-v4/shared
|
|
||||||
npm install
|
|
||||||
chown -R nginx:nginx .
|
|
||||||
|
|
||||||
- name: Update UI Dependencies and Fix Permissions
|
|
||||||
run: |
|
|
||||||
cd /var/www/html/milsim-site-v4/ui
|
|
||||||
npm install
|
|
||||||
chown -R nginx:nginx .
|
|
||||||
|
|
||||||
- name: Update API Dependencies and Fix Permissions
|
|
||||||
run: |
|
|
||||||
cd /var/www/html/milsim-site-v4/api
|
|
||||||
npm install
|
|
||||||
chown -R nginx:nginx .
|
|
||||||
|
|
||||||
- name: Build UI / Update Version / Fix Permissions
|
|
||||||
run: |
|
|
||||||
cd /var/www/html/milsim-site-v4/ui
|
|
||||||
npm run build
|
|
||||||
version=`git describe --abbrev=0 --tags`
|
|
||||||
sed -i "s/VITE_APPLICATION_VERSION=.*/VITE_APPLICATION_VERSION=$version/" .env
|
|
||||||
chown -R nginx:nginx .
|
|
||||||
|
|
||||||
- name: Build API / Update Version / Fix Permissions
|
|
||||||
run: |
|
|
||||||
cd /var/www/html/milsim-site-v4/api
|
|
||||||
npm run build
|
|
||||||
version=`git describe --abbrev=0 --tags`
|
|
||||||
sed -i "s/APPLICATION_VERSION=.*/APPLICATION_VERSION=$version/" .env
|
|
||||||
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
|
|
||||||
run: |
|
|
||||||
sudo chown -R nginx:nginx /var/www/html/milsim-site-v4
|
|
||||||
sudo chmod -R u+w /var/www/html/milsim-site-v4
|
|
||||||
@@ -1,58 +0,0 @@
|
|||||||
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,5 +32,3 @@ coverage
|
|||||||
*.sql
|
*.sql
|
||||||
.env
|
.env
|
||||||
*.db
|
*.db
|
||||||
|
|
||||||
db_data
|
|
||||||
@@ -19,21 +19,7 @@ AUTH_END_SESSION_URI=
|
|||||||
SERVER_PORT=3000
|
SERVER_PORT=3000
|
||||||
CLIENT_URL= # This is whatever URL the client web app is served on
|
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_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,3 +1 @@
|
|||||||
built
|
built
|
||||||
|
|
||||||
!migrations/*/*.sql
|
|
||||||
@@ -1,20 +0,0 @@
|
|||||||
{
|
|
||||||
"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
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,53 +0,0 @@
|
|||||||
'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
|
|
||||||
};
|
|
||||||
@@ -1,53 +0,0 @@
|
|||||||
'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
|
|
||||||
};
|
|
||||||
@@ -1,53 +0,0 @@
|
|||||||
'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
|
|
||||||
};
|
|
||||||
@@ -1,53 +0,0 @@
|
|||||||
'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
|
|
||||||
};
|
|
||||||
@@ -1,53 +0,0 @@
|
|||||||
'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
112185
api/migrations/seed.sql
File diff suppressed because it is too large
Load Diff
@@ -1 +0,0 @@
|
|||||||
/* Replace with your SQL commands */
|
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -1 +0,0 @@
|
|||||||
/* Replace with your SQL commands */
|
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
/* 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`;
|
|
||||||
@@ -1,14 +0,0 @@
|
|||||||
/* 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;
|
|
||||||
@@ -1,57 +0,0 @@
|
|||||||
/* 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;
|
|
||||||
@@ -1 +0,0 @@
|
|||||||
/* Replace with your SQL commands */
|
|
||||||
@@ -1,3 +0,0 @@
|
|||||||
/* Replace with your SQL commands */
|
|
||||||
|
|
||||||
ALTER TABLE member_state_history ADD reason_detailed TEXT;
|
|
||||||
@@ -1 +0,0 @@
|
|||||||
/* Replace with your SQL commands */
|
|
||||||
@@ -1,17 +0,0 @@
|
|||||||
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,33 +9,25 @@
|
|||||||
"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",
|
||||||
"prod": "tsc && tsc-alias && node ./built/api/src/index.js",
|
"build": "tsc && tsc-alias"
|
||||||
"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",
|
||||||
"db-migrate": "^0.11.14",
|
"dotenv": "^17.2.1",
|
||||||
"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"
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,29 +0,0 @@
|
|||||||
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" });
|
|
||||||
@@ -1,33 +0,0 @@
|
|||||||
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,5 +1,8 @@
|
|||||||
// 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,
|
||||||
@@ -9,7 +12,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: process.env.DB_DATABASE,
|
database: 'ranger_unit_tracker',
|
||||||
ssl: false,
|
ssl: false,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
82
api/src/index.js
Normal file
82
api/src/index.js
Normal file
@@ -0,0 +1,82 @@
|
|||||||
|
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) {
|
||||||
|
console.log("Glitchtip disabled AAAAAA")
|
||||||
|
} else {
|
||||||
|
let dsn = process.env.GLITCHTIP_DSN;
|
||||||
|
sentry.init({ dsn: dsn });
|
||||||
|
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');
|
||||||
|
|
||||||
|
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
131
api/src/index.ts
@@ -1,131 +0,0 @@
|
|||||||
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} `)
|
|
||||||
})
|
|
||||||
@@ -1,49 +0,0 @@
|
|||||||
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,171 +2,58 @@ const express = require('express');
|
|||||||
const router = express.Router();
|
const router = express.Router();
|
||||||
|
|
||||||
import pool from '../db';
|
import pool from '../db';
|
||||||
import { approveApplication, createApplication, denyApplication, getAllMemberApplications, getApplicationByID, getApplicationComments, getApplicationList, getMemberApplication } from '../services/db/applicationService';
|
import { approveApplication, createApplication, getApplicationByID, getApplicationComments, getApplicationList, getMemberApplication } from '../services/applicationService';
|
||||||
import { setUserState } from '../services/db/memberService';
|
import { MemberState, setUserState } from '../services/memberService';
|
||||||
import { MemberState } from '@app/shared/types/member';
|
import { getRankByName, insertMemberRank } from '../services/rankService';
|
||||||
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/db/statusService';
|
import { assignUserToStatus } from '../services/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';
|
|
||||||
|
|
||||||
//get CoC
|
|
||||||
router.get('/coc', async (req: Request, res: Response) => {
|
|
||||||
try {
|
|
||||||
const response = await fetch(`${process.env.DOC_HOST}/api/pages/714`, {
|
|
||||||
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 LOA policy from Bookstack', {
|
|
||||||
status: response.status,
|
|
||||||
statusText: response.statusText,
|
|
||||||
body: text,
|
|
||||||
});
|
|
||||||
return res.sendStatus(500);
|
|
||||||
}
|
|
||||||
|
|
||||||
const out = await response.json();
|
|
||||||
res.status(200).json(out.html);
|
|
||||||
|
|
||||||
} catch (error) {
|
|
||||||
logger.error('app', 'Error fetching LOA policy from Bookstack', {
|
|
||||||
error: error instanceof Error ? error.message : String(error),
|
|
||||||
});
|
|
||||||
res.sendStatus(500);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
|
|
||||||
// POST /application
|
// POST /application
|
||||||
router.post('/', [requireLogin], async (req: Request, res: Response) => {
|
router.post('/', async (req, res) => {
|
||||||
const memberID = req.user.id;
|
try {
|
||||||
const App = req.body?.App || {};
|
const App = req.body?.App || {};
|
||||||
|
const memberID = req.user.id;
|
||||||
|
|
||||||
const appVersion = 1;
|
const appVersion = 1;
|
||||||
|
|
||||||
try {
|
createApplication(memberID, appVersion, JSON.stringify(App))
|
||||||
let appID = await createApplication(memberID, appVersion, JSON.stringify(App));
|
setUserState(memberID, MemberState.Applicant);
|
||||||
|
|
||||||
await setUserState(memberID, MemberState.Applicant, "Application Submitted", memberID);
|
|
||||||
|
|
||||||
res.sendStatus(201);
|
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) {
|
} catch (err) {
|
||||||
logger.error(
|
console.error('Insert failed:', err);
|
||||||
'app',
|
res.status(500).json({ error: 'Failed to save application' });
|
||||||
'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', [requireLogin, requireRole("Recruiter")], async (req, res) => {
|
router.get('/all', 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) {
|
||||||
logger.error(
|
console.error(err);
|
||||||
'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('/meList', async (req, res) => {
|
router.get('/me', async (req, res) => {
|
||||||
|
|
||||||
let userID = req.user.id;
|
let userID = req.user.id;
|
||||||
|
|
||||||
try {
|
console.log("application/me")
|
||||||
let application = await getAllMemberApplications(userID);
|
|
||||||
|
|
||||||
return res.status(200).json(application);
|
let app = getMemberApplication(userID);
|
||||||
} catch (error) {
|
console.log(app);
|
||||||
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) => {
|
// GET /application/:id
|
||||||
|
router.get('/:id', async (req, res) => {
|
||||||
let userID = req.user.id;
|
let appID = req.params.id;
|
||||||
|
console.log("HELLO")
|
||||||
try {
|
|
||||||
let application = await getMemberApplication(userID);
|
|
||||||
|
|
||||||
if (application === undefined) {
|
|
||||||
res.sendStatus(204);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const comments: CommentRow[] = await getApplicationComments(application.id);
|
|
||||||
|
|
||||||
const output: ApplicationFull = {
|
|
||||||
application,
|
|
||||||
comments,
|
|
||||||
}
|
|
||||||
|
|
||||||
return res.status(200).json(output);
|
|
||||||
} catch (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);
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
// GET /me/:id
|
|
||||||
router.get('/me/:id', [requireLogin], async (req: Request, res: Response) => {
|
|
||||||
let appID = Number(req.params.id);
|
|
||||||
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);
|
||||||
|
|
||||||
@@ -176,137 +63,78 @@ router.get('/me/:id', [requireLogin], async (req: Request, res: Response) => {
|
|||||||
}
|
}
|
||||||
return res.status(200).json(output);
|
return res.status(200).json(output);
|
||||||
}
|
}
|
||||||
catch (error) {
|
catch (err) {
|
||||||
logger.error(
|
console.error('Query failed:', err);
|
||||||
'app',
|
return res.status(500).json({ error: 'Failed to load application' });
|
||||||
'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', [requireLogin, requireRole("Recruiter")], async (req: Request, res: Response) => {
|
router.post('/approve/:id', async (req, res) => {
|
||||||
const appID = Number(req.params.id);
|
const appID = req.params.id;
|
||||||
const approved_by = req.user.id;
|
|
||||||
|
|
||||||
const app = await getApplicationByID(appID);
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
var con = await pool.getConnection();
|
const app = await getApplicationByID(appID);
|
||||||
|
const result = await approveApplication(appID);
|
||||||
|
|
||||||
con.beginTransaction();
|
console.log("START");
|
||||||
|
console.log(app, result);
|
||||||
|
|
||||||
await approveApplication(appID, approved_by, con);
|
//guard against failures
|
||||||
|
if (result.affectedRows != 1) {
|
||||||
//update user profile
|
throw new Error("Something went wrong approving the application");
|
||||||
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 });
|
|
||||||
|
|
||||||
res.sendStatus(200);
|
|
||||||
} catch (error) {
|
|
||||||
|
|
||||||
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,
|
|
||||||
}
|
}
|
||||||
);
|
|
||||||
|
console.log(app.member_id);
|
||||||
|
//update user profile
|
||||||
|
await setUserState(app.member_id, MemberState.Member);
|
||||||
|
|
||||||
|
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);
|
||||||
|
} catch (err) {
|
||||||
|
console.error('Approve failed:', err);
|
||||||
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', [requireLogin, requireRole("Recruiter")], async (req: Request, res: Response) => {
|
router.post('/deny/:id', async (req, res) => {
|
||||||
const appID = Number(req.params.id);
|
const appID = 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 app = await getApplicationByID(appID);
|
const result = await pool.execute(sql, appID);
|
||||||
await denyApplication(appID, approver);
|
|
||||||
await setUserState(app.member_id, MemberState.Denied, "Application Denied", approver);
|
|
||||||
|
|
||||||
logger.info('app', "Member application approved", {
|
console.log(result);
|
||||||
application: app.id,
|
|
||||||
applicant: app.member_id,
|
if (result.affectedRows === 0) {
|
||||||
approver: approver
|
res.status(400).json('Something went wrong denying the application');
|
||||||
})
|
|
||||||
audit.application('denied', { actorId: approver, targetId: appID }, { applicantId: app.member_id });
|
|
||||||
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,
|
|
||||||
}
|
}
|
||||||
);
|
|
||||||
|
if (result.affectedRows == 1) {
|
||||||
|
res.sendStatus(200);
|
||||||
|
}
|
||||||
|
|
||||||
|
} 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', [requireLogin], async (req: Request, res: Response) => {
|
router.post('/:id/comment', async (req, res) => {
|
||||||
const appID = Number(req.params.id);
|
const appID = req.params.id;
|
||||||
const data = req.body.message;
|
const data = req.body.message;
|
||||||
const user = req.user;
|
const user = 1;
|
||||||
|
|
||||||
const sql = `INSERT INTO application_comments(
|
const sql = `INSERT INTO application_comments(
|
||||||
application_id,
|
application_id,
|
||||||
@@ -315,11 +143,11 @@ router.post('/:id/comment', [requireLogin], async (req: Request, res: Response)
|
|||||||
)
|
)
|
||||||
VALUES(?, ?, ?);`
|
VALUES(?, ?, ?);`
|
||||||
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
var conn = await pool.getConnection();
|
const conn = await pool.getConnection();
|
||||||
|
|
||||||
const result = await conn.query(sql, [appID, user.id, data])
|
const result = await conn.query(sql, [appID, user, data])
|
||||||
|
console.log(result)
|
||||||
if (result.affectedRows !== 1) {
|
if (result.affectedRows !== 1) {
|
||||||
conn.release();
|
conn.release();
|
||||||
throw new Error("Insert Failure")
|
throw new Error("Insert Failure")
|
||||||
@@ -335,114 +163,12 @@ 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 (error) {
|
} catch (err) {
|
||||||
logger.error(
|
console.error('Comment failed:', err);
|
||||||
'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();
|
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
// POST /application/:id/comment
|
module.exports = router;
|
||||||
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: result.insertId });
|
|
||||||
logger.info('app', "Admin application comment posted", {
|
|
||||||
application: appID,
|
|
||||||
poster: user.id,
|
|
||||||
comment: 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;
|
|
||||||
|
|||||||
131
api/src/routes/auth.js
Normal file
131
api/src/routes/auth.js
Normal file
@@ -0,0 +1,131 @@
|
|||||||
|
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('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;
|
||||||
@@ -1,339 +0,0 @@
|
|||||||
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,10 +1,6 @@
|
|||||||
import { Request, Response } from "express";
|
import { Request, Response } from "express";
|
||||||
import { createEvent, getEventAttendance, getEventDetails, getShortEventsInRange, setAttendanceStatus, setEventCancelled, updateEvent } from "../services/db/calendarService";
|
import { createEvent, getEventAttendance, getEventDetails, getShortEventsInRange, setAttendanceStatus, setEventCancelled, updateEvent } from "../services/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();
|
||||||
@@ -30,14 +26,7 @@ r.get('/', async (req, res) => {
|
|||||||
|
|
||||||
res.status(200).json(events);
|
res.status(200).json(events);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
logger.error(
|
console.error('Error fetching calendar events:', 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');
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
@@ -46,84 +35,40 @@ r.get('/upcoming', async (req, res) => {
|
|||||||
res.sendStatus(501);
|
res.sendStatus(501);
|
||||||
})
|
})
|
||||||
|
|
||||||
r.post('/:id/cancel', [requireLogin, requireMemberState(MemberState.Member)], async (req: Request, res: Response) => {
|
r.post('/:id/cancel', async (req: Request, res: Response) => {
|
||||||
let member = req.user.id;
|
|
||||||
try {
|
try {
|
||||||
const eventID = Number(req.params.id);
|
const eventID = Number(req.params.id);
|
||||||
await setEventCancelled(eventID, true);
|
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) {
|
||||||
logger.error(
|
console.error('Error setting cancel status:', 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', [requireLogin, requireMemberState(MemberState.Member)], async (req: Request, res: Response) => {
|
r.post('/:id/uncancel', 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) {
|
||||||
logger.error(
|
console.error('Error setting cancel status:', 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', [requireLogin, requireMemberState(MemberState.Member)], async (req: Request, res: Response) => {
|
r.post('/:id/attendance', 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;
|
||||||
await setAttendanceStatus(member, event, state);
|
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) {
|
||||||
logger.error(
|
console.error('Failed to set attendance:', 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 {
|
||||||
@@ -132,75 +77,42 @@ 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 (error) {
|
} catch (err) {
|
||||||
logger.error(
|
console.error('Insert failed:', err);
|
||||||
'app',
|
res.status(500).json(err);
|
||||||
'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('/', [requireLogin, requireMemberState(MemberState.Member)], async (req: Request, res: Response) => {
|
r.post('/', 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);
|
||||||
let eventID = await createEvent(event);
|
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) {
|
||||||
logger.error(
|
console.error('Failed to create event:', 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('/', [requireLogin, requireMemberState(MemberState.Member)], async (req: Request, res: Response) => {
|
r.put('/', 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) {
|
||||||
logger.error(
|
console.error('Failed to update event:', 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,64 +1,36 @@
|
|||||||
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/db/CourseSerivce";
|
import { getAllCourses, getCourseEventAttendees, getCourseEventDetails, getCourseEventRoles, getCourseEvents, insertCourseEvent } from "../services/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 cr = Router();
|
const courseRouter = Router();
|
||||||
const er = Router();
|
const eventRouter = Router();
|
||||||
|
|
||||||
cr.use(requireLogin)
|
courseRouter.get('/', async (req, res) => {
|
||||||
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 (error) {
|
} catch (err) {
|
||||||
logger.error(
|
console.error('failed to fetch courses', err);
|
||||||
'app',
|
res.status(500).json('failed to fetch courses\n' + err);
|
||||||
'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');
|
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
cr.get('/roles', async (req, res) => {
|
courseRouter.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 (error) {
|
} catch (err) {
|
||||||
logger.error(
|
console.error('failed to fetch course roles', err);
|
||||||
'app',
|
res.status(500).json('failed to fetch course roles\n' + err);
|
||||||
'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');
|
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
//get event list
|
eventRouter.get('/', async (req: Request, res: Response) => {
|
||||||
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)) {
|
||||||
@@ -69,79 +41,49 @@ er.get('/', async (req: Request, res: Response) => {
|
|||||||
|
|
||||||
const sortDir = allowedSorts.get(sort);
|
const sortDir = allowedSorts.get(sort);
|
||||||
|
|
||||||
let events = await getCourseEvents(sortDir, search, page, pageSize);
|
try {
|
||||||
|
let events = await getCourseEvents(sortDir, search);
|
||||||
res.status(200).json(events);
|
res.status(200).json(events);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
logger.error(
|
console.error('failed to fetch reports', 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);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
er.get('/:id', async (req: Request, res: Response) => {
|
eventRouter.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) {
|
||||||
logger.error(
|
console.error('failed to fetch report', 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);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
er.get('/attendees/:id', async (req: Request, res: Response) => {
|
eventRouter.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 (error) {
|
} catch (err) {
|
||||||
logger.error(
|
console.error('failed to fetch attendees', err);
|
||||||
'app',
|
res.status(500).json("failed to fetch attendees\n" + err);
|
||||||
'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");
|
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
er.post('/', async (req: Request, res: Response) => {
|
eventRouter.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) {
|
||||||
logger.error(
|
console.error('failed to post training', 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)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
export const courseRouter = cr;
|
module.exports.courseRouter = courseRouter;
|
||||||
export const eventRouter = er;
|
module.exports.eventRouter = eventRouter;
|
||||||
@@ -1,57 +0,0 @@
|
|||||||
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;
|
|
||||||
56
api/src/routes/loa.js
Normal file
56
api/src/routes/loa.js
Normal file
@@ -0,0 +1,56 @@
|
|||||||
|
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;
|
||||||
@@ -1,313 +0,0 @@
|
|||||||
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;
|
|
||||||
84
api/src/routes/members.js
Normal file
84
api/src/routes/members.js
Normal file
@@ -0,0 +1,84 @@
|
|||||||
|
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;
|
||||||
@@ -1,318 +0,0 @@
|
|||||||
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 } 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.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;
|
|
||||||
31
api/src/routes/ranks.js
Normal file
31
api/src/routes/ranks.js
Normal file
@@ -0,0 +1,31 @@
|
|||||||
|
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;
|
||||||
@@ -1,99 +0,0 @@
|
|||||||
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;
|
|
||||||
116
api/src/routes/roles.js
Normal file
116
api/src/routes/roles.js
Normal file
@@ -0,0 +1,116 @@
|
|||||||
|
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;
|
||||||
@@ -1,178 +0,0 @@
|
|||||||
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,16 +1,11 @@
|
|||||||
import express = require('express');
|
const express = require('express');
|
||||||
const statusR = express.Router();
|
const status = express.Router();
|
||||||
const memberStatusR = express.Router();
|
const memberStatus = 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
|
||||||
memberStatusR.post('/', async (req, res) => {
|
memberStatus.post('/', async (req, res) => {
|
||||||
// try {
|
// try {
|
||||||
// const App = req.body?.App || {};
|
// const App = req.body?.App || {};
|
||||||
|
|
||||||
@@ -35,25 +30,17 @@ memberStatusR.post('/', async (req, res) => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
//get all statuses
|
//get all statuses
|
||||||
statusR.get('/', async (req, res) => {
|
status.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 (error) {
|
} catch (err) {
|
||||||
logger.error(
|
console.error(err);
|
||||||
'app',
|
res.status(500).json({ error: 'Internal server error' });
|
||||||
'Failed to get all statuses',
|
|
||||||
{
|
|
||||||
error: error instanceof Error ? error.message : String(error),
|
|
||||||
stack: error instanceof Error ? error.stack : undefined,
|
|
||||||
}
|
|
||||||
);
|
|
||||||
res.sendStatus(500);
|
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
export const status = statusR;
|
module.exports.status = status;
|
||||||
export const memberStatus = memberStatusR;
|
module.exports.memberStatus = memberStatus;
|
||||||
|
|
||||||
|
|
||||||
// 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;
|
||||||
@@ -1,73 +0,0 @@
|
|||||||
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,6 +1,5 @@
|
|||||||
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;"
|
||||||
@@ -80,13 +79,11 @@ 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, hasBookwork, hasQual) VALUES (?, ?, ?, ?, ?, ?);", [event.course_id, toDateTime(event.event_date), event.remarks, event.created_by, course.hasBookwork, course.hasQual]);
|
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]);
|
||||||
var eventID: number = res.insertId;
|
var eventID: number = res.insertId;
|
||||||
|
|
||||||
for (const attendee of event.attendees) {
|
for (const attendee of event.attendees) {
|
||||||
@@ -101,17 +98,16 @@ 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) {
|
||||||
if (con) await con.rollback();
|
await con.rollback();
|
||||||
|
await con.release();
|
||||||
throw error;
|
throw error;
|
||||||
} finally {
|
|
||||||
if (con) await con.release();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function getCourseEvents(sortDir: string, search: string = "", page = 1, pageSize = 10): Promise<PagedData<CourseEventSummary>> {
|
export async function getCourseEvents(sortDir: string, search: string = ""): Promise<CourseEventSummary[]> {
|
||||||
const offset = (page - 1) * pageSize;
|
|
||||||
|
|
||||||
let params = [];
|
let params = [];
|
||||||
let searchString = "";
|
let searchString = "";
|
||||||
@@ -137,23 +133,11 @@ export async function getCourseEvents(sortDir: string, search: string = "", page
|
|||||||
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};`;
|
||||||
LIMIT ? OFFSET ?;`;
|
console.log(sql)
|
||||||
|
console.log(params)
|
||||||
let countSQL = `SELECT COUNT(*) AS count
|
let events: CourseEventSummary[] = await pool.query(sql, params);
|
||||||
FROM course_events AS E
|
return events;
|
||||||
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[]> {
|
||||||
71
api/src/services/applicationService.ts
Normal file
71
api/src/services/applicationService.ts
Normal file
@@ -0,0 +1,71 @@
|
|||||||
|
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]);
|
||||||
|
}
|
||||||
19
api/src/services/cache/cache.ts
vendored
19
api/src/services/cache/cache.ts
vendored
@@ -1,19 +0,0 @@
|
|||||||
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);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -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,8 +19,7 @@ export async function createEvent(eventObject: Omit<CalendarEvent, 'id' | 'creat
|
|||||||
];
|
];
|
||||||
|
|
||||||
const result = await pool.query(sql, params);
|
const result = await pool.query(sql, params);
|
||||||
let id = Number(result.insertId);
|
return { id: result.insertId, ...eventObject };
|
||||||
return id;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function updateEvent(eventObject: CalendarEvent) {
|
export async function updateEvent(eventObject: CalendarEvent) {
|
||||||
@@ -124,8 +123,15 @@ export async function setAttendanceStatus(memberID: number, eventID: number, sta
|
|||||||
}
|
}
|
||||||
|
|
||||||
export async function getEventAttendance(eventID: number): Promise<CalendarSignup[]> {
|
export async function getEventAttendance(eventID: number): Promise<CalendarSignup[]> {
|
||||||
|
const sql = `
|
||||||
|
SELECT
|
||||||
|
s.member_id,
|
||||||
|
s.status,
|
||||||
|
m.name AS member_name
|
||||||
|
FROM calendar_events_signups s
|
||||||
|
LEFT JOIN members m ON s.member_id = m.id
|
||||||
|
WHERE s.event_id = ?
|
||||||
|
`;
|
||||||
|
|
||||||
const sql = "CALL `sp_GetCalendarEventSignups`(?)"
|
return await pool.query(sql, [eventID]);
|
||||||
const res = await pool.query(sql, [eventID]);
|
|
||||||
return res[0];
|
|
||||||
}
|
}
|
||||||
@@ -1,127 +0,0 @@
|
|||||||
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,110 +0,0 @@
|
|||||||
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];
|
|
||||||
}
|
|
||||||
@@ -1,285 +0,0 @@
|
|||||||
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 ?`);
|
|
||||||
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),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,129 +0,0 @@
|
|||||||
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;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,78 +0,0 @@
|
|||||||
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,22 +0,0 @@
|
|||||||
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');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,56 +0,0 @@
|
|||||||
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();
|
|
||||||
@@ -1,39 +0,0 @@
|
|||||||
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] }),
|
|
||||||
});
|
|
||||||
});
|
|
||||||
}
|
|
||||||
@@ -1,61 +0,0 @@
|
|||||||
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();
|
|
||||||
@@ -1,72 +0,0 @@
|
|||||||
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);
|
|
||||||
},
|
|
||||||
}
|
|
||||||
34
api/src/services/memberService.ts
Normal file
34
api/src/services/memberService.ts
Normal file
@@ -0,0 +1,34 @@
|
|||||||
|
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;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
32
api/src/services/rankService.ts
Normal file
32
api/src/services/rankService.ts
Normal file
@@ -0,0 +1,32 @@
|
|||||||
|
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);
|
||||||
|
}
|
||||||
26
api/src/services/rolesService.ts
Normal file
26
api/src/services/rolesService.ts
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
import pool from '../db';
|
||||||
|
|
||||||
|
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) {
|
||||||
|
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]);
|
||||||
|
}
|
||||||
@@ -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, start_date) VALUES (?, ?, NOW())`
|
const sql = `INSERT INTO members_statuses (member_id, status_id, event_date) VALUES (?, ?, NOW())`
|
||||||
await pool.execute(sql, [userID, statusID]);
|
await pool.execute(sql, [userID, statusID]);
|
||||||
}
|
}
|
||||||
@@ -7,7 +7,6 @@
|
|||||||
"node",
|
"node",
|
||||||
"express"
|
"express"
|
||||||
],
|
],
|
||||||
"sourceMap": true,
|
|
||||||
"paths": {
|
"paths": {
|
||||||
"@app/shared/*": ["../shared/*"]
|
"@app/shared/*": ["../shared/*"]
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,13 +0,0 @@
|
|||||||
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
|
|
||||||
@@ -5,7 +5,6 @@ module.exports = {
|
|||||||
script: 'built/api/src/index.js',
|
script: 'built/api/src/index.js',
|
||||||
watch: ['.env', 'built'],
|
watch: ['.env', 'built'],
|
||||||
ignore_watch: ['.gitignore', '\.json', 'src', '\.db', 'node_modules'],
|
ignore_watch: ['.gitignore', '\.json', 'src', '\.db', 'node_modules'],
|
||||||
appendEnvToName: true,
|
|
||||||
watch_options: {
|
watch_options: {
|
||||||
usePolling: true,
|
usePolling: true,
|
||||||
interval: 10000
|
interval: 10000
|
||||||
|
|||||||
54
readme.md
54
readme.md
@@ -1,54 +0,0 @@
|
|||||||
## 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)
|
|
||||||
@@ -1,10 +0,0 @@
|
|||||||
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;
|
|
||||||
};
|
|
||||||
@@ -1,51 +0,0 @@
|
|||||||
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.`,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
});
|
|
||||||
@@ -1,32 +0,0 @@
|
|||||||
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>;
|
|
||||||
@@ -19,42 +19,5 @@ export const trainingReportSchema = z.object({
|
|||||||
),
|
),
|
||||||
remarks: z.string().nullable().optional(),
|
remarks: z.string().nullable().optional(),
|
||||||
attendees: z.array(courseEventAttendeeSchema).default([]),
|
attendees: z.array(courseEventAttendeeSchema).default([]),
|
||||||
}).superRefine((data, ctx) => {
|
|
||||||
const trainerRole = 1;
|
|
||||||
const traineeRole = 2;
|
|
||||||
|
|
||||||
const hasTrainer = data.attendees.some((a) => a.attendee_role_id === trainerRole);
|
|
||||||
const hasTrainee = data.attendees.some((a) => a.attendee_role_id === traineeRole);
|
|
||||||
|
|
||||||
if (!hasTrainer) {
|
|
||||||
ctx.addIssue({
|
|
||||||
code: z.ZodIssueCode.custom,
|
|
||||||
path: ["attendees"],
|
|
||||||
message: "At least one Primary Trainer is required.",
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!hasTrainee) {
|
|
||||||
ctx.addIssue({
|
|
||||||
code: z.ZodIssueCode.custom,
|
|
||||||
path: ["attendees"],
|
|
||||||
message: "At least one Trainee is required.",
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
//no duplicates
|
|
||||||
const idCounts = new Map<number, number>();
|
|
||||||
|
|
||||||
data.attendees.forEach((a, index) => {
|
|
||||||
idCounts.set(a.attendee_id, (idCounts.get(a.attendee_id) ?? 0) + 1);
|
|
||||||
|
|
||||||
if (idCounts.get(a.attendee_id)! > 1) {
|
|
||||||
ctx.addIssue({
|
|
||||||
code: z.ZodIssueCode.custom,
|
|
||||||
path: ["attendees"],
|
|
||||||
message: "Cannot have duplicate attendee.",
|
|
||||||
});
|
|
||||||
}
|
|
||||||
})
|
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|||||||
@@ -40,7 +40,6 @@ 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,6 @@ export interface CalendarSignup {
|
|||||||
eventID: number;
|
eventID: number;
|
||||||
status: CalendarAttendance;
|
status: CalendarAttendance;
|
||||||
member_name?: string;
|
member_name?: string;
|
||||||
unit_name?: string;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface CalendarEventShort {
|
export interface CalendarEventShort {
|
||||||
|
|||||||
@@ -1,24 +0,0 @@
|
|||||||
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;
|
|
||||||
}
|
|
||||||
@@ -1,53 +0,0 @@
|
|||||||
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;
|
|
||||||
}
|
|
||||||
@@ -1,11 +0,0 @@
|
|||||||
export interface PagedData<T> {
|
|
||||||
data: T[]
|
|
||||||
pagination: pagination
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface pagination {
|
|
||||||
page: number
|
|
||||||
pageSize: number
|
|
||||||
total: number
|
|
||||||
totalPages: number
|
|
||||||
}
|
|
||||||
@@ -1,19 +0,0 @@
|
|||||||
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,14 +0,0 @@
|
|||||||
import { MemberLight } from "./member";
|
|
||||||
|
|
||||||
export interface Role {
|
|
||||||
id: number;
|
|
||||||
name: string;
|
|
||||||
color?: string;
|
|
||||||
description?: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface RoleSummary {
|
|
||||||
id: number;
|
|
||||||
name: string;
|
|
||||||
color?: string;
|
|
||||||
}
|
|
||||||
@@ -1,7 +0,0 @@
|
|||||||
export interface Unit {
|
|
||||||
id: number;
|
|
||||||
name: string;
|
|
||||||
description?: string;
|
|
||||||
active: boolean;
|
|
||||||
color?: string;
|
|
||||||
}
|
|
||||||
@@ -1,7 +1,5 @@
|
|||||||
export function toDateTime(date: Date): string {
|
export function toDateTime(date: Date): string {
|
||||||
if (typeof date === 'string') {
|
console.log(date);
|
||||||
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");
|
||||||
@@ -12,25 +10,3 @@ 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,10 +1,10 @@
|
|||||||
# 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
|
|
||||||
|
|
||||||
|
|
||||||
# Glitchtip
|
# Glitchtip
|
||||||
VITE_GLITCHTIP_DSN=
|
VITE_GLITCHTIP_DSN=
|
||||||
VITE_DISABLE_GLITCHTIP= # true/false
|
VITE_DISABLE_GLITCHTIP= # true/false
|
||||||
|
|
||||||
|
# Matomo
|
||||||
|
VITE_DISABLE_MATOMO= # true/false
|
||||||
@@ -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>17th Ranger Battalion</title>
|
<title>Vite App</title>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<div id="app"></div>
|
<div id="app"></div>
|
||||||
|
|||||||
143
ui/package-lock.json
generated
143
ui/package-lock.json
generated
@@ -8,6 +8,7 @@
|
|||||||
"name": "milsimsitev4",
|
"name": "milsimsitev4",
|
||||||
"version": "0.0.0",
|
"version": "0.0.0",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
|
"@certible/use-matomo": "^1.1.0",
|
||||||
"@fullcalendar/core": "^6.1.19",
|
"@fullcalendar/core": "^6.1.19",
|
||||||
"@fullcalendar/daygrid": "^6.1.19",
|
"@fullcalendar/daygrid": "^6.1.19",
|
||||||
"@fullcalendar/interaction": "^6.1.19",
|
"@fullcalendar/interaction": "^6.1.19",
|
||||||
@@ -22,7 +23,7 @@
|
|||||||
"clsx": "^2.1.1",
|
"clsx": "^2.1.1",
|
||||||
"lucide-vue-next": "^0.539.0",
|
"lucide-vue-next": "^0.539.0",
|
||||||
"pinia": "^3.0.3",
|
"pinia": "^3.0.3",
|
||||||
"reka-ui": "^2.6.1",
|
"reka-ui": "^2.6.0",
|
||||||
"tailwind-merge": "^3.3.1",
|
"tailwind-merge": "^3.3.1",
|
||||||
"tailwindcss": "^4.1.11",
|
"tailwindcss": "^4.1.11",
|
||||||
"tw-animate-css": "^1.3.6",
|
"tw-animate-css": "^1.3.6",
|
||||||
@@ -35,8 +36,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"
|
|
||||||
},
|
},
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": "^20.19.0 || >=22.12.0"
|
"node": "^20.19.0 || >=22.12.0"
|
||||||
@@ -511,6 +511,12 @@
|
|||||||
"node": ">=6.9.0"
|
"node": ">=6.9.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/@certible/use-matomo": {
|
||||||
|
"version": "1.1.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/@certible/use-matomo/-/use-matomo-1.1.0.tgz",
|
||||||
|
"integrity": "sha512-9kOTj0ldP+RX2Rhlosxm/+1uQ2deDefMb4p2DQGFi3Gqi3TuTSrOtx+beUNKGN7D8up/8SsBPJS+ipY1ZHMfrA==",
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
"node_modules/@esbuild/aix-ppc64": {
|
"node_modules/@esbuild/aix-ppc64": {
|
||||||
"version": "0.25.9",
|
"version": "0.25.9",
|
||||||
"resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.25.9.tgz",
|
"resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.25.9.tgz",
|
||||||
@@ -1885,35 +1891,6 @@
|
|||||||
"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",
|
||||||
@@ -2113,22 +2090,6 @@
|
|||||||
"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",
|
||||||
@@ -2217,13 +2178,6 @@
|
|||||||
"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",
|
||||||
@@ -3176,13 +3130,6 @@
|
|||||||
"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",
|
||||||
@@ -3276,13 +3223,6 @@
|
|||||||
"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",
|
||||||
@@ -3400,9 +3340,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/reka-ui": {
|
"node_modules/reka-ui": {
|
||||||
"version": "2.6.1",
|
"version": "2.6.0",
|
||||||
"resolved": "https://registry.npmjs.org/reka-ui/-/reka-ui-2.6.1.tgz",
|
"resolved": "https://registry.npmjs.org/reka-ui/-/reka-ui-2.6.0.tgz",
|
||||||
"integrity": "sha512-XK7cJDQoNuGXfCNzBBo/81Yg/OgjPwvbabnlzXG2VsdSgNsT6iIkuPBPr+C0Shs+3bb0x0lbPvgQAhMSCKm5Ww==",
|
"integrity": "sha512-NrGMKrABD97l890mFS3TNUzB0BLUfbL3hh0NjcJRIUSUljb288bx3Mzo31nOyUcdiiW0HqFGXJwyCBh9cWgb0w==",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@floating-ui/dom": "^1.6.13",
|
"@floating-ui/dom": "^1.6.13",
|
||||||
@@ -3661,13 +3601,13 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/tinyglobby": {
|
"node_modules/tinyglobby": {
|
||||||
"version": "0.2.14",
|
"version": "0.2.15",
|
||||||
"resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.14.tgz",
|
"resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.15.tgz",
|
||||||
"integrity": "sha512-tX5e7OM1HnYr2+a2C/4V0htOcSQcoSTH9KgJnVvNm5zm/cyEWKJ7j7YutsH9CxMdtOkkLFy2AHrMci9IM8IPZQ==",
|
"integrity": "sha512-j2Zq4NyQYG5XMST4cbs02Ak8iJUdxRM0XI5QyxXuZOzKOINmWurp3smXu3y5wDcJrptwpSjgXHzIQxR0omXljQ==",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"fdir": "^6.4.4",
|
"fdir": "^6.5.0",
|
||||||
"picomatch": "^4.0.2"
|
"picomatch": "^4.0.3"
|
||||||
},
|
},
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=12.0.0"
|
"node": ">=12.0.0"
|
||||||
@@ -3713,21 +3653,6 @@
|
|||||||
"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",
|
||||||
@@ -3810,17 +3735,17 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/vite": {
|
"node_modules/vite": {
|
||||||
"version": "7.1.2",
|
"version": "7.2.4",
|
||||||
"resolved": "https://registry.npmjs.org/vite/-/vite-7.1.2.tgz",
|
"resolved": "https://registry.npmjs.org/vite/-/vite-7.2.4.tgz",
|
||||||
"integrity": "sha512-J0SQBPlQiEXAF7tajiH+rUooJPo0l8KQgyg4/aMunNtrOa7bwuZJsJbDWzeljqQpgftxuq5yNJxQ91O9ts29UQ==",
|
"integrity": "sha512-NL8jTlbo0Tn4dUEXEsUg8KeyG/Lkmc4Fnzb8JXN/Ykm9G4HNImjtABMJgkQoVjOBN/j2WAwDTRytdqJbZsah7w==",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"esbuild": "^0.25.0",
|
"esbuild": "^0.25.0",
|
||||||
"fdir": "^6.4.6",
|
"fdir": "^6.5.0",
|
||||||
"picomatch": "^4.0.3",
|
"picomatch": "^4.0.3",
|
||||||
"postcss": "^8.5.6",
|
"postcss": "^8.5.6",
|
||||||
"rollup": "^4.43.0",
|
"rollup": "^4.43.0",
|
||||||
"tinyglobby": "^0.2.14"
|
"tinyglobby": "^0.2.15"
|
||||||
},
|
},
|
||||||
"bin": {
|
"bin": {
|
||||||
"vite": "bin/vite.js"
|
"vite": "bin/vite.js"
|
||||||
@@ -4014,13 +3939,6 @@
|
|||||||
"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",
|
||||||
@@ -4063,23 +3981,6 @@
|
|||||||
"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",
|
||||||
|
|||||||
@@ -12,6 +12,7 @@
|
|||||||
"preview": "vite preview"
|
"preview": "vite preview"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
|
"@certible/use-matomo": "^1.1.0",
|
||||||
"@fullcalendar/core": "^6.1.19",
|
"@fullcalendar/core": "^6.1.19",
|
||||||
"@fullcalendar/daygrid": "^6.1.19",
|
"@fullcalendar/daygrid": "^6.1.19",
|
||||||
"@fullcalendar/interaction": "^6.1.19",
|
"@fullcalendar/interaction": "^6.1.19",
|
||||||
@@ -26,7 +27,7 @@
|
|||||||
"clsx": "^2.1.1",
|
"clsx": "^2.1.1",
|
||||||
"lucide-vue-next": "^0.539.0",
|
"lucide-vue-next": "^0.539.0",
|
||||||
"pinia": "^3.0.3",
|
"pinia": "^3.0.3",
|
||||||
"reka-ui": "^2.6.1",
|
"reka-ui": "^2.6.0",
|
||||||
"tailwind-merge": "^3.3.1",
|
"tailwind-merge": "^3.3.1",
|
||||||
"tailwindcss": "^4.1.11",
|
"tailwindcss": "^4.1.11",
|
||||||
"tw-animate-css": "^1.3.6",
|
"tw-animate-css": "^1.3.6",
|
||||||
@@ -39,7 +40,6 @@
|
|||||||
"@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"
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Binary file not shown.
|
Before Width: | Height: | Size: 42 KiB |
BIN
ui/public/bg.jpg
BIN
ui/public/bg.jpg
Binary file not shown.
|
Before Width: | Height: | Size: 543 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 15 KiB After Width: | Height: | Size: 4.2 KiB |
152
ui/src/App.vue
152
ui/src/App.vue
@@ -1,14 +1,41 @@
|
|||||||
<script setup lang="ts">
|
<script setup>
|
||||||
import { RouterView } from 'vue-router';
|
import { RouterLink, RouterView } from 'vue-router';
|
||||||
|
import Separator from './components/ui/separator/Separator.vue';
|
||||||
import Button from './components/ui/button/Button.vue';
|
import Button from './components/ui/button/Button.vue';
|
||||||
|
import { Popover, PopoverContent, PopoverTrigger } from './components/ui/popover';
|
||||||
|
import {
|
||||||
|
DropdownMenu,
|
||||||
|
DropdownMenuContent,
|
||||||
|
DropdownMenuItem,
|
||||||
|
DropdownMenuTrigger,
|
||||||
|
} from './components/ui/dropdown-menu';
|
||||||
|
import { onMounted } from '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 { cancelLOA } from './api/loa';
|
|
||||||
|
|
||||||
const userStore = useUserStore();
|
const userStore = useUserStore();
|
||||||
|
|
||||||
|
// onMounted(async () => {
|
||||||
|
// const res = await fetch(`${import.meta.env.VITE_APIHOST}/members/me`, {
|
||||||
|
// credentials: 'include',
|
||||||
|
// });
|
||||||
|
// const data = await res.json();
|
||||||
|
// console.log(data);
|
||||||
|
// userStore.user = data;
|
||||||
|
// });
|
||||||
|
const APIHOST = import.meta.env.VITE_APIHOST;
|
||||||
|
|
||||||
|
async function logout() {
|
||||||
|
// await fetch(`${APIHOST}/logout`, {
|
||||||
|
// method: 'GET',
|
||||||
|
// credentials: 'include',
|
||||||
|
// });
|
||||||
|
|
||||||
|
userStore.user = null;
|
||||||
|
window.location.href = APIHOST + "/logout";
|
||||||
|
}
|
||||||
|
|
||||||
function formatDate(dateStr) {
|
function formatDate(dateStr) {
|
||||||
if (!dateStr) return "";
|
if (!dateStr) return "";
|
||||||
return new Date(dateStr).toLocaleDateString("en-US", {
|
return new Date(dateStr).toLocaleDateString("en-US", {
|
||||||
@@ -18,42 +45,95 @@
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
//@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" style="background-image: linear-gradient(rgba(0, 0, 0, 0.25), rgba(0, 0, 0, 0.25)), url('/bg.jpg');
|
<div>
|
||||||
background-size: contain;
|
<div class="flex items-center justify-between px-10">
|
||||||
background-attachment: fixed;
|
<div></div>
|
||||||
background-position: center;">
|
<div class="h-15 flex items-center justify-center gap-20">
|
||||||
<div class="sticky top-0 bg-background z-50">
|
<RouterLink to="/">
|
||||||
<Navbar class="flex"></Navbar>
|
<Button variant="link">Home</Button>
|
||||||
<Alert v-if="environment == 'dev'" class="m-2 mx-auto max-w-5xl" variant="info">
|
</RouterLink>
|
||||||
<AlertDescription class="flex flex-row items-center text-wrap gap-5 mx-auto">
|
<RouterLink to="/calendar">
|
||||||
<p>Development environment (v{{ version }}). Features may be incomplete or unavailable.</p>
|
<Button variant="link">Calendar</Button>
|
||||||
</AlertDescription>
|
</RouterLink>
|
||||||
</Alert>
|
<RouterLink to="/members">
|
||||||
<Alert v-if="userStore.user?.LOAs?.[0]" class="m-2 mx-auto max-w-5xl" variant="info">
|
<Button variant="link">Members</Button>
|
||||||
<AlertDescription class="flex flex-row items-center text-nowrap gap-5 mx-auto">
|
</RouterLink>
|
||||||
<p
|
<Popover>
|
||||||
v-if="new Date(userStore.user?.LOAs?.[0].extended_till || userStore.user?.LOAs?.[0].end_date) > new Date()">
|
<PopoverTrigger as-child>
|
||||||
LOA until <strong>{{ formatDate(userStore.user?.LOAs?.[0].extended_till ||
|
<Button variant="link">Forms</Button>
|
||||||
userStore.user?.LOAs?.[0].end_date) }}</strong>
|
</PopoverTrigger>
|
||||||
</p>
|
<PopoverContent class="flex flex-col gap-4 items-center w-min">
|
||||||
<p v-else>
|
<RouterLink to="/transfer">
|
||||||
LOA expired on <strong>{{ formatDate(userStore.user?.LOAs?.[0].extended_till ||
|
<Button variant="link">Transfer Request</Button>
|
||||||
userStore.user?.LOAs?.[0].end_date) }}</strong>
|
</RouterLink>
|
||||||
</p>
|
<RouterLink to="/trainingReport">
|
||||||
<Button variant="secondary"
|
<Button variant="link">Training Report</Button>
|
||||||
@click="async () => { await cancelLOA(userStore.user.LOAs?.[0].id); userStore.loadUser(); }">End
|
</RouterLink>
|
||||||
LOA</Button>
|
</PopoverContent>
|
||||||
</AlertDescription>
|
</Popover>
|
||||||
</Alert>
|
<Popover>
|
||||||
</div>
|
<PopoverTrigger as-child>
|
||||||
|
<Button variant="link">Administration</Button>
|
||||||
|
</PopoverTrigger>
|
||||||
|
<PopoverContent class="flex flex-col gap-4 items-center w-min">
|
||||||
|
<RouterLink to="/administration/rankChange">
|
||||||
|
<Button variant="link">Promotions</Button>
|
||||||
|
</RouterLink>
|
||||||
|
<RouterLink to="/administration/loa">
|
||||||
|
<Button variant="link">Leave of Absence</Button>
|
||||||
|
</RouterLink>
|
||||||
|
<RouterLink to="/administration/transfer">
|
||||||
|
<Button variant="link">Transfer Requests</Button>
|
||||||
|
</RouterLink>
|
||||||
|
<RouterLink to="/administration/applications">
|
||||||
|
<Button variant="link">Recruitment</Button>
|
||||||
|
</RouterLink>
|
||||||
|
<RouterLink to="/administration/roles">
|
||||||
|
<Button variant="link">Role Management</Button>
|
||||||
|
</RouterLink>
|
||||||
|
</PopoverContent>
|
||||||
|
</Popover>
|
||||||
|
|
||||||
<RouterView class="flex-1 min-h-0"></RouterView>
|
</div>
|
||||||
|
<div>
|
||||||
|
<DropdownMenu v-if="userStore.isLoggedIn">
|
||||||
|
<DropdownMenuTrigger class="cursor-pointer">
|
||||||
|
<p>{{ userStore.user.name }}</p>
|
||||||
|
</DropdownMenuTrigger>
|
||||||
|
<DropdownMenuContent>
|
||||||
|
<DropdownMenuItem>My Profile</DropdownMenuItem>
|
||||||
|
<DropdownMenuItem>Settings</DropdownMenuItem>
|
||||||
|
<DropdownMenuItem>
|
||||||
|
<RouterLink to="/loa">
|
||||||
|
Submit LOA
|
||||||
|
</RouterLink>
|
||||||
|
</DropdownMenuItem>
|
||||||
|
<DropdownMenuItem :variant="'destructive'" @click="logout()">Logout</DropdownMenuItem>
|
||||||
|
</DropdownMenuContent>
|
||||||
|
</DropdownMenu>
|
||||||
|
|
||||||
|
<a v-else :href="APIHOST + '/login'">Login</a>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<Separator></Separator>
|
||||||
|
<Alert v-if="environment == 'dev'" class="m-2 mx-auto w-5xl" variant="info">
|
||||||
|
<AlertDescription class="flex flex-row items-center text-nowrap gap-5 mx-auto">
|
||||||
|
<p>This is a development build of the application. Some features will be unavailable or unstable.</p>
|
||||||
|
</AlertDescription>
|
||||||
|
</Alert>
|
||||||
|
<Alert v-if="userStore.user?.loa?.[0]" class="m-2 mx-auto w-5xl" variant="info">
|
||||||
|
<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>
|
||||||
|
<Button variant="secondary">End LOA</Button>
|
||||||
|
</AlertDescription>
|
||||||
|
</Alert>
|
||||||
|
|
||||||
|
<RouterView class=""></RouterView>
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
|
<style scoped></style>
|
||||||
|
|||||||
@@ -1,11 +1,80 @@
|
|||||||
import { ApplicationFull } from "@shared/types/application";
|
export type ApplicationDto = Partial<{
|
||||||
|
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, asAdmin: boolean = false): Promise<ApplicationFull | null> {
|
export async function loadApplication(id: number | string): Promise<ApplicationFull | null> {
|
||||||
const res = await fetch(`${addr}/application/${id}?admin=${asAdmin}`, { credentials: 'include' })
|
const res = await fetch(`${addr}/application/${id}`)
|
||||||
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()
|
||||||
@@ -35,22 +104,6 @@ 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),
|
||||||
})
|
})
|
||||||
@@ -59,9 +112,7 @@ export async function postAdminChatMessage(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()
|
||||||
@@ -70,67 +121,18 @@ export async function getAllApplications(): Promise<ApplicationFull> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function loadMyApplications(): Promise<ApplicationFull> {
|
|
||||||
const res = await fetch(`${addr}/application/meList`, { credentials: 'include' })
|
|
||||||
|
|
||||||
if (res.ok) {
|
|
||||||
return res.json()
|
|
||||||
} else {
|
|
||||||
console.error("Something went wrong approving the application")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function getMyApplication(id: number): Promise<ApplicationFull> {
|
|
||||||
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) {
|
export async function approveApplication(id: Number) {
|
||||||
const res = await fetch(`${addr}/application/approve/${id}`, { method: 'POST', credentials: 'include' })
|
const res = await fetch(`${addr}/application/approve/${id}`, { method: 'POST' })
|
||||||
|
|
||||||
if (!res.ok) {
|
if (!res.ok) {
|
||||||
throw new Error("Something went wrong approving the application");
|
console.error("Something went wrong approving the application")
|
||||||
}
|
}
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function denyApplication(id: Number) {
|
export async function denyApplication(id: Number) {
|
||||||
const res = await fetch(`${addr}/application/deny/${id}`, { method: 'POST', credentials: 'include' })
|
const res = await fetch(`${addr}/application/deny/${id}`, { method: 'POST' })
|
||||||
|
|
||||||
if (!res.ok) {
|
if (!res.ok) {
|
||||||
throw new Error("Something went wrong denyting the application");
|
console.error("Something went wrong denying 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,6 +100,7 @@ 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"
|
||||||
|
|||||||
@@ -1,18 +0,0 @@
|
|||||||
// @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,5 +1,12 @@
|
|||||||
import { LOARequest, LOAType } from '@shared/types/loa'
|
export type LOARequest = {
|
||||||
import { PagedData } from '@shared/types/pagination'
|
id?: number;
|
||||||
|
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;
|
||||||
|
|
||||||
@@ -10,41 +17,21 @@ 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;
|
return res.json();
|
||||||
} else {
|
} else {
|
||||||
throw new Error("Failed to submit LOA");
|
return { 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',
|
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
||||||
@@ -59,49 +46,12 @@ export async function getMyLOA(): Promise<LOARequest | null> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function getAllLOAs(page?: number, pageSize?: number): Promise<PagedData<LOARequest>> {
|
export function getAllLOAs(): Promise<LOARequest[]> {
|
||||||
const params = new URLSearchParams();
|
return fetch(`${addr}/loa/all`, {
|
||||||
|
|
||||||
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();
|
||||||
@@ -109,86 +59,4 @@ export function getMyLOAs(page?: number, pageSize?: number): Promise<PagedData<L
|
|||||||
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,5 +1,12 @@
|
|||||||
import { Discharge } from "@shared/schemas/dischargeSchema";
|
export type Member = {
|
||||||
import { memberSettings, Member, MemberLight, MemberCardDetails, PaginatedMembers, MemberState } from "@shared/types/member";
|
member_id: number;
|
||||||
|
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;
|
||||||
@@ -13,148 +20,3 @@ 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;
|
|
||||||
}
|
|
||||||
@@ -1,73 +1,38 @@
|
|||||||
import { BatchPromotion, BatchPromotionMember } from '@shared/schemas/promotionSchema';
|
export type Rank = {
|
||||||
import { PagedData } from '@shared/types/pagination';
|
id: number
|
||||||
import { PromotionDetails, PromotionSummary, Rank } from '@shared/types/rank'
|
name: string
|
||||||
|
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 getAllRanks(): Promise<Rank[]> {
|
export async function getRanks(): 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")
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function submitRankChange(promo: BatchPromotion) {
|
// Placeholder: submit a rank change
|
||||||
|
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",
|
||||||
},
|
},
|
||||||
credentials: 'include',
|
body: JSON.stringify({ change: { member_id, rank_id, date } }),
|
||||||
body: JSON.stringify(promo),
|
|
||||||
})
|
})
|
||||||
|
|
||||||
if (res.ok) {
|
if (res.ok) {
|
||||||
return
|
return { ok: true }
|
||||||
} else {
|
} else {
|
||||||
throw new Error("Failed to submit rank change: Server error");
|
console.error("Failed to submit rank change")
|
||||||
}
|
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,13 +1,16 @@
|
|||||||
import { Member, MemberLight } from "@shared/types/member";
|
export type Role = {
|
||||||
import { Role } from "@shared/types/roles";
|
id: number;
|
||||||
|
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[]>;
|
||||||
@@ -17,42 +20,17 @@ 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) {
|
||||||
@@ -69,7 +47,6 @@ 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
|
||||||
@@ -87,7 +64,6 @@ 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"
|
||||||
},
|
},
|
||||||
@@ -107,8 +83,7 @@ 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,34 +1,13 @@
|
|||||||
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, page?: number, pageSize?: number): Promise<PagedData<CourseEventSummary>> {
|
export async function getTrainingReports(sortMode: string, search: string): Promise<CourseEventSummary[]> {
|
||||||
const params = new URLSearchParams();
|
const res = await fetch(`${addr}/courseEvent?sort=${sortMode}&search=${search}`);
|
||||||
|
|
||||||
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<PagedData<CourseEventSummary>>;
|
return await res.json() as Promise<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");
|
||||||
@@ -36,9 +15,7 @@ export async function getTrainingReports(sortMode?: string, search?: string, pag
|
|||||||
}
|
}
|
||||||
|
|
||||||
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>;
|
||||||
@@ -49,9 +26,7 @@ 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[]>;
|
||||||
@@ -62,9 +37,7 @@ 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[]>;
|
||||||
|
|||||||
@@ -1,26 +0,0 @@
|
|||||||
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,55 +4,6 @@
|
|||||||
@custom-variant dark (&:is(.dark *));
|
@custom-variant dark (&:is(.dark *));
|
||||||
|
|
||||||
:root {
|
:root {
|
||||||
--background: oklch(19.125% 0.00002 271.152);
|
|
||||||
--foreground: oklch(0.9219 0 0);
|
|
||||||
--card: oklch(23.075% 0.00003 271.152);
|
|
||||||
--card-foreground: oklch(0.9219 0 0);
|
|
||||||
--popover: oklch(0.2686 0 0);
|
|
||||||
--popover-foreground: oklch(0.9219 0 0);
|
|
||||||
--primary: oklch(0.7686 0.1647 70.0804);
|
|
||||||
--primary-foreground: oklch(0 0 0);
|
|
||||||
--secondary: oklch(0.2686 0 0);
|
|
||||||
--secondary-foreground: oklch(0.9219 0 0);
|
|
||||||
--muted: oklch(0.2686 0 0);
|
|
||||||
--muted-foreground: oklch(0.7155 0 0);
|
|
||||||
--accent: oklch(100% 0.00011 271.152 / 0.253);
|
|
||||||
--accent-foreground: oklch(100% 0.00011 271.152);
|
|
||||||
--destructive: oklch(0.6368 0.2078 25.3313);
|
|
||||||
--destructive-foreground: oklch(1.0000 0 0);
|
|
||||||
--success: oklch(66.104% 0.16937 144.153);
|
|
||||||
--success-foreground: oklch(1.0000 0 0);
|
|
||||||
--border: oklch(0.3715 0 0);
|
|
||||||
--input: oklch(0.3715 0 0);
|
|
||||||
--ring: oklch(0.7686 0.1647 70.0804);
|
|
||||||
--chart-1: oklch(0.8369 0.1644 84.4286);
|
|
||||||
--chart-2: oklch(0.6658 0.1574 58.3183);
|
|
||||||
--chart-3: oklch(0.4732 0.1247 46.2007);
|
|
||||||
--chart-4: oklch(0.5553 0.1455 48.9975);
|
|
||||||
--chart-5: oklch(0.4732 0.1247 46.2007);
|
|
||||||
--sidebar: oklch(0.1684 0 0);
|
|
||||||
--sidebar-foreground: oklch(0.9219 0 0);
|
|
||||||
--sidebar-primary: oklch(0.7686 0.1647 70.0804);
|
|
||||||
--sidebar-primary-foreground: oklch(1.0000 0 0);
|
|
||||||
--sidebar-accent: oklch(0.4732 0.1247 46.2007);
|
|
||||||
--sidebar-accent-foreground: oklch(0.9243 0.1151 95.7459);
|
|
||||||
--sidebar-border: oklch(0.3715 0 0);
|
|
||||||
--sidebar-ring: oklch(0.7686 0.1647 70.0804);
|
|
||||||
--font-sans: Inter, sans-serif;
|
|
||||||
--font-serif: Source Serif 4, serif;
|
|
||||||
--font-mono: JetBrains Mono, monospace;
|
|
||||||
--radius: 0.375rem;
|
|
||||||
--shadow-2xs: 0px 4px 8px -1px hsl(0 0% 0% / 0.07);
|
|
||||||
--shadow-xs: 0px 4px 8px -1px hsl(0 0% 0% / 0.07);
|
|
||||||
--shadow-sm: 0px 4px 8px -1px hsl(0 0% 0% / 0.14), 0px 1px 2px -2px hsl(0 0% 0% / 0.14);
|
|
||||||
--shadow: 0px 4px 8px -1px hsl(0 0% 0% / 0.14), 0px 1px 2px -2px hsl(0 0% 0% / 0.14);
|
|
||||||
--shadow-md: 0px 4px 8px -1px hsl(0 0% 0% / 0.14), 0px 2px 4px -2px hsl(0 0% 0% / 0.14);
|
|
||||||
--shadow-lg: 0px 4px 8px -1px hsl(0 0% 0% / 0.14), 0px 4px 6px -2px hsl(0 0% 0% / 0.14);
|
|
||||||
--shadow-xl: 0px 4px 8px -1px hsl(0 0% 0% / 0.14), 0px 8px 10px -2px hsl(0 0% 0% / 0.14);
|
|
||||||
--shadow-2xl: 0px 4px 8px -1px hsl(0 0% 0% / 0.35);
|
|
||||||
}
|
|
||||||
|
|
||||||
/* .dark {
|
|
||||||
--background: oklch(0.2046 0 0);
|
--background: oklch(0.2046 0 0);
|
||||||
--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);
|
||||||
@@ -99,7 +50,56 @@
|
|||||||
--shadow-lg: 0px 4px 8px -1px hsl(0 0% 0% / 0.14), 0px 4px 6px -2px hsl(0 0% 0% / 0.14);
|
--shadow-lg: 0px 4px 8px -1px hsl(0 0% 0% / 0.14), 0px 4px 6px -2px hsl(0 0% 0% / 0.14);
|
||||||
--shadow-xl: 0px 4px 8px -1px hsl(0 0% 0% / 0.14), 0px 8px 10px -2px hsl(0 0% 0% / 0.14);
|
--shadow-xl: 0px 4px 8px -1px hsl(0 0% 0% / 0.14), 0px 8px 10px -2px hsl(0 0% 0% / 0.14);
|
||||||
--shadow-2xl: 0px 4px 8px -1px hsl(0 0% 0% / 0.35);
|
--shadow-2xl: 0px 4px 8px -1px hsl(0 0% 0% / 0.35);
|
||||||
} */
|
}
|
||||||
|
|
||||||
|
.dark {
|
||||||
|
--background: oklch(0.2046 0 0);
|
||||||
|
--foreground: oklch(0.9219 0 0);
|
||||||
|
--card: oklch(23.075% 0.00003 271.152);
|
||||||
|
--card-foreground: oklch(0.9219 0 0);
|
||||||
|
--popover: oklch(0.2686 0 0);
|
||||||
|
--popover-foreground: oklch(0.9219 0 0);
|
||||||
|
--primary: oklch(0.7686 0.1647 70.0804);
|
||||||
|
--primary-foreground: oklch(0 0 0);
|
||||||
|
--secondary: oklch(0.2686 0 0);
|
||||||
|
--secondary-foreground: oklch(0.9219 0 0);
|
||||||
|
--muted: oklch(0.2686 0 0);
|
||||||
|
--muted-foreground: oklch(0.7155 0 0);
|
||||||
|
--accent: oklch(0.4732 0.1247 46.2007);
|
||||||
|
--accent-foreground: oklch(0.9243 0.1151 95.7459);
|
||||||
|
--destructive: oklch(0.6368 0.2078 25.3313);
|
||||||
|
--destructive-foreground: oklch(1.0000 0 0);
|
||||||
|
--success: oklch(66.104% 0.16937 144.153);
|
||||||
|
--success-foreground: oklch(1.0000 0 0);
|
||||||
|
--border: oklch(0.3715 0 0);
|
||||||
|
--input: oklch(0.3715 0 0);
|
||||||
|
--ring: oklch(0.7686 0.1647 70.0804);
|
||||||
|
--chart-1: oklch(0.8369 0.1644 84.4286);
|
||||||
|
--chart-2: oklch(0.6658 0.1574 58.3183);
|
||||||
|
--chart-3: oklch(0.4732 0.1247 46.2007);
|
||||||
|
--chart-4: oklch(0.5553 0.1455 48.9975);
|
||||||
|
--chart-5: oklch(0.4732 0.1247 46.2007);
|
||||||
|
--sidebar: oklch(0.1684 0 0);
|
||||||
|
--sidebar-foreground: oklch(0.9219 0 0);
|
||||||
|
--sidebar-primary: oklch(0.7686 0.1647 70.0804);
|
||||||
|
--sidebar-primary-foreground: oklch(1.0000 0 0);
|
||||||
|
--sidebar-accent: oklch(0.4732 0.1247 46.2007);
|
||||||
|
--sidebar-accent-foreground: oklch(0.9243 0.1151 95.7459);
|
||||||
|
--sidebar-border: oklch(0.3715 0 0);
|
||||||
|
--sidebar-ring: oklch(0.7686 0.1647 70.0804);
|
||||||
|
--font-sans: Inter, sans-serif;
|
||||||
|
--font-serif: Source Serif 4, serif;
|
||||||
|
--font-mono: JetBrains Mono, monospace;
|
||||||
|
--radius: 0.375rem;
|
||||||
|
--shadow-2xs: 0px 4px 8px -1px hsl(0 0% 0% / 0.07);
|
||||||
|
--shadow-xs: 0px 4px 8px -1px hsl(0 0% 0% / 0.07);
|
||||||
|
--shadow-sm: 0px 4px 8px -1px hsl(0 0% 0% / 0.14), 0px 1px 2px -2px hsl(0 0% 0% / 0.14);
|
||||||
|
--shadow: 0px 4px 8px -1px hsl(0 0% 0% / 0.14), 0px 1px 2px -2px hsl(0 0% 0% / 0.14);
|
||||||
|
--shadow-md: 0px 4px 8px -1px hsl(0 0% 0% / 0.14), 0px 2px 4px -2px hsl(0 0% 0% / 0.14);
|
||||||
|
--shadow-lg: 0px 4px 8px -1px hsl(0 0% 0% / 0.14), 0px 4px 6px -2px hsl(0 0% 0% / 0.14);
|
||||||
|
--shadow-xl: 0px 4px 8px -1px hsl(0 0% 0% / 0.14), 0px 8px 10px -2px hsl(0 0% 0% / 0.14);
|
||||||
|
--shadow-2xl: 0px 4px 8px -1px hsl(0 0% 0% / 0.35);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
@theme inline {
|
@theme inline {
|
||||||
@@ -166,111 +166,3 @@
|
|||||||
@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;
|
|
||||||
}
|
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user