Compare commits

15 Commits

Author SHA1 Message Date
0fba859adf feat(ui): "Foundry Deck" visual redesign + full README
Complete visual redesign via a single centralized design system in
src/index.css (no JSX/logic changes; all existing class selectors kept
1:1, so all ~20 pages restyle at once): blackened-steel dark palette,
molten-ember accent with heat glow, blueprint-grid + grain background,
Saira Condensed / Hanken Grotesk / JetBrains Mono web fonts, staggered
load animations, reduced-motion fallback. README written from stub.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-16 17:50:26 +01:00
6432255203 quick fix 2026-04-15 07:14:36 +01:00
0b55bc873e fix: use npx tsc in build script to ensure tsc is resolved from node_modules 2026-04-15 05:07:45 +00:00
95972b329e fix(api): handle null return type for localStorage getItem 2026-04-15 05:04:11 +00:00
1a20a1050b fix: remove redundant VITE_API_BASE fallback, use wizard config as sole source of truth for HF_BACKEND_BASE_URL 2026-04-15 05:00:56 +00:00
h z
f61c506fdb Merge pull request 'HarborForge.Frontend: proposal/essential tests on current branch head' (#11) from pr/dev-2026-03-29-frontend-tests-20260405 into main
Reviewed-on: #11
2026-04-05 22:07:46 +00:00
zhi
38ebd2bbd1 TEST-FE-PR-001: adapt proposal/essential tests for current UI 2026-04-05 20:48:47 +00:00
zhi
83c9cd8fb7 TEST-FE-PR-001: Add Proposal/Essential frontend unit tests
- Essential list rendering and display tests
- Essential create/edit/delete form tests
- Accept modal with milestone selection tests
- Story creation restriction UI tests
- Error handling tests
2026-04-05 20:48:47 +00:00
8014dcd602 feat: add calendar plan create and edit ui 2026-04-04 15:30:03 +00:00
f39e7da33c fix: render calendar overlap conflicts safely 2026-04-04 14:50:42 +00:00
ea841d0d39 fix: use current calendar slot endpoints 2026-04-04 12:09:43 +00:00
a431711ff0 fix: handle wrapped calendar api responses 2026-04-04 10:44:51 +00:00
8208b3b27b feat: switch frontend indexing to code-first identifiers 2026-04-03 16:25:11 +00:00
zhi
e4804128f6 TEST-FE-CAL-001 add calendar frontend tests 2026-04-01 11:05:58 +00:00
zhi
978d69eea3 FE-CAL-004/005: Add slot create/edit/cancel modals and status warnings
- Create slot modal with type, time, duration, priority, event type/data fields
- Edit slot modal (pre-populates from existing slot)
- Cancel slot with confirmation dialog
- Cancel plan with confirmation dialog
- Overlap error display in modal
- Workload warnings banner after save
- Deferred slots notice banner
- Edit/Cancel buttons on modifiable slots (not_started/deferred, non-past dates)
- Past date detection prevents new slot creation
2026-04-01 06:50:03 +00:00
29 changed files with 5042 additions and 473 deletions

1
.env
View File

@@ -1,2 +1 @@
VITE_API_BASE=http://backend:8000
VITE_WIZARD_PORT=8080

180
README.md
View File

@@ -1,3 +1,181 @@
# HarborForge.Frontend
HarborForge Frontend - React + TypeScript
Single-page web client for HarborForge — the agent/human collaborative
task-management platform. It provides the operator UI for projects,
milestones, tasks, proposals, calendar/meetings, users, roles and the
live monitor, and walks operators through first-time provisioning via the
SSH-tunnel Setup Wizard.
Part of the [HarborForge](../README.md) platform.
## Tech Stack
- **React 18** (`react`, `react-dom`)
- **TypeScript 5**
- **Vite 5** dev server / bundler (`@vitejs/plugin-react`)
- **react-router-dom 6** for client-side routing
- **axios** for HTTP, with a shared request/response interceptor layer
- **dayjs** for date handling
- **Vitest 4** + Testing Library (`@testing-library/react`, `jsdom`) for unit tests
Path alias `@``src/` (configured in `vite.config.ts` and `tsconfig.json`).
## Pages
Routes are declared in `src/App.tsx`. The app gates rendering on three
states — `checking` (probing configuration), `setup` (Setup Wizard), and
`ready` (authenticated app). `/monitor`, `/login`, `/roles` and `/users`
are reachable without an authenticated session; everything else requires login.
| Route | Page | Purpose |
|---|---|---|
| `/` | `DashboardPage` | Landing dashboard |
| `/tasks` | `TasksPage` | Task list / filtering |
| `/tasks/:taskCode` | `TaskDetailPage` | Task detail, transitions, comments |
| `/projects` | `ProjectsPage` | Project list |
| `/projects/:id` | `ProjectDetailPage` | Project detail / editor |
| `/milestones` | `MilestonesPage` | Milestone list |
| `/milestones/:milestoneCode` | `MilestoneDetailPage` | Milestone detail / actions |
| `/proposals` (`/proposes`) | `ProposalsPage` | Proposal list |
| `/proposals/:proposalCode` (`/proposes/:proposalCode`) | `ProposalDetailPage` | Proposal detail, accept/reject/reopen |
| `/calendar` | `CalendarPage` | Calendar view |
| `/meetings/:meetingCode` | `MeetingDetailPage` | Meeting detail |
| `/supports/:supportCode` | `SupportDetailPage` | Support request detail |
| `/notifications` | `NotificationsPage` | Notification inbox |
| `/roles` | `RoleEditorPage` | Role / permission (RBAC) editor |
| `/users` | `UsersPage` | User management |
| `/monitor` | `MonitorPage` | Live system monitor (public) |
| `/login` | `LoginPage` | Authentication |
| _(state-gated)_ | `SetupWizardPage` | First-run provisioning wizard |
Shared building blocks live in `src/components/` (`Sidebar`,
`CreateTaskModal`, `MilestoneFormModal`, `ProjectFormModal`,
`CopyableCode`); the auth hook is `src/hooks/useAuth.ts`; shared types are
in `src/types/index.ts`.
## How It Talks to the Backend
All API access goes through the shared axios instance in
`src/services/api.ts`:
- The base URL is **resolved at runtime** from
`localStorage['HF_BACKEND_BASE_URL']` (re-read on every request via an
axios request interceptor), not baked in at build time.
- A bearer token from `localStorage['token']` is attached automatically
when present.
- A response interceptor clears the token and redirects to `/login` on
HTTP `401`, except on the public paths `/monitor` and `/login`.
Authentication (`src/hooks/useAuth.ts`) posts form-encoded credentials to
`/auth/token`, stores the returned `access_token`, and loads the current
user from `/auth/me`.
In local dev, `vite.config.ts` also proxies `/api/*` to
`http://backend:8000` (stripping the `/api` prefix) for same-origin
development against a Compose backend.
## Setup Wizard / SSH-Tunnel Flow
On startup `App.tsx` runs `checkInitialized()`:
1. It calls the backend `GET /config/status`. If that returns
`initialized: true`, the app is `ready` (and `backend_url`, if present,
is cached into `localStorage['HF_BACKEND_BASE_URL']`).
2. Otherwise, if a wizard port was previously saved
(`localStorage['HF_WIZARD_PORT']`), it tries
`http://127.0.0.1:<port>/api/v1/config/harborforge.json` directly.
3. If neither indicates an initialized install, it renders
`SetupWizardPage`.
The Setup Wizard (`src/pages/SetupWizardPage.tsx`) is a 4-step flow —
**Wizard → Admin → Backend → Finish**:
- **Wizard**: the operator enters the local port that an SSH tunnel
forwards to **AbstractWizard**
(`ssh -L <port>:127.0.0.1:<port> user@server`). The UI health-checks
`http://127.0.0.1:<port>/health` and stores the port.
- **Admin**: collects the first admin account (username, password, email,
full name).
- **Backend**: optional backend base URL override.
- **Finish**: writes the assembled config to AbstractWizard via
`PUT http://127.0.0.1:<port>/api/v1/config/harborforge.json`, caches the
backend URL locally, and instructs the operator to
`docker compose restart` on the server before refreshing.
## Local Development
```bash
npm install
npm run dev # Vite dev server on http://0.0.0.0:3000
```
The dev server proxies `/api` to `http://backend:8000` and allows the
hosts `frontend`, `127.0.0.1`, `localhost`.
### Build
```bash
npm run build # tsc type-check, then vite build → dist/
npm run preview # serve the production build locally
```
### Test
```bash
npm test # vitest run (jsdom)
npm run test:watch # watch mode
npm run test:ui # Vitest UI
```
Tests live in `src/test/**/*.test.{ts,tsx}` (e.g. `calendar.test.tsx`,
`proposal-essential.test.tsx`) with global setup in `src/test/setup.ts`.
### Docker
```bash
docker build -t harborforge-frontend .
docker run -p 3000:3000 harborforge-frontend
```
The multi-stage `Dockerfile` builds with Node 20 and serves `dist/` via
`serve` on port 3000. Set `FRONTEND_DEV_MODE=1` to run the Vite dev server
inside the container instead of serving the static build.
## Environment / Configuration
- **`VITE_API_BASE`** (`.env`, default `http://backend:8000`) — a build
hint for the default backend location.
- The effective backend base URL is determined at **runtime** from
`localStorage['HF_BACKEND_BASE_URL']`, which is populated by the Setup
Wizard or by the backend's `/config/status` response — so changing the
backend target does not require a rebuild.
- `localStorage['HF_WIZARD_PORT']` — last AbstractWizard tunnel port.
- `localStorage['token']` — current JWT bearer token.
## Theming
The entire visual design is a single self-contained design system in
**`src/index.css`** — there is no CSS-in-JS, no Tailwind, and no
per-component stylesheets. Components only reference global CSS classes;
all colors, typography, spacing and effects are driven by CSS custom
properties on `:root`. To re-theme the app, edit this one file.
The theme is **"Foundry Deck"** — a shipwright's drafting table meets a
foundry control panel:
- **Blackened-steel dark palette** — cool-tinted near-black surfaces
(`--bg`, `--bg-card`, `--bg-hover`, `--bg-sink`) with machined,
tight-radius borders.
- **Molten-ember accent** — a single hot orange accent
(`--accent`, `--accent-hover`, `--ember` gradient, ember glow) used
sparingly as the signature element.
- **Oxidized-steel secondary** plus a forge-mapped status palette
(patina success, heat-amber warning, rust danger, arc violet).
- **Blueprint-grid background** — layered radial ember/steel vignettes, a
fine 40px draughting grid, and a subtle SVG film-grain overlay.
- **Technical web fonts** loaded via a Google Fonts `@import` at the top
of `src/index.css`: **Saira Condensed** (headings), **Hanken Grotesk**
(body), and **JetBrains Mono** (code/monospace).
Selectors are kept 1:1 with the existing markup, so theming changes are
made entirely in `src/index.css` via the CSS variables and global classes.

2528
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -5,21 +5,31 @@
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc && vite build",
"preview": "vite preview"
"build": "npx tsc && vite build",
"preview": "vite preview",
"test": "vitest run",
"test:watch": "vitest",
"test:ui": "vitest --ui"
},
"dependencies": {
"axios": "^1.6.7",
"dayjs": "^1.11.10",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-router-dom": "^6.22.0",
"axios": "^1.6.7",
"dayjs": "^1.11.10"
"react-router-dom": "^6.22.0"
},
"devDependencies": {
"@testing-library/dom": "^10.4.1",
"@testing-library/jest-dom": "^6.9.1",
"@testing-library/react": "^16.3.2",
"@testing-library/user-event": "^14.6.1",
"@types/react": "^18.3.1",
"@types/react-dom": "^18.3.0",
"@vitejs/plugin-react": "^4.2.1",
"@vitest/ui": "^4.1.2",
"jsdom": "^29.0.1",
"typescript": "^5.4.0",
"vite": "^5.1.0"
"vite": "^5.1.0",
"vitest": "^4.1.2"
}
}

View File

