109 Commits

Author SHA1 Message Date
406f61a612 Merge branch 'main' into database-view-updates 2025-12-12 10:24:01 -06:00
f7daa1bb19 Merge pull request 'application-dp-upgrade' (#66) from application-dp-upgrade into main
All checks were successful
Continuous Integration / Update Development (push) Successful in 2m35s
Reviewed-on: #66
2025-12-12 10:16:56 -06:00
8a7ca9c2f9 Merge branch 'main' into application-dp-upgrade 2025-12-12 10:12:10 -06:00
1730714737 updated loa bookstack to new render system 2025-12-12 11:10:32 -05:00
8dc11ee34d made nested bookstack links open in new tab 2025-12-12 11:06:00 -05:00
2a841ebf27 fixed "view coc" button causing application submit 2025-12-12 10:56:07 -05:00
d7908570b2 improved bookstack rendering 2025-12-12 10:53:45 -05:00
629fd59a7c fixed scrolling behaviour on application management page 2025-12-12 10:53:33 -05:00
333bf20d86 integrated CoC pull from bookstack 2025-12-12 00:39:19 -05:00
bd3c3564a9 Merge pull request 'Documentation' (#65) from Documentation into main
All checks were successful
Continuous Integration / Update Development (push) Successful in 2m23s
Reviewed-on: #65
2025-12-11 22:00:45 -06:00
6c688a86ea Merge commit 'a6d54e0b73b0e388a96008400977db2715f214ce' into Documentation 2025-12-11 22:49:57 -05:00
26ccae9078 added arrow to indicate redirect
Some checks failed
Continuous Deployment / Update Deployment (push) Failing after 1m29s
2025-12-11 22:36:20 -05:00
dc88126b6c Added documents site link
Some checks failed
Continuous Deployment / Update Deployment (push) Failing after 1m36s
2025-12-11 22:26:33 -05:00
c74b5b280b placeholdered CoC getter until CoC page exists on bookstack 2025-12-11 22:05:46 -05:00
0a1704b60b Updated application acceptance system 2025-12-11 21:43:49 -05:00
97119dec97 added config_id reference to .env 2025-12-11 21:22:23 -05:00
a6d54e0b73 Merge pull request '#54-Application-tweaks' (#62) from #54-Application-tweaks into main
All checks were successful
Continuous Integration / Update Development (push) Successful in 2m8s
Reviewed-on: #62
2025-12-11 19:54:02 -06:00
79d80be1bf Merge commit '0919997e0f90ec5463f63f470213acd7e39493af' into #54-Application-tweaks 2025-12-11 20:55:03 -05:00
0919997e0f Merge pull request 'LOA-Upgrades' (#64) from LOA-Upgrades into main
All checks were successful
Continuous Integration / Update Development (push) Successful in 2m32s
Reviewed-on: #64
2025-12-11 19:50:14 -06:00
a5d4941d00 Merge branch 'main' into LOA-Upgrades 2025-12-11 19:49:55 -06:00
3835f22940 removed nuisance logging 2025-12-11 20:41:29 -05:00
f0ac2dca02 fixed an issue with a bad response on submitting LOA 2025-12-11 20:37:00 -05:00
710b24e5a7 added policy system and self LOA management 2025-12-11 20:28:49 -05:00
bcde81093d implemented LOA cancelling and extensioning 2025-12-11 19:08:24 -05:00
a3216ba5ab More bookstack integration stuff 2025-12-11 15:49:08 -05:00
7ab06b6a4c hooked up new LOA creation system 2025-12-11 12:06:00 -05:00
9d217aafaf improved robustness of time serialization system 2025-12-11 12:05:41 -05:00
87c472e98e fixed dialog scaling issue 2025-12-11 11:52:11 -05:00
dcb4720129 placeholdered bookstack integration 2025-12-11 11:38:11 -05:00
8cdbb99d6f implemented constraints on datepickers 2025-12-11 11:25:09 -05:00
2821bc62c4 removed test datepicker 2025-12-11 11:00:11 -05:00
dd472a5283 updated datepicker dependency 2025-12-11 11:00:02 -05:00
92c0d657ea overhauled form system to new modern form 2025-12-11 10:25:29 -05:00
7a6020febb Changed event_date to start_date 2025-12-11 09:22:44 -06:00
fb64b35807 Updated database reference view_member_rank_status_all to view_member_rank_unit_status_latest 2025-12-10 22:18:52 -06:00
a8165e2ae5 Added Unit Table Header and Cell 2025-12-10 22:18:08 -06:00
79cf77dc63 Added 2 data types unit, unit_date 2025-12-10 22:17:45 -06:00
62defe5b6d LOA backend refactor 2025-12-10 21:30:41 -05:00
065d3f330a Merge pull request 'Updated GUILDED references and links.' (#60) from external-links-and-app-messages into main
All checks were successful
Continuous Integration / Update Development (push) Successful in 1m56s
Continuous Deployment / Update Deployment (push) Successful in 2m9s
Reviewed-on: #60
2025-12-10 20:21:32 -06:00
dcd1f522ad Merge branch 'main' into external-links-and-app-messages 2025-12-10 20:21:24 -06:00
22c909cfa5 increase logging in deploy script
All checks were successful
Continuous Integration / Update Development (push) Successful in 2m24s
for some reason it seems to not be fully updating the local repo, so increase logging and double pull
2025-12-10 20:20:06 -06:00
50b9924627 deployment versioning
Some checks failed
Continuous Integration / Update Development (push) Successful in 1m58s
Continuous Deployment / Update Deployment (push) Failing after 2m12s
port development versioning to deployment, but using tags instead of short sha
2025-12-10 11:50:07 -06:00
d44d490905 version parsing fix
All checks were successful
Continuous Integration / Update Development (push) Successful in 2m13s
attempt parse fix because i forgot this isn't running on windows
2025-12-10 11:43:40 -06:00
114857cceb debug workflow
Some checks failed
Continuous Integration / Update Development (push) Failing after 1m49s
is sed really not included?
2025-12-10 11:35:58 -06:00
0245cb38f4 enable development app versioning
Some checks failed
Continuous Integration / Update Development (push) Failing after 2m16s
parse git commit short sha and use as app version in development
2025-12-10 11:30:13 -06:00
4e443cf46d Fixed glitchtip enable/disable to behave as expected and added support for ENV versioning
All checks were successful
Continuous Integration / Update Development (push) Successful in 2m27s
2025-12-10 00:18:09 -05:00
be53fce4a5 Merge pull request 'Calendar-Improvements' (#57) from Calendar-Improvements into main
All checks were successful
Continuous Integration / Update Development (push) Successful in 2m23s
Reviewed-on: #57
2025-12-09 21:21:24 -06:00
2ac66877eb Merge branch 'main' into Calendar-Improvements 2025-12-09 21:21:03 -06:00
760965de19 Add .gitea/workflows/ci-deploy.yaml
Some checks failed
Continuous Integration / Update Development (push) Failing after 1m28s
create CI script based on CD script to run on every push to main and deploy on development site
2025-12-09 21:11:03 -06:00
37f204137b Update .gitea/workflows/cd-deploy.yaml
fix run, apparently on push triggers are not cumulatively conditional
2025-12-09 21:06:45 -06:00
58431891ba Update ecosystem.config.js
All checks were successful
Continuous Deployment / Update Deployment (push) Successful in 2m15s
allow automatic naming of started process based on environment
2025-12-09 20:55:41 -06:00
a95bf3318d Update .gitea/workflows/cd-deploy.yaml
All checks were successful
Continuous Deployment / Update Deployment (push) Successful in 2m5s
update the CD script to only run on tags signifying a usable release
2025-12-09 20:53:33 -06:00
6d544225d9 Update .gitea/workflows/cd-deploy.yaml
All checks were successful
Continuous Deployment / Update Deployment (push) Successful in 3m20s
fix syntax
2025-12-09 20:31:38 -06:00
ec854c6800 Update .gitea/workflows/cd-deploy.yaml
Some checks failed
Continuous Deployment / Update Deployment (push) Failing after 1m17s
update node version to 20 from built in 18
2025-12-09 20:26:13 -06:00
8089ee4268 Update .gitea/workflows/cd-deploy.yaml
Some checks failed
Continuous Deployment / Update Deployment (push) Failing after 1m48s
stupidly work out permissions error due to sudo not copying environment variables properly
2025-12-09 20:22:08 -06:00
5354fa85f1 minor wording change to submit buttons
Some checks failed
Continuous Deployment / Update Deployment (push) Failing after 1m28s
2025-12-09 17:02:55 -05:00
f5a0df7795 Supported public vs internal application comments, and moved some type dependencies to the shared lib 2025-12-09 17:02:39 -05:00
468fd30514 Update .gitea/workflows/cd-deploy.yaml
Some checks failed
Continuous Deployment / Update Deployment (push) Failing after 1m27s
attempt to preserve existing environment to fix node issues
2025-12-09 14:55:40 -06:00
1f52a2c4f7 Update .gitea/workflows/cd-deploy.yaml
Some checks failed
Continuous Deployment / Update Deployment (push) Failing after 1m27s
forcefully override npm path for execution
2025-12-09 14:48:19 -06:00
dccdaddd20 Update .gitea/workflows/cd-deploy.yaml
Some checks failed
Continuous Deployment / Update Deployment (push) Failing after 1m28s
another deployment attempt
2025-12-09 14:45:24 -06:00
1a80bfc543 Update .gitea/workflows/cd-deploy.yaml
Some checks failed
Continuous Deployment / Update Deployment (push) Failing after 1m33s
continue to debug workflow
2025-12-09 14:37:16 -06:00
2185ffc746 Update .gitea/workflows/cd-deploy.yaml
Some checks failed
Continuous Deployment / Update Deployment (push) Failing after 1m32s
debug workflow action
2025-12-09 14:27:42 -06:00
e22f164097 Handled retired behaviour on join page
Some checks failed
Continuous Deployment / Update Deployment (push) Failing after 1m21s
2025-12-08 22:32:07 -05:00
ae9c7c89b1 fix acknowledge spelling
Some checks failed
Continuous Deployment / Update Deployment (push) Failing after 1m23s
2025-12-08 22:06:04 -05:00
dab0a7543c added steam regex support 2025-12-08 22:03:11 -05:00
63267ac679 set up viewing of users application history
Some checks failed
Continuous Deployment / Update Deployment (push) Failing after 1m22s
2025-12-08 21:28:02 -05:00
4a65596283 tweaked get app query to support multiple applications
Some checks failed
Continuous Deployment / Update Deployment (push) Failing after 1m23s
2025-12-08 19:29:59 -05:00
9720ee6ada Updated GUILDED references and links.
Some checks failed
Continuous Deployment / Update Deployment (push) Failing after 1m22s
2025-12-08 17:55:33 -06:00
e61bd1c5a1 Enabled restarting your application from denied state
Some checks failed
Continuous Deployment / Update Deployment (push) Failing after 1m23s
2025-12-08 17:10:53 -05:00
df89d9bf67 fixed some missing awaits 2025-12-08 16:24:00 -05:00
4ab803ec72 Fixed hardcoded value in application comment poster 2025-12-08 16:15:34 -05:00
6a55846f19 improved error message readability 2025-12-08 15:21:14 -05:00
c04a2b06cb Fixed glitchtip disabled inversion on API
Some checks failed
Continuous Deployment / Update Deployment (push) Failing after 1m22s
2025-12-08 14:51:02 -05:00
8c1b132f8d Merge branch 'Calendar-Improvements' of https://gitea.iceberg-gaming.com/17th-Ranger-Battalion-ORG/milsim-site-v4 into Calendar-Improvements
Some checks failed
Continuous Deployment / Update Deployment (push) Failing after 1m17s
2025-12-05 16:47:27 -05:00
4e69b419f0 Merge branch 'main' into Calendar-Improvements
Some checks failed
Continuous Deployment / Update Deployment (push) Failing after 1m18s
2025-12-05 15:43:49 -06:00
a233b15ad4 Switched clock icon to something more readable at that size 2025-12-05 16:34:00 -05:00
94b5bfcff7 Added support for public read only calendar #53
Some checks failed
Continuous Deployment / Update Deployment (push) Failing after 1m18s
2025-12-05 16:28:42 -05:00
09d20fd18f prevented header wiggle when editable value changes
Some checks failed
Continuous Deployment / Update Deployment (push) Failing after 1m18s
2025-12-05 16:16:51 -05:00
89280dd3a7 Added (hidden) attendees summary
Some checks failed
Continuous Deployment / Update Deployment (push) Failing after 1m18s
2025-12-05 16:12:25 -05:00
575455a0fc overhauled attendance visualization to be more useful for planning
Some checks failed
Continuous Deployment / Update Deployment (push) Failing after 1m22s
2025-12-05 16:04:32 -05:00
ccb132b9b0 Improvements to event details UI to address #41
Some checks failed
Continuous Deployment / Update Deployment (push) Failing after 1m30s
2025-12-05 12:53:32 -05:00
98138f51f4 Fixed glitchtip disabled state inverted (whoops)
Some checks failed
Continuous Deployment / Update Deployment (push) Failing after 1m12s
2025-12-04 23:42:28 -05:00
e550f862bc event details area initial redesign 2025-12-04 23:41:55 -05:00
6d6789c4a6 Disabled attendance buttons if event end time is past current time to address #55
Some checks failed
Continuous Deployment / Update Deployment (push) Failing after 1m13s
2025-12-04 22:55:57 -05:00
f6c4c3e508 Added documentation page
Some checks failed
Continuous Deployment / Update Deployment (push) Failing after 1m13s
2025-12-04 22:24:12 -05:00
5a7b3ba2ab fixed application form sizing
Some checks failed
Continuous Deployment / Update Deployment (push) Failing after 1m12s
2025-12-03 19:23:50 -05:00
2de6b18135 Fixed scrolling on unauthroized page 2025-12-03 19:16:10 -05:00
aedcbd9492 Sticky'd navbar
Some checks failed
Continuous Deployment / Update Deployment (push) Failing after 1m11s
2025-12-03 19:14:47 -05:00
f985e0234c Merge pull request 'Onboarding-Reworko' (#52) from Onboarding-Reworko into main
Some checks failed
Continuous Deployment / Update Deployment (push) Failing after 1m11s
Reviewed-on: #52
2025-12-03 16:58:17 -06:00
66ad8df0c1 Merge branch 'main' into Onboarding-Reworko
Some checks failed
Continuous Deployment / Update Deployment (push) Failing after 1m10s
2025-12-03 16:58:03 -06:00
9bc3098d58 Merge pull request 'Navbar-Rework' (#50) from Navbar-Rework into main
Some checks failed
Continuous Deployment / Update Deployment (push) Failing after 1m11s
Reviewed-on: #50
2025-12-03 16:57:56 -06:00
5aef2f6b73 Merge branch 'main' into Navbar-Rework
Some checks failed
Continuous Deployment / Update Deployment (push) Failing after 1m11s
2025-12-03 16:57:26 -06:00
1faae36abc Merge pull request 'Added more strict form validation rules with user feedback' (#51) from Training-Report-Validation into main
Some checks failed
Continuous Deployment / Update Deployment (push) Failing after 1m11s
Reviewed-on: #51
2025-12-03 16:57:14 -06:00
cf98bba0cd fixed loading placeholder location 2025-12-03 17:56:59 -05:00
d31cb50d71 Added navigation to application stuff under the profile menu 2025-12-03 17:53:31 -05:00
4e6745553b added application view to final stage of onboarding 2025-12-03 17:44:41 -05:00
faf183a23d fixed scrolling issues 2025-12-03 17:01:52 -05:00
3449dcec5c minor UX refinements 2025-12-03 16:05:47 -05:00
12d538dafc vastly modified acceptance/denial display 2025-12-03 15:36:49 -05:00
b79e78c2a6 overhauled recruiter tools 2025-12-03 15:20:37 -05:00
b8f18c060e Mega recruitment pipeline overhaul 2025-12-03 13:37:03 -05:00
41cdd0b74f Added more strict form validation rules with user feedback
Some checks failed
Continuous Deployment / Update Deployment (push) Failing after 1m55s
2025-12-03 00:55:53 -05:00
c537ef9b60 fixed incorrect account status evaluation 2025-12-02 20:31:01 -05:00
26fd323f43 Guest navigation state 2025-12-02 00:09:51 -05:00
9fe18f6b1a Admin navigation permissions 2025-12-01 23:57:26 -05:00
9ac885da56 Changed LOA form label 2025-12-01 19:59:33 -05:00
35cb149202 navbar V2 hell yeah 2025-12-01 18:42:06 -05:00
b40f37c959 cerate deployment configuration
Some checks failed
Continuous Deployment / Update Deployment (push) Failing after 2m16s
add continuous deployment yaml to execute on every push to main to build and make live
2025-11-30 18:18:36 -06:00
5a31d86969 Split navbar from main app 2025-11-30 18:55:41 -05:00
90 changed files with 3536 additions and 891 deletions

View File

@@ -0,0 +1,95 @@
name: Continuous Deployment
on:
push:
tags:
- '*'
jobs:
Deploy:
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 /workspace/17th-Ranger-Battalion-ORG/milsim-site-v4/.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 pull origin main
sudo -u nginx git pull origin main
new_version=`git log -1 --format=%H`
echo "Sucessfully 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: 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

View File

@@ -0,0 +1,89 @@
name: Continuous Integration
on:
push:
branches:
- main
jobs:
Deploy:
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 /workspace/17th-Ranger-Battalion-ORG/milsim-site-v4/.git/config .git/config
chown nginx:nginx .git/config
- name: Update Application Code
run: |
cd /var/www/html/milsim-site-v4
sudo -u nginx git reset --hard
sudo -u nginx git pull origin main
- 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: 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

View File

@@ -19,7 +19,15 @@ AUTH_END_SESSION_URI=
SERVER_PORT=3000
CLIENT_URL= # This is whatever URL the client web app is served on
CLIENT_DOMAIN= #whatever.com
APPLICATION_VERSION= # Should match release tag
APPLICATION_ENVIRONMENT= # dev / prod
CONFIG_ID= # configures
# Glitchtip
GLITCHTIP_DSN=
DISABLE_GLITCHTIP= # true/false
DISABLE_GLITCHTIP= # true/false
# Bookstack
DOC_HOST= # https://bookstack.whatever.com/
DOC_TOKEN_SECRET=
DOC_TOKEN_ID=

View File

@@ -20,11 +20,14 @@ const port = process.env.SERVER_PORT;
//glitchtip setup
const sentry = require('@sentry/node');
if (!process.env.DISABLE_GLITCHTIP) {
console.log("Glitchtip disabled AAAAAA")
if (process.env.DISABLE_GLITCHTIP === "true") {
console.log("Glitchtip disabled")
} else {
let dsn = process.env.GLITCHTIP_DSN;
sentry.init({ dsn: dsn });
let release = process.env.APPLICATION_VERSION;
let environment = process.env.APPLICATION_ENVIRONMENT;
console.log(release, environment)
sentry.init({ dsn: dsn, release: release, environment: environment });
console.log("Glitchtip initialized");
}
@@ -58,6 +61,7 @@ const { roles, memberRoles } = require('./routes/roles');
const { courseRouter, eventRouter } = require('./routes/course');
const { calendarRouter } = require('./routes/calendar')
const morgan = require('morgan');
const { env } = require('process');
app.use('/application', applicationsRouter);
app.use('/ranks', ranks);

View File

@@ -2,11 +2,31 @@ const express = require('express');
const router = express.Router();
import pool from '../db';
import { approveApplication, createApplication, getApplicationByID, getApplicationComments, getApplicationList, getMemberApplication } from '../services/applicationService';
import { approveApplication, createApplication, denyApplication, getAllMemberApplications, getApplicationByID, getApplicationComments, getApplicationList, getMemberApplication } from '../services/applicationService';
import { MemberState, setUserState } from '../services/memberService';
import { getRankByName, insertMemberRank } from '../services/rankService';
import { ApplicationFull, CommentRow } from "@app/shared/types/application"
import { assignUserToStatus } from '../services/statusService';
import { Request, response, Response } from 'express';
import { getUserRoles } from '../services/rolesService';
//get CoC
router.get('/coc', async (req: Request, res: Response) => {
const output = await fetch(`${process.env.DOC_HOST}/api/pages/714`, {
headers: {
Authorization: `Token ${process.env.DOC_TOKEN_ID}:${process.env.DOC_TOKEN_SECRET}`,
}
})
if (output.ok) {
const out = await output.json();
res.status(200).json(out.html);
} else {
console.error("Failed to fetch LOA policy from bookstack");
res.sendStatus(500);
}
})
// POST /application
router.post('/', async (req, res) => {
@@ -16,13 +36,13 @@ router.post('/', async (req, res) => {
const appVersion = 1;
createApplication(memberID, appVersion, JSON.stringify(App))
setUserState(memberID, MemberState.Applicant);
await createApplication(memberID, appVersion, JSON.stringify(App))
await setUserState(memberID, MemberState.Applicant);
res.sendStatus(201);
} catch (err) {
console.error('Insert failed:', err);
res.status(500).json({ error: 'Failed to save application' });
console.error('Failed to create application: \n', err);
res.status(500).json({ error: 'Failed to create application' });
}
});
@@ -37,24 +57,57 @@ router.get('/all', async (req, res) => {
}
});
router.get('/me', async (req, res) => {
router.get('/meList', async (req, res) => {
let userID = req.user.id;
console.log("application/me")
try {
let application = await getAllMemberApplications(userID);
let app = getMemberApplication(userID);
console.log(app);
return res.status(200).json(application);
} catch (error) {
console.error('Failed to load applications: \n', error);
return res.status(500).json(error);
}
})
router.get('/me', async (req, res) => {
let userID = req.user.id;
try {
let application = await getMemberApplication(userID);
if (application === undefined)
res.sendStatus(204);
const comments: CommentRow[] = await getApplicationComments(application.id);
const output: ApplicationFull = {
application,
comments,
}
return res.status(200).json(output);
} catch (error) {
console.error('Failed to load application:', error);
return res.status(500).json(error);
}
})
// GET /application/:id
router.get('/:id', async (req, res) => {
let appID = req.params.id;
console.log("HELLO")
router.get('/me/:id', async (req: Request, res: Response) => {
let appID = Number(req.params.id);
let member = req.user.id;
try {
const application = await getApplicationByID(appID);
if (application === undefined)
return res.sendStatus(204);
console.log(application.member_id, member)
if (application.member_id != member) {
return res.sendStatus(403);
}
const comments: CommentRow[] = await getApplicationComments(appID);
const output: ApplicationFull = {
@@ -69,30 +122,64 @@ router.get('/:id', async (req, res) => {
}
});
// GET /application/:id
router.get('/:id', async (req: Request, res: Response) => {
let appID = Number(req.params.id);
let asAdmin = !!req.query.admin || false;
let user = req.user.id;
//TODO: Replace this with bigger authorization system eventually
if (asAdmin) {
let allowed = (await getUserRoles(user)).some((role) =>
role.name.toLowerCase() === 'dev' ||
role.name.toLowerCase() === 'recruiter' ||
role.name.toLowerCase() === 'administrator')
console.log(allowed)
if (!allowed) {
return res.sendStatus(403)
}
}
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 (err) {
console.error('Query failed:', err);
return res.status(500).json({ error: 'Failed to load application' });
}
});
// POST /application/approve/:id
router.post('/approve/:id', async (req, res) => {
const appID = req.params.id;
router.post('/approve/:id', async (req: Request, res: Response) => {
const appID = Number(req.params.id);
const approved_by = req.user.id;
try {
const app = await getApplicationByID(appID);
const result = await approveApplication(appID);
console.log("START");
console.log(app, result);
//guard against failures
if (result.affectedRows != 1) {
throw new Error("Something went wrong approving the application");
}
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);
await pool.query('CALL sp_accept_new_recruit_validation(?, ?, ?, ?)', [Number(process.env.CONFIG_ID), app.member_id, approved_by, approved_by])
// 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);
@@ -104,26 +191,11 @@ router.post('/approve/:id', async (req, res) => {
router.post('/deny/:id', async (req, res) => {
const appID = req.params.id;
const sql = `
UPDATE applications
SET denied_at = NOW()
WHERE id = ?
AND approved_at IS NULL
AND denied_at IS NULL
`;
try {
const result = await pool.execute(sql, appID);
console.log(result);
if (result.affectedRows === 0) {
res.status(400).json('Something went wrong denying the application');
}
if (result.affectedRows == 1) {
res.sendStatus(200);
}
const app = await getApplicationByID(appID);
await denyApplication(appID);
await setUserState(app.member_id, MemberState.Denied);
res.sendStatus(200);
} catch (err) {
console.error('Approve failed:', err);
res.status(500).json({ error: 'Failed to deny application' });
@@ -131,10 +203,12 @@ router.post('/deny/:id', async (req, res) => {
});
// POST /application/:id/comment
router.post('/:id/comment', async (req, res) => {
router.post('/:id/comment', async (req: Request, res: Response) => {
const appID = req.params.id;
const data = req.body.message;
const user = 1;
const user = req.user;
console.log(user)
const sql = `INSERT INTO application_comments(
application_id,
@@ -146,7 +220,7 @@ VALUES(?, ?, ?);`
try {
const conn = await pool.getConnection();
const result = await conn.query(sql, [appID, user, data])
const result = await conn.query(sql, [appID, user.id, data])
console.log(result)
if (result.affectedRows !== 1) {
conn.release();
@@ -171,4 +245,61 @@ VALUES(?, ?, ?);`
}
});
// POST /application/:id/comment
router.post('/:id/adminComment', async (req: Request, res: Response) => {
const appID = req.params.id;
const data = req.body.message;
const user = req.user;
console.log(user)
const sql = `INSERT INTO application_comments(
application_id,
poster_id,
post_content,
admin_only
)
VALUES(?, ?, ?, 1);`
try {
const conn = await pool.getConnection();
const result = await conn.query(sql, [appID, user.id, data])
console.log(result)
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])
res.status(201).json(comment[0]);
} catch (err) {
console.error('Comment failed:', err);
res.status(500).json({ error: 'Could not post comment' });
}
});
router.post('/restart', async (req: Request, res: Response) => {
const user = req.user.id;
try {
await setUserState(user, MemberState.Guest);
res.sendStatus(200);
} catch (error) {
console.error('Comment failed:', error);
res.status(500).json({ error: 'Could not rester application' });
}
})
module.exports = router;

View File

@@ -21,12 +21,13 @@ passport.use(new OpenIDConnectStrategy({
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('--- 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);
console.log('profile:', profile);
console.log('id_token claims:', JSON.stringify(jwtClaims, null, 2));
console.log('preferred_username:', jwtClaims?.preferred_username);
const con = await pool.getConnection();
try {

View File

@@ -1,56 +0,0 @@
const express = require('express');
const router = express.Router();
import pool from '../db';
//post a new LOA
router.post("/", async (req, res) => {
const { member_id, filed_date, start_date, end_date, reason } = req.body;
if (!member_id || !filed_date || !start_date || !end_date) {
return res.status(400).json({ error: "Missing required fields" });
}
try {
const result = await pool.query(
`INSERT INTO leave_of_absences
(member_id, filed_date, start_date, end_date, reason)
VALUES (?, ?, ?, ?, ?)`,
[member_id, filed_date, start_date, end_date, reason]
);
res.sendStatus(201);
} catch (error) {
console.error(error);
res.status(500).send('Something went wrong', error);
}
});
//get my current LOA
router.get("/me", async (req, res) => {
//TODO: implement current user getter
const user = 89;
try {
const result = await pool.query("SELECT * FROM leave_of_absences WHERE member_id = ?", [user])
res.status(200).json(result)
} catch (error) {
console.error(error);
res.status(500).send(error);
}
})
router.get('/all', async (req, res) => {
try {
const result = await pool.query(
`SELECT loa.*, members.name
FROM leave_of_absences AS loa
INNER JOIN members ON loa.member_id = members.id;
`);
res.status(200).json(result)
} catch (error) {
console.error(error);
res.status(500).send(error);
}
})
module.exports = router;

148
api/src/routes/loa.ts Normal file
View File

@@ -0,0 +1,148 @@
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/loaService';
import { LOARequest } from '@app/shared/types/loa';
//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 {
await createNewLOA(LOARequest);
res.sendStatus(201);
} catch (error) {
console.error(error);
res.status(500).send(error);
}
});
//admin posts LOA
router.post("/admin", async (req: Request, res: Response) => {
let LOARequest = req.body as LOARequest;
LOARequest.created_by = req.user.id;
LOARequest.filed_date = new Date();
console.log(LOARequest);
try {
await createNewLOA(LOARequest);
res.sendStatus(201);
} catch (error) {
console.error(error);
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) {
console.error(error);
res.status(500).send(error);
}
})
//get my LOA history
router.get("/history", async (req: Request, res: Response) => {
const user = req.user.id;
try {
const result = await getUserLOA(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 getAllLOA();
res.status(200).json(result)
} catch (error) {
console.error(error);
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) {
res.status(500).json(error);
console.error(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);
res.sendStatus(200);
} catch (error) {
console.error(error);
res.status(500).json(error);
}
})
//TODO: enforce admin only
router.post('/adminCancel/:id', async (req: Request, res: Response) => {
let closer = req.user.id;
try {
await closeLOA(Number(req.params.id), closer);
res.sendStatus(200);
} catch (error) {
console.error(error);
res.status(500).json(error);
}
})
// TODO: Enforce admin only
router.post('/extend/:id', 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);
res.sendStatus(200);
} catch (error) {
console.error(error)
res.status(500).json(error);
}
})
router.get('/policy', async (req: Request, res: Response) => {
const output = await fetch(`${process.env.DOC_HOST}/api/pages/42`, {
headers: {
Authorization: `Token ${process.env.DOC_TOKEN_ID}:${process.env.DOC_TOKEN_SECRET}`,
}
})
if (output.ok) {
const out = await output.json();
res.status(200).json(out.html);
} else {
console.error("Failed to fetch LOA policy from bookstack");
res.sendStatus(500);
}
})
module.exports = router;

View File

@@ -2,6 +2,7 @@ const express = require('express');
const router = express.Router();
import pool from '../db';
import { getUserActiveLOA } from '../services/loaService';
import { getUserData } from '../services/memberService';
import { getUserRoles } from '../services/rolesService';
@@ -26,7 +27,7 @@ router.get('/', async (req, res) => {
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;`);
FROM view_member_rank_unit_status_latest v;`);
return res.status(200).json(result);
} catch (err) {
console.error('Error fetching users:', err);
@@ -40,12 +41,13 @@ router.get('/me', async (req, res) => {
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 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 LOAData = await getUserActiveLOA(req.user.id);
const roleData = await getUserRoles(req.user.id);
@@ -61,7 +63,7 @@ router.get('/me', async (req, res) => {
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]);
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' });
}

View File

@@ -49,7 +49,7 @@ r.get('/', async (req, res) => {
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
JOIN view_member_rank_unit_status_latest v ON mr.member_id = v.member_id
`);

View File

@@ -1,5 +1,6 @@
import { ApplicationListRow, ApplicationRow, CommentRow } from "@app/shared/types/application";
import pool from "../db";
import { error } from "console";
export async function createApplication(memberID: number, appVersion: number, app: string) {
const sql = `INSERT INTO applications (member_id, app_version, app_data) VALUES (?, ?, ?);`;
@@ -12,12 +13,13 @@ export async function getMemberApplication(memberID: number): Promise<Applicatio
member.name AS member_name
FROM applications AS app
INNER JOIN members AS member ON member.id = app.member_id
WHERE 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.*,
@@ -44,7 +46,20 @@ export async function getApplicationList(): Promise<ApplicationListRow[]> {
return rows;
}
export async function approveApplication(id) {
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) {
const sql = `
UPDATE applications
SET approved_at = NOW()
@@ -57,15 +72,38 @@ export async function approveApplication(id) {
return result;
}
export async function getApplicationComments(appID: number): Promise<CommentRow[]> {
export async function denyApplication(id: number) {
const sql = `
UPDATE applications
SET denied_at = NOW()
WHERE id = ?
AND approved_at IS NULL
AND denied_at IS NULL
`;
const result = await pool.execute(sql, 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
WHERE app.application_id = ?;`,
${whereClause}`,
[appID]);
}

View File

@@ -123,15 +123,9 @@ export async function setAttendanceStatus(memberID: number, eventID: number, sta
}
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 = ?
`;
return await pool.query(sql, [eventID]);
const sql = "CALL `sp_GetCalendarEventSignups`(?)"
const res = await pool.query(sql, [eventID]);
console.log(res[0]);
return res[0];
}

View File

@@ -0,0 +1,98 @@
import { toDateTime } from "@app/shared/utils/time";
import pool from "../db";
import { LOARequest, LOAType } from '@app/shared/types/loa'
export async function getLoaTypes(): Promise<LOAType[]> {
return await pool.query('SELECT * FROM leave_of_absences_types;');
}
export async function getAllLOA(page = 1, pageSize = 20): Promise<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 res: LOARequest[] = await pool.query(sql, [pageSize, offset]) as LOARequest[];
return res;
}
export async function getUserLOA(userId: number): Promise<LOARequest[]> {
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
`, [userId])
return result;
}
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() BETWEEN start_date AND end_date;`
const LOAData = await pool.query(sql, [userId]);
return LOAData;
}
export async function createNewLOA(data: LOARequest) {
const sql = `INSERT INTO leave_of_absences
(member_id, filed_date, start_date, end_date, type_id, reason)
VALUES (?, ?, ?, ?, ?, ?)`;
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;
}
export async function closeLOA(id: number, closer: number) {
const sql = `UPDATE leave_of_absences
SET closed = 1,
closed_by = ?
WHERE leave_of_absences.id = ?`;
let out = await pool.query(sql, [closer, id]);
console.log(out);
return out;
}
export async function getLOAbyID(id: number): Promise<LOARequest> {
let res = await pool.query(`SELECT * FROM leave_of_absences WHERE id = ?`, [id]);
console.log(res);
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];
}

View File

@@ -21,8 +21,8 @@ export async function insertMemberRank(member_id: number, rank_id: number): Prom
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());`;
? `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]

View File

@@ -1,4 +1,5 @@
import pool from '../db';
import { Role } from '@app/shared/types/roles'
export async function assignUserGroup(userID: number, roleID: number) {
@@ -16,7 +17,7 @@ export async function createGroup(name: string, color: string, description: stri
return { id: result.insertId, name, color, description };
}
export async function getUserRoles(userID: number) {
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

View File

@@ -1,6 +1,6 @@
import pool from "../db"
export async function assignUserToStatus(userID: number, statusID: number) {
const sql = `INSERT INTO members_statuses (member_id, status_id, event_date) VALUES (?, ?, NOW())`
const sql = `INSERT INTO members_statuses (member_id, status_id, start_date) VALUES (?, ?, NOW())`
await pool.execute(sql, [userID, statusID]);
}

View File

@@ -5,6 +5,7 @@ module.exports = {
script: 'built/api/src/index.js',
watch: ['.env', 'built'],
ignore_watch: ['.gitignore', '\.json', 'src', '\.db', 'node_modules'],
appendEnvToName: true,
watch_options: {
usePolling: true,
interval: 10000

View File

@@ -0,0 +1,51 @@
import * as z from "zod";
import { LOAType } from "../types/loa";
export const loaTypeSchema = z.object({
id: z.number(),
name: z.string(),
max_length_days: z.number(),
});
export const loaSchema = z.object({
member_id: z.number(),
start_date: z.date(),
end_date: z.date(),
type: loaTypeSchema,
reason: z.string(),
})
.superRefine((data, ctx) => {
const { start_date, end_date, type } = data;
const today = new Date();
today.setHours(0, 0, 0, 0);
if (start_date < today) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: ["start_date"],
message: "Start date cannot be in the past.",
});
}
// 1. end > start
if (end_date <= start_date) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: ["end_date"],
message: "End date must be after start date.",
});
}
// 2. calculate max
const maxEnd = new Date(start_date);
maxEnd.setDate(maxEnd.getDate() + type.max_length_days);
if (end_date > maxEnd) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: ["end_date"],
message: `This LOA type allows a maximum of ${type.max_length_days} days.`,
});
}
});

View File

@@ -1,11 +1,11 @@
import { z } from "zod";
export const courseEventAttendeeSchema = z.object({
attendee_id: z.number({invalid_type_error: "Must select a member"}).int().positive(),
attendee_id: z.number({ invalid_type_error: "Must select a member" }).int().positive(),
passed_bookwork: z.boolean(),
passed_qual: z.boolean(),
remarks: z.string(),
attendee_role_id: z.number({invalid_type_error: "Must select a role"}).int().positive()
attendee_role_id: z.number({ invalid_type_error: "Must select a role" }).int().positive()
})
export const trainingReportSchema = z.object({
@@ -19,5 +19,42 @@ export const trainingReportSchema = z.object({
),
remarks: z.string().nullable().optional(),
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.",
});
}
})
})

View File

@@ -40,6 +40,7 @@ export interface CommentRow {
post_time: string;
last_modified: string | null;
poster_name: string;
admin_only: boolean;
}
export interface ApplicationFull {

View File

@@ -26,6 +26,7 @@ export interface CalendarSignup {
eventID: number;
status: CalendarAttendance;
member_name?: string;
member_unit?: string;
}
export interface CalendarEventShort {

24
shared/types/loa.ts Normal file
View File

@@ -0,0 +1,24 @@
export interface LOARequest {
id?: number;
member_id?: number;
filed_date?: Date; // ISO 8601 string
start_date: Date; // ISO 8601 string
end_date: Date; // ISO 8601 string
extended_till?: Date;
type_id?: number;
reason?: string;
expired?: boolean;
closed?: boolean;
closed_by?: number;
created_by?: number;
name?: string; //member name
type_name?: string;
};
export interface LOAType {
id: number;
name: string;
max_length_days: number;
extendable: boolean;
}

6
shared/types/roles.ts Normal file
View File

@@ -0,0 +1,6 @@
export interface Role {
id: number;
name: string;
color?: string;
description?: string;
}

View File

@@ -1,5 +1,8 @@
export function toDateTime(date: Date): string {
console.log(date);
if (typeof date === 'string') {
date = new Date(date);
}
// This produces a CST-local time because server runs in CST
const year = date.getFullYear();
const month = (date.getMonth() + 1).toString().padStart(2, "0");

View File

@@ -1,10 +1,10 @@
# SITE SETTINGS
VITE_APIHOST=
VITE_DOCHOST= # https://bookstack.whatever.com/api
VITE_ENVIRONMENT= # dev / prod
VITE_APPLICATION_VERSION= # Should match release tag
# Glitchtip
VITE_GLITCHTIP_DSN=
VITE_DISABLE_GLITCHTIP= # true/false
# Matomo
VITE_DISABLE_MATOMO= # true/false
VITE_DISABLE_GLITCHTIP= # true/false

35
ui/package-lock.json generated
View File

@@ -8,7 +8,6 @@
"name": "milsimsitev4",
"version": "0.0.0",
"dependencies": {
"@certible/use-matomo": "^1.1.0",
"@fullcalendar/core": "^6.1.19",
"@fullcalendar/daygrid": "^6.1.19",
"@fullcalendar/interaction": "^6.1.19",
@@ -23,7 +22,7 @@
"clsx": "^2.1.1",
"lucide-vue-next": "^0.539.0",
"pinia": "^3.0.3",
"reka-ui": "^2.6.0",
"reka-ui": "^2.6.1",
"tailwind-merge": "^3.3.1",
"tailwindcss": "^4.1.11",
"tw-animate-css": "^1.3.6",
@@ -511,12 +510,6 @@
"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": {
"version": "0.25.9",
"resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.25.9.tgz",
@@ -3340,9 +3333,9 @@
}
},
"node_modules/reka-ui": {
"version": "2.6.0",
"resolved": "https://registry.npmjs.org/reka-ui/-/reka-ui-2.6.0.tgz",
"integrity": "sha512-NrGMKrABD97l890mFS3TNUzB0BLUfbL3hh0NjcJRIUSUljb288bx3Mzo31nOyUcdiiW0HqFGXJwyCBh9cWgb0w==",
"version": "2.6.1",
"resolved": "https://registry.npmjs.org/reka-ui/-/reka-ui-2.6.1.tgz",
"integrity": "sha512-XK7cJDQoNuGXfCNzBBo/81Yg/OgjPwvbabnlzXG2VsdSgNsT6iIkuPBPr+C0Shs+3bb0x0lbPvgQAhMSCKm5Ww==",
"license": "MIT",
"dependencies": {
"@floating-ui/dom": "^1.6.13",
@@ -3601,13 +3594,13 @@
}
},
"node_modules/tinyglobby": {
"version": "0.2.15",
"resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.15.tgz",
"integrity": "sha512-j2Zq4NyQYG5XMST4cbs02Ak8iJUdxRM0XI5QyxXuZOzKOINmWurp3smXu3y5wDcJrptwpSjgXHzIQxR0omXljQ==",
"version": "0.2.14",
"resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.14.tgz",
"integrity": "sha512-tX5e7OM1HnYr2+a2C/4V0htOcSQcoSTH9KgJnVvNm5zm/cyEWKJ7j7YutsH9CxMdtOkkLFy2AHrMci9IM8IPZQ==",
"license": "MIT",
"dependencies": {
"fdir": "^6.5.0",
"picomatch": "^4.0.3"
"fdir": "^6.4.4",
"picomatch": "^4.0.2"
},
"engines": {
"node": ">=12.0.0"
@@ -3735,17 +3728,17 @@
}
},
"node_modules/vite": {
"version": "7.2.4",
"resolved": "https://registry.npmjs.org/vite/-/vite-7.2.4.tgz",
"integrity": "sha512-NL8jTlbo0Tn4dUEXEsUg8KeyG/Lkmc4Fnzb8JXN/Ykm9G4HNImjtABMJgkQoVjOBN/j2WAwDTRytdqJbZsah7w==",
"version": "7.1.2",
"resolved": "https://registry.npmjs.org/vite/-/vite-7.1.2.tgz",
"integrity": "sha512-J0SQBPlQiEXAF7tajiH+rUooJPo0l8KQgyg4/aMunNtrOa7bwuZJsJbDWzeljqQpgftxuq5yNJxQ91O9ts29UQ==",
"license": "MIT",
"dependencies": {
"esbuild": "^0.25.0",
"fdir": "^6.5.0",
"fdir": "^6.4.6",
"picomatch": "^4.0.3",
"postcss": "^8.5.6",
"rollup": "^4.43.0",
"tinyglobby": "^0.2.15"
"tinyglobby": "^0.2.14"
},
"bin": {
"vite": "bin/vite.js"

View File

@@ -12,7 +12,6 @@
"preview": "vite preview"
},
"dependencies": {
"@certible/use-matomo": "^1.1.0",
"@fullcalendar/core": "^6.1.19",
"@fullcalendar/daygrid": "^6.1.19",
"@fullcalendar/interaction": "^6.1.19",
@@ -27,7 +26,7 @@
"clsx": "^2.1.1",
"lucide-vue-next": "^0.539.0",
"pinia": "^3.0.3",
"reka-ui": "^2.6.0",
"reka-ui": "^2.6.1",
"tailwind-merge": "^3.3.1",
"tailwindcss": "^4.1.11",
"tw-animate-css": "^1.3.6",

BIN
ui/public/17RBN_Logo.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 42 KiB

View File

@@ -1,41 +1,14 @@
<script setup>
import { RouterLink, RouterView } from 'vue-router';
import Separator from './components/ui/separator/Separator.vue';
import { RouterView } from 'vue-router';
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 Alert from './components/ui/alert/Alert.vue';
import AlertDescription from './components/ui/alert/AlertDescription.vue';
import Navbar from './components/Navigation/Navbar.vue';
import { cancelLOA } from './api/loa';
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) {
if (!dateStr) return "";
return new Date(dateStr).toLocaleDateString("en-US", {
@@ -49,90 +22,24 @@ const environment = import.meta.env.VITE_ENVIRONMENT;
</script>
<template>
<div>
<div class="flex items-center justify-between px-10">
<div></div>
<div class="h-15 flex items-center justify-center gap-20">
<RouterLink to="/">
<Button variant="link">Home</Button>
</RouterLink>
<RouterLink to="/calendar">
<Button variant="link">Calendar</Button>
</RouterLink>
<RouterLink to="/members">
<Button variant="link">Members</Button>
</RouterLink>
<Popover>
<PopoverTrigger as-child>
<Button variant="link">Forms</Button>
</PopoverTrigger>
<PopoverContent class="flex flex-col gap-4 items-center w-min">
<RouterLink to="/transfer">
<Button variant="link">Transfer Request</Button>
</RouterLink>
<RouterLink to="/trainingReport">
<Button variant="link">Training Report</Button>
</RouterLink>
</PopoverContent>
</Popover>
<Popover>
<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>
</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 class="flex flex-col min-h-screen">
<div class="sticky top-0 bg-background z-50">
<Navbar class="flex"></Navbar>
<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?.LOAData?.[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?.LOAData?.[0].end_date) }}</strong></p>
<Button variant="secondary" @click="async () => { await cancelLOA(userStore.user?.LOAData?.[0].id); userStore.loadUser(); }">End
LOA</Button>
</AlertDescription>
</Alert>
</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>
<RouterView class="flex-1 min-h-0"></RouterView>
</div>
</template>

View File

@@ -1,80 +1,11 @@
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[];
}
import { ApplicationFull } from "@shared/types/application";
export enum ApplicationStatus {
Pending = "Pending",
Accepted = "Accepted",
Denied = "Denied",
}
// @ts-ignore
const addr = import.meta.env.VITE_APIHOST;
export async function loadApplication(id: number | string): Promise<ApplicationFull | null> {
const res = await fetch(`${addr}/application/${id}`)
export async function loadApplication(id: number | string, asAdmin: boolean = false): Promise<ApplicationFull | null> {
const res = await fetch(`${addr}/application/${id}?admin=${asAdmin}`, { credentials: 'include' })
if (res.status === 204) return null
if (!res.ok) throw new Error('Failed to load application')
const json = await res.json()
@@ -104,6 +35,22 @@ export async function postChatMessage(message: any, post_id: number) {
const response = await fetch(`${addr}/application/${post_id}/comment`, {
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' },
body: JSON.stringify(out),
})
@@ -121,8 +68,28 @@ 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) {
const res = await fetch(`${addr}/application/approve/${id}`, { method: 'POST' })
const res = await fetch(`${addr}/application/approve/${id}`, { method: 'POST', credentials: 'include' })
if (!res.ok) {
console.error("Something went wrong approving the application")
@@ -130,9 +97,36 @@ export async function approveApplication(id: Number) {
}
export async function denyApplication(id: Number) {
const res = await fetch(`${addr}/application/deny/${id}`, { method: 'POST' })
const res = await fetch(`${addr}/application/deny/${id}`, { method: 'POST', credentials: 'include' })
if (!res.ok) {
console.error("Something went wrong denying the application")
}
}
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;
}
}

View File

@@ -1,12 +1,4 @@
export type LOARequest = {
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;
};
import { LOARequest, LOAType } from '@shared/types/loa'
// @ts-ignore
const addr = import.meta.env.VITE_APIHOST;
@@ -17,6 +9,24 @@ export async function submitLOA(request: LOARequest): Promise<{ id?: number; err
"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 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) {
@@ -26,6 +36,7 @@ export async function submitLOA(request: LOARequest): Promise<{ id?: number; err
}
}
export async function getMyLOA(): Promise<LOARequest | null> {
const res = await fetch(`${addr}/loa/me`, {
method: "GET",
@@ -60,3 +71,84 @@ export function getAllLOAs(): Promise<LOARequest[]> {
}
});
}
export function getMyLOAs(): Promise<LOARequest[]> {
return fetch(`${addr}/loa/history`, {
method: "GET",
credentials: 'include',
headers: {
"Content-Type": "application/json",
},
}).then((res) => {
if (res.ok) {
return res.json();
} else {
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");
}
}

View File

@@ -3,6 +3,8 @@ export type Member = {
member_name: string;
rank: string | null;
rank_date: string | null;
unit: string | null;
unit_date: string | null;
status: string | null;
status_date: string | null;
on_loa: boolean | null;

View File

@@ -16,8 +16,8 @@
--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);
--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);
@@ -52,7 +52,7 @@
--shadow-2xl: 0px 4px 8px -1px hsl(0 0% 0% / 0.35);
}
.dark {
/* .dark {
--background: oklch(0.2046 0 0);
--foreground: oklch(0.9219 0 0);
--card: oklch(23.075% 0.00003 271.152);
@@ -99,7 +99,7 @@
--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 {
@@ -165,4 +165,112 @@
body {
@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;
}

View File

@@ -0,0 +1,195 @@
<script setup lang="ts">
import { RouterLink } from 'vue-router';
import Separator from '../ui/separator/Separator.vue';
import { Popover, PopoverContent, PopoverTrigger } from '../ui/popover';
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from '../ui/dropdown-menu';
import { useUserStore } from '@/stores/user';
import Button from '../ui/button/Button.vue';
import NavigationMenu from '../ui/navigation-menu/NavigationMenu.vue';
import NavigationMenuList from '../ui/navigation-menu/NavigationMenuList.vue';
import NavigationMenuItem from '../ui/navigation-menu/NavigationMenuItem.vue';
import NavigationMenuLink from '../ui/navigation-menu/NavigationMenuLink.vue';
import NavigationMenuTrigger from '../ui/navigation-menu/NavigationMenuTrigger.vue';
import NavigationMenuContent from '../ui/navigation-menu/NavigationMenuContent.vue';
import { navigationMenuTriggerStyle } from '../ui/navigation-menu/'
import { useAuth } from '@/composables/useAuth';
import { ArrowUpRight, CircleArrowOutUpRight } from 'lucide-vue-next';
const userStore = useUserStore();
const auth = useAuth();
//@ts-ignore
const APIHOST = import.meta.env.VITE_APIHOST;
//@ts-ignore
const DOCHOST = import.meta.env.VITE_DOCHOST;
async function logout() {
userStore.user = null;
window.location.href = APIHOST + "/logout";
}
function blurAfter() {
requestAnimationFrame(() => {
(document.activeElement as HTMLElement)?.blur();
});
}
</script>
<template>
<div class="w-full border-b">
<div class="max-w-screen-3xl w-full mx-auto flex items-center justify-between pr-10 pl-7">
<!-- left side -->
<div class="flex items-center gap-7">
<RouterLink to="/">
<img src="/17RBN_Logo.png" class="w-10 h-10 object-contain"></img>
</RouterLink>
<!-- Member navigation -->
<div v-if="auth.accountStatus.value == 'member'" class="h-15 flex items-center justify-center">
<NavigationMenu>
<NavigationMenuList class="gap-3">
<!-- Calendar -->
<NavigationMenuItem>
<NavigationMenuLink as-child :class="navigationMenuTriggerStyle()">
<RouterLink to="/calendar" @click="blurAfter">Calendar</RouterLink>
</NavigationMenuLink>
</NavigationMenuItem>
<!-- Docs -->
<NavigationMenuItem>
<NavigationMenuLink as-child :class="navigationMenuTriggerStyle()">
<a href="https://docs.iceberg-gaming.com" target="_blank">
<span class="flex items-center gap-1">
Documents
<ArrowUpRight class="h-4 w-4" />
</span>
</a>
</NavigationMenuLink>
</NavigationMenuItem>
<!-- Forms (Dropdown) -->
<NavigationMenuItem class="bg-none !focus:bg-none !active:bg-none">
<NavigationMenuTrigger>Forms</NavigationMenuTrigger>
<NavigationMenuContent
class="grid gap-1 p-2 text-left [&_a]:w-full [&_a]:block [&_a]:whitespace-nowrap *:bg-transparent">
<NavigationMenuLink as-child :class="navigationMenuTriggerStyle()">
<RouterLink to="/loa" @click="blurAfter">
Leave of Absence
</RouterLink>
</NavigationMenuLink>
<NavigationMenuLink as-child :class="navigationMenuTriggerStyle()">
<RouterLink to="/transfer" @click="blurAfter">
Transfer Request
</RouterLink>
</NavigationMenuLink>
<NavigationMenuLink as-child :class="navigationMenuTriggerStyle()">
<RouterLink to="/trainingReport" @click="blurAfter">
Training Report
</RouterLink>
</NavigationMenuLink>
</NavigationMenuContent>
</NavigationMenuItem>
<!-- Administration (Dropdown) -->
<NavigationMenuItem
v-if="auth.hasAnyRole(['17th Administrator', '17th HQ', '17th Command', 'Recruiter'])">
<NavigationMenuTrigger>Administration</NavigationMenuTrigger>
<NavigationMenuContent
class="grid gap-1 p-2 text-left [&_a]:w-full [&_a]:block [&_a]:whitespace-nowrap *:bg-transparent">
<NavigationMenuLink
v-if="auth.hasAnyRole(['17th Administrator', '17th HQ', '17th Command'])"
as-child :class="navigationMenuTriggerStyle()">
<RouterLink to="/administration/rankChange" @click="blurAfter">
Promotions
</RouterLink>
</NavigationMenuLink>
<NavigationMenuLink
v-if="auth.hasAnyRole(['17th Administrator', '17th HQ', '17th Command'])"
as-child :class="navigationMenuTriggerStyle()">
<RouterLink to="/administration/loa" @click="blurAfter">
Leave of Absence
</RouterLink>
</NavigationMenuLink>
<NavigationMenuLink
v-if="auth.hasAnyRole(['17th Administrator', '17th HQ', '17th Command'])"
as-child :class="navigationMenuTriggerStyle()">
<RouterLink to="/administration/transfer" @click="blurAfter">
Transfer Requests
</RouterLink>
</NavigationMenuLink>
<NavigationMenuLink v-if="auth.hasRole('Recruiter')" as-child
:class="navigationMenuTriggerStyle()">
<RouterLink to="/administration/applications" @click="blurAfter">
Recruitment
</RouterLink>
</NavigationMenuLink>
<NavigationMenuLink v-if="auth.hasRole('17th Administrator')" as-child
:class="navigationMenuTriggerStyle()">
<RouterLink to="/administration/roles" @click="blurAfter">
Role Management
</RouterLink>
</NavigationMenuLink>
</NavigationMenuContent>
</NavigationMenuItem>
<NavigationMenuItem as-child :class="navigationMenuTriggerStyle()">
<RouterLink to="/members" @click="blurAfter">
Members (debug)
</RouterLink>
</NavigationMenuItem>
</NavigationMenuList>
</NavigationMenu>
</div>
<!-- Guest navigation -->
<div v-else class="h-15 flex items-center justify-center">
<NavigationMenu>
<NavigationMenuList>
<NavigationMenuItem>
<NavigationMenuLink as-child :class="navigationMenuTriggerStyle()">
<RouterLink to="/join" @click="blurAfter">Join</RouterLink>
</NavigationMenuLink>
</NavigationMenuItem>
<!-- Calendar -->
<NavigationMenuItem>
<NavigationMenuLink as-child :class="navigationMenuTriggerStyle()">
<RouterLink to="/calendar" @click="blurAfter">Calendar</RouterLink>
</NavigationMenuLink>
</NavigationMenuItem>
</NavigationMenuList>
</NavigationMenu>
</div>
</div>
<!-- right side -->
<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 @click="$router.push('/join')">My Application</DropdownMenuItem>
<DropdownMenuItem @click="$router.push('/applications')">Application History</DropdownMenuItem>
<DropdownMenuItem :variant="'destructive'" @click="logout()">Logout</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
<a v-else :href="APIHOST + '/login'">Login</a>
</div>
</div>
<!-- <Separator></Separator> -->
</div>
</template>

View File

@@ -11,13 +11,18 @@ import {
import Textarea from '@/components/ui/textarea/Textarea.vue'
import { toTypedSchema } from '@vee-validate/zod'
import * as z from 'zod'
import { useAuth } from '@/composables/useAuth'
import { CommentRow } from '@shared/types/application'
import { Dot } from 'lucide-vue-next'
import { ref } from 'vue'
const props = defineProps<{
messages: Array<Record<string, any>>
messages: CommentRow[]
}>()
const emit = defineEmits<{
(e: 'post', text: string): void
(e: 'postInternal', text: string): void
}>()
const commentSchema = toTypedSchema(
@@ -26,9 +31,14 @@ const commentSchema = toTypedSchema(
})
)
const submitMode = ref("public");
// vee-validate passes (values, actions) to @submit
function onSubmit(values: { text: string }, { resetForm }: { resetForm: () => void }) {
emit('post', values.text.trim())
if (submitMode.value === "internal")
emit('postInternal', values.text.trim())
else
emit('post', values.text.trim())
resetForm()
}
</script>
@@ -38,7 +48,7 @@ function onSubmit(values: { text: string }, { resetForm }: { resetForm: () => vo
<Form :validation-schema="commentSchema" @submit="onSubmit">
<FormField name="text" v-slot="{ componentField }">
<FormItem>
<FormLabel class="sr-only">Comment</FormLabel>
<FormLabel>Comment</FormLabel>
<FormControl>
<Textarea v-bind="componentField" rows="3" placeholder="Write a comment…"
class="bg-neutral-800 resize-none w-full" />
@@ -48,25 +58,31 @@ function onSubmit(values: { text: string }, { resetForm }: { resetForm: () => vo
</FormField>
<!-- Button below, right-aligned -->
<div class="mt-2 flex justify-end">
<Button type="submit">Post</Button>
<div class="mt-2 flex justify-end gap-2">
<Button type="submit" @click="submitMode = 'internal'" variant="outline">Post (Internal)</Button>
<Button type="submit" @click="submitMode = 'public'">Post (Public)</Button>
</div>
</Form>
<!-- Existing posts -->
<div class="space-y-3">
<div v-for="(message, i) in props.messages" :key="message.id ?? i"
class="rounded-md border border-neutral-800 p-3 space-y-5">
<div v-for="(message, i) in props.messages" :key="message.comment_id ?? i" class="rounded-md border p-3 space-y-5"
:class="message.admin_only ? 'border-amber-300/70' : 'border-neutral-800'">
<!-- Comment header -->
<div class="flex justify-between">
<p>{{ message.poster_name }}</p>
<div class="flex">
<p>{{ message.poster_name }}</p>
<p v-if="message.admin_only" class="flex">
<Dot /><span class="text-amber-300">Internal</span>
</p>
</div>
<p class="text-muted-foreground">{{ new Date(message.post_time).toLocaleString("EN-us", {
year: "numeric",
month: "long",
day: "numeric",
hour: "2-digit",
minute: "2-digit"
}) }}</p>
}) }}</p>
</div>
<p>{{ message.post_content }}</p>
</div>

View File

@@ -13,26 +13,38 @@ import Input from '@/components/ui/input/Input.vue';
import Textarea from '@/components/ui/textarea/Textarea.vue';
import { toTypedSchema } from '@vee-validate/zod';
import { Form } from 'vee-validate';
import { onMounted, ref } from 'vue';
import { nextTick, onMounted, ref, watch } from 'vue';
import * as z from 'zod';
import DateInput from '../form/DateInput.vue';
import { ApplicationData } from '@/api/application';
import { ApplicationData } from '@shared/types/application';
import Dialog from '../ui/dialog/Dialog.vue';
import DialogTrigger from '../ui/dialog/DialogTrigger.vue';
import DialogContent from '../ui/dialog/DialogContent.vue';
import DialogHeader from '../ui/dialog/DialogHeader.vue';
import DialogTitle from '../ui/dialog/DialogTitle.vue';
import DialogDescription from '../ui/dialog/DialogDescription.vue';
import { getCoC } from '@/api/application';
import { startBrowserTracingPageLoadSpan } from '@sentry/vue';
const regexA = /^https?:\/\/steamcommunity\.com\/id\/[A-Za-z0-9_]+\/?$/;
const regexB = /^https?:\/\/steamcommunity\.com\/profiles\/\d+\/?$/;
const formSchema = toTypedSchema(z.object({
dob: z.string().refine(v => v, { message: "A date of birth is required." }),
name: z.string(),
name: z.string().nonempty(),
playtime: z.coerce.number({ invalid_type_error: "Must be a number", }).min(0, "Cannot be less than 0"),
hobbies: z.string(),
hobbies: z.string().nonempty(),
military: z.boolean(),
communities: z.string(),
joinReason: z.string(),
milsimAttraction: z.string(),
referral: z.string(),
steamProfile: z.string(),
timezone: z.string(),
communities: z.string().nonempty(),
joinReason: z.string().nonempty(),
milsimAttraction: z.string().nonempty(),
referral: z.string().nonempty(),
steamProfile: z.string().nonempty().refine((val) => regexA.test(val) || regexB.test(val), { message: "Invalid Steam profile URL." }),
timezone: z.string().nonempty(),
canAttendSaturday: z.boolean(),
interests: z.string(),
aknowledgeRules: z.literal(true, {
interests: z.string().nonempty(),
acknowledgeRules: z.literal(true, {
errorMap: () => ({ message: "Required" })
}),
}))
@@ -41,7 +53,7 @@ const formSchema = toTypedSchema(z.object({
const fallbackInitials = {
military: false,
canAttendSaturday: false,
aknowledgeRules: false,
acknowledgeRules: false,
}
const props = defineProps<{
@@ -57,7 +69,7 @@ async function onSubmit(val: any) {
emit('submit', val);
}
onMounted(() => {
onMounted(async () => {
if (props.data !== null) {
const parsed = typeof props.data === "string"
? JSON.parse(props.data)
@@ -67,8 +79,35 @@ onMounted(() => {
} else {
initialValues.value = { ...fallbackInitials };
}
// CoCbox.value.innerHTML = await getCoC()
CoCString.value = await getCoC();
})
const showCoC = ref(false);
const CoCbox = ref<HTMLElement>();
const CoCString = ref<string>();
async function onDialogToggle(state: boolean) {
showCoC.value = state;
}
function enforceExternalLinks() {
if (!CoCbox.value) return;
const links = CoCbox.value.querySelectorAll("a");
links.forEach(a => {
a.setAttribute("target", "_blank");
a.setAttribute("rel", "noopener noreferrer");
});
}
watch(() => showCoC.value, async () => {
if (showCoC) {
await nextTick(); // wait for v-html to update
enforceExternalLinks();
}
});
</script>
@@ -82,7 +121,9 @@ onMounted(() => {
<FormControl>
<DateInput :model-value="(value as string) ?? ''" :disabled="readOnly" @update:model-value="handleChange" />
</FormControl>
<FormMessage />
<div class="h-4">
<FormMessage class="text-destructive" />
</div>
</FormItem>
</FormField>
@@ -94,7 +135,9 @@ onMounted(() => {
<FormControl>
<Input :model-value="value" @update:model-value="handleChange" :disabled="readOnly" />
</FormControl>
<FormMessage />
<div class="h-4">
<FormMessage class="text-destructive" />
</div>
</FormItem>
</FormField>
@@ -105,7 +148,9 @@ onMounted(() => {
<FormControl>
<Input type="number" :model-value="value" @update:model-value="handleChange" :disabled="readOnly" />
</FormControl>
<FormMessage />
<div class="h-4">
<FormMessage class="text-destructive" />
</div>
</FormItem>
</FormField>
@@ -117,7 +162,9 @@ onMounted(() => {
<Textarea rows="4" class="resize-none" :model-value="value" @update:model-value="handleChange"
:disabled="readOnly" />
</FormControl>
<FormMessage />
<div class="h-4">
<FormMessage class="text-destructive" />
</div>
</FormItem>
</FormField>
@@ -131,7 +178,9 @@ onMounted(() => {
<span>Yes (checked) / No (unchecked)</span>
</div>
</FormControl>
<FormMessage />
<div class="h-4">
<FormMessage class="text-destructive" />
</div>
</FormItem>
</FormField>
@@ -142,7 +191,9 @@ onMounted(() => {
<FormControl>
<Input :model-value="value" @update:model-value="handleChange" :disabled="readOnly" />
</FormControl>
<FormMessage />
<div class="h-4">
<FormMessage class="text-destructive" />
</div>
</FormItem>
</FormField>
@@ -154,7 +205,9 @@ onMounted(() => {
<Textarea rows="4" class="resize-none" :model-value="value" @update:model-value="handleChange"
:disabled="readOnly" />
</FormControl>
<FormMessage />
<div class="h-4">
<FormMessage class="text-destructive" />
</div>
</FormItem>
</FormField>
@@ -166,7 +219,9 @@ onMounted(() => {
<Textarea rows="4" class="resize-none" :model-value="value" @update:model-value="handleChange"
:disabled="readOnly" />
</FormControl>
<FormMessage />
<div class="h-4">
<FormMessage class="text-destructive" />
</div>
</FormItem>
</FormField>
@@ -178,7 +233,9 @@ onMounted(() => {
<Input placeholder="e.g., Reddit / Member: Alice" :model-value="value" @update:model-value="handleChange"
:disabled="readOnly" />
</FormControl>
<FormMessage />
<div class="h-4">
<FormMessage class="text-destructive" />
</div>
</FormItem>
</FormField>
@@ -194,7 +251,9 @@ onMounted(() => {
<Input type="url" placeholder="https://steamcommunity.com/profiles/7656119..." :model-value="value"
@update:model-value="handleChange" :disabled="readOnly" />
</FormControl>
<FormMessage />
<div class="h-4">
<FormMessage class="text-destructive" />
</div>
</FormItem>
</FormField>
@@ -206,7 +265,9 @@ onMounted(() => {
<Input placeholder="e.g., AEST, EST, UTC+10" :model-value="value" @update:model-value="handleChange"
:disabled="readOnly" />
</FormControl>
<FormMessage />
<div class="h-4">
<FormMessage class="text-destructive" />
</div>
</FormItem>
</FormField>
@@ -220,7 +281,9 @@ onMounted(() => {
<span>Yes (checked) / No (unchecked)</span>
</div>
</FormControl>
<FormMessage />
<div class="h-4">
<FormMessage class="text-destructive" />
</div>
</FormItem>
</FormField>
@@ -232,27 +295,44 @@ onMounted(() => {
<Input placeholder="e.g., Rifleman; Medic; Pilot" :model-value="value" @update:model-value="handleChange"
:disabled="readOnly" />
</FormControl>
<FormMessage />
<div class="h-4">
<FormMessage class="text-destructive" />
</div>
</FormItem>
</FormField>
<!-- Code of Conduct (boolean, field name kept as-is) -->
<FormField name="aknowledgeRules" v-slot="{ value, handleChange }">
<FormField name="acknowledgeRules" v-slot="{ value, handleChange }">
<FormItem>
<FormLabel>Community Code of Conduct</FormLabel>
<FormControl>
<div class="flex items-center gap-2">
<Checkbox :model-value="value" @update:model-value="handleChange" :disabled="readOnly" />
<span>By checking this box, you accept the <Button variant="link" class="p-0">Code of
<span>By checking this box, you accept the <Button variant="link" class="p-0 h-min"
@click.prevent.stop="showCoC = true">Code of
Conduct</Button>.</span>
</div>
</FormControl>
<FormMessage />
<div class="h-4">
<FormMessage class="text-destructive" />
</div>
</FormItem>
</FormField>
<div class="pt-2" v-if="!readOnly">
<Button type="submit" :onClick="() => console.log('hi')" :disabled="readOnly">Submit Application</Button>
<Button type="submit" :disabled="readOnly">Submit Application</Button>
</div>
<Dialog :open="showCoC" @update:open="onDialogToggle">
<DialogContent class="sm:max-w-fit">
<DialogHeader>
<DialogTitle>Community Code of Conduct</DialogTitle>
<DialogDescription class="w-full max-h-[75vh] overflow-y-auto scrollbar-themed">
<div v-html="CoCString" ref="CoCbox" class="bookstack-container w-full"></div>
</DialogDescription>
</DialogHeader>
</DialogContent>
</Dialog>
</Form>
</template>

View File

@@ -1,7 +1,7 @@
<script setup lang="ts">
import type { CalendarEvent, CalendarSignup } from '@shared/types/calendar'
import { CircleAlert, Clock, EllipsisVertical, MapPin, User, X } from 'lucide-vue-next';
import { computed, onMounted, ref, watch } from 'vue';
import { CircleAlert, Clock4, EllipsisVertical, MapPin, User, X } from 'lucide-vue-next';
import { computed, ref, watch } from 'vue';
import ButtonGroup from '../ui/button-group/ButtonGroup.vue';
import Button from '../ui/button/Button.vue';
import { CalendarAttendance, getCalendarEvent, setCalendarEventAttendance, setCancelCalendarEvent } from '@/api/calendar';
@@ -11,24 +11,13 @@ import DropdownMenu from '../ui/dropdown-menu/DropdownMenu.vue';
import DropdownMenuTrigger from '../ui/dropdown-menu/DropdownMenuTrigger.vue';
import DropdownMenuContent from '../ui/dropdown-menu/DropdownMenuContent.vue';
import DropdownMenuItem from '../ui/dropdown-menu/DropdownMenuItem.vue';
import { Calendar } from 'lucide-vue-next';
const route = useRoute();
// const eventID = computed(() => {
// const id = route.params.id;
// if (typeof id === 'string') return id;
// return undefined;
// });
const loaded = ref<boolean>(false);
const activeEvent = ref<CalendarEvent | null>(null);
// onMounted(async () => {
// let eventID = route.params.id;
// console.log(eventID);
// activeEvent.value = await getCalendarEvent(Number(eventID));
// loaded.value = true;
// });
watch(
() => route.params.id,
async (id) => {
@@ -45,23 +34,27 @@ const emit = defineEmits<{
(e: 'edit', event: CalendarEvent): void
}>()
// const activeEvent = computed(() => props.event)
const startFmt = new Intl.DateTimeFormat(undefined, {
weekday: 'short', year: 'numeric', month: 'short', day: 'numeric',
hour: 'numeric', minute: '2-digit'
const dateFmt = new Intl.DateTimeFormat(undefined, {
weekday: 'long', month: 'short', day: 'numeric',
})
const endFmt = new Intl.DateTimeFormat(undefined, {
const timeFmt = new Intl.DateTimeFormat(undefined, {
hour: 'numeric', minute: '2-digit'
})
const whenText = computed(() => {
if (!activeEvent.value?.start) return ''
const s = new Date(activeEvent.value.start)
const e = activeEvent.value?.end ? new Date(activeEvent.value.end) : null
return e
? `${startFmt.format(s)} ${endFmt.format(e)}`
: `${startFmt.format(s)}`
const dateText = computed(() => {
let start = dateFmt.format(new Date(activeEvent.value.start));
let end = dateFmt.format(new Date(activeEvent.value.end));
if (start === end)
return start;
else
return `${start} - ${end}`;
})
const timeText = computed(() => {
let startTime = timeFmt.format(new Date(activeEvent.value.start))
let endTime = timeFmt.format(new Date(activeEvent.value.end))
return [startTime, endTime]
})
const attending = computed<CalendarSignup[]>(() => { return activeEvent.value.eventSignups.filter((s) => s.status == CalendarAttendance.Attending) })
@@ -71,6 +64,7 @@ const viewedState = ref<CalendarAttendance>(CalendarAttendance.Attending);
let user = useUserStore();
const myAttendance = computed<CalendarSignup | null>(() => {
if (!user.isLoggedIn) return null;
return activeEvent.value.eventSignups.find(
(s) => s.member_id === user.user.id
) || null;
@@ -83,6 +77,7 @@ async function setAttendance(state: CalendarAttendance) {
}
const canEditEvent = computed(() => {
if (!user.isLoggedIn) return false;
if (user.user.id == activeEvent.value.creator_id)
return true;
});
@@ -97,17 +92,94 @@ async function forceReload() {
activeEvent.value = await getCalendarEvent(activeEvent.value.id);
}
defineExpose({forceReload})
const isPast = computed(() => {
const end = new Date(activeEvent.value.end)
// is current date later than end date
return new Date() < end;
})
const attendanceTab = ref<"Alpha" | "Echo" | "Other">("Alpha");
const attendanceList = computed<CalendarSignup[]>(() => {
let out: CalendarSignup[] = [];
if (attendanceTab.value === 'Alpha') {
out = activeEvent.value.eventSignups?.filter((s) => s.member_unit === 'Alpha Company');
} else if (attendanceTab.value === 'Echo') {
out = activeEvent.value.eventSignups?.filter((s) => s.member_unit === 'Echo Company')
} else {
out = activeEvent.value.eventSignups?.filter((s) => s.member_unit != 'Alpha Company' && s.member_unit != 'Echo Company')
}
const statusOrder: Record<CalendarAttendance, number> = {
[CalendarAttendance.Attending]: 1,
[CalendarAttendance.Maybe]: 2,
[CalendarAttendance.NotAttending]: 3,
};
out.sort((a, b) => statusOrder[a.status] - statusOrder[b.status]);
return out;
})
const attendanceCountsByGroup = computed(() => {
const signups = activeEvent.value.eventSignups ?? [];
return {
Alpha: signups.filter(s => s.member_unit === "Alpha Company").length,
Echo: signups.filter(s => s.member_unit === "Echo Company").length,
Other: signups.filter(s =>
s.member_unit !== "Alpha Company" &&
s.member_unit !== "Echo Company"
).length,
};
});
const attendanceStatusSummary = computed(() => {
const signups = activeEvent.value.eventSignups ?? [];
return {
attending: signups.filter(s => s.status === CalendarAttendance.Attending).length,
maybe: signups.filter(s => s.status === CalendarAttendance.Maybe).length,
notAttending: signups.filter(s => s.status === CalendarAttendance.NotAttending).length,
};
});
const statusColor = (status: CalendarAttendance) => {
switch (status) {
case CalendarAttendance.Attending:
return "text-success";
case CalendarAttendance.Maybe:
return "text-yellow-600";
case CalendarAttendance.NotAttending:
return "text-destructive";
default:
return "";
}
};
const displayStatus = (status: CalendarAttendance) => {
switch (status) {
case CalendarAttendance.Attending:
return "Attending";
case CalendarAttendance.Maybe:
return "Maybe";
case CalendarAttendance.NotAttending:
return "Declined";
default:
return status;
}
};
defineExpose({ forceReload })
</script>
<template>
<div v-if="loaded">
<!-- Header -->
<div class="flex items-center justify-between gap-3 border-b px-4 py-3">
<div class="flex items-center justify-between gap-3 border-b px-4 py-3 h-14">
<h2 class="text-lg font-semibold break-all">
{{ activeEvent?.name || 'Event' }}
</h2>
<div class="flex gap-4">
<div class="flex gap-4 items-center">
<DropdownMenu v-if="canEditEvent">
<DropdownMenuTrigger>
<button
@@ -119,8 +191,7 @@ defineExpose({forceReload})
<DropdownMenuItem @click="emit('edit', activeEvent)">
Edit
</DropdownMenuItem>
<DropdownMenuItem v-if="activeEvent.cancelled"
@click="setCancel(false)">
<DropdownMenuItem v-if="activeEvent.cancelled" @click="setCancel(false)">
Un-Cancel
</DropdownMenuItem>
<DropdownMenuItem v-else @click="setCancel(true)">
@@ -142,7 +213,7 @@ defineExpose({forceReload})
<CircleAlert></CircleAlert> This event has been cancelled
</div>
</section>
<section class="w-full">
<section v-if="isPast && user.isLoggedIn" class="w-full">
<ButtonGroup class="flex w-full">
<Button variant="outline"
:class="myAttendance?.status === CalendarAttendance.Attending ? 'border-2 border-primary text-primary' : ''"
@@ -155,24 +226,21 @@ defineExpose({forceReload})
@click="setAttendance(CalendarAttendance.NotAttending)">Declined</Button>
</ButtonGroup>
</section>
<!-- When -->
<section v-if="whenText" class="space-y-2 w-full">
<div class="inline-flex items-center gap-2 rounded-md border px-2.5 py-1.5 text-sm">
<Clock class="size-4 opacity-80" />
<span class="font-medium">{{ whenText }}</span>
<!-- Meta -->
<section class="space-y-3 w-full">
<p class="text-lg font-semibold">Details</p>
<div class="text-foreground/80 flex gap-3 items-center">
<Calendar :size="20"></Calendar> {{ dateText }}
</div>
<div class="text-foreground/80 flex gap-3 items-center">
<Clock4 :size="20"></Clock4> {{ timeText[0] }} - {{ timeText[1] }}
</div>
<div class="text-foreground/80 flex gap-3 items-center">
<MapPin :size="20"></MapPin> {{ activeEvent.location || "Unknown" }}
</div>
<div class="text-foreground/80 flex gap-3 items-center">
<User :size="20"></User> {{ activeEvent.creator_name || "Unknown User" }}
</div>
</section>
<!-- Quick meta chips -->
<section class="flex flex-wrap gap-2 w-full">
<span class="inline-flex items-center gap-1.5 rounded-md border px-2 py-1 text-xs">
<MapPin class="size-3.5 opacity-80" />
<span class="font-medium">{{ activeEvent.location || "Unknown" }}</span>
</span>
<span class="inline-flex items-center gap-1.5 rounded-md border px-2 py-1 text-xs">
<User class="size-3.5 opacity-80" />
<span class="font-medium">Created by: {{ activeEvent.creator_name || "Unknown User"
}}</span>
</span>
</section>
<!-- Description -->
<section class="space-y-2 w-full">
@@ -181,46 +249,41 @@ defineExpose({forceReload})
{{ activeEvent.description }}
</p>
</section>
<!-- Attendance -->
<!-- attendance -->
<section class="space-y-2 w-full">
<p class="text-lg font-semibold">Attendance</p>
<div class="flex items-center gap-5">
<p class="text-lg font-semibold">Attendance</p>
<!-- <div class="text-muted-foreground flex gap-6">
<p>Going <span class="ml-1">{{ attendanceStatusSummary.attending }}</span></p>
<p>Maybe <span class="ml-1">{{ attendanceStatusSummary.maybe }}</span></p>
<p>Declined <span class="ml-1">{{ attendanceStatusSummary.notAttending }}</span></p>
</div> -->
</div>
<div class="flex flex-col border bg-muted/50 rounded-lg min-h-24 my-2">
<div class="flex w-full pt-2 border-b *:w-full *:text-center *:pb-1 *:cursor-pointer">
<label
:class="viewedState === CalendarAttendance.Attending ? 'border-b-3 border-foreground' : 'mb-[2px]'"
@click="viewedState = CalendarAttendance.Attending">Going {{ attending.length }}</label>
<label
:class="viewedState === CalendarAttendance.Maybe ? 'border-b-3 border-foreground' : 'mb-[2px]'"
@click="viewedState = CalendarAttendance.Maybe">Maybe {{ maybe.length }}</label>
<label
:class="viewedState === CalendarAttendance.NotAttending ? 'border-b-3 border-foreground' : 'mb-[2px]'"
@click="viewedState = CalendarAttendance.NotAttending">Declined {{ declined.length
}}</label>
<label :class="attendanceTab === 'Alpha' ? 'border-b-3 border-foreground' : 'mb-[2px]'"
@click="attendanceTab = 'Alpha'">Alpha {{ attendanceCountsByGroup.Alpha }}</label>
<label :class="attendanceTab === 'Echo' ? 'border-b-3 border-foreground' : 'mb-[2px]'"
@click="attendanceTab = 'Echo'">Echo {{ attendanceCountsByGroup.Echo }}</label>
<label :class="attendanceTab === 'Other' ? 'border-b-3 border-foreground' : 'mb-[2px]'"
@click="attendanceTab = 'Other'">Other {{ attendanceCountsByGroup.Other }}</label>
</div>
<div class="px-5 py-4 min-h-28">
<div v-if="viewedState === CalendarAttendance.Attending" v-for="person in attending">
<p>{{ person.member_name }}</p>
<div class="pb-1 min-h-48">
<div class="grid grid-cols-2 font-semibold text-muted-foreground border-b py-1 px-3 mb-2">
<p>Name</p>
<p class="text-right">Status</p>
</div>
<div v-if="viewedState === CalendarAttendance.Maybe" v-for="person in maybe">
<p>{{ person.member_name }}</p>
</div>
<div v-if="viewedState === CalendarAttendance.NotAttending" v-for="person in declined">
<div v-for="person in attendanceList" :key="person.member_id"
class="grid grid-cols-2 py-1 *:px-3 hover:bg-muted">
<p>{{ person.member_name }}</p>
<p :class="statusColor(person.status)" class="text-right">
{{ displayStatus(person.status) }}
</p>
</div>
</div>
</div>
</section>
</div>
<!-- Footer (optional actions) -->
<!-- <div class="border-t px-4 py-3 flex items-center justify-end gap-2">
<button class="rounded-md border px-3 py-1.5 text-sm hover:bg-muted/40 transition">
Edit
</button>
<button
class="rounded-md bg-primary text-primary-foreground px-3 py-1.5 text-sm hover:opacity-90 transition">
Open details
</button>
</div> -->
</div>
</template>

View File

@@ -1,26 +1,47 @@
<script setup lang="ts">
import { Check, Search } from "lucide-vue-next"
import { Combobox, ComboboxAnchor, ComboboxEmpty, ComboboxGroup, ComboboxInput, ComboboxItem, ComboboxItemIndicator, ComboboxList } from "@/components/ui/combobox"
import { onMounted, ref } from "vue";
import { ComboboxAnchor, ComboboxEmpty, ComboboxGroup, ComboboxInput, ComboboxItem, ComboboxItemIndicator, ComboboxList } from "@/components/ui/combobox"
import { computed, onMounted, ref, watch } from "vue";
import { Member, getMembers } from "@/api/member";
import Button from "@/components/ui/button/Button.vue";
import {
CalendarDate,
DateFormatter,
fromDate,
getLocalTimeZone,
parseDate,
today,
} from "@internationalized/date"
import type { DateRange } from "reka-ui"
import type { DateRange, DateValue } from "reka-ui"
import type { Ref } from "vue"
import Popover from "@/components/ui/popover/Popover.vue";
import PopoverTrigger from "@/components/ui/popover/PopoverTrigger.vue";
import PopoverContent from "@/components/ui/popover/PopoverContent.vue";
import { RangeCalendar } from "@/components/ui/range-calendar"
import { cn } from "@/lib/utils";
import { CalendarIcon } from "lucide-vue-next"
import Textarea from "@/components/ui/textarea/Textarea.vue";
import { LOARequest, submitLOA } from "@/api/loa"; // <-- import the submit function
import { adminSubmitLOA, getLoaPolicy, getLoaTypes, submitLOA } from "@/api/loa"; // <-- import the submit function
import { LOARequest, LOAType } from "@shared/types/loa";
import { useForm, Field as VeeField } from "vee-validate";
import {
Field,
FieldContent,
FieldDescription,
FieldGroup,
FieldLabel,
} from '@/components/ui/field'
import Combobox from "../ui/combobox/Combobox.vue";
import Select from "../ui/select/Select.vue";
import SelectTrigger from "../ui/select/SelectTrigger.vue";
import SelectValue from "../ui/select/SelectValue.vue";
import SelectContent from "../ui/select/SelectContent.vue";
import SelectItem from "../ui/select/SelectItem.vue";
import FieldError from "../ui/field/FieldError.vue";
const members = ref<Member[]>([])
const loaTypes = ref<LOAType[]>();
const policyString = ref<string | null>(null);
const currentMember = ref<Member | null>(null);
const props = withDefaults(defineProps<{
@@ -31,142 +52,226 @@ const props = withDefaults(defineProps<{
member: null,
});
const df = new Intl.DateTimeFormat('en-US', {
year: 'numeric',
month: 'long',
day: 'numeric'
});
const df = new DateFormatter("en-US", {
dateStyle: "medium",
const userStore = useUserStore()
//form stuff
import { loaSchema } from '@shared/schemas/loaSchema'
import { toTypedSchema } from "@vee-validate/zod";
import Calendar from "../ui/calendar/Calendar.vue";
import { useUserStore } from "@/stores/user";
const { handleSubmit, values, resetForm } = useForm({
validationSchema: toTypedSchema(loaSchema),
})
const value = ref({
// start: new CalendarDate(2022, 1, 20),
// end: new CalendarDate(2022, 1, 20).add({ days: 20 }),
}) as Ref<DateRange>
const reason = ref(""); // <-- reason for LOA
const submitting = ref(false);
const submitError = ref<string | null>(null);
const submitSuccess = ref(false);
const onSubmit = handleSubmit(async (values) => {
console.log(values);
const out: LOARequest = {
member_id: values.member_id,
start_date: values.start_date,
end_date: values.end_date,
type_id: values.type.id,
reason: values.reason
};
if (props.adminMode) {
await adminSubmitLOA(out);
} else {
await submitLOA(out);
userStore.loadUser();
}
})
onMounted(async () => {
if (props.member) {
currentMember.value = props.member;
}
if (props.adminMode) {
members.value = await getMembers();
try {
if (!props.adminMode) {
let policy = await getLoaPolicy() as any;
policyString.value = policy;
policyRef.value.innerHTML = policyString.value;
}
} catch (error) {
console.error(error);
}
members.value = await getMembers();
loaTypes.value = await getLoaTypes();
resetForm({ values: { member_id: currentMember.value?.member_id } });
});
// Submit handler
async function handleSubmit() {
submitError.value = null;
submitSuccess.value = false;
submitting.value = true;
const policyRef = ref<HTMLElement>(null);
// Use currentMember if adminMode, otherwise use your own member id (stubbed as 89 here)
const member_id = currentMember.value?.member_id ?? 89;
const defaultPlaceholder = today(getLocalTimeZone())
// Format dates as ISO strings
const filed_date = toMariaDBDatetime(new Date());
const start_date = toMariaDBDatetime(value.value.start?.toDate(getLocalTimeZone()));
const end_date = toMariaDBDatetime(value.value.end?.toDate(getLocalTimeZone()));
if (!member_id || !filed_date || !start_date || !end_date) {
submitError.value = "Missing required fields";
submitting.value = false;
return;
}
const req: LOARequest = {
filed_date,
start_date,
end_date,
reason: reason.value,
member_id
};
const result = await submitLOA(req);
submitting.value = false;
if (result.id) {
submitSuccess.value = true;
reason.value = "";
const minEndDate = computed(() => {
if (values.start_date) {
return new CalendarDate(values.start_date.getFullYear(), values.start_date.getMonth() + 1, values.start_date.getDate())
} else {
submitError.value = result.error || "Failed to submit LOA";
return null;
}
}
})
function toMariaDBDatetime(date: Date): string {
return date.toISOString().slice(0, 19).replace('T', ' ');
}
const maxEndDate = computed(() => {
if (values.type && values.start_date) {
let endDateObj = new Date(values.start_date.getTime() + values.type.max_length_days * 24 * 60 * 60 * 1000);
return new CalendarDate(endDateObj.getFullYear(), endDateObj.getMonth() + 1, endDateObj.getDate())
} else {
return null;
}
})
</script>
<template>
<div class="flex flex-row-reverse gap-6 mx-auto " :class="!adminMode ? 'max-w-5xl' : 'max-w-5xl'">
<div v-if="!adminMode" class="flex-1 flex space-x-4 rounded-md border p-4">
<div class="flex-2 space-y-1">
<p class="text-sm font-medium leading-none">
LOA Policy
</p>
<p class="text-sm text-muted-foreground">
Policy goes here.
</p>
<div class="flex flex-row-reverse gap-6 mx-auto w-full" :class="!adminMode ? 'max-w-5xl' : 'max-w-5xl'">
<div v-if="!adminMode" class="flex-1 flex flex-col space-x-4 rounded-md border p-4">
<p class="scroll-m-20 text-2xl font-semibold tracking-tight">LOA Policy</p>
<div ref="policyRef" class="bookstack-container">
<!-- LOA policy gets loaded here -->
</div>
</div>
<div class="flex-1 flex flex-col gap-5">
<div class="flex w-full gap-5 ">
<Combobox class="w-1/2" v-model="currentMember" :disabled="!adminMode">
<ComboboxAnchor class="w-full">
<ComboboxInput placeholder="Search members..." class="w-full pl-9"
:display-value="(v) => v ? v.member_name : ''" />
</ComboboxAnchor>
<ComboboxList class="w-full">
<ComboboxEmpty class="text-muted-foreground">No results</ComboboxEmpty>
<ComboboxGroup>
<template v-for="member in members" :key="member.member_id">
<ComboboxItem :value="member"
class="data-[highlighted]:bg-accent data-[highlighted]:text-accent-foreground relative cursor-pointer select-none px-2 py-1.5">
{{ member.member_name }}
<ComboboxItemIndicator class="absolute left-2 inline-flex items-center">
<Check class="h-4 w-4" />
</ComboboxItemIndicator>
</ComboboxItem>
</template>
</ComboboxGroup>
</ComboboxList>
</Combobox>
<Popover>
<PopoverTrigger as-child>
<Button variant="outline" :class="cn(
'w-1/2 justify-start text-left font-normal',
!value && 'text-muted-foreground',
)">
<CalendarIcon class="mr-2 h-4 w-4" />
<template v-if="value.start">
<template v-if="value.end">
{{ df.format(value.start.toDate(getLocalTimeZone())) }} - {{
df.format(value.end.toDate(getLocalTimeZone())) }}
</template>
<template v-else>
{{ df.format(value.start.toDate(getLocalTimeZone())) }}
</template>
</template>
<template v-else>
Pick a date
</template>
</Button>
</PopoverTrigger>
<PopoverContent class="w-auto p-0">
<RangeCalendar v-model="value" initial-focus :number-of-months="2"
@update:start-value="(startDate) => value.start = startDate" />
</PopoverContent>
</Popover>
</div>
<Textarea v-model="reason" placeholder="Reason for LOA" class="w-full resize-none" />
<div class="flex justify-end">
<Button :onClick="handleSubmit" :disabled="submitting" class="w-min">Submit</Button>
</div>
<div v-if="submitError" class="text-red-500 text-sm mt-2">{{ submitError }}</div>
<div v-if="submitSuccess" class="text-green-500 text-sm mt-2">LOA submitted successfully!</div>
<form @submit="onSubmit" class="flex flex-col gap-2">
<div class="flex w-full gap-5">
<VeeField v-slot="{ field, errors }" name="member_id">
<Field>
<FieldContent>
<FieldLabel>Member</FieldLabel>
<Combobox :model-value="field.value" @update:model-value="field.onChange"
:disabled="!adminMode">
<ComboboxAnchor class="w-full">
<ComboboxInput placeholder="Search members..." class="w-full pl-3"
:display-value="(id) => {
const m = members.find(mem => mem.member_id === id)
return m ? m.member_name : ''
}" />
</ComboboxAnchor>
<ComboboxList class="*:w-64">
<ComboboxEmpty class="text-muted-foreground w-full">No results</ComboboxEmpty>
<ComboboxGroup>
<template v-for="member in members" :key="member.member_id">
<ComboboxItem :value="member.member_id"
class="data-[highlighted]:bg-accent data-[highlighted]:text-accent-foreground relative cursor-pointer select-none px-2 py-1.5 w-full">
{{ member.member_name }}
<ComboboxItemIndicator
class="absolute left-2 inline-flex items-center">
<Check class="h-4 w-4" />
</ComboboxItemIndicator>
</ComboboxItem>
</template>
</ComboboxGroup>
</ComboboxList>
</Combobox>
<div class="h-4">
<FieldError v-if="errors.length" :errors="errors"></FieldError>
</div>
</FieldContent>
</Field>
</VeeField>
<VeeField v-slot="{ field, errors }" name="type">
<Field class="w-full">
<FieldContent>
<FieldLabel>Type</FieldLabel>
<Select :model-value="field.value" @update:model-value="field.onChange">
<SelectTrigger class="w-full">
<SelectValue placeholder="Select type"></SelectValue>
</SelectTrigger>
<SelectContent>
<SelectItem v-for="type in loaTypes" :value="type">
{{ type.name }}
</SelectItem>
</SelectContent>
</Select>
<div class="h-4">
<FieldError v-if="errors.length" :errors="errors"></FieldError>
</div>
</FieldContent>
</Field>
</VeeField>
</div>
<div class="flex gap-5">
<VeeField v-slot="{ field, errors }" name="start_date">
<Field>
<FieldContent>
<FieldLabel>Start Date</FieldLabel>
<Popover>
<PopoverTrigger as-child>
<Button variant="outline" :class="cn(
'w-full justify-start text-left font-normal',
!field.value && 'text-muted-foreground',
)">
<CalendarIcon class="mr-2 h-4 w-4" />
{{ field.value ? df.format(field.value) : "Pick a date" }}
</Button>
</PopoverTrigger>
<PopoverContent class="w-auto p-0">
<Calendar
:model-value="field.value
? new CalendarDate(field.value.getFullYear(), field.value.getMonth() + 1, field.value.getDate()) : null"
@update:model-value="(val: CalendarDate) => field.onChange(val.toDate(getLocalTimeZone()))"
layout="month-and-year" :min-value="today(getLocalTimeZone())" />
</PopoverContent>
</Popover>
<div class="h-4">
<FieldError v-if="errors.length" :errors="errors"></FieldError>
</div>
</FieldContent>
</Field>
</VeeField>
<VeeField v-slot="{ field, errors }" name="end_date">
<Field>
<FieldContent>
<FieldLabel>End Date</FieldLabel>
<Popover>
<PopoverTrigger as-child>
<Button variant="outline" :class="cn(
'w-full justify-start text-left font-normal',
!field.value && 'text-muted-foreground',
)">
<CalendarIcon class="mr-2 h-4 w-4" />
{{ field.value ? df.format(field.value) : "Pick a date" }}
</Button>
</PopoverTrigger>
<PopoverContent class="w-auto p-0">
<Calendar
:model-value="field.value ? new CalendarDate(field.value.getFullYear(), field.value.getMonth() + 1, field.value.getDate()) : null"
@update:model-value="(val: CalendarDate) => field.onChange(val.toDate(getLocalTimeZone()))"
:default-placeholder="defaultPlaceholder" :min-value="minEndDate"
:max-value="maxEndDate" layout="month-and-year">
</Calendar>
</PopoverContent>
</Popover>
<div class="h-4">
<FieldError v-if="errors.length" :errors="errors"></FieldError>
</div>
</FieldContent>
</Field>
</VeeField>
</div>
<div>
<VeeField v-slot="{ field, errors }" name="reason">
<Field>
<FieldContent>
<FieldLabel>Reason</FieldLabel>
<Textarea :model-value="field.value" @update:model-value="field.onChange"
placeholder="Reason for LOA" class="resize-none h-28"></Textarea>
<div class="h-4">
<FieldError v-if="errors.length" :errors="errors"></FieldError>
</div>
</FieldContent>
</Field>
</VeeField>
</div>
<div class="flex justify-end">
<Button type="submit">Submit</Button>
</div>
</form>
</div>
</div>
</template>

View File

@@ -16,30 +16,53 @@ import {
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import { Ellipsis } from "lucide-vue-next";
import { getAllLOAs, LOARequest } from "@/api/loa";
import { cancelLOA, extendLOA, getAllLOAs, getMyLOAs } from "@/api/loa";
import { onMounted, ref, computed } from "vue";
import { LOARequest } from "@shared/types/loa";
import Dialog from "../ui/dialog/Dialog.vue";
import DialogTrigger from "../ui/dialog/DialogTrigger.vue";
import DialogContent from "../ui/dialog/DialogContent.vue";
import DialogHeader from "../ui/dialog/DialogHeader.vue";
import DialogTitle from "../ui/dialog/DialogTitle.vue";
import DialogDescription from "../ui/dialog/DialogDescription.vue";
import Button from "../ui/button/Button.vue";
import Calendar from "../ui/calendar/Calendar.vue";
import {
CalendarDate,
getLocalTimeZone,
} from "@internationalized/date"
import { el } from "@fullcalendar/core/internal-common";
const props = defineProps<{
adminMode?: boolean
}>()
const LOAList = ref<LOARequest[]>([]);
onMounted(async () => {
LOAList.value = await getAllLOAs();
await loadLOAs();
});
function formatDate(dateStr: string): string {
if (!dateStr) return "";
return new Date(dateStr).toLocaleDateString("en-US", {
async function loadLOAs() {
if (props.adminMode) {
LOAList.value = await getAllLOAs();
} else {
LOAList.value = await getMyLOAs();
}
}
function formatDate(date: Date): string {
if (!date) return "";
date = typeof date === 'string' ? new Date(date) : date;
return date.toLocaleDateString("en-US", {
year: "numeric",
month: "short",
day: "numeric",
});
}
function loaStatus(loa: {
start_date: string;
end_date: string;
deleted?: number;
}): "Upcoming" | "Active" | "Expired" | "Cancelled" {
if (loa.deleted) return "Cancelled";
function loaStatus(loa: LOARequest): "Upcoming" | "Active" | "Overdue" | "Closed" {
if (loa.closed) return "Closed";
const now = new Date();
const start = new Date(loa.start_date);
@@ -47,9 +70,9 @@ function loaStatus(loa: {
if (now < start) return "Upcoming";
if (now >= start && now <= end) return "Active";
if (now > end) return "Expired";
if (now > end) return "Overdue";
return "Expired"; // fallback
return "Overdue"; // fallback
}
function sortByStartDate(loas: LOARequest[]): LOARequest[] {
@@ -58,50 +81,108 @@ function sortByStartDate(loas: LOARequest[]): LOARequest[] {
);
}
const sortedLoas = computed(() => sortByStartDate(LOAList.value));
async function cancelAndReload(id: number) {
await cancelLOA(id, props.adminMode);
await loadLOAs();
}
const isExtending = ref(false);
const targetLOA = ref<LOARequest | null>(null);
const extendTo = ref<CalendarDate | null>(null);
const targetEnd = computed(() => { return targetLOA.value.extended_till ? targetLOA.value.extended_till : targetLOA.value.end_date })
function toCalendarDate(date: Date): CalendarDate {
if (typeof date === 'string')
date = new Date(date);
return new CalendarDate(date.getFullYear(), date.getMonth() + 1, date.getDate())
}
async function commitExtend() {
await extendLOA(targetLOA.value.id, extendTo.value.toDate(getLocalTimeZone()));
isExtending.value = false;
await loadLOAs();
}
</script>
<template>
<div class="w-5xl mx-auto">
<Table>
<TableHeader>
<TableRow>
<TableHead class="w-[100px]">Member</TableHead>
<TableHead>Start</TableHead>
<TableHead>End</TableHead>
<TableHead>Reason</TableHead>
<TableHead>Posted on</TableHead>
<TableHead>Status</TableHead>
</TableRow>
</TableHeader>
<TableBody>
<TableRow v-for="post in sortedLoas" :key="post.id" class="hover:bg-muted/50">
<TableCell class="font-medium">
{{ post.name }}
</TableCell>
<TableCell>{{ formatDate(post.start_date) }}</TableCell>
<TableCell>{{ formatDate(post.end_date) }}</TableCell>
<TableCell>{{ post.reason }}</TableCell>
<TableCell>{{ formatDate(post.filed_date) }}</TableCell>
<TableCell>
<Badge v-if="loaStatus(post) === 'Upcoming'" class="bg-blue-500">Upcoming</Badge>
<Badge v-else-if="loaStatus(post) === 'Active'" class="bg-green-500">Active</Badge>
<Badge v-else-if="loaStatus(post) === 'Expired'" class="bg-gray-400">Expired</Badge>
<Badge v-else class="bg-red-500">Cancelled</Badge>
</TableCell>
<TableCell @click.stop="console.log('hi')" class="text-right">
<DropdownMenu>
<DropdownMenuTrigger class="cursor-pointer">
<Ellipsis></Ellipsis>
</DropdownMenuTrigger>
<DropdownMenuContent>
<DropdownMenuItem :variant="'destructive'">Cancel</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</TableCell>
</TableRow>
</TableBody>
</Table>
<div>
<Dialog :open="isExtending" @update:open="(val) => isExtending = val">
<DialogContent>
<DialogHeader>
<DialogTitle>Extend {{ targetLOA.name }}'s Leave of Absence </DialogTitle>
</DialogHeader>
<div class="flex gap-5">
<Calendar v-model="extendTo" class="rounded-md border shadow-sm w-min" layout="month-and-year"
:min-value="toCalendarDate(targetEnd)"
:max-value="toCalendarDate(targetEnd).add({ years: 1 })" />
<div class="flex flex-col w-full gap-3 px-2">
<p>Quick Options</p>
<Button variant="outline" @click="extendTo = toCalendarDate(targetEnd).add({ days: 7 })">1
Week</Button>
<Button variant="outline" @click="extendTo = toCalendarDate(targetEnd).add({ months: 1 })">1
Month</Button>
</div>
</div>
<div class="flex justify-end gap-4">
<Button variant="outline" @click="isExtending = false">Cancel</Button>
<Button @click="commitExtend">Extend</Button>
</div>
</DialogContent>
</Dialog>
<div class="max-w-7xl w-full mx-auto">
<Table>
<TableHeader>
<TableRow>
<TableHead>Member</TableHead>
<TableHead>Type</TableHead>
<TableHead>Start</TableHead>
<TableHead>End</TableHead>
<TableHead class="w-[500px]">Reason</TableHead>
<TableHead>Posted on</TableHead>
<TableHead>Status</TableHead>
</TableRow>
</TableHeader>
<TableBody>
<TableRow v-for="post in LOAList" :key="post.id" class="hover:bg-muted/50">
<TableCell class="font-medium">
{{ post.name }}
</TableCell>
<TableCell>{{ post.type_name }}</TableCell>
<TableCell>{{ formatDate(post.start_date) }}</TableCell>
<TableCell>{{ post.extended_till ? formatDate(post.extended_till) : formatDate(post.end_date) }}
</TableCell>
<TableCell>{{ post.reason }}</TableCell>
<TableCell>{{ formatDate(post.filed_date) }}</TableCell>
<TableCell>
<Badge v-if="loaStatus(post) === 'Upcoming'" class="bg-blue-400">Upcoming</Badge>
<Badge v-else-if="loaStatus(post) === 'Active'" class="bg-green-500">Active</Badge>
<Badge v-else-if="loaStatus(post) === 'Overdue'" class="bg-yellow-400">Overdue</Badge>
<Badge v-else class="bg-gray-400">Ended</Badge>
</TableCell>
<TableCell @click.stop="" class="text-right">
<DropdownMenu>
<DropdownMenuTrigger class="cursor-pointer">
<Ellipsis></Ellipsis>
</DropdownMenuTrigger>
<DropdownMenuContent>
<DropdownMenuItem v-if="!post.closed && props.adminMode"
@click="isExtending = true; targetLOA = post">
Extend
</DropdownMenuItem>
<DropdownMenuItem v-if="!post.closed" :variant="'destructive'"
@click="cancelAndReload(post.id)">End
</DropdownMenuItem>
<!-- Fallback: no actions available -->
<p v-if="post.closed || (!props.adminMode && post.closed)" class="p-2 text-center text-sm">
No actions
</p>
</DropdownMenuContent>
</DropdownMenu>
</TableCell>
</TableRow>
</TableBody>
</Table>
</div>
</div>
</template>

View File

@@ -18,10 +18,12 @@ import FieldSet from '../ui/field/FieldSet.vue'
import FieldLegend from '../ui/field/FieldLegend.vue'
import FieldDescription from '../ui/field/FieldDescription.vue'
import Checkbox from '../ui/checkbox/Checkbox.vue'
import { configure } from 'vee-validate'
const { handleSubmit, resetForm, errors, values, setFieldValue } = useForm({
validationSchema: toTypedSchema(trainingReportSchema),
validateOnMount: false,
initialValues: {
course_id: null,
event_date: "",
@@ -129,8 +131,17 @@ onMounted(async () => {
<VeeFieldArray name="attendees" v-slot="{ fields, push, remove }">
<FieldSet class="gap-4">
<FieldLegend class="scroll-m-20 text-lg tracking-tight">Attendees</FieldLegend>
<FieldDescription>Add members who attended this session.</FieldDescription>
<div class="flex flex-col gap-2">
<FieldLegend class="scroll-m-20 text-lg tracking-tight mb-0">Attendees</FieldLegend>
<FieldDescription class="mb-0">Add members who attended this session.</FieldDescription>
<div class="h-4">
<div class="text-red-500 text-sm"
v-if="errors.attendees && typeof errors.attendees === 'string'">
{{ errors.attendees }}
</div>
</div>
</div>
<FieldGroup class="gap-4">

View File

@@ -1,7 +1,14 @@
<script setup>
import { reactiveOmit } from "@vueuse/core";
import { CalendarRoot, useForwardPropsEmits } from "reka-ui";
import { getLocalTimeZone, today } from "@internationalized/date";
import { createReusableTemplate, reactiveOmit, useVModel } from "@vueuse/core";
import { CalendarRoot, useDateFormatter, useForwardPropsEmits } from "reka-ui";
import { createYear, createYearRange, toDate } from "reka-ui/date";
import { computed, toRaw } from "vue";
import { cn } from "@/lib/utils";
import {
NativeSelect,
NativeSelectOption,
} from '@/components/ui/native-select';
import {
CalendarCell,
CalendarCellTrigger,
@@ -38,34 +45,165 @@ const props = defineProps({
dir: { type: String, required: false },
nextPage: { type: Function, required: false },
prevPage: { type: Function, required: false },
modelValue: { type: null, required: false },
modelValue: { type: null, required: false, default: undefined },
multiple: { type: Boolean, required: false },
disableDaysOutsideCurrentView: { type: Boolean, required: false },
asChild: { type: Boolean, required: false },
as: { type: [String, Object, Function], required: false },
as: { type: null, required: false },
class: { type: null, required: false },
layout: { type: null, required: false, default: undefined },
yearRange: { type: Array, required: false },
});
const emits = defineEmits(["update:modelValue", "update:placeholder"]);
const delegatedProps = reactiveOmit(props, "class");
const delegatedProps = reactiveOmit(props, "class", "layout", "placeholder");
const placeholder = useVModel(props, "placeholder", emits, {
passive: true,
defaultValue: props.defaultPlaceholder ?? today(getLocalTimeZone()),
});
const formatter = useDateFormatter(props.locale ?? "en");
const yearRange = computed(() => {
return (
props.yearRange ??
createYearRange({
start:
props?.minValue ??
(
toRaw(props.placeholder) ??
props.defaultPlaceholder ??
today(getLocalTimeZone())
).cycle("year", -100),
end:
props?.maxValue ??
(
toRaw(props.placeholder) ??
props.defaultPlaceholder ??
today(getLocalTimeZone())
).cycle("year", 10),
})
);
});
const [DefineMonthTemplate, ReuseMonthTemplate] = createReusableTemplate();
const [DefineYearTemplate, ReuseYearTemplate] = createReusableTemplate();
const forwarded = useForwardPropsEmits(delegatedProps, emits);
</script>
<template>
<DefineMonthTemplate v-slot="{ date }">
<div class="**:data-[slot=native-select-icon]:right-1">
<div class="relative">
<div
class="absolute inset-0 flex h-full items-center text-sm pl-2 pointer-events-none"
>
{{ formatter.custom(toDate(date), { month: "short" }) }}
</div>
<NativeSelect
class="text-xs h-8 pr-6 pl-2 text-transparent relative"
@change="
(e) => {
placeholder = placeholder.set({
month: Number(e?.target?.value),
});
}
"
>
<NativeSelectOption
v-for="month in createYear({ dateObj: date })"
:key="month.toString()"
:value="month.month"
:selected="date.month === month.month"
>
{{ formatter.custom(toDate(month), { month: "short" }) }}
</NativeSelectOption>
</NativeSelect>
</div>
</div>
</DefineMonthTemplate>
<DefineYearTemplate v-slot="{ date }">
<div class="**:data-[slot=native-select-icon]:right-1">
<div class="relative">
<div
class="absolute inset-0 flex h-full items-center text-sm pl-2 pointer-events-none"
>
{{ formatter.custom(toDate(date), { year: "numeric" }) }}
</div>
<NativeSelect
class="text-xs h-8 pr-6 pl-2 text-transparent relative"
@change="
(e) => {
placeholder = placeholder.set({
year: Number(e?.target?.value),
});
}
"
>
<NativeSelectOption
v-for="year in yearRange"
:key="year.toString()"
:value="year.year"
:selected="date.year === year.year"
>
{{ formatter.custom(toDate(year), { year: "numeric" }) }}
</NativeSelectOption>
</NativeSelect>
</div>
</div>
</DefineYearTemplate>
<CalendarRoot
v-slot="{ grid, weekDays }"
v-slot="{ grid, weekDays, date }"
v-bind="forwarded"
v-model:placeholder="placeholder"
data-slot="calendar"
:class="cn('p-3', props.class)"
v-bind="forwarded"
>
<CalendarHeader>
<CalendarHeading />
<CalendarHeader class="pt-0">
<nav
class="flex items-center gap-1 absolute top-0 inset-x-0 justify-between"
>
<CalendarPrevButton>
<slot name="calendar-prev-icon" />
</CalendarPrevButton>
<CalendarNextButton>
<slot name="calendar-next-icon" />
</CalendarNextButton>
</nav>
<div class="flex items-center gap-1">
<CalendarPrevButton />
<CalendarNextButton />
</div>
<slot
name="calendar-heading"
:date="date"
:month="ReuseMonthTemplate"
:year="ReuseYearTemplate"
>
<template v-if="layout === 'month-and-year'">
<div class="flex items-center justify-center gap-1">
<ReuseMonthTemplate :date="date" />
<ReuseYearTemplate :date="date" />
</div>
</template>
<template v-else-if="layout === 'month-only'">
<div class="flex items-center justify-center gap-1">
<ReuseMonthTemplate :date="date" />
{{ formatter.custom(toDate(date), { year: "numeric" }) }}
</div>
</template>
<template v-else-if="layout === 'year-only'">
<div class="flex items-center justify-center gap-1">
{{ formatter.custom(toDate(date), { month: "short" }) }}
<ReuseYearTemplate :date="date" />
</div>
</template>
<template v-else>
<CalendarHeading />
</template>
</slot>
</CalendarHeader>
<div class="flex flex-col gap-y-4 mt-4 sm:flex-row sm:gap-x-4 sm:gap-y-0">

View File

@@ -6,7 +6,7 @@ import { cn } from "@/lib/utils";
const props = defineProps({
date: { type: null, required: true },
asChild: { type: Boolean, required: false },
as: { type: [String, Object, Function], required: false },
as: { type: null, required: false },
class: { type: null, required: false },
});

View File

@@ -8,7 +8,7 @@ const props = defineProps({
day: { type: null, required: true },
month: { type: null, required: true },
asChild: { type: Boolean, required: false },
as: { type: [String, Object, Function], required: false, default: "button" },
as: { type: null, required: false, default: "button" },
class: { type: null, required: false },
});

View File

@@ -5,7 +5,7 @@ import { cn } from "@/lib/utils";
const props = defineProps({
asChild: { type: Boolean, required: false },
as: { type: [String, Object, Function], required: false },
as: { type: null, required: false },
class: { type: null, required: false },
});

View File

@@ -3,7 +3,7 @@ import { CalendarGridBody } from "reka-ui";
const props = defineProps({
asChild: { type: Boolean, required: false },
as: { type: [String, Object, Function], required: false },
as: { type: null, required: false },
});
</script>

View File

@@ -3,7 +3,7 @@ import { CalendarGridHead } from "reka-ui";
const props = defineProps({
asChild: { type: Boolean, required: false },
as: { type: [String, Object, Function], required: false },
as: { type: null, required: false },
class: { type: null, required: false },
});
</script>

View File

@@ -5,7 +5,7 @@ import { cn } from "@/lib/utils";
const props = defineProps({
asChild: { type: Boolean, required: false },
as: { type: [String, Object, Function], required: false },
as: { type: null, required: false },
class: { type: null, required: false },
});

View File

@@ -5,7 +5,7 @@ import { cn } from "@/lib/utils";
const props = defineProps({
asChild: { type: Boolean, required: false },
as: { type: [String, Object, Function], required: false },
as: { type: null, required: false },
class: { type: null, required: false },
});
@@ -19,7 +19,7 @@ const forwardedProps = useForwardProps(delegatedProps);
data-slot="calendar-head-cell"
:class="
cn(
'text-muted-foreground rounded-md w-8 font-normal text-[0.8rem]',
'text-muted-foreground rounded-md flex-1 font-normal text-[0.8rem]',
props.class,
)
"

View File

@@ -5,7 +5,7 @@ import { cn } from "@/lib/utils";
const props = defineProps({
asChild: { type: Boolean, required: false },
as: { type: [String, Object, Function], required: false },
as: { type: null, required: false },
class: { type: null, required: false },
});
@@ -18,7 +18,10 @@ const forwardedProps = useForwardProps(delegatedProps);
<CalendarHeader
data-slot="calendar-header"
:class="
cn('flex justify-center pt-1 relative items-center w-full', props.class)
cn(
'flex justify-center pt-1 relative items-center w-full px-8',
props.class,
)
"
v-bind="forwardedProps"
>

View File

@@ -5,7 +5,7 @@ import { cn } from "@/lib/utils";
const props = defineProps({
asChild: { type: Boolean, required: false },
as: { type: [String, Object, Function], required: false },
as: { type: null, required: false },
class: { type: null, required: false },
});

View File

@@ -8,7 +8,7 @@ import { buttonVariants } from '@/components/ui/button';
const props = defineProps({
nextPage: { type: Function, required: false },
asChild: { type: Boolean, required: false },
as: { type: [String, Object, Function], required: false },
as: { type: null, required: false },
class: { type: null, required: false },
});
@@ -23,7 +23,6 @@ const forwardedProps = useForwardProps(delegatedProps);
:class="
cn(
buttonVariants({ variant: 'outline' }),
'absolute right-1',
'size-7 bg-transparent p-0 opacity-50 hover:opacity-100',
props.class,
)

View File

@@ -8,7 +8,7 @@ import { buttonVariants } from '@/components/ui/button';
const props = defineProps({
prevPage: { type: Function, required: false },
asChild: { type: Boolean, required: false },
as: { type: [String, Object, Function], required: false },
as: { type: null, required: false },
class: { type: null, required: false },
});
@@ -23,7 +23,6 @@ const forwardedProps = useForwardProps(delegatedProps);
:class="
cn(
buttonVariants({ variant: 'outline' }),
'absolute left-1',
'size-7 bg-transparent p-0 opacity-50 hover:opacity-100',
props.class,
)

View File

@@ -0,0 +1,51 @@
<script setup>
import { reactiveOmit, useVModel } from "@vueuse/core";
import { ChevronDownIcon } from "lucide-vue-next";
import { cn } from "@/lib/utils";
defineOptions({
inheritAttrs: false,
});
const props = defineProps({
modelValue: { type: null, required: false },
class: { type: null, required: false },
});
const emit = defineEmits(["update:modelValue"]);
const modelValue = useVModel(props, "modelValue", emit, {
passive: true,
defaultValue: "",
});
const delegatedProps = reactiveOmit(props, "class");
</script>
<template>
<div
class="group/native-select relative w-fit has-[select:disabled]:opacity-50"
data-slot="native-select-wrapper"
>
<select
v-bind="{ ...$attrs, ...delegatedProps }"
v-model="modelValue"
data-slot="native-select"
:class="
cn(
'border-input placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground dark:bg-input/30 dark:hover:bg-input/50 h-9 w-full min-w-0 appearance-none rounded-md border bg-transparent px-3 py-2 pr-9 text-sm shadow-xs transition-[color,box-shadow] outline-none disabled:pointer-events-none disabled:cursor-not-allowed',
'focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]',
'aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive',
props.class,
)
"
>
<slot />
</select>
<ChevronDownIcon
class="text-muted-foreground pointer-events-none absolute top-1/2 right-3.5 size-4 -translate-y-1/2 opacity-50 select-none"
aria-hidden="true"
data-slot="native-select-icon"
/>
</div>
</template>

View File

@@ -0,0 +1,19 @@
<!-- @fallthroughAttributes true -->
<!-- @strictTemplates true -->
<script setup>
import { cn } from "@/lib/utils";
const props = defineProps({
class: { type: null, required: false },
});
</script>
<template>
<optgroup
data-slot="native-select-optgroup"
:class="cn('bg-popover text-popover-foreground', props.class)"
>
<slot />
</optgroup>
</template>

View File

@@ -0,0 +1,19 @@
<!-- @fallthroughAttributes true -->
<!-- @strictTemplates true -->
<script setup>
import { cn } from "@/lib/utils";
const props = defineProps({
class: { type: null, required: false },
});
</script>
<template>
<option
data-slot="native-select-option"
:class="cn('bg-popover text-popover-foreground', props.class)"
>
<slot />
</option>
</template>

View File

@@ -0,0 +1,3 @@
export { default as NativeSelect } from "./NativeSelect.vue";
export { default as NativeSelectOptGroup } from "./NativeSelectOptGroup.vue";
export { default as NativeSelectOption } from "./NativeSelectOption.vue";

View File

@@ -0,0 +1,45 @@
<script setup>
import { reactiveOmit } from "@vueuse/core";
import { NavigationMenuRoot, useForwardPropsEmits } from "reka-ui";
import { cn } from "@/lib/utils";
import NavigationMenuViewport from "./NavigationMenuViewport.vue";
const props = defineProps({
modelValue: { type: String, required: false },
defaultValue: { type: String, required: false },
dir: { type: String, required: false },
orientation: { type: String, required: false },
delayDuration: { type: Number, required: false },
skipDelayDuration: { type: Number, required: false },
disableClickTrigger: { type: Boolean, required: false },
disableHoverTrigger: { type: Boolean, required: false },
disablePointerLeaveClose: { type: Boolean, required: false },
unmountOnHide: { type: Boolean, required: false },
asChild: { type: Boolean, required: false },
as: { type: null, required: false },
class: { type: null, required: false },
viewport: { type: Boolean, required: false, default: true },
});
const emits = defineEmits(["update:modelValue"]);
const delegatedProps = reactiveOmit(props, "class", "viewport");
const forwarded = useForwardPropsEmits(delegatedProps, emits);
</script>
<template>
<NavigationMenuRoot
v-slot="slotProps"
data-slot="navigation-menu"
:data-viewport="viewport"
v-bind="forwarded"
:class="
cn(
'group/navigation-menu relative flex max-w-max flex-1 items-center justify-center',
props.class,
)
"
>
<slot v-bind="slotProps" />
<NavigationMenuViewport v-if="viewport" />
</NavigationMenuRoot>
</template>

View File

@@ -0,0 +1,39 @@
<script setup>
import { reactiveOmit } from "@vueuse/core";
import { NavigationMenuContent, useForwardPropsEmits } from "reka-ui";
import { cn } from "@/lib/utils";
const props = defineProps({
forceMount: { type: Boolean, required: false },
disableOutsidePointerEvents: { type: Boolean, required: false },
asChild: { type: Boolean, required: false },
as: { type: null, required: false },
class: { type: null, required: false },
});
const emits = defineEmits([
"escapeKeyDown",
"pointerDownOutside",
"focusOutside",
"interactOutside",
]);
const delegatedProps = reactiveOmit(props, "class");
const forwarded = useForwardPropsEmits(delegatedProps, emits);
</script>
<template>
<NavigationMenuContent
data-slot="navigation-menu-content"
v-bind="forwarded"
:class="
cn(
'data-[motion^=from-]:animate-in data-[motion^=to-]:animate-out data-[motion^=from-]:fade-in data-[motion^=to-]:fade-out data-[motion=from-end]:slide-in-from-right-52 data-[motion=from-start]:slide-in-from-left-52 data-[motion=to-end]:slide-out-to-right-52 data-[motion=to-start]:slide-out-to-left-52 top-0 left-0 w-full p-2 pr-2.5 md:absolute md:w-auto',
'group-data-[viewport=false]/navigation-menu:bg-popover group-data-[viewport=false]/navigation-menu:text-popover-foreground group-data-[viewport=false]/navigation-menu:data-[state=open]:animate-in group-data-[viewport=false]/navigation-menu:data-[state=closed]:animate-out group-data-[viewport=false]/navigation-menu:data-[state=closed]:zoom-out-95 group-data-[viewport=false]/navigation-menu:data-[state=open]:zoom-in-95 group-data-[viewport=false]/navigation-menu:data-[state=open]:fade-in-0 group-data-[viewport=false]/navigation-menu:data-[state=closed]:fade-out-0 group-data-[viewport=false]/navigation-menu:top-full group-data-[viewport=false]/navigation-menu:mt-1.5 group-data-[viewport=false]/navigation-menu:overflow-hidden group-data-[viewport=false]/navigation-menu:rounded-md group-data-[viewport=false]/navigation-menu:border group-data-[viewport=false]/navigation-menu:shadow group-data-[viewport=false]/navigation-menu:duration-200 **:data-[slot=navigation-menu-link]:focus:ring-0 **:data-[slot=navigation-menu-link]:focus:outline-none',
props.class,
)
"
>
<slot />
</NavigationMenuContent>
</template>

View File

@@ -0,0 +1,33 @@
<script setup>
import { reactiveOmit } from "@vueuse/core";
import { NavigationMenuIndicator, useForwardProps } from "reka-ui";
import { cn } from "@/lib/utils";
const props = defineProps({
forceMount: { type: Boolean, required: false },
asChild: { type: Boolean, required: false },
as: { type: null, required: false },
class: { type: null, required: false },
});
const delegatedProps = reactiveOmit(props, "class");
const forwardedProps = useForwardProps(delegatedProps);
</script>
<template>
<NavigationMenuIndicator
data-slot="navigation-menu-indicator"
v-bind="forwardedProps"
:class="
cn(
'data-[state=visible]:animate-in data-[state=hidden]:animate-out data-[state=hidden]:fade-out data-[state=visible]:fade-in top-full z-[1] flex h-1.5 items-end justify-center overflow-hidden',
props.class,
)
"
>
<div
class="bg-border relative top-[60%] h-2 w-2 rotate-45 rounded-tl-sm shadow-md"
/>
</NavigationMenuIndicator>
</template>

View File

@@ -0,0 +1,24 @@
<script setup>
import { reactiveOmit } from "@vueuse/core";
import { NavigationMenuItem } from "reka-ui";
import { cn } from "@/lib/utils";
const props = defineProps({
value: { type: String, required: false },
asChild: { type: Boolean, required: false },
as: { type: null, required: false },
class: { type: null, required: false },
});
const delegatedProps = reactiveOmit(props, "class");
</script>
<template>
<NavigationMenuItem
data-slot="navigation-menu-item"
v-bind="delegatedProps"
:class="cn('relative', props.class)"
>
<slot />
</NavigationMenuItem>
</template>

View File

@@ -0,0 +1,31 @@
<script setup>
import { reactiveOmit } from "@vueuse/core";
import { NavigationMenuLink, useForwardPropsEmits } from "reka-ui";
import { cn } from "@/lib/utils";
const props = defineProps({
active: { type: Boolean, required: false },
asChild: { type: Boolean, required: false },
as: { type: null, required: false },
class: { type: null, required: false },
});
const emits = defineEmits(["select"]);
const delegatedProps = reactiveOmit(props, "class");
const forwarded = useForwardPropsEmits(delegatedProps, emits);
</script>
<template>
<NavigationMenuLink
data-slot="navigation-menu-link"
v-bind="forwarded"
:class="
cn(
'data-active:focus:bg-accent data-active:hover:bg-accent data-active:bg-accent/50 data-active:text-accent-foreground hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground ring-ring/10 dark:ring-ring/20 dark:outline-ring/40 outline-ring/50 [&_svg:not([class*=\'text-\'])]:text-muted-foreground flex flex-col gap-1 rounded-sm p-2 text-sm transition-[color,box-shadow] focus-visible:ring-4 focus-visible:outline-1 [&_svg:not([class*=\'size-\'])]:size-4',
props.class,
)
"
>
<slot />
</NavigationMenuLink>
</template>

View File

@@ -0,0 +1,30 @@
<script setup>
import { reactiveOmit } from "@vueuse/core";
import { NavigationMenuList, useForwardProps } from "reka-ui";
import { cn } from "@/lib/utils";
const props = defineProps({
asChild: { type: Boolean, required: false },
as: { type: null, required: false },
class: { type: null, required: false },
});
const delegatedProps = reactiveOmit(props, "class");
const forwardedProps = useForwardProps(delegatedProps);
</script>
<template>
<NavigationMenuList
data-slot="navigation-menu-list"
v-bind="forwardedProps"
:class="
cn(
'group flex flex-1 list-none items-center justify-center gap-1',
props.class,
)
"
>
<slot />
</NavigationMenuList>
</template>

View File

@@ -0,0 +1,32 @@
<script setup>
import { reactiveOmit } from "@vueuse/core";
import { ChevronDown } from "lucide-vue-next";
import { NavigationMenuTrigger, useForwardProps } from "reka-ui";
import { cn } from "@/lib/utils";
import { navigationMenuTriggerStyle } from ".";
const props = defineProps({
disabled: { type: Boolean, required: false },
asChild: { type: Boolean, required: false },
as: { type: null, required: false },
class: { type: null, required: false },
});
const delegatedProps = reactiveOmit(props, "class");
const forwardedProps = useForwardProps(delegatedProps);
</script>
<template>
<NavigationMenuTrigger
data-slot="navigation-menu-trigger"
v-bind="forwardedProps"
:class="cn(navigationMenuTriggerStyle(), 'group', props.class)"
>
<slot />
<ChevronDown
class="relative top-[1px] ml-1 size-3 transition duration-300 group-data-[state=open]:rotate-180"
aria-hidden="true"
/>
</NavigationMenuTrigger>
</template>

View File

@@ -0,0 +1,32 @@
<script setup>
import { reactiveOmit } from "@vueuse/core";
import { NavigationMenuViewport, useForwardProps } from "reka-ui";
import { cn } from "@/lib/utils";
const props = defineProps({
forceMount: { type: Boolean, required: false },
align: { type: String, required: false },
asChild: { type: Boolean, required: false },
as: { type: null, required: false },
class: { type: null, required: false },
});
const delegatedProps = reactiveOmit(props, "class");
const forwardedProps = useForwardProps(delegatedProps);
</script>
<template>
<div class="absolute top-full left-0 isolate z-50 flex justify-center">
<NavigationMenuViewport
data-slot="navigation-menu-viewport"
v-bind="forwardedProps"
:class="
cn(
'origin-top-center bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-90 relative mt-1.5 h-[var(--reka-navigation-menu-viewport-height)] w-full overflow-hidden rounded-md border shadow md:w-[var(--reka-navigation-menu-viewport-width)] left-[var(--reka-navigation-menu-viewport-left)]',
props.class,
)
"
/>
</div>
</template>

View File

@@ -0,0 +1,14 @@
import { cva } from "class-variance-authority";
export { default as NavigationMenu } from "./NavigationMenu.vue";
export { default as NavigationMenuContent } from "./NavigationMenuContent.vue";
export { default as NavigationMenuIndicator } from "./NavigationMenuIndicator.vue";
export { default as NavigationMenuItem } from "./NavigationMenuItem.vue";
export { default as NavigationMenuLink } from "./NavigationMenuLink.vue";
export { default as NavigationMenuList } from "./NavigationMenuList.vue";
export { default as NavigationMenuTrigger } from "./NavigationMenuTrigger.vue";
export { default as NavigationMenuViewport } from "./NavigationMenuViewport.vue";
export const navigationMenuTriggerStyle = cva(
"group inline-flex h-9 w-max items-center justify-center rounded-md bg-background px-4 py-2 text-sm font-medium hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground disabled:pointer-events-none disabled:opacity-50 data-[state=open]:hover:bg-accent data-[state=open]:text-accent-foreground data-[state=open]:focus:bg-accent data-[state=open]:bg-accent/50 focus-visible:ring-ring/50 outline-none transition-[color,box-shadow] focus-visible:ring-[3px] focus-visible:outline-1",
);

View File

@@ -0,0 +1,31 @@
<script setup>
import { reactiveOmit } from "@vueuse/core";
import { StepperRoot, useForwardPropsEmits } from "reka-ui";
import { cn } from "@/lib/utils";
const props = defineProps({
defaultValue: { type: Number, required: false },
orientation: { type: String, required: false },
dir: { type: String, required: false },
modelValue: { type: Number, required: false },
linear: { type: Boolean, required: false },
asChild: { type: Boolean, required: false },
as: { type: null, required: false },
class: { type: null, required: false },
});
const emits = defineEmits(["update:modelValue"]);
const delegatedProps = reactiveOmit(props, "class");
const forwarded = useForwardPropsEmits(delegatedProps, emits);
</script>
<template>
<StepperRoot
v-slot="slotProps"
:class="cn('flex gap-2', props.class)"
v-bind="forwarded"
>
<slot v-bind="slotProps" />
</StepperRoot>
</template>

View File

@@ -0,0 +1,25 @@
<script setup>
import { reactiveOmit } from "@vueuse/core";
import { StepperDescription, useForwardProps } from "reka-ui";
import { cn } from "@/lib/utils";
const props = defineProps({
asChild: { type: Boolean, required: false },
as: { type: null, required: false },
class: { type: null, required: false },
});
const delegatedProps = reactiveOmit(props, "class");
const forwarded = useForwardProps(delegatedProps);
</script>
<template>
<StepperDescription
v-slot="slotProps"
v-bind="forwarded"
:class="cn('text-xs text-muted-foreground', props.class)"
>
<slot v-bind="slotProps" />
</StepperDescription>
</template>

View File

@@ -0,0 +1,36 @@
<script setup>
import { reactiveOmit } from "@vueuse/core";
import { StepperIndicator, useForwardProps } from "reka-ui";
import { cn } from "@/lib/utils";
const props = defineProps({
asChild: { type: Boolean, required: false },
as: { type: null, required: false },
class: { type: null, required: false },
});
const delegatedProps = reactiveOmit(props, "class");
const forwarded = useForwardProps(delegatedProps);
</script>
<template>
<StepperIndicator
v-slot="slotProps"
v-bind="forwarded"
:class="
cn(
'inline-flex items-center justify-center rounded-full text-muted-foreground/50 w-8 h-8',
// Disabled
'group-data-[disabled]:text-muted-foreground group-data-[disabled]:opacity-50',
// Active
'group-data-[state=active]:bg-primary group-data-[state=active]:text-primary-foreground',
// Completed
'group-data-[state=completed]:bg-accent group-data-[state=completed]:text-accent-foreground',
props.class,
)
"
>
<slot v-bind="slotProps" />
</StepperIndicator>
</template>

View File

@@ -0,0 +1,33 @@
<script setup>
import { reactiveOmit } from "@vueuse/core";
import { StepperItem, useForwardProps } from "reka-ui";
import { cn } from "@/lib/utils";
const props = defineProps({
step: { type: Number, required: true },
disabled: { type: Boolean, required: false },
completed: { type: Boolean, required: false },
asChild: { type: Boolean, required: false },
as: { type: null, required: false },
class: { type: null, required: false },
});
const delegatedProps = reactiveOmit(props, "class");
const forwarded = useForwardProps(delegatedProps);
</script>
<template>
<StepperItem
v-slot="slotProps"
v-bind="forwarded"
:class="
cn(
'flex items-center gap-2 group data-[disabled]:pointer-events-none',
props.class,
)
"
>
<slot v-bind="slotProps" />
</StepperItem>
</template>

View File

@@ -0,0 +1,33 @@
<script setup>
import { reactiveOmit } from "@vueuse/core";
import { StepperSeparator, useForwardProps } from "reka-ui";
import { cn } from "@/lib/utils";
const props = defineProps({
orientation: { type: String, required: false },
decorative: { type: Boolean, required: false },
asChild: { type: Boolean, required: false },
as: { type: null, required: false },
class: { type: null, required: false },
});
const delegatedProps = reactiveOmit(props, "class");
const forwarded = useForwardProps(delegatedProps);
</script>
<template>
<StepperSeparator
v-bind="forwarded"
:class="
cn(
'bg-muted',
// Disabled
'group-data-[disabled]:bg-muted group-data-[disabled]:opacity-50',
// Completed
'group-data-[state=completed]:bg-accent',
props.class,
)
"
/>
</template>

View File

@@ -0,0 +1,24 @@
<script setup>
import { reactiveOmit } from "@vueuse/core";
import { StepperTitle, useForwardProps } from "reka-ui";
import { cn } from "@/lib/utils";
const props = defineProps({
asChild: { type: Boolean, required: false },
as: { type: null, required: false },
class: { type: null, required: false },
});
const delegatedProps = reactiveOmit(props, "class");
const forwarded = useForwardProps(delegatedProps);
</script>
<template>
<StepperTitle
v-bind="forwarded"
:class="cn('text-md font-semibold whitespace-nowrap', props.class)"
>
<slot />
</StepperTitle>
</template>

View File

@@ -0,0 +1,29 @@
<script setup>
import { reactiveOmit } from "@vueuse/core";
import { StepperTrigger, useForwardProps } from "reka-ui";
import { cn } from "@/lib/utils";
const props = defineProps({
asChild: { type: Boolean, required: false },
as: { type: null, required: false },
class: { type: null, required: false },
});
const delegatedProps = reactiveOmit(props, "class");
const forwarded = useForwardProps(delegatedProps);
</script>
<template>
<StepperTrigger
v-bind="forwarded"
:class="
cn(
'p-1 flex flex-col items-center text-center gap-1 rounded-md',
props.class,
)
"
>
<slot />
</StepperTrigger>
</template>

View File

@@ -0,0 +1,7 @@
export { default as Stepper } from "./Stepper.vue";
export { default as StepperDescription } from "./StepperDescription.vue";
export { default as StepperIndicator } from "./StepperIndicator.vue";
export { default as StepperItem } from "./StepperItem.vue";
export { default as StepperSeparator } from "./StepperSeparator.vue";
export { default as StepperTitle } from "./StepperTitle.vue";
export { default as StepperTrigger } from "./StepperTrigger.vue";

View File

@@ -0,0 +1,36 @@
import { useUserStore } from "@/stores/user"
import { computed } from "vue";
import { Role } from "@shared/types/roles"
export function useAuth() {
const userStore = useUserStore();
// Account status control
const accountStatus = computed(() => userStore.state);
// RBAC
const roles = computed<string[]>(() => {
return userStore.user?.roleData?.map((r: Role) => r.name) ?? [];
});
function isDev() {
return roles.value.includes('Dev');
}
function hasRole(roleName: string): boolean {
if (isDev()) return true;
return roles.value.includes(roleName);
}
function hasAnyRole(roleNames: string[]): boolean {
if (isDev()) return true;
return roles.value.some(name => roleNames.includes(name))
}
function hasAllRoles(roleNames: string[]): boolean {
if (isDev()) return true;
return roles.value.every(name => roleNames.includes(name))
}
return { hasRole, hasAnyRole, hasAllRoles, accountStatus }
}

View File

@@ -9,17 +9,23 @@ import FormCheckbox from './components/form/FormCheckbox.vue'
import FormInput from './components/form/FormInput.vue'
import * as Sentry from "@sentry/vue";
import { initMatomo } from "@certible/use-matomo"
const app = createApp(App)
app.use(createPinia())
app.use(router)
if (!!import.meta.env.VITE_DISABLE_GLITCHTIP) {
if (import.meta.env.VITE_DISABLE_GLITCHTIP === "true") {
console.log("Glitchtip disabled");
} else {
let dsn = import.meta.env.VITE_GLITCHTIP_DSN;
let environment = import.meta.env.VITE_ENVIRONMENT;
let release = import.meta.env.VITE_APPLICATION_VERSION;
Sentry.init({
app,
dsn: dsn,
@@ -28,22 +34,11 @@ if (!!import.meta.env.VITE_DISABLE_GLITCHTIP) {
],
tracesSampleRate: 0.01,
environment: environment,
release: 'release tag'
release: release
});
}
if (!!import.meta.env.VITE_DISABLE_MATOMO) {
console.log("Matomo init")
app.use(initMatomo({
host: 'https://stats.nexuszone.net/',
siteId: 4,
trackRouter: true,
}));
}
app.component("FormInput", FormInput)
app.component("FormCheckbox", FormCheckbox)
app.mount('#app')
// window._paq.push(['trackPageView']);

View File

@@ -2,14 +2,16 @@
import ApplicationChat from '@/components/application/ApplicationChat.vue';
import ApplicationForm from '@/components/application/ApplicationForm.vue';
import { onMounted, ref } from 'vue';
import { ApplicationData, approveApplication, denyApplication, loadApplication, postApplication, postChatMessage, ApplicationStatus } from '@/api/application';
import { approveApplication, denyApplication, loadApplication, postApplication, postChatMessage, getMyApplication, postAdminChatMessage } from '@/api/application';
import { useRoute } from 'vue-router';
import Button from '@/components/ui/button/Button.vue';
import { CheckIcon, XIcon } from 'lucide-vue-next';
import Unauthorized from './Unauthorized.vue';
import { ApplicationData, ApplicationFull, ApplicationStatus, CommentRow } from '@shared/types/application';
const appData = ref<ApplicationData>(null);
const appID = ref<number | null>(null);
const chatData = ref<object[]>([])
const chatData = ref<CommentRow[]>([])
const readOnly = ref<boolean>(false);
const newApp = ref<boolean>(null);
const status = ref<ApplicationStatus>(null);
@@ -17,35 +19,68 @@ const decisionDate = ref<Date | null>(null);
const submitDate = ref<Date | null>(null);
const loading = ref<boolean>(true);
const member_name = ref<string>();
const props = defineProps<{
mode?: "create" | "view-self" | "view-recruiter" | "view-self-id"
}>()
const finalMode = ref<"create" | "view-self" | "view-recruiter" | "view-self-id">("create");
function loadData(raw: ApplicationFull) {
const data = raw.application;
appID.value = data.id;
appData.value = data.app_data;
chatData.value = raw.comments;
status.value = data.app_status;
decisionDate.value = new Date(data.decision_at);
submitDate.value = data.submitted_at ? new Date(data.submitted_at) : null;
member_name.value = data.member_name;
newApp.value = false;
readOnly.value = true;
}
const route = useRoute();
const unauthorized = ref(false);
onMounted(async () => {
try {
//get app ID from URL param
const router = useRoute();
const appIDRaw = router.params.id;
if (appIDRaw === undefined) {
//new app
appData.value = null
readOnly.value = false;
newApp.value = true;
} else {
//load app
const raw = await loadApplication(appIDRaw.toString());
const data = raw.application;
appID.value = data.id;
appData.value = data.app_data;
chatData.value = raw.comments;
status.value = data.app_status;
decisionDate.value = new Date(data.decision_at);
submitDate.value = data.submitted_at ? new Date(data.submitted_at) : null;
member_name.value = data.member_name;
newApp.value = false;
readOnly.value = true;
}
} catch (e) {
console.error(e);
//recruiter mode
if (props.mode === 'view-recruiter') {
finalMode.value = 'view-recruiter';
loadData(await loadApplication(Number(route.params.id), true))
}
//viewer mode
if (props.mode === 'view-self') {
finalMode.value = 'view-self';
loadData(await loadApplication("me"))
}
//creator mode
if (props.mode === 'create') {
finalMode.value = 'create';
appData.value = null
readOnly.value = false;
newApp.value = true;
}
if (props.mode === 'view-self-id') {
finalMode.value = 'view-self-id';
try {
let raw = await getMyApplication(Number(route.params.id))
loadData(raw);
unauthorized.value = false;
} catch (error) {
if (error.message === "Unauthorized") {
unauthorized.value = true;
} else {
console.error(error);
}
}
}
loading.value = false;
})
@@ -53,14 +88,20 @@ async function postComment(comment) {
chatData.value.push(await postChatMessage(comment, appID.value));
}
async function postCommentInternal(comment) {
chatData.value.push(await postAdminChatMessage(comment, appID.value));
}
const emit = defineEmits(['submit']);
async function postApp(appData) {
console.log("test")
const res = await postApplication(appData);
if (res.ok) {
readOnly.value = true;
newApp.value = false;
emit('submit');
}
// TODO: Handle fail to post
// TODO: Handle fail to post
}
async function handleApprove(id) {
@@ -74,54 +115,61 @@ async function handleDeny(id) {
</script>
<template>
<div v-if="!loading" class="max-w-3xl mx-auto my-20">
<div v-if="!newApp" class="flex flex-row justify-between items-center py-2 mb-8">
<!-- Application header -->
<div>
<h3 class="scroll-m-20 text-2xl font-semibold tracking-tight">{{ member_name }}</h3>
<p class="text-muted-foreground">Submitted: {{ submitDate.toLocaleString("en-US", {
year: "numeric",
month: "long",
day: "numeric",
hour: "2-digit",
minute: "2-digit"
}) }}</p>
</div>
<div>
<h3 class="text-right" :class="[
'font-semibold',
status === ApplicationStatus.Pending && 'text-yellow-500',
status === ApplicationStatus.Accepted && 'text-green-500',
status === ApplicationStatus.Denied && 'text-red-500'
]">{{ status }}</h3>
<p v-if="status != ApplicationStatus.Pending" class="text-muted-foreground">{{ status }}: {{
decisionDate.toLocaleString("en-US", {
<div v-if="!loading" class="w-full h-20">
<div v-if="unauthorized" class="flex justify-center w-full my-10">
You do not have permission to view this application.
</div>
<div v-else>
<div v-if="!newApp" class="flex flex-row justify-between items-center py-2 mb-8">
<!-- Application header -->
<div>
<h3 class="scroll-m-20 text-2xl font-semibold tracking-tight">{{ member_name }}</h3>
<p class="text-muted-foreground">Submitted: {{ submitDate.toLocaleString("en-US", {
year: "numeric",
month: "long",
day: "numeric",
hour: "2-digit",
minute: "2-digit"
}) }}</p>
<div class="mt-2" v-else>
<Button variant="success" class="mr-2" :onclick="() => { handleApprove(appID) }">
<CheckIcon></CheckIcon>
</Button>
<Button variant="destructive" :onClick="() => { handleDeny(appID) }">
<XIcon></XIcon>
</Button>
</div>
<div>
<h3 class="text-right" :class="[
'font-semibold',
status === ApplicationStatus.Pending && 'text-yellow-500',
status === ApplicationStatus.Accepted && 'text-green-500',
status === ApplicationStatus.Denied && 'text-red-500'
]">{{ status }}</h3>
<p v-if="status != ApplicationStatus.Pending" class="text-muted-foreground">{{ status }}: {{
decisionDate.toLocaleString("en-US", {
year: "numeric",
month: "long",
day: "numeric",
hour: "2-digit",
minute: "2-digit"
}) }}</p>
<div class="mt-2" v-else-if="finalMode === 'view-recruiter'">
<Button variant="success" class="mr-2" :onclick="() => { handleApprove(appID) }">
<CheckIcon></CheckIcon>
</Button>
<Button variant="destructive" :onClick="() => { handleDeny(appID) }">
<XIcon></XIcon>
</Button>
</div>
</div>
</div>
<div v-else class="flex flex-row justify-between items-center py-2 mb-8">
<h3 class="scroll-m-20 text-2xl font-semibold tracking-tight">Apply to join the 17th Rangers</h3>
</div>
<ApplicationForm :read-only="readOnly" :data="appData" @submit="(e) => { postApp(e) }" class="mb-7">
</ApplicationForm>
<div v-if="!newApp" class="pb-15">
<h3 class="scroll-m-20 text-2xl font-semibold tracking-tight mb-4">Discussion</h3>
<ApplicationChat :messages="chatData" @post="postComment" @post-internal="postCommentInternal">
</ApplicationChat>
</div>
</div>
<div v-else class="flex flex-row justify-between items-center py-2 mb-8">
<h3 class="scroll-m-20 text-2xl font-semibold tracking-tight">Apply to join the 17th Rangers</h3>
</div>
<ApplicationForm :read-only="readOnly" :data="appData" @submit="(e) => { postApp(e) }" class="mb-7">
</ApplicationForm>
<div v-if="!newApp">
<h3 class="scroll-m-20 text-2xl font-semibold tracking-tight mb-4">Discussion</h3>
<ApplicationChat :messages="chatData" @post="postComment"></ApplicationChat>
</div>
</div>
<!-- TODO: Implement some kinda loading screen -->
<div v-else>Loading</div>
<div v-else class="flex items-center justify-center h-full">Loading</div>
</template>

View File

@@ -3,15 +3,14 @@ import { ref, watch, nextTick, computed, onMounted } from 'vue'
import FullCalendar from '@fullcalendar/vue3'
import dayGridPlugin from '@fullcalendar/daygrid'
import interactionPlugin from '@fullcalendar/interaction'
import { X, Clock, MapPin, User, ListTodo, ChevronLeft, ChevronRight, Plus } from 'lucide-vue-next'
import { ChevronLeft, ChevronRight, Plus } from 'lucide-vue-next'
import CreateCalendarEvent from '@/components/calendar/CreateCalendarEvent.vue'
import { getCalendarEvent, getMonthCalendarEvents } from '@/api/calendar'
import { CalendarEvent, CalendarEventShort } from '@shared/types/calendar'
import { Calendar } from '@fullcalendar/core'
import { CalendarEvent } from '@shared/types/calendar'
import ViewCalendarEvent from '@/components/calendar/ViewCalendarEvent.vue'
import { useRouter, useRoute } from 'vue-router'
import { useCalendarEvents } from '@/composables/useCalendarEvents'
import { useCalendarNavigation } from '@/composables/useCalendarNavigation'
import { useUserStore } from '@/stores/user'
const monthLabels = [
'January', 'February', 'March', 'April', 'May', 'June',
@@ -24,13 +23,14 @@ function api() {
const router = useRouter();
const route = useRoute();
const userStore = useUserStore();
function buildFullDate(month: number, year: number): Date {
return new Date(year, month, 1); //default to first of month
}
const { selectedMonth, selectedYear, years, goPrev, goNext, goToday, onDatesSet, goToSelectedDate } = useCalendarNavigation(api)
const { events, loadEvents} = useCalendarEvents(selectedMonth, selectedYear);
const { events, loadEvents } = useCalendarEvents(selectedMonth, selectedYear);
const panelOpen = ref(false)
const activeEvent = ref<CalendarEvent | null>(null)
@@ -48,6 +48,7 @@ const dialogRef = ref<any>(null)
// NEW: handle day/time slot clicks to start creating an event
function onDateClick(arg: { dateStr: string }) {
if (!userStore.isLoggedIn) return;
dialogRef.value?.openDialog(arg.dateStr);
// For now, just open the panel with a draft payload.
// activeEvent.value = {
@@ -202,7 +203,7 @@ onMounted(() => {
@click="goToday">
Today
</button>
<button
<button v-if="userStore.isLoggedIn"
class="cursor-pointer ml-1 inline-flex items-center gap-1.5 rounded-md bg-primary px-3 py-1.5 text-sm text-primary-foreground hover:opacity-90"
@click="onCreateEvent">
<Plus class="h-4 w-4" />
@@ -216,7 +217,8 @@ onMounted(() => {
<aside v-if="panelOpen"
class="3xl:w-lg 2xl:w-md border-l bg-card text-foreground flex flex-col overflow-auto scrollbar-themed"
:style="{ height: 'calc(100vh - 61px)', position: 'sticky', top: '64px' }">
<ViewCalendarEvent ref="eventViewRef" @close="() => { router.push('/calendar'); }" @reload="loadEvents()" @edit="(val) => {dialogRef.openDialog(null, 'edit', val)}">
<ViewCalendarEvent ref="eventViewRef" @close="() => { router.push('/calendar'); }"
@reload="loadEvents()" @edit="(val) => { dialogRef.openDialog(null, 'edit', val) }">
</ViewCalendarEvent>
</aside>
</div>

View File

@@ -0,0 +1,11 @@
<script setup lang="ts">
</script>
<template>
<div>
Alo
<iframe src="https://docs.iceberg-gaming.com/" ></iframe>
</div>
</template>

View File

@@ -13,17 +13,18 @@ function goToApplication() {
</script>
<template>
<div v-if="user.state == 'guest'"
class="min-h-screen flex flex-col items-center justify-center text-center bg-neutral-950 text-white px-4">
<h1 class="text-4xl font-bold mb-4">Welcome to the 17th</h1>
<p class="text-neutral-400 mb-8 max-w-md">
To join our unit, please fill out an application to continue.
</p>
<Button @click="goToApplication" class="px-6 py-3 text-lg">
Begin Application
</Button>
</div>
<div v-else>
HOMEPAGEEEEEEEEEEEEEEEEEEE
<div>
<div v-if="user.state == 'guest'" class="flex flex-col items-center justify-center">
<h1 class="text-4xl font-bold mb-4">Welcome to the 17th</h1>
<p class="text-neutral-400 mb-8 max-w-md">
To join our unit, please fill out an application to continue.
</p>
<Button @click="goToApplication" class="px-6 py-3 text-lg">
Begin Application
</Button>
</div>
<div v-else>
HOMEPAGEEEEEEEEEEEEEEEEEEE
</div>
</div>
</template>

View File

@@ -1,24 +1,303 @@
<template>
<div class="min-h-screen flex items-center justify-center ">
<div class="w-full max-w-2xl mx-auto p-8 text-center">
<h1 class="text-4xl sm:text-5xl font-extrabold mb-4">
welcome to the 17th
</h1>
<p class=" mb-8">
Welcome click below to get started.
</p>
<script setup lang="ts">
import ApplicationForm from '@/components/application/ApplicationForm.vue';
import Button from '@/components/ui/button/Button.vue';
import {
Stepper,
StepperDescription,
StepperIndicator,
StepperItem,
StepperSeparator,
StepperTitle,
StepperTrigger,
} from '@/components/ui/stepper'
import { useUserStore } from '@/stores/user';
import { Check, Circle, Dot, Users, X } from 'lucide-vue-next'
import { computed, ref } from 'vue';
import Application from './Application.vue';
import { restartApplication } from '@/api/application';
<Button class="w-44" @click="goToLogin">Get started</Button>
function goToLogin() {
const redirectUrl = encodeURIComponent(window.location.origin + '/join')
window.location.href = `https://aj17thdevapi.nexuszone.net/login?redirect=${redirectUrl}`;
}
let userStore = useUserStore();
const steps = computed(() => {
const isDenied = userStore.state === 'denied'
return [
{
step: 1,
title: 'Create account',
description: 'Begin by setting up your account',
},
{
step: 2,
title: 'Submit application',
description: 'Provide a few details about yourself',
},
{
step: 3,
title: 'Application review',
description: 'Our team will review your submission',
},
{
step: 4,
title: isDenied ? 'Application denied' : 'Acceptance',
description: isDenied
? 'Your application was not approved'
: 'Get started with the 17th Rangers',
},
]
})
const currentStep = computed<number>(() => {
if (!userStore.isLoggedIn)
return 1;
switch (userStore.state) {
case "guest":
return 2;
break;
case "applicant":
return 3;
break;
case "member":
return 5;
break;
case "denied":
return 5;
break;
case "retired":
return 5;
break;
}
})
const finalPanel = ref<'app' | 'message'>('message');
const reloadKey = ref(0);
async function restartApp() {
await restartApplication();
await userStore.loadUser();
reloadKey.value++;
}
</script>
<template>
<div class="flex flex-col items-center mt-10 w-full" :key="reloadKey">
<!-- Stepper Container -->
<div class="w-full flex justify-center">
<div class="w-full max-w-7xl">
<Stepper class="flex w-full items-start gap-2" v-model="currentStep">
<StepperItem v-for="step in steps" :key="step.step" v-slot="{ state }"
class="relative flex w-full flex-col items-center" :step="step.step">
<StepperSeparator v-if="step.step !== steps[steps.length - 1]?.step"
class="absolute left-[calc(50%+20px)] right-[calc(-50%+10px)] top-5 block h-0.5 rounded-full bg-muted group-data-[state=completed]:bg-primary" />
<StepperTrigger as-child>
<Button :variant="state === 'completed' || state === 'active' ? 'default' : 'outline'"
size="icon" class="z-10 rounded-full shrink-0"
:class="[state === 'active' && 'ring-2 ring-ring ring-offset-2 ring-offset-background']">
<template v-if="state === 'completed'">
<X v-if="step.step === 4 && userStore.state === 'denied'" class="size-5" />
<Check v-else class="size-5" />
</template>
<Circle v-if="state === 'active'" />
<Dot v-if="state === 'inactive'" />
</Button>
</StepperTrigger>
<div class="mt-2 flex flex-col items-center text-center">
<StepperTitle class="text-sm font-semibold transition lg:text-base"
:class="[state === 'active' && 'text-primary']">
{{ step.title }}
</StepperTitle>
<StepperDescription
class="sr-only text-xs text-muted-foreground transition md:not-sr-only lg:text-sm"
:class="[state === 'active' && 'text-primary']">
{{ step.description }}
</StepperDescription>
</div>
</StepperItem>
</Stepper>
</div>
</div>
<!-- Content -->
<div class="mt-12 mb-20 flex w-full max-w-6xl justify-center">
<div v-if="currentStep === 1" class="w-full max-w-2xl p-8">
<h1 class="text-3xl sm:text-4xl font-bold mb-4 text-left">
Create your account
</h1>
<p class="text-left text-muted-foreground mb-6">
You'll be redirected to our secure sign-in system to set up your account
and begin your application.
</p>
<Button class="px-6 py-3" @click="goToLogin">
Continue to account creation
</Button>
</div>
<Application v-else-if="currentStep === 2" @submit="userStore.loadUser()" :mode="'create'"></Application>
<Application v-else-if="currentStep === 3" :mode="'view-self'"></Application>
<div v-if="currentStep === 5" class="w-full p-8 pt-0">
<div class="mb-5">
<div class="flex w-min *:px-10 pt-2 border-b *:w-full *:text-center *:pb-1 *:cursor-pointer">
<label :class="finalPanel === 'message' ? 'border-b-3 border-foreground' : 'mb-[2px]'"
@click="finalPanel = 'message'">Message
</label>
<label :class="finalPanel === 'app' ? 'border-b-3 border-foreground' : 'mb-[2px]'"
@click="finalPanel = 'app'">Application
</label>
</div>
</div>
<div v-if="finalPanel === 'message'">
<!-- Accepted message -->
<div v-if="userStore.state === 'member'">
<h1 class="text-3xl sm:text-4xl font-bold mb-4 text-left">
Welcome to the 17th Ranger Battalion
</h1>
<div class="space-y-4 text-muted-foreground text-left leading-relaxed">
<p>
Your application to the 17th Ranger Battalion has been <strong>accepted</strong>!
Were excited to welcome you to the community.
</p>
<p>
There are just a couple of steps to complete before joining us on the battlefield:
</p>
<!-- MODPACK SECTION -->
<h2 class="text-xl font-semibold text-foreground mt-6">1. Download the Modpack</h2>
<p>
Youll need to download our private server modpack. This can take some time, so we
recommend
starting as soon as possible. The link below leads to our
<strong>Shadow Mod</strong>, which automatically pulls all required dependencies.
</p>
<ul class="list-disc pl-6 space-y-1">
<li>Subscribe to the Shadow Mod.</li>
<li>When prompted, choose <em>“Yes”</em> to download all associated mods.</li>
</ul>
<p>
<a href="https://docs.iceberg-gaming.com/books/member-guides/page/new-member-setup-onboarding"
class="text-primary underline" target="_blank">
Click here for the full installation guide (Requires Sign-in)
</a>
</p>
<!-- CONTACT SECTION -->
<h2 class="text-xl font-semibold text-foreground mt-6">2. Contact a Corporal or Higher</h2>
<p>
Once you have the modpack installed, connect on TeamSpeak or post in Discord. Anyone
with
the
rank of <strong>Corporal or above</strong> can help get you set up.
</p>
<ul class="list-none pl-0 space-y-1">
<li><strong>TeamSpeak:</strong><a href="ts3server://ts.iceberg-gaming.com"
class="text-primary underline"
target="_blank">ts3server://ts.iceberg-gaming.com</a>
</li>
<li>
<strong>Discord:</strong>
<a href="https://discord.gg/7hDQCEb" class="text-primary underline"
target="_blank">https://discord.gg/7hDQCEb</a>
</li>
</ul>
<p>
They will assist you with your initial assessments and training. Basic trainings run on
a
rotating schedule or can be requested through our Battalion Forms. Dont hesitate to hop
in
during weeknights or Saturday operations to start playing with us!
</p>
<!-- FINAL NOTES -->
<h2 class="text-xl font-semibold text-foreground mt-6">3. Get Familiar with the Unit</h2>
<p>
Please take a moment to read through our <strong>Code of Conduct</strong>,
<strong>Ranks</strong>, and <strong>Structure</strong> pages. We also encourage you to
browse
our forums and introduce yourself.
</p>
<p>
If you have any questions, feel free to reach out on TeamSpeak or Discord
someone
will always be around to help.
</p>
</div>
</div>
<!-- Denied message -->
<div v-else-if="userStore.state === 'denied'">
<div class="w-full max-w-2xl flex flex-col gap-8">
<h1 class="text-3xl sm:text-4xl font-bold text-left">
Application Not Approved
</h1>
<div class="space-y-4 text-muted-foreground text-left leading-relaxed">
<p>
Thank you for your interest in joining the <strong>17th Ranger Battalion</strong>.
After reviewing your application, we regret to inform you that we are not able to
approve it at this time.
</p>
<p>
If you would like more information, you are encouraged to
<strong>reach out and inquire</strong> about the reason your application was not
approved.
We are always happy to provide clarification where possible.
</p>
<p>
You are welcome to <strong>resubmit your application in the future</strong> should
your
circumstances change or when we may be better able to incorporate you into the unit.
</p>
<p>
All the best,<br />
<span class="text-foreground font-medium">The 17th Ranger Battalion Recruitment
Team</span>
</p>
</div>
<Button class="w-min" @click="restartApp">New Application</Button>
</div>
</div>
<div v-else-if="userStore.state === 'retired'">
<div class="w-full max-w-2xl flex flex-col gap-8">
<h1 class="text-3xl sm:text-4xl font-bold text-left">
You have retired from the 17th Ranger Battalion
</h1>
<div class="space-y-4 text-muted-foreground text-left leading-relaxed">
<p>
Thank you for your service and participation in the <strong>17th Ranger
Battalion</strong>.
Your time with us has been sincerely appreciated.
</p>
<p>
Should you ever wish to return, you are welcome to <strong>reach out to our
leadership
team</strong>
for guidance on the reinstatement process or to stay connected with the community.
</p>
<p>
We recognize that circumstances change, and you will always have a place to
reconnect with
us
should the opportunity arise in the future.
</p>
<p>
All the best,<br />
<span class="text-foreground font-medium">The 17th Ranger Battalion Leadership
Team</span>
</p>
</div>
<Button class="w-min" @click="restartApp">New Application</Button>
</div>
</div>
</div>
<div v-if="finalPanel === 'app'">
<Application :mode="'view-self'"></Application>
</div>
</div>
</div>
</div>
</template>
<script setup>
import Button from '@/components/ui/button/Button.vue';
function goToLogin() {
window.location.href = 'https://aj17thdevapi.nexuszone.net/login';
}
</script>

View File

@@ -1,5 +1,6 @@
<script setup>
import { getAllApplications, approveApplication, denyApplication, ApplicationStatus } from '@/api/application';
import { getAllApplications, approveApplication, denyApplication } from '@/api/application';
import { ApplicationStatus } from '@shared/types/application'
import {
Table,
TableBody,
@@ -10,9 +11,10 @@ import {
TableRow,
} from '@/components/ui/table'
import Button from '@/components/ui/button/Button.vue';
import { onMounted, ref } from 'vue';
import { useRouter } from 'vue-router';
import { onMounted, ref, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { CheckIcon, XIcon } from 'lucide-vue-next';
import Application from './Application.vue';
const appList = ref([]);
const now = Date.now();
@@ -61,48 +63,96 @@ async function handleDeny(id) {
const router = useRouter();
function openApplication(id) {
router.push(`./application/${id}`)
router.push(`/administration/applications/${id}`)
openPanel.value = true;
}
function closeApplication() {
router.push('/administration/applications')
openPanel.value = false;
}
const route = useRoute();
watch(() => route.params.id, (newId) => {
if (newId === undefined) {
openPanel.value = false;
}
})
const openPanel = ref(false);
onMounted(async () => {
appList.value = await getAllApplications();
//preload application
if (route.params.id != undefined) {
openApplication(route.params.id)
}
})
</script>
<template>
<div class="mx-auto max-w-5xl">
<h1 class="my-4">Manage Applications</h1>
<Table>
<!-- <TableCaption>A list of your recent invoices.</TableCaption> -->
<TableHeader>
<TableRow>
<TableHead>User</TableHead>
<TableHead>Date Submitted</TableHead>
<TableHead class="text-right">Status</TableHead>
</TableRow>
</TableHeader>
<TableBody>
<TableRow v-for="app in appList" :key="app.id" class="cursor-pointer"
:onClick="() => { openApplication(app.id) }">
<TableCell class="font-medium">{{ app.member_name }}</TableCell>
<TableCell :title="formatExact(app.submitted_at)">
{{ formatAgo(app.submitted_at) }}
</TableCell>
<TableCell v-if="app.app_status === ApplicationStatus.Pending" class="inline-flex items-end gap-2">
<Button variant="success" @click.stop="() => { handleApprove(app.id) }">
<CheckIcon></CheckIcon>
</Button>
<Button variant="destructive" @click.stop="() => { handleDeny(app.id) }">
<XIcon></XIcon>
</Button>
</TableCell>
<TableCell class="text-right font-semibold" :class="[
,
app.app_status === ApplicationStatus.Pending && 'text-yellow-500',
app.app_status === ApplicationStatus.Accepted && 'text-green-500',
app.app_status === ApplicationStatus.Denied && 'text-destructive'
]">{{ app.app_status }}</TableCell>
</TableRow>
</TableBody>
</Table>
<div class="px-20 mx-auto max-w-[100rem] w-full flex mt-5 h-52 min-h-0 overflow-hidden">
<!-- application list -->
<div :class="openPanel == false ? 'w-full' : 'w-2/5'" class="pr-9">
<h1 class="scroll-m-20 text-2xl font-semibold tracking-tight">Manage Applications</h1>
<div class="max-h-[80vh] overflow-hidden">
<Table class="w-full">
<TableHeader>
<TableRow>
<TableHead>User</TableHead>
<TableHead>Date Submitted</TableHead>
<TableHead class="text-right">Status</TableHead>
</TableRow>
</TableHeader>
</Table>
<!-- Scrollable body container -->
<div class="overflow-y-auto max-h-[70vh] scrollbar-themed">
<Table class="w-full">
<TableBody>
<TableRow v-for="app in appList" :key="app.id" class="cursor-pointer"
@click="openApplication(app.id)">
<TableCell class="font-medium">{{ app.member_name }}</TableCell>
<TableCell :title="formatExact(app.submitted_at)">
{{ formatAgo(app.submitted_at) }}
</TableCell>
<TableCell v-if="app.app_status === ApplicationStatus.Pending"
class="inline-flex items-end gap-2">
<Button variant="success" @click.stop="handleApprove(app.id)">
<CheckIcon />
</Button>
<Button variant="destructive" @click.stop="handleDeny(app.id)">
<XIcon />
</Button>
</TableCell>
<TableCell class="text-right font-semibold" :class="[
app.app_status === ApplicationStatus.Pending && 'text-yellow-500',
app.app_status === ApplicationStatus.Accepted && 'text-green-500',
app.app_status === ApplicationStatus.Denied && 'text-destructive'
]">
{{ app.app_status }}
</TableCell>
</TableRow>
</TableBody>
</Table>
</div>
</div>
</div>
<div v-if="openPanel" class="pl-9 border-l w-3/5" :key="$route.params.id">
<div class="mb-5 flex justify-between">
<p class="scroll-m-20 text-2xl font-semibold tracking-tight"> Application</p>
<button @click="closeApplication()" class="cursor-pointer">
<XIcon></XIcon>
</button>
</div>
<div class="overflow-y-auto max-h-[80vh] h-full mt-5 scrollbar-themed">
<Application :mode="'view-recruiter'"></Application>
</div>
</div>
</div>
</template>
</template>
<style scoped></style>

View File

@@ -17,27 +17,24 @@ const showLOADialog = ref(false);
</script>
<template>
<Dialog v-model:open="showLOADialog" v-on:update:open="showLOADialog = false">
<DialogContent>
<DialogHeader>
<DialogTitle>Post LOA</DialogTitle>
<DialogDescription>
Post an LOA on behalf of a member.
</DialogDescription>
</DialogHeader>
<LoaForm :admin-mode="true" class="my-5 w-full"></LoaForm>
<!-- <DialogFooter>
<Button variant="secondary" @click="showLOADialog = false">Cancel</Button>
<Button>Apply</Button>
</DialogFooter> -->
</DialogContent>
</Dialog>
<div class="max-w-5xl mx-auto pt-10">
<div class="flex justify-end mb-4">
<Button @click="showLOADialog = true">Post LOA</Button>
<div>
<Dialog v-model:open="showLOADialog" v-on:update:open="showLOADialog = false">
<DialogContent class="sm:max-w-fit">
<DialogHeader>
<DialogTitle>Post LOA</DialogTitle>
<DialogDescription>
Post an LOA on behalf of a member.
</DialogDescription>
</DialogHeader>
<LoaForm :admin-mode="true" class="my-3"></LoaForm>
</DialogContent>
</Dialog>
<div class="max-w-5xl mx-auto pt-10">
<div class="flex justify-end mb-4">
<Button @click="showLOADialog = true">Post LOA</Button>
</div>
<h1>LOA Log</h1>
<LoaList :admin-mode="true"></LoaList>
</div>
<h1>LOA Log</h1>
<LoaList></LoaList>
</div>
</template>

View File

@@ -68,7 +68,7 @@ onMounted(async () => {
</DialogContent>
</Dialog>
<div class="max-w-5xl mx-auto">
<div class="max-w-5xl w-full mx-auto">
Active
<div>
<Card>

View File

@@ -0,0 +1,148 @@
<script setup>
import { loadMyApplications } from '@/api/application';
import { ApplicationStatus } from '@shared/types/application';
import {
Table,
TableBody,
TableCaption,
TableCell,
TableHead,
TableHeader,
TableRow,
} from '@/components/ui/table'
import Button from '@/components/ui/button/Button.vue';
import { onMounted, ref, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { CheckIcon, XIcon } from 'lucide-vue-next';
import Application from './Application.vue';
const appList = ref([]);
const now = Date.now();
// relative time formatter (uses user locale)
const rtf = new Intl.RelativeTimeFormat(undefined, { numeric: 'auto' })
// exact date/time for tooltip
const exactFmt = new Intl.DateTimeFormat(undefined, {
dateStyle: 'medium', timeStyle: 'short', timeZone: 'America/Toronto'
})
function formatAgo(iso) {
const d = new Date(iso)
if (isNaN(d)) return ''
let diff = (d.getTime() - now) / 1000 // seconds relative to page load
const divisions = [
{ amount: 60, name: 'second' },
{ amount: 60, name: 'minute' },
{ amount: 24, name: 'hour' },
{ amount: 7, name: 'day' },
{ amount: 4.34524, name: 'week' }, // avg weeks per month
{ amount: 12, name: 'month' },
{ amount: Infinity, name: 'year' },
]
for (const div of divisions) {
if (Math.abs(diff) < div.amount) {
return rtf.format(Math.round(diff), div.name)
}
diff /= div.amount
}
}
function formatExact(iso) {
const d = new Date(iso)
return isNaN(d) ? '' : exactFmt.format(d)
}
const router = useRouter();
function openApplication(id) {
router.push(`/applications/${id}`)
openPanel.value = true;
}
const route = useRoute();
watch(() => route.params.id, (newId) => {
if (newId === undefined) {
openPanel.value = false;
}
})
const openPanel = ref(false);
onMounted(async () => {
appList.value = await loadMyApplications();
//preload application
if (route.params.id != undefined) {
openApplication(route.params.id)
} else {
}
})
</script>
<template>
<div class="px-20 mx-auto max-w-[100rem] w-full flex mt-5 h-52 min-h-0 overflow-hidden">
<!-- application list -->
<div :class="openPanel == false ? 'w-full' : 'w-2/5'" class="pr-9">
<h1 class="scroll-m-20 text-2xl font-semibold tracking-tight mb-5">My Applications</h1>
<Table>
<TableHeader>
<TableRow>
<TableHead>Date Submitted</TableHead>
<TableHead class="text-right">Status</TableHead>
</TableRow>
</TableHeader>
<TableBody class="overflow-y-auto scrollbar-themed">
<TableRow v-for="app in appList" :key="app.id" class="cursor-pointer"
:onClick="() => { openApplication(app.id) }">
<TableCell :title="formatExact(app.submitted_at)">
{{ formatAgo(app.submitted_at) }}
</TableCell>
<TableCell class="text-right font-semibold" :class="[
,
app.app_status === ApplicationStatus.Pending && 'text-yellow-500',
app.app_status === ApplicationStatus.Accepted && 'text-green-500',
app.app_status === ApplicationStatus.Denied && 'text-destructive'
]">{{ app.app_status }}</TableCell>
</TableRow>
</TableBody>
</Table>
</div>
<div v-if="openPanel" class="pl-9 border-l w-3/5" :key="$route.params.id">
<div class="mb-5 flex justify-between">
<p class="scroll-m-20 text-2xl font-semibold tracking-tight"> Application</p>
</div>
<div class="overflow-y-auto max-h-[80vh] h-full mt-5 scrollbar-themed">
<Application :mode="'view-self-id'"></Application>
</div>
</div>
</div>
</template>
<style scoped>
/* 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;
}
</style>

View File

@@ -2,6 +2,8 @@
import LoaForm from '@/components/loa/loaForm.vue';
import { useUserStore } from '@/stores/user';
import { Member } from '@/api/member';
import LoaList from '@/components/loa/loaList.vue';
import { ref } from 'vue';
const userStore = useUserStore();
const user = userStore.user;
@@ -13,8 +15,24 @@ const memberFull: Member = {
status: null,
status_date: null,
};
const mode = ref<'submit' | 'view'>('submit')
</script>
<template>
<LoaForm class="m-10" :member="memberFull"></LoaForm>
<div class="max-w-5xl mx-auto flex w-full flex-col mt-4 mb-10">
<div class="mb-8">
<p class="scroll-m-20 text-2xl font-semibold tracking-tight">Leave of Absence</p>
<div class="pt-3">
<div class="flex w-min *:px-10 pt-2 border-b *:w-full *:text-center *:pb-1 *:cursor-pointer">
<label :class="mode === 'submit' ? 'border-b-3 border-foreground' : 'mb-[2px]'"
@click="mode = 'submit'">Submit</label>
<label :class="mode === 'view' ? 'border-b-3 border-foreground' : 'mb-[2px]'"
@click="mode = 'view'">History</label>
</div>
</div>
</div>
<LoaForm v-if="mode === 'submit'" :member="memberFull"></LoaForm>
<LoaList v-if="mode === 'view'" :admin-mode="false"></LoaList>
</div>
</template>

View File

@@ -95,7 +95,7 @@ onMounted(async () => {
</script>
<template>
<div class="px-20 mx-auto max-w-[100rem] flex mt-5">
<div class="px-20 mx-auto max-w-[100rem] w-full flex mt-5">
<!-- training report list -->
<div class="px-4 my-3" :class="sidePanel == sidePanelState.closed ? 'w-full' : 'w-2/5'">
<div class="flex justify-between mb-4">

View File

@@ -1,5 +1,5 @@
<template>
<div class="min-h-screen flex flex-col items-center justify-center text-center px-6">
<div class="flex flex-col items-center justify-center text-center px-6">
<h1 class="text-5xl font-bold mb-4">Unauthorized</h1>
<p class="text-lg text-muted-foreground max-w-md mb-6">
You don't have permission to access this page.

View File

@@ -65,6 +65,7 @@ const searchedMembers = computed(() => {
Member
</TableHead>
<TableHead>Rank</TableHead>
<TableHead>Unit</TableHead>
<TableHead>Status</TableHead>
</TableRow>
</TableHeader>
@@ -75,6 +76,7 @@ const searchedMembers = computed(() => {
{{ member.member_name }}
</TableCell>
<TableCell>{{ member.rank }}</TableCell>
<TableCell>{{ member.unit }}</TableCell>
<TableCell>{{ member.status }}</TableCell>
<TableCell><Badge v-if="member.on_loa">On LOA</Badge></TableCell>
<TableCell @click.stop="" class="text-right">

View File

@@ -6,19 +6,24 @@ const router = createRouter({
routes: [
// PUBLIC
{ path: '/join', component: () => import('@/pages/Join.vue') },
{ path: '/applications', component: () => import('@/pages/MyApplications.vue'), meta: { requiresAuth: true } },
{ path: '/applications/:id', component: () => import('@/pages/MyApplications.vue'), meta: { requiresAuth: true } },
// AUTH REQUIRED
{ path: '/apply', component: () => import('@/pages/Application.vue'), meta: { requiresAuth: true } },
{ path: '/', component: () => import('@/pages/Homepage.vue'), meta: { requiresAuth: true } },
{ path: '/', component: () => import('@/pages/Homepage.vue') },
// MEMBER ROUTES
{ path: '/members', component: () => import('@/pages/memberList.vue'), meta: { requiresAuth: true, memberOnly: true } },
{ path: '/loa', component: () => import('@/pages/SubmitLOA.vue'), meta: { requiresAuth: true, memberOnly: true } },
{ path: '/transfer', component: () => import('@/pages/Transfer.vue'), meta: { requiresAuth: true, memberOnly: true } },
{ path: '/calendar', component: () => import('@/pages/Calendar.vue'), meta: { requiresAuth: true, memberOnly: true }, },
{ path: '/calendar/event/:id', component: () => import('@/pages/Calendar.vue'), meta: { requiresAuth: true, memberOnly: true }, },
// disabled in favor of linking
// { path: '/documents', component: () => import('@/pages/Documentation.vue'), meta: { requiresAuth: true, memberOnly: true }, },
{ path: '/trainingReport', component: () => import('@/pages/TrainingReport.vue'), meta: { requiresAuth: true, memberOnly: true } },
{ path: '/trainingReport/new', component: () => import('@/pages/TrainingReport.vue'), meta: { requiresAuth: true, memberOnly: true } },
{ path: '/trainingReport/:id', component: () => import('@/pages/TrainingReport.vue'), meta: { requiresAuth: true, memberOnly: true } },
@@ -29,7 +34,7 @@ const router = createRouter({
meta: { requiresAuth: true, memberOnly: true, roles: ['staff', 'admin'] },
children: [
{ path: 'applications', component: () => import('@/pages/ManageApplications.vue') },
{ path: 'application/:id', component: () => import('@/pages/Application.vue') },
{ path: 'applications/:id', component: () => import('@/pages/ManageApplications.vue') },
{ path: 'rankChange', component: () => import('@/pages/RankChange.vue') },
{ path: 'applications/:id', component: () => import('@/pages/Application.vue') },
{ path: 'transfer', component: () => import('@/pages/ManageTransfers.vue') },
@@ -63,15 +68,15 @@ router.beforeEach(async (to) => {
}
// // Must be a member
// if (to.meta.memberOnly && user.state !== 'member') {
// return '/unauthorized'
// }
// Must be a member
if (to.meta.memberOnly && user.state !== 'member') {
return '/unauthorized'
}
// // Must have specific role
// if (to.meta.roles && !user.hasRole('Dev') && !user.hasAnyRole(to.meta.roles)) {
// return '/unauthorized'
// }
// Must have specific role
if (to.meta.roles && !user.hasRole('Dev') && !user.hasAnyRole(to.meta.roles)) {
return '/unauthorized'
}
})
export default router;

View File

@@ -5,7 +5,7 @@ export const useUserStore = defineStore('user', () => {
const user = ref(null)
const roles = computed(() => new Set(user.value?.roleData?.map(r => r.name) ?? []));
const loaded = ref(false);
const state = computed(() => user.value.state);
const state = computed<string | undefined>(() => user.value?.state || undefined);
const isLoggedIn = computed(() => user.value !== null)
async function loadUser() {
@@ -16,6 +16,7 @@ export const useUserStore = defineStore('user', () => {
if (res.ok) {
const data = await res.json();
console.log(data);
user.value = data;
}