# HSE
# Voltech EHS Platform

Full-stack EHS (Environment, Health & Safety) application for Voltech Group.
It uses the same stack and conventions as the HRMS project, and the look of the
client-approved demo (`voltech-hse-demo.html`).

**Phase 1 (this release):** login, app shell (sidebar, top bar, Company/Division/Site scope),
dashboard shell and the full **Master Setup** module, including **User Master** and
**Roles & Rights** (who can view, create, edit or delete on each screen). Every other menu item is in place and
shows a "coming in a later phase" page.

| Layer    | Technology (same as HRMS)                                    |
|----------|--------------------------------------------------------------|
| Frontend | React 19 + Vite 7, React Router 7, Axios                      |
| Backend  | Node.js + Express 4, JWT auth (jsonwebtoken), bcryptjs       |
| Database | MySQL 8 (mysql2), numbered SQL files in `backend/sql/`        |

## Run it locally

Prerequisites: **Node.js 20+** and **MySQL 8** (or MariaDB 10.6+).

```bash
# 1. Database user (once). Any MySQL user with rights on voltech_ehs works.
mysql -u root -p -e "CREATE DATABASE voltech_ehs CHARACTER SET utf8mb4;"

# 2. Backend
cd backend
cp .env.example .env          # set DB_USER / DB_PASSWORD / JWT_SECRET
npm install
npm run db:migrate            # creates the tables (backend/sql/*.sql)
npm run db:seed               # roles, 17 demo users, 2 companies, 5 divisions, 9 sites, 7 HSE lists
npm run dev                   # API on http://localhost:5000

# 3. Frontend (second terminal)
cd frontend
npm install
npm run dev                   # http://localhost:5173  (proxies /api to :5000)
```

Open http://localhost:5173 and sign in.

| Who | Employee ID | Email | Can |
|---|---|---|---|
| Gopal Iyer, Corporate HSE Head | `VT-HSE-0013` | gopal.iyer@voltech.demo | full access (every screen, users and rights) |
| Ramesh Kannan, Site HSE Manager | `VT-SPB-0201` | ramesh.kannan@voltech.demo | views master data, assigns people to sites |
| Karthik Sundaram, HSE Officer | `VT-TLP-0311` | karthik.sundaram@voltech.demo | views master data only |

Every seeded user has the password **`Voltech@2026`** (set `SEED_PASSWORD` in `backend/.env`
before seeding to change it). All seeded companies, people and emails are sample data.

### Useful scripts (backend)

| Script | What it does |
|---|---|
| `npm run db:migrate` | Applies new files in `backend/sql/` in order and records them in `schema_migrations`. The files can also be run by hand in MySQL Workbench, as in HRMS. |
| `npm run db:seed` | Loads the sample data. On an existing database it only adds default rights for roles that have none (the upgrade step from the first Phase 1 drop). |
| `npm run db:reset` | Drops all tables, migrates and seeds again. Local use only; refuses when `NODE_ENV=production`. |
| `npm run test:smoke` | With the API running: 33 end-to-end checks of login, every Master Setup action, users, roles and rights enforcement, then cleans up. |

## Master Setup

| Screen | What it does |
|---|---|
| **Company Master** | Legal entities (code, legal name, GSTIN, CIN, head office, corporate HSE head, status). |
| **Division Master** | Divisions under a company. Type **Manufacturing** or **Services** decides the checklist (MFG-WSI / SVC-WSI) and risk register its sites use. |
| **Site Master** | Company › Division › Site tree, site details, in-charge history and change log. |
| **Site User Assignment** | Who can act at each site and in which role (roles drive permit approval chains later). |
| **User Master** | People who can sign in: employee ID, work email, designation, phone, role, status, password (set or reset by the administrator) and the sites they work at. Search and filter by role and status; shows last sign-in. Users change their own password from the top-right menu. |
| **Roles & Rights** | Roles and a rights matrix: for every screen/module, View / Create / Edit / Delete. A role can instead be marked **full access**. Add, edit, retire (inactive) or delete roles; a new role can start from another role's rights. |
| **HSE Master Data** | Shared drop-down lists: hazard categories, PPE types, inspection standards, incident types, severity levels, departments, training types. Add lists and values, rename, deactivate, delete. |

### The site mailbox rule

Each site owns **one permanent HSE email** (`sites.email`, unique per site). It belongs to the site, not to a person:

* **Change in-charge** moves the site to a new person, closes the previous period in
  `site_in_charge_history`, assigns the new person to the site, and writes the change log.
  The mailbox is never touched.
* The normal **Edit site** form cannot change the mailbox or the in-charge.
* If the mailbox address itself has to change (for example IT renamed it), an admin uses
  **Correct** on the mailbox. That is a separate, logged action.

### Users, roles and rights

* Every user has **one role**. The role's rights decide which menu items they see and what
  they can do. The modules and their keys are listed in `backend/src/config/modules.js`
  (Master Setup screens each have their own rights; later modules have one entry each).
* The API checks the right on **every** request: `GET` needs View, `POST` Create, `PUT`/`PATCH`
  Edit, `DELETE` Delete (`permit()` in `backend/src/middleware/auth.js`). The screens hide menu
  items and disable buttons the same way, and show "No access" if someone opens a link directly.
