From 3e3c875e0058bafaf0912c67f5e3293760a8ce56 Mon Sep 17 00:00:00 2001 From: Divyansh Date: Wed, 10 Jun 2026 15:44:49 +0530 Subject: [PATCH 01/11] Fix #86: assign names to all users --- app/src/pages/auth/CentreHeadSignup.tsx | 13 +++++++++++++ app/src/pages/auth/WardenSignup.tsx | 13 +++++++++++++ handlers/centrehead_auth.go | 1 + handlers/warden_auth.go | 1 + models/centrehead_auth.go | 2 ++ models/warden_auth.go | 2 ++ 6 files changed, 32 insertions(+) diff --git a/app/src/pages/auth/CentreHeadSignup.tsx b/app/src/pages/auth/CentreHeadSignup.tsx index 6630de3..e8b8737 100644 --- a/app/src/pages/auth/CentreHeadSignup.tsx +++ b/app/src/pages/auth/CentreHeadSignup.tsx @@ -6,6 +6,7 @@ import { BUILDINGS } from '../../constants/models'; export function CentreHeadSignup() { const [formData, setFormData] = useState({ + name: '', email: '', password: '', phone_number: '', @@ -97,6 +98,18 @@ export function CentreHeadSignup() {

Account Details

+
+ + +

Account Details

