Compare commits
23 Commits
ab9bb99987
...
DIscussion
| Author | SHA1 | Date | |
|---|---|---|---|
| 33679542d7 | |||
| e8b30f6947 | |||
| 7c090c647e | |||
| 5483e42bb4 | |||
| 5cdbf72328 | |||
| a239b7e204 | |||
| 19db5a8ca5 | |||
| 4611de4b0d | |||
| 86d069651c | |||
| 82d746fee1 | |||
| ae13cdebb3 | |||
| 90db7de843 | |||
| a1996419d6 | |||
| 4d87ff4925 | |||
| 2e944231a5 | |||
| 947c657e92 | |||
| f1695e3a00 | |||
| c7d79ae586 | |||
| 545b317caa | |||
| bd8f6ba84b | |||
| 9be1d953bf | |||
| 5106b72e24 | |||
| 34ce7d1e14 |
@@ -89,6 +89,12 @@ jobs:
|
||||
sed -i "s/APPLICATION_VERSION=.*/APPLICATION_VERSION=$version/" .env
|
||||
chown -R nginx:nginx .
|
||||
|
||||
- name: Run Database Migrations
|
||||
run: |
|
||||
cd /var/www/html/milsim-site-v4/api
|
||||
npx db-migrate up -e prod
|
||||
chown -R nginx:nginx .
|
||||
|
||||
- name: Reset File Permissions
|
||||
run: |
|
||||
sudo chown -R nginx:nginx /var/www/html/milsim-site-v4
|
||||
|
||||
@@ -89,6 +89,12 @@ jobs:
|
||||
sed -i "s/APPLICATION_VERSION=.*/APPLICATION_VERSION=$version/" .env
|
||||
chown -R nginx:nginx .
|
||||
|
||||
- name: Run Database Migrations
|
||||
run: |
|
||||
cd /var/www/html/milsim-site-v4/api
|
||||
npx db-migrate up -e prod
|
||||
chown -R nginx:nginx .
|
||||
|
||||
- name: Reset File Permissions
|
||||
run: |
|
||||
sudo chown -R nginx:nginx /var/www/html/milsim-site-v4
|
||||
|
||||
@@ -10,7 +10,7 @@ on:
|
||||
|
||||
jobs:
|
||||
build:
|
||||
name: Update Deployment
|
||||
name: Merge Check
|
||||
runs-on: ubuntu-latest
|
||||
container:
|
||||
steps:
|
||||
|
||||
53
api/migrations/20260212165353-audit-log.js
Normal file
53
api/migrations/20260212165353-audit-log.js
Normal file
@@ -0,0 +1,53 @@
|
||||
'use strict';
|
||||
|
||||
var dbm;
|
||||
var type;
|
||||
var seed;
|
||||
var fs = require('fs');
|
||||
var path = require('path');
|
||||
var Promise;
|
||||
|
||||
/**
|
||||
* We receive the dbmigrate dependency from dbmigrate initially.
|
||||
* This enables us to not have to rely on NODE_PATH.
|
||||
*/
|
||||
exports.setup = function(options, seedLink) {
|
||||
dbm = options.dbmigrate;
|
||||
type = dbm.dataType;
|
||||
seed = seedLink;
|
||||
Promise = options.Promise;
|
||||
};
|
||||
|
||||
exports.up = function(db) {
|
||||
var filePath = path.join(__dirname, 'sqls', '20260212165353-audit-log-up.sql');
|
||||
return new Promise( function( resolve, reject ) {
|
||||
fs.readFile(filePath, {encoding: 'utf-8'}, function(err,data){
|
||||
if (err) return reject(err);
|
||||
console.log('received data: ' + data);
|
||||
|
||||
resolve(data);
|
||||
});
|
||||
})
|
||||
.then(function(data) {
|
||||
return db.runSql(data);
|
||||
});
|
||||
};
|
||||
|
||||
exports.down = function(db) {
|
||||
var filePath = path.join(__dirname, 'sqls', '20260212165353-audit-log-down.sql');
|
||||
return new Promise( function( resolve, reject ) {
|
||||
fs.readFile(filePath, {encoding: 'utf-8'}, function(err,data){
|
||||
if (err) return reject(err);
|
||||
console.log('received data: ' + data);
|
||||
|
||||
resolve(data);
|
||||
});
|
||||
})
|
||||
.then(function(data) {
|
||||
return db.runSql(data);
|
||||
});
|
||||
};
|
||||
|
||||
exports._meta = {
|
||||
"version": 1
|
||||
};
|
||||
53
api/migrations/20260222232949-discussion-posts.js
Normal file
53
api/migrations/20260222232949-discussion-posts.js
Normal file
@@ -0,0 +1,53 @@
|
||||
'use strict';
|
||||
|
||||
var dbm;
|
||||
var type;
|
||||
var seed;
|
||||
var fs = require('fs');
|
||||
var path = require('path');
|
||||
var Promise;
|
||||
|
||||
/**
|
||||
* We receive the dbmigrate dependency from dbmigrate initially.
|
||||
* This enables us to not have to rely on NODE_PATH.
|
||||
*/
|
||||
exports.setup = function(options, seedLink) {
|
||||
dbm = options.dbmigrate;
|
||||
type = dbm.dataType;
|
||||
seed = seedLink;
|
||||
Promise = options.Promise;
|
||||
};
|
||||
|
||||
exports.up = function(db) {
|
||||
var filePath = path.join(__dirname, 'sqls', '20260222232949-discussion-posts-up.sql');
|
||||
return new Promise( function( resolve, reject ) {
|
||||
fs.readFile(filePath, {encoding: 'utf-8'}, function(err,data){
|
||||
if (err) return reject(err);
|
||||
console.log('received data: ' + data);
|
||||
|
||||
resolve(data);
|
||||
});
|
||||
})
|
||||
.then(function(data) {
|
||||
return db.runSql(data);
|
||||
});
|
||||
};
|
||||
|
||||
exports.down = function(db) {
|
||||
var filePath = path.join(__dirname, 'sqls', '20260222232949-discussion-posts-down.sql');
|
||||
return new Promise( function( resolve, reject ) {
|
||||
fs.readFile(filePath, {encoding: 'utf-8'}, function(err,data){
|
||||
if (err) return reject(err);
|
||||
console.log('received data: ' + data);
|
||||
|
||||
resolve(data);
|
||||
});
|
||||
})
|
||||
.then(function(data) {
|
||||
return db.runSql(data);
|
||||
});
|
||||
};
|
||||
|
||||
exports._meta = {
|
||||
"version": 1
|
||||
};
|
||||
1
api/migrations/sqls/20260212165353-audit-log-down.sql
Normal file
1
api/migrations/sqls/20260212165353-audit-log-down.sql
Normal file
@@ -0,0 +1 @@
|
||||
/* Replace with your SQL commands */
|
||||
17
api/migrations/sqls/20260212165353-audit-log-up.sql
Normal file
17
api/migrations/sqls/20260212165353-audit-log-up.sql
Normal file
@@ -0,0 +1,17 @@
|
||||
CREATE TABLE audit_log (
|
||||
id INT PRIMARY KEY AUTO_INCREMENT,
|
||||
-- "area.action" (e.g., 'calendarEvent.create', 'member.update_rank')
|
||||
action_type VARCHAR(100) NOT NULL,
|
||||
-- The JSON blob containing detailed information
|
||||
payload JSON DEFAULT NULL,
|
||||
-- Identifying the actor
|
||||
created_by INT,
|
||||
-- The ID of the resource being acted upon
|
||||
target_id INT DEFAULT NULL,
|
||||
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
CONSTRAINT fk_created_by FOREIGN KEY (created_by) REFERENCES members(id) ON DELETE
|
||||
SET NULL,
|
||||
INDEX idx_action (action_type),
|
||||
INDEX idx_target (target_id)
|
||||
);
|
||||
@@ -0,0 +1,3 @@
|
||||
/* Replace with your SQL commands */
|
||||
DROP TABLE discussion_posts;
|
||||
DROP TABLE discussion_comments;
|
||||
34
api/migrations/sqls/20260222232949-discussion-posts-up.sql
Normal file
34
api/migrations/sqls/20260222232949-discussion-posts-up.sql
Normal file
@@ -0,0 +1,34 @@
|
||||
/* Replace with your SQL commands */
|
||||
CREATE TABLE discussion_posts (
|
||||
id INT PRIMARY KEY AUTO_INCREMENT,
|
||||
type VARCHAR(50) NOT NULL,
|
||||
poster_id INT NOT NULL,
|
||||
title VARCHAR(100) NOT NULL,
|
||||
content JSON NOT NULL,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||
is_deleted BOOLEAN DEFAULT FALSE,
|
||||
is_locked BOOLEAN DEFAULT FALSE,
|
||||
is_open BOOLEAN GENERATED ALWAYS AS (
|
||||
NOT is_deleted
|
||||
AND NOT is_locked
|
||||
) STORED,
|
||||
FOREIGN KEY (poster_id) REFERENCES members(id) ON DELETE CASCADE
|
||||
);
|
||||
CREATE TABLE discussion_comments (
|
||||
id INT PRIMARY KEY AUTO_INCREMENT,
|
||||
post_id INT NOT NULL,
|
||||
poster_id INT NOT NULL,
|
||||
content TEXT NOT NULL,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||
is_deleted BOOLEAN DEFAULT FALSE,
|
||||
FOREIGN KEY (post_id) REFERENCES discussion_posts(id) ON DELETE CASCADE,
|
||||
FOREIGN KEY (poster_id) REFERENCES members(id) ON DELETE CASCADE
|
||||
);
|
||||
CREATE INDEX idx_discussion_posts_title ON discussion_posts(title);
|
||||
CREATE INDEX idx_discussion_posts_type ON discussion_posts(type);
|
||||
CREATE INDEX idx_discussion_posts_poster_id ON discussion_posts(poster_id);
|
||||
CREATE INDEX idx_discussion_comments_post_id ON discussion_comments(post_id);
|
||||
CREATE INDEX idx_discussion_comments_poster_id ON discussion_comments(poster_id);
|
||||
CREATE INDEX idx_discussion_posts_is_open ON discussion_posts(is_open);
|
||||
@@ -18,7 +18,8 @@ app.use(morgan((tokens: morgan.TokenIndexer, req: express.Request, res: express.
|
||||
}
|
||||
|
||||
const payload: LogPayload = {
|
||||
message: 'HTTP request completed',
|
||||
message: `${tokens.method(req, res)} ${tokens.url(req, res)}`,
|
||||
// message: 'HTTP request completed',
|
||||
data: {
|
||||
method: tokens.method(req, res),
|
||||
path: tokens.url(req, res),
|
||||
@@ -103,6 +104,8 @@ import { courseRouter, eventRouter } from './routes/course';
|
||||
import { calendarRouter } from './routes/calendar';
|
||||
import { docsRouter } from './routes/docs';
|
||||
import { units } from './routes/units';
|
||||
import { modRequestRouter } from './routes/modRequest'
|
||||
import { discussionRouter } from './routes/discussion';
|
||||
|
||||
app.use('/application', applicationRouter);
|
||||
app.use('/ranks', ranks);
|
||||
@@ -118,6 +121,8 @@ app.use('/courseEvent', eventRouter)
|
||||
app.use('/calendar', calendarRouter)
|
||||
app.use('/units', units)
|
||||
app.use('/docs', docsRouter)
|
||||
app.use('/mod-request', modRequestRouter)
|
||||
app.use('/discussions', discussionRouter)
|
||||
app.use('/', authRouter)
|
||||
|
||||
app.get('/ping', (req, res) => {
|
||||
|
||||
@@ -12,6 +12,7 @@ import { Request, response, Response } from 'express';
|
||||
import { getUserRoles } from '../services/db/rolesService';
|
||||
import { requireLogin, requireRole } from '../middleware/auth';
|
||||
import { logger } from '../services/logging/logger';
|
||||
import { audit, AuditContext } from '../services/logging/auditLog';
|
||||
import { bus } from '../services/events/eventBus';
|
||||
|
||||
//get CoC
|
||||
@@ -58,6 +59,8 @@ router.post('/', [requireLogin], async (req: Request, res: Response) => {
|
||||
|
||||
res.sendStatus(201);
|
||||
|
||||
audit.application('created', { actorId: memberID, targetId: appID });
|
||||
|
||||
bus.emit("application.create", { application: appID, member_name: req.user.name, member_discord_id: req.user.discord_id || null })
|
||||
|
||||
logger.info('app', 'Application Posted', {
|
||||
@@ -228,31 +231,26 @@ router.post('/approve/:id', [requireLogin, requireRole("Recruiter")], async (req
|
||||
const app = await getApplicationByID(appID);
|
||||
|
||||
try {
|
||||
console.log("HELLO MFS")
|
||||
var con = await pool.getConnection();
|
||||
console.log("START")
|
||||
|
||||
con.beginTransaction();
|
||||
console.log("APPROVE")
|
||||
|
||||
await approveApplication(appID, approved_by, con);
|
||||
console.log("STATE")
|
||||
|
||||
//update user profile
|
||||
await setUserState(app.member_id, MemberState.Member, "Application Accepted", approved_by, con);
|
||||
|
||||
console.log("SP")
|
||||
|
||||
await con.query('CALL sp_accept_new_recruit_validation(?, ?, ?, ?)', [Number(process.env.CONFIG_ID), app.member_id, approved_by, approved_by])
|
||||
|
||||
console.log("COMMIT")
|
||||
|
||||
con.commit();
|
||||
logger.info('app', "Member application approved", {
|
||||
application: app.id,
|
||||
applicant: app.member_id,
|
||||
approver: approved_by
|
||||
})
|
||||
|
||||
audit.application('approved', { actorId: approved_by, targetId: appID }, { applicantId: app.member_id });
|
||||
|
||||
res.sendStatus(200);
|
||||
} catch (error) {
|
||||
|
||||
@@ -288,6 +286,7 @@ router.post('/deny/:id', [requireLogin, requireRole("Recruiter")], async (req: R
|
||||
applicant: app.member_id,
|
||||
approver: approver
|
||||
})
|
||||
audit.application('denied', { actorId: approver, targetId: appID }, { applicantId: app.member_id });
|
||||
res.sendStatus(200);
|
||||
} catch (error) {
|
||||
logger.error(
|
||||
@@ -305,7 +304,7 @@ router.post('/deny/:id', [requireLogin, requireRole("Recruiter")], async (req: R
|
||||
|
||||
// POST /application/:id/comment
|
||||
router.post('/:id/comment', [requireLogin], async (req: Request, res: Response) => {
|
||||
const appID = req.params.id;
|
||||
const appID = Number(req.params.id);
|
||||
const data = req.body.message;
|
||||
const user = req.user;
|
||||
|
||||
@@ -337,10 +336,12 @@ VALUES(?, ?, ?);`
|
||||
WHERE app.id = ?; `;
|
||||
const comment = await conn.query(getSQL, [result.insertId])
|
||||
|
||||
audit.record('application', 'comment_added', { actorId: user.id, targetId: appID }, { commentId: Number(result.insertId) });
|
||||
|
||||
logger.info('app', "Application comment posted", {
|
||||
application: appID,
|
||||
poster: user.id,
|
||||
comment: result.insertId,
|
||||
comment: Number(result.insertId),
|
||||
})
|
||||
|
||||
res.status(201).json(comment[0]);
|
||||
@@ -363,7 +364,7 @@ VALUES(?, ?, ?);`
|
||||
|
||||
// POST /application/:id/comment
|
||||
router.post('/:id/adminComment', [requireLogin, requireRole("Recruiter")], async (req: Request, res: Response) => {
|
||||
const appID = req.params.id;
|
||||
const appID = Number(req.params.id);
|
||||
const data = req.body.message;
|
||||
const user = req.user;
|
||||
|
||||
@@ -395,7 +396,7 @@ VALUES(?, ?, ?, 1);`
|
||||
INNER JOIN members AS member ON member.id = app.poster_id
|
||||
WHERE app.id = ?; `;
|
||||
const comment = await conn.query(getSQL, [result.insertId])
|
||||
|
||||
audit.record('application', 'comment_added', { actorId: user.id, targetId: appID }, { commentId: result.insertId });
|
||||
logger.info('app', "Admin application comment posted", {
|
||||
application: appID,
|
||||
poster: user.id,
|
||||
@@ -424,6 +425,7 @@ router.post('/restart', async (req: Request, res: Response) => {
|
||||
try {
|
||||
await setUserState(user, MemberState.Guest, "Restarted Application", user);
|
||||
|
||||
audit.application('restarted', { actorId: user, targetId: user });
|
||||
logger.info('app', "Member restarted application", {
|
||||
user: user
|
||||
})
|
||||
|
||||
@@ -4,6 +4,7 @@ import { CalendarAttendance, CalendarEvent } from "@app/shared/types/calendar";
|
||||
import { requireLogin, requireMemberState, requireRole } from "../middleware/auth";
|
||||
import { MemberState } from "@app/shared/types/member";
|
||||
import { logger } from "../services/logging/logger";
|
||||
import { audit } from "../services/logging/auditLog";
|
||||
|
||||
const express = require('express');
|
||||
const r = express.Router();
|
||||
@@ -46,10 +47,12 @@ r.get('/upcoming', async (req, res) => {
|
||||
})
|
||||
|
||||
r.post('/:id/cancel', [requireLogin, requireMemberState(MemberState.Member)], async (req: Request, res: Response) => {
|
||||
let member = req.user.id;
|
||||
try {
|
||||
const eventID = Number(req.params.id);
|
||||
setEventCancelled(eventID, true);
|
||||
await setEventCancelled(eventID, true);
|
||||
|
||||
audit.calendar('cancelled', { actorId: member, targetId: eventID });
|
||||
logger.info('app', 'Calendar event cancelled', {
|
||||
event: eventID,
|
||||
user: req.user.id
|
||||
@@ -68,10 +71,12 @@ r.post('/:id/cancel', [requireLogin, requireMemberState(MemberState.Member)], as
|
||||
}
|
||||
})
|
||||
r.post('/:id/uncancel', [requireLogin, requireMemberState(MemberState.Member)], async (req: Request, res: Response) => {
|
||||
let member = req.user.id;
|
||||
try {
|
||||
const eventID = Number(req.params.id);
|
||||
setEventCancelled(eventID, false);
|
||||
|
||||
audit.calendar('un-cancelled', { actorId: member, targetId: eventID });
|
||||
logger.info('app', 'Calendar event un-cancelled', {
|
||||
event: eventID,
|
||||
user: req.user.id
|
||||
@@ -96,8 +101,9 @@ r.post('/:id/attendance', [requireLogin, requireMemberState(MemberState.Member)]
|
||||
let member = req.user.id;
|
||||
let event = Number(req.params.id);
|
||||
let state = req.query.state as CalendarAttendance;
|
||||
setAttendanceStatus(member, event, state);
|
||||
await setAttendanceStatus(member, event, state);
|
||||
|
||||
audit.calendar('attendance_set', { actorId: member, targetId: event }, { attendanceState: state });
|
||||
logger.info('app', 'Member set calendar event attendance', {
|
||||
event: event,
|
||||
user: req.user.id,
|
||||
@@ -148,8 +154,8 @@ r.post('/', [requireLogin, requireMemberState(MemberState.Member)], async (req:
|
||||
event.creator_id = member;
|
||||
event.start = new Date(event.start);
|
||||
event.end = new Date(event.end);
|
||||
createEvent(event);
|
||||
|
||||
let eventID = await createEvent(event);
|
||||
audit.calendar('event_created', { actorId: member, targetId: eventID });
|
||||
logger.info('app', 'Calendar event posted', {
|
||||
event: event.id,
|
||||
user: req.user.id
|
||||
@@ -170,12 +176,14 @@ r.post('/', [requireLogin, requireMemberState(MemberState.Member)], async (req:
|
||||
})
|
||||
|
||||
r.put('/', [requireLogin, requireMemberState(MemberState.Member)], async (req: Request, res: Response) => {
|
||||
let member = req.user.id;
|
||||
try {
|
||||
let event: CalendarEvent = req.body;
|
||||
event.start = new Date(event.start);
|
||||
event.end = new Date(event.end);
|
||||
updateEvent(event);
|
||||
|
||||
audit.calendar('event_updated', { actorId: member, targetId: event.id });
|
||||
logger.info('app', 'Calendar event updated', {
|
||||
event: event.id,
|
||||
user: req.user.id
|
||||
|
||||
@@ -4,6 +4,7 @@ import { Request, Response, Router } from "express";
|
||||
import { requireLogin, requireMemberState } from "../middleware/auth";
|
||||
import { MemberState } from "@app/shared/types/member";
|
||||
import { logger } from "../services/logging/logger";
|
||||
import { audit } from "../services/logging/auditLog";
|
||||
|
||||
const cr = Router();
|
||||
const er = Router();
|
||||
@@ -125,6 +126,7 @@ er.post('/', async (req: Request, res: Response) => {
|
||||
data.event_date = new Date(data.event_date);
|
||||
const id = await insertCourseEvent(data);
|
||||
|
||||
audit.course('report_created', { actorId: posterID, targetId: id });
|
||||
logger.info('app', 'Training report posted', { user: posterID, report: id })
|
||||
res.status(201).json(id);
|
||||
} catch (error) {
|
||||
|
||||
49
api/src/routes/discussion.ts
Normal file
49
api/src/routes/discussion.ts
Normal file
@@ -0,0 +1,49 @@
|
||||
const express = require('express');
|
||||
const router = express.Router();
|
||||
|
||||
import { Request, Response } from 'express';
|
||||
import { requireLogin, requireMemberState, requireRole } from '../middleware/auth';
|
||||
import { logger } from '../services/logging/logger';
|
||||
import { audit } from '../services/logging/auditLog';
|
||||
import { MemberState } from '@app/shared/types/member';
|
||||
import { createDiscussion, getAllDiscussions, getDiscussionById, getPostComments, postComment } from '../services/db/discussionService';
|
||||
import { ModRequest } from '@app/shared/schemas/modRequest';
|
||||
import { DiscussionComment } from '@app/shared/types/discussion';
|
||||
|
||||
router.use(requireLogin);
|
||||
router.use(requireMemberState(MemberState.Member));
|
||||
|
||||
router.post('/comment', async (req: Request, res: Response) => {
|
||||
try {
|
||||
let comment = req.body as DiscussionComment;
|
||||
|
||||
if (!comment.content || comment.content.trim() === '') {
|
||||
return res.status(400).json({ error: 'Comment content cannot be empty' });
|
||||
}
|
||||
|
||||
let rowID = await postComment(comment, req.user.id);
|
||||
audit.discussion('comment_posted', { actorId: req.user.id, targetId: rowID }, { parent: comment.post_id })
|
||||
res.sendStatus(201);
|
||||
} catch (error) {
|
||||
logger.error('app', "Failed to post comments", error);
|
||||
res.sendStatus(500);
|
||||
}
|
||||
});
|
||||
|
||||
router.get('/:postId/comments', async (req: Request, res: Response) => {
|
||||
try {
|
||||
const postId = parseInt(req.params.postId);
|
||||
const comments = await getPostComments(postId);
|
||||
res.json(comments);
|
||||
} catch (error) {
|
||||
logger.error('app', "Failed to fetch comments", error);
|
||||
res.sendStatus(500);
|
||||
}
|
||||
});
|
||||
|
||||
router.delete('/comment/:id', async (req: Request, res: Response) => {
|
||||
|
||||
})
|
||||
|
||||
|
||||
export const discussionRouter = router;
|
||||
@@ -7,6 +7,7 @@ import { closeLOA, createNewLOA, getAllLOA, getLOAbyID, getLoaTypes, getUserLOA,
|
||||
import { LOARequest } from '@app/shared/types/loa';
|
||||
import { requireLogin, requireRole } from '../middleware/auth';
|
||||
import { logger } from '../services/logging/logger';
|
||||
import { audit } from '../services/logging/auditLog';
|
||||
|
||||
router.use(requireLogin);
|
||||
|
||||
@@ -18,7 +19,9 @@ router.post("/", async (req: Request, res: Response) => {
|
||||
LOARequest.filed_date = new Date();
|
||||
|
||||
try {
|
||||
await createNewLOA(LOARequest);
|
||||
let loaID = await createNewLOA(LOARequest);
|
||||
|
||||
audit.leaveOfAbsence('created', { actorId: req.user.id, targetId: loaID })
|
||||
logger.info('app', 'LOA Posted', { poster: req.user.id, user: LOARequest.member_id })
|
||||
res.sendStatus(201);
|
||||
} catch (error) {
|
||||
@@ -40,7 +43,8 @@ router.post("/admin", [requireRole(['17th Administrator', '17th HQ', '17th Comma
|
||||
LOARequest.created_by = req.user.id;
|
||||
LOARequest.filed_date = new Date();
|
||||
try {
|
||||
await createNewLOA(LOARequest);
|
||||
let loaID = await createNewLOA(LOARequest);
|
||||
audit.leaveOfAbsence('admin_created', { actorId: req.user.id, targetId: loaID }, { for: LOARequest.member_id })
|
||||
logger.info('app', 'LOA Posted', { poster: req.user.id, user: LOARequest.member_id })
|
||||
res.sendStatus(201);
|
||||
} catch (error) {
|
||||
@@ -144,6 +148,7 @@ router.post('/cancel/:id', async (req: Request, res: Response) => {
|
||||
|
||||
await closeLOA(Number(req.params.id), closer);
|
||||
|
||||
audit.leaveOfAbsence('ended', { actorId: req.user.id, targetId: id });
|
||||
logger.info('app', 'LOA Closed', { closed_by: closer, LOA: id })
|
||||
|
||||
res.sendStatus(200);
|
||||
@@ -166,6 +171,7 @@ router.post('/adminCancel/:id', [requireRole(['17th Administrator', '17th HQ', '
|
||||
try {
|
||||
await closeLOA(Number(req.params.id), closer);
|
||||
|
||||
audit.leaveOfAbsence('admin_ended', { actorId: req.user.id, targetId: Number(req.params.id) });
|
||||
logger.info('app', 'LOA Closed', { closed_by: closer, LOA: req.params.id })
|
||||
|
||||
res.sendStatus(200);
|
||||
@@ -183,7 +189,50 @@ router.post('/adminCancel/:id', [requireRole(['17th Administrator', '17th HQ', '
|
||||
})
|
||||
|
||||
// extend LOA
|
||||
router.post('/extend/:id', [requireRole(['17th Administrator', '17th HQ', '17th Command'])], async (req: Request, res: Response) => {
|
||||
router.post('/extend/:id', async (req: Request, res: Response) => {
|
||||
const to: Date = req.body.to;
|
||||
|
||||
const member = req.user.id;
|
||||
|
||||
let LOA = await getLOAbyID(Number(req.params.id));
|
||||
if (!LOA) {
|
||||
return res.status(404).send("LOA not found");
|
||||
}
|
||||
|
||||
if (LOA.member_id !== member) {
|
||||
return res.status(403).send("You do not have permission to extend this LOA");
|
||||
}
|
||||
|
||||
if (LOA.extended_till !== null) {
|
||||
return res.status(409).send("You must contact the administration team to extend your LOA again");
|
||||
}
|
||||
|
||||
if (!to) {
|
||||
return res.status(400).send("Extension length is required");
|
||||
}
|
||||
|
||||
try {
|
||||
await setLOAExtension(Number(req.params.id), to);
|
||||
|
||||
audit.leaveOfAbsence('extended', { actorId: req.user.id, targetId: Number(req.params.id) });
|
||||
logger.info('app', 'LOA Extended', { extended_by: req.user.id, LOA: req.params.id })
|
||||
|
||||
res.sendStatus(200);
|
||||
} catch (error) {
|
||||
logger.error(
|
||||
'app',
|
||||
'Failed to extend LOA',
|
||||
{
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
stack: error instanceof Error ? error.stack : undefined,
|
||||
}
|
||||
);
|
||||
res.status(500).json(error);
|
||||
}
|
||||
})
|
||||
|
||||
// admin extend LOA
|
||||
router.post('/extendAdmin/:id', [requireRole(['17th Administrator', '17th HQ', '17th Command'])], async (req: Request, res: Response) => {
|
||||
const to: Date = req.body.to;
|
||||
|
||||
if (!to) {
|
||||
@@ -192,6 +241,8 @@ router.post('/extend/:id', [requireRole(['17th Administrator', '17th HQ', '17th
|
||||
|
||||
try {
|
||||
await setLOAExtension(Number(req.params.id), to);
|
||||
|
||||
audit.leaveOfAbsence('extended', { actorId: req.user.id, targetId: Number(req.params.id) });
|
||||
logger.info('app', 'LOA Extended', { extended_by: req.user.id, LOA: req.params.id })
|
||||
|
||||
res.sendStatus(200);
|
||||
|
||||
@@ -15,6 +15,7 @@ import { logger } from '../services/logging/logger';
|
||||
import { memberCache } from './auth';
|
||||
import { cancelLatestRank } from '../services/db/rankService';
|
||||
import { cancelLatestUnit } from '../services/db/unitService';
|
||||
import { audit } from '../services/logging/auditLog';
|
||||
|
||||
//get all users
|
||||
router.get('/', [requireLogin, requireMemberState(MemberState.Member)], async (req, res) => {
|
||||
@@ -157,7 +158,9 @@ router.put('/settings', [requireLogin], async (req: Request, res: Response) => {
|
||||
|
||||
router.get('/lite', [requireLogin], async (req: Request, res: Response) => {
|
||||
try {
|
||||
let out = await getAllMembersLite();
|
||||
let activeOnly = Boolean(req.query.active);
|
||||
console.log(activeOnly);
|
||||
let out = await getAllMembersLite(activeOnly);
|
||||
res.status(200).json(out);
|
||||
} catch (error) {
|
||||
logger.error(
|
||||
@@ -251,6 +254,9 @@ router.post('/discharge', [requireLogin, requireMemberState(MemberState.Member),
|
||||
con.commit();
|
||||
memberCache.Invalidate(data.userID);
|
||||
|
||||
|
||||
audit.member('discharged', { actorId: req.user.id, targetId: data.userID }, { reason: data.reason });
|
||||
|
||||
res.sendStatus(200);
|
||||
} catch (error) {
|
||||
logger.error('app', 'Failed to discharge user', {
|
||||
@@ -272,6 +278,9 @@ router.post('/suspend', [requireLogin, requireMemberState(MemberState.Member), r
|
||||
let target = Number(req.query.target);
|
||||
try {
|
||||
await setUserState(target, MemberState.Suspended, "Member Suspended", author, null);
|
||||
|
||||
audit.member('suspension_added', { actorId: author, targetId: target });
|
||||
|
||||
res.sendStatus(200);
|
||||
} catch (error) {
|
||||
logger.error('app', 'Failed to suspend user', {
|
||||
@@ -291,6 +300,8 @@ router.post('/unsuspend', [requireLogin, requireMemberState(MemberState.Member),
|
||||
try {
|
||||
let prevState = await getLastNonSuspendedState(target);
|
||||
await setUserState(target, prevState, "Member Suspension Removed", author, null);
|
||||
audit.member('suspension_removed', { actorId: author, targetId: target });
|
||||
|
||||
res.sendStatus(200);
|
||||
} catch (error) {
|
||||
logger.error('app', 'Failed to suspend user', {
|
||||
|
||||
65
api/src/routes/modRequest.ts
Normal file
65
api/src/routes/modRequest.ts
Normal file
@@ -0,0 +1,65 @@
|
||||
const express = require('express');
|
||||
const router = express.Router();
|
||||
|
||||
import { Request, Response } from 'express';
|
||||
import { requireLogin, requireMemberState, requireRole } from '../middleware/auth';
|
||||
import { logger } from '../services/logging/logger';
|
||||
import { audit } from '../services/logging/auditLog';
|
||||
import { MemberState } from '@app/shared/types/member';
|
||||
import { createDiscussion, getAllDiscussions, getDiscussionById } from '../services/db/discussionService';
|
||||
import { ModRequest } from '@app/shared/schemas/modRequest';
|
||||
|
||||
router.use(requireLogin);
|
||||
router.use(requireMemberState(MemberState.Member));
|
||||
|
||||
router.get('/', async (req: Request, res: Response) => {
|
||||
try {
|
||||
const page = parseInt(req.query.page as string) || 1;
|
||||
const pageSize = parseInt(req.query.pageSize as string) || 10;
|
||||
const search = parseInt(req.query.search as string) || null;
|
||||
|
||||
const result = await getAllDiscussions<ModRequest>('mod_request', page, pageSize);
|
||||
|
||||
return res.json(result);
|
||||
} catch (error) {
|
||||
console.error('Error fetching mod requests:', error);
|
||||
res.status(500).json({ error: 'Internal Server Error' });
|
||||
}
|
||||
});
|
||||
|
||||
// GET a single mod request by ID
|
||||
router.get('/:id', async (req: Request, res: Response) => {
|
||||
try {
|
||||
const id = parseInt(req.params.id, 10);
|
||||
if (isNaN(id)) {
|
||||
return res.status(400).json({ error: 'Invalid ID' });
|
||||
}
|
||||
|
||||
const discussion = await getDiscussionById<ModRequest>(id);
|
||||
if (!discussion) {
|
||||
return res.status(404).json({ error: 'Mod request not found' });
|
||||
}
|
||||
|
||||
return res.json(discussion);
|
||||
} catch (error) {
|
||||
console.error('Error fetching mod request by id:', error);
|
||||
res.status(500).json({ error: 'Internal Server Error' });
|
||||
}
|
||||
});
|
||||
|
||||
router.post('/', async (req: Request, res: Response) => {
|
||||
try {
|
||||
let author = req.user.id;
|
||||
let data = req.body as ModRequest;
|
||||
|
||||
let postID = await createDiscussion<ModRequest>('mod_request', author, data.mod_title, data);
|
||||
logger.info('app', 'Mod request posted', {});
|
||||
audit.discussion('created', { actorId: author, targetId: postID }, { type: "mod_request" });
|
||||
return res.status(200).send(postID);
|
||||
} catch (error) {
|
||||
console.error('Error posting a mod request:', error);
|
||||
res.status(500).json({ error: 'Internal Server Error' });
|
||||
}
|
||||
})
|
||||
|
||||
export const modRequestRouter = router;
|
||||
@@ -5,6 +5,7 @@ import { BatchPromotion, BatchPromotionMember } from '@app/shared/schemas/promot
|
||||
|
||||
import express = require('express');
|
||||
import { logger } from "../services/logging/logger";
|
||||
import { audit } from "../services/logging/auditLog";
|
||||
const r = express.Router();
|
||||
const ur = express.Router();
|
||||
|
||||
@@ -21,6 +22,8 @@ ur.post('/', [requireRole(["17th Command", "17th Administrator", "17th HQ"]), re
|
||||
if (!change) res.sendStatus(400);
|
||||
|
||||
await batchInsertMemberRank(change, author, approver);
|
||||
|
||||
audit.member('update_rank', { actorId: author, targetId: null }, { changes: change.length });
|
||||
logger.info('app', 'Promotion batch submitted', { author: author })
|
||||
res.sendStatus(201);
|
||||
} catch (error) {
|
||||
|
||||
@@ -8,6 +8,7 @@ import { requireLogin, requireMemberState, requireRole } from '../middleware/aut
|
||||
import { assignUserGroup, createGroup, getAllRoles, getRole, getUsersWithRole } from '../services/db/rolesService';
|
||||
import { Request, Response } from 'express';
|
||||
import { logger } from '../services/logging/logger';
|
||||
import { audit } from '../services/logging/auditLog';
|
||||
|
||||
r.use(requireLogin)
|
||||
ur.use(requireLogin)
|
||||
@@ -22,6 +23,8 @@ ur.post('/', [requireMemberState(MemberState.Member), requireRole("17th Administ
|
||||
|
||||
logger.info('app', 'User assigned role', { user: body.member_id, role: body.role_id, assigner: req.user.id })
|
||||
res.sendStatus(201);
|
||||
audit.roles('add_member', { actorId: req.user.id, targetId: body.role_id }, { member: body.member_id, role: body.role_id });
|
||||
|
||||
} catch (error) {
|
||||
if (error?.code === 'ER_DUP_ENTRY') {
|
||||
return res.status(400).json({
|
||||
@@ -54,6 +57,7 @@ ur.delete('/', [requireMemberState(MemberState.Member), requireRole("17th Admini
|
||||
await pool.query(sql, [body.member_id, body.role_id])
|
||||
|
||||
logger.info('app', 'User removed role', { user: body.member_id, role: body.role_id, assigner: req.user.id })
|
||||
audit.roles('remove_member', { actorId: req.user.id, targetId: body.role_id }, { member: body.member_id, role: body.role_id });
|
||||
|
||||
res.sendStatus(200);
|
||||
}
|
||||
@@ -77,7 +81,7 @@ ur.delete('/', [requireMemberState(MemberState.Member), requireRole("17th Admini
|
||||
r.get('/', [requireMemberState(MemberState.Member)], async (req, res) => {
|
||||
try {
|
||||
const roles = await getAllRoles();
|
||||
|
||||
|
||||
res.status(200).json(roles);
|
||||
} catch (error) {
|
||||
logger.error(
|
||||
@@ -144,7 +148,8 @@ r.post('/', [requireMemberState(MemberState.Member), requireRole("dev")], async
|
||||
return res.status(400).json({ error: 'Color must be a valid hex color (#ffffff)' });
|
||||
}
|
||||
|
||||
await createGroup(name, color, description);
|
||||
let out = await createGroup(name, color, description);
|
||||
audit.roles('create', { actorId: req.user.id, targetId: out.id });
|
||||
|
||||
res.sendStatus(201);
|
||||
} catch (err) {
|
||||
@@ -159,6 +164,9 @@ r.delete('/:id', [requireMemberState(MemberState.Member), requireRole("dev")], a
|
||||
|
||||
const sql = 'DELETE FROM roles WHERE id = ?';
|
||||
const res = await pool.query(sql, [id]);
|
||||
|
||||
audit.roles('delete', { actorId: req.user.id, targetId: id });
|
||||
|
||||
res.sendStatus(200);
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
|
||||
@@ -19,7 +19,8 @@ export async function createEvent(eventObject: Omit<CalendarEvent, 'id' | 'creat
|
||||
];
|
||||
|
||||
const result = await pool.query(sql, params);
|
||||
return { id: result.insertId, ...eventObject };
|
||||
let id = Number(result.insertId);
|
||||
return id;
|
||||
}
|
||||
|
||||
export async function updateEvent(eventObject: CalendarEvent) {
|
||||
|
||||
150
api/src/services/db/discussionService.ts
Normal file
150
api/src/services/db/discussionService.ts
Normal file
@@ -0,0 +1,150 @@
|
||||
import { toDateTime } from "@app/shared/utils/time";
|
||||
import pool from "../../db";
|
||||
import { LOARequest, LOAType } from '@app/shared/types/loa'
|
||||
import { PagedData } from '@app/shared/types/pagination'
|
||||
import { DiscussionPost } from '@app/shared/types/discussion';
|
||||
import { DiscussionComment } from '@app/shared/types/discussion';
|
||||
|
||||
/**
|
||||
* Retrieves all discussion posts with pagination and optional type filtering.
|
||||
* @template T - The type of content stored in discussion posts
|
||||
* @param {string} [type] - Optional type filter to retrieve only posts of a specific type
|
||||
* @param {number} [page=1] - The page number for pagination (1-indexed)
|
||||
* @param {number} [pageSize=10] - The number of posts per page
|
||||
* @returns {Promise<PagedData<DiscussionPost<T>>>} A promise that resolves to paginated discussion posts with metadata
|
||||
* @throws {Error} If the database query fails
|
||||
*/
|
||||
export async function getAllDiscussions<T>(type?: string, page = 1, pageSize = 10, search?: string): Promise<PagedData<DiscussionPost<T>>> {
|
||||
const offset = (page - 1) * pageSize;
|
||||
const params: any[] = [];
|
||||
|
||||
// Base query parts
|
||||
let whereClause = "WHERE is_deleted = FALSE";
|
||||
if (type) {
|
||||
whereClause += " AND type = ?";
|
||||
params.push(type);
|
||||
}
|
||||
|
||||
const sql = `
|
||||
SELECT
|
||||
p.*,
|
||||
m.name as poster_name
|
||||
FROM discussion_posts AS p
|
||||
LEFT JOIN members m ON p.poster_id = m.id
|
||||
${whereClause}
|
||||
ORDER BY
|
||||
p.is_open DESC, -- Show active/unlocked threads first
|
||||
p.created_at DESC -- Then show newest first
|
||||
LIMIT ? OFFSET ?;
|
||||
`;
|
||||
|
||||
// Add pagination params to the end
|
||||
params.push(pageSize, offset);
|
||||
|
||||
// Execute queries
|
||||
const posts: DiscussionPost<T>[] = await pool.query(sql, params) as DiscussionPost<T>[];
|
||||
|
||||
// Get count for the specific types
|
||||
const countSql = `SELECT COUNT(*) as count FROM discussion_posts ${whereClause}`;
|
||||
const countResult = await pool.query(countSql, type ? [type] : []);
|
||||
const totalCount = Number(countResult[0].count);
|
||||
|
||||
const totalPages = Math.ceil(totalCount / pageSize);
|
||||
|
||||
return {
|
||||
data: posts,
|
||||
pagination: {
|
||||
page,
|
||||
pageSize,
|
||||
total: totalCount,
|
||||
totalPages
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new discussion post.
|
||||
* @template T - The type of content for the discussion post
|
||||
* @param {string} type - The type/category of the discussion post
|
||||
* @param {number} authorID - The ID of the member creating the post
|
||||
* @param {postTitle} string - The title of the discussion post
|
||||
* @param {T} data - The content data to be stored in the post
|
||||
* @returns {Promise<Number>} A promise that resolves to the ID of the newly created post
|
||||
* @throws {Error} If the database insertion fails
|
||||
*/
|
||||
export async function createDiscussion<T>(type: string, authorID: number, postTitle: string, data: T): Promise<number> {
|
||||
const sql = `
|
||||
INSERT INTO discussion_posts (type, poster_id, title, content)
|
||||
VALUES (?, ?, ?, ?)
|
||||
`;
|
||||
|
||||
console.log(data);
|
||||
const result = await pool.query(sql, [
|
||||
type,
|
||||
authorID,
|
||||
postTitle,
|
||||
JSON.stringify(data)
|
||||
]);
|
||||
|
||||
console.log(result);
|
||||
return Number(result.insertId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve a single discussion post by its ID.
|
||||
* @template T - type of the content stored in the post (e.g. ModRequest)
|
||||
* @param {number} id - The id of the discussion post to fetch
|
||||
* @returns {Promise<DiscussionPost<T> | null>} The discussion post or null if not found
|
||||
*/
|
||||
export async function getDiscussionById<T>(id: number): Promise<DiscussionPost<T> | null> {
|
||||
// Get the post
|
||||
const postSql = `
|
||||
SELECT
|
||||
p.*,
|
||||
m.name as poster_name
|
||||
FROM discussion_posts AS p
|
||||
LEFT JOIN members m ON p.poster_id = m.id
|
||||
WHERE p.id = ?
|
||||
LIMIT 1;
|
||||
`;
|
||||
const postResults = (await pool.query(postSql, [id])) as DiscussionPost<T>[];
|
||||
if (postResults.length === 0) {
|
||||
return null;
|
||||
}
|
||||
const post = postResults[0];
|
||||
|
||||
// Get comments for the post
|
||||
const commentSql = `
|
||||
SELECT
|
||||
c.*
|
||||
FROM discussion_comments AS c
|
||||
WHERE c.post_id = ?
|
||||
AND c.is_deleted = FALSE
|
||||
ORDER BY c.created_at ASC;
|
||||
`;
|
||||
const comments = (await pool.query(commentSql, [id])) as DiscussionComment[];
|
||||
|
||||
// Attach comments to post
|
||||
post.comments = comments;
|
||||
|
||||
return post;
|
||||
}
|
||||
|
||||
export async function getPostComments(postID: number): Promise<DiscussionComment[]> {
|
||||
let comments = await pool.query("SELECT * FROM discussion_comments WHERE post_id = ?", [postID]);
|
||||
return comments;
|
||||
}
|
||||
|
||||
export async function postComment(commentData: DiscussionComment, poster: number) {
|
||||
const sql = `
|
||||
INSERT INTO discussion_comments (post_id, poster_id, content) VALUES (?, ?, ?);
|
||||
`;
|
||||
|
||||
const result = await pool.query(sql, [commentData.post_id, poster, commentData.content]);
|
||||
|
||||
if (!result.affectedRows || result.affectedRows !== 1) {
|
||||
throw new Error('Failed to insert comment: expected 1 row to be inserted');
|
||||
}
|
||||
|
||||
return Number(result.insertId);
|
||||
}
|
||||
@@ -74,12 +74,13 @@ export async function getUserActiveLOA(userId: number): Promise<LOARequest[]> {
|
||||
return LOAData;
|
||||
}
|
||||
|
||||
export async function createNewLOA(data: LOARequest) {
|
||||
export async function createNewLOA(data: LOARequest): Promise<number> {
|
||||
const sql = `INSERT INTO leave_of_absences
|
||||
(member_id, filed_date, start_date, end_date, type_id, reason)
|
||||
VALUES (?, ?, ?, ?, ?, ?)`;
|
||||
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;
|
||||
let out = await pool.query(sql, [data.member_id, toDateTime(data.filed_date), toDateTime(data.start_date), toDateTime(data.end_date), data.type_id, data.reason])
|
||||
|
||||
return Number(out.insertId);
|
||||
}
|
||||
|
||||
export async function closeLOA(id: number, closer: number) {
|
||||
|
||||
@@ -170,14 +170,16 @@ export async function getMembersLite(ids: number[]): Promise<MemberLight[]> {
|
||||
return res;
|
||||
}
|
||||
|
||||
export async function getAllMembersLite(): Promise<MemberLight[]> {
|
||||
export async function getAllMembersLite(activeOnly: boolean): Promise<MemberLight[]> {
|
||||
|
||||
const filter = activeOnly ? `\nWHERE member_state = ${MemberState.Member}` : ''
|
||||
const sql = `SELECT m.member_id AS id,
|
||||
m.member_name AS username,
|
||||
m.displayName,
|
||||
u.color
|
||||
FROM view_member_rank_unit_status_latest m
|
||||
LEFT JOIN units u ON u.name = m.unit;`;
|
||||
|
||||
LEFT JOIN units u ON u.name = m.unit ${filter};`;
|
||||
console.log(sql);
|
||||
const res: MemberLight[] = await pool.query(sql);
|
||||
return res;
|
||||
}
|
||||
|
||||
65
api/src/services/logging/auditLog.ts
Normal file
65
api/src/services/logging/auditLog.ts
Normal file
@@ -0,0 +1,65 @@
|
||||
import pool from "../../db";
|
||||
import { logger } from "./logger";
|
||||
|
||||
export type AuditArea = 'member' | 'calendar' | 'roles' | 'auth' | 'leave_of_absence' | 'application' | 'course' | 'discussion';
|
||||
|
||||
export interface AuditContext {
|
||||
actorId: number; // The person doing the action (created_by)
|
||||
targetId?: number; // The ID of the thing being changed (target_id)
|
||||
}
|
||||
|
||||
class AuditLogger {
|
||||
async record(
|
||||
area: AuditArea,
|
||||
action: string,
|
||||
context: AuditContext,
|
||||
data: Record<string, any> = {} // Already optional with default {}
|
||||
) {
|
||||
const actionType = `${area}.${action}`;
|
||||
|
||||
try {
|
||||
await pool.query(
|
||||
`INSERT INTO audit_log (action_type, payload, target_id, created_by)
|
||||
VALUES (?, ?, ?, ?)`, // Fixed: removed extra comma/placeholder
|
||||
[
|
||||
actionType,
|
||||
JSON.stringify(data),
|
||||
context.targetId || null,
|
||||
context.actorId,
|
||||
]
|
||||
);
|
||||
} catch (err) {
|
||||
logger.error('audit', `AUDIT_FAILURE: Failed to log ${actionType}`, { error: err });
|
||||
}
|
||||
}
|
||||
|
||||
member(action: 'update_rank' | 'suspension_added' | 'suspension_removed' | 'discharged', context: AuditContext, data: any = {}) {
|
||||
return this.record('member', action, context, data);
|
||||
}
|
||||
|
||||
roles(action: 'add_member' | 'remove_member' | 'create' | 'delete', context: AuditContext, data: any = {}) {
|
||||
return this.record('roles', action, context, data);
|
||||
}
|
||||
|
||||
leaveOfAbsence(action: 'created' | 'admin_created' | 'ended' | 'admin_ended' | 'extended', context: AuditContext, data: any = {}) {
|
||||
return this.record('leave_of_absence', action, context, data);
|
||||
}
|
||||
|
||||
calendar(action: 'event_created' | 'event_updated' | 'attendance_set' | 'cancelled' | 'un-cancelled', context: AuditContext, data: any = {}) {
|
||||
return this.record('calendar', action, context, data);
|
||||
}
|
||||
|
||||
application(action: 'created' | 'approved' | 'denied' | 'restarted', context: AuditContext, data: any = {}) {
|
||||
return this.record('application', action, context, data);
|
||||
}
|
||||
|
||||
course(action: 'report_created' | 'report_edited', context: AuditContext, data: any = {}) {
|
||||
return this.record('course', action, context, data);
|
||||
}
|
||||
|
||||
discussion(action: 'created' | 'comment_posted', context: AuditContext, data: any = {}) {
|
||||
return this.record('discussion', action, context, data);
|
||||
}
|
||||
}
|
||||
|
||||
export const audit = new AuditLogger();
|
||||
@@ -1,6 +1,6 @@
|
||||
export type LogLevel = 'debug' | 'info' | 'warn' | 'error';
|
||||
export type LogDepth = 'normal' | 'verbose' | 'profiling';
|
||||
export type LogType = 'http' | 'app' | 'auth' | 'profiling';
|
||||
export type LogType = 'http' | 'app' | 'auth' | 'profiling' | 'audit';
|
||||
|
||||
export interface LogHeader {
|
||||
timestamp: string;
|
||||
|
||||
24
shared/schemas/modRequest.ts
Normal file
24
shared/schemas/modRequest.ts
Normal file
@@ -0,0 +1,24 @@
|
||||
import { z } from 'zod';
|
||||
|
||||
export const ModRequestSchema = z.object({
|
||||
// Basic Info
|
||||
mod_title: z.string().min(1),
|
||||
description: z.string().min(1),
|
||||
mod_link: z.string().min(1),
|
||||
|
||||
// Consolidated Testing
|
||||
confirmed_tested: z.boolean().refine(val => val === true, {
|
||||
message: "You must confirm that you have tested this mod before submitting"
|
||||
}),
|
||||
|
||||
// Vetting
|
||||
reason: z.string().min(1),
|
||||
|
||||
// Compatibility & Technical
|
||||
detrimental_effects: z.string().min(1),
|
||||
keybind_conflicts: z.string(),
|
||||
|
||||
special_considerations: z.string().optional()
|
||||
});
|
||||
|
||||
export type ModRequest = z.infer<typeof ModRequestSchema>;
|
||||
24
shared/types/discussion.ts
Normal file
24
shared/types/discussion.ts
Normal file
@@ -0,0 +1,24 @@
|
||||
export interface DiscussionPost<T = any> {
|
||||
id: number;
|
||||
type: string;
|
||||
poster_id: number;
|
||||
poster_name?: string;
|
||||
title: string;
|
||||
content: T;
|
||||
created_at: Date;
|
||||
updated_at: Date;
|
||||
is_deleted: boolean;
|
||||
is_locked: boolean;
|
||||
is_open: boolean;
|
||||
comments?: DiscussionComment[];
|
||||
}
|
||||
|
||||
export interface DiscussionComment {
|
||||
id?: number;
|
||||
post_id: number;
|
||||
poster_id?: number;
|
||||
content: string;
|
||||
created_at?: Date;
|
||||
updated_at?: Date;
|
||||
is_deleted?: boolean;
|
||||
}
|
||||
36
ui/src/api/discussion.ts
Normal file
36
ui/src/api/discussion.ts
Normal file
@@ -0,0 +1,36 @@
|
||||
import { DiscussionComment } from "@shared/types/discussion";
|
||||
|
||||
//@ts-expect-error
|
||||
const addr = import.meta.env.VITE_APIHOST;
|
||||
|
||||
export async function postComment(comment: DiscussionComment) {
|
||||
const res = await fetch(`${addr}/discussions/comment`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify(comment),
|
||||
credentials: 'include',
|
||||
});
|
||||
|
||||
if (res.ok) {
|
||||
return;
|
||||
} else {
|
||||
throw new Error("Failed to submit LOA");
|
||||
}
|
||||
}
|
||||
|
||||
export async function getPostComments(postId: number): Promise<DiscussionComment[]> {
|
||||
const res = await fetch(`${addr}/discussions/${postId}/comments`, {
|
||||
method: "GET",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
credentials: 'include',
|
||||
});
|
||||
if (!res.ok) {
|
||||
throw new Error("Failed to fetch comments");
|
||||
}
|
||||
return res.json();
|
||||
}
|
||||
|
||||
@@ -169,6 +169,23 @@ export async function extendLOA(id: number, to: Date) {
|
||||
}
|
||||
});
|
||||
|
||||
if (res.ok) {
|
||||
return
|
||||
} else {
|
||||
throw new Error("Could not extend LOA");
|
||||
}
|
||||
}
|
||||
|
||||
export async function adminExtendLOA(id: number, to: Date) {
|
||||
const res = await fetch(`${addr}/loa/extendAdmin/${id}`, {
|
||||
method: "POST",
|
||||
credentials: 'include',
|
||||
body: JSON.stringify({ to }),
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
}
|
||||
});
|
||||
|
||||
if (res.ok) {
|
||||
return
|
||||
} else {
|
||||
|
||||
@@ -66,8 +66,8 @@ export async function setMemberSettings(settings: memberSettings) {
|
||||
return;
|
||||
}
|
||||
|
||||
export async function getAllLightMembers(): Promise<MemberLight[]> {
|
||||
const response = await fetch(`${addr}/members/lite`, {
|
||||
export async function getAllLightMembers(activeOnly: boolean = true): Promise<MemberLight[]> {
|
||||
const response = await fetch(`${addr}/members/lite${activeOnly ? '?active=true' : '?active=false'}`, {
|
||||
credentials: 'include',
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
|
||||
72
ui/src/api/modRequests.ts
Normal file
72
ui/src/api/modRequests.ts
Normal file
@@ -0,0 +1,72 @@
|
||||
import { ModRequest } from "@shared/schemas/modRequest";
|
||||
import { DiscussionPost } from "@shared/types/discussion";
|
||||
import { PagedData } from "@shared/types/pagination";
|
||||
|
||||
//@ts-expect-error
|
||||
const addr = import.meta.env.VITE_APIHOST;
|
||||
|
||||
export async function getModRequests(page?: number, pageSize?: number): Promise<PagedData<DiscussionPost<ModRequest>>> {
|
||||
const params = new URLSearchParams();
|
||||
|
||||
if (page !== undefined) {
|
||||
params.set("page", page.toString());
|
||||
}
|
||||
|
||||
if (pageSize !== undefined) {
|
||||
params.set("pageSize", pageSize.toString());
|
||||
}
|
||||
|
||||
return fetch(`${addr}/mod-request?${params}`, {
|
||||
method: "GET",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
credentials: 'include',
|
||||
}).then((res) => {
|
||||
if (res.ok) {
|
||||
return res.json();
|
||||
} else {
|
||||
return [];
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Posts a new mod request to the server
|
||||
* @param data Form data
|
||||
* @returns Numerical ID of the new post
|
||||
*/
|
||||
export async function postModRequest(data: ModRequest): Promise<Number> {
|
||||
return fetch(`${addr}/mod-request`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
credentials: 'include',
|
||||
body: JSON.stringify(data)
|
||||
}).then((res) => {
|
||||
if (res.ok) {
|
||||
return res.text().then((id) => Number(id));
|
||||
} else {
|
||||
throw new Error("Failed to post mod request");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve a single mod request by its discussion post ID
|
||||
* @param id numeric post id
|
||||
*/
|
||||
export async function getModRequest(id: number): Promise<DiscussionPost<ModRequest>> {
|
||||
const res = await fetch(`${addr}/mod-request/${id}`, {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
credentials: 'include',
|
||||
});
|
||||
if (!res.ok) {
|
||||
throw new Error(`Failed to fetch mod request ${id}`);
|
||||
}
|
||||
return res.json();
|
||||
}
|
||||
@@ -1,46 +1,46 @@
|
||||
<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';
|
||||
import DropdownMenuGroup from '../ui/dropdown-menu/DropdownMenuGroup.vue';
|
||||
import DropdownMenuSeparator from '../ui/dropdown-menu/DropdownMenuSeparator.vue';
|
||||
import { MemberState } from '@shared/types/member';
|
||||
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';
|
||||
import DropdownMenuGroup from '../ui/dropdown-menu/DropdownMenuGroup.vue';
|
||||
import DropdownMenuSeparator from '../ui/dropdown-menu/DropdownMenuSeparator.vue';
|
||||
import { MemberState } from '@shared/types/member';
|
||||
|
||||
const userStore = useUserStore();
|
||||
const auth = useAuth();
|
||||
const userStore = useUserStore();
|
||||
const auth = useAuth();
|
||||
|
||||
//@ts-ignore
|
||||
const APIHOST = import.meta.env.VITE_APIHOST;
|
||||
//@ts-ignore
|
||||
const DOCHOST = import.meta.env.VITE_DOCHOST;
|
||||
//@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";
|
||||
}
|
||||
async function logout() {
|
||||
userStore.user = null;
|
||||
window.location.href = APIHOST + "/logout";
|
||||
}
|
||||
|
||||
function blurAfter() {
|
||||
requestAnimationFrame(() => {
|
||||
(document.activeElement as HTMLElement)?.blur();
|
||||
});
|
||||
}
|
||||
function blurAfter() {
|
||||
requestAnimationFrame(() => {
|
||||
(document.activeElement as HTMLElement)?.blur();
|
||||
});
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -52,7 +52,8 @@ function blurAfter() {
|
||||
<img src="/17RBN_Logo.png" class="w-10 h-10 object-contain"></img>
|
||||
</RouterLink>
|
||||
<!-- Member navigation -->
|
||||
<div v-if="auth.accountStatus.value == MemberState.Member" class="h-15 flex items-center justify-center">
|
||||
<div v-if="auth.accountStatus.value == MemberState.Member"
|
||||
class="h-15 flex items-center justify-center">
|
||||
<NavigationMenu>
|
||||
<NavigationMenuList class="gap-3">
|
||||
|
||||
@@ -101,6 +102,19 @@ function blurAfter() {
|
||||
</NavigationMenuContent>
|
||||
</NavigationMenuItem>
|
||||
|
||||
<!-- Discussions (Dropdown) -->
|
||||
<NavigationMenuItem class="bg-none !focus:bg-none !active:bg-none">
|
||||
<NavigationMenuTrigger>Discussions</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="/discussions/mod-requests" @click="blurAfter">
|
||||
Mod Requests
|
||||
</RouterLink>
|
||||
</NavigationMenuLink>
|
||||
</NavigationMenuContent>
|
||||
</NavigationMenuItem>
|
||||
|
||||
<!-- Administration (Dropdown) -->
|
||||
<NavigationMenuItem
|
||||
v-if="auth.hasAnyRole(['17th Administrator', '17th HQ', '17th Command', 'Recruiter'])">
|
||||
|
||||
42
ui/src/components/discussion/CommentForm.vue
Normal file
42
ui/src/components/discussion/CommentForm.vue
Normal file
@@ -0,0 +1,42 @@
|
||||
<script setup lang="ts">
|
||||
import { ref } from 'vue';
|
||||
import Textarea from '../ui/textarea/Textarea.vue';
|
||||
import Button from '../ui/button/Button.vue';
|
||||
import { postComment } from '@/api/discussion';
|
||||
import { DiscussionComment } from '@shared/types/discussion';
|
||||
|
||||
const props = defineProps<{
|
||||
parentId: number,
|
||||
}>();
|
||||
|
||||
const emit = defineEmits(['commentPosted']);
|
||||
const commentText = ref('');
|
||||
const error = ref('');
|
||||
|
||||
async function submitComment(e: Event) {
|
||||
e.preventDefault();
|
||||
error.value = '';
|
||||
if (!commentText.value.trim()) {
|
||||
error.value = 'Comment cannot be empty';
|
||||
return;
|
||||
}
|
||||
let newComment: DiscussionComment = { post_id: props.parentId, content: commentText.value.trim() };
|
||||
await postComment(newComment);
|
||||
emit('commentPosted');
|
||||
commentText.value = '';
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<form @submit="submitComment">
|
||||
<div class="mb-2">
|
||||
<label class="block font-medium mb-1">Add a comment</label>
|
||||
<Textarea rows="3" class="bg-neutral-800 resize-none w-full" v-model="commentText"
|
||||
placeholder="Add a comment…" />
|
||||
<div class="h-4 text-red-500 text-sm mt-1" v-if="error">{{ error }}</div>
|
||||
</div>
|
||||
<div class="mt-2 flex justify-end">
|
||||
<Button type="submit" :disabled="!commentText.trim()">Post Comment</Button>
|
||||
</div>
|
||||
</form>
|
||||
</template>
|
||||
40
ui/src/components/discussion/CommentThread.vue
Normal file
40
ui/src/components/discussion/CommentThread.vue
Normal file
@@ -0,0 +1,40 @@
|
||||
<script setup lang="ts">
|
||||
|
||||
import { DiscussionComment } from '@shared/types/discussion';
|
||||
import DiscussionCommentView from './DiscussionCommentView.vue';
|
||||
import CommentForm from './CommentForm.vue';
|
||||
import { ref } from 'process';
|
||||
import { getPostComments } from '@/api/discussion';
|
||||
|
||||
const props = defineProps<{
|
||||
parentId: number,
|
||||
comments: DiscussionComment[]
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
(e: 'commentsUpdated', comments: DiscussionComment[]): void
|
||||
}>()
|
||||
|
||||
async function onCommentPosted() {
|
||||
const res = await getPostComments(props.parentId);
|
||||
console.log(res);
|
||||
// tell parent to update state
|
||||
emit('commentsUpdated', res);
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="mt-10 *:my-5">
|
||||
<h3 class="text-xl font-semibold">Discussion</h3>
|
||||
<div class="comment-thread">
|
||||
<div class="comments-list flex flex-col gap-5">
|
||||
<div v-for="comment in comments" :key="comment.id" class="comment">
|
||||
<DiscussionCommentView :comment="comment"></DiscussionCommentView>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<CommentForm :parent-id="props.parentId" @commentPosted="onCommentPosted" />
|
||||
</div>
|
||||
|
||||
</div>
|
||||
</template>
|
||||
26
ui/src/components/discussion/DiscussionCommentView.vue
Normal file
26
ui/src/components/discussion/DiscussionCommentView.vue
Normal file
@@ -0,0 +1,26 @@
|
||||
<script setup lang="ts">
|
||||
import { DiscussionComment } from '@shared/types/discussion';
|
||||
import MemberCard from '../members/MemberCard.vue';
|
||||
|
||||
const props = defineProps<{
|
||||
comment: DiscussionComment;
|
||||
}>();
|
||||
</script>
|
||||
|
||||
|
||||
<template>
|
||||
<div class="rounded-md border border-neutral-800 p-3 space-y-5">
|
||||
<!-- Comment header -->
|
||||
<div class="flex justify-between">
|
||||
<MemberCard :member-id="comment.poster_id"></MemberCard>
|
||||
<p class="text-muted-foreground">{{ new Date(comment.created_at).toLocaleString("EN-us", {
|
||||
year: "numeric",
|
||||
month: "long",
|
||||
day: "numeric",
|
||||
hour: "2-digit",
|
||||
minute: "2-digit"
|
||||
}) }}</p>
|
||||
</div>
|
||||
<p>{{ comment.content }}</p>
|
||||
</div>
|
||||
</template>
|
||||
@@ -1,138 +1,141 @@
|
||||
<script setup lang="ts">
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCaption,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from "@/components/ui/table"
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/components/ui/dropdown-menu"
|
||||
import { ChevronDown, ChevronUp, Ellipsis, X } from "lucide-vue-next";
|
||||
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";
|
||||
import MemberCard from "../members/MemberCard.vue";
|
||||
import {
|
||||
Pagination,
|
||||
PaginationContent,
|
||||
PaginationEllipsis,
|
||||
PaginationItem,
|
||||
PaginationNext,
|
||||
PaginationPrevious,
|
||||
} from '@/components/ui/pagination'
|
||||
import { pagination } from "@shared/types/pagination";
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCaption,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from "@/components/ui/table"
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/components/ui/dropdown-menu"
|
||||
import { ChevronDown, ChevronUp, Ellipsis, X } from "lucide-vue-next";
|
||||
import { adminExtendLOA, 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";
|
||||
import MemberCard from "../members/MemberCard.vue";
|
||||
import {
|
||||
Pagination,
|
||||
PaginationContent,
|
||||
PaginationEllipsis,
|
||||
PaginationItem,
|
||||
PaginationNext,
|
||||
PaginationPrevious,
|
||||
} from '@/components/ui/pagination'
|
||||
import { pagination } from "@shared/types/pagination";
|
||||
|
||||
const props = defineProps<{
|
||||
adminMode?: boolean
|
||||
}>()
|
||||
const props = defineProps<{
|
||||
adminMode?: boolean
|
||||
}>()
|
||||
|
||||
const LOAList = ref<LOARequest[]>([]);
|
||||
const LOAList = ref<LOARequest[]>([]);
|
||||
|
||||
onMounted(async () => {
|
||||
await loadLOAs();
|
||||
});
|
||||
|
||||
async function loadLOAs() {
|
||||
if (props.adminMode) {
|
||||
let result = await getAllLOAs(pageNum.value, pageSize.value);
|
||||
LOAList.value = result.data;
|
||||
pageData.value = result.pagination;
|
||||
} else {
|
||||
let result = await getMyLOAs(pageNum.value, pageSize.value);
|
||||
LOAList.value = result.data;
|
||||
pageData.value = result.pagination;
|
||||
}
|
||||
}
|
||||
|
||||
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",
|
||||
onMounted(async () => {
|
||||
await loadLOAs();
|
||||
});
|
||||
}
|
||||
|
||||
function loaStatus(loa: LOARequest): "Upcoming" | "Active" | "Extended" | "Overdue" | "Closed" {
|
||||
if (loa.closed) return "Closed";
|
||||
async function loadLOAs() {
|
||||
if (props.adminMode) {
|
||||
let result = await getAllLOAs(pageNum.value, pageSize.value);
|
||||
LOAList.value = result.data;
|
||||
pageData.value = result.pagination;
|
||||
} else {
|
||||
let result = await getMyLOAs(pageNum.value, pageSize.value);
|
||||
LOAList.value = result.data;
|
||||
pageData.value = result.pagination;
|
||||
}
|
||||
}
|
||||
|
||||
const now = new Date();
|
||||
const start = new Date(loa.start_date);
|
||||
const end = new Date(loa.end_date);
|
||||
const extension = new Date(loa.extended_till);
|
||||
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",
|
||||
});
|
||||
}
|
||||
|
||||
if (now < start) return "Upcoming";
|
||||
if (now >= start && (now <= end)) return "Active";
|
||||
if (now >= start && (now <= extension)) return "Extended";
|
||||
if (now > loa.extended_till || end) return "Overdue";
|
||||
function loaStatus(loa: LOARequest): "Upcoming" | "Active" | "Extended" | "Overdue" | "Closed" {
|
||||
if (loa.closed) return "Closed";
|
||||
|
||||
return "Overdue"; // fallback
|
||||
}
|
||||
const now = new Date();
|
||||
const start = new Date(loa.start_date);
|
||||
const end = new Date(loa.end_date);
|
||||
const extension = new Date(loa.extended_till);
|
||||
|
||||
async function cancelAndReload(id: number) {
|
||||
await cancelLOA(id, props.adminMode);
|
||||
await loadLOAs();
|
||||
}
|
||||
if (now < start) return "Upcoming";
|
||||
if (now >= start && (now <= end)) return "Active";
|
||||
if (now >= start && (now <= extension)) return "Extended";
|
||||
if (now > loa.extended_till || end) return "Overdue";
|
||||
|
||||
const isExtending = ref(false);
|
||||
const targetLOA = ref<LOARequest | null>(null);
|
||||
const extendTo = ref<CalendarDate | null>(null);
|
||||
return "Overdue"; // fallback
|
||||
}
|
||||
|
||||
const targetEnd = computed(() => { return targetLOA.value.extended_till ? targetLOA.value.extended_till : targetLOA.value.end_date })
|
||||
async function cancelAndReload(id: number) {
|
||||
await cancelLOA(id, props.adminMode);
|
||||
await loadLOAs();
|
||||
}
|
||||
|
||||
function toCalendarDate(date: Date): CalendarDate {
|
||||
if (typeof date === 'string')
|
||||
date = new Date(date);
|
||||
return new CalendarDate(date.getFullYear(), date.getMonth() + 1, date.getDate())
|
||||
}
|
||||
const isExtending = ref(false);
|
||||
const targetLOA = ref<LOARequest | null>(null);
|
||||
const extendTo = ref<CalendarDate | null>(null);
|
||||
|
||||
async function commitExtend() {
|
||||
await extendLOA(targetLOA.value.id, extendTo.value.toDate(getLocalTimeZone()));
|
||||
isExtending.value = false;
|
||||
await loadLOAs();
|
||||
}
|
||||
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())
|
||||
}
|
||||
|
||||
const expanded = ref<number | null>(null);
|
||||
const hoverID = ref<number | null>(null);
|
||||
async function commitExtend() {
|
||||
if (props.adminMode) {
|
||||
await adminExtendLOA(targetLOA.value.id, extendTo.value.toDate(getLocalTimeZone()));
|
||||
} else {
|
||||
await extendLOA(targetLOA.value.id, extendTo.value.toDate(getLocalTimeZone()));
|
||||
}
|
||||
isExtending.value = false;
|
||||
await loadLOAs();
|
||||
}
|
||||
|
||||
const pageNum = ref<number>(1);
|
||||
const pageData = ref<pagination>();
|
||||
const expanded = ref<number | null>(null);
|
||||
const hoverID = ref<number | null>(null);
|
||||
|
||||
const pageSize = ref<number>(15)
|
||||
const pageSizeOptions = [10, 15, 30]
|
||||
const pageNum = ref<number>(1);
|
||||
const pageData = ref<pagination>();
|
||||
|
||||
function setPageSize(size: number) {
|
||||
pageSize.value = size
|
||||
pageNum.value = 1;
|
||||
loadLOAs();
|
||||
}
|
||||
const pageSize = ref<number>(15)
|
||||
const pageSizeOptions = [10, 15, 30]
|
||||
|
||||
function setPage(pagenum: number) {
|
||||
pageNum.value = pagenum;
|
||||
loadLOAs();
|
||||
}
|
||||
function setPageSize(size: number) {
|
||||
pageSize.value = size
|
||||
pageNum.value = 1;
|
||||
loadLOAs();
|
||||
}
|
||||
|
||||
function setPage(pagenum: number) {
|
||||
pageNum.value = pagenum;
|
||||
loadLOAs();
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -145,7 +148,7 @@ function setPage(pagenum: number) {
|
||||
<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 })" />
|
||||
:max-value="props.adminMode ? toCalendarDate(targetEnd).add({ years: 1 }) : toCalendarDate(targetEnd).add({ months: 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
|
||||
@@ -205,9 +208,10 @@ function setPage(pagenum: number) {
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent>
|
||||
<DropdownMenuItem v-if="!post.closed && props.adminMode"
|
||||
<DropdownMenuItem v-if="!post.closed"
|
||||
:disabled="post.extended_till !== null && !props.adminMode"
|
||||
@click="isExtending = true; targetLOA = post">
|
||||
Extend
|
||||
{{ (post.extended_till !== null && !props.adminMode) ? 'Extend (Already Extended)' : 'Extend' }}
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem v-if="!post.closed" :variant="'destructive'"
|
||||
@click="cancelAndReload(post.id)">{{ loaStatus(post) === 'Upcoming' ?
|
||||
@@ -256,7 +260,7 @@ function setPage(pagenum: number) {
|
||||
<div class="">
|
||||
<p class="text-muted-foreground">Extended to</p>
|
||||
<p class="font-medium text-foreground">
|
||||
{{post.extended_till ? formatDate(post.extended_till) : 'N/A' }}
|
||||
{{ post.extended_till ? formatDate(post.extended_till) : 'N/A' }}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
241
ui/src/components/modRequests/ModRequestForm.vue
Normal file
241
ui/src/components/modRequests/ModRequestForm.vue
Normal file
@@ -0,0 +1,241 @@
|
||||
<script setup lang="ts">
|
||||
import { ModRequestSchema } from '@shared/schemas/modRequest'
|
||||
import { useForm, Field as VeeField } from 'vee-validate'
|
||||
import { toTypedSchema } from '@vee-validate/zod'
|
||||
import { ref } from 'vue'
|
||||
import Button from '@/components/ui/button/Button.vue'
|
||||
import Field from '@/components/ui/field/Field.vue'
|
||||
import FieldLabel from '@/components/ui/field/FieldLabel.vue'
|
||||
import FieldError from '@/components/ui/field/FieldError.vue'
|
||||
import FieldDescription from '@/components/ui/field/FieldDescription.vue'
|
||||
import Input from '@/components/ui/input/Input.vue'
|
||||
import Textarea from '@/components/ui/textarea/Textarea.vue'
|
||||
import Checkbox from '@/components/ui/checkbox/Checkbox.vue'
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { Separator } from '@/components/ui/separator'
|
||||
import { X } from 'lucide-vue-next'
|
||||
import { postModRequest } from '@/api/modRequests'
|
||||
|
||||
const { handleSubmit, resetForm, errors } = useForm({
|
||||
validationSchema: toTypedSchema(ModRequestSchema),
|
||||
validateOnMount: false,
|
||||
initialValues: {
|
||||
mod_title: '',
|
||||
description: '',
|
||||
mod_link: '',
|
||||
confirmed_tested: false,
|
||||
reason: '',
|
||||
detrimental_effects: '',
|
||||
keybind_conflicts: '',
|
||||
special_considerations: '',
|
||||
},
|
||||
})
|
||||
|
||||
const submitting = ref(false)
|
||||
const emit = defineEmits(['submit', 'close'])
|
||||
|
||||
const submitForm = handleSubmit(async (values) => {
|
||||
if (submitting.value) return
|
||||
submitting.value = true
|
||||
try {
|
||||
await postModRequest(values);
|
||||
emit('submit', values)
|
||||
} catch (err) {
|
||||
console.error('Error submitting mod request:', err)
|
||||
} finally {
|
||||
submitting.value = false
|
||||
}
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Card class="border-0 shadow-sm">
|
||||
<CardHeader>
|
||||
<div class="flex items-start justify-between">
|
||||
<div class="flex-1">
|
||||
<CardTitle>New Mod Request</CardTitle>
|
||||
<CardDescription>Share details about the mod you'd like to see added to our server</CardDescription>
|
||||
</div>
|
||||
<Button type="button" variant="ghost" @click="emit('close')"
|
||||
class="text-muted-foreground hover:text-foreground -mt-1 -mr-2">
|
||||
Back to posts <X></X>
|
||||
</Button>
|
||||
</div>
|
||||
</CardHeader>
|
||||
|
||||
<Separator class="mb-0" />
|
||||
|
||||
<CardContent>
|
||||
<form @submit.prevent="submitForm" class="space-y-8">
|
||||
<!-- SECTION: Basic Mod Information -->
|
||||
<div class="space-y-5">
|
||||
<div class="space-y-1">
|
||||
<h3 class="font-semibold text-sm text-foreground">Mod Information</h3>
|
||||
<p class="text-xs text-muted-foreground">Core details about the mod</p>
|
||||
</div>
|
||||
|
||||
<div class="space-y-5">
|
||||
<!-- Title -->
|
||||
<VeeField name="mod_title" v-slot="{ field, errors: e }">
|
||||
<Field :data-invalid="!!e.length">
|
||||
<FieldLabel class="text-sm font-medium">Mod Title</FieldLabel>
|
||||
<Input v-bind="field" placeholder="Name of the mod" rows="4" class="resize-none mt-2" />
|
||||
<div class="h-4">
|
||||
<FieldError v-if="e.length" :errors="e" />
|
||||
</div>
|
||||
</Field>
|
||||
</VeeField>
|
||||
|
||||
<!-- Description -->
|
||||
<VeeField name="description" v-slot="{ field, errors: e }">
|
||||
<Field :data-invalid="!!e.length">
|
||||
<FieldLabel class="text-sm font-medium">What is this mod?</FieldLabel>
|
||||
<FieldDescription class="text-xs">Brief overview of the mod and its main functionality
|
||||
</FieldDescription>
|
||||
<Textarea v-bind="field" placeholder="Describe what this mod does..." rows="4"
|
||||
class="resize-none mt-2" />
|
||||
<div class="h-4">
|
||||
<FieldError v-if="e.length" :errors="e" />
|
||||
</div>
|
||||
</Field>
|
||||
</VeeField>
|
||||
|
||||
<!-- Mod Link -->
|
||||
<VeeField name="mod_link" v-slot="{ field, errors: e }">
|
||||
<Field :data-invalid="!!e.length">
|
||||
<FieldLabel class="text-sm font-medium">Mod Link</FieldLabel>
|
||||
<FieldDescription class="text-xs">Where can this mod be found?</FieldDescription>
|
||||
<Input v-bind="field" placeholder="https://..." class="mt-2" />
|
||||
<div class="h-4">
|
||||
<FieldError v-if="e.length" :errors="e" />
|
||||
</div>
|
||||
</Field>
|
||||
</VeeField>
|
||||
|
||||
<!-- Reason -->
|
||||
<VeeField name="reason" v-slot="{ field, errors: e }">
|
||||
<Field :data-invalid="!!e.length">
|
||||
<FieldLabel class="text-sm font-medium">Why add this mod?</FieldLabel>
|
||||
<FieldDescription class="text-xs">What benefits does this mod bring to our community and
|
||||
why should we consider it?
|
||||
</FieldDescription>
|
||||
<Textarea v-bind="field" placeholder="Share your thoughts..." rows="3"
|
||||
class="resize-none mt-2" />
|
||||
<div class="h-4">
|
||||
<FieldError v-if="e.length" :errors="e" />
|
||||
</div>
|
||||
</Field>
|
||||
</VeeField>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Separator />
|
||||
|
||||
<!-- SECTION: Testing & Verification -->
|
||||
<div class="space-y-5">
|
||||
<div class="space-y-1">
|
||||
<h3 class="font-semibold text-sm text-foreground">Testing & Verification</h3>
|
||||
<p class="text-xs text-muted-foreground">Your experience with this mod</p>
|
||||
</div>
|
||||
|
||||
<div class="space-y-5">
|
||||
<!-- Confirmed Tested -->
|
||||
<VeeField name="confirmed_tested" v-slot="{ field, errors: e }">
|
||||
<Field :data-invalid="!!e.length">
|
||||
<div class="flex items-center gap-3 p-3 rounded-md bg-muted/30 border border-border/50">
|
||||
<Checkbox :model-value="field.value" @update:model-value="field.onChange"
|
||||
class="hover:cursor-pointer" />
|
||||
<div class="flex-1">
|
||||
<FieldLabel class="font-medium text-md cursor-pointer">Testing & Stability
|
||||
Confirmation
|
||||
</FieldLabel>
|
||||
<FieldDescription class="text-sm">I confirm that I have personally tested this
|
||||
mod and to the best of my ability have verified that it functions as
|
||||
described without
|
||||
causing game-breaking bugs,
|
||||
critical stability issues, or unintended performance degradation.
|
||||
</FieldDescription>
|
||||
</div>
|
||||
</div>
|
||||
<div class="h-4">
|
||||
<FieldError v-if="e.length" :errors="e" />
|
||||
</div>
|
||||
</Field>
|
||||
</VeeField>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Separator />
|
||||
|
||||
<!-- SECTION: Compatibility -->
|
||||
<div class="space-y-5">
|
||||
<div class="space-y-1">
|
||||
<h3 class="font-semibold text-sm text-foreground">Compatibility & Conflicts</h3>
|
||||
<p class="text-xs text-muted-foreground">How does it work with our current setup?</p>
|
||||
</div>
|
||||
|
||||
<div class="space-y-5">
|
||||
<!-- Detrimental Effects -->
|
||||
<VeeField name="detrimental_effects" v-slot="{ field, errors: e }">
|
||||
<Field :data-invalid="!!e.length">
|
||||
<FieldLabel class="text-sm font-medium">Potential Issues</FieldLabel>
|
||||
<FieldDescription class="text-xs">Any negative impacts or concerns you noticed (Keybind
|
||||
conflicts sould be noted in the dedicated section)?
|
||||
</FieldDescription>
|
||||
<Textarea v-bind="field" placeholder="List any issues... (leave blank if none)" rows="3"
|
||||
class="resize-none mt-2" />
|
||||
<div class="h-4">
|
||||
<FieldError v-if="e.length" :errors="e" />
|
||||
</div>
|
||||
</Field>
|
||||
</VeeField>
|
||||
|
||||
<!-- Keybind Conflicts -->
|
||||
<VeeField name="keybind_conflicts" v-slot="{ field, errors: e }">
|
||||
<Field :data-invalid="!!e.length">
|
||||
<FieldLabel class="text-sm font-medium">Keybind Conflicts</FieldLabel>
|
||||
<FieldDescription class="text-xs">Identify any controls that conflict with the existing
|
||||
modpack along with resolutions for those conflicts.
|
||||
</FieldDescription>
|
||||
<Textarea v-bind="field"
|
||||
placeholder='List specific conflicts and resolutions here, or type "None" if there are no conflicts.'
|
||||
rows="3" class="resize-none mt-2" />
|
||||
<div class="h-4">
|
||||
<FieldError v-if="e.length" :errors="e" />
|
||||
</div>
|
||||
</Field>
|
||||
</VeeField>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Separator />
|
||||
|
||||
<!-- SECTION: Additional Notes -->
|
||||
<div class="space-y-5">
|
||||
<div class="space-y-5">
|
||||
<!-- Special Considerations -->
|
||||
<VeeField name="special_considerations" v-slot="{ field, errors: e }">
|
||||
<Field :data-invalid="!!e.length">
|
||||
<FieldLabel class="text-sm font-medium">Additional Information</FieldLabel>
|
||||
<FieldDescription class="text-xs">Anything else we should know?</FieldDescription>
|
||||
<Textarea v-bind="field" placeholder="Add any other important notes... (optional)"
|
||||
rows="4" class="resize-none mt-2" />
|
||||
<div class="h-4">
|
||||
<FieldError v-if="e.length" :errors="e" />
|
||||
</div>
|
||||
</Field>
|
||||
</VeeField>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Action Buttons -->
|
||||
<div class="flex gap-2 justify-end pt-4">
|
||||
<Button type="button" variant="outline" @click="resetForm">Clear</Button>
|
||||
<Button type="submit" :disabled="submitting">
|
||||
{{ submitting ? 'Submitting...' : 'Submit Request' }}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</template>
|
||||
125
ui/src/components/modRequests/ModRequestList.vue
Normal file
125
ui/src/components/modRequests/ModRequestList.vue
Normal file
@@ -0,0 +1,125 @@
|
||||
<script setup lang="ts">
|
||||
import { ref, onMounted } from 'vue';
|
||||
import type { DiscussionPost } from '@shared/types/discussion';
|
||||
import type { ModRequest } from '@shared/schemas/modRequest';
|
||||
import type { PagedData, pagination } from '@shared/types/pagination';
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from '@/components/ui/table';
|
||||
import Badge from '@/components/ui/badge/Badge.vue';
|
||||
import { getModRequests } from '@/api/modRequests';
|
||||
import Pagination from '../ui/pagination/Pagination.vue';
|
||||
import PaginationContent from '../ui/pagination/PaginationContent.vue';
|
||||
import PaginationPrevious from '../ui/pagination/PaginationPrevious.vue';
|
||||
import PaginationItem from '../ui/pagination/PaginationItem.vue';
|
||||
import PaginationEllipsis from '../ui/pagination/PaginationEllipsis.vue';
|
||||
import PaginationNext from '../ui/pagination/PaginationNext.vue';
|
||||
import { Lock } from 'lucide-vue-next';
|
||||
|
||||
const requests = ref<DiscussionPost<ModRequest>[]>([]);
|
||||
const loading = ref(true);
|
||||
|
||||
async function loadRequests() {
|
||||
loading.value = true;
|
||||
try {
|
||||
const response = await getModRequests(pageNum.value, pageSize.value);
|
||||
|
||||
requests.value = response.data;
|
||||
pageData.value = response.pagination;
|
||||
} catch (error) {
|
||||
console.error("Failed to load requests:", error);
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
loadRequests();
|
||||
});
|
||||
|
||||
const pageNum = ref<number>(1);
|
||||
const pageData = ref<pagination>();
|
||||
|
||||
const pageSize = ref<number>(15)
|
||||
const pageSizeOptions = [10, 15, 30]
|
||||
|
||||
function setPageSize(size: number) {
|
||||
pageSize.value = size;
|
||||
pageNum.value = 1;
|
||||
loadRequests();
|
||||
}
|
||||
|
||||
function setPage(pagenum: number) {
|
||||
pageNum.value = pagenum;
|
||||
loadRequests();
|
||||
}
|
||||
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="mod-request-list">
|
||||
<Table v-if="!loading">
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead class="w-1/2">Title</TableHead>
|
||||
<TableHead class="w-1/4">Creator</TableHead>
|
||||
<TableHead class="w-1/4">Date</TableHead>
|
||||
<TableHead class="w-1/5 text-right">Status</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
<TableRow v-for="post in requests" :key="post.id"
|
||||
class="hover:bg-muted/50 cursor-pointer transition-colors"
|
||||
@click="$router.push(`/discussions/mod-requests/${post.id}`)">
|
||||
<TableCell class="font-medium">{{ post.title }}</TableCell>
|
||||
<TableCell>{{ post.poster_name }}</TableCell>
|
||||
<TableCell class="text-muted-foreground">{{ new Date(post.created_at).toLocaleDateString() }}
|
||||
</TableCell>
|
||||
<TableCell class="text-right">
|
||||
<Badge :variant="post.is_open ? 'secondary' : 'outline'">
|
||||
{{ post.is_open ? 'Open' : 'Locked' }}
|
||||
<Lock v-if="!post.is_open" />
|
||||
</Badge>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
</TableBody>
|
||||
</Table>
|
||||
<div v-else class="flex items-center justify-center py-12">
|
||||
<p class="text-muted-foreground">Loading requests...</p>
|
||||
</div>
|
||||
<div class="mt-5 flex justify-between">
|
||||
<div></div>
|
||||
<Pagination v-slot="{ page }" :items-per-page="pageData?.pageSize || 10" :total="pageData?.total || 10"
|
||||
:default-page="2" :page="pageNum" @update:page="setPage">
|
||||
<PaginationContent v-slot="{ items }">
|
||||
<PaginationPrevious />
|
||||
<template v-for="(item, index) in items" :key="index">
|
||||
<PaginationItem v-if="item.type === 'page'" :value="item.value"
|
||||
:is-active="item.value === page">
|
||||
{{ item.value }}
|
||||
</PaginationItem>
|
||||
</template>
|
||||
<PaginationEllipsis :index="4" />
|
||||
<PaginationNext />
|
||||
</PaginationContent>
|
||||
</Pagination>
|
||||
<div class="flex items-center gap-3 text-sm">
|
||||
<p class="text-muted-foreground text-nowrap">Per page:</p>
|
||||
|
||||
<button v-for="size in pageSizeOptions" :key="size" @click="setPageSize(size)"
|
||||
class="px-2 py-1 rounded transition-colors" :class="{
|
||||
'bg-muted font-semibold': pageSize === size,
|
||||
'hover:bg-muted/50': pageSize !== size
|
||||
}">
|
||||
{{ size }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
</template>
|
||||
106
ui/src/components/modRequests/ViewModRequest.vue
Normal file
106
ui/src/components/modRequests/ViewModRequest.vue
Normal file
@@ -0,0 +1,106 @@
|
||||
<script setup lang="ts">
|
||||
import { ref, onMounted } from 'vue';
|
||||
import { useRoute, useRouter } from 'vue-router';
|
||||
import type { DiscussionPost } from '@shared/types/discussion';
|
||||
import type { ModRequest } from '@shared/schemas/modRequest';
|
||||
import { getModRequest } from '@/api/modRequests';
|
||||
import Button from '@/components/ui/button/Button.vue';
|
||||
import Badge from '@/components/ui/badge/Badge.vue';
|
||||
import CommentThread from '../discussion/CommentThread.vue';
|
||||
|
||||
const route = useRoute();
|
||||
const router = useRouter();
|
||||
|
||||
const post = ref<DiscussionPost<ModRequest> | null>(null);
|
||||
const loading = ref(true);
|
||||
const error = ref<string | null>(null);
|
||||
|
||||
async function loadPost() {
|
||||
loading.value = true;
|
||||
error.value = null;
|
||||
try {
|
||||
const id = Number(route.params.id);
|
||||
if (isNaN(id)) {
|
||||
error.value = 'Invalid request ID';
|
||||
return;
|
||||
}
|
||||
post.value = await getModRequest(id);
|
||||
} catch (err: any) {
|
||||
console.error('Failed to fetch mod request', err);
|
||||
error.value = 'Failed to load mod request';
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
loadPost();
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="max-w-[80rem] mt-5 mx-auto px-2 lg:px-20 w-full">
|
||||
<div class="mb-8 flex items-center justify-between">
|
||||
<div>
|
||||
<h1 class="scroll-m-20 text-3xl font-semibold tracking-tight mb-2">Mod Request: {{ post?.title }}</h1>
|
||||
<p class="text-muted-foreground" v-if="post">
|
||||
Requested by {{ post.poster_name || 'Unknown' }} on {{ new
|
||||
Date(post.created_at).toLocaleDateString() }}
|
||||
</p>
|
||||
</div>
|
||||
<Button variant="outline" @click="router.push('/discussions/mod-requests')">
|
||||
Back to posts
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div v-if="loading" class="flex items-center justify-center py-12">
|
||||
<p class="text-muted-foreground">Loading...</p>
|
||||
</div>
|
||||
<div v-else-if="error" class="text-red-500">{{ error }}</div>
|
||||
<div v-else-if="post" class="space-y-6">
|
||||
<div class="flex items-center gap-3">
|
||||
<Badge :variant="post.is_open ? 'secondary' : 'outline'">
|
||||
{{ post.is_open ? 'Open' : 'Locked' }}
|
||||
</Badge>
|
||||
</div>
|
||||
<div class="border rounded-lg p-6 bg-muted/50">
|
||||
<h2 class="text-2xl font-semibold mb-2">{{ post.content.mod_title }}</h2>
|
||||
<p class="text-sm text-muted-foreground mb-4"><a :href="post.content.mod_link" target="_blank"
|
||||
class="text-primary underline">{{ post.content.mod_link }}</a></p>
|
||||
<div class="space-y-4">
|
||||
<div>
|
||||
<h3 class="font-medium">Description</h3>
|
||||
<p>{{ post.content.description }}</p>
|
||||
</div>
|
||||
<div>
|
||||
<h3 class="font-medium">Reason</h3>
|
||||
<p>{{ post.content.reason }}</p>
|
||||
</div>
|
||||
<div>
|
||||
<h3 class="font-medium">Tested?</h3>
|
||||
<p>{{ post.content.confirmed_tested ? 'Yes' : 'No' }}</p>
|
||||
</div>
|
||||
<div>
|
||||
<h3 class="font-medium">Detrimental Effects</h3>
|
||||
<p>{{ post.content.detrimental_effects }}</p>
|
||||
</div>
|
||||
<div>
|
||||
<h3 class="font-medium">Keybind Conflicts</h3>
|
||||
<p>{{ post.content.keybind_conflicts || 'None' }}</p>
|
||||
</div>
|
||||
<div v-if="post.content.special_considerations">
|
||||
<h3 class="font-medium">Additional Notes</h3>
|
||||
<p>{{ post.content.special_considerations }}</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- discussion placeholder -->
|
||||
<CommentThread :parent-id="post.id" :comments="post.comments" @comments-updated="post.comments = $event" />
|
||||
|
||||
</div>
|
||||
<div v-else>
|
||||
<p class="text-muted-foreground">Unable to locate this mod request.</p>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
32
ui/src/pages/ModRequest.vue
Normal file
32
ui/src/pages/ModRequest.vue
Normal file
@@ -0,0 +1,32 @@
|
||||
<script setup lang="ts">
|
||||
import { ref } from 'vue';
|
||||
import Button from '@/components/ui/button/Button.vue';
|
||||
import ModRequestForm from '@/components/modRequests/ModRequestForm.vue';
|
||||
import ModRequestList from '@/components/modRequests/ModRequestList.vue';
|
||||
|
||||
const showForm = ref(false);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="max-w-[80rem] mt-5 mx-auto px-2 lg:px-20 w-full">
|
||||
<!-- Header - always visible -->
|
||||
<div class="mb-8">
|
||||
<h1 class="scroll-m-20 text-3xl font-semibold tracking-tight mb-2">Mod Requests</h1>
|
||||
<p class="text-muted-foreground">Submit and manage mod requests for the community</p>
|
||||
</div>
|
||||
|
||||
<!-- List View -->
|
||||
<template v-if="!showForm">
|
||||
<Button @click="showForm = true" class="mb-6">
|
||||
New Request
|
||||
</Button>
|
||||
<ModRequestList></ModRequestList>
|
||||
</template>
|
||||
|
||||
<!-- Form View -->
|
||||
<template v-else>
|
||||
<ModRequestForm class="mb-8" @close="showForm = false" @submit="(id) => $router.push(`/discussions/mod-requests/${id}`)"></ModRequestForm>
|
||||
|
||||
</template>
|
||||
</div>
|
||||
</template>
|
||||
@@ -28,6 +28,16 @@ const router = createRouter({
|
||||
{ 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 } },
|
||||
|
||||
//discussion routes
|
||||
{
|
||||
path: '/discussions',
|
||||
meta: { requiresAuth: true, memberOnly: true },
|
||||
children: [
|
||||
{ path: 'mod-requests', component: () => import('@/pages/ModRequest.vue') },
|
||||
{ path: 'mod-requests/:id', component: () => import('@/components/modRequests/ViewModRequest.vue') },
|
||||
]
|
||||
},
|
||||
|
||||
// ADMIN / STAFF ROUTES
|
||||
{
|
||||
path: '/administration',
|
||||
|
||||
Reference in New Issue
Block a user