phase-0: scaffold backend and frontend shell

This commit is contained in:
Atharv1705
2026-11-12 12:12:15 +05:30
commit cb2f48620c
67 changed files with 9125 additions and 0 deletions
+4
View File
@@ -0,0 +1,4 @@
DATABASE_URL=sqlite:///./data/ams.db
SECRET_KEY=change-me-in-production-use-a-32-char-random-string
UPLOAD_DIR=./data/uploads
TIMEZONE=Asia/Kolkata
+20
View File
@@ -0,0 +1,20 @@
backend/data/ams.db
backend/data/test.db
backend/data/uploads/*
!backend/data/uploads/.gitkeep
backend/data/*
!backend/data/.gitkeep
!backend/data/uploads/
.venv/
backend/.venv/
.pytest_cache/
**/.pytest_cache/
__pycache__/
**/__pycache__/
**/*.pyc
*.pyc
frontend/node_modules/
frontend/dist/
.env
*.env.local
.DS_Store
+17
View File
@@ -0,0 +1,17 @@
# Agent Operating Rules — Poona Hospital AMS
- Build exactly what the plan and proposal describe. **Out of scope:** QR codes, barcode scanning, SMS/WhatsApp, any AI/LLM features, payment/rent/depreciation modules, multi-hospital tenancy, mobile native apps.
- Work phase by phase. Do not start the next phase until told. Commit at the end of each phase with message `phase-N: <summary>`.
- Never invent requirements. Where the proposal says "to be confirmed", implement it as an editable setting with the default given in section 4 and log it in `docs/ASSUMPTIONS.md`.
- Store all timestamps in UTC; display in Asia/Kolkata with format `DD-MMM-YYYY HH:mm` (dates only: `DD-MMM-YYYY`). One shared formatting helper on the frontend (src/lib/format.ts); one on the backend (app/core/time_utils.py).
- Business calculations live in pure functions in `backend/app/services/` with unit tests. Routers stay thin.
- Permissions are enforced on the server (including field-level). The UI hides or disables controls as a convenience only.
- No secrets in code. Demo passwords exist only in the seed script and the README.
- Keep dependencies minimal and pinned.
- After each phase update README.md.
- If something is ambiguous and blocking, make the most reasonable choice, record it in `docs/ASSUMPTIONS.md`, and continue.
## Implementation Notes
- N1: When renewing a contract, add `is_superseded: bool = False` to the contracts model and set True on the old contract when renewing, so history filtering works cleanly.
- N2: `calibration_records.status` and `pm_records.status` values `upcoming`/`due`/`overdue` are NEVER stored in the DB; only `completed` is persisted. The Pydantic response schema computes them from due_date and effective_today().
- N3: SQLite engine must use `check_same_thread=False`, WAL mode, and busy_timeout=5000ms. APScheduler jobs must use `get_scheduler_db()` context manager — never a request session.
+29
View File
@@ -0,0 +1,29 @@
.PHONY: dev backend frontend test seed install
ifeq ($(OS),Windows_NT)
VENV_BIN := .venv/Scripts
PYTHON_SYS := python
else
VENV_BIN := .venv/bin
PYTHON_SYS := python3
endif
dev:
$(MAKE) -j2 backend frontend
backend:
cd backend && "$(VENV_BIN)/uvicorn" app.main:app --reload --port 8000
frontend:
cd frontend && npm run dev
test:
cd backend && "$(VENV_BIN)/python" -m pytest tests/ -v
seed:
cd backend && "$(VENV_BIN)/python" -m app.seed.seed
install:
$(PYTHON_SYS) -m venv backend/.venv
"backend/$(VENV_BIN)/pip" install -r backend/requirements.txt
cd frontend && npm install
+72
View File
@@ -0,0 +1,72 @@
# Poona Hospital Asset Management System
![Poona Hospital and Research Centre](frontend/public/logo.jpg)
A centralized Hospital Asset Management and Maintenance System for Poona Hospital and Research Centre.
## Quick Start
### Prerequisites
- Python 3.11+
- Node.js 18+
### Backend
```bash
cd backend
python -m venv .venv
# Windows PowerShell: .venv\Scripts\Activate.ps1
# macOS/Linux: source .venv/bin/activate
.venv/Scripts/pip install -r requirements.txt # or pip install -r requirements.txt once activated
.venv/Scripts/uvicorn app.main:app --reload --port 8000
```
- Health check: http://localhost:8000/api/health
- API docs: http://localhost:8000/docs
### Frontend
```bash
cd frontend
npm install
npm run dev
```
- App: http://localhost:5173
### Run both servers (with Make)
```bash
make dev
```
### Run tests
```bash
make test
# Or directly:
cd backend
.venv/Scripts/python -m pytest tests/ -v
```
### Seed demo data (available after Phase 1)
```bash
cd backend
.venv/Scripts/python -m app.seed.seed
```
## Demo Accounts (available after Phase 1)
| Email | Password | Role |
|---|---|---|
| admin@poona.demo | Demo@123 | System Admin |
| bio@poona.demo | Demo@123 | Biomedical |
| dept@poona.demo | Demo@123 | Department User (ICU) |
| mgmt@poona.demo | Demo@123 | Management |
| coord@poona.demo | Demo@123 | Coordinator |
## What exists now (Phase 0)
- FastAPI backend scaffold with `/api/health` endpoint
- React + TypeScript frontend with full app shell
- Left sidebar with all module links (stubbed pages)
- DataTable component with column filters, sort, pagination, CSV export
- Tailwind CSS + shadcn/ui design system
- Makefile for common tasks
## Modules (all phases)
Phase 0: Scaffold | Phase 1: Auth & Masters | Phase 2: Assets | Phase 3: Complaints
Phase 4: PM & Calibration | Phase 5: Contracts, Warranty, Insurance, Demo, Visits
Phase 6: Notifications & Dashboard | Phase 7: Reports | Phase 8: Polish
View File
View File
+15
View File
@@ -0,0 +1,15 @@
from pydantic_settings import BaseSettings, SettingsConfigDict
class Settings(BaseSettings):
model_config = SettingsConfigDict(env_file=".env", extra="ignore")
DATABASE_URL: str = "sqlite:///./data/ams.db"
SECRET_KEY: str = "change-me-in-production-32-chars-min"
UPLOAD_DIR: str = "./data/uploads"
TIMEZONE: str = "Asia/Kolkata"
ACCESS_TOKEN_EXPIRE_MINUTES: int = 480
ALGORITHM: str = "HS256"
MAX_UPLOAD_SIZE_MB: int = 10
settings = Settings()
+42
View File
@@ -0,0 +1,42 @@
from sqlalchemy import create_engine, event
from sqlalchemy.orm import sessionmaker, Session
from contextlib import contextmanager
from .config import settings
engine = create_engine(
settings.DATABASE_URL,
connect_args={"check_same_thread": False},
)
@event.listens_for(engine, "connect")
def set_sqlite_pragmas(dbapi_conn, connection_record):
cursor = dbapi_conn.cursor()
cursor.execute("PRAGMA journal_mode=WAL")
cursor.execute("PRAGMA busy_timeout=5000")
cursor.close()
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
@contextmanager
def get_scheduler_db() -> Session:
"""Short-lived session for APScheduler jobs — never share with request sessions."""
db = SessionLocal()
try:
yield db
db.commit()
except Exception:
db.rollback()
raise
finally:
db.close()
+7
View File
@@ -0,0 +1,7 @@
# Placeholder — full implementation in Phase 1 when User model exists.
from fastapi import Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/api/auth/login")
# get_current_user and require_roles will be implemented in Phase 1.
+26
View File
@@ -0,0 +1,26 @@
from datetime import timedelta
from jose import JWTError, jwt
from passlib.context import CryptContext
from .config import settings
from .time_utils import utc_now
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
def verify_password(plain: str, hashed: str) -> bool:
return pwd_context.verify(plain, hashed)
def hash_password(plain: str) -> str:
return pwd_context.hash(plain)
def create_access_token(data: dict, expires_minutes: int | None = None) -> str:
to_encode = data.copy()
expire = utc_now() + timedelta(minutes=expires_minutes or settings.ACCESS_TOKEN_EXPIRE_MINUTES)
to_encode["exp"] = expire
return jwt.encode(to_encode, settings.SECRET_KEY, algorithm=settings.ALGORITHM)
def decode_token(token: str) -> dict:
return jwt.decode(token, settings.SECRET_KEY, algorithms=[settings.ALGORITHM])
+47
View File
@@ -0,0 +1,47 @@
from datetime import date, datetime, timezone
import pytz
KOLKATA = pytz.timezone("Asia/Kolkata")
def utc_now() -> datetime:
return datetime.now(timezone.utc)
def effective_today() -> date:
"""Returns demo_as_of_date from settings if set, else real today (Asia/Kolkata).
Phase 0: always real today. Phase 1 wires in DB settings lookup."""
return datetime.now(KOLKATA).date()
def to_kolkata(dt: datetime) -> datetime:
return dt.astimezone(KOLKATA)
def format_datetime(dt: datetime | None) -> str | None:
if dt is None:
return None
local = to_kolkata(dt) if dt.tzinfo else KOLKATA.localize(dt)
return local.strftime("%d-%b-%Y %H:%M")
def format_date(d: date | None) -> str | None:
if d is None:
return None
return d.strftime("%d-%b-%Y")
def format_duration(minutes: int | None) -> str:
if minutes is None:
return "\u2014"
minutes = int(minutes)
d, rem = divmod(minutes, 1440)
h, m = divmod(rem, 60)
parts = []
if d:
parts.append(f"{d}d")
if h:
parts.append(f"{h}h")
if m or not parts:
parts.append(f"{m}m")
return " ".join(parts)
+44
View File
@@ -0,0 +1,44 @@
import logging
import traceback
from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from .core.db import engine
from .models import Base
from .routers import health
# Logging setup
logging.basicConfig(
format="%(asctime)s | %(levelname)s | %(name)s | %(message)s",
level=logging.INFO,
)
logger = logging.getLogger("poona_ams")
app = FastAPI(title="Poona Hospital AMS", version="0.1.0", docs_url="/docs")
app.add_middleware(
CORSMiddleware,
allow_origins=["http://localhost:5173", "http://127.0.0.1:5173"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
@app.exception_handler(Exception)
async def global_exception_handler(request: Request, exc: Exception):
logger.error(f"Unhandled exception: {traceback.format_exc()}")
return JSONResponse(
status_code=500,
content={"detail": "An internal error occurred.", "code": "INTERNAL_ERROR"},
)
app.include_router(health.router, prefix="/api")
@app.on_event("startup")
def startup():
Base.metadata.create_all(bind=engine)
logger.info("Database tables created/verified.")
logger.info("Poona Hospital AMS started.")
+1
View File
@@ -0,0 +1 @@
from .base import Base
+5
View File
@@ -0,0 +1,5 @@
from sqlalchemy.orm import DeclarativeBase
class Base(DeclarativeBase):
pass
View File
+8
View File
@@ -0,0 +1,8 @@
from fastapi import APIRouter
router = APIRouter(tags=["health"])
@router.get("/health")
def health_check():
return {"status": "ok", "service": "Poona Hospital AMS", "version": "0.1.0"}
View File
View File
View File
View File
+15
View File
@@ -0,0 +1,15 @@
fastapi==0.115.5
uvicorn[standard]==0.32.1
sqlalchemy==2.0.36
pydantic==2.10.1
pydantic-settings==2.6.1
python-jose[cryptography]==3.3.0
passlib[bcrypt]==1.7.4
python-multipart==0.0.12
apscheduler==3.10.4
openpyxl==3.1.5
pillow==11.0.0
pytest==8.3.3
pytest-asyncio==0.24.0
httpx==0.28.0
pytz==2024.2
View File
+34
View File
@@ -0,0 +1,34 @@
import pytest
from fastapi.testclient import TestClient
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from app.main import app
from app.core.db import get_db
from app.models import Base
SQLALCHEMY_TEST_URL = "sqlite:///./data/test.db"
engine_test = create_engine(SQLALCHEMY_TEST_URL, connect_args={"check_same_thread": False})
TestingSessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine_test)
@pytest.fixture(scope="session")
def db():
Base.metadata.create_all(bind=engine_test)
session = TestingSessionLocal()
yield session
session.close()
Base.metadata.drop_all(bind=engine_test)
@pytest.fixture(scope="session")
def client(db):
def override_get_db():
try:
yield db
finally:
pass
app.dependency_overrides[get_db] = override_get_db
with TestClient(app) as c:
yield c
app.dependency_overrides.clear()
+7
View File
@@ -0,0 +1,7 @@
def test_health_check(client):
response = client.get("/api/health")
assert response.status_code == 200
data = response.json()
assert data["status"] == "ok"
assert data["service"] == "Poona Hospital AMS"
assert data["version"] == "0.1.0"
+38
View File
@@ -0,0 +1,38 @@
from datetime import date, datetime, timezone
from app.core.time_utils import format_date, format_datetime, format_duration
def test_format_datetime_none():
assert format_datetime(None) is None
def test_format_datetime_utc_to_kolkata():
dt = datetime(2025, 3, 15, 10, 30, tzinfo=timezone.utc)
assert format_datetime(dt) == "15-Mar-2025 16:00"
def test_format_datetime_naive_assumes_kolkata():
dt = datetime(2025, 3, 15, 9, 5)
assert format_datetime(dt) == "15-Mar-2025 09:05"
def test_format_date_none():
assert format_date(None) is None
def test_format_date_valid():
assert format_date(date(2025, 1, 5)) == "05-Jan-2025"
def test_format_duration_none():
assert format_duration(None) == "\u2014"
def test_format_duration_values():
assert format_duration(0) == "0m"
assert format_duration(45) == "45m"
assert format_duration(60) == "1h"
assert format_duration(90) == "1h 30m"
assert format_duration(1440) == "1d"
assert format_duration(1445) == "1d 5m"
assert format_duration(1505) == "1d 1h 5m"
+3
View File
@@ -0,0 +1,3 @@
# Assumptions Log
Will be populated with all assumptions during Phase 1.
+6
View File
@@ -0,0 +1,6 @@
# Implementation Plan
Full plan is in docs/. See the user's implementation plan document for the complete specification.
This file will be updated progressively as phases are completed.
**Current phase:** 0 — Scaffold
+24
View File
@@ -0,0 +1,24 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dist-ssr
*.local
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
+50
View File
@@ -0,0 +1,50 @@
# React + TypeScript + Vite
This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.
Currently, two official plugins are available:
- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react/README.md) uses [Babel](https://babeljs.io/) for Fast Refresh
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react-swc) uses [SWC](https://swc.rs/) for Fast Refresh
## Expanding the ESLint configuration
If you are developing a production application, we recommend updating the configuration to enable type aware lint rules:
- Configure the top-level `parserOptions` property like this:
```js
export default tseslint.config({
languageOptions: {
// other options...
parserOptions: {
project: ['./tsconfig.node.json', './tsconfig.app.json'],
tsconfigRootDir: import.meta.dirname,
},
},
})
```
- Replace `tseslint.configs.recommended` to `tseslint.configs.recommendedTypeChecked` or `tseslint.configs.strictTypeChecked`
- Optionally add `...tseslint.configs.stylisticTypeChecked`
- Install [eslint-plugin-react](https://github.com/jsx-eslint/eslint-plugin-react) and update the config:
```js
// eslint.config.js
import react from 'eslint-plugin-react'
export default tseslint.config({
// Set the react version
settings: { react: { version: '18.3' } },
plugins: {
// Add the react plugin
react,
},
rules: {
// other rules...
// Enable its recommended rules
...react.configs.recommended.rules,
...react.configs['jsx-runtime'].rules,
},
})
```
+28
View File
@@ -0,0 +1,28 @@
import js from '@eslint/js'
import globals from 'globals'
import reactHooks from 'eslint-plugin-react-hooks'
import reactRefresh from 'eslint-plugin-react-refresh'
import tseslint from 'typescript-eslint'
export default tseslint.config(
{ ignores: ['dist'] },
{
extends: [js.configs.recommended, ...tseslint.configs.recommended],
files: ['**/*.{ts,tsx}'],
languageOptions: {
ecmaVersion: 2020,
globals: globals.browser,
},
plugins: {
'react-hooks': reactHooks,
'react-refresh': reactRefresh,
},
rules: {
...reactHooks.configs.recommended.rules,
'react-refresh/only-export-components': [
'warn',
{ allowConstantExport: true },
],
},
},
)
+13
View File
@@ -0,0 +1,13 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" href="/logo.jpg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Poona Hospital AMS</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
+7409
View File
File diff suppressed because it is too large Load Diff
+63
View File
@@ -0,0 +1,63 @@
{
"name": "frontend",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc -b && vite build",
"lint": "eslint .",
"preview": "vite preview",
"test": "vitest run"
},
"dependencies": {
"@hookform/resolvers": "^3.10.0",
"@radix-ui/react-checkbox": "^1.1.2",
"@radix-ui/react-dialog": "^1.1.2",
"@radix-ui/react-dropdown-menu": "^2.1.2",
"@radix-ui/react-label": "^2.1.0",
"@radix-ui/react-popover": "^1.1.2",
"@radix-ui/react-select": "^2.1.2",
"@radix-ui/react-separator": "^1.1.0",
"@radix-ui/react-slot": "^1.1.0",
"@radix-ui/react-tabs": "^1.1.2",
"@radix-ui/react-toast": "^1.2.2",
"@radix-ui/react-tooltip": "^1.1.4",
"@tanstack/react-query": "^5.62.3",
"@tanstack/react-table": "^8.20.5",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"date-fns": "^4.1.0",
"date-fns-tz": "^3.2.0",
"lucide-react": "^0.460.0",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-hook-form": "^7.54.0",
"react-router-dom": "^6.28.0",
"recharts": "^2.13.3",
"tailwind-merge": "^2.5.4",
"zod": "^3.23.8",
"zustand": "^4.5.5"
},
"devDependencies": {
"@eslint/js": "^9.13.0",
"@testing-library/jest-dom": "^6.6.3",
"@testing-library/react": "^16.0.1",
"@types/node": "^26.6.6",
"@types/react": "^18.3.12",
"@types/react-dom": "^18.3.1",
"@vitejs/plugin-react": "^4.3.3",
"autoprefixer": "^10.4.20",
"eslint": "^9.13.0",
"eslint-plugin-react-hooks": "^5.0.0",
"eslint-plugin-react-refresh": "^0.4.14",
"globals": "^15.11.0",
"jsdom": "^25.0.1",
"postcss": "^8.4.49",
"tailwindcss": "^3.4.15",
"typescript": "~5.6.2",
"typescript-eslint": "^8.11.0",
"vite": "^5.4.10",
"vitest": "^2.1.6"
}
}
+3
View File
@@ -0,0 +1,3 @@
export default {
plugins: { tailwindcss: {}, autoprefixer: {} },
};
Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="31.88" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 257"><defs><linearGradient id="IconifyId1813088fe1fbc01fb466" x1="-.828%" x2="57.636%" y1="7.652%" y2="78.411%"><stop offset="0%" stop-color="#41D1FF"></stop><stop offset="100%" stop-color="#BD34FE"></stop></linearGradient><linearGradient id="IconifyId1813088fe1fbc01fb467" x1="43.376%" x2="50.316%" y1="2.242%" y2="89.03%"><stop offset="0%" stop-color="#FFEA83"></stop><stop offset="8.333%" stop-color="#FFDD35"></stop><stop offset="100%" stop-color="#FFA800"></stop></linearGradient></defs><path fill="url(#IconifyId1813088fe1fbc01fb466)" d="M255.153 37.938L134.897 252.976c-2.483 4.44-8.862 4.466-11.382.048L.875 37.958c-2.746-4.814 1.371-10.646 6.827-9.67l120.385 21.517a6.537 6.537 0 0 0 2.322-.004l117.867-21.483c5.438-.991 9.574 4.796 6.877 9.62Z"></path><path fill="url(#IconifyId1813088fe1fbc01fb467)" d="M185.432.063L96.44 17.501a3.268 3.268 0 0 0-2.634 3.014l-5.474 92.456a3.268 3.268 0 0 0 3.997 3.378l24.777-5.718c2.318-.535 4.413 1.507 3.936 3.838l-7.361 36.047c-.495 2.426 1.782 4.5 4.151 3.78l15.304-4.649c2.372-.72 4.652 1.36 4.15 3.788l-11.698 56.621c-.732 3.542 3.979 5.473 5.943 2.437l1.313-2.028l72.516-144.72c1.215-2.423-.88-5.186-3.54-4.672l-25.505 4.922c-2.396.462-4.435-1.77-3.759-4.114l16.646-57.705c.677-2.35-1.37-4.583-3.769-4.113Z"></path></svg>