+
+ + +
Date: Wed, 10 Jun 2026 15:53:09 +0530 Subject: [PATCH 02/11] Fix #86 tests: Add name field to mock payloads --- test/centrehead_auth_test.go | 1 + test/warden_auth_test.go | 1 + 2 files changed, 2 insertions(+) diff --git a/test/centrehead_auth_test.go b/test/centrehead_auth_test.go index 97f431d..4bb9c4a 100644 --- a/test/centrehead_auth_test.go +++ b/test/centrehead_auth_test.go @@ -24,6 +24,7 @@ func TestCentreheadSignup_AlreadyRegistered(t *testing.T) { e := newAuthRouter(db, noAuth()) body := map[string]any{ + "name": "Duplicate Head", "email": "ch.dup@iit.ac.in", "password": "whatever", "building": string(models.LHC), diff --git a/test/warden_auth_test.go b/test/warden_auth_test.go index e3e119f..ee6ea8c 100644 --- a/test/warden_auth_test.go +++ b/test/warden_auth_test.go @@ -24,6 +24,7 @@ func TestWardenSignup_AlreadyRegistered(t *testing.T) { e := newAuthRouter(db, noAuth()) body := map[string]any{ + "name": "Duplicate Warden", "email": "war.dup@iit.ac.in", "password": "whatever", "hostel": string(models.KBH), From 7edf91e7e69ab0a9bc6aee214003c643c62bde14 Mon Sep 17 00:00:00 2001 From: Divyansh Date: Mon, 22 Jun 2026 14:18:27 +0530 Subject: [PATCH 03/11] feat: allow for editing and deleting admin comments (fixes #41) --- handlers/admin_comment.go | 120 ++++++++++++++++++++++++++++++++++++++ routes/admin.go | 2 + 2 files changed, 122 insertions(+) diff --git a/handlers/admin_comment.go b/handlers/admin_comment.go index 7c2026a..5810a15 100644 --- a/handlers/admin_comment.go +++ b/handlers/admin_comment.go @@ -103,3 +103,123 @@ func (h *AdminHandler) AdminPostComment(c *gin.Context) { c.JSON(201, gin.H{"success": "comment posted!"}) } + +// AdminEditComment allows an admin to edit their own comment. +func (h *AdminHandler) AdminEditComment(c *gin.Context) { + // verify the admin + emailID, exists := c.Get(middleware.EmailKey) + if !exists { + c.JSON(401, gin.H{"error": "permission denied"}) + return + } + + var inputs CommentType + if err := c.ShouldBindJSON(&inputs); err != nil { + c.JSON(400, gin.H{"error": "invalid request body"}) + return + } + + postType := c.Param("type") + postIDString := c.Param("id") + postID, err := strconv.ParseUint(postIDString, 10, 64) + if err != nil { + c.JSON(400, gin.H{"error": "invalid post id"}) + return + } + + commentIDString := c.Param("comment_id") + commentID, err := strconv.ParseUint(commentIDString, 10, 64) + if err != nil { + c.JSON(400, gin.H{"error": "invalid comment id"}) + return + } + + var comment models.Comment + result := h.DB.Where("id = ?", commentID).Take(&comment) + if result.Error != nil { + if errors.Is(result.Error, gorm.ErrRecordNotFound) { + c.JSON(404, gin.H{"error": "comment not found"}) + return + } + c.JSON(500, gin.H{"error": "internal server error"}) + return + } + + if comment.CommentableType != postType || comment.CommentableID != uint(postID) { + c.JSON(400, gin.H{"error": "comment does not belong to this post"}) + return + } + + // Verify that the comment belongs to this admin + if comment.Email != emailID { + c.JSON(403, gin.H{"error": "you are not authorized to edit this comment"}) + return + } + + // Update the comment + comment.Content = inputs.Content + comment.UpdatedAt = time.Now() + + result = h.DB.Save(&comment) + if result.Error != nil { + c.JSON(500, gin.H{"error": "failed to update comment"}) + return + } + + c.JSON(200, gin.H{"success": "comment updated!"}) +} + +// AdminDeleteComment allows an admin to delete their own comment. +func (h *AdminHandler) AdminDeleteComment(c *gin.Context) { + // verify the admin + emailID, exists := c.Get(middleware.EmailKey) + if !exists { + c.JSON(401, gin.H{"error": "permission denied"}) + return + } + + postType := c.Param("type") + postIDString := c.Param("id") + postID, err := strconv.ParseUint(postIDString, 10, 64) + if err != nil { + c.JSON(400, gin.H{"error": "invalid post id"}) + return + } + + commentIDString := c.Param("comment_id") + commentID, err := strconv.ParseUint(commentIDString, 10, 64) + if err != nil { + c.JSON(400, gin.H{"error": "invalid comment id"}) + return + } + + var comment models.Comment + result := h.DB.Where("id = ?", commentID).Take(&comment) + if result.Error != nil { + if errors.Is(result.Error, gorm.ErrRecordNotFound) { + c.JSON(404, gin.H{"error": "comment not found"}) + return + } + c.JSON(500, gin.H{"error": "internal server error"}) + return + } + + if comment.CommentableType != postType || comment.CommentableID != uint(postID) { + c.JSON(400, gin.H{"error": "comment does not belong to this post"}) + return + } + + // Verify that the comment belongs to this admin + if comment.Email != emailID { + c.JSON(403, gin.H{"error": "you are not authorized to delete this comment"}) + return + } + + result = h.DB.Delete(&comment) + if result.Error != nil { + c.JSON(500, gin.H{"error": "failed to delete comment"}) + return + } + + c.JSON(200, gin.H{"success": "comment deleted!"}) +} diff --git a/routes/admin.go b/routes/admin.go index 13678f1..3d88c1f 100644 --- a/routes/admin.go +++ b/routes/admin.go @@ -11,6 +11,8 @@ func AdminRoutes (e *gin.Engine, h *handlers.AdminHandler) { e.POST("/api/auth/admin/login", h.AdminLogin) e.POST("/api/admin/comment/:type/:id", middleware.IsAuthenticated(), h.AdminPostComment) + e.PATCH("/api/admin/comment/:type/:id/:comment_id", middleware.IsAuthenticated(), h.AdminEditComment) + e.DELETE("/api/admin/comment/:type/:id/:comment_id", middleware.IsAuthenticated(), h.AdminDeleteComment) // keep separate apis for updating status stage := e.Group("/api/admin") From 806f966348ae91dbd4e64b6de19963f99a4fbb39 Mon Sep 17 00:00:00 2001 From: Divyansh Date: Mon, 22 Jun 2026 14:22:06 +0530 Subject: [PATCH 04/11] feat: add AdminGetComments endpoint to fetch admin's own comments --- handlers/admin_comment.go | 21 +++++++++++++++++++++ routes/admin.go | 1 + 2 files changed, 22 insertions(+) diff --git a/handlers/admin_comment.go b/handlers/admin_comment.go index 5810a15..170079f 100644 --- a/handlers/admin_comment.go +++ b/handlers/admin_comment.go @@ -24,6 +24,27 @@ type CommentType struct { // AdminGetComments ///////////////////////////////////////////////////////////////////// +// AdminGetComments fetches all comments made by the logged-in admin. +func (h *AdminHandler) AdminGetComments(c *gin.Context) { + emailID, exists := c.Get(middleware.EmailKey) + if !exists { + c.JSON(401, gin.H{"error": "permission denied"}) + return + } + + var comments []models.Comment + result := h.DB.Where("email = ?", emailID).Find(&comments) + if result.Error != nil { + c.JSON(500, gin.H{"error": "failed to fetch comments"}) + return + } + + c.JSON(200, gin.H{ + "success": "comments fetched", + "comments": comments, + }) +} + // AdminPost comment allow any admin comment on any type of post. // Common for all type of admins and posts. diff --git a/routes/admin.go b/routes/admin.go index 3d88c1f..3981ed6 100644 --- a/routes/admin.go +++ b/routes/admin.go @@ -10,6 +10,7 @@ func AdminRoutes (e *gin.Engine, h *handlers.AdminHandler) { // e.POST("/api/auth/admin/signup", h.AdminSignup) // not to be used as an public API e.POST("/api/auth/admin/login", h.AdminLogin) + e.GET("/api/admin/comments", middleware.IsAuthenticated(), h.AdminGetComments) e.POST("/api/admin/comment/:type/:id", middleware.IsAuthenticated(), h.AdminPostComment) e.PATCH("/api/admin/comment/:type/:id/:comment_id", middleware.IsAuthenticated(), h.AdminEditComment) e.DELETE("/api/admin/comment/:type/:id/:comment_id", middleware.IsAuthenticated(), h.AdminDeleteComment) From 58b92784958296f37db7b00ce4a08b6dafb6c4fa Mon Sep 17 00:00:00 2001 From: Divyansh Date: Mon, 22 Jun 2026 14:30:21 +0530 Subject: [PATCH 05/11] docs: add wiki pages (Home, Setup, Architecture, API Reference, Contributing) --- docs/API-Reference.md | 86 ++++++++++++++++++++++++++++++++++ docs/Architecture-and-Flows.md | 52 ++++++++++++++++++++ docs/Contributing.md | 41 ++++++++++++++++ docs/Home.md | 20 ++++++++ docs/Local-Setup.md | 61 ++++++++++++++++++++++++ 5 files changed, 260 insertions(+) create mode 100644 docs/API-Reference.md create mode 100644 docs/Architecture-and-Flows.md create mode 100644 docs/Contributing.md create mode 100644 docs/Home.md create mode 100644 docs/Local-Setup.md diff --git a/docs/API-Reference.md b/docs/API-Reference.md new file mode 100644 index 0000000..509769c --- /dev/null +++ b/docs/API-Reference.md @@ -0,0 +1,86 @@ +# API Reference + +This document maps all the API endpoints available in the CMS Web backend. Most endpoints require authentication via token cookies checked by the `IsAuthenticated` middleware. + +--- + +## 1. Authentication Routes + +### Faculty Auth +* `POST /api/auth/faculty/signup` - Register a new faculty account +* `POST /api/auth/faculty/login` - Login to a faculty account +* `POST /api/auth/faculty/forget-password` - Request a password reset link +* `PATCH /api/auth/faculty/reset-password` - Complete password reset using token + +### Warden Auth +* `POST /api/auth/warden/signup` - Register a new warden account +* `POST /api/auth/warden/login` - Login to a warden account +* `POST /api/auth/warden/forget-password` - Request a password reset link +* `PATCH /api/auth/warden/reset-password` - Complete password reset using token + +### Centrehead Auth +* `POST /api/auth/centrehead/signup` - Register a new centrehead account +* `POST /api/auth/centrehead/login` - Login to a centrehead account +* `POST /api/auth/centrehead/forget-password` - Request a password reset link +* `PATCH /api/auth/centrehead/reset-password` - Complete password reset using token + +### Admin Auth +* `POST /api/auth/admin/login` - Login to an admin account (XEN, AE, JE) + +### General Auth +* `POST /api/auth/logout` - Clear authentication cookies +* `GET /api/auth/verify` - Verify an account via email link +* `GET /api/profile` - Fetch the profile details of the current logged-in user + +--- + +## 2. Complaint (Post) Routes + +Protected by `IsAuthenticated` middleware. + +* `POST /api/post/faculty` - Submit a new faculty post +* `POST /api/post/warden` - Submit a new warden post +* `POST /api/post/centrehead` - Submit a new centrehead post + +* `PATCH /api/post/faculty/edit/:post_id` - Edit a faculty post (valid for 30 mins post-creation) +* `PATCH /api/post/warden/edit/:post_id` - Edit a warden post (valid for 30 mins post-creation) +* `PATCH /api/post/centrehead/edit/:post_id` - Edit a centrehead post (valid for 30 mins post-creation) + +* `DELETE /api/post/faculty/delete/:post_id` - Delete a faculty post (valid for 30 mins post-creation) +* `DELETE /api/post/warden/delete/:post_id` - Delete a warden post (valid for 30 mins post-creation) +* `DELETE /api/post/centrehead/delete/:post_id` - Delete a centrehead post (valid for 30 mins post-creation) + +* `GET /api/post/faculty` - Retrieve posts submitted by the logged-in faculty +* `GET /api/post/warden` - Retrieve posts submitted by the logged-in warden +* `GET /api/post/centrehead` - Retrieve posts submitted by the logged-in centrehead + +--- + +## 3. Comments Routes + +* `POST /api/post/faculty/comment/:post_id` - Comment on a faculty post (as post author) +* `POST /api/post/warden/comment/:post_id` - Comment on a warden post (as post author) +* `POST /api/post/centrehead/comment/:post_id` - Comment on a centrehead post (as post author) + +--- + +## 4. Admin Operations Routes + +Admins can perform operations across any user post types and manage comments/statuses. + +### Comments Management +* `GET /api/admin/comments` - Fetch all comments created by the logged-in admin +* `POST /api/admin/comment/:type/:id` - Post an admin comment on a specific post (`type` can be `faculty_posts`, `warden_posts`, `centrehead_posts`) +* `PATCH /api/admin/comment/:type/:id/:comment_id` - Edit an admin's own comment +* `DELETE /api/admin/comment/:type/:id/:comment_id` - Delete an admin's own comment + +### Status Management +* `PATCH /api/admin/faculty_posts/status/:post_id` - Update status of a faculty post +* `PATCH /api/admin/warden_posts/status/:post_id` - Update status of a warden post +* `PATCH /api/admin/centrehead_posts/status/:post_id` - Update status of a centrehead post + +### Post Queries +* `GET /api/admin/xen/posts` - Fetch posts available to XEN +* `GET /api/admin/ae/posts` - Fetch posts available to AE +* `GET /api/admin/je/posts` - Fetch posts assigned to JE +* `GET /api/admin/posts/:role/:post_id` - Fetch details of any post by role and ID diff --git a/docs/Architecture-and-Flows.md b/docs/Architecture-and-Flows.md new file mode 100644 index 0000000..2625f5f --- /dev/null +++ b/docs/Architecture-and-Flows.md @@ -0,0 +1,52 @@ +# Architecture & Flows + +CMS Web relies on a role-based workflow to process maintenance complaints efficiently. + +## 1. Role-Based Authorization + +The system classifies users into distinct roles, each having specific privileges: +* **Faculty**: Submits departmental or residential complaints. Can comment, edit, or delete posts within a 30-minute window. +* **Warden**: Submits hostel-related complaints. Can comment, edit, or delete posts within a 30-minute window. +* **Centrehead**: Submits administrative/building-related complaints. Can comment, edit, or delete posts within a 30-minute window. +* **Admin (XEN, AE, JE)**: + * **XEN (Executive Engineer)**: Oversees all pending posts, assigns Junior Engineers (JE), and manages post statuses. + * **AE (Assistant Engineer)**: Reviews posts pending AE review and manages them. + * **JE (Junior Engineer)**: Resolves assignments directly or reports progress. + +*Diagram location:* `/public/img/cms6.png` + +--- + +## 2. Authentication Flow + +Authentication is session or token-based, verifying credentials (login) and checking positions/roles on protected routes via custom Gin middleware. + +*Diagram location:* `/public/img/cms1.png` + +--- + +## 3. Complaint Lifecycle Flow + +The typical flow of a complaint from submission to closure: +1. **Creation**: Submissions by Faculty, Warden, or Centrehead default to the `Pending_XEN` status. +2. **Review/Assignment**: The XEN reviews and delegates it to a Junior Engineer (`Pending_JE`). +3. **Execution**: The JE performs the work and updates the status to `Resolved_JE`. +4. **Resolution**: The complaint progresses through administrative checks (AE / XEN) until it reaches `Resolved` or `Closed`. + +*Diagram location:* `/public/img/cms2.png` + +--- + +## 4. Request Status Matrix (XEN, JE) + +A quick matrix showing how request statuses transition between the Executive Engineer (XEN) and the Junior Engineer (JE): + +*Diagram location:* `/public/img/cms3.png` + +--- + +## 5. Request Status (AE) + +How Assistant Engineers (AE) intervene in the verification process for specific complaints: + +*Diagram location:* `/public/img/cms4.png` diff --git a/docs/Contributing.md b/docs/Contributing.md new file mode 100644 index 0000000..8dc243a --- /dev/null +++ b/docs/Contributing.md @@ -0,0 +1,41 @@ +# Contributing Guide + +Thank you for contributing to CMS Web! To maintain code quality and ensure a smooth development process, please adhere to the following guidelines. + +--- + +## 1. Development Workflow + +1. **Create a Branch**: Create a descriptive feature branch from `main`: + ```bash + git checkout -b feat/your-feature-name + ``` +2. **Implement Changes**: Ensure your changes are modular and contain appropriate comments. Avoid unrelated refactorings. +3. **Run Tests**: Always run backend tests locally to verify no regressions were introduced: + ```bash + go test -v ./test/... + ``` +4. **Commit & Push**: Commit with concise messages conforming to conventional commits (e.g. `feat: add ...`, `fix: resolve ...`): + ```bash + git add . + git commit -m "feat: add user profile page" + git push origin feat/your-feature-name + ``` +5. **Pull Request**: Open a pull request against the `main` branch. Provide a comprehensive summary of your changes. + +--- + +## 2. Code Conventions + +### Backend (Go) +* **GORM Models**: When creating or modifying database schemas, verify relationships and validation tags (e.g., `binding:"required"`, `gorm:"not null"`). +* **Endpoints**: Add routes to their designated category in the `routes/` package. +* **Error Handling**: Follow idiomatic Go patterns. Return clear JSON error payloads with relevant HTTP statuses: + * `400 Bad Request` for invalid input parameters/schemas. + * `401 Unauthorized` / `403 Forbidden` for failed authentication/authorization checks. + * `404 Not Found` when GORM queries return `gorm.ErrRecordNotFound`. + * `500 Internal Server Error` for database failures. + +### Frontend (React + TS) +* **TypeScript**: Define explicit types/interfaces for state, props, and API response schemas. Avoid using `any` whenever possible. +* **Styling**: Maintain vanilla CSS conventions and structure styles clearly within component directories. diff --git a/docs/Home.md b/docs/Home.md new file mode 100644 index 0000000..37f19f0 --- /dev/null +++ b/docs/Home.md @@ -0,0 +1,20 @@ +# Welcome to the CMS Web Wiki + +**CMS Web** is the official web interface of the Estate Office of NIT Hamirpur designed to streamline and manage maintenance complaints across the campus. It handles both **civil** and **electrical** complaints for both **official/departmental** buildings and **residential** quarters. + +## Project Structure + +Here is a quick overview of the key directories in this project: + +- **`/app`**: The frontend application built using **Vite**, **React**, and **TypeScript**. +- **`/handlers`**: Go backend controller logic handling authentication, posts (complaints), and comments. +- **`/models`**: Gorm database models representing users (Faculty, Warden, Centrehead, Admin), posts, and comments. +- **`/routes`**: API routing configurations for both user actions and administrative control. +- **`/middleware`**: Backend middleware including authentication and permissions checking. +- **`/test`**: Go backend test suite verifying auth flows, complaint management, and administrative actions. + +## Quick Links +- [[Local Setup|Local-Setup]] +- [[Architecture & Flows|Architecture-and-Flows]] +- [[API Reference|API-Reference]] +- [[Contributing|Contributing]] diff --git a/docs/Local-Setup.md b/docs/Local-Setup.md new file mode 100644 index 0000000..9de4122 --- /dev/null +++ b/docs/Local-Setup.md @@ -0,0 +1,61 @@ +# Local Setup + +This guide will help you get CMS Web running locally on your development machine. The project is split into a Go backend and a React + TypeScript frontend. + +## Prerequisites + +Ensure you have the following installed: +- [Go](https://go.dev/dl/) (version 1.20+) +- [Node.js](https://nodejs.org/en) (v18+) and npm +- A relational database (SQLite by default or PostgreSQL/MySQL depending on configuration) + +--- + +## 1. Backend Setup + +The backend is built in Go using the **Gin** framework and **GORM**. + +1. Navigate to the root directory of the project. +2. Create your `.env` configuration file from the example: + ```bash + cp .env.example .env + ``` + Configure your database credentials and secret keys inside `.env`. +3. Install the dependencies: + ```bash + go mod download + ``` +4. Run the backend server: + ```bash + go run main.go + ``` + The backend should now be running on its configured port (typically `:8080`). + +--- + +## 2. Frontend Setup + +The frontend is located in the `/app` folder. + +1. Navigate to the `/app` directory: + ```bash + cd app + ``` +2. Install dependencies: + ```bash + npm install + ``` +3. Run the Vite development server: + ```bash + npm run dev + ``` +4. Open the local address printed in the terminal (usually `http://localhost:5173`) in your browser. + +--- + +## 3. Running Tests + +To verify that everything is working as expected, run the Go test suite: +```bash +go test -v ./test/... +``` From b0b96903cef2ad1b96d1c52acf2866aabb43708f Mon Sep 17 00:00:00 2001 From: Divyansh Date: Mon, 22 Jun 2026 14:37:16 +0530 Subject: [PATCH 06/11] docs: use raw github urls to embed flowcharts in Architecture and Flows wiki --- docs/Architecture-and-Flows.md | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/docs/Architecture-and-Flows.md b/docs/Architecture-and-Flows.md index 2625f5f..2139ab9 100644 --- a/docs/Architecture-and-Flows.md +++ b/docs/Architecture-and-Flows.md @@ -13,7 +13,7 @@ The system classifies users into distinct roles, each having specific privileges * **AE (Assistant Engineer)**: Reviews posts pending AE review and manages them. * **JE (Junior Engineer)**: Resolves assignments directly or reports progress. -*Diagram location:* `/public/img/cms6.png` +![Role-Based Authorization](https://raw.githubusercontent.com/divyansh-v15-06/cms-webb/main/public/img/cms6.png) --- @@ -21,7 +21,7 @@ The system classifies users into distinct roles, each having specific privileges Authentication is session or token-based, verifying credentials (login) and checking positions/roles on protected routes via custom Gin middleware. -*Diagram location:* `/public/img/cms1.png` +![Authentication Flow](https://raw.githubusercontent.com/divyansh-v15-06/cms-webb/main/public/img/cms1.png) --- @@ -33,7 +33,7 @@ The typical flow of a complaint from submission to closure: 3. **Execution**: The JE performs the work and updates the status to `Resolved_JE`. 4. **Resolution**: The complaint progresses through administrative checks (AE / XEN) until it reaches `Resolved` or `Closed`. -*Diagram location:* `/public/img/cms2.png` +![Complaint Lifecycle Flow](https://raw.githubusercontent.com/divyansh-v15-06/cms-webb/main/public/img/cms2.png) --- @@ -41,7 +41,7 @@ The typical flow of a complaint from submission to closure: A quick matrix showing how request statuses transition between the Executive Engineer (XEN) and the Junior Engineer (JE): -*Diagram location:* `/public/img/cms3.png` +![Request Status Matrix](https://raw.githubusercontent.com/divyansh-v15-06/cms-webb/main/public/img/cms3.png) --- @@ -49,4 +49,5 @@ A quick matrix showing how request statuses transition between the Executive Eng How Assistant Engineers (AE) intervene in the verification process for specific complaints: -*Diagram location:* `/public/img/cms4.png` +![Request Status AE](https://raw.githubusercontent.com/divyansh-v15-06/cms-webb/main/public/img/cms4.png) + From 8ecaf0f21edec56026c9e0562dd31bc466b35064 Mon Sep 17 00:00:00 2001 From: Divyansh Date: Mon, 22 Jun 2026 18:19:39 +0530 Subject: [PATCH 07/11] remove docs/ dir and fix frontend api paths --- app/src/pages/admin/AdminPostView.tsx | 2 +- docs/API-Reference.md | 86 --------------------------- docs/Architecture-and-Flows.md | 53 ----------------- docs/Contributing.md | 41 ------------- docs/Home.md | 20 ------- docs/Local-Setup.md | 61 ------------------- routes/admin.go | 6 +- 7 files changed, 4 insertions(+), 265 deletions(-) delete mode 100644 docs/API-Reference.md delete mode 100644 docs/Architecture-and-Flows.md delete mode 100644 docs/Contributing.md delete mode 100644 docs/Home.md delete mode 100644 docs/Local-Setup.md diff --git a/app/src/pages/admin/AdminPostView.tsx b/app/src/pages/admin/AdminPostView.tsx index bf24890..f01cb6a 100644 --- a/app/src/pages/admin/AdminPostView.tsx +++ b/app/src/pages/admin/AdminPostView.tsx @@ -138,7 +138,7 @@ const ROLE_TO_STATUS_API: Record = { // Maps URL role param → API segment for the comment endpoint const ROLE_TO_COMMENT_API: Record = { faculty: 'faculty_posts', - warden: 'wardens_posts', + warden: 'warden_posts', centrehead: 'centrehead_posts', }; diff --git a/docs/API-Reference.md b/docs/API-Reference.md deleted file mode 100644 index 509769c..0000000 --- a/docs/API-Reference.md +++ /dev/null @@ -1,86 +0,0 @@ -# API Reference - -This document maps all the API endpoints available in the CMS Web backend. Most endpoints require authentication via token cookies checked by the `IsAuthenticated` middleware. - ---- - -## 1. Authentication Routes - -### Faculty Auth -* `POST /api/auth/faculty/signup` - Register a new faculty account -* `POST /api/auth/faculty/login` - Login to a faculty account -* `POST /api/auth/faculty/forget-password` - Request a password reset link -* `PATCH /api/auth/faculty/reset-password` - Complete password reset using token - -### Warden Auth -* `POST /api/auth/warden/signup` - Register a new warden account -* `POST /api/auth/warden/login` - Login to a warden account -* `POST /api/auth/warden/forget-password` - Request a password reset link -* `PATCH /api/auth/warden/reset-password` - Complete password reset using token - -### Centrehead Auth -* `POST /api/auth/centrehead/signup` - Register a new centrehead account -* `POST /api/auth/centrehead/login` - Login to a centrehead account -* `POST /api/auth/centrehead/forget-password` - Request a password reset link -* `PATCH /api/auth/centrehead/reset-password` - Complete password reset using token - -### Admin Auth -* `POST /api/auth/admin/login` - Login to an admin account (XEN, AE, JE) - -### General Auth -* `POST /api/auth/logout` - Clear authentication cookies -* `GET /api/auth/verify` - Verify an account via email link -* `GET /api/profile` - Fetch the profile details of the current logged-in user - ---- - -## 2. Complaint (Post) Routes - -Protected by `IsAuthenticated` middleware. - -* `POST /api/post/faculty` - Submit a new faculty post -* `POST /api/post/warden` - Submit a new warden post -* `POST /api/post/centrehead` - Submit a new centrehead post - -* `PATCH /api/post/faculty/edit/:post_id` - Edit a faculty post (valid for 30 mins post-creation) -* `PATCH /api/post/warden/edit/:post_id` - Edit a warden post (valid for 30 mins post-creation) -* `PATCH /api/post/centrehead/edit/:post_id` - Edit a centrehead post (valid for 30 mins post-creation) - -* `DELETE /api/post/faculty/delete/:post_id` - Delete a faculty post (valid for 30 mins post-creation) -* `DELETE /api/post/warden/delete/:post_id` - Delete a warden post (valid for 30 mins post-creation) -* `DELETE /api/post/centrehead/delete/:post_id` - Delete a centrehead post (valid for 30 mins post-creation) - -* `GET /api/post/faculty` - Retrieve posts submitted by the logged-in faculty -* `GET /api/post/warden` - Retrieve posts submitted by the logged-in warden -* `GET /api/post/centrehead` - Retrieve posts submitted by the logged-in centrehead - ---- - -## 3. Comments Routes - -* `POST /api/post/faculty/comment/:post_id` - Comment on a faculty post (as post author) -* `POST /api/post/warden/comment/:post_id` - Comment on a warden post (as post author) -* `POST /api/post/centrehead/comment/:post_id` - Comment on a centrehead post (as post author) - ---- - -## 4. Admin Operations Routes - -Admins can perform operations across any user post types and manage comments/statuses. - -### Comments Management -* `GET /api/admin/comments` - Fetch all comments created by the logged-in admin -* `POST /api/admin/comment/:type/:id` - Post an admin comment on a specific post (`type` can be `faculty_posts`, `warden_posts`, `centrehead_posts`) -* `PATCH /api/admin/comment/:type/:id/:comment_id` - Edit an admin's own comment -* `DELETE /api/admin/comment/:type/:id/:comment_id` - Delete an admin's own comment - -### Status Management -* `PATCH /api/admin/faculty_posts/status/:post_id` - Update status of a faculty post -* `PATCH /api/admin/warden_posts/status/:post_id` - Update status of a warden post -* `PATCH /api/admin/centrehead_posts/status/:post_id` - Update status of a centrehead post - -### Post Queries -* `GET /api/admin/xen/posts` - Fetch posts available to XEN -* `GET /api/admin/ae/posts` - Fetch posts available to AE -* `GET /api/admin/je/posts` - Fetch posts assigned to JE -* `GET /api/admin/posts/:role/:post_id` - Fetch details of any post by role and ID diff --git a/docs/Architecture-and-Flows.md b/docs/Architecture-and-Flows.md deleted file mode 100644 index 2139ab9..0000000 --- a/docs/Architecture-and-Flows.md +++ /dev/null @@ -1,53 +0,0 @@ -# Architecture & Flows - -CMS Web relies on a role-based workflow to process maintenance complaints efficiently. - -## 1. Role-Based Authorization - -The system classifies users into distinct roles, each having specific privileges: -* **Faculty**: Submits departmental or residential complaints. Can comment, edit, or delete posts within a 30-minute window. -* **Warden**: Submits hostel-related complaints. Can comment, edit, or delete posts within a 30-minute window. -* **Centrehead**: Submits administrative/building-related complaints. Can comment, edit, or delete posts within a 30-minute window. -* **Admin (XEN, AE, JE)**: - * **XEN (Executive Engineer)**: Oversees all pending posts, assigns Junior Engineers (JE), and manages post statuses. - * **AE (Assistant Engineer)**: Reviews posts pending AE review and manages them. - * **JE (Junior Engineer)**: Resolves assignments directly or reports progress. - -![Role-Based Authorization](https://raw.githubusercontent.com/divyansh-v15-06/cms-webb/main/public/img/cms6.png) - ---- - -## 2. Authentication Flow - -Authentication is session or token-based, verifying credentials (login) and checking positions/roles on protected routes via custom Gin middleware. - -![Authentication Flow](https://raw.githubusercontent.com/divyansh-v15-06/cms-webb/main/public/img/cms1.png) - ---- - -## 3. Complaint Lifecycle Flow - -The typical flow of a complaint from submission to closure: -1. **Creation**: Submissions by Faculty, Warden, or Centrehead default to the `Pending_XEN` status. -2. **Review/Assignment**: The XEN reviews and delegates it to a Junior Engineer (`Pending_JE`). -3. **Execution**: The JE performs the work and updates the status to `Resolved_JE`. -4. **Resolution**: The complaint progresses through administrative checks (AE / XEN) until it reaches `Resolved` or `Closed`. - -![Complaint Lifecycle Flow](https://raw.githubusercontent.com/divyansh-v15-06/cms-webb/main/public/img/cms2.png) - ---- - -## 4. Request Status Matrix (XEN, JE) - -A quick matrix showing how request statuses transition between the Executive Engineer (XEN) and the Junior Engineer (JE): - -![Request Status Matrix](https://raw.githubusercontent.com/divyansh-v15-06/cms-webb/main/public/img/cms3.png) - ---- - -## 5. Request Status (AE) - -How Assistant Engineers (AE) intervene in the verification process for specific complaints: - -![Request Status AE](https://raw.githubusercontent.com/divyansh-v15-06/cms-webb/main/public/img/cms4.png) - diff --git a/docs/Contributing.md b/docs/Contributing.md deleted file mode 100644 index 8dc243a..0000000 --- a/docs/Contributing.md +++ /dev/null @@ -1,41 +0,0 @@ -# Contributing Guide - -Thank you for contributing to CMS Web! To maintain code quality and ensure a smooth development process, please adhere to the following guidelines. - ---- - -## 1. Development Workflow - -1. **Create a Branch**: Create a descriptive feature branch from `main`: - ```bash - git checkout -b feat/your-feature-name - ``` -2. **Implement Changes**: Ensure your changes are modular and contain appropriate comments. Avoid unrelated refactorings. -3. **Run Tests**: Always run backend tests locally to verify no regressions were introduced: - ```bash - go test -v ./test/... - ``` -4. **Commit & Push**: Commit with concise messages conforming to conventional commits (e.g. `feat: add ...`, `fix: resolve ...`): - ```bash - git add . - git commit -m "feat: add user profile page" - git push origin feat/your-feature-name - ``` -5. **Pull Request**: Open a pull request against the `main` branch. Provide a comprehensive summary of your changes. - ---- - -## 2. Code Conventions - -### Backend (Go) -* **GORM Models**: When creating or modifying database schemas, verify relationships and validation tags (e.g., `binding:"required"`, `gorm:"not null"`). -* **Endpoints**: Add routes to their designated category in the `routes/` package. -* **Error Handling**: Follow idiomatic Go patterns. Return clear JSON error payloads with relevant HTTP statuses: - * `400 Bad Request` for invalid input parameters/schemas. - * `401 Unauthorized` / `403 Forbidden` for failed authentication/authorization checks. - * `404 Not Found` when GORM queries return `gorm.ErrRecordNotFound`. - * `500 Internal Server Error` for database failures. - -### Frontend (React + TS) -* **TypeScript**: Define explicit types/interfaces for state, props, and API response schemas. Avoid using `any` whenever possible. -* **Styling**: Maintain vanilla CSS conventions and structure styles clearly within component directories. diff --git a/docs/Home.md b/docs/Home.md deleted file mode 100644 index 37f19f0..0000000 --- a/docs/Home.md +++ /dev/null @@ -1,20 +0,0 @@ -# Welcome to the CMS Web Wiki - -**CMS Web** is the official web interface of the Estate Office of NIT Hamirpur designed to streamline and manage maintenance complaints across the campus. It handles both **civil** and **electrical** complaints for both **official/departmental** buildings and **residential** quarters. - -## Project Structure - -Here is a quick overview of the key directories in this project: - -- **`/app`**: The frontend application built using **Vite**, **React**, and **TypeScript**. -- **`/handlers`**: Go backend controller logic handling authentication, posts (complaints), and comments. -- **`/models`**: Gorm database models representing users (Faculty, Warden, Centrehead, Admin), posts, and comments. -- **`/routes`**: API routing configurations for both user actions and administrative control. -- **`/middleware`**: Backend middleware including authentication and permissions checking. -- **`/test`**: Go backend test suite verifying auth flows, complaint management, and administrative actions. - -## Quick Links -- [[Local Setup|Local-Setup]] -- [[Architecture & Flows|Architecture-and-Flows]] -- [[API Reference|API-Reference]] -- [[Contributing|Contributing]] diff --git a/docs/Local-Setup.md b/docs/Local-Setup.md deleted file mode 100644 index 9de4122..0000000 --- a/docs/Local-Setup.md +++ /dev/null @@ -1,61 +0,0 @@ -# Local Setup - -This guide will help you get CMS Web running locally on your development machine. The project is split into a Go backend and a React + TypeScript frontend. - -## Prerequisites - -Ensure you have the following installed: -- [Go](https://go.dev/dl/) (version 1.20+) -- [Node.js](https://nodejs.org/en) (v18+) and npm -- A relational database (SQLite by default or PostgreSQL/MySQL depending on configuration) - ---- - -## 1. Backend Setup - -The backend is built in Go using the **Gin** framework and **GORM**. - -1. Navigate to the root directory of the project. -2. Create your `.env` configuration file from the example: - ```bash - cp .env.example .env - ``` - Configure your database credentials and secret keys inside `.env`. -3. Install the dependencies: - ```bash - go mod download - ``` -4. Run the backend server: - ```bash - go run main.go - ``` - The backend should now be running on its configured port (typically `:8080`). - ---- - -## 2. Frontend Setup - -The frontend is located in the `/app` folder. - -1. Navigate to the `/app` directory: - ```bash - cd app - ``` -2. Install dependencies: - ```bash - npm install - ``` -3. Run the Vite development server: - ```bash - npm run dev - ``` -4. Open the local address printed in the terminal (usually `http://localhost:5173`) in your browser. - ---- - -## 3. Running Tests - -To verify that everything is working as expected, run the Go test suite: -```bash -go test -v ./test/... -``` diff --git a/routes/admin.go b/routes/admin.go index 3981ed6..b158a57 100644 --- a/routes/admin.go +++ b/routes/admin.go @@ -26,9 +26,9 @@ func AdminRoutes (e *gin.Engine, h *handlers.AdminHandler) { // get the posts according to the status posts := e.Group("/api/admin") { - posts.GET("xen/posts", middleware.IsAuthenticated(), h.GetXENPosts) - posts.GET("ae/posts", middleware.IsAuthenticated(), h.GetAEPosts) - posts.GET("je/posts", middleware.IsAuthenticated(), h.GetJEPosts) + posts.GET("/xen/posts", middleware.IsAuthenticated(), h.GetXENPosts) + posts.GET("/ae/posts", middleware.IsAuthenticated(), h.GetAEPosts) + posts.GET("/je/posts", middleware.IsAuthenticated(), h.GetJEPosts) } // for any post From dbf6cf81b47e82681742e4cfbfe572fc55d4e3f8 Mon Sep 17 00:00:00 2001 From: Divyansh Date: Tue, 23 Jun 2026 09:38:30 +0530 Subject: [PATCH 08/11] feat: serve frontend React SPA static files from Go backend --- main.go | 24 +++++++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/main.go b/main.go index 0d99070..feb2ef8 100644 --- a/main.go +++ b/main.go @@ -3,6 +3,9 @@ package main import ( "fmt" "log" + "os" + "path/filepath" + "strings" "github.com/ayush00git/cms-web/config" "github.com/ayush00git/cms-web/handlers" @@ -54,6 +57,25 @@ func main() { routes.PostRoute(r, postHandler) routes.AdminRoutes(r, adminHandler) + // Fallback/serving logic for frontend React SPA in app/dist + r.NoRoute(func(c *gin.Context) { + // If request is for backend API, return standard 404 JSON response + if strings.HasPrefix(c.Request.URL.Path, "/api") { + c.JSON(404, gin.H{"error": "route not found"}) + return + } + + // Try to serve static file from app/dist + path := filepath.Join("app", "dist", c.Request.URL.Path) + if fileInfo, err := os.Stat(path); err == nil && !fileInfo.IsDir() { + c.File(path) + return + } + + // Fallback to index.html for SPA routing + c.File(filepath.Join("app", "dist", "index.html")) + }) + + fmt.Println("Server running on port 8080") r.Run(":8080") - fmt.Println("Sevrer running on port 8080") } From b8333e5d4453eee787a45f3dbfb802885771b3a5 Mon Sep 17 00:00:00 2001 From: Divyansh Date: Tue, 23 Jun 2026 09:39:42 +0530 Subject: [PATCH 09/11] Revert "feat: serve frontend React SPA static files from Go backend" This reverts commit dbf6cf81b47e82681742e4cfbfe572fc55d4e3f8. --- main.go | 24 +----------------------- 1 file changed, 1 insertion(+), 23 deletions(-) diff --git a/main.go b/main.go index feb2ef8..0d99070 100644 --- a/main.go +++ b/main.go @@ -3,9 +3,6 @@ package main import ( "fmt" "log" - "os" - "path/filepath" - "strings" "github.com/ayush00git/cms-web/config" "github.com/ayush00git/cms-web/handlers" @@ -57,25 +54,6 @@ func main() { routes.PostRoute(r, postHandler) routes.AdminRoutes(r, adminHandler) - // Fallback/serving logic for frontend React SPA in app/dist - r.NoRoute(func(c *gin.Context) { - // If request is for backend API, return standard 404 JSON response - if strings.HasPrefix(c.Request.URL.Path, "/api") { - c.JSON(404, gin.H{"error": "route not found"}) - return - } - - // Try to serve static file from app/dist - path := filepath.Join("app", "dist", c.Request.URL.Path) - if fileInfo, err := os.Stat(path); err == nil && !fileInfo.IsDir() { - c.File(path) - return - } - - // Fallback to index.html for SPA routing - c.File(filepath.Join("app", "dist", "index.html")) - }) - - fmt.Println("Server running on port 8080") r.Run(":8080") + fmt.Println("Sevrer running on port 8080") } From ae406a6d2aaccebab698b4367ac1c388d17a86b1 Mon Sep 17 00:00:00 2001 From: Divyansh Date: Tue, 23 Jun 2026 11:13:46 +0530 Subject: [PATCH 10/11] Wire admin comment GET, PATCH, and DELETE APIs to frontend and fix unused imports/variables --- app/package-lock.json | 30 +---- app/src/components/ComplaintCard.tsx | 1 - app/src/pages/admin/AdminPostView.tsx | 167 +++++++++++++++++++++++++- app/src/pages/profile/Profile.tsx | 2 +- 4 files changed, 165 insertions(+), 35 deletions(-) diff --git a/app/package-lock.json b/app/package-lock.json index df5c2ae..d66e589 100644 --- a/app/package-lock.json +++ b/app/package-lock.json @@ -562,7 +562,6 @@ "version": "0.130.0", "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.130.0.tgz", "integrity": "sha512-ibD2usx9JRu7f5pu2tMKMI4cpA4NgXJQoYRP4pQ7Pxmn1l6k/53qWtQWZayhYy3X4QZkt90Ot+mJEaeXouio6Q==", - "dev": true, "license": "MIT", "funding": { "url": "https://github.com/sponsors/Boshen" @@ -575,7 +574,6 @@ "cpu": [ "arm64" ], - "dev": true, "license": "MIT", "optional": true, "os": [ @@ -592,7 +590,6 @@ "cpu": [ "arm64" ], - "dev": true, "license": "MIT", "optional": true, "os": [ @@ -609,7 +606,6 @@ "cpu": [ "x64" ], - "dev": true, "license": "MIT", "optional": true, "os": [ @@ -626,7 +622,6 @@ "cpu": [ "x64" ], - "dev": true, "license": "MIT", "optional": true, "os": [ @@ -643,7 +638,6 @@ "cpu": [ "arm" ], - "dev": true, "license": "MIT", "optional": true, "os": [ @@ -660,7 +654,6 @@ "cpu": [ "arm64" ], - "dev": true, "license": "MIT", "optional": true, "os": [ @@ -677,7 +670,6 @@ "cpu": [ "arm64" ], - "dev": true, "license": "MIT", "optional": true, "os": [ @@ -694,7 +686,6 @@ "cpu": [ "ppc64" ], - "dev": true, "license": "MIT", "optional": true, "os": [ @@ -711,7 +702,6 @@ "cpu": [ "s390x" ], - "dev": true, "license": "MIT", "optional": true, "os": [ @@ -728,7 +718,6 @@ "cpu": [ "x64" ], - "dev": true, "license": "MIT", "optional": true, "os": [ @@ -745,7 +734,6 @@ "cpu": [ "x64" ], - "dev": true, "license": "MIT", "optional": true, "os": [ @@ -762,7 +750,6 @@ "cpu": [ "arm64" ], - "dev": true, "license": "MIT", "optional": true, "os": [ @@ -779,7 +766,6 @@ "cpu": [ "wasm32" ], - "dev": true, "license": "MIT", "optional": true, "dependencies": { @@ -798,7 +784,6 @@ "cpu": [ "arm64" ], - "dev": true, "license": "MIT", "optional": true, "os": [ @@ -815,7 +800,6 @@ "cpu": [ "x64" ], - "dev": true, "license": "MIT", "optional": true, "os": [ @@ -829,7 +813,6 @@ "version": "1.0.1", "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.1.tgz", "integrity": "sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==", - "dev": true, "license": "MIT" }, "node_modules/@tailwindcss/node": { @@ -1124,7 +1107,7 @@ "version": "24.12.4", "resolved": "https://registry.npmjs.org/@types/node/-/node-24.12.4.tgz", "integrity": "sha512-GUUEShf+PBCGW2KaXwcIt3Yk+e3pkKwWKb9GSyM9WQVE+ep2jzmHdGsHzu4wgcZy5fN9FBdVzjpBQsYlpfpgLA==", - "dev": true, + "devOptional": true, "license": "MIT", "dependencies": { "undici-types": "~7.16.0" @@ -1876,7 +1859,6 @@ "version": "6.5.0", "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", - "dev": true, "license": "MIT", "engines": { "node": ">=12.0.0" @@ -1945,7 +1927,6 @@ "version": "2.3.3", "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", - "dev": true, "hasInstallScript": true, "license": "MIT", "optional": true, @@ -2472,7 +2453,6 @@ "version": "3.3.12", "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.12.tgz", "integrity": "sha512-ZB9RH/39qpq5Vu6Y+NmUaFhQR6pp+M2Xt76XBnEwDaGcVAqhlvxrl3B2bKS5D3NH3QR76v3aSrKaF/Kiy7lEtQ==", - "dev": true, "funding": [ { "type": "github", @@ -2575,14 +2555,12 @@ "version": "1.1.1", "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", - "dev": true, "license": "ISC" }, "node_modules/picomatch": { "version": "4.0.4", "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.4.tgz", "integrity": "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==", - "dev": true, "license": "MIT", "engines": { "node": ">=12" @@ -2595,7 +2573,6 @@ "version": "8.5.15", "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.15.tgz", "integrity": "sha512-FfR8sjd4em2T6fb3I2MwAJU7HWVMr9zba+enmQeeWFfCbm+UOC/0X4DS8XtpUTMwWMGbjKYP7xjfNekzyGmB3A==", - "dev": true, "funding": [ { "type": "opencollective", @@ -2703,7 +2680,6 @@ "version": "1.0.1", "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.0.1.tgz", "integrity": "sha512-X0KQHljNnEkWNqqiz9zJrGunh1B0HgOxLXvnFpCOcadzcy5qohZ3tqMEUg00vncoRovXuK3ZqCT9KnnKzoInFQ==", - "dev": true, "license": "MIT", "dependencies": { "@oxc-project/types": "=0.130.0", @@ -2810,7 +2786,6 @@ "version": "0.2.16", "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.16.tgz", "integrity": "sha512-pn99VhoACYR8nFHhxqix+uvsbXineAasWm5ojXoN8xEwK5Kd3/TrhNn1wByuD52UxWRLy8pu+kRMniEi6Eq9Zg==", - "dev": true, "license": "MIT", "dependencies": { "fdir": "^6.5.0", @@ -2898,7 +2873,7 @@ "version": "7.16.0", "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.16.0.tgz", "integrity": "sha512-Zz+aZWSj8LE6zoxD+xrjh4VfkIG8Ya6LvYkZqtUQGJPZjYl53ypCaUwWqo7eI0x66KBGeRo+mlBEkMSeSZ38Nw==", - "dev": true, + "devOptional": true, "license": "MIT" }, "node_modules/update-browserslist-db": { @@ -2946,7 +2921,6 @@ "version": "8.0.13", "resolved": "https://registry.npmjs.org/vite/-/vite-8.0.13.tgz", "integrity": "sha512-MFtjBYgzmSxmgA4RAfjIyXWpGe1oALnjgUTzzV7QLx/TKxCzjtMH6Fd9/eVK+5Fg1qNoz5VAwsmMs/NofrmJvw==", - "dev": true, "license": "MIT", "dependencies": { "lightningcss": "^1.32.0", diff --git a/app/src/components/ComplaintCard.tsx b/app/src/components/ComplaintCard.tsx index 477d98a..20a760a 100644 --- a/app/src/components/ComplaintCard.tsx +++ b/app/src/components/ComplaintCard.tsx @@ -310,7 +310,6 @@ function PostModal({ const isElectrical = post.type_of_post === 'Electrical'; const theme = typeTheme(isElectrical); const comments = post.comments ?? []; - const currentStageIdx = STAGES.indexOf(post.stage); const editExpired = isEditWindowExpired(post.created_at); return createPortal( diff --git a/app/src/pages/admin/AdminPostView.tsx b/app/src/pages/admin/AdminPostView.tsx index f01cb6a..dad81d3 100644 --- a/app/src/pages/admin/AdminPostView.tsx +++ b/app/src/pages/admin/AdminPostView.tsx @@ -14,6 +14,8 @@ import { XCircle, ChevronRight, RefreshCcw, + Pencil, + Trash2, } from 'lucide-react'; import { MainLayout } from '../../components/layout/MainLayout'; @@ -229,6 +231,26 @@ export function AdminPostView() { const [actSuccess, setActSuccess] = useState(null); const actTimer = useRef | null>(null); + // Admin's own comments states + const [adminComments, setAdminComments] = useState([]); + const [editingCommentId, setEditingCommentId] = useState(null); + const [editingText, setEditingText] = useState(''); + const [commentActionLoadingId, setCommentActionLoadingId] = useState(null); + + const fetchAdminComments = useCallback(() => { + fetch('/api/admin/comments', { credentials: 'include' }) + .then((res) => { + if (!res.ok) throw new Error('Failed to fetch admin comments'); + return res.json(); + }) + .then((json) => { + if (json.comments) { + setAdminComments(json.comments); + } + }) + .catch((err) => console.error(err)); + }, []); + const fetchPost = useCallback((silent = false) => { if (!silent) setLoading(true); fetch(`/api/admin/posts/${role}/${post_id}`, { credentials: 'include' }) @@ -256,9 +278,82 @@ export function AdminPostView() { }); }, [role, post_id, navigate]); - useEffect(() => { fetchPost(); }, [fetchPost]); + useEffect(() => { + fetchPost(); + fetchAdminComments(); + }, [fetchPost, fetchAdminComments]); + useEffect(() => () => { if (actTimer.current) clearTimeout(actTimer.current); }, []); + // ── Edit comment handler ── + async function handleEditComment(commentId: number) { + const trimmed = editingText.trim(); + if (!trimmed) return; + + const commentApi = ROLE_TO_COMMENT_API[role ?? '']; + if (!commentApi) { + setActError('Unknown post type.'); + return; + } + + setCommentActionLoadingId(commentId); + try { + const res = await fetch(`/api/admin/comment/${commentApi}/${post_id}/${commentId}`, { + method: 'PATCH', + credentials: 'include', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ Content: trimmed }), + }); + + if (!res.ok) { + let msg = `Failed to edit comment (${res.status})`; + try { const b = await res.json(); if (b?.error) msg = b.error; } catch {} + throw new Error(msg); + } + + setEditingCommentId(null); + setEditingText(''); + fetchPost(true); + fetchAdminComments(); + } catch (err) { + alert((err as Error).message); + } finally { + setCommentActionLoadingId(null); + } + } + + // ── Delete comment handler ── + async function handleDeleteComment(commentId: number) { + if (!window.confirm('Are you sure you want to delete this comment?')) return; + + const commentApi = ROLE_TO_COMMENT_API[role ?? '']; + if (!commentApi) { + setActError('Unknown post type.'); + return; + } + + setCommentActionLoadingId(commentId); + try { + const res = await fetch(`/api/admin/comment/${commentApi}/${post_id}/${commentId}`, { + method: 'DELETE', + credentials: 'include', + }); + + if (!res.ok) { + let msg = `Failed to delete comment (${res.status})`; + try { const b = await res.json(); if (b?.error) msg = b.error; } catch {} + throw new Error(msg); + } + + fetchPost(true); + fetchAdminComments(); + } catch (err) { + alert((err as Error).message); + } finally { + setCommentActionLoadingId(null); + } + } + // ── Combined handler: post comment THEN update status ── async function handleAction(review: string) { const trimmed = commentText.trim(); @@ -307,6 +402,7 @@ export function AdminPostView() { if (actTimer.current) clearTimeout(actTimer.current); actTimer.current = setTimeout(() => setActSuccess(null), 3000); fetchPost(true); + fetchAdminComments(); } catch (err) { setActError((err as Error).message); } finally { @@ -462,14 +558,75 @@ export function AdminPostView() {
    {comments.map((c) => { const who = c.role ? c.role.replace(/_/g, ' ') : 'Staff'; + const isMyComment = adminComments.some((ac) => ac.id === c.id); + const isEditing = editingCommentId === c.id; + const isBusy = commentActionLoadingId === c.id; + return ( -
  • +
  • {who} - {c.email && {c.email}} - {formatDateTime(c.created_at)} + {c.email && {c.email}} + + {formatDateTime(c.created_at)} + + {/* Edit/Delete actions (only shown for owner comments on hover and when not editing) */} + {isMyComment && !isEditing && ( + + + + + )} +
    -

    {c.comment_text}

    + + {isEditing ? ( +
    +