* Rights changes take effect on the user's next action; no new sign-in is needed.
* Ticking Create, Edit or Delete also ticks View.
* Users chosen in User Master's **Site access** appear in Site User Assignment with their role;
  the role per site can then be changed there.
* Safety rules: you cannot delete or deactivate yourself; at least one active user must keep a
  full-access role; a user who is a site in-charge or a company HSE head cannot be deleted (set
  them Inactive, or move that duty first); a role still in use cannot be deleted.
* Inactive users cannot sign in.

## Branding, profile menu and User Preferences

* Brand: an orange **HSE** tile (curved bottom corner, like the demo's V tile) followed by the
  white VEPL logo (`frontend/src/assets/VEPL_New_white.svg`, also in `frontend/public/`), on the
  sidebar and the sign-in page. The logo is drawn by `components/VeplLogo.jsx` in the sidebar's
  text colour, so it turns dark on the light "Steel" sidebar. A collapsed sidebar shows the HSE tile.
* Footer on every screen and on sign-in: "© <year> Voltech Group · Software Development Team",
  linked to https://software.voltechgroup.com/ (`components/AppFooter.jsx`).
* Profile menu (your name, top right): User preferences, Change password, Switch light / dark, Logout.
* **Settings → User Preferences** is open to every signed-in user (it is personal, so no right is
  needed): theme, sidebar colour, accent colour, density, collapsed sidebar, landing page after
  sign-in, default site scope, date format and notification choices. Saved in the browser
  (`vt_hse_prefs`), same as the demo. Change password is also on this page.

## Project structure

```
backend/
  sql/                       001_auth_users_roles.sql, 002_master_setup.sql, 003_users_roles_rights.sql
  src/
    app.js, server.js
    config/                  index.js (.env loading), db.js (mysql2 pool)
    middleware/auth.js       requireAuth (JWT), requireAdmin
    data/userStore.js        user lookups for login (email or employee ID)
    config/modules.js        modules that have rights + default rights for the seeded roles
    controllers/             auth, company, division, site, siteUser, hseMasterData, users, roles, lookup, dashboard
    routes/                  authRoutes, masterRoutes, dashboardRoutes
    utils/http.js            validation, error mapping, audit log helper
    scripts/                 migrate.js, seed.js, smokeTest.js
frontend/
  src/
    index.css                the approved demo's stylesheet, unchanged
    styles/app-extras.css    small additions (row actions, loading states)
    api/axios.js             Axios instance with the JWT header (as HRMS)
    context/                 AuthContext, ScopeContext (lookups + top-bar scope)
    config/menu.js           the demo's full sidebar menu
    layouts/                 MainLayout, Sidebar, Topbar
    components/              Icon (demo icon set), FormSheet (demo full-screen form), Feedback (toast/confirm/modal), ui
    pages/auth/Login.jsx
    pages/dashboard/Dashboard.jsx
    pages/master-setup/      company/, division/, site/, site-users/, master-data/, users/, roles/
    pages/settings/          UserPreferences.jsx
    assets/                  VEPL_New_white.svg (logo source)
    utils/prefs.js           appearance + work-default preferences
```

## API (all under `/api`, JSON, `Authorization: Bearer <token>` except login)

| Method | Path | |
|---|---|---|
| POST | `/auth/login` | `{ login, password }` where login is employee ID or email |
| GET | `/auth/me` · POST `/auth/logout` · POST `/auth/change-password` | `/auth/me` and login return the user's rights |
| GET | `/master/lookups` | companies, divisions, sites, users, roles for drop-downs |
| GET POST PUT DELETE | `/master/companies[/:id]`, `/master/divisions[/:id]`, `/master/site-users[/:id]` | |
| GET POST PUT DELETE | `/master/sites[/:id]` | GET `/:id` includes in-charge history and change log |
| POST | `/master/sites/:id/change-in-charge` | `{ user_id, effective_from, reason }` |
| PATCH | `/master/sites/:id/email` | `{ email, reason }` mailbox correction |
| GET POST | `/master/master-data` | lists with values / create list |
| POST | `/master/master-data/:listId/values` | add value |
| PUT DELETE | `/master/master-data/values/:id` | rename, activate/deactivate, delete |
| GET POST PUT DELETE | `/master/users[/:id]` | users; `site_ids: [..]` sets site access; blank `password` on edit keeps the old one |
| GET | `/master/roles/modules` | modules and actions for the rights matrix |
| GET POST PUT DELETE | `/master/roles[/:id]` | roles with `permissions: { moduleKey: { view, create, edit, delete } }` |
| GET | `/dashboard/summary?company=&division=&site=` | dashboard figures for the scope |

## Deploying

Same as HRMS: `npm run build` in `frontend/` and serve `frontend/dist` (Apache/Nginx, with
`/api` proxied to the backend), run the backend with PM2 (`pm2 start src/server.js --name voltech-ehs-api`),
and keep real secrets only in `backend/.env` on the server.

## Next phases

HIRA & Risk Assessment, Work Permits, Audit & Inspection, Incident Management, Training,
Legal & Compliance, Safety Asset Tracking, Achievements & Events, Reports, Settings. Each one
reads companies, divisions, sites, site mailboxes, people, roles and lookup lists from Master
Setup, and already has its row in the rights matrix.

**Upgrading a database from the first Phase 1 drop:** run `npm run db:migrate` (adds
`003_users_roles_rights.sql`), then `npm run db:seed` (adds default rights for the existing roles).