After

Width:  |  Height:  |  Size: 1.5 KiB

+42
View File
@@ -0,0 +1,42 @@
#root {
max-width: 1280px;
margin: 0 auto;
padding: 2rem;
text-align: center;
}
.logo {
height: 6em;
padding: 1.5em;
will-change: filter;
transition: filter 300ms;
}
.logo:hover {
filter: drop-shadow(0 0 2em #646cffaa);
}
.logo.react:hover {
filter: drop-shadow(0 0 2em #61dafbaa);
}
@keyframes logo-spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
@media (prefers-reduced-motion: no-preference) {
a:nth-of-type(2) .logo {
animation: logo-spin infinite 20s linear;
}
}
.card {
padding: 2em;
}
.read-the-docs {
color: #888;
}
+48
View File
@@ -0,0 +1,48 @@
import { BrowserRouter, Routes, Route } from "react-router-dom";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { AppShell } from "@/components/layout/AppShell";
import { DataTableDemoPage } from "@/pages/DataTableDemoPage";
import {
DashboardPage,
AssetsPage,
ComplaintsPage,
PMPage,
CalibrationPage,
ContractsPage,
InsurancePage,
DemoEquipmentPage,
VisitsPage,
ReportsPage,
NotificationsPage,
SettingsPage,
} from "@/pages/stubs";
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: 1, staleTime: 30_000 } },
});
export default function App() {
return (
<QueryClientProvider client={queryClient}>
<BrowserRouter>
<Routes>
<Route element={<AppShell />}>
<Route path="/" element={<DashboardPage />} />
<Route path="/assets" element={<AssetsPage />} />
<Route path="/complaints" element={<ComplaintsPage />} />
<Route path="/pm" element={<PMPage />} />
<Route path="/calibration" element={<CalibrationPage />} />
<Route path="/contracts" element={<ContractsPage />} />
<Route path="/insurance" element={<InsurancePage />} />
<Route path="/demo-equipment" element={<DemoEquipmentPage />} />
<Route path="/visits" element={<VisitsPage />} />
<Route path="/reports" element={<ReportsPage />} />
<Route path="/notifications" element={<NotificationsPage />} />
<Route path="/settings" element={<SettingsPage />} />
<Route path="/demo" element={<DataTableDemoPage />} />
</Route>
</Routes>
</BrowserRouter>
</QueryClientProvider>
);
}
+39
View File
@@ -0,0 +1,39 @@
const BASE_URL = "/api";
export class ApiError extends Error {
constructor(
public status: number,
public detail: string,
public code?: string
) {
super(detail);
}
}
async function request<T>(path: string, options: RequestInit = {}): Promise<T> {
const token = sessionStorage.getItem("access_token");
const headers: Record<string, string> = {
"Content-Type": "application/json",
...(options.headers as Record<string, string>),
};
if (token) headers["Authorization"] = `Bearer ${token}`;
const res = await fetch(`${BASE_URL}${path}`, { ...options, headers });
if (!res.ok) {
const body = await res.json().catch(() => ({ detail: res.statusText }));
throw new ApiError(res.status, body.detail ?? res.statusText, body.code);
}
if (res.status === 204) return undefined as T;
return res.json();
}
export const api = {
get: <T>(path: string) => request<T>(path),
post: <T>(path: string, data?: unknown) =>
request<T>(path, { method: "POST", body: data ? JSON.stringify(data) : undefined }),
patch: <T>(path: string, data: unknown) =>
request<T>(path, { method: "PATCH", body: JSON.stringify(data) }),
put: <T>(path: string, data: unknown) =>
request<T>(path, { method: "PUT", body: JSON.stringify(data) }),
delete: <T>(path: string) => request<T>(path, { method: "DELETE" }),
};
+4
View File
@@ -0,0 +1,4 @@
import { api } from "./client";
export const fetchHealth = () =>
api.get<{ status: string; service: string; version: string }>("/health");
+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="35.93" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 228"><path fill="#00D8FF" d="M210.483 73.824a171.49 171.49 0 0 0-8.24-2.597c.465-1.9.893-3.777 1.273-5.621c6.238-30.281 2.16-54.676-11.769-62.708c-13.355-7.7-35.196.329-57.254 19.526a171.23 171.23 0 0 0-6.375 5.848a155.866 155.866 0 0 0-4.241-3.917C100.759 3.829 77.587-4.822 63.673 3.233C50.33 10.957 46.379 33.89 51.995 62.588a170.974 170.974 0 0 0 1.892 8.48c-3.28.932-6.445 1.924-9.474 2.98C17.309 83.498 0 98.307 0 113.668c0 15.865 18.582 31.778 46.812 41.427a145.52 145.52 0 0 0 6.921 2.165a167.467 167.467 0 0 0-2.01 9.138c-5.354 28.2-1.173 50.591 12.134 58.266c13.744 7.926 36.812-.22 59.273-19.855a145.567 145.567 0 0 0 5.342-4.923a168.064 168.064 0 0 0 6.92 6.314c21.758 18.722 43.246 26.282 56.54 18.586c13.731-7.949 18.194-32.003 12.4-61.268a145.016 145.016 0 0 0-1.535-6.842c1.62-.48 3.21-.974 4.76-1.488c29.348-9.723 48.443-25.443 48.443-41.52c0-15.417-17.868-30.326-45.517-39.844Zm-6.365 70.984c-1.4.463-2.836.91-4.3 1.345c-3.24-10.257-7.612-21.163-12.963-32.432c5.106-11 9.31-21.767 12.459-31.957c2.619.758 5.16 1.557 7.61 2.4c23.69 8.156 38.14 20.213 38.14 29.504c0 9.896-15.606 22.743-40.946 31.14Zm-10.514 20.834c2.562 12.94 2.927 24.64 1.23 33.787c-1.524 8.219-4.59 13.698-8.382 15.893c-8.067 4.67-25.32-1.4-43.927-17.412a156.726 156.726 0 0 1-6.437-5.87c7.214-7.889 14.423-17.06 21.459-27.246c12.376-1.098 24.068-2.894 34.671-5.345a134.17 134.17 0 0 1 1.386 6.193ZM87.276 214.515c-7.882 2.783-14.16 2.863-17.955.675c-8.075-4.657-11.432-22.636-6.853-46.752a156.923 156.923 0 0 1 1.869-8.499c10.486 2.32 22.093 3.988 34.498 4.994c7.084 9.967 14.501 19.128 21.976 27.15a134.668 134.668 0 0 1-4.877 4.492c-9.933 8.682-19.886 14.842-28.658 17.94ZM50.35 144.747c-12.483-4.267-22.792-9.812-29.858-15.863c-6.35-5.437-9.555-10.836-9.555-15.216c0-9.322 13.897-21.212 37.076-29.293c2.813-.98 5.757-1.905 8.812-2.773c3.204 10.42 7.406 21.315 12.477 32.332c-5.137 11.18-9.399 22.249-12.634 32.792a134.718 134.718 0 0 1-6.318-1.979Zm12.378-84.26c-4.811-24.587-1.616-43.134 6.425-47.789c8.564-4.958 27.502 2.111 47.463 19.835a144.318 144.318 0 0 1 3.841 3.545c-7.438 7.987-14.787 17.08-21.808 26.988c-12.04 1.116-23.565 2.908-34.161 5.309a160.342 160.342 0 0 1-1.76-7.887Zm110.427 27.268a347.8 347.8 0 0 0-7.785-12.803c8.168 1.033 15.994 2.404 23.343 4.08c-2.206 7.072-4.956 14.465-8.193 22.045a381.151 381.151 0 0 0-7.365-13.322Zm-45.032-43.861c5.044 5.465 10.096 11.566 15.065 18.186a322.04 322.04 0 0 0-30.257-.006c4.974-6.559 10.069-12.652 15.192-18.18ZM82.802 87.83a323.167 323.167 0 0 0-7.227 13.238c-3.184-7.553-5.909-14.98-8.134-22.152c7.304-1.634 15.093-2.97 23.209-3.984a321.524 321.524 0 0 0-7.848 12.897Zm8.081 65.352c-8.385-.936-16.291-2.203-23.593-3.793c2.26-7.3 5.045-14.885 8.298-22.6a321.187 321.187 0 0 0 7.257 13.246c2.594 4.48 5.28 8.868 8.038 13.147Zm37.542 31.03c-5.184-5.592-10.354-11.779-15.403-18.433c4.902.192 9.899.29 14.978.29c5.218 0 10.376-.117 15.453-.343c-4.985 6.774-10.018 12.97-15.028 18.486Zm52.198-57.817c3.422 7.8 6.306 15.345 8.596 22.52c-7.422 1.694-15.436 3.058-23.88 4.071a382.417 382.417 0 0 0 7.859-13.026a347.403 347.403 0 0 0 7.425-13.565Zm-16.898 8.101a358.557 358.557 0 0 1-12.281 19.815a329.4 329.4 0 0 1-23.444.823c-7.967 0-15.716-.248-23.178-.732a310.202 310.202 0 0 1-12.513-19.846h.001a307.41 307.41 0 0 1-10.923-20.627a310.278 310.278 0 0 1 10.89-20.637l-.001.001a307.318 307.318 0 0 1 12.413-19.761c7.613-.576 15.42-.876 23.31-.876H128c7.926 0 15.743.303 23.354.883a329.357 329.357 0 0 1 12.335 19.695a358.489 358.489 0 0 1 11.036 20.54a329.472 329.472 0 0 1-11 20.722Zm22.56-122.124c8.572 4.944 11.906 24.881 6.52 51.026c-.344 1.668-.73 3.367-1.15 5.09c-10.622-2.452-22.155-4.275-34.23-5.408c-7.034-10.017-14.323-19.124-21.64-27.008a160.789 160.789 0 0 1 5.888-5.4c18.9-16.447 36.564-22.941 44.612-18.3ZM128 90.808c12.625 0 22.86 10.235 22.86 22.86s-10.235 22.86-22.86 22.86s-22.86-10.235-22.86-22.86s10.235-22.86 22.86-22.86Z"></path></svg>