@@ -22,11 +22,13 @@ import SupportDetailPage from '@/pages/SupportDetailPage'
import MeetingDetailPage from '@/pages/MeetingDetailPage'
import axios from 'axios'
const WIZARD_PORT = Number(import.meta.env.VITE_WIZARD_PORT) || 18080
const WIZARD_BASE = `http://127.0.0.1:${WIZARD_PORT}`
const getStoredWizardPort = (): number | null => {
const stored = Number(localStorage.getItem('HF_WIZARD_PORT'))
return stored && stored > 0 ? stored : null
}
const getApiBase = () => {
return localStorage.getItem('HF_BACKEND_BASE_URL') || import.meta.env.VITE_API_BASE || 'http://127.0.0.1:8000'
return localStorage.getItem('HF_BACKEND_BASE_URL') ?? undefined
}
type AppState = 'checking' | 'setup' | 'ready'
@@ -55,24 +57,26 @@ export default function App() {
// Backend unreachable — fall through to wizard check
}
// Fallback: try the wizard directly (needed during initial setup before backend starts)
try {
const res = await axios.get(`${WIZARD_BASE}/api/v1/config/harborforge.json`, {
timeout: 5000,
})
const cfg = res.data || {}
if (cfg.backend_url) {
localStorage.setItem('HF_BACKEND_BASE_URL', cfg.backend_url)
// Fallback: if a wizard port was previously saved during setup, try it directly
const storedPort = getStoredWizardPort()
if (storedPort) {
try {
const res = await axios.get(`http://127.0.0.1:${storedPort}/api/v1/config/harborforge.json`, {
timeout: 5000,
})
const cfg = res.data || {}
if (cfg.backend_url) {
localStorage.setItem('HF_BACKEND_BASE_URL', cfg.backend_url)
}
if (cfg.initialized === true) {
setAppState('ready')
return
}
} catch {
// ignore — fall through to setup
}
if (cfg.initialized === true) {
setAppState('ready')
} else {
setAppState('setup')
}
} catch {
// Neither backend nor wizard reachable → setup needed
setAppState('setup')
}
setAppState('setup')
}
if (appState === 'checking') {
@@ -80,7 +84,7 @@ export default function App() {
}
if (appState === 'setup') {
return <SetupWizardPage wizardBase={WIZARD_BASE} onComplete={checkInitialized} />
return <SetupWizardPage initialWizardPort={getStoredWizardPort()} onComplete={checkInitialized} />
}
if (loading) return <div className="loading">Loading...</div>
@@ -112,19 +116,19 @@ export default function App() {
<Routes>
<Route path="/" element={<DashboardPage />} />
<Route path="/tasks" element={<TasksPage />} />
<Route path="/tasks/:id" element={<TaskDetailPage />} />
<Route path="/tasks/:taskCode" element={<TaskDetailPage />} />
<Route path="/projects" element={<ProjectsPage />} />
<Route path="/projects/:id" element={<ProjectDetailPage />} />
<Route path="/milestones" element={<MilestonesPage />} />
<Route path="/milestones/:id" element={<MilestoneDetailPage />} />
<Route path="/milestones/:milestoneCode" element={<MilestoneDetailPage />} />
<Route path="/proposals" element={<ProposalsPage />} />
<Route path="/proposals/:id" element={<ProposalDetailPage />} />
<Route path="/proposals/:proposalCode" element={<ProposalDetailPage />} />
<Route path="/calendar" element={<CalendarPage />} />
{/* Legacy routes for backward compatibility */}
<Route path="/proposes" element={<ProposalsPage />} />
<Route path="/proposes/:id" element={<ProposalDetailPage />} />
<Route path="/meetings/:meetingId" element={<MeetingDetailPage />} />
<Route path="/supports/:supportId" element={<SupportDetailPage />} />
<Route path="/proposes/:proposalCode" element={<ProposalDetailPage />} />
<Route path="/meetings/:meetingCode" element={<MeetingDetailPage />} />
<Route path="/supports/:supportCode" element={<SupportDetailPage />} />
<Route path="/notifications" element={<NotificationsPage />} />
<Route path="/roles" element={<RoleEditorPage />} />
<Route path="/users" element={<UsersPage />} />

View File

@@ -18,8 +18,8 @@ type Props = {
onClose: () => void
onCreated?: (task: Task) => void | Promise<void>
onSaved?: (task: Task) => void | Promise<void>
initialProjectId?: number
initialMilestoneId?: number
initialProjectCode?: string
initialMilestoneCode?: string
lockProject?: boolean
lockMilestone?: boolean
task?: Task | null
@@ -28,8 +28,8 @@ type Props = {
type FormState = {
title: string
description: string
project_id: number
milestone_id: number
project_code: string
milestone_code: string
task_type: string
task_subtype: string
priority: string
@@ -37,11 +37,11 @@ type FormState = {
reporter_id: number
}
const makeInitialForm = (projectId = 0, milestoneId = 0): FormState => ({
const makeInitialForm = (projectCode = '', milestoneCode = ''): FormState => ({
title: '',
description: '',
project_id: projectId,
milestone_id: milestoneId,
project_code: projectCode,
milestone_code: milestoneCode,
task_type: 'issue', // P7.1: default changed from 'task' to 'issue'
task_subtype: '',
priority: 'medium',
@@ -54,8 +54,8 @@ export default function CreateTaskModal({
onClose,
onCreated,
onSaved,
initialProjectId,
initialMilestoneId,
initialProjectCode,
initialMilestoneCode,
lockProject = false,
lockMilestone = false,
task,
@@ -63,7 +63,7 @@ export default function CreateTaskModal({
const [projects, setProjects] = useState<Project[]>([])
const [milestones, setMilestones] = useState<Milestone[]>([])
const [saving, setSaving] = useState(false)
const [form, setForm] = useState<FormState>(makeInitialForm(initialProjectId, initialMilestoneId))
const [form, setForm] = useState<FormState>(makeInitialForm(initialProjectCode, initialMilestoneCode))
const isEdit = Boolean(task)
const currentType = useMemo(
@@ -72,18 +72,18 @@ export default function CreateTaskModal({
)
const subtypes = currentType.subtypes || []
const loadMilestones = async (projectId: number, preferredMilestoneId?: number) => {
if (!projectId) {
const loadMilestones = async (projectCode: string, preferredMilestoneCode?: string) => {
if (!projectCode) {
setMilestones([])
setForm((f) => ({ ...f, milestone_id: 0 }))
setForm((f) => ({ ...f, milestone_code: '' }))
return
}
const { data } = await api.get<Milestone[]>(`/milestones?project_id=${projectId}`)
const { data } = await api.get<Milestone[]>(`/milestones?project_code=${projectCode}`)
setMilestones(data)
const hasPreferred = preferredMilestoneId && data.some((m) => m.id === preferredMilestoneId)
const nextMilestoneId = hasPreferred ? preferredMilestoneId! : (data[0]?.id || 0)
setForm((f) => ({ ...f, milestone_id: nextMilestoneId }))
const hasPreferred = preferredMilestoneCode && data.some((m) => m.milestone_code === preferredMilestoneCode)
const nextMilestoneCode = hasPreferred ? preferredMilestoneCode! : (data[0]?.milestone_code || '')
setForm((f) => ({ ...f, milestone_code: nextMilestoneCode }))
}
useEffect(() => {
@@ -93,30 +93,30 @@ export default function CreateTaskModal({
const { data } = await api.get<Project[]>('/projects')
setProjects(data)
const chosenProjectId = task?.project_id || initialProjectId || data[0]?.id || 0
const chosenMilestoneId = task?.milestone_id || initialMilestoneId || 0
const chosenProjectCode = task?.project_code || initialProjectCode || data[0]?.project_code || ''
const chosenMilestoneCode = task?.milestone_code || initialMilestoneCode || ''
setForm(task ? {
title: task.title,
description: task.description || '',
project_id: task.project_id,
milestone_id: task.milestone_id || 0,
project_code: task.project_code || '',
milestone_code: task.milestone_code || '',
task_type: task.task_type,
task_subtype: task.task_subtype || '',
priority: task.priority,
tags: task.tags || '',
reporter_id: task.reporter_id,
} : makeInitialForm(chosenProjectId, chosenMilestoneId))
} : makeInitialForm(chosenProjectCode, chosenMilestoneCode))
await loadMilestones(chosenProjectId, chosenMilestoneId)
await loadMilestones(chosenProjectCode, chosenMilestoneCode)
}
init().catch(console.error)
}, [isOpen, initialProjectId, initialMilestoneId, task])
}, [isOpen, initialProjectCode, initialMilestoneCode, task])
const handleProjectChange = async (projectId: number) => {
setForm((f) => ({ ...f, project_id: projectId, milestone_id: 0 }))
await loadMilestones(projectId)
const handleProjectChange = async (projectCode: string) => {
setForm((f) => ({ ...f, project_code: projectCode, milestone_code: '' }))
await loadMilestones(projectCode)
}
const handleTypeChange = (taskType: string) => {
@@ -125,7 +125,7 @@ export default function CreateTaskModal({
const submit = async (e: React.FormEvent) => {
e.preventDefault()
if (!form.milestone_id) {
if (!form.milestone_code) {
alert('Please select a milestone')
return
}
@@ -136,7 +136,7 @@ export default function CreateTaskModal({
setSaving(true)
try {
const { data } = isEdit
? await api.patch<Task>(`/tasks/${task!.id}`, payload)
? await api.patch<Task>(`/tasks/${task!.task_code}`, payload)
: await api.post<Task>('/tasks', payload)
await onCreated?.(data)
await onSaved?.(data)
@@ -181,12 +181,12 @@ export default function CreateTaskModal({
Project
<select
data-testid="project-select"
value={form.project_id}
onChange={(e) => handleProjectChange(Number(e.target.value))}
value={form.project_code}
onChange={(e) => handleProjectChange(e.target.value)}
disabled={lockProject}
>
{projects.map((p) => (
<option key={p.id} value={p.id}>{p.name}</option>
<option key={p.id} value={p.project_code || ''}>{p.name}</option>
))}
</select>
</label>
@@ -195,13 +195,13 @@ export default function CreateTaskModal({
Milestone
<select
data-testid="milestone-select"
value={form.milestone_id}
onChange={(e) => setForm({ ...form, milestone_id: Number(e.target.value) })}
value={form.milestone_code}
onChange={(e) => setForm({ ...form, milestone_code: e.target.value })}
disabled={lockMilestone}
>
{milestones.length === 0 && <option value={0}>No milestones available</option>}
{milestones.map((m) => (
<option key={m.id} value={m.id}>{m.title}</option>
<option key={m.id} value={m.milestone_code || ''}>{m.title}</option>
))}
</select>
</label>

View File

@@ -7,14 +7,14 @@ type Props = {
onClose: () => void
onSaved?: (milestone: Milestone) => void | Promise<void>
milestone?: Milestone | null
initialProjectId?: number
initialProjectCode?: string
lockProject?: boolean
}
type FormState = {
title: string
description: string
project_id: number
project_code: string
status: string
due_date: string
planned_release_date: string
@@ -23,7 +23,7 @@ type FormState = {
const emptyForm: FormState = {
title: '',
description: '',
project_id: 0,
project_code: '',
status: 'open',
due_date: '',
planned_release_date: '',
@@ -31,7 +31,7 @@ const emptyForm: FormState = {
const toDateInput = (value?: string | null) => (value ? String(value).slice(0, 10) : '')
export default function MilestoneFormModal({ isOpen, onClose, onSaved, milestone, initialProjectId, lockProject = false }: Props) {
export default function MilestoneFormModal({ isOpen, onClose, onSaved, milestone, initialProjectCode, lockProject = false }: Props) {
const [projects, setProjects] = useState<Project[]>([])
const [saving, setSaving] = useState(false)
const [form, setForm] = useState<FormState>(emptyForm)
@@ -42,11 +42,11 @@ export default function MilestoneFormModal({ isOpen, onClose, onSaved, milestone
const init = async () => {
const { data } = await api.get<Project[]>('/projects')
setProjects(data)
const defaultProjectId = milestone?.project_id || initialProjectId || data[0]?.id || 0
const defaultProjectCode = milestone?.project_code || initialProjectCode || data[0]?.project_code || ''
setForm({
title: milestone?.title || '',
description: milestone?.description || '',
project_id: defaultProjectId,
project_code: defaultProjectCode,
status: milestone?.status || 'open',
due_date: toDateInput(milestone?.due_date),
planned_release_date: toDateInput(milestone?.planned_release_date),
@@ -54,7 +54,7 @@ export default function MilestoneFormModal({ isOpen, onClose, onSaved, milestone
}
init().catch(console.error)
}, [isOpen, milestone, initialProjectId])
}, [isOpen, milestone, initialProjectCode])
const submit = async (e: React.FormEvent) => {
e.preventDefault()
@@ -63,13 +63,13 @@ export default function MilestoneFormModal({ isOpen, onClose, onSaved, milestone
const payload = {
title: form.title,
description: form.description || null,
project_id: form.project_id,
project_code: form.project_code,
status: form.status,
due_date: form.due_date || null,
planned_release_date: form.planned_release_date || null,
}
if (milestone) {
const { data } = await api.patch<Milestone>(`/milestones/${milestone.id}`, payload)
const { data } = await api.patch<Milestone>(`/milestones/${milestone.milestone_code}`, payload)
await onSaved?.(data)
} else {
const { data } = await api.post<Milestone>('/milestones', payload)
@@ -116,8 +116,8 @@ export default function MilestoneFormModal({ isOpen, onClose, onSaved, milestone
<div className="task-create-grid">
<label>
Project
<select value={form.project_id} onChange={(e) => setForm((f) => ({ ...f, project_id: Number(e.target.value) }))} disabled={lockProject}>
{projects.map((p) => <option key={p.id} value={p.id}>{p.name}</option>)}
<select value={form.project_code} onChange={(e) => setForm((f) => ({ ...f, project_code: e.target.value }))} disabled={lockProject}>
{projects.map((p) => <option key={p.id} value={p.project_code || ''}>{p.name}</option>)}
</select>
</label>

View File

@@ -1,227 +1,554 @@
/* ============================================================================
HarborForge — "FOUNDRY DECK"
A shipwright's drafting table meets a foundry control panel.
Blackened steel, blueprint grid, molten-ember accent, technical type.
Full visual redesign — selectors kept 1:1 with existing markup.
========================================================================== */
@import url('https://fonts.googleapis.com/css2?family=Saira+Condensed:wght@500;600;700&family=Hanken+Grotesk:wght@400;500;600;700&family=JetBrains+Mono:wght@400;500;700&display=swap');
:root {
--bg: #0f1117;
--bg-card: #1a1d27;
--bg-hover: #22252f;
--border: #2a2d37;
--text: #e1e4ea;
--text-dim: #8b8fa3;
--accent: #3b82f6;
--accent-hover: #2563eb;
--success: #10b981;
--warning: #f59e0b;
--danger: #ef4444;
--sidebar-w: 220px;
/* core surfaces — blackened, cool-tinted steel */
--bg: #0b0c0f;
--bg-card: #14161c;
--bg-hover: #1d212b;
--bg-sink: #08090b; /* recessed inputs / wells */
--border: #2b2f3a;
--border-bright: #3b414f;
/* ink — warm cast-paper on cold metal */
--text: #ece6d8;
--text-dim: #888f9e;
/* molten ember — the one unforgettable thing */
--accent: #ff6a1a;
--accent-hover: #ff8636;
--ember: linear-gradient(135deg, #ff7a1f 0%, #ffa83a 100%);
--ember-soft: rgba(255, 106, 26, .14);
--glow: 0 0 0 1px rgba(255,122,31,.40), 0 10px 34px -10px rgba(255,122,31,.55);
/* oxidized steel — the cold secondary */
--steel: #56c6d6;
/* forge-mapped status palette */
--success: #46b487; /* patina */
--warning: #efa53c; /* heat amber */
--danger: #e2553c; /* rust */
--violet: #9a7bff; /* arc */
--sidebar-w: 240px;
--hair: 1px solid var(--border);
--radius: 4px; /* tight, machined corners */
}
* { margin: 0; padding: 0; box-sizing: border-box; }
body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; background: var(--bg); color: var(--text); }
a { color: var(--accent); text-decoration: none; }
a:hover { text-decoration: underline; }
/* Layout */
.app-layout { display: flex; min-height: 100vh; }
.main-content { flex: 1; padding: 24px 32px; margin-left: var(--sidebar-w); }
.loading { display: flex; align-items: center; justify-content: center; height: 100vh; font-size: 1.2rem; color: var(--text-dim); }
html { scroll-behavior: smooth; }
/* Sidebar */
.sidebar { position: fixed; top: 0; left: 0; width: var(--sidebar-w); height: 100vh; background: var(--bg-card); border-right: 1px solid var(--border); display: flex; flex-direction: column; padding: 16px 0; }
.sidebar-header { padding: 8px 20px 24px; }
.sidebar-header h1 { font-size: 1.2rem; }
.nav-links { list-style: none; flex: 1; }
.nav-links li a { display: block; padding: 10px 20px; color: var(--text-dim); transition: .15s; }
.nav-links li a:hover, .nav-links li.active a { background: var(--bg-hover); color: var(--text); text-decoration: none; }
.sidebar-footer { padding: 12px 20px; border-top: 1px solid var(--border); display: flex; justify-content: space-between; align-items: center; font-size: .85rem; color: var(--text-dim); }
.sidebar-footer button { background: none; border: 1px solid var(--border); color: var(--text-dim); padding: 4px 10px; border-radius: 4px; cursor: pointer; }
/* Login */
.login-page { display: flex; align-items: center; justify-content: center; height: 100vh; }
.login-card { background: var(--bg-card); padding: 40px; border-radius: 12px; border: 1px solid var(--border); width: 360px; text-align: center; }
.login-card h1 { margin-bottom: 8px; }
.login-card .subtitle { color: var(--text-dim); margin-bottom: 24px; }
.login-card form { display: flex; flex-direction: column; gap: 12px; }
.login-card input { padding: 10px 12px; border: 1px solid var(--border); border-radius: 6px; background: var(--bg); color: var(--text); font-size: .95rem; }
.login-card button { padding: 10px; background: var(--accent); color: #fff; border: none; border-radius: 6px; font-size: 1rem; cursor: pointer; }
.login-card button:hover { background: var(--accent-hover); }
.error { color: var(--danger); font-size: .85rem; }
/* Stats */
.stats-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(140px, 1fr)); gap: 12px; margin: 16px 0 24px; }
.stat-card { background: var(--bg-card); border: 1px solid var(--border); border-left: 4px solid var(--accent); border-radius: 8px; padding: 16px; text-align: center; }
.stat-card.total { border-left-color: var(--success); }
.stat-number { display: block; font-size: 1.8rem; font-weight: 700; }
.stat-label { display: block; font-size: .8rem; color: var(--text-dim); margin-top: 4px; text-transform: capitalize; }
/* Bar chart */
.bar-chart { margin: 12px 0; }
.bar-row { display: flex; align-items: center; margin: 6px 0; }
.bar-label { width: 70px; font-size: .85rem; color: var(--text-dim); text-transform: capitalize; }
.bar { padding: 4px 10px; border-radius: 4px; color: #fff; font-size: .8rem; min-width: 30px; text-align: right; transition: .3s; }
/* Table */
table { width: 100%; border-collapse: collapse; margin-top: 12px; }
thead th { text-align: left; padding: 10px 12px; border-bottom: 2px solid var(--border); color: var(--text-dim); font-size: .8rem; text-transform: uppercase; }
tbody td { padding: 10px 12px; border-bottom: 1px solid var(--border); }
tr.clickable { cursor: pointer; }
tr.clickable:hover { background: var(--bg-hover); }
.task-title { font-weight: 500; max-width: 400px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
/* Badges */
.badge { display: inline-block; padding: 2px 8px; border-radius: 4px; font-size: .75rem; font-weight: 600; text-transform: capitalize; color: #fff; background: var(--text-dim); }
.status-open { background: #3b82f6; }
.status-in_progress { background: #f59e0b; }
.status-resolved { background: #10b981; }
.status-closed { background: #6b7280; }
.status-blocked { background: #ef4444; }
.status-freeze { background: #8b5cf6; }
.status-undergoing { background: #f59e0b; }
.status-completed { background: #10b981; }
.priority-low { background: #6b7280; }
.priority-medium { background: #3b82f6; }
.priority-high { background: #f59e0b; }
.priority-critical { background: #ef4444; }
/* Page header */
.page-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 16px; }
.btn-primary { background: var(--accent); color: #fff; border: none; padding: 8px 16px; border-radius: 6px; cursor: pointer; font-size: .9rem; }
.btn-primary:hover { background: var(--accent-hover); }
.btn-back { background: none; border: 1px solid var(--border); color: var(--text-dim); padding: 6px 12px; border-radius: 6px; cursor: pointer; margin-bottom: 16px; }
/* Filters */
.filters { margin-bottom: 12px; display: flex; gap: 8px; }
.filters select { padding: 6px 10px; border: 1px solid var(--border); border-radius: 6px; background: var(--bg-card); color: var(--text); }
/* Pagination */
.pagination { display: flex; align-items: center; justify-content: center; gap: 12px; margin-top: 16px; }
.pagination button { padding: 6px 14px; border: 1px solid var(--border); background: var(--bg-card); color: var(--text); border-radius: 6px; cursor: pointer; }
.pagination button:disabled { opacity: .4; cursor: default; }
/* Task detail */
.task-header { margin-bottom: 20px; }
.task-header h2 { margin-bottom: 8px; }
.task-meta { display: flex; gap: 8px; flex-wrap: wrap; }
.tags { color: var(--accent); font-size: .85rem; }
.section { margin: 20px 0; }
.section h3 { margin-bottom: 8px; color: var(--text-dim); font-size: .9rem; text-transform: uppercase; }
dl { display: grid; grid-template-columns: 120px 1fr; gap: 6px; }
dt { color: var(--text-dim); font-size: .85rem; }
dd { font-size: .9rem; }
.actions { display: flex; gap: 8px; }
.btn-transition { padding: 6px 14px; border: 1px solid var(--border); background: var(--bg-card); color: var(--text); border-radius: 6px; cursor: pointer; text-transform: capitalize; }
.btn-transition:hover { background: var(--bg-hover); }
/* Comments */
.comment { background: var(--bg-card); border: 1px solid var(--border); border-radius: 8px; padding: 12px; margin-bottom: 8px; }
.comment-meta { font-size: .8rem; color: var(--text-dim); margin-bottom: 4px; }
.comment-form { margin-top: 12px; }
.comment-form textarea { width: 100%; min-height: 80px; padding: 10px; border: 1px solid var(--border); border-radius: 6px; background: var(--bg); color: var(--text); resize: vertical; margin-bottom: 8px; }
.comment-form button { padding: 8px 16px; background: var(--accent); color: #fff; border: none; border-radius: 6px; cursor: pointer; }
/* Create Task form / modal */
.create-task form, .task-create-form { max-width: 600px; display: flex; flex-direction: column; gap: 14px; }
.create-task label, .task-create-form label { display: flex; flex-direction: column; gap: 4px; font-size: .85rem; color: var(--text-dim); }
.create-task input, .create-task textarea, .create-task select,
.task-create-form input, .task-create-form textarea, .task-create-form select {
padding: 8px 12px; border: 1px solid var(--border); border-radius: 6px; background: var(--bg); color: var(--text); font-size: .95rem;
body {
font-family: 'Hanken Grotesk', system-ui, sans-serif;
font-size: 15px;
line-height: 1.55;
color: var(--text);
background-color: var(--bg);
/* layered atmosphere: ember vignette + blueprint grid + grain */
background-image:
radial-gradient(120% 80% at 78% -10%, rgba(255,122,31,.13), transparent 55%),
radial-gradient(90% 70% at 0% 100%, rgba(86,198,214,.06), transparent 60%),
linear-gradient(rgba(255,255,255,.022) 1px, transparent 1px),
linear-gradient(90deg, rgba(255,255,255,.022) 1px, transparent 1px);
background-size: 100% 100%, 100% 100%, 40px 40px, 40px 40px;
background-attachment: fixed;
-webkit-font-smoothing: antialiased;
text-rendering: optimizeLegibility;
}
.create-task textarea, .task-create-form textarea { min-height: 100px; resize: vertical; }
.task-create-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 12px; }
/* fine grain overlay over everything */
body::after {
content: '';
position: fixed; inset: 0;
pointer-events: none; z-index: 9999;
opacity: .035;
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='120' height='120'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.85' numOctaves='2'/%3E%3C/filter%3E%3Crect width='120' height='120' filter='url(%23n)'/%3E%3C/svg%3E");
}
h1, h2, h3, h4 {
font-family: 'Saira Condensed', 'Hanken Grotesk', sans-serif;
font-weight: 600;
letter-spacing: .02em;
line-height: 1.12;
color: var(--text);
}
h1 { font-size: 1.55rem; text-transform: uppercase; letter-spacing: .06em; }
h2 { font-size: 1.4rem; }
h3 { font-size: 1.1rem; }
code, pre, .mono { font-family: 'JetBrains Mono', monospace; }
a { color: var(--accent); text-decoration: none; transition: color .15s; }
a:hover { color: var(--accent-hover); text-decoration: none; }
::selection { background: rgba(255,122,31,.32); color: #fff; }
:focus-visible {
outline: none;
box-shadow: 0 0 0 2px var(--bg), 0 0 0 4px rgba(255,122,31,.6);
border-radius: 3px;
}
::-webkit-scrollbar { width: 11px; height: 11px; }
::-webkit-scrollbar-track { background: var(--bg-sink); }
::-webkit-scrollbar-thumb { background: #2c313d; border: 3px solid var(--bg-sink); border-radius: 6px; }
::-webkit-scrollbar-thumb:hover { background: #3c4250; }
input, textarea, select, button { font-family: inherit; }
/* ---- Layout ------------------------------------------------------------- */
.app-layout { display: flex; min-height: 100vh; }
.main-content {
flex: 1; padding: 34px 44px; margin-left: var(--sidebar-w);
max-width: 1500px;
animation: deck-in .5s cubic-bezier(.16,1,.3,1) both;
}
.loading {
display: flex; align-items: center; justify-content: center; height: 100vh;
font-family: 'Saira Condensed', sans-serif; text-transform: uppercase;
letter-spacing: .35em; font-size: 1rem; color: var(--text-dim);
}
.loading::before { content: '◆ '; color: var(--accent); animation: pulse 1.4s ease-in-out infinite; }
@keyframes deck-in { from { opacity: 0; transform: translateY(14px); } to { opacity: 1; transform: none; } }
@keyframes fadeIn { from { opacity: 0; transform: translateY(8px); } to { opacity: 1; transform: none; } }
@keyframes pulse { 0%,100% { opacity: .35; } 50% { opacity: 1; } }
@keyframes sheen { from { background-position: -200% 0; } to { background-position: 200% 0; } }
@media (prefers-reduced-motion: reduce) {
*, *::before, *::after { animation: none !important; transition: none !important; scroll-behavior: auto !important; }
}
/* ---- Sidebar ------------------------------------------------------------ */
.sidebar {
position: fixed; top: 0; left: 0; width: var(--sidebar-w); height: 100vh;
background:
linear-gradient(180deg, #15171e, #101218);
border-right: var(--hair);
display: flex; flex-direction: column; padding: 0 0 14px;
z-index: 50;
}
.sidebar::before { /* hot edge line */
content: ''; position: absolute; top: 0; right: -1px; width: 2px; height: 100%;
background: linear-gradient(180deg, transparent, rgba(255,122,31,.5), transparent);
}
.sidebar-header { padding: 26px 22px 22px; border-bottom: var(--hair); }
.sidebar-header h1 {
font-size: 1.3rem; letter-spacing: .12em;
display: flex; align-items: center; gap: 8px;
}
.sidebar-header h1::first-letter { color: var(--accent); }
.nav-links { list-style: none; flex: 1; padding: 14px 12px; display: flex; flex-direction: column; gap: 2px; }
.nav-links li a {
display: flex; align-items: center; gap: 10px;
padding: 10px 14px; border-radius: var(--radius);
color: var(--text-dim); font-size: .82rem;
font-weight: 600; letter-spacing: .04em; text-transform: uppercase;
position: relative; transition: .15s;
}
.nav-links li a:hover { color: var(--text); background: var(--bg-hover); }
.nav-links li.active a {
color: var(--text); background: var(--ember-soft);
}
.nav-links li.active a::before {
content: ''; position: absolute; left: -12px; top: 6px; bottom: 6px; width: 3px;
background: var(--ember); border-radius: 0 3px 3px 0;
box-shadow: 0 0 12px rgba(255,122,31,.7);
}
.sidebar-footer {
margin: 0 12px; padding: 14px; border-top: var(--hair);
display: flex; justify-content: space-between; align-items: center;
font-size: .8rem; color: var(--text-dim); font-family: 'JetBrains Mono', monospace;
}
.sidebar-footer button {
background: none; border: var(--hair); color: var(--text-dim);
padding: 5px 11px; border-radius: var(--radius); cursor: pointer;
font-size: .72rem; text-transform: uppercase; letter-spacing: .08em; transition: .15s;
}
.sidebar-footer button:hover { border-color: var(--accent); color: var(--accent); }
/* ---- Login -------------------------------------------------------------- */
.login-page, .setup-wizard {
display: flex; align-items: center; justify-content: center;
min-height: 100vh; padding: 24px;
}
.login-card {
position: relative; background: var(--bg-card); padding: 46px 42px;
border: var(--hair); border-radius: 6px; width: 380px; text-align: center;
box-shadow: 0 40px 80px -30px rgba(0,0,0,.8);
animation: deck-in .55s cubic-bezier(.16,1,.3,1) both;
}
.login-card::before { /* molten top edge */
content: ''; position: absolute; left: 0; right: 0; top: 0; height: 3px;
background: var(--ember); border-radius: 6px 6px 0 0;
}
.login-card::after { /* corner draftsman tick */
content: ''; position: absolute; right: 14px; bottom: 14px; width: 14px; height: 14px;
border-right: 2px solid var(--border-bright); border-bottom: 2px solid var(--border-bright);
}
.login-card h1 { margin-bottom: 6px; letter-spacing: .1em; }
.login-card .subtitle, .setup-header p {
color: var(--text-dim); margin-bottom: 28px; font-size: .82rem;
text-transform: uppercase; letter-spacing: .14em;
}
.login-card form, .setup-form { display: flex; flex-direction: column; gap: 14px; }
.login-card input {
padding: 12px 14px; border: var(--hair); border-radius: var(--radius);
background: var(--bg-sink); color: var(--text); font-size: .95rem; transition: .15s;
}
.login-card input::placeholder { color: #5b6170; text-transform: uppercase; letter-spacing: .08em; font-size: .8rem; }
.login-card input:focus { border-color: var(--accent); background: var(--bg); }
.login-card button, .setup-nav button {
padding: 12px; background: var(--ember); color: #1a0d02; border: none;
border-radius: var(--radius); font-size: .9rem; cursor: pointer;
font-family: 'Saira Condensed', sans-serif; font-weight: 700;
text-transform: uppercase; letter-spacing: .14em; transition: .18s;
}
.login-card button:hover, .setup-nav button:hover { box-shadow: var(--glow); transform: translateY(-1px); }
.login-card button:disabled { opacity: .55; cursor: default; transform: none; box-shadow: none; }
.error { color: var(--danger); font-size: .82rem; font-family: 'JetBrains Mono', monospace; }
/* ---- Stats -------------------------------------------------------------- */
.stats-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); gap: 14px; margin: 18px 0 28px; }
.stat-card {
position: relative; background: var(--bg-card); border: var(--hair);
border-radius: var(--radius); padding: 20px 18px; overflow: hidden;
transition: .18s; animation: deck-in .5s cubic-bezier(.16,1,.3,1) both;
}
.stat-card::before {
content: ''; position: absolute; left: 0; top: 0; bottom: 0; width: 3px; background: var(--ember);
}
.stat-card.total::before { background: var(--steel); }
.stat-card:hover { transform: translateY(-3px); border-color: var(--border-bright); box-shadow: 0 16px 30px -18px rgba(0,0,0,.8); }
.stat-card:nth-child(2) { animation-delay: .05s; }
.stat-card:nth-child(3) { animation-delay: .1s; }
.stat-card:nth-child(4) { animation-delay: .15s; }
.stat-card:nth-child(5) { animation-delay: .2s; }
.stat-number {
display: block; font-family: 'Saira Condensed', sans-serif; font-size: 2.4rem;
font-weight: 700; line-height: 1; color: var(--text);
}
.stat-label {
display: block; font-size: .68rem; color: var(--text-dim); margin-top: 8px;
text-transform: uppercase; letter-spacing: .16em;
}
/* ---- Bar chart ---------------------------------------------------------- */
.bar-chart { margin: 14px 0; }
.bar-row { display: flex; align-items: center; margin: 7px 0; }
.bar-label { width: 80px; font-size: .72rem; color: var(--text-dim); text-transform: uppercase; letter-spacing: .08em; }
.bar {
padding: 5px 11px; border-radius: 2px; color: #fff;
font-family: 'JetBrains Mono', monospace; font-size: .76rem;
min-width: 30px; text-align: right; transition: width .5s cubic-bezier(.16,1,.3,1);
}
/* ---- Tables ------------------------------------------------------------- */
table { width: 100%; border-collapse: collapse; margin-top: 14px; }
thead th {
text-align: left; padding: 11px 14px; border-bottom: 2px solid var(--border-bright);
color: var(--text-dim); font-size: .68rem; text-transform: uppercase; letter-spacing: .16em;
font-weight: 700;
}
tbody td { padding: 12px 14px; border-bottom: var(--hair); font-size: .9rem; }
tbody tr:last-child td { border-bottom: none; }
tr.clickable { cursor: pointer; transition: .12s; }
tr.clickable:hover { background: var(--ember-soft); }
tr.clickable:hover td:first-child { box-shadow: inset 3px 0 0 var(--accent); }
.task-title { font-weight: 600; max-width: 420px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
/* ---- Badges ------------------------------------------------------------- */
.badge {
display: inline-block; padding: 3px 9px; border-radius: 2px;
font-family: 'JetBrains Mono', monospace; font-size: .68rem; font-weight: 700;
text-transform: uppercase; letter-spacing: .06em;
color: #0b0c0f; background: var(--text-dim);
border: 1px solid rgba(255,255,255,.12);
}
.status-open { background: #5b8def; color: #fff; }
.status-in_progress { background: var(--ember); }
.status-undergoing { background: var(--ember); }
.status-resolved { background: var(--success); color: #04130d; }
.status-completed { background: var(--success); color: #04130d; }
.status-closed { background: #5a616f; color: #fff; }
.status-blocked { background: var(--danger); color: #fff; }
.status-freeze { background: var(--steel); color: #042127; }
.status-pending { background: var(--warning); }
.priority-low { background: #5a616f; color: #fff; }
.priority-medium { background: #5b8def; color: #fff; }
.priority-high { background: var(--warning); }
.priority-critical { background: var(--danger); color: #fff; }
/* ---- Page header / buttons --------------------------------------------- */
.page-header {
display: flex; justify-content: space-between; align-items: center;
margin-bottom: 22px; padding-bottom: 16px; border-bottom: var(--hair);
}
.page-header h2 { letter-spacing: .04em; }
.btn-primary {
background: var(--ember); color: #1a0d02; border: none;
padding: 9px 18px; border-radius: var(--radius); cursor: pointer;
font-family: 'Saira Condensed', sans-serif; font-weight: 700;
font-size: .85rem; text-transform: uppercase; letter-spacing: .1em; transition: .18s;
}
.btn-primary:hover { box-shadow: var(--glow); transform: translateY(-1px); }
.btn-back {
background: none; border: var(--hair); color: var(--text-dim);
padding: 7px 14px; border-radius: var(--radius); cursor: pointer;
margin-bottom: 18px; font-size: .8rem; text-transform: uppercase;
letter-spacing: .08em; transition: .15s;
}
.btn-back:hover { border-color: var(--accent); color: var(--accent); }
/* ---- Filters / pagination ---------------------------------------------- */
.filters { margin-bottom: 14px; display: flex; gap: 8px; }
.filters select, .inline-form select, .inline-form input {
padding: 8px 12px; border: var(--hair); border-radius: var(--radius);
background: var(--bg-card); color: var(--text); font-size: .88rem; transition: .15s;
}
.filters select:focus, .inline-form select:focus, .inline-form input:focus { border-color: var(--accent); }
.pagination { display: flex; align-items: center; justify-content: center; gap: 14px; margin-top: 22px; }
.pagination button {
padding: 7px 16px; border: var(--hair); background: var(--bg-card); color: var(--text);
border-radius: var(--radius); cursor: pointer; font-size: .82rem;
text-transform: uppercase; letter-spacing: .06em; transition: .15s;
}
.pagination button:hover:not(:disabled) { border-color: var(--accent); color: var(--accent); }
.pagination button:disabled { opacity: .35; cursor: default; }
/* ---- Task / detail ------------------------------------------------------ */
.task-header { margin-bottom: 24px; }
.task-header h2 { margin-bottom: 10px; }
.task-meta { display: flex; gap: 8px; flex-wrap: wrap; }
.tags { color: var(--steel); font-size: .82rem; font-family: 'JetBrains Mono', monospace; }
.section { margin: 26px 0; }
.section h3 {
margin-bottom: 12px; color: var(--text-dim); font-size: .72rem;
text-transform: uppercase; letter-spacing: .2em;
padding-bottom: 8px; border-bottom: var(--hair);
}
dl { display: grid; grid-template-columns: 140px 1fr; gap: 8px 12px; }
dt { color: var(--text-dim); font-size: .72rem; text-transform: uppercase; letter-spacing: .1em; padding-top: 2px; }
dd { font-size: .92rem; font-family: 'JetBrains Mono', monospace; }
.actions { display: flex; gap: 8px; }
.btn-transition {
padding: 7px 15px; border: var(--hair); background: var(--bg-card); color: var(--text);
border-radius: var(--radius); cursor: pointer; text-transform: uppercase;
font-size: .78rem; letter-spacing: .08em; transition: .15s;
}
.btn-transition:hover { border-color: var(--accent); color: var(--accent); background: var(--ember-soft); }
/* ---- Comments ----------------------------------------------------------- */
.comment {
background: var(--bg-card); border: var(--hair); border-left: 3px solid var(--border-bright);
border-radius: var(--radius); padding: 14px 16px; margin-bottom: 10px;
}
.comment:hover { border-left-color: var(--accent); }
.comment-meta { font-size: .74rem; color: var(--text-dim); margin-bottom: 6px; font-family: 'JetBrains Mono', monospace; }
.comment-form { margin-top: 14px; }
.comment-form textarea {
width: 100%; min-height: 88px; padding: 12px; border: var(--hair);
border-radius: var(--radius); background: var(--bg-sink); color: var(--text);
resize: vertical; margin-bottom: 10px; transition: .15s;
}
.comment-form textarea:focus { border-color: var(--accent); }
.comment-form button {
padding: 9px 18px; background: var(--ember); color: #1a0d02; border: none;
border-radius: var(--radius); cursor: pointer; font-family: 'Saira Condensed', sans-serif;
font-weight: 700; text-transform: uppercase; letter-spacing: .1em; transition: .18s;
}
.comment-form button:hover { box-shadow: var(--glow); }
/* ---- Forms / modal ------------------------------------------------------ */
.create-task form, .task-create-form { max-width: 640px; display: flex; flex-direction: column; gap: 16px; }
.create-task label, .task-create-form label, .setup-form label {
display: flex; flex-direction: column; gap: 6px; font-size: .7rem;
color: var(--text-dim); text-transform: uppercase; letter-spacing: .12em;
}
.create-task input, .create-task textarea, .create-task select,
.task-create-form input, .task-create-form textarea, .task-create-form select,
.setup-form input {
padding: 10px 13px; border: var(--hair); border-radius: var(--radius);
background: var(--bg-sink); color: var(--text); font-size: .92rem;
font-family: inherit; transition: .15s;
}
.create-task input:focus, .create-task textarea:focus, .create-task select:focus,
.task-create-form input:focus, .task-create-form textarea:focus, .task-create-form select:focus,
.setup-form input:focus { border-color: var(--accent); background: var(--bg); }
.create-task textarea, .task-create-form textarea { min-height: 110px; resize: vertical; }
.task-create-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 14px; }
.modal-overlay {
position: fixed; inset: 0; background: rgba(0, 0, 0, .6); display: flex; align-items: center; justify-content: center; z-index: 1000; padding: 24px;
position: fixed; inset: 0; background: rgba(4,5,7,.78);
backdrop-filter: blur(3px); display: flex; align-items: center;
justify-content: center; z-index: 1000; padding: 24px;
animation: fadeIn .2s ease;
}
.modal {
width: min(720px, 100%); max-height: calc(100vh - 48px); overflow: auto; background: var(--bg-card); border: 1px solid var(--border); border-radius: 12px; padding: 20px;
position: relative; width: min(720px, 100%); max-height: calc(100vh - 48px);
overflow: auto; background: var(--bg-card); border: var(--hair);
border-radius: 6px; padding: 26px;
box-shadow: 0 40px 90px -30px rgba(0,0,0,.85);
animation: deck-in .35s cubic-bezier(.16,1,.3,1) both;
}
.modal-header { display: flex; align-items: center; justify-content: space-between; gap: 12px; margin-bottom: 16px; }
.modal-actions { display: flex; justify-content: flex-end; gap: 8px; margin-top: 8px; }
.modal::before { content: ''; position: absolute; left: 0; right: 0; top: 0; height: 3px; background: var(--ember); border-radius: 6px 6px 0 0; }
.modal-header { display: flex; align-items: center; justify-content: space-between; gap: 12px; margin-bottom: 20px; padding-bottom: 14px; border-bottom: var(--hair); }
.modal-actions { display: flex; justify-content: flex-end; gap: 10px; margin-top: 12px; }
/* Project grid */
.project-grid, .milestone-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(280px, 1fr)); gap: 16px; margin-top: 16px; }
.project-card, .milestone-card { background: var(--bg-card); border: 1px solid var(--border); border-radius: 8px; padding: 20px; cursor: pointer; transition: .15s; }
.project-card:hover, .milestone-card:hover { border-color: var(--accent); background: var(--bg-hover); }
.project-card h3, .milestone-card h3 { margin-bottom: 8px; }
.project-desc { color: var(--text-dim); font-size: .9rem; margin-bottom: 12px; }
.project-meta { font-size: .8rem; color: var(--text-dim); display: flex; gap: 12px; }
/* ---- Cards (project / milestone) --------------------------------------- */
.project-grid, .milestone-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(290px, 1fr)); gap: 18px; margin-top: 18px; }
.project-card, .milestone-card {
position: relative; background: var(--bg-card); border: var(--hair);
border-radius: var(--radius); padding: 22px; cursor: pointer;
transition: .2s; overflow: hidden;
animation: deck-in .5s cubic-bezier(.16,1,.3,1) both;
}
.project-card::after, .milestone-card::after { /* draftsman corner tick */
content: ''; position: absolute; right: 12px; top: 12px; width: 10px; height: 10px;
border-top: 2px solid var(--border-bright); border-right: 2px solid var(--border-bright);
transition: .2s;
}
.project-card:hover, .milestone-card:hover {
border-color: var(--accent); background: var(--bg-hover);
transform: translateY(-3px); box-shadow: 0 18px 36px -20px rgba(0,0,0,.85);
}
.project-card:hover::after, .milestone-card:hover::after { border-color: var(--accent); }
.project-card h3, .milestone-card h3 { margin-bottom: 10px; }
.project-desc { color: var(--text-dim); font-size: .88rem; margin-bottom: 14px; }
.project-meta { font-size: .72rem; color: var(--text-dim); display: flex; gap: 14px; font-family: 'JetBrains Mono', monospace; text-transform: uppercase; letter-spacing: .06em; }
.milestone-card-header { display: flex; align-items: center; gap: 8px; margin-bottom: 10px; }
.milestone-item { display: flex; align-items: center; gap: 10px; padding: 11px 8px; border-bottom: var(--hair); cursor: pointer; transition: .12s; }
.milestone-item:hover { background: var(--ember-soft); box-shadow: inset 3px 0 0 var(--accent); }
.milestone-title { font-weight: 600; }
/* Milestone card header */
.milestone-card-header { display: flex; align-items: center; gap: 8px; margin-bottom: 8px; }
.milestone-item { display: flex; align-items: center; gap: 8px; padding: 8px 0; border-bottom: 1px solid var(--border); cursor: pointer; }
.milestone-item:hover { background: var(--bg-hover); }
.milestone-title { font-weight: 500; }
/* ---- Progress bar ------------------------------------------------------- */
.progress-bar-container {
width: 100%; height: 18px; background: var(--bg-sink); border-radius: 2px;
overflow: hidden; border: var(--hair);
}
.progress-bar {
height: 100%; background: var(--ember);
background-image: linear-gradient(135deg, #ff7a1f, #ffa83a), linear-gradient(90deg, transparent, rgba(255,255,255,.35), transparent);
background-size: 100% 100%, 200% 100%;
color: #1a0d02; font-family: 'JetBrains Mono', monospace; font-size: .68rem; font-weight: 700;
display: flex; align-items: center; justify-content: center; min-width: 28px;
transition: width .6s cubic-bezier(.16,1,.3,1);
animation: sheen 2.6s linear infinite;
}
/* Progress bar */
.progress-bar-container { width: 100%; height: 20px; background: var(--bg); border-radius: 10px; overflow: hidden; border: 1px solid var(--border); }
.progress-bar { height: 100%; background: var(--success); color: #fff; font-size: .75rem; display: flex; align-items: center; justify-content: center; min-width: 30px; transition: width .3s; border-radius: 10px; }
/* Notification list */
.notification-list { margin-top: 16px; }
.notification-item { display: flex; gap: 12px; padding: 12px 16px; border-bottom: 1px solid var(--border); cursor: pointer; transition: .15s; }
/* ---- Notifications ------------------------------------------------------ */
.notification-list { margin-top: 18px; border: var(--hair); border-radius: var(--radius); overflow: hidden; }
.notification-item { display: flex; gap: 14px; padding: 14px 18px; border-bottom: var(--hair); cursor: pointer; transition: .12s; }
.notification-item:last-child { border-bottom: none; }
.notification-item:hover { background: var(--bg-hover); }
.notification-item.unread { background: var(--bg-card); }
.notification-dot { width: 12px; color: var(--accent); font-size: .6rem; padding-top: 4px; }
.notification-item.unread { background: var(--ember-soft); box-shadow: inset 3px 0 0 var(--accent); }
.notification-dot { width: 12px; color: var(--accent); font-size: .55rem; padding-top: 5px; }
.notification-body p { margin-bottom: 4px; }
/* Inline form */
.inline-form { display: flex; gap: 8px; margin-bottom: 16px; flex-wrap: wrap; align-items: center; }
.inline-form input, .inline-form select { padding: 8px 12px; border: 1px solid var(--border); border-radius: 6px; background: var(--bg); color: var(--text); }
/* Filter checkbox */
.filter-check { display: flex; align-items: center; gap: 6px; color: var(--text-dim); font-size: .9rem; cursor: pointer; }
/* Member list */
/* ---- Misc helpers ------------------------------------------------------- */
.inline-form { display: flex; gap: 8px; margin-bottom: 18px; flex-wrap: wrap; align-items: center; }
.filter-check { display: flex; align-items: center; gap: 6px; color: var(--text-dim); font-size: .82rem; cursor: pointer; text-transform: uppercase; letter-spacing: .06em; }
.member-list { display: flex; gap: 8px; flex-wrap: wrap; }
.empty {
color: var(--text-dim); padding: 28px 0; text-align: center;
font-family: 'Saira Condensed', sans-serif; text-transform: uppercase;
letter-spacing: .24em; font-size: .9rem;
}
.empty::before { content: '— '; color: var(--accent); }
.empty::after { content: ' —'; color: var(--accent); }
.text-dim { color: var(--text-dim); font-size: .82rem; }
/* Empty state */
.empty { color: var(--text-dim); font-style: italic; padding: 16px 0; }
/* Text dim helper */
.text-dim { color: var(--text-dim); font-size: .85rem; }
/* Setup Wizard */
.setup-wizard { display: flex; align-items: center; justify-content: center; min-height: 100vh; padding: 24px; }
.setup-container { background: var(--bg-card); border: 1px solid var(--border); border-radius: 16px; padding: 40px; max-width: 600px; width: 100%; }
.setup-header { text-align: center; margin-bottom: 32px; }
.setup-header h1 { font-size: 1.5rem; margin-bottom: 20px; }
/* ---- Setup Wizard ------------------------------------------------------- */
.setup-container {
position: relative; background: var(--bg-card); border: var(--hair);
border-radius: 6px; padding: 44px; max-width: 620px; width: 100%;
box-shadow: 0 40px 80px -30px rgba(0,0,0,.8);
animation: deck-in .55s cubic-bezier(.16,1,.3,1) both;
}
.setup-container::before { content: ''; position: absolute; left: 0; right: 0; top: 0; height: 3px; background: var(--ember); border-radius: 6px 6px 0 0; }
.setup-header { text-align: center; margin-bottom: 34px; }
.setup-header h1 { font-size: 1.6rem; margin-bottom: 22px; letter-spacing: .1em; }
.setup-steps { display: flex; justify-content: center; gap: 8px; flex-wrap: wrap; }
.setup-step { font-size: .8rem; color: var(--text-dim); padding: 4px 10px; border-radius: 12px; border: 1px solid var(--border); }
.setup-step.active { color: var(--accent); border-color: var(--accent); background: rgba(59,130,246,.1); }
.setup-step {
font-size: .68rem; color: var(--text-dim); padding: 5px 12px; border-radius: 2px;
border: var(--hair); text-transform: uppercase; letter-spacing: .1em;
font-family: 'JetBrains Mono', monospace;
}
.setup-step.active { color: var(--accent); border-color: var(--accent); background: var(--ember-soft); }
.setup-step.done { color: var(--success); border-color: var(--success); }
.setup-step-content { animation: fadeIn .2s ease; }
.setup-step-content h2 { margin-bottom: 8px; font-size: 1.2rem; }
.setup-form { display: flex; flex-direction: column; gap: 12px; margin: 20px 0; }
.setup-form label { display: flex; flex-direction: column; gap: 4px; font-size: .85rem; color: var(--text-dim); }
.setup-form input { padding: 10px 12px; border: 1px solid var(--border); border-radius: 6px; background: var(--bg); color: var(--text); font-size: .95rem; }
.setup-nav { display: flex; justify-content: space-between; margin-top: 24px; }
.setup-error { background: rgba(239,68,68,.1); border: 1px solid var(--danger); color: var(--danger); padding: 12px 16px; border-radius: 8px; margin-bottom: 16px; font-size: .9rem; white-space: pre-line; }
.setup-info { background: rgba(59,130,246,.08); border: 1px solid rgba(59,130,246,.2); padding: 16px; border-radius: 8px; margin: 16px 0; }
.setup-info code { display: block; background: var(--bg); padding: 8px 12px; border-radius: 4px; margin-top: 8px; font-size: .85rem; color: var(--accent); word-break: break-all; }
.setup-hint { color: var(--warning); font-size: .85rem; margin-top: 8px; }
.setup-step-content { animation: fadeIn .25s ease; }
.setup-step-content h2 { margin-bottom: 10px; font-size: 1.3rem; }
.setup-form { margin: 22px 0; }
.setup-nav { display: flex; justify-content: space-between; margin-top: 28px; }
.setup-nav button:disabled { opacity: .5; cursor: default; }
.setup-error {
background: rgba(226,85,60,.12); border: 1px solid var(--danger); color: var(--danger);
padding: 13px 16px; border-radius: var(--radius); margin-bottom: 18px;
font-size: .85rem; white-space: pre-line; font-family: 'JetBrains Mono', monospace;
}
.setup-info { background: rgba(86,198,214,.07); border: 1px solid rgba(86,198,214,.25); padding: 18px; border-radius: var(--radius); margin: 18px 0; }
.setup-info code {
display: block; background: var(--bg-sink); padding: 10px 13px; border-radius: 2px;
margin-top: 10px; font-size: .82rem; color: var(--steel); word-break: break-all;
}
.setup-hint { color: var(--warning); font-size: .82rem; margin-top: 8px; }
.setup-done { text-align: center; }
.setup-done h2 { color: var(--success); margin-bottom: 12px; }
@keyframes fadeIn { from { opacity: 0; transform: translateY(8px); } to { opacity: 1; transform: none; } }
.setup-done h2 { color: var(--success); margin-bottom: 14px; }
/* Monitor */
.monitor-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(260px, 1fr)); gap: 16px; margin-top: 12px; }
.monitor-card { background: var(--bg-card); border: 1px solid var(--border); border-radius: 8px; padding: 16px; }
.monitor-card-header { display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 8px; }
.monitor-metrics { margin: 8px 0; font-size: .9rem; }
.monitor-admin { display: grid; grid-template-columns: repeat(auto-fit, minmax(320px, 1fr)); gap: 16px; }
.status-ok { background: var(--success); }
.status-error { background: var(--danger); }
/* ---- Monitor ------------------------------------------------------------ */
.monitor-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(270px, 1fr)); gap: 18px; margin-top: 14px; }
.monitor-card {
position: relative; background: var(--bg-card); border: var(--hair);
border-radius: var(--radius); padding: 18px; overflow: hidden;
animation: deck-in .5s cubic-bezier(.16,1,.3,1) both;
}
.monitor-card::before { content: ''; position: absolute; left: 0; top: 0; bottom: 0; width: 3px; background: var(--steel); }
.monitor-card-header { display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 10px; }
.monitor-metrics { margin: 10px 0; font-size: .86rem; font-family: 'JetBrains Mono', monospace; }
.monitor-admin { display: grid; grid-template-columns: repeat(auto-fit, minmax(320px, 1fr)); gap: 18px; }
.status-ok { background: var(--success); color: #04130d; }
.status-error { background: var(--danger); color: #fff; }
.status-pending { background: var(--warning); }
.status-online { background: var(--success); }
.status-offline { background: var(--danger); }
.status-online { background: var(--success); color: #04130d; }
.status-offline { background: #5a616f; color: #fff; }
.btn-secondary { background: none; border: 1px solid var(--border); color: var(--text); padding: 6px 12px; border-radius: 6px; cursor: pointer; }
.btn-danger { background: var(--danger); color: #fff; border: none; padding: 6px 12px; border-radius: 6px; cursor: pointer; }
.btn-danger:hover { opacity: .9; }
/* ---- Secondary / danger buttons ---------------------------------------- */
.btn-secondary {
background: none; border: var(--hair); color: var(--text);
padding: 7px 14px; border-radius: var(--radius); cursor: pointer;
font-size: .8rem; text-transform: uppercase; letter-spacing: .08em; transition: .15s;
}
.btn-secondary:hover { border-color: var(--accent); color: var(--accent); }
.btn-danger {
background: var(--danger); color: #fff; border: none;
padding: 7px 14px; border-radius: var(--radius); cursor: pointer;
font-family: 'Saira Condensed', sans-serif; font-weight: 700;
text-transform: uppercase; letter-spacing: .1em; transition: .15s;
}
.btn-danger:hover { box-shadow: 0 8px 24px -8px rgba(226,85,60,.6); transform: translateY(-1px); }
/* Tabs */
.tabs { display: flex; gap: 4px; border-bottom: 1px solid var(--border); margin-bottom: 16px; }
.tab { background: none; border: none; padding: 10px 16px; color: var(--text-dim); cursor: pointer; border-bottom: 2px solid transparent; margin-bottom: -1px; }
/* ---- Tabs --------------------------------------------------------------- */
.tabs { display: flex; gap: 2px; border-bottom: var(--hair); margin-bottom: 20px; }
.tab {
background: none; border: none; padding: 11px 18px; color: var(--text-dim);
cursor: pointer; border-bottom: 2px solid transparent; margin-bottom: -1px;
font-family: 'Saira Condensed', sans-serif; font-weight: 600;
font-size: .92rem; text-transform: uppercase; letter-spacing: .08em; transition: .15s;
}
.tab:hover { color: var(--text); }
.tab.active { color: var(--accent); border-bottom-color: var(--accent); }
.tab-content { margin-top: 16px; }
.tab-content { margin-top: 18px; animation: fadeIn .25s ease; }
/* ---- Responsive --------------------------------------------------------- */
@media (max-width: 860px) {
:root { --sidebar-w: 0px; }
.sidebar { transform: translateX(-100%); }
.main-content { padding: 22px 18px; }
.task-create-grid { grid-template-columns: 1fr; }
}

View File

@@ -3,28 +3,38 @@ import api from '@/services/api'
import dayjs from 'dayjs'
// Types for Calendar entities
type SlotType = 'work' | 'on_call' | 'entertainment' | 'system'
type EventType = 'job' | 'entertainment' | 'system_event'
type SlotStatus = 'not_started' | 'ongoing' | 'deferred' | 'skipped' | 'paused' | 'finished' | 'aborted'
interface TimeSlotResponse {
slot_id: string // real int id or "plan-{planId}-{date}" for virtual
date: string
slot_type: 'work' | 'on_call' | 'entertainment' | 'system'
slot_type: SlotType
estimated_duration: number
scheduled_at: string // HH:mm
started_at: string | null
attended: boolean
actual_duration: number | null
event_type: 'job' | 'entertainment' | 'system_event' | null
event_type: EventType | null
event_data: Record<string, any> | null
priority: number
status: 'not_started' | 'ongoing' | 'deferred' | 'skipped' | 'paused' | 'finished' | 'aborted'
status: SlotStatus
plan_id: number | null
is_virtual: boolean
created_at: string | null
updated_at: string | null
}
interface DayViewResponse {
date: string
user_id: number
slots: TimeSlotResponse[]
}
interface SchedulePlanResponse {
id: number
slot_type: 'work' | 'on_call' | 'entertainment' | 'system'
slot_type: SlotType
estimated_duration: number
event_type: string | null
event_data: Record<string, any> | null
@@ -37,6 +47,64 @@ interface SchedulePlanResponse {
updated_at: string | null
}
interface PlanListResponse {
plans: SchedulePlanResponse[]
}
type Weekday = 'sun' | 'mon' | 'tue' | 'wed' | 'thu' | 'fri' | 'sat'
type MonthName = 'jan' | 'feb' | 'mar' | 'apr' | 'may' | 'jun' | 'jul' | 'aug' | 'sep' | 'oct' | 'nov' | 'dec'
interface WorkloadWarning {
period: string
slot_type: string
current: number
minimum: number
message: string
}
interface ScheduleResponse {
slot: TimeSlotResponse
warnings: WorkloadWarning[]
}
const SLOT_TYPES: { value: SlotType; label: string }[] = [
{ value: 'work', label: 'Work' },
{ value: 'on_call', label: 'On Call' },
{ value: 'entertainment', label: 'Entertainment' },
{ value: 'system', label: 'System' },
]
const EVENT_TYPES: { value: EventType; label: string }[] = [
{ value: 'job', label: 'Job' },
{ value: 'entertainment', label: 'Entertainment' },
{ value: 'system_event', label: 'System Event' },
]
const WEEKDAYS: { value: Weekday; label: string }[] = [
{ value: 'sun', label: 'Sunday' },
{ value: 'mon', label: 'Monday' },
{ value: 'tue', label: 'Tuesday' },
{ value: 'wed', label: 'Wednesday' },
{ value: 'thu', label: 'Thursday' },
{ value: 'fri', label: 'Friday' },
{ value: 'sat', label: 'Saturday' },
]
const MONTHS: { value: MonthName; label: string }[] = [
{ value: 'jan', label: 'January' },
{ value: 'feb', label: 'February' },
{ value: 'mar', label: 'March' },
{ value: 'apr', label: 'April' },
{ value: 'may', label: 'May' },
{ value: 'jun', label: 'June' },
{ value: 'jul', label: 'July' },
{ value: 'aug', label: 'August' },
{ value: 'sep', label: 'September' },
{ value: 'oct', label: 'October' },
{ value: 'nov', label: 'November' },
{ value: 'dec', label: 'December' },
]
const SLOT_TYPE_ICONS: Record<string, string> = {
work: '💼',
on_call: '📞',
@@ -62,12 +130,41 @@ export default function CalendarPage() {
const [activeTab, setActiveTab] = useState<'daily' | 'plans'>('daily')
const [error, setError] = useState('')
// Create/Edit slot modal state
const [showSlotModal, setShowSlotModal] = useState(false)
const [editingSlot, setEditingSlot] = useState<TimeSlotResponse | null>(null)
const [slotForm, setSlotForm] = useState({
slot_type: 'work' as SlotType,
scheduled_at: '09:00',
estimated_duration: 25,
event_type: '' as string,
event_data_code: '',
event_data_event: '',
priority: 50,
})
const [slotSaving, setSlotSaving] = useState(false)
const [warnings, setWarnings] = useState<WorkloadWarning[]>([])
const [showPlanModal, setShowPlanModal] = useState(false)
const [editingPlan, setEditingPlan] = useState<SchedulePlanResponse | null>(null)
const [planSaving, setPlanSaving] = useState(false)
const [planForm, setPlanForm] = useState({
slot_type: 'work' as SlotType,
estimated_duration: 25,
at_time: '09:00',
on_day: '' as Weekday | '',
on_week: '' as string,
on_month: '' as MonthName | '',
event_type: '' as string,
event_data_code: '',
event_data_event: '',
})
const fetchSlots = async (date: string) => {
setLoading(true)
setError('')
try {
const { data } = await api.get<TimeSlotResponse[]>(`/calendar/day?date=${date}`)
setSlots(data)
const { data } = await api.get<DayViewResponse>(`/calendar/day?date=${date}`)
setSlots(Array.isArray(data?.slots) ? data.slots : [])
} catch (err: any) {
setError(err.response?.data?.detail || 'Failed to load calendar')
setSlots([])
@@ -78,8 +175,8 @@ export default function CalendarPage() {
const fetchPlans = async () => {
try {
const { data } = await api.get<SchedulePlanResponse[]>('/calendar/plans')
setPlans(data)
const { data } = await api.get<PlanListResponse>('/calendar/plans')
setPlans(Array.isArray(data?.plans) ? data.plans : [])
} catch (err: any) {
console.error('Failed to load plans:', err)
}
@@ -100,17 +197,9 @@ export default function CalendarPage() {
setSelectedDate(e.target.value)
}
const goToday = () => {
setSelectedDate(dayjs().format('YYYY-MM-DD'))
}
const goPrev = () => {
setSelectedDate(dayjs(selectedDate).subtract(1, 'day').format('YYYY-MM-DD'))
}
const goNext = () => {
setSelectedDate(dayjs(selectedDate).add(1, 'day').format('YYYY-MM-DD'))
}
const goToday = () => setSelectedDate(dayjs().format('YYYY-MM-DD'))
const goPrev = () => setSelectedDate(dayjs(selectedDate).subtract(1, 'day').format('YYYY-MM-DD'))
const goNext = () => setSelectedDate(dayjs(selectedDate).add(1, 'day').format('YYYY-MM-DD'))
const formatPlanSchedule = (plan: SchedulePlanResponse) => {
const parts: string[] = [`at ${plan.at_time}`]
@@ -120,6 +209,221 @@ export default function CalendarPage() {
return parts.join(' · ')
}
// --- Slot create/edit ---
const openCreateSlotModal = () => {
setEditingSlot(null)
setSlotForm({
slot_type: 'work',
scheduled_at: '09:00',
estimated_duration: 25,
event_type: '',
event_data_code: '',
event_data_event: '',
priority: 50,
})
setWarnings([])
setError('')
setShowSlotModal(true)
}
const openEditSlotModal = (slot: TimeSlotResponse) => {
setEditingSlot(slot)
setSlotForm({
slot_type: slot.slot_type,
scheduled_at: slot.scheduled_at,
estimated_duration: slot.estimated_duration,
event_type: slot.event_type || '',
event_data_code: slot.event_data?.code || '',
event_data_event: slot.event_data?.event || '',
priority: slot.priority,
})
setWarnings([])
setError('')
setShowSlotModal(true)
}
const buildEventData = () => {
if (!slotForm.event_type) return null
if (slotForm.event_type === 'job') {
return slotForm.event_data_code ? { type: 'Task', code: slotForm.event_data_code } : null
}
if (slotForm.event_type === 'system_event') {
return slotForm.event_data_event ? { event: slotForm.event_data_event } : null
}
return null
}
const buildPlanEventData = () => {
if (!planForm.event_type) return null
if (planForm.event_type === 'job') {
return planForm.event_data_code ? { type: 'Task', code: planForm.event_data_code } : null
}
if (planForm.event_type === 'system_event') {
return planForm.event_data_event ? { event: planForm.event_data_event } : null
}
return null
}
const openCreatePlanModal = () => {
setEditingPlan(null)
setPlanForm({
slot_type: 'work',
estimated_duration: 25,
at_time: '09:00',
on_day: '',
on_week: '',
on_month: '',
event_type: '',
event_data_code: '',
event_data_event: '',
})
setError('')
setShowPlanModal(true)
}
const openEditPlanModal = (plan: SchedulePlanResponse) => {
setEditingPlan(plan)
setPlanForm({
slot_type: plan.slot_type,
estimated_duration: plan.estimated_duration,
at_time: plan.at_time.slice(0, 5),
on_day: (plan.on_day?.toLowerCase() as Weekday | undefined) || '',
on_week: plan.on_week ? String(plan.on_week) : '',
on_month: (plan.on_month?.toLowerCase() as MonthName | undefined) || '',
event_type: plan.event_type || '',
event_data_code: plan.event_data?.code || '',
event_data_event: plan.event_data?.event || '',
})
setError('')
setShowPlanModal(true)
}
const handleSavePlan = async () => {
setPlanSaving(true)
setError('')
try {
const payload: any = {
slot_type: planForm.slot_type,
estimated_duration: planForm.estimated_duration,
at_time: planForm.at_time,
on_day: planForm.on_day || null,
on_week: planForm.on_week ? Number(planForm.on_week) : null,
on_month: planForm.on_month || null,
event_type: planForm.event_type || null,
event_data: buildPlanEventData(),
}
if (editingPlan) {
await api.patch(`/calendar/plans/${editingPlan.id}`, payload)
} else {
await api.post('/calendar/plans', payload)
}
setShowPlanModal(false)
fetchPlans()
if (activeTab === 'daily') {
fetchSlots(selectedDate)
}
} catch (err: any) {
setError(err.response?.data?.detail || 'Save plan failed')
} finally {
setPlanSaving(false)
}
}
const handleSaveSlot = async () => {
setSlotSaving(true)
setError('')
setWarnings([])
try {
const payload: any = {
slot_type: slotForm.slot_type,
scheduled_at: slotForm.scheduled_at,
estimated_duration: slotForm.estimated_duration,
priority: slotForm.priority,
event_type: slotForm.event_type || null,
event_data: buildEventData(),
}
let response: any
if (editingSlot) {
// Edit existing slot
if (editingSlot.is_virtual) {
response = await api.patch(`/calendar/slots/virtual/${editingSlot.slot_id}`, payload)
} else if (editingSlot.slot_id) {
response = await api.patch(`/calendar/slots/${editingSlot.slot_id}`, payload)
} else {
throw new Error('Missing slot identifier for edit')
}
} else {
// Create new slot
payload.date = selectedDate
response = await api.post('/calendar/slots', payload)
}
// Check for warnings in response
if (response.data?.warnings && response.data.warnings.length > 0) {
setWarnings(response.data.warnings)
}
setShowSlotModal(false)
fetchSlots(selectedDate)
} catch (err: any) {
const detail = err.response?.data?.detail
if (typeof detail === 'string' && detail.toLowerCase().includes('overlap')) {
setError(`⚠️ Overlap conflict: ${detail}`)
} else if (detail && typeof detail === 'object') {
const message = typeof detail.message === 'string' ? detail.message : 'Save failed'
const conflicts = Array.isArray(detail.conflicts) ? detail.conflicts : []
if (conflicts.length > 0) {
const summary = conflicts
.map((conflict: any) => `${conflict.slot_type || 'slot'} at ${conflict.scheduled_at || 'unknown time'}`)
.join(', ')
setError(`⚠️ ${message}: ${summary}`)
} else {
setError(`⚠️ ${message}`)
}
} else {
setError(detail || 'Save failed')
}
} finally {
setSlotSaving(false)
}
}
// --- Slot cancel ---
const handleCancelSlot = async (slot: TimeSlotResponse) => {
if (!confirm(`Cancel this ${slot.slot_type} slot at ${slot.scheduled_at}?`)) return
setError('')
try {
if (slot.is_virtual) {
await api.post(`/calendar/slots/virtual/${slot.slot_id}/cancel`)
} else if (slot.slot_id) {
await api.post(`/calendar/slots/${slot.slot_id}/cancel`)
} else {
throw new Error('Missing slot identifier for cancel')
}
fetchSlots(selectedDate)
} catch (err: any) {
setError(err.response?.data?.detail || 'Cancel failed')
}
}
// --- Plan cancel ---
const handleCancelPlan = async (plan: SchedulePlanResponse) => {
if (!confirm(`Cancel plan #${plan.id}? This won't affect past materialized slots.`)) return
setError('')
try {
await api.post(`/calendar/plans/${plan.id}/cancel`)
fetchPlans()
} catch (err: any) {
setError(err.response?.data?.detail || 'Cancel plan failed')
}
}
// Check if a date is in the past
const isPastDate = dayjs(selectedDate).isBefore(dayjs().startOf('day'))
return (
<div className="calendar-page">
<div className="page-header" style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 }}>
@@ -144,6 +448,18 @@ export default function CalendarPage() {
{error && <div className="error-message" style={{ color: 'var(--danger)', marginBottom: 12 }}>{error}</div>}
{/* Workload warnings banner */}
{warnings.length > 0 && (
<div style={{ background: 'var(--warning-bg, #fff3cd)', border: '1px solid var(--warning-border, #ffc107)', borderRadius: 8, padding: 12, marginBottom: 12 }}>
<strong> Workload Warnings:</strong>
<ul style={{ margin: '4px 0 0 16px', padding: 0 }}>
{warnings.map((w, i) => (
<li key={i}>{w.message} ({w.period} {w.slot_type}: {w.current}/{w.minimum} min)</li>
))}
</ul>
</div>
)}
{activeTab === 'daily' && (
<>
{/* Date navigation */}
@@ -157,8 +473,18 @@ export default function CalendarPage() {
/>
<button className="btn-secondary" onClick={goNext}></button>
<button className="btn-transition" onClick={goToday}>Today</button>
{!isPastDate && (
<button className="btn-primary" onClick={openCreateSlotModal} style={{ marginLeft: 'auto' }}>+ New Slot</button>
)}
</div>
{/* Deferred slots notice */}
{slots.some(s => s.status === 'deferred') && (
<div style={{ background: 'var(--warning-bg, #fff3cd)', border: '1px solid var(--warning-border, #ffc107)', borderRadius: 8, padding: 10, marginBottom: 12, fontSize: '0.9rem' }}>
Some slots are <strong>deferred</strong> they were postponed due to scheduling conflicts or agent unavailability.
</div>
)}
{/* Slot list */}
{loading ? (
<div className="loading">Loading...</div>
@@ -196,6 +522,25 @@ export default function CalendarPage() {
📣 {slot.event_data.event}
</div>
)}
{/* Action buttons for non-past, modifiable slots */}
{!isPastDate && (slot.status === 'not_started' || slot.status === 'deferred') && (
<div style={{ marginTop: 8, display: 'flex', gap: 6 }}>
<button
className="btn-transition"
style={{ padding: '4px 10px', fontSize: '0.8rem' }}
onClick={() => openEditSlotModal(slot)}
>
Edit
</button>
<button
className="btn-danger"
style={{ padding: '4px 10px', fontSize: '0.8rem' }}
onClick={() => handleCancelSlot(slot)}
>
Cancel
</button>
</div>
)}
</div>
))}
</div>
@@ -204,7 +549,12 @@ export default function CalendarPage() {
)}
{activeTab === 'plans' && (
<div className="milestone-grid">
<>
<div style={{ display: 'flex', justifyContent: 'flex-end', marginBottom: 16 }}>
<button className="btn-primary" onClick={openCreatePlanModal}>+ New Plan</button>
</div>
<div className="milestone-grid">
{plans.length === 0 ? (
<div className="empty" style={{ padding: '40px 0', color: 'var(--text-secondary)', textAlign: 'center' }}>
No schedule plans configured.
@@ -223,9 +573,277 @@ export default function CalendarPage() {
<div> {plan.estimated_duration} min</div>
{plan.event_type && <div>📌 {plan.event_type.replace('_', ' ')}</div>}
</div>
{plan.is_active && (
<div style={{ marginTop: 8, display: 'flex', gap: 8 }}>
<button
className="btn-transition"
style={{ padding: '4px 10px', fontSize: '0.8rem' }}
onClick={() => openEditPlanModal(plan)}
>
Edit Plan
</button>
<button
className="btn-danger"
style={{ padding: '4px 10px', fontSize: '0.8rem' }}
onClick={() => handleCancelPlan(plan)}
>
Cancel Plan
</button>
</div>
)}
</div>
))
)}
</div>
</>
)}
{/* Create/Edit Slot Modal */}
{showSlotModal && (
<div className="modal-overlay" onClick={() => setShowSlotModal(false)}>
<div className="modal" onClick={(e) => e.stopPropagation()}>
<h3>{editingSlot ? 'Edit Slot' : 'New Slot'}</h3>
<p style={{ color: 'var(--text-secondary)', fontSize: '0.9rem' }}>
Date: <strong>{dayjs(selectedDate).format('MMMM D, YYYY')}</strong>
</p>
<label style={{ display: 'block', marginBottom: 8 }}>
<strong>Slot Type</strong>
<select
value={slotForm.slot_type}
onChange={(e) => setSlotForm({ ...slotForm, slot_type: e.target.value as SlotType })}
style={{ width: '100%', marginTop: 4 }}
>
{SLOT_TYPES.map((t) => (
<option key={t.value} value={t.value}>{t.label}</option>
))}
</select>
</label>
<label style={{ display: 'block', marginBottom: 8 }}>
<strong>Scheduled At</strong>
<input
type="time"
value={slotForm.scheduled_at}
onChange={(e) => setSlotForm({ ...slotForm, scheduled_at: e.target.value })}
style={{ width: '100%', marginTop: 4 }}
/>
</label>
<label style={{ display: 'block', marginBottom: 8 }}>
<strong>Estimated Duration (minutes, 150)</strong>
<input
type="number"
min={1}
max={50}
value={slotForm.estimated_duration}
onChange={(e) => setSlotForm({ ...slotForm, estimated_duration: Number(e.target.value) })}
style={{ width: '100%', marginTop: 4 }}
/>
</label>
<label style={{ display: 'block', marginBottom: 8 }}>
<strong>Priority (099)</strong>
<input
type="number"
min={0}
max={99}
value={slotForm.priority}
onChange={(e) => setSlotForm({ ...slotForm, priority: Number(e.target.value) })}
style={{ width: '100%', marginTop: 4 }}
/>
</label>
<label style={{ display: 'block', marginBottom: 8 }}>
<strong>Event Type</strong>
<select
value={slotForm.event_type}
onChange={(e) => setSlotForm({ ...slotForm, event_type: e.target.value })}
style={{ width: '100%', marginTop: 4 }}
>
<option value="">None</option>
{EVENT_TYPES.map((t) => (
<option key={t.value} value={t.value}>{t.label}</option>
))}
</select>
</label>
{slotForm.event_type === 'job' && (
<label style={{ display: 'block', marginBottom: 8 }}>
<strong>Job Code</strong>
<input
type="text"
value={slotForm.event_data_code}
onChange={(e) => setSlotForm({ ...slotForm, event_data_code: e.target.value })}
placeholder="e.g. TASK-42"
style={{ width: '100%', marginTop: 4 }}
/>
</label>
)}
{slotForm.event_type === 'system_event' && (
<label style={{ display: 'block', marginBottom: 8 }}>
<strong>System Event</strong>
<select
value={slotForm.event_data_event}
onChange={(e) => setSlotForm({ ...slotForm, event_data_event: e.target.value })}
style={{ width: '100%', marginTop: 4 }}
>
<option value="">Select event</option>
<option value="ScheduleToday">Schedule Today</option>
<option value="SummaryToday">Summary Today</option>
<option value="ScheduledGatewayRestart">Scheduled Gateway Restart</option>
</select>
</label>
)}
<div style={{ marginTop: 12, display: 'flex', gap: 8 }}>
<button
className="btn-primary"
onClick={handleSaveSlot}
disabled={slotSaving}
>
{slotSaving ? 'Saving...' : 'Save'}
</button>
<button className="btn-back" onClick={() => setShowSlotModal(false)}>Cancel</button>
</div>
</div>
</div>
)}
{showPlanModal && (
<div className="modal-overlay" onClick={() => setShowPlanModal(false)}>
<div className="modal" onClick={(e) => e.stopPropagation()}>
<h3>{editingPlan ? 'Edit Plan' : 'New Plan'}</h3>
<label style={{ display: 'block', marginBottom: 8 }}>
<strong>Slot Type</strong>
<select
value={planForm.slot_type}
onChange={(e) => setPlanForm({ ...planForm, slot_type: e.target.value as SlotType })}
style={{ width: '100%', marginTop: 4 }}
>
{SLOT_TYPES.map((t) => (
<option key={t.value} value={t.value}>{t.label}</option>
))}
</select>
</label>
<label style={{ display: 'block', marginBottom: 8 }}>
<strong>At Time</strong>
<input
type="time"
value={planForm.at_time}
onChange={(e) => setPlanForm({ ...planForm, at_time: e.target.value })}
style={{ width: '100%', marginTop: 4 }}
/>
</label>
<label style={{ display: 'block', marginBottom: 8 }}>
<strong>Estimated Duration (minutes, 150)</strong>
<input
type="number"
min={1}
max={50}
value={planForm.estimated_duration}
onChange={(e) => setPlanForm({ ...planForm, estimated_duration: Number(e.target.value) })}
style={{ width: '100%', marginTop: 4 }}
/>
</label>
<label style={{ display: 'block', marginBottom: 8 }}>
<strong>On Day (optional)</strong>
<select
value={planForm.on_day}
onChange={(e) => setPlanForm({ ...planForm, on_day: e.target.value as Weekday | '' })}
style={{ width: '100%', marginTop: 4 }}
>
<option value="">Every day</option>
{WEEKDAYS.map((d) => (
<option key={d.value} value={d.value}>{d.label}</option>
))}
</select>
</label>
<label style={{ display: 'block', marginBottom: 8 }}>
<strong>On Week (optional)</strong>
<select
value={planForm.on_week}
onChange={(e) => setPlanForm({ ...planForm, on_week: e.target.value })}
style={{ width: '100%', marginTop: 4 }}
>
<option value="">Every matching week</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
</label>
<label style={{ display: 'block', marginBottom: 8 }}>
<strong>On Month (optional)</strong>
<select
value={planForm.on_month}
onChange={(e) => setPlanForm({ ...planForm, on_month: e.target.value as MonthName | '' })}
style={{ width: '100%', marginTop: 4 }}
>
<option value="">Every month</option>
{MONTHS.map((m) => (
<option key={m.value} value={m.value}>{m.label}</option>
))}
</select>
</label>
<label style={{ display: 'block', marginBottom: 8 }}>
<strong>Event Type</strong>
<select
value={planForm.event_type}
onChange={(e) => setPlanForm({ ...planForm, event_type: e.target.value })}
style={{ width: '100%', marginTop: 4 }}
>
<option value="">None</option>
{EVENT_TYPES.map((t) => (
<option key={t.value} value={t.value}>{t.label}</option>
))}
</select>
</label>
{planForm.event_type === 'job' && (
<label style={{ display: 'block', marginBottom: 8 }}>
<strong>Job Code</strong>
<input
type="text"
value={planForm.event_data_code}
onChange={(e) => setPlanForm({ ...planForm, event_data_code: e.target.value })}
placeholder="e.g. TASK-42"
style={{ width: '100%', marginTop: 4 }}
/>
</label>
)}
{planForm.event_type === 'system_event' && (
<label style={{ display: 'block', marginBottom: 8 }}>
<strong>System Event</strong>
<select
value={planForm.event_data_event}
onChange={(e) => setPlanForm({ ...planForm, event_data_event: e.target.value })}
style={{ width: '100%', marginTop: 4 }}
>
<option value="">Select event</option>
<option value="ScheduleToday">Schedule Today</option>
<option value="SummaryToday">Summary Today</option>
<option value="ScheduledGatewayRestart">Scheduled Gateway Restart</option>
</select>
</label>
)}
<div style={{ marginTop: 12, display: 'flex', gap: 8 }}>
<button className="btn-primary" onClick={handleSavePlan} disabled={planSaving}>
{planSaving ? 'Saving...' : 'Save Plan'}
</button>
<button className="btn-back" onClick={() => setShowPlanModal(false)}>Cancel</button>
</div>
</div>
</div>
)}
</div>

View File

@@ -19,7 +19,7 @@ export default function CreateTaskPage() {
const [projects, setProjects] = useState<Project[]>([])
const [milestones, setMilestones] = useState<Milestone[]>([])
const [form, setForm] = useState({
title: '', description: '', project_id: 0, milestone_id: 0, task_type: 'issue', // P7.1: default changed from 'task' to 'issue'
title: '', description: '', project_code: '', milestone_code: '', task_type: 'issue', // P7.1: default changed from 'task' to 'issue'
task_subtype: '', priority: 'medium', tags: '', reporter_id: 1,
})
@@ -27,21 +27,21 @@ export default function CreateTaskPage() {
api.get<Project[]>('/projects').then(({ data }) => {
setProjects(data)
if (data.length) {
setForm((f) => ({ ...f, project_id: data[0].id }))
setForm((f) => ({ ...f, project_code: data[0].project_code || '' }))
// Load milestones for the first project
api.get<Milestone[]>(`/milestones?project_id=${data[0].id}`).then(({ data: ms }) => {
api.get<Milestone[]>(`/milestones?project_code=${data[0].project_code}`).then(({ data: ms }) => {
setMilestones(ms)
if (ms.length) setForm((f) => ({ ...f, milestone_id: ms[0].id }))
if (ms.length) setForm((f) => ({ ...f, milestone_code: ms[0].milestone_code || '' }))
})
}
})
}, [])
const handleProjectChange = (projectId: number) => {
setForm(f => ({ ...f, project_id: projectId, milestone_id: 0 }))
api.get<Milestone[]>(`/milestones?project_id=${projectId}`).then(({ data: ms }) => {
const handleProjectChange = (projectCode: string) => {
setForm(f => ({ ...f, project_code: projectCode, milestone_code: '' }))
api.get<Milestone[]>(`/milestones?project_code=${projectCode}`).then(({ data: ms }) => {
setMilestones(ms)
if (ms.length) setForm((f) => ({ ...f, milestone_id: ms[0].id }))
if (ms.length) setForm((f) => ({ ...f, milestone_code: ms[0].milestone_code || '' }))
})
}
@@ -54,7 +54,7 @@ export default function CreateTaskPage() {
const submit = async (e: React.FormEvent) => {
e.preventDefault()
if (!form.milestone_id) {
if (!form.milestone_code) {
alert('Please select a milestone')
return
}
@@ -71,14 +71,14 @@ export default function CreateTaskPage() {
<label>Title <input data-testid="task-title-input" required value={form.title} onChange={(e) => setForm({ ...form, title: e.target.value })} /></label>
<label>Description <textarea data-testid="task-description-input" value={form.description} onChange={(e) => setForm({ ...form, description: e.target.value })} /></label>
<label>Projects
<select data-testid="project-select" value={form.project_id} onChange={(e) => handleProjectChange(Number(e.target.value))}>
{projects.map((p) => <option key={p.id} value={p.id}>{p.name}</option>)}
<select data-testid="project-select" value={form.project_code} onChange={(e) => handleProjectChange(e.target.value)}>
{projects.map((p) => <option key={p.id} value={p.project_code || ''}>{p.name}</option>)}
</select>
</label>
<label>Milestone
<select data-testid="milestone-select" value={form.milestone_id} onChange={(e) => setForm({ ...form, milestone_id: Number(e.target.value) })}>
{milestones.length === 0 && <option value={0}>No milestones available</option>}
{milestones.map((m) => <option key={m.id} value={m.id}>{m.title}</option>)}
<select data-testid="milestone-select" value={form.milestone_code} onChange={(e) => setForm({ ...form, milestone_code: e.target.value })}>
{milestones.length === 0 && <option value="">No milestones available</option>}
{milestones.map((m) => <option key={m.id} value={m.milestone_code || ''}>{m.title}</option>)}
</select>
</label>
<label>Type

View File

@@ -1,4 +1,5 @@
import { useState, useEffect } from 'react'
import { Link } from 'react-router-dom'
import api from '@/services/api'
import type { DashboardStats, Task } from '@/types'
@@ -60,8 +61,8 @@ export default function DashboardPage() {
<tbody>
{(stats.recent_tasks || []).map((i) => (
<tr key={i.id}>
<td>{i.task_code || `#${i.id}`}</td>
<td><a href={`/tasks/${i.task_code || i.id}`}>{i.title}</a></td>
<td>{i.task_code || '—'}</td>
<td>{i.task_code ? <Link to={`/tasks/${i.task_code}`}>{i.title}</Link> : i.title}</td>
<td><span className={`badge status-${i.status}`}>{i.status}</span></td>
<td><span className={`badge priority-${i.priority}`}>{i.priority}</span></td>
<td>{i.task_type}</td><td>{i.task_subtype || "-"}</td>

View File

@@ -29,7 +29,7 @@ interface MeetingItem {
const STATUS_OPTIONS = ['scheduled', 'in_progress', 'completed', 'cancelled']
export default function MeetingDetailPage() {
const { meetingId } = useParams()
const { meetingCode } = useParams()
const navigate = useNavigate()
const { user } = useAuth()
const [meeting, setMeeting] = useState<MeetingItem | null>(null)
@@ -46,7 +46,7 @@ export default function MeetingDetailPage() {
const fetchMeeting = async () => {
try {
const { data } = await api.get<MeetingItem>(`/meetings/${meetingId}`)
const { data } = await api.get<MeetingItem>(`/meetings/${meetingCode}`)
setMeeting(data)
setEditForm({
title: data.title,
@@ -63,14 +63,14 @@ export default function MeetingDetailPage() {
useEffect(() => {
fetchMeeting()
}, [meetingId])
}, [meetingCode])
const handleAttend = async () => {
if (!meeting) return
setSaving(true)
setMessage('')
try {
const { data } = await api.post<MeetingItem>(`/meetings/${meetingId}/attend`)
const { data } = await api.post<MeetingItem>(`/meetings/${meetingCode}/attend`)
setMeeting(data)
setMessage('You have joined this meeting')
} catch (err: any) {
@@ -85,7 +85,7 @@ export default function MeetingDetailPage() {
setSaving(true)
setMessage('')
try {
const { data } = await api.patch<MeetingItem>(`/meetings/${meetingId}`, {
const { data } = await api.patch<MeetingItem>(`/meetings/${meetingCode}`, {
status: newStatus,
})
setMeeting(data)
@@ -117,7 +117,7 @@ export default function MeetingDetailPage() {
return
}
const { data } = await api.patch<MeetingItem>(`/meetings/${meetingId}`, payload)
const { data } = await api.patch<MeetingItem>(`/meetings/${meetingCode}`, payload)
setMeeting(data)
setEditMode(false)
setMessage('Meeting updated')
@@ -133,7 +133,7 @@ export default function MeetingDetailPage() {
if (!confirm(`Delete meeting ${meeting.meeting_code || meeting.id}? This cannot be undone.`)) return
setSaving(true)
try {
await api.delete(`/meetings/${meetingId}`)
await api.delete(`/meetings/${meetingCode}`)
navigate(-1)
} catch (err: any) {
setMessage(err.response?.data?.detail || 'Failed to delete meeting')

View File

@@ -24,7 +24,7 @@ interface MilestoneTask {
}
export default function MilestoneDetailPage() {
const { id } = useParams()
const { milestoneCode } = useParams()
const navigate = useNavigate()
const { user } = useAuth()
const [milestone, setMilestone] = useState<Milestone | null>(null)
@@ -49,7 +49,8 @@ export default function MilestoneDetailPage() {
const [preflight, setPreflight] = useState<{ freeze?: { allowed: boolean; reason: string | null }; start?: { allowed: boolean; reason: string | null } } | null>(null)
const fetchMilestone = () => {
api.get<Milestone>(`/milestones/${id}`).then(({ data }) => {
if (!milestoneCode) return
api.get<Milestone>(`/milestones/${milestoneCode}`).then(({ data }) => {
setMilestone(data)
if (data.project_id) {
api.get<Project>(`/projects/${data.project_id}`).then(({ data: proj }) => {
@@ -57,40 +58,44 @@ export default function MilestoneDetailPage() {
setProjectCode(proj.project_code || '')
})
api.get<ProjectMember[]>(`/projects/${data.project_id}/members`).then(({ data }) => setMembers(data)).catch(() => {})
fetchPreflight(data.project_id, data.id)
if (data.project_code && data.milestone_code) {
fetchPreflight(data.project_code, data.milestone_code)
}
}
if (data.milestone_code) {
api.get<MilestoneProgress>(`/milestones/${data.milestone_code}/progress`).then(({ data: prog }) => setProgress(prog)).catch(() => {})
}
api.get<MilestoneProgress>(`/milestones/${data.id}/progress`).then(({ data: prog }) => setProgress(prog)).catch(() => {})
})
}
const fetchPreflight = (projectId: number, milestoneId: number) => {
api.get(`/projects/${projectId}/milestones/${milestoneId}/actions/preflight`)
const fetchPreflight = (projectCode: string, milestoneCode: string) => {
api.get(`/projects/${projectCode}/milestones/${milestoneCode}/actions/preflight`)
.then(({ data }) => setPreflight(data))
.catch(() => setPreflight(null))
}
useEffect(() => {
fetchMilestone()
}, [id])
}, [milestoneCode])
const refreshMilestoneItems = () => {
if (!projectCode || !milestone) return
api.get<MilestoneTask[]>(`/tasks/${projectCode}/${milestone.id}`).then(({ data }) => setTasks(data)).catch(() => {})
api.get<any[]>(`/supports/${projectCode}/${milestone.id}`).then(({ data }) => setSupports(data)).catch(() => {})
api.get<any[]>(`/meetings/${projectCode}/${milestone.id}`).then(({ data }) => setMeetings(data)).catch(() => {})
if (!projectCode || !milestone?.milestone_code) return
api.get<MilestoneTask[]>(`/tasks/${projectCode}/${milestone.milestone_code}`).then(({ data }) => setTasks(data)).catch(() => {})
api.get<any[]>(`/supports/${projectCode}/${milestone.milestone_code}`).then(({ data }) => setSupports(data)).catch(() => {})
api.get<any[]>(`/meetings/${projectCode}/${milestone.milestone_code}`).then(({ data }) => setMeetings(data)).catch(() => {})
}
useEffect(() => {
refreshMilestoneItems()
}, [projectCode, milestone?.id])
}, [projectCode, milestone?.milestone_code])
const createItem = async (type: 'supports' | 'meetings') => {
if (!newTitle.trim() || !projectCode || !milestone) return
if (!newTitle.trim() || !projectCode || !milestone?.milestone_code) return
const payload = {
title: newTitle,
description: newDesc || null,
}
await api.post(`/${type}/${projectCode}/${milestone.id}`, payload)
await api.post(`/${type}/${projectCode}/${milestone.milestone_code}`, payload)
setNewTitle('')
setNewDesc('')
setShowCreateSupport(false)
@@ -119,10 +124,12 @@ export default function MilestoneDetailPage() {
setActionLoading(action)
setActionError(null)
try {
await api.post(`/projects/${project.id}/milestones/${milestone.id}/actions/${action}`, body ?? {})
await api.post(`/projects/${project.project_code}/milestones/${milestone.milestone_code}/actions/${action}`, body ?? {})
fetchMilestone()
refreshMilestoneItems()
fetchPreflight(project.id, milestone.id)
if (project.project_code && milestone.milestone_code) {
fetchPreflight(project.project_code, milestone.milestone_code)
}
} catch (err: any) {
const detail = err?.response?.data?.detail
setActionError(typeof detail === 'string' ? detail : `${action} failed`)
@@ -142,8 +149,8 @@ export default function MilestoneDetailPage() {
if (!milestone) return <div className="loading">Loading...</div>
const renderTaskRow = (t: MilestoneTask) => (
<tr key={t.id} className="clickable" onClick={() => navigate(`/tasks/${t.task_code || t.id}`)}>
<td>{t.task_code || t.id}</td>
<tr key={t.id} className={t.task_code ? 'clickable' : ''} onClick={() => t.task_code && navigate(`/tasks/${t.task_code}`)}>
<td>{t.task_code || '—'}</td>
<td className="task-title">{t.title}</td>
<td><span className={`badge status-${t.task_status || t.status}`}>{t.task_status || t.status}</span></td>
<td>{t.estimated_effort || '-'}</td>
@@ -297,8 +304,8 @@ export default function MilestoneDetailPage() {
<CreateTaskModal
isOpen={showCreateTask}
onClose={() => setShowCreateTask(false)}
initialProjectId={milestone.project_id}
initialMilestoneId={milestone.id}
initialProjectCode={milestone.project_code || ''}
initialMilestoneCode={milestone.milestone_code || ''}
lockProject
lockMilestone
onCreated={() => {
@@ -356,8 +363,8 @@ export default function MilestoneDetailPage() {
<thead><tr><th>Code</th><th>Title</th><th>Status</th><th>Priority</th></tr></thead>
<tbody>
{supports.map((i) => (
<tr key={i.id} className="clickable" onClick={() => navigate(`/supports/${i.support_code || i.id}`)}>
<td>{i.support_code || i.id}</td>
<tr key={i.id} className={i.support_code ? 'clickable' : ''} onClick={() => i.support_code && navigate(`/supports/${i.support_code}`)}>
<td>{i.support_code || '—'}</td>
<td className="task-title">{i.title}</td>
<td><span className={`badge status-${i.status}`}>{i.status}</span></td>
<td><span className={`badge priority-${i.priority}`}>{i.priority}</span></td>
@@ -373,8 +380,8 @@ export default function MilestoneDetailPage() {
<thead><tr><th>Code</th><th>Title</th><th>Status</th><th>Priority</th></tr></thead>
<tbody>
{meetings.map((i) => (
<tr key={i.id} className="clickable" onClick={() => navigate(`/meetings/${i.meeting_code || i.id}`)}>
<td>{i.meeting_code || i.id}</td>
<tr key={i.id} className={i.meeting_code ? 'clickable' : ''} onClick={() => i.meeting_code && navigate(`/meetings/${i.meeting_code}`)}>
<td>{i.meeting_code || '—'}</td>
<td className="task-title">{i.title}</td>
<td><span className={`badge status-${i.status}`}>{i.status}</span></td>
<td><span className={`badge priority-${i.priority}`}>{i.priority}</span></td>

View File

@@ -13,7 +13,7 @@ export default function MilestonesPage() {
const navigate = useNavigate()
const fetchMilestones = () => {
const params = projectFilter ? `?project_id=${projectFilter}` : ''
const params = projectFilter ? `?project_code=${projectFilter}` : ''
api.get<Milestone[]>(`/milestones${params}`).then(({ data }) => setMilestones(data))
}
@@ -35,21 +35,21 @@ export default function MilestonesPage() {
<div className="filters">
<select value={projectFilter} onChange={(e) => setProjectFilter(e.target.value)}>
<option value="">All projects</option>
{projects.map((p) => <option key={p.id} value={p.id}>{p.name}</option>)}
{projects.map((p) => <option key={p.id} value={p.project_code || ''}>{p.name}</option>)}
</select>
</div>
<MilestoneFormModal
isOpen={showCreate}
onClose={() => setShowCreate(false)}
initialProjectId={projectFilter ? Number(projectFilter) : undefined}
initialProjectCode={projectFilter || undefined}
lockProject={Boolean(projectFilter)}
onSaved={() => fetchMilestones()}
/>
<div className="milestone-grid">
{milestones.map((ms) => (
<div key={ms.id} className="milestone-card" onClick={() => navigate(`/milestones/${ms.milestone_code || ms.id}`)}>
<div key={ms.id} className="milestone-card" onClick={() => ms.milestone_code && navigate(`/milestones/${ms.milestone_code}`)}>
<div className="milestone-card-header">
<span className={`badge status-${ms.status}`}>{ms.status}</span>
<h3>{ms.title}</h3>{ms.milestone_code && <span className="badge" style={{ marginLeft: 8, fontSize: '0.75em' }}>{ms.milestone_code}</span>}

View File

@@ -52,7 +52,7 @@ export default function NotificationsPage() {
className={`notification-item ${n.is_read ? 'read' : 'unread'}`}
onClick={() => {
if (!n.is_read) markRead(n.id)
if (n.task_id) navigate(`/tasks/${n.task_id}`)
if (n.task_code) navigate(`/tasks/${n.task_code}`)
}}
>
<div className="notification-dot">{n.is_read ? '' : '●'}</div>

View File

@@ -114,7 +114,7 @@ export default function ProjectDetailPage() {
{canEditProject && <button className="btn-sm" onClick={() => setShowMilestoneModal(true)}>+ New</button>}
</h3>
{milestones.map((ms) => (
<div key={ms.id} className="milestone-item" onClick={() => navigate(`/milestones/${ms.milestone_code || ms.id}`)}>
<div key={ms.id} className="milestone-item" onClick={() => ms.milestone_code && navigate(`/milestones/${ms.milestone_code}`)}>
<span className={`badge status-${ms.status === 'open' ? 'open' : ms.status === 'closed' ? 'closed' : 'in_progress'}`}>{ms.status}</span>
<span className="milestone-title">{ms.title}</span>
{ms.due_date && <span className="text-dim"> · Due {dayjs(ms.due_date).format('YYYY-MM-DD')}</span>}
@@ -136,7 +136,7 @@ export default function ProjectDetailPage() {
<MilestoneFormModal
isOpen={showMilestoneModal}
onClose={() => setShowMilestoneModal(false)}
initialProjectId={project.id}
initialProjectCode={project.project_code || ''}
lockProject
onSaved={() => fetchProject()}
/>

View File

@@ -6,15 +6,15 @@ import dayjs from 'dayjs'
import CopyableCode from '@/components/CopyableCode'
export default function ProposalDetailPage() {
const { id } = useParams()
const { proposalCode } = useParams()
const [searchParams] = useSearchParams()
const projectId = searchParams.get('project_id')
const projectCode = searchParams.get('project_code')
const navigate = useNavigate()
const [proposal, setProposal] = useState<Proposal | null>(null)
const [milestones, setMilestones] = useState<Milestone[]>([])
const [showAccept, setShowAccept] = useState(false)
const [selectedMilestone, setSelectedMilestone] = useState<number | ''>('')
const [selectedMilestone, setSelectedMilestone] = useState<string>('')
const [actionLoading, setActionLoading] = useState(false)
const [error, setError] = useState('')
@@ -37,38 +37,38 @@ export default function ProposalDetailPage() {
const [essentialLoading, setEssentialLoading] = useState(false)
const fetchProposal = () => {
if (!projectId) return
api.get<Proposal>(`/projects/${projectId}/proposals/${id}`).then(({ data }) => setProposal(data))
if (!projectCode || !proposalCode) return
api.get<Proposal>(`/projects/${projectCode}/proposals/${proposalCode}`).then(({ data }) => setProposal(data))
}
useEffect(() => {
fetchProposal()
}, [id, projectId])
}, [proposalCode, projectCode])
const loadMilestones = () => {
if (!projectId) return
api.get<Milestone[]>(`/milestones?project_id=${projectId}`)
if (!projectCode) return
api.get<Milestone[]>(`/milestones?project_code=${projectCode}`)
.then(({ data }) => setMilestones(data.filter((m) => m.status === 'open')))
}
const fetchEssentials = () => {
if (!projectId || !id) return
if (!projectCode || !proposalCode) return
setLoadingEssentials(true)
api.get<Essential[]>(`/projects/${projectId}/proposals/${id}/essentials`)
api.get<Essential[]>(`/projects/${projectCode}/proposals/${proposalCode}/essentials`)
.then(({ data }) => setEssentials(data))
.finally(() => setLoadingEssentials(false))
}
useEffect(() => {
fetchEssentials()
}, [id, projectId])
}, [proposalCode, projectCode])
const handleAccept = async () => {
if (!selectedMilestone || !projectId) return
if (!selectedMilestone || !projectCode || !proposalCode) return
setActionLoading(true)
setError('')
try {
await api.post(`/projects/${projectId}/proposals/${id}/accept`, { milestone_id: selectedMilestone })
await api.post(`/projects/${projectCode}/proposals/${proposalCode}/accept`, { milestone_code: selectedMilestone })
setShowAccept(false)
fetchProposal()
} catch (err: any) {
@@ -79,12 +79,12 @@ export default function ProposalDetailPage() {
}
const handleReject = async () => {
if (!projectId) return
if (!projectCode || !proposalCode) return
const reason = prompt('Reject reason (optional):')
setActionLoading(true)
setError('')
try {
await api.post(`/projects/${projectId}/proposals/${id}/reject`, { reason: reason || undefined })
await api.post(`/projects/${projectCode}/proposals/${proposalCode}/reject`, { reason: reason || undefined })
fetchProposal()
} catch (err: any) {
setError(err.response?.data?.detail || 'Reject failed')
@@ -102,11 +102,11 @@ export default function ProposalDetailPage() {
}
const handleEdit = async () => {
if (!projectId) return
if (!projectCode || !proposalCode) return
setEditLoading(true)
setError('')
try {
await api.patch(`/projects/${projectId}/proposals/${id}`, {
await api.patch(`/projects/${projectCode}/proposals/${proposalCode}`, {
title: editTitle,
description: editDescription,
})
@@ -120,11 +120,11 @@ export default function ProposalDetailPage() {
}
const handleReopen = async () => {
if (!projectId) return
if (!projectCode || !proposalCode) return
setActionLoading(true)
setError('')
try {
await api.post(`/projects/${projectId}/proposals/${id}/reopen`)
await api.post(`/projects/${projectCode}/proposals/${proposalCode}/reopen`)
fetchProposal()
} catch (err: any) {
setError(err.response?.data?.detail || 'Reopen failed')
@@ -151,18 +151,18 @@ export default function ProposalDetailPage() {
}
const handleSaveEssential = async () => {
if (!projectId || !id) return
if (!projectCode || !proposalCode) return
setEssentialLoading(true)
setError('')
try {
if (editingEssential) {
await api.patch(`/projects/${projectId}/proposals/${id}/essentials/${editingEssential.id}`, {
await api.patch(`/projects/${projectCode}/proposals/${proposalCode}/essentials/${editingEssential.essential_code}`, {
title: essentialTitle,
type: essentialType,
description: essentialDesc || null,
})
} else {
await api.post(`/projects/${projectId}/proposals/${id}/essentials`, {
await api.post(`/projects/${projectCode}/proposals/${proposalCode}/essentials`, {
title: essentialTitle,
type: essentialType,
description: essentialDesc || null,
@@ -177,12 +177,12 @@ export default function ProposalDetailPage() {
}
}
const handleDeleteEssential = async (essentialId: number) => {
if (!projectId || !id) return
const handleDeleteEssential = async (essentialCode: string) => {
if (!projectCode || !proposalCode) return
if (!confirm('Are you sure you want to delete this Essential?')) return
setEssentialLoading(true)
try {
await api.delete(`/projects/${projectId}/proposals/${id}/essentials/${essentialId}`)
await api.delete(`/projects/${projectCode}/proposals/${proposalCode}/essentials/${essentialCode}`)
fetchEssentials()
} catch (err: any) {
setError(err.response?.data?.detail || 'Delete failed')
@@ -266,7 +266,7 @@ export default function ProposalDetailPage() {
<button
className="btn-danger"
style={{ padding: '4px 8px', fontSize: '0.8rem' }}
onClick={() => handleDeleteEssential(e.id)}
onClick={() => handleDeleteEssential(e.essential_code)}
>
Delete
</button>
@@ -291,7 +291,7 @@ export default function ProposalDetailPage() {
<div
key={gt.task_id}
className="milestone-card"
onClick={() => navigate(`/tasks/${gt.task_code || gt.task_id}`)}
onClick={() => gt.task_code && navigate(`/tasks/${gt.task_code}`)}
style={{ cursor: 'pointer' }}
>
<div className="milestone-card-header">
@@ -387,11 +387,11 @@ export default function ProposalDetailPage() {
<p>Select an <strong>open</strong> milestone to generate story tasks in:</p>
<select
value={selectedMilestone}
onChange={(e) => setSelectedMilestone(Number(e.target.value))}
onChange={(e) => setSelectedMilestone(e.target.value)}
>
<option value=""> Select milestone </option>
{milestones.map((ms) => (
<option key={ms.id} value={ms.id}>{ms.title}</option>
<option key={ms.id} value={ms.milestone_code || ''}>{ms.title}</option>
))}
</select>
{milestones.length === 0 && (

View File

@@ -64,7 +64,7 @@ export default function ProposalsPage() {
<div className="filters">
<select value={projectFilter} onChange={(e) => setProjectFilter(e.target.value)}>
<option value="">Select a project</option>
{projects.map((p) => <option key={p.id} value={p.id}>{p.name}</option>)}
{projects.map((p) => <option key={p.id} value={p.project_code || ''}>{p.name}</option>)}
</select>
</div>
@@ -72,7 +72,7 @@ export default function ProposalsPage() {
<div className="milestone-grid">
{proposals.map((pr) => (
<div key={pr.id} className="milestone-card" onClick={() => navigate(`/proposals/${pr.proposal_code || pr.id}?project_id=${pr.project_id}`)}>
<div key={pr.id} className="milestone-card" onClick={() => pr.proposal_code && pr.project_code && navigate(`/proposals/${pr.proposal_code}?project_code=${pr.project_code}`)}>
<div className="milestone-card-header">
<span className={`badge ${statusBadgeClass(pr.status)}`}>{pr.status}</span>
{pr.proposal_code && <span className="badge">{pr.proposal_code}</span>}

View File

@@ -2,7 +2,7 @@ import { useState } from 'react'
import axios from 'axios'
interface Props {
wizardBase: string
initialWizardPort: number | null
onComplete: () => void
}
@@ -11,55 +11,53 @@ interface SetupForm {
admin_password: string
admin_email: string
admin_full_name: string
db_host: string
db_port: number
db_user: string
db_password: string
db_database: string
backend_base_url: string
project_name: string
project_description: string
}
const STEPS = ['Welcome', 'Database', 'Admin', 'Backend', 'Finish']
const STEPS = ['Wizard', 'Admin', 'Backend', 'Finish']
export default function SetupWizardPage({ wizardBase, onComplete }: Props) {
export default function SetupWizardPage({ initialWizardPort, onComplete }: Props) {
const [step, setStep] = useState(0)
const [error, setError] = useState('')
const [saving, setSaving] = useState(false)
const [wizardOk, setWizardOk] = useState<boolean | null>(null)
const [connecting, setConnecting] = useState(false)
const [wizardPortInput, setWizardPortInput] = useState<string>(
initialWizardPort ? String(initialWizardPort) : ''
)
const [wizardBase, setWizardBase] = useState<string>('')
const [form, setForm] = useState<SetupForm>({
admin_username: 'admin',
admin_password: '',
admin_email: '',
admin_full_name: 'Admin',
db_host: 'mysql',
db_port: 3306,
db_user: 'harborforge',
db_password: 'harborforge_pass',
db_database: 'harborforge',
backend_base_url: 'http://backend:8000',
backend_base_url: '',
project_name: '',
project_description: '',
})
const wizardApi = axios.create({
baseURL: wizardBase,
timeout: 5000,
})
const set = (key: keyof SetupForm, value: string | number) =>
setForm((f) => ({ ...f, [key]: value }))
const checkWizard = async () => {
setError('')
const port = Number(wizardPortInput)
if (!port || port <= 0 || port > 65535) {
setError('Please enter a valid wizard port (1-65535).')
return
}
const base = `http://127.0.0.1:${port}`
setConnecting(true)
try {
await wizardApi.get('/health')
setWizardOk(true)
await axios.get(`${base}/health`, { timeout: 5000 })
setWizardBase(base)
localStorage.setItem('HF_WIZARD_PORT', String(port))
setStep(1)
} catch {
setWizardOk(false)
setError(`Unable to connect to AbstractWizard (${wizardBase}).\nPlease ensure the SSH tunnel is configured:\nssh -L <wizard_port>:127.0.0.1:<wizard_port> user@server`)
setError(`Unable to connect to AbstractWizard at ${base}.\nMake sure the SSH tunnel is up:\nssh -L ${port}:127.0.0.1:${port} user@server`)
} finally {
setConnecting(false)
}
}
@@ -75,25 +73,19 @@ export default function SetupWizardPage({ wizardBase, onComplete }: Props) {
email: form.admin_email,
full_name: form.admin_full_name,
},
database: {
host: form.db_host,
port: form.db_port,
user: form.db_user,
password: form.db_password,
database: form.db_database,
},
backend_url: form.backend_base_url || undefined,
}
await wizardApi.put('/api/v1/config/harborforge.json', config, {
await axios.put(`${wizardBase}/api/v1/config/harborforge.json`, config, {
headers: { 'Content-Type': 'application/json' },
timeout: 5000,
})
if (form.backend_base_url) {
localStorage.setItem('HF_BACKEND_BASE_URL', form.backend_base_url)
}
setStep(4)
setStep(3)
} catch (err: any) {
setError(`Failed to save configuration: ${err.message}`)
} finally {
@@ -117,45 +109,38 @@ export default function SetupWizardPage({ wizardBase, onComplete }: Props) {
{error && <div className="setup-error">{error}</div>}
{/* Step 0: Welcome */}
{/* Step 0: Wizard connection */}
{step === 0 && (
<div className="setup-step-content">
<h2>Welcome to HarborForge</h2>
<p>Agent/Human collaborative task management platform</p>
<h2>Connect to AbstractWizard</h2>
<p className="text-dim">Enter the local port that forwards to AbstractWizard, then test the connection.</p>
<div className="setup-info">
<p> The setup wizard connects to AbstractWizard via SSH tunnel. Ensure the port is forwarded:</p>
<p> AbstractWizard is reached over an SSH tunnel. Forward the port first:</p>
<code>ssh -L &lt;wizard_port&gt;:127.0.0.1:&lt;wizard_port&gt; user@your-server</code>
</div>
<button className="btn-primary" onClick={checkWizard}>
Connect to Wizard
</button>
{wizardOk === false && (
<p className="setup-hint">Connection failed. Check the SSH tunnel.</p>
)}
</div>
)}
{/* Step 1: Database */}
{step === 1 && (
<div className="setup-step-content">
<h2>Database configuration</h2>
<p className="text-dim">Configure MySQL connection (docker-compose defaults are fine if using the bundled MySQL).</p>
<div className="setup-form">
<label>Host <input value={form.db_host} onChange={(e) => set('db_host', e.target.value)} /></label>
<label>Port <input type="number" value={form.db_port} onChange={(e) => set('db_port', Number(e.target.value))} /></label>
<label>Username <input value={form.db_user} onChange={(e) => set('db_user', e.target.value)} /></label>
<label>Password <input type="password" value={form.db_password} onChange={(e) => set('db_password', e.target.value)} /></label>
<label>Database <input value={form.db_database} onChange={(e) => set('db_database', e.target.value)} /></label>
<label>
Wizard port
<input
type="number"
value={wizardPortInput}
min={1}
max={65535}
onChange={(e) => setWizardPortInput(e.target.value)}
placeholder="e.g. 8080"
/>
</label>
</div>
<div className="setup-nav">
<button className="btn-back" onClick={() => setStep(0)}>Back</button>
<button className="btn-primary" onClick={() => setStep(2)}>Next</button>
<button className="btn-primary" onClick={checkWizard} disabled={connecting}>
{connecting ? 'Connecting...' : 'Test connection & continue'}
</button>
</div>
</div>
)}
{/* Step 2: Admin */}
{step === 2 && (
{/* Step 1: Admin */}
{step === 1 && (
<div className="setup-step-content">
<h2>Admin account</h2>
<p className="text-dim">Create the first admin user</p>
@@ -166,26 +151,26 @@ export default function SetupWizardPage({ wizardBase, onComplete }: Props) {
<label>Full name <input value={form.admin_full_name} onChange={(e) => set('admin_full_name', e.target.value)} /></label>
</div>
<div className="setup-nav">
<button className="btn-back" onClick={() => setStep(1)}>Back</button>
<button className="btn-back" onClick={() => setStep(0)}>Back</button>
<button className="btn-primary" onClick={() => {
if (!form.admin_password) { setError('Please set an admin password'); return }
setError('')
setStep(3)
setStep(2)
}}>Next</button>
</div>
</div>
)}
{/* Step 3: Backend */}
{step === 3 && (
{/* Step 2: Backend */}
{step === 2 && (
<div className="setup-step-content">
<h2>Backend URL</h2>
<p className="text-dim">Configure the HarborForge backend API URL</p>
<p className="text-dim">Configure the HarborForge backend API URL (leave blank to use the frontend default).</p>
<div className="setup-form">
<label>Backend Base URL <input value={form.backend_base_url} onChange={(e) => set('backend_base_url', e.target.value)} placeholder="http://backend:8000" /></label>
</div>
<div className="setup-nav">
<button className="btn-back" onClick={() => setStep(2)}>Back</button>
<button className="btn-back" onClick={() => setStep(1)}>Back</button>
<button className="btn-primary" onClick={saveConfig} disabled={saving}>
{saving ? 'Saving...' : 'Finish setup'}
</button>
@@ -193,8 +178,8 @@ export default function SetupWizardPage({ wizardBase, onComplete }: Props) {
</div>
)}
{/* Step 4: Done */}
{step === 4 && (
{/* Step 3: Done */}
{step === 3 && (
<div className="setup-step-content">
<div className="setup-done">
<h2> Setup complete!</h2>

View File

@@ -27,7 +27,7 @@ const STATUS_OPTIONS = ['open', 'in_progress', 'resolved', 'closed']
const PRIORITY_OPTIONS = ['low', 'medium', 'high', 'critical']
export default function SupportDetailPage() {
const { supportId } = useParams()
const { supportCode } = useParams()
const navigate = useNavigate()
const { user } = useAuth()
const [support, setSupport] = useState<SupportItem | null>(null)
@@ -40,7 +40,7 @@ export default function SupportDetailPage() {
const fetchSupport = async () => {
try {
const { data } = await api.get<SupportItem>(`/supports/${supportId}`)
const { data } = await api.get<SupportItem>(`/supports/${supportCode}`)
setSupport(data)
setEditForm({
title: data.title,
@@ -56,14 +56,14 @@ export default function SupportDetailPage() {
useEffect(() => {
fetchSupport()
}, [supportId])
}, [supportCode])
const handleTake = async () => {
if (!support) return
setSaving(true)
setMessage('')
try {
const { data } = await api.post<SupportItem>(`/supports/${supportId}/take`)
const { data } = await api.post<SupportItem>(`/supports/${supportCode}/take`)
setSupport(data)
setMessage('You have taken this support ticket')
} catch (err: any) {
@@ -78,7 +78,7 @@ export default function SupportDetailPage() {
setSaving(true)
setMessage('')
try {
const { data } = await api.post<SupportItem>(`/supports/${supportId}/transition`, {
const { data } = await api.post<SupportItem>(`/supports/${supportCode}/transition`, {
status: transitionStatus,
})
setSupport(data)
@@ -106,7 +106,7 @@ export default function SupportDetailPage() {
return
}
const { data } = await api.patch<SupportItem>(`/supports/${supportId}`, payload)
const { data } = await api.patch<SupportItem>(`/supports/${supportCode}`, payload)
setSupport(data)
setEditMode(false)
setMessage('Support ticket updated')
@@ -122,7 +122,7 @@ export default function SupportDetailPage() {
if (!confirm(`Delete support ticket ${support.support_code || support.id}? This cannot be undone.`)) return
setSaving(true)
try {
await api.delete(`/supports/${supportId}`)
await api.delete(`/supports/${supportCode}`)
navigate(-1)
} catch (err: any) {
setMessage(err.response?.data?.detail || 'Failed to delete support ticket')

View File

@@ -8,7 +8,7 @@ import CreateTaskModal from '@/components/CreateTaskModal'
import CopyableCode from '@/components/CopyableCode'
export default function TaskDetailPage() {
const { id } = useParams()
const { taskCode } = useParams()
const navigate = useNavigate()
const { user } = useAuth()
const [task, setTask] = useState<Task | null>(null)
@@ -26,27 +26,30 @@ export default function TaskDetailPage() {
const [closeReason, setCloseReason] = useState('')
const refreshTask = async () => {
const { data } = await api.get<Task>(`/tasks/${id}`)
if (!taskCode) return
const { data } = await api.get<Task>(`/tasks/${taskCode}`)
setTask(data)
if (data.project_id) {
api.get<Project>(`/projects/${data.project_id}`).then(({ data }) => setProject(data)).catch(() => {})
api.get<ProjectMember[]>(`/projects/${data.project_id}/members`).then(({ data }) => setMembers(data)).catch(() => {})
}
if (data.milestone_id) {
api.get<Milestone>(`/milestones/${data.milestone_id}`).then(({ data }) => setMilestone(data)).catch(() => {})
if (data.milestone_code) {
api.get<Milestone>(`/milestones/${data.milestone_code}`).then(({ data }) => setMilestone(data)).catch(() => {})
}
}
useEffect(() => {
refreshTask().catch(console.error)
api.get<Comment[]>(`/tasks/${id}/comments`).then(({ data }) => setComments(data))
}, [id])
if (taskCode) {
api.get<Comment[]>(`/tasks/${taskCode}/comments`).then(({ data }) => setComments(data))
}
}, [taskCode])
const addComment = async () => {
if (!newComment.trim() || !task) return
await api.post('/comments', { content: newComment, task_id: task.id, author_id: 1 })
setNewComment('')
const { data } = await api.get<Comment[]>(`/tasks/${id}/comments`)
const { data } = await api.get<Comment[]>(`/tasks/${taskCode}/comments`)
setComments(data)
}
@@ -54,10 +57,10 @@ export default function TaskDetailPage() {
setActionLoading(actionName)
setActionError(null)
try {
await api.post(`/tasks/${id}/transition?new_status=${newStatus}`, body || {})
await api.post(`/tasks/${taskCode}/transition?new_status=${newStatus}`, body || {})
await refreshTask()
// refresh comments too (finish adds one via backend)
const { data } = await api.get<Comment[]>(`/tasks/${id}/comments`)
const { data } = await api.get<Comment[]>(`/tasks/${taskCode}/comments`)
setComments(data)
} catch (err: any) {
setActionError(err?.response?.data?.detail || err?.message || 'Action failed')

View File

@@ -64,8 +64,8 @@ export default function TasksPage() {
</thead>
<tbody>
{tasks.map((t) => (
<tr key={t.id} onClick={() => navigate(`/tasks/${t.task_code || t.id}`)} className="clickable">
<td>{t.task_code || t.id}</td>
<tr key={t.id} onClick={() => t.task_code && navigate(`/tasks/${t.task_code}`)} className={t.task_code ? 'clickable' : ''}>
<td>{t.task_code || '—'}</td>
<td className="task-title">{t.title}</td>
<td><span className="badge" style={{ backgroundColor: statusColors[t.status] || '#ccc' }}>{t.status}</span></td>
<td><span className={`badge priority-${t.priority}`}>{t.priority}</span></td>

View File

@@ -1,7 +1,7 @@
import axios from 'axios'
const getApiBase = () => {
return localStorage.getItem('HF_BACKEND_BASE_URL') || import.meta.env.VITE_API_BASE || 'http://127.0.0.1:8000'
const getApiBase = (): string | undefined => {
return localStorage.getItem('HF_BACKEND_BASE_URL') ?? undefined
}
const api = axios.create({

317
src/test/calendar.test.tsx Normal file
View File

@@ -0,0 +1,317 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import { render, screen, waitFor, fireEvent, cleanup } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import CalendarPage from '@/pages/CalendarPage'
const mockGet = vi.fn()
const mockPost = vi.fn()
vi.mock('@/services/api', () => ({
default: {
get: (...args: any[]) => mockGet(...args),
post: (...args: any[]) => mockPost(...args),
},
}))
type Slot = {
slot_id: string
date: string
slot_type: 'work' | 'on_call' | 'entertainment' | 'system'
estimated_duration: number
scheduled_at: string
started_at: string | null
attended: boolean
actual_duration: number | null
event_type: 'job' | 'entertainment' | 'system_event' | null
event_data: Record<string, any> | null
priority: number
status: 'not_started' | 'ongoing' | 'deferred' | 'skipped' | 'paused' | 'finished' | 'aborted'
plan_id: number | null
is_virtual: boolean
created_at: string | null
updated_at: string | null
}
type Plan = {
id: number
slot_type: 'work' | 'on_call' | 'entertainment' | 'system'
estimated_duration: number
event_type: string | null
event_data: Record<string, any> | null
at_time: string
on_day: string | null
on_week: number | null
on_month: string | null
is_active: boolean
created_at: string
updated_at: string | null
}
const slots: Slot[] = [
{
slot_id: '1',
date: '2026-04-01',
slot_type: 'work',
estimated_duration: 25,
scheduled_at: '09:00',
started_at: null,
attended: false,
actual_duration: null,
event_type: 'job',
event_data: { type: 'Task', code: 'TASK-1' },
priority: 50,
status: 'not_started',
plan_id: null,
is_virtual: false,
created_at: '2026-04-01T00:00:00Z',
updated_at: '2026-04-01T00:00:00Z',
},
{
slot_id: 'plan-5-2026-04-01',
date: '2026-04-01',
slot_type: 'on_call',
estimated_duration: 30,
scheduled_at: '14:00',
started_at: null,
attended: false,
actual_duration: null,
event_type: null,
event_data: null,
priority: 70,
status: 'deferred',
plan_id: 5,
is_virtual: true,
created_at: null,
updated_at: null,
},
]
const plans: Plan[] = [
{
id: 5,
slot_type: 'on_call',
estimated_duration: 30,
event_type: null,
event_data: null,
at_time: '14:00',
on_day: 'Mon',
on_week: null,
on_month: null,
is_active: true,
created_at: '2026-03-01T00:00:00Z',
updated_at: null,
},
{
id: 6,
slot_type: 'work',
estimated_duration: 50,
event_type: 'system_event',
event_data: { event: 'ScheduleToday' },
at_time: '08:00',
on_day: 'Tue',
on_week: 1,
on_month: null,
is_active: false,
created_at: '2026-03-01T00:00:00Z',
updated_at: null,
},
]
function setupApi(options?: {
slots?: Slot[]
plans?: Plan[]
dayError?: string
postImpl?: (url: string, payload?: any) => any
}) {
const currentSlots = options?.slots ?? slots
const currentPlans = options?.plans ?? plans
mockGet.mockImplementation((url: string) => {
if (url.startsWith('/calendar/day')) {
if (options?.dayError) {
return Promise.reject({ response: { data: { detail: options.dayError } } })
}
return Promise.resolve({ data: currentSlots })
}
if (url === '/calendar/plans') {
return Promise.resolve({ data: currentPlans })
}
return Promise.reject(new Error(`Unhandled GET ${url}`))
})
mockPost.mockImplementation((url: string, payload?: any) => {
if (options?.postImpl) return options.postImpl(url, payload)
return Promise.resolve({ data: {} })
})
}
describe('CalendarPage', () => {
beforeEach(() => {
vi.clearAllMocks()
setupApi()
vi.spyOn(window, 'confirm').mockReturnValue(true)
})
afterEach(() => {
cleanup()
vi.restoreAllMocks()
})
it('renders daily slots, deferred notice, and virtual-plan badge', async () => {
render(<CalendarPage />)
expect(await screen.findByText('09:00')).toBeInTheDocument()
expect(screen.getByText('14:00')).toBeInTheDocument()
expect(screen.getAllByText(/deferred/i).length).toBeGreaterThan(0)
expect(screen.getByText(/agent unavailability/i)).toBeInTheDocument()
expect(screen.getByText(/TASK-1/i)).toBeInTheDocument()
expect(screen.getByText(/^plan$/i)).toBeInTheDocument()
expect(screen.getByText(/Priority: 50/i)).toBeInTheDocument()
})
it('renders plans tab content', async () => {
render(<CalendarPage />)
await screen.findByText('09:00')
await userEvent.click(screen.getByRole('button', { name: /Plans \(2\)/i }))
expect(await screen.findByText(/Plan #5/i)).toBeInTheDocument()
expect(screen.getByText(/Plan #6/i)).toBeInTheDocument()
expect(screen.getByText(/at 14:00 · on Mon/i)).toBeInTheDocument()
expect(screen.getByText(/inactive/i)).toBeInTheDocument()
})
it('opens create modal and toggles event-specific fields', async () => {
render(<CalendarPage />)
await screen.findByText('09:00')
await userEvent.click(screen.getByRole('button', { name: /\+ New Slot/i }))
expect(screen.getByRole('heading', { name: /New Slot/i })).toBeInTheDocument()
const selects = screen.getAllByRole('combobox')
const eventTypeSelect = selects[1]
fireEvent.change(eventTypeSelect, { target: { value: 'job' } })
expect(screen.getByLabelText(/Job Code/i)).toBeInTheDocument()
fireEvent.change(eventTypeSelect, { target: { value: 'system_event' } })
expect(screen.getByLabelText(/System Event/i)).toBeInTheDocument()
})
it('submits new slot and displays workload warnings', async () => {
setupApi({
postImpl: (url: string) => {
if (url === '/calendar/schedule') {
return Promise.resolve({
data: {
slot: slots[0],
warnings: [
{
period: 'daily',
slot_type: 'work',
current: 25,
minimum: 120,
message: 'Daily work minimum not met',
},
],
},
})
}
return Promise.resolve({ data: {} })
},
})
render(<CalendarPage />)
await screen.findByText('09:00')
await userEvent.click(screen.getByRole('button', { name: /\+ New Slot/i }))
await userEvent.click(screen.getByRole('button', { name: /^Save$/i }))
await waitFor(() => {
expect(mockPost).toHaveBeenCalledWith(
'/calendar/schedule',
expect.objectContaining({
slot_type: 'work',
scheduled_at: '09:00',
estimated_duration: 25,
priority: 50,
date: '2026-04-01',
}),
)
})
expect(await screen.findByText(/Workload Warnings/i)).toBeInTheDocument()
expect(screen.getByText(/Daily work minimum not met/i)).toBeInTheDocument()
})
it('shows overlap error when save fails with overlap detail', async () => {
setupApi({
postImpl: (url: string) => {
if (url === '/calendar/schedule') {
return Promise.reject({
response: { data: { detail: 'Slot overlap with existing slot at 09:00' } },
})
}
return Promise.resolve({ data: {} })
},
})
render(<CalendarPage />)
await screen.findByText('09:00')
await userEvent.click(screen.getByRole('button', { name: /\+ New Slot/i }))
await userEvent.click(screen.getByRole('button', { name: /^Save$/i }))
expect(await screen.findByText(/Overlap conflict/i)).toBeInTheDocument()
})
it('opens edit modal with existing slot values and submits edit request', async () => {
setupApi({
postImpl: (url: string) => {
if (url.startsWith('/calendar/edit')) {
return Promise.resolve({ data: { slot: slots[0], warnings: [] } })
}
return Promise.resolve({ data: {} })
},
})
render(<CalendarPage />)
await screen.findByText('09:00')
await userEvent.click(screen.getAllByRole('button', { name: /✏️ Edit/i })[0])
expect(screen.getByRole('heading', { name: /Edit Slot/i })).toBeInTheDocument()
expect((screen.getAllByRole('combobox')[0] as HTMLSelectElement).value).toBe('work')
expect((document.querySelector('input[type="time"]') as HTMLInputElement).value).toBe('09:00')
await userEvent.click(screen.getByRole('button', { name: /^Save$/i }))
await waitFor(() => {
expect(mockPost).toHaveBeenCalledWith(
expect.stringContaining('/calendar/edit?date=2026-04-01&slot_id=1'),
expect.objectContaining({ slot_type: 'work' }),
)
})
})
it('cancels a slot after confirmation', async () => {
render(<CalendarPage />)
await screen.findByText('09:00')
await userEvent.click(screen.getAllByRole('button', { name: /❌ Cancel/i })[0])
await waitFor(() => {
expect(window.confirm).toHaveBeenCalled()
expect(mockPost).toHaveBeenCalledWith('/calendar/cancel?date=2026-04-01&slot_id=1')
})
})
it('shows fetch error banner when day loading fails', async () => {
setupApi({ dayError: 'Failed to load calendar' })
render(<CalendarPage />)
expect(await screen.findByText(/Failed to load calendar/i)).toBeInTheDocument()
})
})

View File

@@ -0,0 +1,525 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import { render, screen, waitFor, fireEvent, cleanup } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import ProposalDetailPage from '@/pages/ProposalDetailPage'
import { MemoryRouter, Routes, Route } from 'react-router-dom'
const mockGet = vi.fn()
const mockPost = vi.fn()
const mockPatch = vi.fn()
const mockDelete = vi.fn()
vi.mock('@/services/api', () => ({
default: {
get: (...args: any[]) => mockGet(...args),
post: (...args: any[]) => mockPost(...args),
patch: (...args: any[]) => mockPatch(...args),
delete: (...args: any[]) => mockDelete(...args),
},
}))
const mockNavigate = vi.fn()
vi.mock('react-router-dom', async () => {
const actual = await vi.importActual('react-router-dom')
return {
...actual,
useNavigate: () => mockNavigate,
useParams: () => ({ id: '1' }),
useSearchParams: () => [new URLSearchParams('?project_id=1'), vi.fn()],
}
})
type Essential = {
id: number
essential_code: string
proposal_id: number
type: 'feature' | 'improvement' | 'refactor'
title: string
description: string | null
created_by_id: number | null
created_at: string
updated_at: string | null
}
type Proposal = {
id: number
proposal_code: string | null
title: string
description: string | null
status: 'open' | 'accepted' | 'rejected'
project_id: number
created_by_id: number | null
created_by_username: string | null
feat_task_id: string | null
essentials: Essential[] | null
generated_tasks: any[] | null
created_at: string
updated_at: string | null
}
type Milestone = {
id: number
title: string
status: 'open' | 'freeze' | 'undergoing' | 'completed' | 'closed'
}
const mockProposal: Proposal = {
id: 1,
proposal_code: 'PROP-001',
title: 'Test Proposal',
description: 'Test description',
status: 'open',
project_id: 1,
created_by_id: 1,
created_by_username: 'admin',
feat_task_id: null,
essentials: [],
generated_tasks: null,
created_at: '2026-03-01T00:00:00Z',
updated_at: null,
}
const mockEssentials: Essential[] = [
{
id: 1,
essential_code: 'ESS-001',
proposal_id: 1,
type: 'feature',
title: 'Feature Essential',
description: 'A feature essential',
created_by_id: 1,
created_at: '2026-03-01T00:00:00Z',
updated_at: null,
},
{
id: 2,
essential_code: 'ESS-002',
proposal_id: 1,
type: 'improvement',
title: 'Improvement Essential',
description: null,
created_by_id: 1,
created_at: '2026-03-01T00:00:00Z',
updated_at: null,
},
]
const mockMilestones: Milestone[] = [
{ id: 1, title: 'Milestone 1', status: 'open' },
{ id: 2, title: 'Milestone 2', status: 'open' },
]
function setupApi(options?: {
proposal?: Proposal
essentials?: Essential[]
milestones?: Milestone[]
error?: string
}) {
const proposal = options?.proposal ?? mockProposal
const essentials = options?.essentials ?? mockEssentials
const milestones = options?.milestones ?? mockMilestones
mockGet.mockImplementation((url: string) => {
if (url.includes('/proposals/1') && !url.includes('/essentials')) {
if (options?.error) {
return Promise.reject({ response: { data: { detail: options.error } } })
}
return Promise.resolve({ data: proposal })
}
if (url.includes('/essentials')) {
return Promise.resolve({ data: essentials })
}
if (url.includes('/milestones')) {
return Promise.resolve({ data: milestones })
}
return Promise.reject(new Error(`Unhandled GET ${url}`))
})
mockPost.mockResolvedValue({ data: {} })
mockPatch.mockResolvedValue({ data: {} })
mockDelete.mockResolvedValue({ data: {} })
}
describe('ProposalDetailPage', () => {
beforeEach(() => {
vi.clearAllMocks()
setupApi()
vi.spyOn(window, 'confirm').mockReturnValue(true)
})
afterEach(() => {
cleanup()
vi.restoreAllMocks()
})
describe('Essential List Display', () => {
it('renders essentials section with count', async () => {
render(<ProposalDetailPage />)
await waitFor(() => {
expect(screen.getByText('Essentials (2)')).toBeInTheDocument()
})
})
it('displays essential cards with type badges', async () => {
render(<ProposalDetailPage />)
await waitFor(() => {
expect(screen.getByText('Feature Essential')).toBeInTheDocument()
})
expect(screen.getByText('Improvement Essential')).toBeInTheDocument()
expect(screen.getByText('feature')).toBeInTheDocument()
expect(screen.getByText('improvement')).toBeInTheDocument()
})
it('displays essential codes', async () => {
render(<ProposalDetailPage />)
await waitFor(() => {
expect(screen.getByText('ESS-001')).toBeInTheDocument()
})
expect(screen.getByText('ESS-002')).toBeInTheDocument()
})
it('displays essential descriptions when available', async () => {
render(<ProposalDetailPage />)
await waitFor(() => {
expect(screen.getByText('A feature essential')).toBeInTheDocument()
})
})
it('shows empty state when no essentials', async () => {
setupApi({ essentials: [] })
render(<ProposalDetailPage />)
await waitFor(() => {
expect(screen.getByText('Essentials (0)')).toBeInTheDocument()
})
expect(screen.getByText(/No essentials yet/)).toBeInTheDocument()
expect(screen.getByText(/Add one to define deliverables/)).toBeInTheDocument()
})
it('shows loading state for essentials', async () => {
mockGet.mockImplementation((url: string) => {
if (url.includes('/proposals/1') && !url.includes('/essentials')) {
return Promise.resolve({ data: mockProposal })
}
if (url.includes('/essentials')) {
return new Promise(() => {}) // Never resolve
}
return Promise.reject(new Error(`Unhandled GET ${url}`))
})
render(<ProposalDetailPage />)
await waitFor(() => {
expect(screen.getByText(/Loading/i)).toBeInTheDocument()
})
})
})
describe('Essential Create/Edit Forms', () => {
it('opens create essential modal', async () => {
render(<ProposalDetailPage />)
await waitFor(() => {
expect(screen.getByText('+ New Essential')).toBeInTheDocument()
})
await userEvent.click(screen.getByText('+ New Essential'))
expect(screen.getByRole('heading', { name: 'New Essential' })).toBeInTheDocument()
expect(screen.getByPlaceholderText('Essential title')).toBeInTheDocument()
expect(screen.getByText('Feature')).toBeInTheDocument()
expect(screen.getByText('Improvement')).toBeInTheDocument()
expect(screen.getByText('Refactor')).toBeInTheDocument()
})
it('creates new essential', async () => {
render(<ProposalDetailPage />)
await waitFor(() => {
expect(screen.getByText('+ New Essential')).toBeInTheDocument()
})
await userEvent.click(screen.getByText('+ New Essential'))
await userEvent.type(screen.getByPlaceholderText('Essential title'), 'New Test Essential')
fireEvent.change(screen.getAllByRole('combobox')[0], { target: { value: 'refactor' } })
await userEvent.type(screen.getByPlaceholderText('Description (optional)'), 'Test description')
await userEvent.click(screen.getByRole('button', { name: 'Save' }))
await waitFor(() => {
expect(mockPost).toHaveBeenCalledWith(
'/projects/1/proposals/1/essentials',
expect.objectContaining({
title: 'New Test Essential',
type: 'refactor',
description: 'Test description',
})
)
})
})
it('opens edit essential modal with pre-filled data', async () => {
render(<ProposalDetailPage />)
await waitFor(() => {
expect(screen.getByText('Feature Essential')).toBeInTheDocument()
})
const editButtons = screen.getAllByRole('button', { name: 'Edit' })
await userEvent.click(editButtons[0])
expect(screen.getByRole('heading', { name: 'Edit Essential' })).toBeInTheDocument()
const titleInput = screen.getByDisplayValue('Feature Essential')
expect(titleInput).toBeInTheDocument()
const descriptionInput = screen.getByDisplayValue('A feature essential')
expect(descriptionInput).toBeInTheDocument()
})
it('updates essential', async () => {
render(<ProposalDetailPage />)
await waitFor(() => {
expect(screen.getByText('Feature Essential')).toBeInTheDocument()
})
const editButtons = screen.getAllByRole('button', { name: 'Edit' })
await userEvent.click(editButtons[0])
const titleInput = screen.getByDisplayValue('Feature Essential')
await userEvent.clear(titleInput)
await userEvent.type(titleInput, 'Updated Essential Title')
await userEvent.click(screen.getByRole('button', { name: 'Save' }))
await waitFor(() => {
expect(mockPatch).toHaveBeenCalledWith(
'/projects/1/proposals/1/essentials/1',
expect.objectContaining({
title: 'Updated Essential Title',
type: 'feature',
description: 'A feature essential',
})
)
})
})
it('deletes essential after confirmation', async () => {
render(<ProposalDetailPage />)
await waitFor(() => {
expect(screen.getByText('Feature Essential')).toBeInTheDocument()
})
const deleteButtons = screen.getAllByRole('button', { name: 'Delete' })
await userEvent.click(deleteButtons[0])
await waitFor(() => {
expect(window.confirm).toHaveBeenCalledWith('Are you sure you want to delete this Essential?')
})
await waitFor(() => {
expect(mockDelete).toHaveBeenCalledWith('/projects/1/proposals/1/essentials/1')
})
})
it('disables save button when title is empty', async () => {
render(<ProposalDetailPage />)
await waitFor(() => {
expect(screen.getByText('+ New Essential')).toBeInTheDocument()
})
await userEvent.click(screen.getByText('+ New Essential'))
const saveButton = screen.getByRole('button', { name: 'Save' })
expect(saveButton).toBeDisabled()
await userEvent.type(screen.getByPlaceholderText('Essential title'), 'Some Title')
expect(saveButton).toBeEnabled()
await userEvent.clear(screen.getByPlaceholderText('Essential title'))
expect(saveButton).toBeDisabled()
})
})
describe('Accept with Milestone Selection', () => {
it('opens accept modal with milestone selector', async () => {
render(<ProposalDetailPage />)
const acceptButton = await screen.findByRole('button', { name: /accept/i })
await userEvent.click(acceptButton)
expect(screen.getByRole('heading', { name: 'Accept Proposal' })).toBeInTheDocument()
expect(screen.getByText(/milestone to generate story tasks/i)).toBeInTheDocument()
expect(screen.getByRole('combobox')).toBeInTheDocument()
})
it('disables confirm button without milestone selection', async () => {
render(<ProposalDetailPage />)
const acceptButton = await screen.findByRole('button', { name: /accept/i })
await userEvent.click(acceptButton)
const confirmButton = screen.getByRole('button', { name: 'Confirm Accept' })
expect(confirmButton).toBeDisabled()
})
it('enables confirm button after milestone selection', async () => {
render(<ProposalDetailPage />)
const acceptButton = await screen.findByRole('button', { name: /accept/i })
await userEvent.click(acceptButton)
const select = screen.getByRole('combobox')
fireEvent.change(select, { target: { value: '1' } })
const confirmButton = screen.getByRole('button', { name: 'Confirm Accept' })
expect(confirmButton).toBeEnabled()
})
it('calls accept API with selected milestone', async () => {
render(<ProposalDetailPage />)
const acceptButton = await screen.findByRole('button', { name: /accept/i })
await userEvent.click(acceptButton)
const select = screen.getByRole('combobox')
fireEvent.change(select, { target: { value: '1' } })
await userEvent.click(screen.getByRole('button', { name: 'Confirm Accept' }))
await waitFor(() => {
expect(mockPost).toHaveBeenCalledWith(
'/projects/1/proposals/1/accept',
{ milestone_id: 1 }
)
})
})
it('shows warning when no open milestones available', async () => {
setupApi({ milestones: [] })
render(<ProposalDetailPage />)
const acceptButton = await screen.findByRole('button', { name: /accept/i })
await userEvent.click(acceptButton)
expect(screen.getByText('No open milestones available.')).toBeInTheDocument()
})
it('displays generated tasks after accept', async () => {
const acceptedProposal: Proposal = {
...mockProposal,
status: 'accepted',
generated_tasks: [
{ task_id: 1, task_code: 'TASK-001', title: 'Story Task 1', task_type: 'story', task_subtype: 'feature' },
{ task_id: 2, task_code: 'TASK-002', title: 'Story Task 2', task_type: 'story', task_subtype: 'improvement' },
],
}
setupApi({ proposal: acceptedProposal })
render(<ProposalDetailPage />)
await waitFor(() => {
expect(screen.getByText('Generated Tasks')).toBeInTheDocument()
})
expect(screen.getByText('Story Task 1')).toBeInTheDocument()
expect(screen.getByText('Story Task 2')).toBeInTheDocument()
expect(screen.getByText('story/feature')).toBeInTheDocument()
expect(screen.getByText('story/improvement')).toBeInTheDocument()
})
})
describe('Story Creation Restriction UI', () => {
it('hides essential controls for accepted proposal', async () => {
const acceptedProposal: Proposal = {
...mockProposal,
status: 'accepted',
essentials: mockEssentials,
}
setupApi({ proposal: acceptedProposal })
render(<ProposalDetailPage />)
await screen.findByText('Feature Essential')
expect(screen.queryByText('+ New Essential')).not.toBeInTheDocument()
})
it('hides edit/delete buttons for essentials when proposal is accepted', async () => {
const acceptedProposal: Proposal = {
...mockProposal,
status: 'accepted',
essentials: mockEssentials,
}
setupApi({ proposal: acceptedProposal })
render(<ProposalDetailPage />)
await waitFor(() => {
expect(screen.getByText('Feature Essential')).toBeInTheDocument()
})
const deleteButtons = screen.queryAllByRole('button', { name: 'Delete' })
expect(deleteButtons.length).toBe(0)
})
it('hides edit/delete buttons for rejected proposal', async () => {
const rejectedProposal: Proposal = {
...mockProposal,
status: 'rejected',
essentials: mockEssentials,
}
setupApi({ proposal: rejectedProposal })
render(<ProposalDetailPage />)
await screen.findByRole('button', { name: /reopen/i })
expect(screen.queryByText('+ New Essential')).not.toBeInTheDocument()
})
})
describe('Error Handling', () => {
it('displays error message on essential create failure', async () => {
mockPost.mockRejectedValue({ response: { data: { detail: 'Failed to create essential' } } })
render(<ProposalDetailPage />)
await waitFor(() => {
expect(screen.getByText('+ New Essential')).toBeInTheDocument()
})
await userEvent.click(screen.getByText('+ New Essential'))
await userEvent.type(screen.getByPlaceholderText('Essential title'), 'Test')
await userEvent.click(screen.getByRole('button', { name: 'Save' }))
await waitFor(() => {
expect(screen.getByText('Failed to create essential')).toBeInTheDocument()
})
})
it('displays error message on accept failure', async () => {
mockPost.mockRejectedValue({ response: { data: { detail: 'Accept failed: milestone required' } } })
render(<ProposalDetailPage />)
const acceptButton = await screen.findByRole('button', { name: /accept/i })
await userEvent.click(acceptButton)
fireEvent.change(screen.getByRole('combobox'), { target: { value: '1' } })
await userEvent.click(screen.getByRole('button', { name: 'Confirm Accept' }))
await waitFor(() => {
expect(screen.getByText('Accept failed: milestone required')).toBeInTheDocument()
})
})
})
})

58
src/test/setup.ts Normal file
View File

@@ -0,0 +1,58 @@
import '@testing-library/jest-dom'
import { vi } from 'vitest'
// Mock localStorage
const localStorageMock = {
getItem: vi.fn((key: string) => {
if (key === 'token') return 'mock-token'
if (key === 'HF_BACKEND_BASE_URL') return 'http://localhost:8000'
return null
}),
setItem: vi.fn(),
removeItem: vi.fn(),
clear: vi.fn(),
}
vi.stubGlobal('localStorage', localStorageMock)
// Mock window.location
Object.defineProperty(window, 'location', {
configurable: true,
value: Object.defineProperties({}, {
pathname: { value: '/calendar', writable: true },
href: { value: 'http://localhost/calendar', writable: true },
assign: { value: vi.fn(), writable: true },
replace: { value: vi.fn(), writable: true },
}) as any,
})
// Mock matchMedia
Object.defineProperty(window, 'matchMedia', {
writable: true,
value: vi.fn().mockImplementation((query: string) => ({
matches: false,
media: query,
onchange: null,
addListener: vi.fn(),
removeListener: vi.fn(),
addEventListener: vi.fn(),
removeEventListener: vi.fn(),
dispatchEvent: vi.fn(),
})),
})
// Mock ResizeObserver
class ResizeObserverMock {
observe() {}
unobserve() {}
disconnect() {}
}
vi.stubGlobal('ResizeObserver', ResizeObserverMock)
// Mock IntersectionObserver
class IntersectionObserverMock {
constructor() {}
observe() {}
unobserve() {}
disconnect() {}
}
vi.stubGlobal('IntersectionObserver', IntersectionObserverMock)

View File

@@ -36,6 +36,8 @@ export interface ProjectMember {
export interface Task {
id: number
task_code: string | null
project_code?: string | null
milestone_code?: string | null
title: string
description: string | null
task_type: 'issue' | 'maintenance' | 'research' | 'review' | 'story' | 'test' | 'resolution' // P7.1: 'task' removed
@@ -69,6 +71,7 @@ export interface Comment {
export interface Milestone {
id: number
milestone_code: string | null
project_code?: string | null
title: string
description: string | null
status: 'open' | 'freeze' | 'undergoing' | 'completed' | 'closed'
@@ -106,6 +109,7 @@ export interface Notification {
message: string
is_read: boolean
task_id: number | null
task_code?: string | null
created_at: string
}
@@ -134,6 +138,7 @@ export interface Proposal {
description: string | null
status: 'open' | 'accepted' | 'rejected'
project_id: number
project_code?: string | null
created_by_id: number | null
created_by_username: string | null
feat_task_id: string | null

1
src/vite-env.d.ts vendored
View File

@@ -2,7 +2,6 @@
interface ImportMetaEnv {
readonly VITE_API_BASE: string
readonly VITE_WIZARD_PORT: string
}
interface ImportMeta {

View File

@@ -19,4 +19,11 @@ export default defineConfig({
},
},
},
test: {
globals: true,
environment: 'jsdom',
setupFiles: './src/test/setup.ts',
css: true,
include: ['src/test/**/*.test.{ts,tsx}'],
},
})