After

Width:  |  Height:  |  Size: 4.0 KiB

@@ -0,0 +1,33 @@
import { describe, it, expect } from "vitest";
import { render, screen, fireEvent } from "@testing-library/react";
import { ColumnDef } from "@tanstack/react-table";
import { DataTable } from "./DataTable";
interface RowItem {
code: string;
name: string;
}
const columns: ColumnDef<RowItem, unknown>[] = [
{ accessorKey: "code", header: "Code", enableColumnFilter: true },
{ accessorKey: "name", header: "Name", enableColumnFilter: true },
];
const data: RowItem[] = [
{ code: "A-001", name: "Ventilator" },
{ code: "A-002", name: "Monitor" },
];
describe("DataTable", () => {
it("renders rows and filters globally", () => {
render(<DataTable data={data} columns={columns} globalFilterPlaceholder="Search..." />);
expect(screen.getByText("Ventilator")).toBeInTheDocument();
expect(screen.getByText("Monitor")).toBeInTheDocument();
const searchInput = screen.getByPlaceholderText("Search...");
fireEvent.change(searchInput, { target: { value: "Ventilator" } });
expect(screen.getByText("Ventilator")).toBeInTheDocument();
expect(screen.queryByText("Monitor")).not.toBeInTheDocument();
});
});
@@ -0,0 +1,266 @@
import {
useReactTable,
getCoreRowModel,
getFilteredRowModel,
getPaginationRowModel,
getSortedRowModel,
flexRender,
ColumnDef,
SortingState,
ColumnFiltersState,
VisibilityState,
PaginationState,
FilterFn,
} from "@tanstack/react-table";
import { useState, useMemo } from "react";
import { ChevronUp, ChevronDown, ChevronsUpDown, Download, Eye, Search } from "lucide-react";
import { cn } from "@/lib/utils";
import { Button } from "@/components/ui/button";
interface DataTableProps<TData> {
data: TData[];
columns: ColumnDef<TData, unknown>[];
loading?: boolean;
emptyMessage?: string;
emptyAction?: React.ReactNode;
globalFilterPlaceholder?: string;
onRowClick?: (row: TData) => void;
exportFilename?: string;
}
function exportToCsv<TData>(data: TData[], filename: string) {
if (!data.length) return;
const headers = Object.keys(data[0] as object);
const rows = data.map((row) =>
headers.map((h) => JSON.stringify((row as Record<string, unknown>)[h] ?? "")).join(",")
);
const csv = [headers.join(","), ...rows].join("\n");
const blob = new Blob([csv], { type: "text/csv" });
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = `${filename}.csv`;
a.click();
URL.revokeObjectURL(url);
}
export function DataTable<TData>({
data,
columns,
loading = false,
emptyMessage = "No records found.",
emptyAction,
globalFilterPlaceholder = "Search...",
onRowClick,
exportFilename = "export",
}: DataTableProps<TData>) {
const [sorting, setSorting] = useState<SortingState>([]);
const [columnFilters, setColumnFilters] = useState<ColumnFiltersState>([]);
const [columnVisibility, setColumnVisibility] = useState<VisibilityState>({});
const [globalFilter, setGlobalFilter] = useState("");
const [pagination, setPagination] = useState<PaginationState>({ pageIndex: 0, pageSize: 20 });
const [showColVis, setShowColVis] = useState(false);
const globalFilterFn: FilterFn<TData> = (row, _columnId, filterValue: string) => {
const search = String(filterValue ?? "").toLowerCase();
return Object.values(row.original as Record<string, unknown>).some((v) =>
String(v ?? "").toLowerCase().includes(search)
);
};
const table = useReactTable({
data,
columns,
state: { sorting, columnFilters, columnVisibility, globalFilter, pagination },
onSortingChange: setSorting,
onColumnFiltersChange: setColumnFilters,
onColumnVisibilityChange: setColumnVisibility,
onGlobalFilterChange: setGlobalFilter,
onPaginationChange: setPagination,
globalFilterFn,
getCoreRowModel: getCoreRowModel(),
getFilteredRowModel: getFilteredRowModel(),
getSortedRowModel: getSortedRowModel(),
getPaginationRowModel: getPaginationRowModel(),
});
const visibleRows = table.getRowModel().rows;
const filteredRows = table.getFilteredRowModel().rows;
const allFilteredData = useMemo(
() => filteredRows.map((r) => r.original),
[filteredRows]
);
return (
<div className="space-y-3">
{/* Toolbar */}
<div className="flex items-center gap-2 flex-wrap">
<div className="relative flex-1 min-w-48">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-gray-400" />
<input
value={globalFilter}
onChange={(e) => setGlobalFilter(e.target.value)}
placeholder={globalFilterPlaceholder}
className="w-full pl-9 pr-4 py-1.5 text-sm border border-gray-200 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
/>
</div>
<div className="relative">
<Button variant="outline" size="sm" onClick={() => setShowColVis(!showColVis)}>
<Eye className="h-4 w-4 mr-1" /> Columns
</Button>
{showColVis && (
<div className="absolute right-0 mt-1 w-48 bg-white border border-gray-200 rounded-md shadow-lg z-20 p-2">
{table.getAllLeafColumns().map((col) => (
<label key={col.id} className="flex items-center gap-2 px-2 py-1 hover:bg-gray-50 rounded cursor-pointer text-sm">
<input
type="checkbox"
checked={col.getIsVisible()}
onChange={col.getToggleVisibilityHandler()}
className="rounded"
/>
{String(col.columnDef.header ?? col.id)}
</label>
))}
</div>
)}
</div>
<Button variant="outline" size="sm" onClick={() => exportToCsv(allFilteredData, exportFilename)}>
<Download className="h-4 w-4 mr-1" /> CSV (current view)
</Button>
</div>
{/* Table */}
<div className="bg-white rounded-lg border border-gray-200 overflow-hidden">
<div className="overflow-x-auto">
<table className="w-full text-sm">
<thead className="bg-gray-50 border-b border-gray-200">
{table.getHeaderGroups().map((hg) => (
<tr key={hg.id}>
{hg.headers.map((header) => (
<th key={header.id} className="text-left font-medium text-gray-600 px-4 py-3">
{header.isPlaceholder ? null : (
<div className="space-y-1">
{/* Sortable header */}
<button
type="button"
className={cn(
"flex items-center gap-1 hover:text-gray-900 font-medium",
header.column.getCanSort() ? "cursor-pointer select-none" : "cursor-default"
)}
onClick={header.column.getToggleSortingHandler()}
>
{flexRender(header.column.columnDef.header, header.getContext())}
{header.column.getCanSort() && (
header.column.getIsSorted() === "asc" ? (
<ChevronUp className="h-3 w-3" />
) : header.column.getIsSorted() === "desc" ? (
<ChevronDown className="h-3 w-3" />
) : (
<ChevronsUpDown className="h-3 w-3 opacity-30" />
)
)}
</button>
{/* Per-column filter */}
{header.column.getCanFilter() && (
<input
value={(header.column.getFilterValue() as string) ?? ""}
onChange={(e) => header.column.setFilterValue(e.target.value)}
placeholder="Filter..."
className="w-full px-2 py-0.5 text-xs border border-gray-200 rounded focus:outline-none focus:ring-1 focus:ring-blue-400"
onClick={(e) => e.stopPropagation()}
/>
)}
</div>
)}
</th>
))}
</tr>
))}
</thead>
<tbody className="divide-y divide-gray-100">
{loading ? (
[...Array(5)].map((_, i) => (
<tr key={i}>
{columns.map((_, j) => (
<td key={j} className="px-4 py-3">
<div className="h-4 bg-gray-100 rounded animate-pulse" />
</td>
))}
</tr>
))
) : visibleRows.length === 0 ? (
<tr>
<td colSpan={columns.length} className="px-4 py-12 text-center">
<div className="text-gray-400 space-y-2">
<p>{emptyMessage}</p>
{emptyAction}
</div>
</td>
</tr>
) : (
visibleRows.map((row) => (
<tr
key={row.id}
className={cn(
"hover:bg-blue-50/50 transition-colors",
onRowClick && "cursor-pointer"
)}
onClick={() => onRowClick?.(row.original)}
>
{row.getVisibleCells().map((cell) => (
<td key={cell.id} className="px-4 py-3 text-gray-700">
{flexRender(cell.column.columnDef.cell, cell.getContext())}
</td>
))}
</tr>
))
)}
</tbody>
</table>
</div>
{/* Pagination */}
{!loading && visibleRows.length > 0 && (
<div className="flex items-center justify-between px-4 py-3 border-t border-gray-200 bg-gray-50 text-sm text-gray-600">
<span>
{filteredRows.length} record{filteredRows.length !== 1 ? "s" : ""}
{globalFilter || columnFilters.length ? " (filtered)" : ""}
</span>
<div className="flex items-center gap-2">
<select
value={pagination.pageSize}
onChange={(e) => table.setPageSize(Number(e.target.value))}
className="border border-gray-200 rounded px-2 py-1 text-xs"
>
{[10, 20, 50, 100].map((s) => (
<option key={s} value={s}>
{s} / page
</option>
))}
</select>
<button
type="button"
onClick={() => table.previousPage()}
disabled={!table.getCanPreviousPage()}
className="px-2 py-1 rounded border border-gray-200 disabled:opacity-40 hover:bg-white"
>
←
</button>
<span className="text-xs">
Page {pagination.pageIndex + 1} / {table.getPageCount()}
</span>
<button
type="button"
onClick={() => table.nextPage()}
disabled={!table.getCanNextPage()}
className="px-2 py-1 rounded border border-gray-200 disabled:opacity-40 hover:bg-white"
>
→
</button>
</div>
</div>
)}
</div>
</div>
);
}
@@ -0,0 +1 @@
export { DataTable } from "./DataTable";
@@ -0,0 +1,17 @@
import { Outlet } from "react-router-dom";
import { Sidebar } from "./Sidebar";
import { TopBar } from "./TopBar";
export function AppShell() {
return (
<div className="flex min-h-screen bg-gray-50">
<Sidebar />
<div className="flex-1 flex flex-col min-w-0">
<TopBar />
<main className="flex-1 p-6 overflow-auto">
<Outlet />
</main>
</div>
</div>
);
}
@@ -0,0 +1,80 @@
import { NavLink } from "react-router-dom";
import {
LayoutDashboard,
Package,
AlertCircle,
Wrench,
FlaskConical,
FileText,
Shield,
Truck,
Building2,
BarChart3,
Bell,
Settings,
ChevronRight,
} from "lucide-react";
import { cn } from "@/lib/utils";
const NAV_ITEMS = [
{ to: "/", label: "Dashboard", icon: LayoutDashboard, phase: 6 },
{ to: "/assets", label: "Assets", icon: Package, phase: 2 },
{ to: "/complaints", label: "Complaints", icon: AlertCircle, phase: 3 },
{ to: "/pm", label: "Preventive Maintenance", icon: Wrench, phase: 4 },
{ to: "/calibration", label: "Calibration", icon: FlaskConical, phase: 4 },
{ to: "/contracts", label: "Contracts & Warranty", icon: FileText, phase: 5 },
{ to: "/insurance", label: "Insurance", icon: Shield, phase: 5 },
{ to: "/demo-equipment", label: "Demo Equipment", icon: Truck, phase: 5 },
{ to: "/visits", label: "Department Visits", icon: Building2, phase: 5 },
{ to: "/reports", label: "Reports", icon: BarChart3, phase: 7 },
{ to: "/notifications", label: "Notifications", icon: Bell, phase: 6 },
{ to: "/settings", label: "Settings", icon: Settings, phase: 1, adminOnly: true },
];
export function Sidebar() {
return (
<aside className="w-56 lg:w-64 shrink-0 min-h-screen bg-[#1e3a8a] text-white flex flex-col">
{/* Logo */}
<div className="px-4 py-4 border-b border-blue-700 space-y-2">
<div className="bg-white rounded-lg p-2">
<img
src="/logo.jpg"
alt="Poona Hospital and Research Centre"
className="w-full h-16 object-contain"
/>
</div>
<div className="text-xs text-blue-200 text-center">
Asset Management &amp; Maintenance
</div>
</div>
{/* Navigation */}
<nav className="flex-1 px-2 py-4 space-y-0.5 overflow-y-auto">
{NAV_ITEMS.map(({ to, label, icon: Icon }) => (
<NavLink
key={to}
to={to}
end={to === "/"}
className={({ isActive }) =>
cn(
"flex items-center gap-3 px-3 py-2.5 rounded-md text-sm transition-colors group",
isActive
? "bg-blue-700 text-white"
: "text-blue-100 hover:bg-blue-700/50 hover:text-white"
)
}
>
<Icon className="h-4 w-4 shrink-0" />
<span className="flex-1 truncate">{label}</span>
<ChevronRight className="h-3 w-3 opacity-0 group-hover:opacity-50" />
</NavLink>
))}
</nav>
{/* Footer */}
<div className="px-4 py-3 border-t border-blue-700 text-xs text-blue-300">
Phase 0 — Scaffold
</div>
</aside>
);
}
+40
View File
@@ -0,0 +1,40 @@
import { Search, Bell, ChevronDown, User } from "lucide-react";
import { cn } from "@/lib/utils";
interface TopBarProps {
title?: string;
}
export function TopBar({ title }: TopBarProps) {
return (
<header className="h-14 bg-white border-b border-gray-200 flex items-center px-4 gap-4 sticky top-0 z-10">
{/* Page title */}
{title && <h1 className="font-semibold text-gray-800 text-sm truncate mr-auto">{title}</h1>}
{/* Global search placeholder */}
<div className={cn("relative ml-auto", title ? "" : "flex-1 max-w-md")}>
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-gray-400" />
<input
type="text"
placeholder="Search assets, complaints... (Phase 8)"
className="w-full pl-9 pr-4 py-1.5 text-sm border border-gray-200 rounded-md bg-gray-50 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:bg-white"
/>
</div>
{/* Notification bell placeholder */}
<button className="relative p-2 rounded-md hover:bg-gray-100 text-gray-500">
<Bell className="h-5 w-5" />
<span className="absolute top-1 right-1 h-2 w-2 rounded-full bg-red-500" />
</button>
{/* User menu placeholder */}
<button className="flex items-center gap-2 px-3 py-1.5 rounded-md hover:bg-gray-100 text-sm text-gray-700">
<div className="h-7 w-7 rounded-full bg-[#1e3a8a] flex items-center justify-center text-white text-xs font-bold">
<User className="h-4 w-4" />
</div>
<span className="hidden sm:block">Admin</span>
<ChevronDown className="h-4 w-4 text-gray-400" />
</button>
</header>
);
}
+30
View File
@@ -0,0 +1,30 @@
import { cn } from "@/lib/utils";
interface BadgeProps {
variant?: "default" | "success" | "warning" | "danger" | "info" | "outline";
className?: string;
children: React.ReactNode;
}
const variantClasses = {
default: "bg-gray-100 text-gray-800",
success: "bg-green-100 text-green-800",
warning: "bg-yellow-100 text-yellow-800",
danger: "bg-red-100 text-red-800",
info: "bg-blue-100 text-blue-800",
outline: "border border-gray-300 text-gray-700 bg-white",
};
export function Badge({ variant = "default", className, children }: BadgeProps) {
return (
<span
className={cn(
"inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium",
variantClasses[variant],
className
)}
>
{children}
</span>
);
}
+49
View File
@@ -0,0 +1,49 @@
import { cn } from "@/lib/utils";
import { ButtonHTMLAttributes, forwardRef } from "react";
export interface ButtonProps extends ButtonHTMLAttributes<HTMLButtonElement> {
variant?: "default" | "outline" | "ghost" | "danger" | "success";
size?: "sm" | "md" | "lg";
loading?: boolean;
}
const variantClasses = {
default: "bg-[#1e3a8a] text-white hover:bg-[#1e3480] focus:ring-blue-500",
outline: "border border-gray-300 bg-white text-gray-700 hover:bg-gray-50 focus:ring-blue-500",
ghost: "text-gray-600 hover:bg-gray-100 focus:ring-gray-400",
danger: "bg-red-600 text-white hover:bg-red-700 focus:ring-red-500",
success: "bg-green-600 text-white hover:bg-green-700 focus:ring-green-500",
};
const sizeClasses = {
sm: "px-3 py-1.5 text-sm",
md: "px-4 py-2 text-sm",
lg: "px-6 py-3 text-base",
};
export const Button = forwardRef<HTMLButtonElement, ButtonProps>(
({ variant = "default", size = "md", loading, className, children, disabled, ...props }, ref) => (
<button
ref={ref}
disabled={disabled || loading}
className={cn(
"inline-flex items-center justify-center rounded-md font-medium transition-colors",
"focus:outline-none focus:ring-2 focus:ring-offset-1",
"disabled:opacity-50 disabled:cursor-not-allowed",
variantClasses[variant],
sizeClasses[size],
className
)}
{...props}
>
{loading && (
<svg className="animate-spin -ml-1 mr-2 h-4 w-4" fill="none" viewBox="0 0 24 24">
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
</svg>
)}
{children}
</button>
)
);
Button.displayName = "Button";
+21
View File
@@ -0,0 +1,21 @@
import { create } from "zustand";
interface AuthState {
user: { id: number; email: string; name: string; role: string } | null;
token: string | null;
setAuth: (user: AuthState["user"], token: string) => void;
logout: () => void;
}
export const useAuthStore = create<AuthState>((set) => ({
user: null,
token: sessionStorage.getItem("access_token"),
setAuth: (user, token) => {
sessionStorage.setItem("access_token", token);
set({ user, token });
},
logout: () => {
sessionStorage.removeItem("access_token");
set({ user: null, token: null });
},
}));
+12
View File
@@ -0,0 +1,12 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
@layer base {
:root {
--brand: #1e3a8a;
}
body {
@apply bg-gray-50 text-gray-900 antialiased;
}
}
+55
View File
@@ -0,0 +1,55 @@
import { format, formatDistanceToNow } from "date-fns";
import { toZonedTime } from "date-fns-tz";
// Kolkata offset: +05:30
const KOLKATA_TZ = "Asia/Kolkata";
export function formatDateTime(isoString: string | null | undefined): string {
if (!isoString) return "—";
try {
const d = toZonedTime(new Date(isoString), KOLKATA_TZ);
return format(d, "dd-MMM-yyyy HH:mm");
} catch {
return "—";
}
}
export function formatDate(isoString: string | null | undefined): string {
if (!isoString) return "—";
try {
const d = toZonedTime(new Date(isoString), KOLKATA_TZ);
return format(d, "dd-MMM-yyyy");
} catch {
return "—";
}
}
export function formatDuration(minutes: number | null | undefined): string {
if (minutes == null) return "—";
const d = Math.floor(minutes / 1440);
const h = Math.floor((minutes % 1440) / 60);
const m = minutes % 60;
const parts: string[] = [];
if (d) parts.push(`${d}d`);
if (h) parts.push(`${h}h`);
if (m || !parts.length) parts.push(`${m}m`);
return parts.join(" ");
}
export function formatINR(amount: number | null | undefined): string {
if (amount == null) return "—";
return new Intl.NumberFormat("en-IN", {
style: "currency",
currency: "INR",
maximumFractionDigits: 0,
}).format(amount);
}
export function formatRelative(isoString: string | null | undefined): string {
if (!isoString) return "—";
try {
return formatDistanceToNow(new Date(isoString), { addSuffix: true });
} catch {
return "—";
}
}
+16
View File
@@ -0,0 +1,16 @@
export type Role = "system_admin" | "biomedical" | "department_user" | "management" | "coordinator";
export const ROLE_LABELS: Record<Role, string> = {
system_admin: "System Administrator",
biomedical: "Biomedical / Maintenance",
department_user: "Department User",
management: "Management",
coordinator: "Coordinator",
};
// Full permission matrix will be added in Phase 1
export function can(role: Role | undefined, _capability: string): boolean {
if (!role) return false;
if (role === "system_admin") return true;
return false; // placeholder
}
+6
View File
@@ -0,0 +1,6 @@
import { type ClassValue, clsx } from "clsx";
import { twMerge } from "tailwind-merge";
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs));
}
+10
View File
@@ -0,0 +1,10 @@
import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App";
import "./index.css";
ReactDOM.createRoot(document.getElementById("root")!).render(
<React.StrictMode>
<App />
</React.StrictMode>
);
+66
View File
@@ -0,0 +1,66 @@
import { DataTable } from "@/components/DataTable";
import { ColumnDef } from "@tanstack/react-table";
import { Badge } from "@/components/ui/badge";
interface MockAsset {
code: string;
name: string;
department: string;
status: string;
category: string;
}
const MOCK_DATA: MockAsset[] = [
{ code: "PHRC-ICU-0001", name: "Ventilator", department: "ICU", status: "In Service", category: "Life Support" },
{ code: "PHRC-ICU-0002", name: "Patient Monitor", department: "ICU", status: "Under Repair", category: "Monitoring" },
{ code: "PHRC-OT-0001", name: "Anaesthesia Machine", department: "Operation Theatre", status: "In Service", category: "Life Support" },
{ code: "PHRC-RAD-0001", name: "CT Scanner", department: "Radiology", status: "In Service", category: "Imaging" },
{ code: "PHRC-RAD-0002", name: "X-Ray Unit", department: "Radiology", status: "Out of Service", category: "Imaging" },
{ code: "PHRC-EM-0001", name: "Defibrillator", department: "Emergency", status: "In Service", category: "Life Support" },
{ code: "PHRC-PATH-0001", name: "Centrifuge", department: "Pathology", status: "In Service", category: "Laboratory" },
{ code: "PHRC-DIAL-0001", name: "Dialysis Machine", department: "Dialysis", status: "In Service", category: "Dialysis" },
];
const STATUS_VARIANTS: Record<string, "success" | "danger" | "warning" | "outline"> = {
"In Service": "success",
"Under Repair": "danger",
"Out of Service": "warning",
Condemned: "outline",
};
const columns: ColumnDef<MockAsset, unknown>[] = [
{ accessorKey: "code", header: "Asset Code", enableColumnFilter: true },
{ accessorKey: "name", header: "Equipment Name", enableColumnFilter: true },
{ accessorKey: "category", header: "Category", enableColumnFilter: true },
{ accessorKey: "department", header: "Department", enableColumnFilter: true },
{
accessorKey: "status",
header: "Status",
enableColumnFilter: true,
cell: ({ getValue }) => {
const v = getValue() as string;
return <Badge variant={STATUS_VARIANTS[v] ?? "default"}>{v}</Badge>;
},
},
];
export function DataTableDemoPage() {
return (
<div className="space-y-4">
<div>
<h1 className="text-2xl font-bold text-gray-900">Phase 0 — DataTable Demo</h1>
<p className="text-gray-500 mt-1 text-sm">
Mock asset data demonstrating column filters, sort, pagination, column visibility, and CSV export.
Every list in the app will use this component.
</p>
</div>
<DataTable
data={MOCK_DATA}
columns={columns}
globalFilterPlaceholder="Search assets..."
exportFilename="assets-demo"
emptyMessage="No assets found."
/>
</div>
);
}
+75
View File
@@ -0,0 +1,75 @@
// Stub pages — replaced phase by phase
import { Link } from "react-router-dom";
interface StubProps {
title: string;
phase: number;
description?: string;
children?: React.ReactNode;
}
function StubPage({ title, phase, description, children }: StubProps) {
return (
<div className="max-w-lg mx-auto mt-16 text-center">
<div className="inline-flex items-center justify-center w-16 h-16 rounded-full bg-blue-50 mb-4">
<span className="text-2xl">🏗️</span>
</div>
<h2 className="text-xl font-semibold text-gray-800 mb-2">{title}</h2>
{description && <p className="text-gray-500 text-sm mb-4">{description}</p>}
<div className="inline-flex items-center gap-2 bg-amber-50 border border-amber-200 text-amber-700 px-4 py-2 rounded-full text-sm font-medium">
Coming in Phase {phase}
</div>
{children}
</div>
);
}
export const DashboardPage = () => (
<StubPage title="Dashboard" phase={6} description="KPI cards, charts, and needs-attention panel.">
<div className="mt-6">
<Link
to="/demo"
className="inline-flex items-center gap-1 text-sm font-medium text-[#1e3a8a] hover:underline"
>
Open Phase 0 DataTable Demo →
</Link>
</div>
</StubPage>
);
export const AssetsPage = () => (
<StubPage title="Asset Register" phase={2} description="60+ assets with column filters and detail tabs." />
);
export const ComplaintsPage = () => (
<StubPage
title="Breakdown & Complaint Register"
phase={3}
description="Full complaint lifecycle with response time and downtime tracking."
/>
);
export const PMPage = () => (
<StubPage title="Preventive Maintenance" phase={4} description="PM schedules and calendar view." />
);
export const CalibrationPage = () => (
<StubPage title="Calibration" phase={4} description="Calibration plans and records with due-date alerts." />
);
export const ContractsPage = () => (
<StubPage title="Contracts & Warranty" phase={5} description="AMC/CMC contracts and warranty tracking." />
);
export const InsurancePage = () => (
<StubPage title="Insurance" phase={5} description="Insurance policies with expiry alerts." />
);
export const DemoEquipmentPage = () => (
<StubPage title="Demo Equipment Register" phase={5} description="Demo equipment tracking with overdue returns." />
);
export const VisitsPage = () => (
<StubPage title="Department Visits" phase={5} description="Daily department visit reports." />
);
export const ReportsPage = () => (
<StubPage title="Reports & Exports" phase={7} description="8 reports with Excel export." />
);
export const NotificationsPage = () => (
<StubPage title="Notifications" phase={6} description="In-app alerts and notification centre." />
);
export const SettingsPage = () => (
<StubPage title="Settings" phase={1} description="Configurable lead days, downtime rules, and system settings." />
);
+1
View File
@@ -0,0 +1 @@
import "@testing-library/jest-dom";
+57
View File
@@ -0,0 +1,57 @@
import { describe, it, expect } from "vitest";
import { render, screen } from "@testing-library/react";
import { MemoryRouter } from "react-router-dom";
import { Sidebar } from "@/components/layout/Sidebar";
import { DashboardPage } from "@/pages/stubs";
import { DataTableDemoPage } from "@/pages/DataTableDemoPage";
describe("Phase 0 Frontend Smoke Tests", () => {
it("renders Sidebar with Poona Hospital logo, subtitle, and all 12 navigation links", () => {
render(
<MemoryRouter>
<Sidebar />
</MemoryRouter>
);
const logo = screen.getByAltText("Poona Hospital and Research Centre") as HTMLImageElement;
expect(logo).toBeInTheDocument();
expect(logo.getAttribute("src")).toBe("/logo.jpg");
expect(screen.getByText("Asset Management & Maintenance")).toBeInTheDocument();
const labels = [
"Dashboard",
"Assets",
"Complaints",
"Preventive Maintenance",
"Calibration",
"Contracts & Warranty",
"Insurance",
"Demo Equipment",
"Department Visits",
"Reports",
"Notifications",
"Settings",
];
for (const label of labels) {
expect(screen.getByText(label)).toBeInTheDocument();
}
});
it("renders DashboardPage with clickable link to /demo", () => {
render(
<MemoryRouter>
<DashboardPage />
</MemoryRouter>
);
const link = screen.getByRole("link", { name: /Open Phase 0 DataTable Demo/i });
expect(link).toBeInTheDocument();
expect(link).toHaveAttribute("href", "/demo");
});
it("renders DataTableDemoPage with mock rows", () => {
render(<DataTableDemoPage />);
expect(screen.getByText("Phase 0 — DataTable Demo")).toBeInTheDocument();
expect(screen.getByText("PHRC-ICU-0001")).toBeInTheDocument();
expect(screen.getByText("CT Scanner")).toBeInTheDocument();
});
});
+1
View File
@@ -0,0 +1 @@
/// <reference types="vite/client" />
+32
View File
@@ -0,0 +1,32 @@
/** @type {import('tailwindcss').Config} */
export default {
darkMode: ["class"],
content: ["./index.html", "./src/**/*.{ts,tsx}"],
theme: {
extend: {
colors: {
// Brand colours — Poona Hospital deep blue
brand: {
50: "#eef2ff",
100: "#e0e7ff",
500: "#1e3a8a",
600: "#1e3a8a",
700: "#1e3480",
900: "#1a2f6b",
},
// Status colours
status: {
open: "#ef4444", // red
"in-progress": "#f59e0b", // amber
closed: "#22c55e", // green
ok: "#6b7280", // grey
info: "#3b82f6", // blue
yellow: "#eab308",
red: "#ef4444",
green: "#22c55e",
},
},
},
},
plugins: [],
};
+26
View File
@@ -0,0 +1,26 @@
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
"target": "ES2020",
"useDefineForClassFields": true,
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"module": "ESNext",
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "Bundler",
"allowImportingTsExtensions": true,
"isolatedModules": true,
"moduleDetection": "force",
"noEmit": true,
"jsx": "react-jsx",
/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedSideEffectImports": true
},
"include": ["src"]
}
+19
View File
@@ -0,0 +1,19 @@
{
"compilerOptions": {
"target": "ES2020",
"useDefineForClassFields": true,
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"module": "ESNext",
"skipLibCheck": true,
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx",
"strict": true,
"baseUrl": ".",
"paths": { "@/*": ["./src/*"] }
},
"include": ["src"]
}
+24
View File
@@ -0,0 +1,24 @@
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
"target": "ES2022",
"lib": ["ES2023"],
"module": "ESNext",
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "Bundler",
"allowImportingTsExtensions": true,
"isolatedModules": true,
"moduleDetection": "force",
"noEmit": true,
/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedSideEffectImports": true
},
"include": ["vite.config.ts"]
}
+1
View File
@@ -0,0 +1 @@
{"root":["./src/app.tsx","./src/main.tsx","./src/vite-env.d.ts","./src/api/client.ts","./src/api/health.ts","./src/components/datatable/datatable.test.tsx","./src/components/datatable/datatable.tsx","./src/components/datatable/index.ts","./src/components/layout/appshell.tsx","./src/components/layout/sidebar.tsx","./src/components/layout/topbar.tsx","./src/components/ui/badge.tsx","./src/components/ui/button.tsx","./src/hooks/useauth.ts","./src/lib/format.ts","./src/lib/permissions.ts","./src/lib/utils.ts","./src/pages/datatabledemopage.tsx","./src/pages/stubs.tsx","./src/test/setup.ts","./src/test/smoke.test.tsx"],"version":"5.6.3"}
+22
View File
@@ -0,0 +1,22 @@
/// <reference types="vitest" />
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import path from "path";
export default defineConfig({
plugins: [react()],
resolve: {
alias: { "@": path.resolve(__dirname, "./src") },
},
server: {
port: 5173,
proxy: {
"/api": { target: "http://localhost:8000", changeOrigin: true },
},
},
test: {
globals: true,
environment: "jsdom",
setupFiles: ["./src/test/setup.ts"],
},
});