Compare commits
25 Commits
b838c66bb1
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
668397104a
|
|||
|
0446e8f8a7
|
|||
|
975225e650
|
|||
|
704f11cec3
|
|||
|
07f11fa94e
|
|||
|
73ad1ed788
|
|||
|
9dbe18caea
|
|||
|
8344bf016f
|
|||
|
a8e170f7e1
|
|||
|
bb2c2cbc52
|
|||
|
6575ce8f44
|
|||
|
07bf4c2112
|
|||
|
9473ce24bc
|
|||
|
c78a35377a
|
|||
|
0af53c9b55
|
|||
|
3900dff5a1
|
|||
|
f29d9669f8
|
|||
|
e82a39f2e4
|
|||
|
9905234b34
|
|||
|
fc88b8f005
|
|||
|
96a363d28f
|
|||
|
6c9746eb05
|
|||
|
c2b0a4fea2
|
|||
|
22fae34b55
|
|||
|
0711a792ab
|
14
.claude/memory/feedback_tests.md
Normal file
14
.claude/memory/feedback_tests.md
Normal file
@@ -0,0 +1,14 @@
|
||||
---
|
||||
name: Always include tests with changes
|
||||
description: All code changes must include appropriate tests; never ship untested code
|
||||
type: feedback
|
||||
---
|
||||
|
||||
All changes (new features, bug fixes, refactors) must include tests as part of the same implementation. Do not ship code without accompanying tests.
|
||||
|
||||
**Why:** User explicitly called out that tests were missing from Issue #1 implementation and expects tests to always accompany changes going forward.
|
||||
|
||||
**How to apply:**
|
||||
- Go backend: add `_test.go` files alongside changed packages, using `httptest` for handler tests and a real (or in-memory) DB for store tests
|
||||
- Frontend: add `.test.tsx` files alongside new/changed pages and components using React Testing Library
|
||||
- Tests go in the same PR/commit as the code they cover — never as a follow-up
|
||||
@@ -6,7 +6,11 @@
|
||||
"Bash(go build ./...)",
|
||||
"Bash(go vet ./...)",
|
||||
"Bash(go test -count=1 -v -coverprofile=coverage.out ./...)",
|
||||
"Bash(go tool cover -func=coverage.out)"
|
||||
"Bash(go tool cover -func=coverage.out)",
|
||||
"Bash(tea issue:*)",
|
||||
"Bash(go test:*)",
|
||||
"Bash(npm test:*)",
|
||||
"Bash(go vet:*)"
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
195
.claude/skills/actions-runs/SKILL.md
Normal file
195
.claude/skills/actions-runs/SKILL.md
Normal file
@@ -0,0 +1,195 @@
|
||||
---
|
||||
name: actions-runs
|
||||
description: Fetch and monitor Gitea Actions CI results for a PR or branch
|
||||
dependencies: tea
|
||||
---
|
||||
|
||||
# Gitea Actions Run Monitoring
|
||||
|
||||
Guide for inspecting CI workflow runs using the `tea actions runs` CLI.
|
||||
|
||||
## Table of Contents
|
||||
|
||||
- [Listing Runs](#listing-runs)
|
||||
- [Viewing a Run](#viewing-a-run)
|
||||
- [Viewing Logs](#viewing-logs)
|
||||
- [Managing Workflows](#managing-workflows)
|
||||
- [Common Workflows](#common-workflows)
|
||||
|
||||
## Listing Runs
|
||||
|
||||
```bash
|
||||
# List recent runs (default: last 30)
|
||||
tea actions runs ls --repo thatguygriff/walkies
|
||||
|
||||
# Filter by branch (use this to find runs for a PR's branch)
|
||||
tea actions runs ls --branch feature/my-branch --repo thatguygriff/walkies
|
||||
|
||||
# Filter by status
|
||||
tea actions runs ls --status failure --repo thatguygriff/walkies
|
||||
tea actions runs ls --status success --repo thatguygriff/walkies
|
||||
tea actions runs ls --status in_progress --repo thatguygriff/walkies
|
||||
# Valid statuses: success, failure, pending, queued, in_progress, skipped, canceled
|
||||
|
||||
# Filter by trigger event
|
||||
tea actions runs ls --event pull_request --repo thatguygriff/walkies
|
||||
tea actions runs ls --event push --repo thatguygriff/walkies
|
||||
|
||||
# Filter by who triggered the run
|
||||
tea actions runs ls --actor thatguygriff --repo thatguygriff/walkies
|
||||
|
||||
# Filter by time range
|
||||
tea actions runs ls --since 24h --repo thatguygriff/walkies
|
||||
tea actions runs ls --since 2026-04-01 --until 2026-04-08 --repo thatguygriff/walkies
|
||||
|
||||
# Increase result limit
|
||||
tea actions runs ls --limit 50 --repo thatguygriff/walkies
|
||||
|
||||
# JSON output for scripting
|
||||
tea actions runs ls --output json --repo thatguygriff/walkies
|
||||
```
|
||||
|
||||
## Viewing a Run
|
||||
|
||||
Get the run ID from `tea actions runs ls`, then:
|
||||
|
||||
```bash
|
||||
# View run summary
|
||||
tea actions runs view 42 --repo thatguygriff/walkies
|
||||
|
||||
# View with jobs table (shows individual job statuses)
|
||||
tea actions runs view 42 --jobs --repo thatguygriff/walkies
|
||||
|
||||
# JSON output (includes job IDs for log fetching)
|
||||
tea actions runs view 42 --output json --repo thatguygriff/walkies
|
||||
```
|
||||
|
||||
## Viewing Logs
|
||||
|
||||
```bash
|
||||
# View logs for all jobs in a run
|
||||
tea actions runs logs 42 --repo thatguygriff/walkies
|
||||
|
||||
# View logs for a specific job
|
||||
tea actions runs logs 42 --job JOB_ID --repo thatguygriff/walkies
|
||||
|
||||
# Follow live logs for an in-progress job (requires --job)
|
||||
tea actions runs logs 42 --job JOB_ID --follow --repo thatguygriff/walkies
|
||||
```
|
||||
|
||||
Get job IDs from `tea actions runs view 42 --output json`.
|
||||
|
||||
## Managing Workflows
|
||||
|
||||
```bash
|
||||
# List all workflow definitions in the repo
|
||||
tea actions workflows ls --repo thatguygriff/walkies
|
||||
|
||||
# Cancel or delete a run
|
||||
tea actions runs delete 42 --repo thatguygriff/walkies
|
||||
```
|
||||
|
||||
## Common Workflows
|
||||
|
||||
### Check CI status for the current PR branch
|
||||
|
||||
```bash
|
||||
BRANCH=$(git branch --show-current)
|
||||
|
||||
# Find the latest run for this branch
|
||||
tea actions runs ls --branch "$BRANCH" --limit 5 --repo thatguygriff/walkies
|
||||
|
||||
# Get the most recent run ID as JSON
|
||||
RUN_ID=$(tea actions runs ls --branch "$BRANCH" --limit 1 --output json --repo thatguygriff/walkies \
|
||||
| jq -r '.[0].id')
|
||||
|
||||
echo "Latest run: $RUN_ID"
|
||||
|
||||
# View job-level summary
|
||||
tea actions runs view "$RUN_ID" --jobs --repo thatguygriff/walkies
|
||||
```
|
||||
|
||||
### Wait for CI to finish, then report status
|
||||
|
||||
```bash
|
||||
BRANCH=$(git branch --show-current)
|
||||
|
||||
while true; do
|
||||
STATUS=$(tea actions runs ls --branch "$BRANCH" --limit 1 --output json --repo thatguygriff/walkies \
|
||||
| jq -r '.[0].status')
|
||||
echo "Status: $STATUS"
|
||||
case "$STATUS" in
|
||||
success|failure|canceled|skipped) break ;;
|
||||
*) sleep 15 ;;
|
||||
esac
|
||||
done
|
||||
|
||||
echo "Final CI status: $STATUS"
|
||||
```
|
||||
|
||||
### Fetch logs for a failing run
|
||||
|
||||
```bash
|
||||
BRANCH=$(git branch --show-current)
|
||||
|
||||
RUN_ID=$(tea actions runs ls --branch "$BRANCH" --status failure --limit 1 --output json \
|
||||
--repo thatguygriff/walkies | jq -r '.[0].id')
|
||||
|
||||
# Show all logs for the failed run
|
||||
tea actions runs logs "$RUN_ID" --repo thatguygriff/walkies
|
||||
|
||||
# Or drill into a specific failing job
|
||||
tea actions runs view "$RUN_ID" --output json --repo thatguygriff/walkies \
|
||||
| jq '.jobs[] | select(.status == "failure") | {id: .id, name: .name}'
|
||||
|
||||
# Then fetch that job's logs
|
||||
JOB_ID=<id from above>
|
||||
tea actions runs logs "$RUN_ID" --job "$JOB_ID" --repo thatguygriff/walkies
|
||||
```
|
||||
|
||||
### Monitor a run that's currently in progress
|
||||
|
||||
```bash
|
||||
RUN_ID=42
|
||||
|
||||
# Get the in-progress job ID
|
||||
JOB_ID=$(tea actions runs view "$RUN_ID" --output json --repo thatguygriff/walkies \
|
||||
| jq -r '.jobs[] | select(.status == "in_progress") | .id' | head -1)
|
||||
|
||||
# Follow live logs
|
||||
tea actions runs logs "$RUN_ID" --job "$JOB_ID" --follow --repo thatguygriff/walkies
|
||||
```
|
||||
|
||||
## Quick Reference
|
||||
|
||||
```bash
|
||||
# List
|
||||
tea actions runs ls # Last 30 runs
|
||||
tea actions runs ls --branch feature/foo # Runs for a branch
|
||||
tea actions runs ls --status failure # Failed runs only
|
||||
tea actions runs ls --event pull_request # PR-triggered runs
|
||||
tea actions runs ls --limit 1 --output json | jq '.[0]' # Latest run as JSON
|
||||
|
||||
# View
|
||||
tea actions runs view 42 # Run summary
|
||||
tea actions runs view 42 --jobs # With jobs table
|
||||
tea actions runs view 42 --output json # Full JSON (incl. job IDs)
|
||||
|
||||
# Logs
|
||||
tea actions runs logs 42 # All logs for a run
|
||||
tea actions runs logs 42 --job JOB_ID # Specific job logs
|
||||
tea actions runs logs 42 --job JOB_ID --follow # Follow live output
|
||||
|
||||
# Cancel / delete
|
||||
tea actions runs delete 42 # Cancel or delete run
|
||||
|
||||
# Workflows
|
||||
tea actions workflows ls # List workflow definitions
|
||||
```
|
||||
|
||||
## Tips
|
||||
|
||||
1. **Find the run for a PR**: PRs run on their head branch — filter with `--branch` using the feature branch name, not the PR number.
|
||||
2. **Get job IDs**: Use `--output json` on `view` then `jq '.jobs[] | {id, name, status}'` to identify which job to drill into.
|
||||
3. **Status polling**: The `--status in_progress` filter helps confirm a run is still going before following logs.
|
||||
4. **Log noise**: Full run logs can be large — use `--job` to focus on the failing step.
|
||||
501
.claude/skills/issues/SKILL.md
Normal file
501
.claude/skills/issues/SKILL.md
Normal file
@@ -0,0 +1,501 @@
|
||||
---
|
||||
name: issues
|
||||
description: Create and Manage issues in Gitea
|
||||
dependencies: tea
|
||||
---
|
||||
|
||||
# Issue Management
|
||||
|
||||
Comprehensive guide for managing Gitea issues using the tea CLI.
|
||||
|
||||
## Table of Contents
|
||||
|
||||
- [Viewing Issues](#viewing-issues)
|
||||
- [Creating Issues](#creating-issues)
|
||||
- [Updating Issues](#updating-issues)
|
||||
- [Closing and Reopening Issues](#closing-and-reopening-issues)
|
||||
- [Labels](#labels)
|
||||
- [Milestones](#milestones)
|
||||
- [Projects](#projects)
|
||||
- [Search and Filtering](#search-and-filtering)
|
||||
- [Common Workflows](#common-workflows)
|
||||
|
||||
## Viewing Issues
|
||||
|
||||
### ls issues
|
||||
|
||||
```bash
|
||||
# ls open issues in current repository
|
||||
tea issue ls --repo thatguygriff/walkies
|
||||
|
||||
# ls all issues (open and closed)
|
||||
tea issue ls --state all --repo thatguygriff/walkies
|
||||
|
||||
# Limit number of results
|
||||
tea issue ls --limit 50 --repo thatguygriff/walkies
|
||||
|
||||
# Filter by label
|
||||
tea issue ls --labels bug --repo thatguygriff/walkies
|
||||
tea issue ls --labels "help wanted,good first issue" --repo thatguygriff/walkies
|
||||
|
||||
# Filter by assignee
|
||||
tea issue ls --assignee @me --repo thatguygriff/walkies
|
||||
tea issue ls --assignee username --repo thatguygriff/walkies
|
||||
|
||||
# Filter by milestone
|
||||
tea issue ls --milestones "v1.0" --repo thatguygriff/walkies
|
||||
|
||||
# Get JSON output (use --fields to select columns)
|
||||
tea issue ls --output json --fields number,title,state,labels,assignees --repo thatguygriff/walkies
|
||||
```
|
||||
|
||||
### View specific issue
|
||||
|
||||
```bash
|
||||
# View issue details
|
||||
tea issue view 123
|
||||
|
||||
# View in browser
|
||||
tea issue view 123 --web
|
||||
|
||||
# View issue comments
|
||||
tea issue view 123 --comments
|
||||
|
||||
# Get JSON output
|
||||
tea issue view 123 --output json
|
||||
```
|
||||
|
||||
## Creating Issues
|
||||
|
||||
### Interactive creation
|
||||
|
||||
```bash
|
||||
# Create issue with interactive prompts
|
||||
tea issue create --repo thatguygriff/walkies
|
||||
|
||||
# Follow prompts for:
|
||||
# - Title
|
||||
# - Body
|
||||
# - Metadata (labels, assignees, milestones)
|
||||
```
|
||||
|
||||
### Non-interactive creation
|
||||
|
||||
```bash
|
||||
# Create issue with title only
|
||||
tea issue create --title "Fix login bug" --repo thatguygriff/walkies
|
||||
|
||||
# Create issue with title and body
|
||||
tea issue create --title "Add dark mode" --description "Users have requested dark mode support" --repo thatguygriff/walkies
|
||||
|
||||
# Create issue with metadata
|
||||
tea issue create \
|
||||
--title "Performance optimization" \
|
||||
--description "Optimize database queries" \
|
||||
--labels bug,performance \
|
||||
--assignees username \
|
||||
--milestone "v2.0" \
|
||||
--repo thatguygriff/walkies
|
||||
```
|
||||
|
||||
## Updating Issues
|
||||
|
||||
### Edit issue
|
||||
|
||||
```bash
|
||||
# Edit issue interactively
|
||||
tea issue edit 123
|
||||
|
||||
# Update title
|
||||
tea issue edit 123 --title "New title"
|
||||
|
||||
# Update body
|
||||
tea issue edit 123 --description "Updated description"
|
||||
|
||||
# Add labels (flag is plural: --add-labels)
|
||||
tea issue edit 123 --add-labels bug,priority-high
|
||||
|
||||
# Remove labels (flag is plural: --remove-labels)
|
||||
tea issue edit 123 --remove-labels wontfix
|
||||
|
||||
# Add assignees (flag is plural: --add-assignees)
|
||||
tea issue edit 123 --add-assignees user1,user2
|
||||
|
||||
# Set milestone
|
||||
tea issue edit 123 --milestone "v1.5"
|
||||
|
||||
# Remove milestone
|
||||
tea issue edit 123 --milestone ""
|
||||
```
|
||||
|
||||
### Comment on issue
|
||||
|
||||
```bash
|
||||
# Add comment — body is a positional argument, not a flag
|
||||
tea comment 123 "Working on this now" --repo thatguygriff/walkies
|
||||
|
||||
# Edit comment (requires comment ID, via API)
|
||||
tea api repos/:owner/:repo/issues/comments/COMMENT_ID -X PATCH -f body="Updated comment"
|
||||
```
|
||||
|
||||
## Closing and Reopening Issues
|
||||
|
||||
```bash
|
||||
# Close issue (no --comment or --reason flags available)
|
||||
tea issue close 123 --repo thatguygriff/walkies
|
||||
|
||||
# Close multiple issues
|
||||
for issue in 123 124 125; do
|
||||
tea issue close $issue --repo thatguygriff/walkies
|
||||
done
|
||||
|
||||
# Reopen issue
|
||||
tea issue reopen 123 --repo thatguygriff/walkies
|
||||
|
||||
# To add a comment when closing, close first then comment separately
|
||||
tea issue close 123 --repo thatguygriff/walkies
|
||||
tea comment 123 "Fixed in PR #456" --repo thatguygriff/walkies
|
||||
```
|
||||
|
||||
### Delete issues
|
||||
|
||||
```bash
|
||||
# Delete issue (via API - CAREFUL)
|
||||
tea api repos/:owner/:repo/issues/123 -X DELETE
|
||||
```
|
||||
|
||||
## Labels
|
||||
|
||||
### ls labels
|
||||
|
||||
```bash
|
||||
# ls labels in repository
|
||||
tea label ls --repo thatguygriff/walkies
|
||||
|
||||
# Get JSON output
|
||||
tea label ls --output json --repo thatguygriff/walkies
|
||||
```
|
||||
|
||||
### Create labels
|
||||
|
||||
```bash
|
||||
# Create label — name is a named flag (--name), not positional
|
||||
tea label create --name bug --description "Something isn't working" --color d73a4a --repo thatguygriff/walkies
|
||||
|
||||
# Create multiple labels
|
||||
tea label create --name enhancement --description "New feature or request" --color a2eeef --repo thatguygriff/walkies
|
||||
tea label create --name documentation --description "Improvements to documentation" --color 0075ca --repo thatguygriff/walkies
|
||||
tea label create --name "good first issue" --description "Good for newcomers" --color 7057ff --repo thatguygriff/walkies
|
||||
```
|
||||
|
||||
### Update labels
|
||||
|
||||
```bash
|
||||
# tea label edit does not exist — use tea label update with --id (get ID from tea label ls --output json)
|
||||
tea label update --id 42 --name "bug" --description "Bug report" --color ff0000 --repo thatguygriff/walkies
|
||||
|
||||
# Rename label (change --name)
|
||||
tea label update --id 42 --name new-name --repo thatguygriff/walkies
|
||||
```
|
||||
|
||||
### Delete labels
|
||||
|
||||
```bash
|
||||
# Delete label by ID (get ID from tea label ls --output json)
|
||||
tea label delete --id 42 --repo thatguygriff/walkies
|
||||
```
|
||||
|
||||
### Manage issue labels
|
||||
|
||||
```bash
|
||||
# Add labels to issue
|
||||
tea issue edit 123 --add-labels bug,priority-high --repo thatguygriff/walkies
|
||||
|
||||
# Remove labels from issue
|
||||
tea issue edit 123 --remove-labels wontfix --repo thatguygriff/walkies
|
||||
|
||||
# Replace all labels (via API)
|
||||
tea api repos/:owner/:repo/issues/123 -X PATCH -f labels='["bug","confirmed"]'
|
||||
```
|
||||
|
||||
## Milestones
|
||||
|
||||
### ls milestones
|
||||
|
||||
```bash
|
||||
# ls milestones (via API)
|
||||
tea api repos/:owner/:repo/milestones | jq '.[] | {number: .number, title: .title, due_on: .due_on}'
|
||||
```
|
||||
|
||||
### Create milestone
|
||||
|
||||
```bash
|
||||
# Create milestone
|
||||
tea api repos/:owner/:repo/milestones -X POST \
|
||||
-f title="v1.0" \
|
||||
-f description="First major release" \
|
||||
-f due_on="2024-12-31T23:59:59Z"
|
||||
```
|
||||
|
||||
### Update milestone
|
||||
|
||||
```bash
|
||||
# Update milestone
|
||||
tea api repos/:owner/:repo/milestones/1 -X PATCH \
|
||||
-f title="v1.0.0" \
|
||||
-f state="closed"
|
||||
```
|
||||
|
||||
### Delete milestone
|
||||
|
||||
```bash
|
||||
# Delete milestone
|
||||
tea api repos/:owner/:repo/milestones/1 -X DELETE
|
||||
```
|
||||
|
||||
## Projects
|
||||
|
||||
Projects are managed via the API — `tea issue edit` does not support `--add-project` or `--remove-project`.
|
||||
|
||||
```bash
|
||||
# ls projects (via API)
|
||||
tea api repos/:owner/:repo/projects | jq '.[] | {name: .name, number: .number}'
|
||||
|
||||
# ls organization projects
|
||||
tea api orgs/:org/projects | jq '.[] | {name: .name, number: .number}'
|
||||
```
|
||||
|
||||
## Search and Filtering
|
||||
|
||||
Search uses `--keyword` / `-k`, not `--search`.
|
||||
|
||||
```bash
|
||||
# Filter by keyword in title/body
|
||||
tea issue ls --keyword "authentication" --repo thatguygriff/walkies
|
||||
|
||||
# Filter by label + keyword
|
||||
tea issue ls --labels bug --keyword "login" --repo thatguygriff/walkies
|
||||
|
||||
# Filter by assignee + state
|
||||
tea issue ls --assignee @me --state open --repo thatguygriff/walkies
|
||||
|
||||
# Filter by milestone
|
||||
tea issue ls --milestones "v2.0" --repo thatguygriff/walkies
|
||||
|
||||
# Filter by date range
|
||||
tea issue ls --from "2024-01-01" --until "2024-12-31" --repo thatguygriff/walkies
|
||||
```
|
||||
|
||||
### Filter with JSON output
|
||||
|
||||
Pipe `--output json` to `jq` for advanced filtering — there is no `--jq` flag.
|
||||
|
||||
```bash
|
||||
# Get open issues as JSON and filter with jq
|
||||
tea issue ls --output json --repo thatguygriff/walkies \
|
||||
| jq '.[] | select(.labels[].name == "bug")'
|
||||
|
||||
# Count issues by label
|
||||
tea issue ls --state all --output json --repo thatguygriff/walkies \
|
||||
| jq '[.[] | .labels[].name] | group_by(.) | map({label: .[0], count: length})'
|
||||
|
||||
# Find untriaged issues (no labels)
|
||||
tea issue ls --output json --repo thatguygriff/walkies \
|
||||
| jq '.[] | select(.labels | length == 0) | {number: .number, title: .title}'
|
||||
```
|
||||
|
||||
## Common Workflows
|
||||
|
||||
### Workflow 1: Bug report workflow
|
||||
|
||||
```bash
|
||||
# Create bug report
|
||||
tea issue create \
|
||||
--title "Login fails with 2FA enabled" \
|
||||
--description "$(cat <<EOF
|
||||
## Bug Description
|
||||
Users cannot log in when 2FA is enabled.
|
||||
|
||||
## Steps to Reproduce
|
||||
1. Enable 2FA on account
|
||||
2. Attempt to log in
|
||||
3. Authentication fails
|
||||
|
||||
## Expected Behavior
|
||||
Login should succeed with 2FA code
|
||||
|
||||
## Actual Behavior
|
||||
Login fails with error message
|
||||
|
||||
## Environment
|
||||
- Browser: Chrome 119
|
||||
- OS: macOS 14.0
|
||||
EOF
|
||||
)" \
|
||||
--labels bug,priority-high \
|
||||
--assignees security-team \
|
||||
--repo thatguygriff/walkies
|
||||
|
||||
# Get issue number from JSON output
|
||||
ISSUE=$(tea issue ls --labels bug --limit 1 --output json --repo thatguygriff/walkies | jq -r '.[0].number')
|
||||
|
||||
# Add follow-up comment
|
||||
tea comment $ISSUE "Investigating root cause" --repo thatguygriff/walkies
|
||||
|
||||
# Link to PR when fixed
|
||||
tea comment $ISSUE "Fixed in PR #789" --repo thatguygriff/walkies
|
||||
|
||||
# Close issue, then add closing comment separately
|
||||
tea issue close $ISSUE --repo thatguygriff/walkies
|
||||
tea comment $ISSUE "Resolved in v2.1.0" --repo thatguygriff/walkies
|
||||
```
|
||||
|
||||
### Workflow 2: Feature request workflow
|
||||
|
||||
```bash
|
||||
# Create feature request
|
||||
tea issue create \
|
||||
--title "Add export to PDF feature" \
|
||||
--description "Users want to export reports as PDF" \
|
||||
--labels enhancement,feature-request \
|
||||
--repo thatguygriff/walkies
|
||||
|
||||
# Team discusses and assigns
|
||||
tea issue edit 123 --add-assignees developer1 --milestone "v2.0" --repo thatguygriff/walkies
|
||||
|
||||
# Track progress with comments
|
||||
tea comment 123 "Starting implementation" --repo thatguygriff/walkies
|
||||
tea comment 123 "UI mockups ready for review" --repo thatguygriff/walkies
|
||||
tea comment 123 "Backend API complete" --repo thatguygriff/walkies
|
||||
|
||||
# Link to PR
|
||||
tea comment 123 "Implementation complete, see PR #456" --repo thatguygriff/walkies
|
||||
|
||||
# Close when merged
|
||||
tea issue close 123 --repo thatguygriff/walkies
|
||||
tea comment 123 "Feature released in v2.0" --repo thatguygriff/walkies
|
||||
```
|
||||
|
||||
### Workflow 3: Issue triage workflow
|
||||
|
||||
```bash
|
||||
# ls untriaged issues (no labels)
|
||||
tea issue ls --output json --repo thatguygriff/walkies \
|
||||
| jq '.[] | select(.labels | length == 0) | {number: .number, title: .title}'
|
||||
|
||||
# Triage each issue (--add-labels is plural)
|
||||
tea issue edit 123 --add-labels bug --repo thatguygriff/walkies
|
||||
tea issue edit 124 --add-labels enhancement --repo thatguygriff/walkies
|
||||
tea issue edit 125 --add-labels question,help-wanted --repo thatguygriff/walkies
|
||||
|
||||
# Assign priority labels
|
||||
tea issue edit 123 --add-labels priority-high --repo thatguygriff/walkies
|
||||
tea issue edit 124 --add-labels priority-medium --repo thatguygriff/walkies
|
||||
|
||||
# Assign to milestones
|
||||
tea issue edit 123 --milestone "v1.5" --repo thatguygriff/walkies
|
||||
tea issue edit 124 --milestone "v2.0" --repo thatguygriff/walkies
|
||||
|
||||
# Assign to team members
|
||||
tea issue edit 123 --add-assignees developer1 --repo thatguygriff/walkies
|
||||
```
|
||||
|
||||
### Workflow 4: Sprint planning workflow
|
||||
|
||||
```bash
|
||||
# ls issues in milestone
|
||||
tea issue ls --milestones "Sprint 5" --output json --repo thatguygriff/walkies
|
||||
|
||||
# Assign issues to team members
|
||||
tea issue edit 101 --add-assignees alice --repo thatguygriff/walkies
|
||||
tea issue edit 102 --add-assignees bob --repo thatguygriff/walkies
|
||||
tea issue edit 103 --add-assignees charlie --repo thatguygriff/walkies
|
||||
|
||||
# Add sprint label
|
||||
for issue in 101 102 103; do
|
||||
tea issue edit $issue --add-labels "sprint-5" --repo thatguygriff/walkies
|
||||
done
|
||||
|
||||
# Monitor progress during sprint
|
||||
tea issue ls --milestones "Sprint 5" --state all --output json --repo thatguygriff/walkies
|
||||
|
||||
# Close completed issues
|
||||
tea issue ls --milestones "Sprint 5" --labels done --output json --repo thatguygriff/walkies \
|
||||
| jq -r '.[].number' \
|
||||
| xargs -I {} tea issue close {} --repo thatguygriff/walkies
|
||||
```
|
||||
|
||||
### Workflow 5: Bulk issue operations
|
||||
|
||||
```bash
|
||||
# Create multiple issues from file (title|body|labels per line)
|
||||
while IFS='|' read -r title body labels; do
|
||||
tea issue create --title "$title" --description "$body" --labels "$labels" --repo thatguygriff/walkies
|
||||
done < issues.txt
|
||||
|
||||
# Bulk close stale issues
|
||||
tea issue ls --until "2023-01-01" --output json --repo thatguygriff/walkies \
|
||||
| jq -r '.[].number' \
|
||||
| xargs -I {} tea issue close {} --repo thatguygriff/walkies
|
||||
|
||||
# Bulk label update
|
||||
tea issue ls --labels old-label --output json --repo thatguygriff/walkies \
|
||||
| jq -r '.[].number' \
|
||||
| xargs -I {} tea issue edit {} --remove-labels old-label --add-labels new-label --repo thatguygriff/walkies
|
||||
|
||||
# Export issues to CSV
|
||||
tea issue ls --state all --output json --limit 1000 --repo thatguygriff/walkies \
|
||||
| jq -r '.[] | [.number, .title, .state, (.labels | map(.name) | join(";")), (.assignees | map(.login) | join(";")), .created] | @csv' \
|
||||
> issues.csv
|
||||
```
|
||||
|
||||
## Tips and Best Practices
|
||||
|
||||
1. **Label systematically**: Develop a consistent labeling scheme
|
||||
2. **Triage regularly**: Review and label new issues promptly
|
||||
3. **Link PRs**: Always reference issues in PR descriptions
|
||||
4. **Use milestones**: Group related issues for release planning
|
||||
5. **Assign clearly**: Assign issues to specific people
|
||||
6. **Comment updates**: Keep stakeholders informed with comments
|
||||
7. **Use --output json + jq**: Combine for powerful filtering and reporting
|
||||
8. **Get label IDs first**: `tea label update` and `tea label delete` require `--id`, not name — run `tea label ls --output json` to find IDs
|
||||
|
||||
## Quick Reference
|
||||
|
||||
```bash
|
||||
# List
|
||||
tea issue ls # ls open issues
|
||||
tea issue ls --state all # ls all issues
|
||||
tea issue ls --labels bug # Filter by label (plural flag)
|
||||
tea issue ls --assignee @me # Your issues
|
||||
tea issue ls --keyword "auth" # Search by keyword
|
||||
|
||||
# View
|
||||
tea issue view 123 # View issue details
|
||||
tea issue view 123 --web # Open in browser
|
||||
tea issue view 123 --comments # Include comments
|
||||
|
||||
# Create
|
||||
tea issue create # Interactive creation
|
||||
tea issue create --title "text" --description "text" # Non-interactive
|
||||
tea issue create --labels bug --assignees user # With metadata (both plural)
|
||||
|
||||
# Update
|
||||
tea issue edit 123 --title "new title" # Change title
|
||||
tea issue edit 123 --add-labels bug # Add label (plural flag)
|
||||
tea issue edit 123 --remove-labels wontfix # Remove label (plural flag)
|
||||
tea issue edit 123 --add-assignees user # Add assignee (plural flag)
|
||||
|
||||
# Comment (tea comment, not tea issue comment)
|
||||
tea comment 123 "comment text" --repo thatguygriff/walkies
|
||||
|
||||
# Close/Reopen (no --comment or --reason flags; add comment separately)
|
||||
tea issue close 123 # Close issue
|
||||
tea issue reopen 123 # Reopen issue
|
||||
|
||||
# Labels
|
||||
tea label ls # ls labels
|
||||
tea label create --name "bug" --color d73a4a # Create (--name flag required)
|
||||
tea label update --id 42 --name new-name # Update (--id required, not name)
|
||||
tea label delete --id 42 # Delete (--id required, not name)
|
||||
```
|
||||
@@ -1,7 +1,6 @@
|
||||
---
|
||||
name: review-and-commit
|
||||
description: Review and Commit
|
||||
disable-model-invocation: true
|
||||
---
|
||||
|
||||
# Review and Commit
|
||||
|
||||
@@ -1,4 +1,8 @@
|
||||
PORT=8080
|
||||
DATABASE_DSN=walkies.db
|
||||
DB_HOST=localhost
|
||||
DB_PORT=3306
|
||||
DB_USER=root
|
||||
DB_PASSWORD=
|
||||
DB_NAME=walkies
|
||||
JWT_SECRET=change-me-in-production
|
||||
STATIC_DIR=./web/build
|
||||
STATIC_DIR=./web/dist
|
||||
|
||||
47
.gitea/workflows/ci.yml
Normal file
47
.gitea/workflows/ci.yml
Normal file
@@ -0,0 +1,47 @@
|
||||
name: CI
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: ["**"]
|
||||
pull_request:
|
||||
branches: ["**"]
|
||||
|
||||
jobs:
|
||||
go:
|
||||
name: Go tests & lint
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version-file: go.mod
|
||||
cache: true
|
||||
|
||||
- name: go vet
|
||||
run: go vet ./...
|
||||
|
||||
- name: go test
|
||||
run: go test ./...
|
||||
|
||||
web:
|
||||
name: Frontend tests & type-check
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version-file: .node-version
|
||||
|
||||
- name: Install dependencies
|
||||
working-directory: web
|
||||
run: npm install && npm exec -- allow-scripts
|
||||
|
||||
- name: Type check
|
||||
working-directory: web
|
||||
run: npx tsc --noEmit
|
||||
|
||||
- name: Run tests
|
||||
working-directory: web
|
||||
run: npm test
|
||||
1
.node-version
Normal file
1
.node-version
Normal file
@@ -0,0 +1 @@
|
||||
22
|
||||
@@ -45,7 +45,7 @@ All API routes are prefixed `/api/v1`. The Go binary serves the compiled React a
|
||||
|
||||
### React Frontend
|
||||
|
||||
Standard CRA layout in `web/src/`:
|
||||
Vite + React + TypeScript in `web/src/`. Tests use Vitest with jsdom.
|
||||
|
||||
- `api.ts` — typed fetch wrapper; reads JWT from `localStorage`, prefixes `BASE = '/api/v1'`
|
||||
- `auth.tsx` — `AuthProvider` context; decodes the JWT payload to expose `role` and `volunteerID`
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
# Stage 1: Build React frontend
|
||||
FROM node:22-alpine AS frontend
|
||||
WORKDIR /app/web
|
||||
COPY web/package*.json ./
|
||||
RUN npm ci
|
||||
COPY web/package*.json web/.npmrc ./
|
||||
RUN npm install && npm exec -- allow-scripts
|
||||
COPY web/ ./
|
||||
RUN npm run build
|
||||
|
||||
@@ -19,7 +19,7 @@ FROM alpine:3.21
|
||||
RUN apk add --no-cache ca-certificates tzdata
|
||||
WORKDIR /app
|
||||
COPY --from=backend /walkies ./walkies
|
||||
COPY --from=frontend /app/web/build ./web/dist
|
||||
COPY --from=frontend /app/web/dist ./web/dist
|
||||
EXPOSE 8080
|
||||
ENV STATIC_DIR=/app/web/dist
|
||||
CMD ["./walkies"]
|
||||
|
||||
13
README.md
13
README.md
@@ -4,8 +4,9 @@ A web-based application for an animal shelter to manage volunteer scheduling, ti
|
||||
|
||||
## Requirements
|
||||
|
||||
- [Go](https://golang.org/) 1.21+
|
||||
- [Node.js](https://nodejs.org/) 18+
|
||||
- [Go](https://golang.org/) 1.25+
|
||||
- [Node.js](https://nodejs.org/) 22+
|
||||
- [MySQL](https://www.mysql.com/) 8.0
|
||||
- [Task](https://taskfile.dev/) (`brew install go-task` or see [install docs](https://taskfile.dev/installation/))
|
||||
- [Docker](https://www.docker.com/) (optional, for containerised deployment)
|
||||
|
||||
@@ -64,8 +65,12 @@ The server is configured via environment variables:
|
||||
| Variable | Default | Description |
|
||||
|----------|---------|-------------|
|
||||
| `PORT` | `8080` | HTTP listen port |
|
||||
| `DATABASE_DSN` | `walkies.db` | SQLite file path |
|
||||
| `DB_HOST` | `localhost` | MySQL host |
|
||||
| `DB_PORT` | `3306` | MySQL port |
|
||||
| `DB_USER` | `root` | MySQL username |
|
||||
| `DB_PASSWORD` | *(empty)* | MySQL password |
|
||||
| `DB_NAME` | `walkies` | MySQL database name |
|
||||
| `JWT_SECRET` | `change-me-in-production` | HMAC signing key — **change this** |
|
||||
| `STATIC_DIR` | `./web/build` | Path to compiled React app |
|
||||
| `STATIC_DIR` | `./web/dist` | Path to compiled React app |
|
||||
|
||||
Copy `.env.example` to `.env` to set these locally (the server reads environment variables directly; use a process manager or Docker to inject them).
|
||||
|
||||
28
Taskfile.yml
28
Taskfile.yml
@@ -3,7 +3,7 @@ version: '3'
|
||||
vars:
|
||||
BINARY: walkies
|
||||
WEB_DIR: web
|
||||
STATIC_DIR: "{{.WEB_DIR}}/build"
|
||||
STATIC_DIR: "{{.WEB_DIR}}/dist"
|
||||
|
||||
tasks:
|
||||
default:
|
||||
@@ -15,7 +15,9 @@ tasks:
|
||||
web:install:
|
||||
desc: Install frontend dependencies
|
||||
dir: "{{.WEB_DIR}}"
|
||||
cmd: npm install
|
||||
cmds:
|
||||
- npm install
|
||||
- npm exec -- allow-scripts
|
||||
sources:
|
||||
- package.json
|
||||
generates:
|
||||
@@ -31,20 +33,22 @@ tasks:
|
||||
- public/**/*
|
||||
- package.json
|
||||
- tsconfig.json
|
||||
- vite.config.ts
|
||||
- index.html
|
||||
generates:
|
||||
- build/**/*
|
||||
- dist/**/*
|
||||
|
||||
web:dev:
|
||||
desc: Start frontend dev server (hot reload on :3000)
|
||||
dir: "{{.WEB_DIR}}"
|
||||
deps: [web:install]
|
||||
cmd: npm start
|
||||
cmd: npm run dev
|
||||
|
||||
web:test:
|
||||
desc: Run frontend tests
|
||||
dir: "{{.WEB_DIR}}"
|
||||
deps: [web:install]
|
||||
cmd: npm test -- --watchAll=false
|
||||
cmd: npm test
|
||||
|
||||
# ── Backend ─────────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -104,16 +108,16 @@ tasks:
|
||||
cmd: docker build -t walkies .
|
||||
|
||||
docker:up:
|
||||
desc: Build and start with docker-compose
|
||||
cmd: docker-compose up --build
|
||||
desc: Build and start with docker compose
|
||||
cmd: docker compose up --build
|
||||
|
||||
docker:down:
|
||||
desc: Stop docker-compose services
|
||||
cmd: docker-compose down
|
||||
desc: Stop docker compose services
|
||||
cmd: docker compose down
|
||||
|
||||
docker:logs:
|
||||
desc: Tail docker-compose logs
|
||||
cmd: docker-compose logs -f
|
||||
desc: Tail docker compose logs
|
||||
cmd: docker compose logs -f
|
||||
|
||||
# ── Utilities ────────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -121,7 +125,7 @@ tasks:
|
||||
desc: Remove build artifacts
|
||||
cmds:
|
||||
- rm -f {{.BINARY}}
|
||||
- rm -rf {{.WEB_DIR}}/build
|
||||
- rm -rf {{.WEB_DIR}}/dist
|
||||
|
||||
tidy:
|
||||
desc: Tidy Go modules
|
||||
|
||||
@@ -28,23 +28,25 @@ func NewService(db *sql.DB, secret string) *Service {
|
||||
return &Service{db: db, jwtSecret: []byte(secret)}
|
||||
}
|
||||
|
||||
func (s *Service) Login(ctx context.Context, email, password string) (string, error) {
|
||||
// Login authenticates by email/password and returns the volunteer ID and JWT token.
|
||||
func (s *Service) Login(ctx context.Context, email, password string) (int64, string, error) {
|
||||
var id int64
|
||||
var hash, role string
|
||||
err := s.db.QueryRowContext(ctx,
|
||||
`SELECT id, password, role FROM volunteers WHERE email = ? AND active = 1`,
|
||||
`SELECT id, password, role FROM volunteers WHERE email = ? AND active = 1 AND (password != '' AND password IS NOT NULL)`,
|
||||
email,
|
||||
).Scan(&id, &hash, &role)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return "", ErrInvalidCredentials
|
||||
return 0, "", ErrInvalidCredentials
|
||||
}
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("query volunteer: %w", err)
|
||||
return 0, "", fmt.Errorf("query volunteer: %w", err)
|
||||
}
|
||||
if err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password)); err != nil {
|
||||
return "", ErrInvalidCredentials
|
||||
return 0, "", ErrInvalidCredentials
|
||||
}
|
||||
return s.issueToken(id, role)
|
||||
token, err := s.issueToken(id, role)
|
||||
return id, token, err
|
||||
}
|
||||
|
||||
func (s *Service) issueToken(volunteerID int64, role string) (string, error) {
|
||||
@@ -81,3 +83,9 @@ func HashPassword(password string) (string, error) {
|
||||
b, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
|
||||
return string(b), err
|
||||
}
|
||||
|
||||
// IssueToken mints a JWT for the given volunteer ID and role without querying the DB.
|
||||
// Intended for use in tests and invite-activation flows.
|
||||
func (s *Service) IssueToken(volunteerID int64, role string) (string, error) {
|
||||
return s.issueToken(volunteerID, role)
|
||||
}
|
||||
|
||||
92
internal/auth/auth_test.go
Normal file
92
internal/auth/auth_test.go
Normal file
@@ -0,0 +1,92 @@
|
||||
package auth_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"git.unsupervised.ca/walkies/internal/auth"
|
||||
)
|
||||
|
||||
func TestHashPassword_RoundTrip(t *testing.T) {
|
||||
hash, err := auth.HashPassword("mysecret")
|
||||
if err != nil {
|
||||
t.Fatalf("HashPassword: %v", err)
|
||||
}
|
||||
if hash == "mysecret" {
|
||||
t.Error("hash should not equal plaintext")
|
||||
}
|
||||
if len(hash) == 0 {
|
||||
t.Error("hash should not be empty")
|
||||
}
|
||||
}
|
||||
|
||||
func TestHashPassword_DifferentInputs(t *testing.T) {
|
||||
h1, _ := auth.HashPassword("password1")
|
||||
h2, _ := auth.HashPassword("password2")
|
||||
if h1 == h2 {
|
||||
t.Error("different passwords should produce different hashes")
|
||||
}
|
||||
}
|
||||
|
||||
func TestIssueToken_Parse_RoundTrip(t *testing.T) {
|
||||
svc := auth.NewService(nil, "test-secret")
|
||||
|
||||
token, err := svc.IssueToken(42, "admin")
|
||||
if err != nil {
|
||||
t.Fatalf("IssueToken: %v", err)
|
||||
}
|
||||
if token == "" {
|
||||
t.Fatal("expected non-empty token")
|
||||
}
|
||||
|
||||
claims, err := svc.Parse(token)
|
||||
if err != nil {
|
||||
t.Fatalf("Parse: %v", err)
|
||||
}
|
||||
if claims.VolunteerID != 42 {
|
||||
t.Errorf("expected volunteer_id 42, got %d", claims.VolunteerID)
|
||||
}
|
||||
if claims.Role != "admin" {
|
||||
t.Errorf("expected role admin, got %q", claims.Role)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParse_InvalidToken(t *testing.T) {
|
||||
svc := auth.NewService(nil, "test-secret")
|
||||
_, err := svc.Parse("not.a.token")
|
||||
if err == nil {
|
||||
t.Error("expected error parsing invalid token")
|
||||
}
|
||||
}
|
||||
|
||||
func TestParse_WrongSecret(t *testing.T) {
|
||||
svc1 := auth.NewService(nil, "secret-A")
|
||||
svc2 := auth.NewService(nil, "secret-B")
|
||||
|
||||
token, err := svc1.IssueToken(1, "volunteer")
|
||||
if err != nil {
|
||||
t.Fatalf("IssueToken: %v", err)
|
||||
}
|
||||
|
||||
_, err = svc2.Parse(token)
|
||||
if err == nil {
|
||||
t.Error("token signed with secret-A should not parse with secret-B")
|
||||
}
|
||||
}
|
||||
|
||||
func TestIssueToken_Volunteer(t *testing.T) {
|
||||
svc := auth.NewService(nil, "test-secret")
|
||||
token, err := svc.IssueToken(7, "volunteer")
|
||||
if err != nil {
|
||||
t.Fatalf("IssueToken: %v", err)
|
||||
}
|
||||
claims, err := svc.Parse(token)
|
||||
if err != nil {
|
||||
t.Fatalf("Parse: %v", err)
|
||||
}
|
||||
if claims.Role != "volunteer" {
|
||||
t.Errorf("expected role volunteer, got %q", claims.Role)
|
||||
}
|
||||
if claims.VolunteerID != 7 {
|
||||
t.Errorf("expected volunteer_id 7, got %d", claims.VolunteerID)
|
||||
}
|
||||
}
|
||||
@@ -3,9 +3,10 @@ package db
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
_ "github.com/go-sql-driver/mysql"
|
||||
"github.com/go-sql-driver/mysql"
|
||||
)
|
||||
|
||||
func Open(dsn string) (*sql.DB, error) {
|
||||
@@ -22,6 +23,10 @@ func Open(dsn string) (*sql.DB, error) {
|
||||
func Migrate(ctx context.Context, db *sql.DB) error {
|
||||
for _, stmt := range statements {
|
||||
if _, err := db.ExecContext(ctx, stmt); err != nil {
|
||||
var mysqlErr *mysql.MySQLError
|
||||
if errors.As(err, &mysqlErr) && mysqlErr.Number == 1060 {
|
||||
continue // duplicate column — already exists
|
||||
}
|
||||
return fmt.Errorf("migrate: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,12 +5,29 @@ var statements = []string{
|
||||
id INT AUTO_INCREMENT PRIMARY KEY,
|
||||
name VARCHAR(255) NOT NULL,
|
||||
email VARCHAR(255) NOT NULL UNIQUE,
|
||||
password VARCHAR(255) NOT NULL,
|
||||
password VARCHAR(255) NOT NULL DEFAULT '',
|
||||
role VARCHAR(50) NOT NULL DEFAULT 'volunteer' COMMENT 'admin or volunteer',
|
||||
active TINYINT NOT NULL DEFAULT 1,
|
||||
is_trainee TINYINT NOT NULL DEFAULT 0,
|
||||
phone VARCHAR(20) NULL,
|
||||
operational_roles TEXT NOT NULL,
|
||||
notification_preference VARCHAR(50) NOT NULL DEFAULT 'email',
|
||||
admin_notes TEXT NULL,
|
||||
last_login DATETIME NULL,
|
||||
invite_token VARCHAR(255) NULL,
|
||||
invite_expires_at DATETIME NULL,
|
||||
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci`,
|
||||
// Additive column migrations for existing deployments (duplicates ignored at runtime)
|
||||
`ALTER TABLE volunteers ADD COLUMN is_trainee TINYINT NOT NULL DEFAULT 0`,
|
||||
`ALTER TABLE volunteers ADD COLUMN phone VARCHAR(20) NULL`,
|
||||
`ALTER TABLE volunteers ADD COLUMN operational_roles TEXT NOT NULL`,
|
||||
`ALTER TABLE volunteers ADD COLUMN notification_preference VARCHAR(50) NOT NULL DEFAULT 'email'`,
|
||||
`ALTER TABLE volunteers ADD COLUMN admin_notes TEXT NULL`,
|
||||
`ALTER TABLE volunteers ADD COLUMN last_login DATETIME NULL`,
|
||||
`ALTER TABLE volunteers ADD COLUMN invite_token VARCHAR(255) NULL`,
|
||||
`ALTER TABLE volunteers ADD COLUMN invite_expires_at DATETIME NULL`,
|
||||
`CREATE TABLE IF NOT EXISTS schedules (
|
||||
id INT AUTO_INCREMENT PRIMARY KEY,
|
||||
volunteer_id INT NOT NULL,
|
||||
@@ -55,10 +72,77 @@ var statements = []string{
|
||||
id INT AUTO_INCREMENT PRIMARY KEY,
|
||||
volunteer_id INT NOT NULL,
|
||||
message TEXT NOT NULL,
|
||||
read TINYINT NOT NULL DEFAULT 0,
|
||||
is_read TINYINT NOT NULL DEFAULT 0,
|
||||
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY (volunteer_id) REFERENCES volunteers(id) ON DELETE CASCADE,
|
||||
INDEX idx_volunteer_id (volunteer_id),
|
||||
INDEX idx_read (read)
|
||||
INDEX idx_is_read (is_read)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci`,
|
||||
`CREATE TABLE IF NOT EXISTS shift_templates (
|
||||
id INT AUTO_INCREMENT PRIMARY KEY,
|
||||
name VARCHAR(255) NOT NULL,
|
||||
day_of_week TINYINT NOT NULL COMMENT '0=Sunday 1=Monday ... 6=Saturday (matches Go time.Weekday)',
|
||||
start_time TIME NOT NULL,
|
||||
end_time TIME NOT NULL,
|
||||
min_capacity INT NOT NULL DEFAULT 1,
|
||||
max_capacity INT NOT NULL DEFAULT 1,
|
||||
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci`,
|
||||
`CREATE TABLE IF NOT EXISTS shift_template_roles (
|
||||
id INT AUTO_INCREMENT PRIMARY KEY,
|
||||
template_id INT NOT NULL,
|
||||
role_name VARCHAR(255) NOT NULL,
|
||||
count INT NOT NULL DEFAULT 1,
|
||||
FOREIGN KEY (template_id) REFERENCES shift_templates(id) ON DELETE CASCADE,
|
||||
INDEX idx_template_id (template_id)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci`,
|
||||
`CREATE TABLE IF NOT EXISTS shift_template_volunteers (
|
||||
id INT AUTO_INCREMENT PRIMARY KEY,
|
||||
template_id INT NOT NULL,
|
||||
volunteer_id INT NOT NULL,
|
||||
UNIQUE KEY uq_template_volunteer (template_id, volunteer_id),
|
||||
FOREIGN KEY (template_id) REFERENCES shift_templates(id) ON DELETE CASCADE,
|
||||
FOREIGN KEY (volunteer_id) REFERENCES volunteers(id) ON DELETE CASCADE
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci`,
|
||||
`CREATE TABLE IF NOT EXISTS shift_instances (
|
||||
id INT AUTO_INCREMENT PRIMARY KEY,
|
||||
template_id INT NULL,
|
||||
name VARCHAR(255) NOT NULL,
|
||||
date DATE NOT NULL,
|
||||
start_time TIME NOT NULL,
|
||||
end_time TIME NOT NULL,
|
||||
min_capacity INT NOT NULL DEFAULT 1,
|
||||
max_capacity INT NOT NULL DEFAULT 1,
|
||||
status VARCHAR(20) NOT NULL DEFAULT 'draft' COMMENT 'draft or published',
|
||||
year INT NOT NULL,
|
||||
month INT NOT NULL,
|
||||
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY (template_id) REFERENCES shift_templates(id) ON DELETE SET NULL,
|
||||
INDEX idx_year_month (year, month),
|
||||
INDEX idx_status (status)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci`,
|
||||
`CREATE TABLE IF NOT EXISTS shift_instance_volunteers (
|
||||
id INT AUTO_INCREMENT PRIMARY KEY,
|
||||
instance_id INT NOT NULL,
|
||||
volunteer_id INT NOT NULL,
|
||||
confirmed TINYINT NOT NULL DEFAULT 0,
|
||||
confirmed_at DATETIME NULL,
|
||||
UNIQUE KEY uq_instance_volunteer (instance_id, volunteer_id),
|
||||
FOREIGN KEY (instance_id) REFERENCES shift_instances(id) ON DELETE CASCADE,
|
||||
FOREIGN KEY (volunteer_id) REFERENCES volunteers(id) ON DELETE CASCADE,
|
||||
INDEX idx_instance_id (instance_id),
|
||||
INDEX idx_volunteer_id (volunteer_id)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci`,
|
||||
`CREATE TABLE IF NOT EXISTS time_off_removed_shifts (
|
||||
id INT AUTO_INCREMENT PRIMARY KEY,
|
||||
time_off_id INT NOT NULL,
|
||||
instance_id INT NOT NULL,
|
||||
volunteer_id INT NOT NULL,
|
||||
FOREIGN KEY (time_off_id) REFERENCES time_off_requests(id) ON DELETE CASCADE,
|
||||
FOREIGN KEY (instance_id) REFERENCES shift_instances(id) ON DELETE CASCADE,
|
||||
FOREIGN KEY (volunteer_id) REFERENCES volunteers(id) ON DELETE CASCADE,
|
||||
INDEX idx_time_off_id (time_off_id)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci`,
|
||||
}
|
||||
|
||||
@@ -14,7 +14,7 @@ type Notification struct {
|
||||
ID int64 `json:"id"`
|
||||
VolunteerID int64 `json:"volunteer_id"`
|
||||
Message string `json:"message"`
|
||||
Read bool `json:"read"`
|
||||
Read bool `json:"is_read"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
@@ -42,7 +42,7 @@ func (s *Store) GetByID(ctx context.Context, id int64) (*Notification, error) {
|
||||
n := &Notification{}
|
||||
var createdAt string
|
||||
err := s.db.QueryRowContext(ctx,
|
||||
`SELECT id, volunteer_id, message, read, created_at FROM notifications WHERE id = ?`, id,
|
||||
`SELECT id, volunteer_id, message, is_read, created_at FROM notifications WHERE id = ?`, id,
|
||||
).Scan(&n.ID, &n.VolunteerID, &n.Message, &n.Read, &createdAt)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return nil, ErrNotFound
|
||||
@@ -56,7 +56,7 @@ func (s *Store) GetByID(ctx context.Context, id int64) (*Notification, error) {
|
||||
|
||||
func (s *Store) ListForVolunteer(ctx context.Context, volunteerID int64) ([]Notification, error) {
|
||||
rows, err := s.db.QueryContext(ctx,
|
||||
`SELECT id, volunteer_id, message, read, created_at FROM notifications WHERE volunteer_id = ? ORDER BY created_at DESC`,
|
||||
`SELECT id, volunteer_id, message, is_read, created_at FROM notifications WHERE volunteer_id = ? ORDER BY created_at DESC`,
|
||||
volunteerID,
|
||||
)
|
||||
if err != nil {
|
||||
@@ -77,9 +77,15 @@ func (s *Store) ListForVolunteer(ctx context.Context, volunteerID int64) ([]Noti
|
||||
return notifications, rows.Err()
|
||||
}
|
||||
|
||||
// CreateNotification satisfies the schedule.Notifier interface.
|
||||
func (s *Store) CreateNotification(ctx context.Context, volunteerID int64, message string) error {
|
||||
_, err := s.Create(ctx, volunteerID, message)
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *Store) MarkRead(ctx context.Context, id, volunteerID int64) (*Notification, error) {
|
||||
result, err := s.db.ExecContext(ctx,
|
||||
`UPDATE notifications SET read = 1 WHERE id = ? AND volunteer_id = ?`,
|
||||
`UPDATE notifications SET is_read = 1 WHERE id = ? AND volunteer_id = ?`,
|
||||
id, volunteerID,
|
||||
)
|
||||
if err != nil {
|
||||
|
||||
@@ -1,99 +1,358 @@
|
||||
package schedule
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"git.unsupervised.ca/walkies/internal/respond"
|
||||
"git.unsupervised.ca/walkies/internal/server/middleware"
|
||||
"github.com/go-chi/chi/v5"
|
||||
)
|
||||
|
||||
// Notifier is the subset of notification.Store the handler needs.
|
||||
type Notifier interface {
|
||||
CreateNotification(ctx context.Context, volunteerID int64, message string) error
|
||||
}
|
||||
|
||||
// TimeOffChecker checks whether a volunteer has approved time off on a date (FR-T06).
|
||||
type TimeOffChecker interface {
|
||||
HasApprovedTimeOff(ctx context.Context, volunteerID int64, date string) (bool, error)
|
||||
}
|
||||
|
||||
type Handler struct {
|
||||
store *Store
|
||||
store Storer
|
||||
notifier Notifier
|
||||
timeOffChecker TimeOffChecker
|
||||
}
|
||||
|
||||
func NewHandler(store *Store) *Handler {
|
||||
return &Handler{store: store}
|
||||
// Storer is the interface the Handler depends on.
|
||||
type Storer interface {
|
||||
CreateTemplate(ctx context.Context, in CreateTemplateInput) (*ShiftTemplate, error)
|
||||
GetTemplate(ctx context.Context, id int64) (*ShiftTemplate, error)
|
||||
ListTemplates(ctx context.Context) ([]ShiftTemplate, error)
|
||||
UpdateTemplate(ctx context.Context, id int64, in UpdateTemplateInput) (*ShiftTemplate, error)
|
||||
DeleteTemplate(ctx context.Context, id int64) error
|
||||
|
||||
GenerateInstances(ctx context.Context, year, month int) ([]ShiftInstance, error)
|
||||
ListInstances(ctx context.Context, year, month int, volunteerID int64) ([]ShiftInstance, error)
|
||||
GetInstance(ctx context.Context, id int64) (*ShiftInstance, error)
|
||||
UpdateInstance(ctx context.Context, id int64, in UpdateInstanceInput) (*ShiftInstance, []int64, error)
|
||||
PublishMonth(ctx context.Context, year, month int) (map[int64][]ShiftInstance, error)
|
||||
UnpublishMonth(ctx context.Context, year, month int) ([]int64, error)
|
||||
ConfirmShift(ctx context.Context, instanceID, volunteerID int64) error
|
||||
}
|
||||
|
||||
// GET /api/v1/schedules
|
||||
func (h *Handler) List(w http.ResponseWriter, r *http.Request) {
|
||||
claims := middleware.ClaimsFromContext(r.Context())
|
||||
volunteerID := int64(0)
|
||||
if claims.Role != "admin" {
|
||||
volunteerID = claims.VolunteerID
|
||||
}
|
||||
schedules, err := h.store.List(r.Context(), volunteerID)
|
||||
func NewHandler(store *Store, notifier Notifier, timeOffChecker TimeOffChecker) *Handler {
|
||||
return &Handler{store: store, notifier: notifier, timeOffChecker: timeOffChecker}
|
||||
}
|
||||
|
||||
// NewHandlerFromInterfaces constructs a Handler from interface values, intended for testing.
|
||||
func NewHandlerFromInterfaces(store Storer, notifier Notifier, timeOffChecker TimeOffChecker) *Handler {
|
||||
return &Handler{store: store, notifier: notifier, timeOffChecker: timeOffChecker}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Template handlers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// GET /api/v1/shift-templates
|
||||
func (h *Handler) ListTemplates(w http.ResponseWriter, r *http.Request) {
|
||||
templates, err := h.store.ListTemplates(r.Context())
|
||||
if err != nil {
|
||||
respond.Error(w, http.StatusInternalServerError, "could not list schedules")
|
||||
respond.Error(w, http.StatusInternalServerError, "could not list templates")
|
||||
return
|
||||
}
|
||||
if schedules == nil {
|
||||
schedules = []Schedule{}
|
||||
if templates == nil {
|
||||
templates = []ShiftTemplate{}
|
||||
}
|
||||
respond.JSON(w, http.StatusOK, schedules)
|
||||
respond.JSON(w, http.StatusOK, templates)
|
||||
}
|
||||
|
||||
// POST /api/v1/schedules
|
||||
func (h *Handler) Create(w http.ResponseWriter, r *http.Request) {
|
||||
claims := middleware.ClaimsFromContext(r.Context())
|
||||
var in CreateInput
|
||||
// POST /api/v1/shift-templates
|
||||
func (h *Handler) CreateTemplate(w http.ResponseWriter, r *http.Request) {
|
||||
var in CreateTemplateInput
|
||||
if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
|
||||
respond.Error(w, http.StatusBadRequest, "invalid request body")
|
||||
return
|
||||
}
|
||||
if claims.Role != "admin" {
|
||||
in.VolunteerID = claims.VolunteerID
|
||||
}
|
||||
if in.Title == "" || in.StartsAt == "" || in.EndsAt == "" {
|
||||
respond.Error(w, http.StatusBadRequest, "title, starts_at, and ends_at are required")
|
||||
if in.Name == "" || in.StartTime == "" || in.EndTime == "" {
|
||||
respond.Error(w, http.StatusBadRequest, "name, start_time, and end_time are required")
|
||||
return
|
||||
}
|
||||
sc, err := h.store.Create(r.Context(), in)
|
||||
if in.MinCapacity <= 0 {
|
||||
in.MinCapacity = 1
|
||||
}
|
||||
if in.MaxCapacity < in.MinCapacity {
|
||||
in.MaxCapacity = in.MinCapacity
|
||||
}
|
||||
t, err := h.store.CreateTemplate(r.Context(), in)
|
||||
if err != nil {
|
||||
respond.Error(w, http.StatusInternalServerError, "could not create schedule")
|
||||
respond.Error(w, http.StatusInternalServerError, "could not create template")
|
||||
return
|
||||
}
|
||||
respond.JSON(w, http.StatusCreated, sc)
|
||||
respond.JSON(w, http.StatusCreated, t)
|
||||
}
|
||||
|
||||
// PUT /api/v1/schedules/{id}
|
||||
func (h *Handler) Update(w http.ResponseWriter, r *http.Request) {
|
||||
// PUT /api/v1/shift-templates/{id}
|
||||
func (h *Handler) UpdateTemplate(w http.ResponseWriter, r *http.Request) {
|
||||
id, err := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64)
|
||||
if err != nil {
|
||||
respond.Error(w, http.StatusBadRequest, "invalid id")
|
||||
return
|
||||
}
|
||||
var in UpdateInput
|
||||
var in UpdateTemplateInput
|
||||
if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
|
||||
respond.Error(w, http.StatusBadRequest, "invalid request body")
|
||||
return
|
||||
}
|
||||
sc, err := h.store.Update(r.Context(), id, in)
|
||||
t, err := h.store.UpdateTemplate(r.Context(), id, in)
|
||||
if errors.Is(err, ErrNotFound) {
|
||||
respond.Error(w, http.StatusNotFound, "schedule not found")
|
||||
respond.Error(w, http.StatusNotFound, "template not found")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
respond.Error(w, http.StatusInternalServerError, "could not update schedule")
|
||||
respond.Error(w, http.StatusInternalServerError, "could not update template")
|
||||
return
|
||||
}
|
||||
respond.JSON(w, http.StatusOK, sc)
|
||||
respond.JSON(w, http.StatusOK, t)
|
||||
}
|
||||
|
||||
// DELETE /api/v1/schedules/{id}
|
||||
func (h *Handler) Delete(w http.ResponseWriter, r *http.Request) {
|
||||
// DELETE /api/v1/shift-templates/{id}
|
||||
func (h *Handler) DeleteTemplate(w http.ResponseWriter, r *http.Request) {
|
||||
id, err := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64)
|
||||
if err != nil {
|
||||
respond.Error(w, http.StatusBadRequest, "invalid id")
|
||||
return
|
||||
}
|
||||
if err := h.store.Delete(r.Context(), id); err != nil {
|
||||
respond.Error(w, http.StatusInternalServerError, "could not delete schedule")
|
||||
if err := h.store.DeleteTemplate(r.Context(), id); err != nil {
|
||||
respond.Error(w, http.StatusInternalServerError, "could not delete template")
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Instance handlers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// GET /api/v1/shifts?year=2026&month=4
|
||||
func (h *Handler) ListInstances(w http.ResponseWriter, r *http.Request) {
|
||||
year, month := parseYearMonth(r)
|
||||
claims := middleware.ClaimsFromContext(r.Context())
|
||||
|
||||
volunteerID := int64(0)
|
||||
if claims.Role != "admin" {
|
||||
volunteerID = claims.VolunteerID
|
||||
}
|
||||
|
||||
instances, err := h.store.ListInstances(r.Context(), year, month, volunteerID)
|
||||
if err != nil {
|
||||
respond.Error(w, http.StatusInternalServerError, "could not list shifts")
|
||||
return
|
||||
}
|
||||
if instances == nil {
|
||||
instances = []ShiftInstance{}
|
||||
}
|
||||
respond.JSON(w, http.StatusOK, instances)
|
||||
}
|
||||
|
||||
// POST /api/v1/shifts/generate body: {"year":2026,"month":4}
|
||||
func (h *Handler) GenerateInstances(w http.ResponseWriter, r *http.Request) {
|
||||
var body struct {
|
||||
Year int `json:"year"`
|
||||
Month int `json:"month"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
||||
respond.Error(w, http.StatusBadRequest, "invalid request body")
|
||||
return
|
||||
}
|
||||
if body.Year == 0 || body.Month < 1 || body.Month > 12 {
|
||||
respond.Error(w, http.StatusBadRequest, "valid year and month (1-12) are required")
|
||||
return
|
||||
}
|
||||
instances, err := h.store.GenerateInstances(r.Context(), body.Year, body.Month)
|
||||
if errors.Is(err, ErrAlreadyExists) {
|
||||
respond.Error(w, http.StatusConflict, "shifts already generated for this period")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
respond.Error(w, http.StatusInternalServerError, "could not generate shifts")
|
||||
return
|
||||
}
|
||||
respond.JSON(w, http.StatusCreated, instances)
|
||||
}
|
||||
|
||||
// POST /api/v1/shifts/publish body: {"year":2026,"month":4}
|
||||
func (h *Handler) PublishMonth(w http.ResponseWriter, r *http.Request) {
|
||||
var body struct {
|
||||
Year int `json:"year"`
|
||||
Month int `json:"month"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
||||
respond.Error(w, http.StatusBadRequest, "invalid request body")
|
||||
return
|
||||
}
|
||||
if body.Year == 0 || body.Month < 1 || body.Month > 12 {
|
||||
respond.Error(w, http.StatusBadRequest, "valid year and month (1-12) are required")
|
||||
return
|
||||
}
|
||||
|
||||
byVol, err := h.store.PublishMonth(r.Context(), body.Year, body.Month)
|
||||
if err != nil {
|
||||
respond.Error(w, http.StatusInternalServerError, "could not publish schedule")
|
||||
return
|
||||
}
|
||||
|
||||
// Notify each affected volunteer (FR-S04)
|
||||
mn := time.Month(body.Month).String()
|
||||
for vid, shifts := range byVol {
|
||||
msg := fmt.Sprintf("Your schedule for %s %d has been published. You have %d shift(s).",
|
||||
mn, body.Year, len(shifts))
|
||||
h.notifier.CreateNotification(r.Context(), vid, msg) //nolint:errcheck
|
||||
}
|
||||
|
||||
respond.JSON(w, http.StatusOK, map[string]any{
|
||||
"year": body.Year,
|
||||
"month": body.Month,
|
||||
})
|
||||
}
|
||||
|
||||
// POST /api/v1/shifts/unpublish body: {"year":2026,"month":4}
|
||||
func (h *Handler) UnpublishMonth(w http.ResponseWriter, r *http.Request) {
|
||||
var body struct {
|
||||
Year int `json:"year"`
|
||||
Month int `json:"month"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
||||
respond.Error(w, http.StatusBadRequest, "invalid request body")
|
||||
return
|
||||
}
|
||||
if body.Year == 0 || body.Month < 1 || body.Month > 12 {
|
||||
respond.Error(w, http.StatusBadRequest, "valid year and month (1-12) are required")
|
||||
return
|
||||
}
|
||||
|
||||
volunteerIDs, err := h.store.UnpublishMonth(r.Context(), body.Year, body.Month)
|
||||
if err != nil {
|
||||
respond.Error(w, http.StatusInternalServerError, "could not unpublish schedule")
|
||||
return
|
||||
}
|
||||
|
||||
// Notify affected volunteers (FR-S05)
|
||||
mn := time.Month(body.Month).String()
|
||||
for _, vid := range volunteerIDs {
|
||||
msg := fmt.Sprintf("The schedule for %s %d has been retracted.", mn, body.Year)
|
||||
h.notifier.CreateNotification(r.Context(), vid, msg) //nolint:errcheck
|
||||
}
|
||||
|
||||
respond.JSON(w, http.StatusOK, map[string]any{
|
||||
"year": body.Year,
|
||||
"month": body.Month,
|
||||
})
|
||||
}
|
||||
|
||||
// PUT /api/v1/shifts/{id}
|
||||
func (h *Handler) UpdateInstance(w http.ResponseWriter, r *http.Request) {
|
||||
id, err := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64)
|
||||
if err != nil {
|
||||
respond.Error(w, http.StatusBadRequest, "invalid id")
|
||||
return
|
||||
}
|
||||
var in UpdateInstanceInput
|
||||
if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
|
||||
respond.Error(w, http.StatusBadRequest, "invalid request body")
|
||||
return
|
||||
}
|
||||
|
||||
// FR-T06: Block assigning volunteers with approved time off on the shift date
|
||||
if in.VolunteerIDs != nil && h.timeOffChecker != nil {
|
||||
existing, getErr := h.store.GetInstance(r.Context(), id)
|
||||
if getErr != nil && !errors.Is(getErr, ErrNotFound) {
|
||||
respond.Error(w, http.StatusInternalServerError, "could not get shift")
|
||||
return
|
||||
}
|
||||
if existing != nil {
|
||||
for _, vid := range *in.VolunteerIDs {
|
||||
hasTimeOff, checkErr := h.timeOffChecker.HasApprovedTimeOff(r.Context(), vid, existing.Date)
|
||||
if checkErr != nil {
|
||||
respond.Error(w, http.StatusInternalServerError, "could not check time off")
|
||||
return
|
||||
}
|
||||
if hasTimeOff {
|
||||
respond.Error(w, http.StatusConflict,
|
||||
fmt.Sprintf("Volunteer %d has approved time off on %s. Remove the time off first.", vid, existing.Date))
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
inst, added, err := h.store.UpdateInstance(r.Context(), id, in)
|
||||
if errors.Is(err, ErrNotFound) {
|
||||
respond.Error(w, http.StatusNotFound, "shift not found")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
respond.Error(w, http.StatusInternalServerError, "could not update shift")
|
||||
return
|
||||
}
|
||||
|
||||
// Notify all volunteers on a published shift of the change (FR-S09)
|
||||
if inst.Status == "published" && in.VolunteerIDs != nil {
|
||||
for _, v := range inst.Volunteers {
|
||||
msg := fmt.Sprintf("Your shift on %s (%s–%s) has been updated. Please re-confirm.", inst.Date, inst.StartTime, inst.EndTime)
|
||||
h.notifier.CreateNotification(r.Context(), v.VolunteerID, msg) //nolint:errcheck
|
||||
}
|
||||
}
|
||||
|
||||
// Notify only newly added volunteers (FR-S10)
|
||||
if inst.Status == "published" && len(added) > 0 {
|
||||
for _, vid := range added {
|
||||
msg := fmt.Sprintf("You have been added to a shift on %s (%s–%s).", inst.Date, inst.StartTime, inst.EndTime)
|
||||
h.notifier.CreateNotification(r.Context(), vid, msg) //nolint:errcheck
|
||||
}
|
||||
}
|
||||
|
||||
respond.JSON(w, http.StatusOK, inst)
|
||||
}
|
||||
|
||||
// POST /api/v1/shifts/{id}/confirm
|
||||
func (h *Handler) ConfirmShift(w http.ResponseWriter, r *http.Request) {
|
||||
id, err := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64)
|
||||
if err != nil {
|
||||
respond.Error(w, http.StatusBadRequest, "invalid id")
|
||||
return
|
||||
}
|
||||
claims := middleware.ClaimsFromContext(r.Context())
|
||||
if err := h.store.ConfirmShift(r.Context(), id, claims.VolunteerID); err != nil {
|
||||
if errors.Is(err, ErrNotFound) {
|
||||
respond.Error(w, http.StatusNotFound, "shift assignment not found")
|
||||
return
|
||||
}
|
||||
respond.Error(w, http.StatusInternalServerError, "could not confirm shift")
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
func parseYearMonth(r *http.Request) (year, month int) {
|
||||
now := time.Now()
|
||||
year = now.Year()
|
||||
month = int(now.Month())
|
||||
if y, err := strconv.Atoi(r.URL.Query().Get("year")); err == nil {
|
||||
year = y
|
||||
}
|
||||
if m, err := strconv.Atoi(r.URL.Query().Get("month")); err == nil && m >= 1 && m <= 12 {
|
||||
month = m
|
||||
}
|
||||
return year, month
|
||||
}
|
||||
|
||||
476
internal/schedule/handler_test.go
Normal file
476
internal/schedule/handler_test.go
Normal file
@@ -0,0 +1,476 @@
|
||||
package schedule_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"git.unsupervised.ca/walkies/internal/auth"
|
||||
"git.unsupervised.ca/walkies/internal/schedule"
|
||||
"git.unsupervised.ca/walkies/internal/server/middleware"
|
||||
"github.com/go-chi/chi/v5"
|
||||
)
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Fakes
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
type fakeStore struct {
|
||||
templates []schedule.ShiftTemplate
|
||||
instances []schedule.ShiftInstance
|
||||
createTmpl *schedule.ShiftTemplate
|
||||
createErr error
|
||||
updateTmpl *schedule.ShiftTemplate
|
||||
updateErr error
|
||||
deleteErr error
|
||||
genResult []schedule.ShiftInstance
|
||||
genErr error
|
||||
publishResult map[int64][]schedule.ShiftInstance
|
||||
publishErr error
|
||||
unpubResult []int64
|
||||
unpubErr error
|
||||
updateInst *schedule.ShiftInstance
|
||||
addedVols []int64
|
||||
updateInstErr error
|
||||
confirmErr error
|
||||
}
|
||||
|
||||
func (f *fakeStore) CreateTemplate(_ context.Context, in schedule.CreateTemplateInput) (*schedule.ShiftTemplate, error) {
|
||||
if f.createErr != nil {
|
||||
return nil, f.createErr
|
||||
}
|
||||
if f.createTmpl != nil {
|
||||
return f.createTmpl, nil
|
||||
}
|
||||
return &schedule.ShiftTemplate{ID: 1, Name: in.Name, DayOfWeek: in.DayOfWeek,
|
||||
StartTime: in.StartTime, EndTime: in.EndTime,
|
||||
MinCapacity: in.MinCapacity, MaxCapacity: in.MaxCapacity,
|
||||
Roles: []schedule.TemplateRole{}, VolunteerIDs: []int64{}}, nil
|
||||
}
|
||||
|
||||
func (f *fakeStore) GetTemplate(_ context.Context, id int64) (*schedule.ShiftTemplate, error) {
|
||||
for _, t := range f.templates {
|
||||
if t.ID == id {
|
||||
return &t, nil
|
||||
}
|
||||
}
|
||||
return nil, schedule.ErrNotFound
|
||||
}
|
||||
|
||||
func (f *fakeStore) ListTemplates(_ context.Context) ([]schedule.ShiftTemplate, error) {
|
||||
return f.templates, nil
|
||||
}
|
||||
|
||||
func (f *fakeStore) UpdateTemplate(_ context.Context, id int64, _ schedule.UpdateTemplateInput) (*schedule.ShiftTemplate, error) {
|
||||
if f.updateErr != nil {
|
||||
return nil, f.updateErr
|
||||
}
|
||||
if f.updateTmpl != nil {
|
||||
return f.updateTmpl, nil
|
||||
}
|
||||
for _, t := range f.templates {
|
||||
if t.ID == id {
|
||||
return &t, nil
|
||||
}
|
||||
}
|
||||
return nil, schedule.ErrNotFound
|
||||
}
|
||||
|
||||
func (f *fakeStore) DeleteTemplate(_ context.Context, _ int64) error {
|
||||
return f.deleteErr
|
||||
}
|
||||
|
||||
func (f *fakeStore) GenerateInstances(_ context.Context, _, _ int) ([]schedule.ShiftInstance, error) {
|
||||
return f.genResult, f.genErr
|
||||
}
|
||||
|
||||
func (f *fakeStore) ListInstances(_ context.Context, _, _ int, _ int64) ([]schedule.ShiftInstance, error) {
|
||||
return f.instances, nil
|
||||
}
|
||||
|
||||
func (f *fakeStore) GetInstance(_ context.Context, id int64) (*schedule.ShiftInstance, error) {
|
||||
for _, inst := range f.instances {
|
||||
if inst.ID == id {
|
||||
return &inst, nil
|
||||
}
|
||||
}
|
||||
return nil, schedule.ErrNotFound
|
||||
}
|
||||
|
||||
func (f *fakeStore) UpdateInstance(_ context.Context, _ int64, _ schedule.UpdateInstanceInput) (*schedule.ShiftInstance, []int64, error) {
|
||||
return f.updateInst, f.addedVols, f.updateInstErr
|
||||
}
|
||||
|
||||
func (f *fakeStore) PublishMonth(_ context.Context, _, _ int) (map[int64][]schedule.ShiftInstance, error) {
|
||||
return f.publishResult, f.publishErr
|
||||
}
|
||||
|
||||
func (f *fakeStore) UnpublishMonth(_ context.Context, _, _ int) ([]int64, error) {
|
||||
return f.unpubResult, f.unpubErr
|
||||
}
|
||||
|
||||
func (f *fakeStore) ConfirmShift(_ context.Context, _, _ int64) error {
|
||||
return f.confirmErr
|
||||
}
|
||||
|
||||
type fakeNotifier struct {
|
||||
calls []struct {
|
||||
volunteerID int64
|
||||
message string
|
||||
}
|
||||
}
|
||||
|
||||
func (n *fakeNotifier) CreateNotification(_ context.Context, volunteerID int64, message string) error {
|
||||
n.calls = append(n.calls, struct {
|
||||
volunteerID int64
|
||||
message string
|
||||
}{volunteerID, message})
|
||||
return nil
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
func jwtForRole(t *testing.T, id int64, role string) string {
|
||||
t.Helper()
|
||||
svc := auth.NewService(nil, "test-secret")
|
||||
token, err := svc.IssueToken(id, role)
|
||||
if err != nil {
|
||||
t.Fatalf("issue token: %v", err)
|
||||
}
|
||||
return token
|
||||
}
|
||||
|
||||
func newRouter(h *schedule.Handler) http.Handler {
|
||||
realAuthSvc := auth.NewService(nil, "test-secret")
|
||||
r := chi.NewRouter()
|
||||
r.Group(func(r chi.Router) {
|
||||
r.Use(middleware.Authenticate(realAuthSvc))
|
||||
|
||||
r.Get("/api/v1/shift-templates", h.ListTemplates)
|
||||
r.Post("/api/v1/shift-templates",
|
||||
middleware.RequireAdmin(http.HandlerFunc(h.CreateTemplate)).ServeHTTP)
|
||||
r.Put("/api/v1/shift-templates/{id}",
|
||||
middleware.RequireAdmin(http.HandlerFunc(h.UpdateTemplate)).ServeHTTP)
|
||||
r.Delete("/api/v1/shift-templates/{id}",
|
||||
middleware.RequireAdmin(http.HandlerFunc(h.DeleteTemplate)).ServeHTTP)
|
||||
|
||||
r.Get("/api/v1/shifts", h.ListInstances)
|
||||
r.Post("/api/v1/shifts/generate",
|
||||
middleware.RequireAdmin(http.HandlerFunc(h.GenerateInstances)).ServeHTTP)
|
||||
r.Post("/api/v1/shifts/publish",
|
||||
middleware.RequireAdmin(http.HandlerFunc(h.PublishMonth)).ServeHTTP)
|
||||
r.Post("/api/v1/shifts/unpublish",
|
||||
middleware.RequireAdmin(http.HandlerFunc(h.UnpublishMonth)).ServeHTTP)
|
||||
r.Put("/api/v1/shifts/{id}",
|
||||
middleware.RequireAdmin(http.HandlerFunc(h.UpdateInstance)).ServeHTTP)
|
||||
r.Post("/api/v1/shifts/{id}/confirm", h.ConfirmShift)
|
||||
})
|
||||
return r
|
||||
}
|
||||
|
||||
func do(t *testing.T, router http.Handler, method, path, body, token string) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
var b *bytes.Reader
|
||||
if body != "" {
|
||||
b = bytes.NewReader([]byte(body))
|
||||
} else {
|
||||
b = bytes.NewReader(nil)
|
||||
}
|
||||
req := httptest.NewRequest(method, path, b)
|
||||
if body != "" {
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
}
|
||||
if token != "" {
|
||||
req.Header.Set("Authorization", "Bearer "+token)
|
||||
}
|
||||
w := httptest.NewRecorder()
|
||||
router.ServeHTTP(w, req)
|
||||
return w
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Template tests
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
func TestListTemplates_ReturnsEmpty(t *testing.T) {
|
||||
store := &fakeStore{}
|
||||
notifier := &fakeNotifier{}
|
||||
h := schedule.NewHandlerFromInterfaces(store, notifier, nil)
|
||||
router := newRouter(h)
|
||||
|
||||
token := jwtForRole(t, 1, "admin")
|
||||
w := do(t, router, "GET", "/api/v1/shift-templates", "", token)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("expected 200, got %d: %s", w.Code, w.Body)
|
||||
}
|
||||
var result []schedule.ShiftTemplate
|
||||
json.NewDecoder(w.Body).Decode(&result)
|
||||
if len(result) != 0 {
|
||||
t.Errorf("expected empty list, got %d items", len(result))
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateTemplate_AdminOnly(t *testing.T) {
|
||||
store := &fakeStore{}
|
||||
notifier := &fakeNotifier{}
|
||||
h := schedule.NewHandlerFromInterfaces(store, notifier, nil)
|
||||
router := newRouter(h)
|
||||
|
||||
token := jwtForRole(t, 2, "volunteer")
|
||||
w := do(t, router, "POST", "/api/v1/shift-templates",
|
||||
`{"name":"Morning","day_of_week":1,"start_time":"09:00:00","end_time":"12:00:00","min_capacity":2,"max_capacity":5}`,
|
||||
token)
|
||||
|
||||
if w.Code != http.StatusForbidden {
|
||||
t.Fatalf("expected 403, got %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateTemplate_Success(t *testing.T) {
|
||||
store := &fakeStore{}
|
||||
notifier := &fakeNotifier{}
|
||||
h := schedule.NewHandlerFromInterfaces(store, notifier, nil)
|
||||
router := newRouter(h)
|
||||
|
||||
token := jwtForRole(t, 1, "admin")
|
||||
w := do(t, router, "POST", "/api/v1/shift-templates",
|
||||
`{"name":"Morning","day_of_week":1,"start_time":"09:00:00","end_time":"12:00:00","min_capacity":2,"max_capacity":5}`,
|
||||
token)
|
||||
|
||||
if w.Code != http.StatusCreated {
|
||||
t.Fatalf("expected 201, got %d: %s", w.Code, w.Body)
|
||||
}
|
||||
var tmpl schedule.ShiftTemplate
|
||||
json.NewDecoder(w.Body).Decode(&tmpl)
|
||||
if tmpl.Name != "Morning" {
|
||||
t.Errorf("expected name Morning, got %q", tmpl.Name)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateTemplate_MissingFields(t *testing.T) {
|
||||
store := &fakeStore{}
|
||||
notifier := &fakeNotifier{}
|
||||
h := schedule.NewHandlerFromInterfaces(store, notifier, nil)
|
||||
router := newRouter(h)
|
||||
|
||||
token := jwtForRole(t, 1, "admin")
|
||||
w := do(t, router, "POST", "/api/v1/shift-templates",
|
||||
`{"day_of_week":1}`, token)
|
||||
|
||||
if w.Code != http.StatusBadRequest {
|
||||
t.Fatalf("expected 400, got %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeleteTemplate_AdminOnly(t *testing.T) {
|
||||
store := &fakeStore{}
|
||||
notifier := &fakeNotifier{}
|
||||
h := schedule.NewHandlerFromInterfaces(store, notifier, nil)
|
||||
router := newRouter(h)
|
||||
|
||||
token := jwtForRole(t, 2, "volunteer")
|
||||
w := do(t, router, "DELETE", "/api/v1/shift-templates/1", "", token)
|
||||
|
||||
if w.Code != http.StatusForbidden {
|
||||
t.Fatalf("expected 403, got %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeleteTemplate_Success(t *testing.T) {
|
||||
store := &fakeStore{}
|
||||
notifier := &fakeNotifier{}
|
||||
h := schedule.NewHandlerFromInterfaces(store, notifier, nil)
|
||||
router := newRouter(h)
|
||||
|
||||
token := jwtForRole(t, 1, "admin")
|
||||
w := do(t, router, "DELETE", "/api/v1/shift-templates/1", "", token)
|
||||
|
||||
if w.Code != http.StatusNoContent {
|
||||
t.Fatalf("expected 204, got %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Instance tests
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
func TestGenerateInstances_AdminOnly(t *testing.T) {
|
||||
store := &fakeStore{}
|
||||
notifier := &fakeNotifier{}
|
||||
h := schedule.NewHandlerFromInterfaces(store, notifier, nil)
|
||||
router := newRouter(h)
|
||||
|
||||
token := jwtForRole(t, 2, "volunteer")
|
||||
w := do(t, router, "POST", "/api/v1/shifts/generate",
|
||||
`{"year":2026,"month":4}`, token)
|
||||
|
||||
if w.Code != http.StatusForbidden {
|
||||
t.Fatalf("expected 403, got %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGenerateInstances_AlreadyExists(t *testing.T) {
|
||||
store := &fakeStore{genErr: schedule.ErrAlreadyExists}
|
||||
notifier := &fakeNotifier{}
|
||||
h := schedule.NewHandlerFromInterfaces(store, notifier, nil)
|
||||
router := newRouter(h)
|
||||
|
||||
token := jwtForRole(t, 1, "admin")
|
||||
w := do(t, router, "POST", "/api/v1/shifts/generate",
|
||||
`{"year":2026,"month":4}`, token)
|
||||
|
||||
if w.Code != http.StatusConflict {
|
||||
t.Fatalf("expected 409, got %d: %s", w.Code, w.Body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGenerateInstances_Success(t *testing.T) {
|
||||
store := &fakeStore{
|
||||
genResult: []schedule.ShiftInstance{
|
||||
{ID: 1, Name: "Morning", Date: "2026-04-06", Status: "draft", Volunteers: []schedule.InstanceVolunteer{}},
|
||||
},
|
||||
}
|
||||
notifier := &fakeNotifier{}
|
||||
h := schedule.NewHandlerFromInterfaces(store, notifier, nil)
|
||||
router := newRouter(h)
|
||||
|
||||
token := jwtForRole(t, 1, "admin")
|
||||
w := do(t, router, "POST", "/api/v1/shifts/generate",
|
||||
`{"year":2026,"month":4}`, token)
|
||||
|
||||
if w.Code != http.StatusCreated {
|
||||
t.Fatalf("expected 201, got %d: %s", w.Code, w.Body)
|
||||
}
|
||||
var result []schedule.ShiftInstance
|
||||
json.NewDecoder(w.Body).Decode(&result)
|
||||
if len(result) != 1 {
|
||||
t.Errorf("expected 1 instance, got %d", len(result))
|
||||
}
|
||||
}
|
||||
|
||||
func TestPublishMonth_SendsNotifications(t *testing.T) {
|
||||
store := &fakeStore{
|
||||
publishResult: map[int64][]schedule.ShiftInstance{
|
||||
10: {{ID: 1, Name: "Morning", Date: "2026-04-06", Volunteers: []schedule.InstanceVolunteer{}}},
|
||||
20: {{ID: 2, Name: "Morning", Date: "2026-04-13", Volunteers: []schedule.InstanceVolunteer{}}},
|
||||
},
|
||||
}
|
||||
notifier := &fakeNotifier{}
|
||||
h := schedule.NewHandlerFromInterfaces(store, notifier, nil)
|
||||
router := newRouter(h)
|
||||
|
||||
token := jwtForRole(t, 1, "admin")
|
||||
w := do(t, router, "POST", "/api/v1/shifts/publish",
|
||||
`{"year":2026,"month":4}`, token)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("expected 200, got %d: %s", w.Code, w.Body)
|
||||
}
|
||||
if len(notifier.calls) != 2 {
|
||||
t.Errorf("expected 2 notifications, got %d", len(notifier.calls))
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnpublishMonth_SendsNotifications(t *testing.T) {
|
||||
store := &fakeStore{unpubResult: []int64{10, 20}}
|
||||
notifier := &fakeNotifier{}
|
||||
h := schedule.NewHandlerFromInterfaces(store, notifier, nil)
|
||||
router := newRouter(h)
|
||||
|
||||
token := jwtForRole(t, 1, "admin")
|
||||
w := do(t, router, "POST", "/api/v1/shifts/unpublish",
|
||||
`{"year":2026,"month":4}`, token)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("expected 200, got %d: %s", w.Code, w.Body)
|
||||
}
|
||||
if len(notifier.calls) != 2 {
|
||||
t.Errorf("expected 2 notifications, got %d", len(notifier.calls))
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpdateInstance_AdminOnly(t *testing.T) {
|
||||
store := &fakeStore{}
|
||||
notifier := &fakeNotifier{}
|
||||
h := schedule.NewHandlerFromInterfaces(store, notifier, nil)
|
||||
router := newRouter(h)
|
||||
|
||||
token := jwtForRole(t, 2, "volunteer")
|
||||
w := do(t, router, "PUT", "/api/v1/shifts/1",
|
||||
`{"volunteer_ids":[5]}`, token)
|
||||
|
||||
if w.Code != http.StatusForbidden {
|
||||
t.Fatalf("expected 403, got %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpdateInstance_PublishedResetsAndNotifies(t *testing.T) {
|
||||
vids := []int64{5, 6}
|
||||
store := &fakeStore{
|
||||
updateInst: &schedule.ShiftInstance{
|
||||
ID: 1, Status: "published", Date: "2026-04-06",
|
||||
StartTime: "09:00:00", EndTime: "12:00:00",
|
||||
Volunteers: []schedule.InstanceVolunteer{
|
||||
{InstanceID: 1, VolunteerID: 5, Name: "Alice"},
|
||||
{InstanceID: 1, VolunteerID: 6, Name: "Bob"},
|
||||
},
|
||||
},
|
||||
addedVols: []int64{6}, // Bob is newly added
|
||||
}
|
||||
notifier := &fakeNotifier{}
|
||||
h := schedule.NewHandlerFromInterfaces(store, notifier, nil)
|
||||
router := newRouter(h)
|
||||
|
||||
token := jwtForRole(t, 1, "admin")
|
||||
body, _ := json.Marshal(map[string]any{"volunteer_ids": vids})
|
||||
w := do(t, router, "PUT", "/api/v1/shifts/1", string(body), token)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("expected 200, got %d: %s", w.Code, w.Body)
|
||||
}
|
||||
// 2 notifications for existing volunteers (reset) + 1 for newly added
|
||||
// Total = 3 but FR-S10 is a subset of FR-S09, so we don't double-count
|
||||
// The handler sends update notices to all current volunteers (2) and
|
||||
// an "added" notice only to the newly added one (1) = 3 notifications.
|
||||
if len(notifier.calls) != 3 {
|
||||
t.Errorf("expected 3 notifications (2 reset + 1 added), got %d", len(notifier.calls))
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfirmShift_NotAssigned(t *testing.T) {
|
||||
store := &fakeStore{confirmErr: schedule.ErrNotFound}
|
||||
notifier := &fakeNotifier{}
|
||||
h := schedule.NewHandlerFromInterfaces(store, notifier, nil)
|
||||
router := newRouter(h)
|
||||
|
||||
token := jwtForRole(t, 5, "volunteer")
|
||||
w := do(t, router, "POST", "/api/v1/shifts/99/confirm", "", token)
|
||||
|
||||
if w.Code != http.StatusNotFound {
|
||||
t.Fatalf("expected 404, got %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfirmShift_Success(t *testing.T) {
|
||||
store := &fakeStore{}
|
||||
notifier := &fakeNotifier{}
|
||||
h := schedule.NewHandlerFromInterfaces(store, notifier, nil)
|
||||
router := newRouter(h)
|
||||
|
||||
token := jwtForRole(t, 5, "volunteer")
|
||||
w := do(t, router, "POST", "/api/v1/shifts/1/confirm", "", token)
|
||||
|
||||
if w.Code != http.StatusNoContent {
|
||||
t.Fatalf("expected 204, got %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// Compile-time interface check
|
||||
var _ schedule.Storer = (*fakeStore)(nil)
|
||||
var _ schedule.Notifier = (*fakeNotifier)(nil)
|
||||
@@ -8,35 +8,96 @@ import (
|
||||
"time"
|
||||
)
|
||||
|
||||
var ErrNotFound = fmt.Errorf("schedule not found")
|
||||
var (
|
||||
ErrNotFound = fmt.Errorf("not found")
|
||||
ErrAlreadyExists = fmt.Errorf("instances already generated for this period")
|
||||
)
|
||||
|
||||
type Schedule struct {
|
||||
// ---------------------------------------------------------------------------
|
||||
// Models
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
type ShiftTemplate struct {
|
||||
ID int64 `json:"id"`
|
||||
VolunteerID int64 `json:"volunteer_id"`
|
||||
Title string `json:"title"`
|
||||
StartsAt time.Time `json:"starts_at"`
|
||||
EndsAt time.Time `json:"ends_at"`
|
||||
Notes string `json:"notes,omitempty"`
|
||||
Name string `json:"name"`
|
||||
DayOfWeek int `json:"day_of_week"` // matches time.Weekday: 0=Sun, 6=Sat
|
||||
StartTime string `json:"start_time"` // "HH:MM:SS"
|
||||
EndTime string `json:"end_time"`
|
||||
MinCapacity int `json:"min_capacity"`
|
||||
MaxCapacity int `json:"max_capacity"`
|
||||
Roles []TemplateRole `json:"roles"`
|
||||
VolunteerIDs []int64 `json:"volunteer_ids"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
type CreateInput struct {
|
||||
type TemplateRole struct {
|
||||
ID int64 `json:"id"`
|
||||
TemplateID int64 `json:"template_id"`
|
||||
RoleName string `json:"role_name"`
|
||||
Count int `json:"count"`
|
||||
}
|
||||
|
||||
type ShiftInstance struct {
|
||||
ID int64 `json:"id"`
|
||||
TemplateID *int64 `json:"template_id,omitempty"`
|
||||
Name string `json:"name"`
|
||||
Date string `json:"date"` // "YYYY-MM-DD"
|
||||
StartTime string `json:"start_time"`
|
||||
EndTime string `json:"end_time"`
|
||||
MinCapacity int `json:"min_capacity"`
|
||||
MaxCapacity int `json:"max_capacity"`
|
||||
Status string `json:"status"` // "draft" or "published"
|
||||
Year int `json:"year"`
|
||||
Month int `json:"month"`
|
||||
Volunteers []InstanceVolunteer `json:"volunteers"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
type InstanceVolunteer struct {
|
||||
InstanceID int64 `json:"instance_id"`
|
||||
VolunteerID int64 `json:"volunteer_id"`
|
||||
Title string `json:"title"`
|
||||
StartsAt string `json:"starts_at"`
|
||||
EndsAt string `json:"ends_at"`
|
||||
Notes string `json:"notes"`
|
||||
Name string `json:"name"`
|
||||
Confirmed bool `json:"confirmed"`
|
||||
ConfirmedAt *time.Time `json:"confirmed_at,omitempty"`
|
||||
}
|
||||
|
||||
type UpdateInput struct {
|
||||
Title *string `json:"title"`
|
||||
StartsAt *string `json:"starts_at"`
|
||||
EndsAt *string `json:"ends_at"`
|
||||
Notes *string `json:"notes"`
|
||||
// ---------------------------------------------------------------------------
|
||||
// Input types
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
type CreateTemplateInput struct {
|
||||
Name string `json:"name"`
|
||||
DayOfWeek int `json:"day_of_week"`
|
||||
StartTime string `json:"start_time"`
|
||||
EndTime string `json:"end_time"`
|
||||
MinCapacity int `json:"min_capacity"`
|
||||
MaxCapacity int `json:"max_capacity"`
|
||||
Roles []TemplateRole `json:"roles"`
|
||||
VolunteerIDs []int64 `json:"volunteer_ids"`
|
||||
}
|
||||
|
||||
const timeLayout = "2006-01-02T15:04:05Z"
|
||||
type UpdateTemplateInput struct {
|
||||
Name *string `json:"name"`
|
||||
DayOfWeek *int `json:"day_of_week"`
|
||||
StartTime *string `json:"start_time"`
|
||||
EndTime *string `json:"end_time"`
|
||||
MinCapacity *int `json:"min_capacity"`
|
||||
MaxCapacity *int `json:"max_capacity"`
|
||||
Roles []TemplateRole `json:"roles"`
|
||||
VolunteerIDs []int64 `json:"volunteer_ids"`
|
||||
}
|
||||
|
||||
type UpdateInstanceInput struct {
|
||||
VolunteerIDs *[]int64 `json:"volunteer_ids"`
|
||||
MinCapacity *int `json:"min_capacity"`
|
||||
MaxCapacity *int `json:"max_capacity"`
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Store
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
type Store struct {
|
||||
db *sql.DB
|
||||
@@ -46,109 +107,614 @@ func NewStore(db *sql.DB) *Store {
|
||||
return &Store{db: db}
|
||||
}
|
||||
|
||||
func (s *Store) Create(ctx context.Context, in CreateInput) (*Schedule, error) {
|
||||
res, err := s.db.ExecContext(ctx,
|
||||
`INSERT INTO schedules (volunteer_id, title, starts_at, ends_at, notes) VALUES (?, ?, ?, ?, ?)`,
|
||||
in.VolunteerID, in.Title, in.StartsAt, in.EndsAt, in.Notes,
|
||||
// ---------------------------------------------------------------------------
|
||||
// Template operations
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
func (s *Store) CreateTemplate(ctx context.Context, in CreateTemplateInput) (*ShiftTemplate, error) {
|
||||
tx, err := s.db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("begin tx: %w", err)
|
||||
}
|
||||
defer tx.Rollback()
|
||||
|
||||
res, err := tx.ExecContext(ctx,
|
||||
`INSERT INTO shift_templates (name, day_of_week, start_time, end_time, min_capacity, max_capacity)
|
||||
VALUES (?, ?, ?, ?, ?, ?)`,
|
||||
in.Name, in.DayOfWeek, in.StartTime, in.EndTime, in.MinCapacity, in.MaxCapacity,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("insert schedule: %w", err)
|
||||
return nil, fmt.Errorf("insert template: %w", err)
|
||||
}
|
||||
id, _ := res.LastInsertId()
|
||||
return s.GetByID(ctx, id)
|
||||
|
||||
if err := upsertTemplateRoles(ctx, tx, id, in.Roles); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := upsertTemplateVolunteers(ctx, tx, id, in.VolunteerIDs); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := tx.Commit(); err != nil {
|
||||
return nil, fmt.Errorf("commit: %w", err)
|
||||
}
|
||||
return s.GetTemplate(ctx, id)
|
||||
}
|
||||
|
||||
func (s *Store) GetByID(ctx context.Context, id int64) (*Schedule, error) {
|
||||
sc := &Schedule{}
|
||||
var startsAt, endsAt, createdAt, updatedAt string
|
||||
var notes sql.NullString
|
||||
func (s *Store) GetTemplate(ctx context.Context, id int64) (*ShiftTemplate, error) {
|
||||
t := &ShiftTemplate{}
|
||||
var createdAt, updatedAt string
|
||||
err := s.db.QueryRowContext(ctx,
|
||||
`SELECT id, volunteer_id, title, starts_at, ends_at, notes, created_at, updated_at FROM schedules WHERE id = ?`, id,
|
||||
).Scan(&sc.ID, &sc.VolunteerID, &sc.Title, &startsAt, &endsAt, ¬es, &createdAt, &updatedAt)
|
||||
`SELECT id, name, day_of_week, start_time, end_time, min_capacity, max_capacity, created_at, updated_at
|
||||
FROM shift_templates WHERE id = ?`, id,
|
||||
).Scan(&t.ID, &t.Name, &t.DayOfWeek, &t.StartTime, &t.EndTime,
|
||||
&t.MinCapacity, &t.MaxCapacity, &createdAt, &updatedAt)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("get schedule: %w", err)
|
||||
return nil, fmt.Errorf("get template: %w", err)
|
||||
}
|
||||
sc.StartsAt, _ = time.Parse("2006-01-02 15:04:05", startsAt)
|
||||
sc.EndsAt, _ = time.Parse("2006-01-02 15:04:05", endsAt)
|
||||
sc.CreatedAt, _ = time.Parse("2006-01-02 15:04:05", createdAt)
|
||||
sc.UpdatedAt, _ = time.Parse("2006-01-02 15:04:05", updatedAt)
|
||||
if notes.Valid {
|
||||
sc.Notes = notes.String
|
||||
t.CreatedAt, _ = time.Parse("2006-01-02 15:04:05", createdAt)
|
||||
t.UpdatedAt, _ = time.Parse("2006-01-02 15:04:05", updatedAt)
|
||||
|
||||
roles, err := s.templateRoles(ctx, id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return sc, nil
|
||||
t.Roles = roles
|
||||
|
||||
vids, err := s.templateVolunteerIDs(ctx, id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
t.VolunteerIDs = vids
|
||||
return t, nil
|
||||
}
|
||||
|
||||
func (s *Store) List(ctx context.Context, volunteerID int64) ([]Schedule, error) {
|
||||
query := `SELECT id, volunteer_id, title, starts_at, ends_at, notes, created_at, updated_at FROM schedules`
|
||||
args := []any{}
|
||||
if volunteerID > 0 {
|
||||
query += ` WHERE volunteer_id = ?`
|
||||
args = append(args, volunteerID)
|
||||
}
|
||||
query += ` ORDER BY starts_at`
|
||||
|
||||
rows, err := s.db.QueryContext(ctx, query, args...)
|
||||
func (s *Store) ListTemplates(ctx context.Context) ([]ShiftTemplate, error) {
|
||||
rows, err := s.db.QueryContext(ctx,
|
||||
`SELECT id, name, day_of_week, start_time, end_time, min_capacity, max_capacity, created_at, updated_at
|
||||
FROM shift_templates ORDER BY day_of_week, start_time`)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("list schedules: %w", err)
|
||||
return nil, fmt.Errorf("list templates: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var schedules []Schedule
|
||||
var templates []ShiftTemplate
|
||||
for rows.Next() {
|
||||
var sc Schedule
|
||||
var startsAt, endsAt, createdAt, updatedAt string
|
||||
var notes sql.NullString
|
||||
if err := rows.Scan(&sc.ID, &sc.VolunteerID, &sc.Title, &startsAt, &endsAt, ¬es, &createdAt, &updatedAt); err != nil {
|
||||
var t ShiftTemplate
|
||||
var createdAt, updatedAt string
|
||||
if err := rows.Scan(&t.ID, &t.Name, &t.DayOfWeek, &t.StartTime, &t.EndTime,
|
||||
&t.MinCapacity, &t.MaxCapacity, &createdAt, &updatedAt); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
sc.StartsAt, _ = time.Parse("2006-01-02 15:04:05", startsAt)
|
||||
sc.EndsAt, _ = time.Parse("2006-01-02 15:04:05", endsAt)
|
||||
sc.CreatedAt, _ = time.Parse("2006-01-02 15:04:05", createdAt)
|
||||
sc.UpdatedAt, _ = time.Parse("2006-01-02 15:04:05", updatedAt)
|
||||
if notes.Valid {
|
||||
sc.Notes = notes.String
|
||||
t.CreatedAt, _ = time.Parse("2006-01-02 15:04:05", createdAt)
|
||||
t.UpdatedAt, _ = time.Parse("2006-01-02 15:04:05", updatedAt)
|
||||
templates = append(templates, t)
|
||||
}
|
||||
schedules = append(schedules, sc)
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return schedules, rows.Err()
|
||||
}
|
||||
|
||||
func (s *Store) Update(ctx context.Context, id int64, in UpdateInput) (*Schedule, error) {
|
||||
sc, err := s.GetByID(ctx, id)
|
||||
// Load roles and volunteers for each template
|
||||
for i := range templates {
|
||||
roles, err := s.templateRoles(ctx, templates[i].ID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
title := sc.Title
|
||||
startsAt := sc.StartsAt.Format("2006-01-02 15:04:05")
|
||||
endsAt := sc.EndsAt.Format("2006-01-02 15:04:05")
|
||||
notes := sc.Notes
|
||||
templates[i].Roles = roles
|
||||
|
||||
if in.Title != nil {
|
||||
title = *in.Title
|
||||
vids, err := s.templateVolunteerIDs(ctx, templates[i].ID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if in.StartsAt != nil {
|
||||
startsAt = *in.StartsAt
|
||||
templates[i].VolunteerIDs = vids
|
||||
}
|
||||
if in.EndsAt != nil {
|
||||
endsAt = *in.EndsAt
|
||||
return templates, nil
|
||||
}
|
||||
|
||||
func (s *Store) UpdateTemplate(ctx context.Context, id int64, in UpdateTemplateInput) (*ShiftTemplate, error) {
|
||||
t, err := s.GetTemplate(ctx, id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if in.Notes != nil {
|
||||
notes = *in.Notes
|
||||
|
||||
name := t.Name
|
||||
dow := t.DayOfWeek
|
||||
startTime := t.StartTime
|
||||
endTime := t.EndTime
|
||||
minCap := t.MinCapacity
|
||||
maxCap := t.MaxCapacity
|
||||
|
||||
if in.Name != nil {
|
||||
name = *in.Name
|
||||
}
|
||||
_, err = s.db.ExecContext(ctx,
|
||||
`UPDATE schedules SET title=?, starts_at=?, ends_at=?, notes=?, updated_at=NOW() WHERE id=?`,
|
||||
title, startsAt, endsAt, notes, id,
|
||||
if in.DayOfWeek != nil {
|
||||
dow = *in.DayOfWeek
|
||||
}
|
||||
if in.StartTime != nil {
|
||||
startTime = *in.StartTime
|
||||
}
|
||||
if in.EndTime != nil {
|
||||
endTime = *in.EndTime
|
||||
}
|
||||
if in.MinCapacity != nil {
|
||||
minCap = *in.MinCapacity
|
||||
}
|
||||
if in.MaxCapacity != nil {
|
||||
maxCap = *in.MaxCapacity
|
||||
}
|
||||
|
||||
tx, err := s.db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("begin tx: %w", err)
|
||||
}
|
||||
defer tx.Rollback()
|
||||
|
||||
_, err = tx.ExecContext(ctx,
|
||||
`UPDATE shift_templates SET name=?, day_of_week=?, start_time=?, end_time=?,
|
||||
min_capacity=?, max_capacity=?, updated_at=NOW() WHERE id=?`,
|
||||
name, dow, startTime, endTime, minCap, maxCap, id,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("update schedule: %w", err)
|
||||
return nil, fmt.Errorf("update template: %w", err)
|
||||
}
|
||||
return s.GetByID(ctx, id)
|
||||
|
||||
if in.Roles != nil {
|
||||
if _, err := tx.ExecContext(ctx, `DELETE FROM shift_template_roles WHERE template_id = ?`, id); err != nil {
|
||||
return nil, fmt.Errorf("clear roles: %w", err)
|
||||
}
|
||||
if err := upsertTemplateRoles(ctx, tx, id, in.Roles); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
if in.VolunteerIDs != nil {
|
||||
if _, err := tx.ExecContext(ctx, `DELETE FROM shift_template_volunteers WHERE template_id = ?`, id); err != nil {
|
||||
return nil, fmt.Errorf("clear volunteers: %w", err)
|
||||
}
|
||||
if err := upsertTemplateVolunteers(ctx, tx, id, in.VolunteerIDs); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
if err := tx.Commit(); err != nil {
|
||||
return nil, fmt.Errorf("commit: %w", err)
|
||||
}
|
||||
return s.GetTemplate(ctx, id)
|
||||
}
|
||||
|
||||
func (s *Store) Delete(ctx context.Context, id int64) error {
|
||||
_, err := s.db.ExecContext(ctx, `DELETE FROM schedules WHERE id = ?`, id)
|
||||
func (s *Store) DeleteTemplate(ctx context.Context, id int64) error {
|
||||
_, err := s.db.ExecContext(ctx, `DELETE FROM shift_templates WHERE id = ?`, id)
|
||||
return err
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Instance operations
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// GenerateInstances creates draft shift instances for every template × date in
|
||||
// the given month. Returns ErrAlreadyExists if instances already exist for
|
||||
// that month (FR-S02).
|
||||
func (s *Store) GenerateInstances(ctx context.Context, year, month int) ([]ShiftInstance, error) {
|
||||
var count int
|
||||
if err := s.db.QueryRowContext(ctx,
|
||||
`SELECT COUNT(*) FROM shift_instances WHERE year = ? AND month = ?`, year, month,
|
||||
).Scan(&count); err != nil {
|
||||
return nil, fmt.Errorf("check existing: %w", err)
|
||||
}
|
||||
if count > 0 {
|
||||
return nil, ErrAlreadyExists
|
||||
}
|
||||
|
||||
templates, err := s.ListTemplates(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Find all dates in the month for each template's day of week
|
||||
first := time.Date(year, time.Month(month), 1, 0, 0, 0, 0, time.UTC)
|
||||
daysInMonth := daysIn(year, month)
|
||||
|
||||
tx, err := s.db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("begin tx: %w", err)
|
||||
}
|
||||
defer tx.Rollback()
|
||||
|
||||
var instanceIDs []int64
|
||||
for _, tmpl := range templates {
|
||||
for d := 0; d < daysInMonth; d++ {
|
||||
day := first.AddDate(0, 0, d)
|
||||
if int(day.Weekday()) != tmpl.DayOfWeek {
|
||||
continue
|
||||
}
|
||||
res, err := tx.ExecContext(ctx,
|
||||
`INSERT INTO shift_instances
|
||||
(template_id, name, date, start_time, end_time, min_capacity, max_capacity, status, year, month)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, 'draft', ?, ?)`,
|
||||
tmpl.ID, tmpl.Name, day.Format("2006-01-02"),
|
||||
tmpl.StartTime, tmpl.EndTime,
|
||||
tmpl.MinCapacity, tmpl.MaxCapacity,
|
||||
year, month,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("insert instance: %w", err)
|
||||
}
|
||||
instID, _ := res.LastInsertId()
|
||||
instanceIDs = append(instanceIDs, instID)
|
||||
|
||||
// Copy recurring volunteer assignments from template
|
||||
for _, vid := range tmpl.VolunteerIDs {
|
||||
if _, err := tx.ExecContext(ctx,
|
||||
`INSERT IGNORE INTO shift_instance_volunteers (instance_id, volunteer_id) VALUES (?, ?)`,
|
||||
instID, vid,
|
||||
); err != nil {
|
||||
return nil, fmt.Errorf("copy volunteer: %w", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if err := tx.Commit(); err != nil {
|
||||
return nil, fmt.Errorf("commit: %w", err)
|
||||
}
|
||||
|
||||
return s.ListInstances(ctx, year, month, 0)
|
||||
}
|
||||
|
||||
// ListInstances returns instances for a month. When volunteerID > 0, only
|
||||
// returns published instances where that volunteer is assigned.
|
||||
func (s *Store) ListInstances(ctx context.Context, year, month int, volunteerID int64) ([]ShiftInstance, error) {
|
||||
query := `SELECT id, template_id, name, date, start_time, end_time,
|
||||
min_capacity, max_capacity, status, year, month, created_at, updated_at
|
||||
FROM shift_instances WHERE year = ? AND month = ?`
|
||||
args := []any{year, month}
|
||||
|
||||
if volunteerID > 0 {
|
||||
query += ` AND status = 'published'
|
||||
AND id IN (SELECT instance_id FROM shift_instance_volunteers WHERE volunteer_id = ?)`
|
||||
args = append(args, volunteerID)
|
||||
}
|
||||
query += ` ORDER BY date, start_time`
|
||||
|
||||
rows, err := s.db.QueryContext(ctx, query, args...)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("list instances: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var instances []ShiftInstance
|
||||
for rows.Next() {
|
||||
inst, err := scanInstance(rows)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
instances = append(instances, *inst)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
for i := range instances {
|
||||
vols, err := s.instanceVolunteers(ctx, instances[i].ID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
instances[i].Volunteers = vols
|
||||
}
|
||||
return instances, nil
|
||||
}
|
||||
|
||||
func (s *Store) GetInstance(ctx context.Context, id int64) (*ShiftInstance, error) {
|
||||
row := s.db.QueryRowContext(ctx,
|
||||
`SELECT id, template_id, name, date, start_time, end_time,
|
||||
min_capacity, max_capacity, status, year, month, created_at, updated_at
|
||||
FROM shift_instances WHERE id = ?`, id)
|
||||
inst, err := scanInstanceRow(row)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("get instance: %w", err)
|
||||
}
|
||||
vols, err := s.instanceVolunteers(ctx, inst.ID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
inst.Volunteers = vols
|
||||
return inst, nil
|
||||
}
|
||||
|
||||
// UpdateInstance edits volunteer assignments and/or capacity on any instance.
|
||||
// For published instances, volunteer confirmation statuses are reset (FR-S09).
|
||||
// Returns the previous and new volunteer ID sets so the caller can send notifications.
|
||||
func (s *Store) UpdateInstance(ctx context.Context, id int64, in UpdateInstanceInput) (inst *ShiftInstance, added []int64, err error) {
|
||||
inst, err = s.GetInstance(ctx, id)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
tx, txErr := s.db.BeginTx(ctx, nil)
|
||||
if txErr != nil {
|
||||
return nil, nil, fmt.Errorf("begin tx: %w", txErr)
|
||||
}
|
||||
defer tx.Rollback()
|
||||
|
||||
if in.MinCapacity != nil || in.MaxCapacity != nil {
|
||||
minCap := inst.MinCapacity
|
||||
maxCap := inst.MaxCapacity
|
||||
if in.MinCapacity != nil {
|
||||
minCap = *in.MinCapacity
|
||||
}
|
||||
if in.MaxCapacity != nil {
|
||||
maxCap = *in.MaxCapacity
|
||||
}
|
||||
if _, err := tx.ExecContext(ctx,
|
||||
`UPDATE shift_instances SET min_capacity=?, max_capacity=?, updated_at=NOW() WHERE id=?`,
|
||||
minCap, maxCap, id,
|
||||
); err != nil {
|
||||
return nil, nil, fmt.Errorf("update capacity: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
if in.VolunteerIDs != nil {
|
||||
// Determine newly added volunteers (FR-S10)
|
||||
existing := make(map[int64]bool)
|
||||
for _, v := range inst.Volunteers {
|
||||
existing[v.VolunteerID] = true
|
||||
}
|
||||
for _, vid := range *in.VolunteerIDs {
|
||||
if !existing[vid] {
|
||||
added = append(added, vid)
|
||||
}
|
||||
}
|
||||
|
||||
// Replace assignments
|
||||
if _, err := tx.ExecContext(ctx,
|
||||
`DELETE FROM shift_instance_volunteers WHERE instance_id = ?`, id,
|
||||
); err != nil {
|
||||
return nil, nil, fmt.Errorf("clear volunteers: %w", err)
|
||||
}
|
||||
for _, vid := range *in.VolunteerIDs {
|
||||
if _, err := tx.ExecContext(ctx,
|
||||
`INSERT INTO shift_instance_volunteers (instance_id, volunteer_id) VALUES (?, ?)`,
|
||||
id, vid,
|
||||
); err != nil {
|
||||
return nil, nil, fmt.Errorf("insert volunteer: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Reset confirmation for published shifts (FR-S09)
|
||||
if inst.Status == "published" {
|
||||
if _, err := tx.ExecContext(ctx,
|
||||
`UPDATE shift_instance_volunteers SET confirmed=0, confirmed_at=NULL WHERE instance_id=?`, id,
|
||||
); err != nil {
|
||||
return nil, nil, fmt.Errorf("reset confirmations: %w", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if err := tx.Commit(); err != nil {
|
||||
return nil, nil, fmt.Errorf("commit: %w", err)
|
||||
}
|
||||
|
||||
inst, err = s.GetInstance(ctx, id)
|
||||
return inst, added, err
|
||||
}
|
||||
|
||||
// PublishMonth marks all draft instances for the month as published and returns
|
||||
// a map of volunteerID → []ShiftInstance for notification purposes (FR-S04).
|
||||
func (s *Store) PublishMonth(ctx context.Context, year, month int) (map[int64][]ShiftInstance, error) {
|
||||
if _, err := s.db.ExecContext(ctx,
|
||||
`UPDATE shift_instances SET status='published', updated_at=NOW()
|
||||
WHERE year=? AND month=? AND status='draft'`, year, month,
|
||||
); err != nil {
|
||||
return nil, fmt.Errorf("publish: %w", err)
|
||||
}
|
||||
|
||||
instances, err := s.ListInstances(ctx, year, month, 0)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
byVol := make(map[int64][]ShiftInstance)
|
||||
for _, inst := range instances {
|
||||
for _, v := range inst.Volunteers {
|
||||
byVol[v.VolunteerID] = append(byVol[v.VolunteerID], inst)
|
||||
}
|
||||
}
|
||||
return byVol, nil
|
||||
}
|
||||
|
||||
// UnpublishMonth marks all published instances for the month back to draft and
|
||||
// returns volunteer IDs who had assignments (for notifications FR-S05).
|
||||
func (s *Store) UnpublishMonth(ctx context.Context, year, month int) ([]int64, error) {
|
||||
// Collect affected volunteer IDs before unpublishing
|
||||
rows, err := s.db.QueryContext(ctx,
|
||||
`SELECT DISTINCT siv.volunteer_id
|
||||
FROM shift_instance_volunteers siv
|
||||
JOIN shift_instances si ON siv.instance_id = si.id
|
||||
WHERE si.year=? AND si.month=? AND si.status='published'`, year, month,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("query volunteers: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var volunteerIDs []int64
|
||||
for rows.Next() {
|
||||
var vid int64
|
||||
if err := rows.Scan(&vid); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
volunteerIDs = append(volunteerIDs, vid)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if _, err := s.db.ExecContext(ctx,
|
||||
`UPDATE shift_instances SET status='draft', updated_at=NOW()
|
||||
WHERE year=? AND month=? AND status='published'`, year, month,
|
||||
); err != nil {
|
||||
return nil, fmt.Errorf("unpublish: %w", err)
|
||||
}
|
||||
|
||||
return volunteerIDs, nil
|
||||
}
|
||||
|
||||
// ConfirmShift marks a volunteer's attendance confirmation for a shift (FR-S06).
|
||||
func (s *Store) ConfirmShift(ctx context.Context, instanceID, volunteerID int64) error {
|
||||
result, err := s.db.ExecContext(ctx,
|
||||
`UPDATE shift_instance_volunteers SET confirmed=1, confirmed_at=NOW()
|
||||
WHERE instance_id=? AND volunteer_id=?`, instanceID, volunteerID,
|
||||
)
|
||||
if err != nil {
|
||||
return fmt.Errorf("confirm shift: %w", err)
|
||||
}
|
||||
affected, _ := result.RowsAffected()
|
||||
if affected == 0 {
|
||||
return ErrNotFound
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
func (s *Store) templateRoles(ctx context.Context, templateID int64) ([]TemplateRole, error) {
|
||||
rows, err := s.db.QueryContext(ctx,
|
||||
`SELECT id, template_id, role_name, count FROM shift_template_roles WHERE template_id = ?`, templateID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("get template roles: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
roles := make([]TemplateRole, 0)
|
||||
for rows.Next() {
|
||||
var r TemplateRole
|
||||
if err := rows.Scan(&r.ID, &r.TemplateID, &r.RoleName, &r.Count); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
roles = append(roles, r)
|
||||
}
|
||||
return roles, rows.Err()
|
||||
}
|
||||
|
||||
func (s *Store) templateVolunteerIDs(ctx context.Context, templateID int64) ([]int64, error) {
|
||||
rows, err := s.db.QueryContext(ctx,
|
||||
`SELECT volunteer_id FROM shift_template_volunteers WHERE template_id = ?`, templateID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("get template volunteers: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
ids := make([]int64, 0)
|
||||
for rows.Next() {
|
||||
var id int64
|
||||
if err := rows.Scan(&id); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ids = append(ids, id)
|
||||
}
|
||||
return ids, rows.Err()
|
||||
}
|
||||
|
||||
func (s *Store) instanceVolunteers(ctx context.Context, instanceID int64) ([]InstanceVolunteer, error) {
|
||||
rows, err := s.db.QueryContext(ctx,
|
||||
`SELECT siv.instance_id, siv.volunteer_id, v.name, siv.confirmed, siv.confirmed_at
|
||||
FROM shift_instance_volunteers siv
|
||||
JOIN volunteers v ON v.id = siv.volunteer_id
|
||||
WHERE siv.instance_id = ?
|
||||
ORDER BY v.name`, instanceID,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("get instance volunteers: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
vols := make([]InstanceVolunteer, 0)
|
||||
for rows.Next() {
|
||||
var iv InstanceVolunteer
|
||||
var confirmedAt sql.NullString
|
||||
if err := rows.Scan(&iv.InstanceID, &iv.VolunteerID, &iv.Name, &iv.Confirmed, &confirmedAt); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if confirmedAt.Valid {
|
||||
t, _ := time.Parse("2006-01-02 15:04:05", confirmedAt.String)
|
||||
iv.ConfirmedAt = &t
|
||||
}
|
||||
vols = append(vols, iv)
|
||||
}
|
||||
return vols, rows.Err()
|
||||
}
|
||||
|
||||
func upsertTemplateRoles(ctx context.Context, tx *sql.Tx, templateID int64, roles []TemplateRole) error {
|
||||
for _, r := range roles {
|
||||
if _, err := tx.ExecContext(ctx,
|
||||
`INSERT INTO shift_template_roles (template_id, role_name, count) VALUES (?, ?, ?)`,
|
||||
templateID, r.RoleName, r.Count,
|
||||
); err != nil {
|
||||
return fmt.Errorf("insert role: %w", err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func upsertTemplateVolunteers(ctx context.Context, tx *sql.Tx, templateID int64, volunteerIDs []int64) error {
|
||||
for _, vid := range volunteerIDs {
|
||||
if _, err := tx.ExecContext(ctx,
|
||||
`INSERT IGNORE INTO shift_template_volunteers (template_id, volunteer_id) VALUES (?, ?)`,
|
||||
templateID, vid,
|
||||
); err != nil {
|
||||
return fmt.Errorf("insert template volunteer: %w", err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type instanceScanner interface {
|
||||
Scan(dest ...any) error
|
||||
}
|
||||
|
||||
func scanInstance(r instanceScanner) (*ShiftInstance, error) {
|
||||
var inst ShiftInstance
|
||||
var templateID sql.NullInt64
|
||||
var createdAt, updatedAt string
|
||||
if err := r.Scan(&inst.ID, &templateID, &inst.Name, &inst.Date, &inst.StartTime, &inst.EndTime,
|
||||
&inst.MinCapacity, &inst.MaxCapacity, &inst.Status, &inst.Year, &inst.Month,
|
||||
&createdAt, &updatedAt); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if templateID.Valid {
|
||||
inst.TemplateID = &templateID.Int64
|
||||
}
|
||||
inst.CreatedAt, _ = time.Parse("2006-01-02 15:04:05", createdAt)
|
||||
inst.UpdatedAt, _ = time.Parse("2006-01-02 15:04:05", updatedAt)
|
||||
if inst.Volunteers == nil {
|
||||
inst.Volunteers = []InstanceVolunteer{}
|
||||
}
|
||||
return &inst, nil
|
||||
}
|
||||
|
||||
func scanInstanceRow(row *sql.Row) (*ShiftInstance, error) {
|
||||
var inst ShiftInstance
|
||||
var templateID sql.NullInt64
|
||||
var createdAt, updatedAt string
|
||||
if err := row.Scan(&inst.ID, &templateID, &inst.Name, &inst.Date, &inst.StartTime, &inst.EndTime,
|
||||
&inst.MinCapacity, &inst.MaxCapacity, &inst.Status, &inst.Year, &inst.Month,
|
||||
&createdAt, &updatedAt); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if templateID.Valid {
|
||||
inst.TemplateID = &templateID.Int64
|
||||
}
|
||||
inst.CreatedAt, _ = time.Parse("2006-01-02 15:04:05", createdAt)
|
||||
inst.UpdatedAt, _ = time.Parse("2006-01-02 15:04:05", updatedAt)
|
||||
if inst.Volunteers == nil {
|
||||
inst.Volunteers = []InstanceVolunteer{}
|
||||
}
|
||||
return &inst, nil
|
||||
}
|
||||
|
||||
func daysIn(year, month int) int {
|
||||
return time.Date(year, time.Month(month+1), 0, 0, 0, 0, 0, time.UTC).Day()
|
||||
}
|
||||
|
||||
@@ -12,6 +12,7 @@ import (
|
||||
"git.unsupervised.ca/walkies/internal/notification"
|
||||
"git.unsupervised.ca/walkies/internal/schedule"
|
||||
"git.unsupervised.ca/walkies/internal/server/middleware"
|
||||
"git.unsupervised.ca/walkies/internal/setup"
|
||||
"git.unsupervised.ca/walkies/internal/timeoff"
|
||||
"git.unsupervised.ca/walkies/internal/volunteer"
|
||||
)
|
||||
@@ -22,17 +23,21 @@ func New(db *sql.DB, jwtSecret string, staticDir string) http.Handler {
|
||||
volunteerStore := volunteer.NewStore(db)
|
||||
volunteerHandler := volunteer.NewHandler(volunteerStore, authSvc)
|
||||
|
||||
scheduleStore := schedule.NewStore(db)
|
||||
scheduleHandler := schedule.NewHandler(scheduleStore)
|
||||
notificationStore := notification.NewStore(db)
|
||||
notificationHandler := notification.NewHandler(notificationStore)
|
||||
|
||||
timeoffStore := timeoff.NewStore(db)
|
||||
timeoffHandler := timeoff.NewHandler(timeoffStore)
|
||||
|
||||
scheduleStore := schedule.NewStore(db)
|
||||
scheduleHandler := schedule.NewHandler(scheduleStore, notificationStore, timeoffStore)
|
||||
|
||||
timeoffHandler := timeoff.NewHandler(timeoffStore, notificationStore, volunteerStore)
|
||||
|
||||
checkinStore := checkin.NewStore(db)
|
||||
checkinHandler := checkin.NewHandler(checkinStore)
|
||||
|
||||
notificationStore := notification.NewStore(db)
|
||||
notificationHandler := notification.NewHandler(notificationStore)
|
||||
setupStore := setup.NewStore(db)
|
||||
setupHandler := setup.NewHandler(setupStore, authSvc)
|
||||
|
||||
r := chi.NewRouter()
|
||||
r.Use(chimiddleware.Logger)
|
||||
@@ -42,28 +47,45 @@ func New(db *sql.DB, jwtSecret string, staticDir string) http.Handler {
|
||||
// API routes
|
||||
r.Route("/api/v1", func(r chi.Router) {
|
||||
// Public auth endpoints
|
||||
r.Post("/auth/register", volunteerHandler.Register)
|
||||
r.Post("/auth/login", volunteerHandler.Login)
|
||||
r.Post("/auth/activate", volunteerHandler.Activate)
|
||||
|
||||
// Public setup endpoints (self-disabling once first user exists)
|
||||
r.Get("/setup/status", setupHandler.Status)
|
||||
r.Post("/setup/admin", setupHandler.CreateAdmin)
|
||||
|
||||
// Protected routes
|
||||
r.Group(func(r chi.Router) {
|
||||
r.Use(middleware.Authenticate(authSvc))
|
||||
|
||||
// Volunteers
|
||||
r.With(middleware.RequireAdmin).Post("/volunteers", volunteerHandler.Create)
|
||||
r.Get("/volunteers", volunteerHandler.List)
|
||||
r.Get("/volunteers/{id}", volunteerHandler.Get)
|
||||
r.With(middleware.RequireAdmin).Put("/volunteers/{id}", volunteerHandler.Update)
|
||||
r.Put("/volunteers/{id}", volunteerHandler.Update)
|
||||
r.With(middleware.RequireAdmin).Post("/volunteers/{id}/invite", volunteerHandler.ResendInvite)
|
||||
|
||||
// Schedules
|
||||
r.Get("/schedules", scheduleHandler.List)
|
||||
r.Post("/schedules", scheduleHandler.Create)
|
||||
r.With(middleware.RequireAdmin).Put("/schedules/{id}", scheduleHandler.Update)
|
||||
r.With(middleware.RequireAdmin).Delete("/schedules/{id}", scheduleHandler.Delete)
|
||||
// Shift templates (admin only)
|
||||
r.Get("/shift-templates", scheduleHandler.ListTemplates)
|
||||
r.With(middleware.RequireAdmin).Post("/shift-templates", scheduleHandler.CreateTemplate)
|
||||
r.With(middleware.RequireAdmin).Put("/shift-templates/{id}", scheduleHandler.UpdateTemplate)
|
||||
r.With(middleware.RequireAdmin).Delete("/shift-templates/{id}", scheduleHandler.DeleteTemplate)
|
||||
|
||||
// Shift instances
|
||||
r.Get("/shifts", scheduleHandler.ListInstances)
|
||||
r.With(middleware.RequireAdmin).Post("/shifts/generate", scheduleHandler.GenerateInstances)
|
||||
r.With(middleware.RequireAdmin).Post("/shifts/publish", scheduleHandler.PublishMonth)
|
||||
r.With(middleware.RequireAdmin).Post("/shifts/unpublish", scheduleHandler.UnpublishMonth)
|
||||
r.With(middleware.RequireAdmin).Put("/shifts/{id}", scheduleHandler.UpdateInstance)
|
||||
r.Post("/shifts/{id}/confirm", scheduleHandler.ConfirmShift)
|
||||
|
||||
// Time off
|
||||
r.Get("/timeoff", timeoffHandler.List)
|
||||
r.Post("/timeoff", timeoffHandler.Create)
|
||||
r.Put("/timeoff/{id}", timeoffHandler.Update)
|
||||
r.Delete("/timeoff/{id}", timeoffHandler.Delete)
|
||||
r.With(middleware.RequireAdmin).Put("/timeoff/{id}/review", timeoffHandler.Review)
|
||||
r.With(middleware.RequireAdmin).Get("/timeoff/{id}/shifts", timeoffHandler.RemovedShifts)
|
||||
|
||||
// Check-in / check-out
|
||||
r.Post("/checkin", checkinHandler.CheckIn)
|
||||
@@ -76,8 +98,25 @@ func New(db *sql.DB, jwtSecret string, staticDir string) http.Handler {
|
||||
})
|
||||
})
|
||||
|
||||
// Serve static React app for all other routes
|
||||
r.Handle("/*", http.FileServer(http.Dir(staticDir)))
|
||||
// Serve static React app for all other routes, with SPA fallback
|
||||
r.Handle("/*", spaHandler(staticDir))
|
||||
|
||||
return r
|
||||
}
|
||||
|
||||
// spaHandler serves static files from dir, falling back to index.html for
|
||||
// paths that don't match a file on disk (so client-side routing works).
|
||||
func spaHandler(dir string) http.HandlerFunc {
|
||||
fs := http.Dir(dir)
|
||||
fileServer := http.FileServer(fs)
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
// Try to open the requested path as a static file.
|
||||
if f, err := fs.Open(r.URL.Path); err == nil {
|
||||
f.Close()
|
||||
fileServer.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
// Not a real file — serve index.html and let React Router handle it.
|
||||
http.ServeFile(w, r, dir+"/index.html")
|
||||
}
|
||||
}
|
||||
|
||||
84
internal/setup/handler.go
Normal file
84
internal/setup/handler.go
Normal file
@@ -0,0 +1,84 @@
|
||||
package setup
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"git.unsupervised.ca/walkies/internal/auth"
|
||||
"git.unsupervised.ca/walkies/internal/respond"
|
||||
)
|
||||
|
||||
// TokenIssuer is the subset of auth.Service the setup handler needs.
|
||||
type TokenIssuer interface {
|
||||
IssueToken(volunteerID int64, role string) (string, error)
|
||||
}
|
||||
|
||||
type Handler struct {
|
||||
store Storer
|
||||
authSvc TokenIssuer
|
||||
}
|
||||
|
||||
func NewHandler(store *Store, authSvc *auth.Service) *Handler {
|
||||
return &Handler{store: store, authSvc: authSvc}
|
||||
}
|
||||
|
||||
// NewHandlerFromInterfaces constructs a Handler from interface values, intended for testing.
|
||||
func NewHandlerFromInterfaces(store Storer, authSvc TokenIssuer) *Handler {
|
||||
return &Handler{store: store, authSvc: authSvc}
|
||||
}
|
||||
|
||||
// Status handles GET /api/v1/setup/status.
|
||||
func (h *Handler) Status(w http.ResponseWriter, r *http.Request) {
|
||||
needs, err := h.store.NeedsSetup(r.Context())
|
||||
if err != nil {
|
||||
respond.Error(w, http.StatusInternalServerError, "could not check setup status")
|
||||
return
|
||||
}
|
||||
respond.JSON(w, http.StatusOK, map[string]bool{"needs_setup": needs})
|
||||
}
|
||||
|
||||
// CreateAdmin handles POST /api/v1/setup/admin.
|
||||
func (h *Handler) CreateAdmin(w http.ResponseWriter, r *http.Request) {
|
||||
var body struct {
|
||||
Name string `json:"name"`
|
||||
Email string `json:"email"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
||||
respond.Error(w, http.StatusBadRequest, "invalid request body")
|
||||
return
|
||||
}
|
||||
if body.Name == "" || body.Email == "" || body.Password == "" {
|
||||
respond.Error(w, http.StatusBadRequest, "name, email, and password are required")
|
||||
return
|
||||
}
|
||||
if len(body.Password) < 8 {
|
||||
respond.Error(w, http.StatusBadRequest, "password must be at least 8 characters")
|
||||
return
|
||||
}
|
||||
|
||||
hashed, err := auth.HashPassword(body.Password)
|
||||
if err != nil {
|
||||
respond.Error(w, http.StatusInternalServerError, "could not hash password")
|
||||
return
|
||||
}
|
||||
|
||||
id, err := h.store.CreateAdmin(r.Context(), body.Name, body.Email, hashed)
|
||||
if errors.Is(err, ErrSetupAlreadyDone) {
|
||||
respond.Error(w, http.StatusForbidden, "setup already completed")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
respond.Error(w, http.StatusInternalServerError, "could not create admin account")
|
||||
return
|
||||
}
|
||||
|
||||
token, err := h.authSvc.IssueToken(id, "admin")
|
||||
if err != nil {
|
||||
respond.Error(w, http.StatusInternalServerError, "could not issue token")
|
||||
return
|
||||
}
|
||||
|
||||
respond.JSON(w, http.StatusCreated, map[string]string{"token": token})
|
||||
}
|
||||
168
internal/setup/handler_test.go
Normal file
168
internal/setup/handler_test.go
Normal file
@@ -0,0 +1,168 @@
|
||||
package setup_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"git.unsupervised.ca/walkies/internal/setup"
|
||||
)
|
||||
|
||||
// ---- fakes ---------------------------------------------------------------
|
||||
|
||||
type fakeStore struct {
|
||||
needsSetup bool
|
||||
needsSetupErr error
|
||||
createAdminID int64
|
||||
createAdminErr error
|
||||
}
|
||||
|
||||
func (f *fakeStore) NeedsSetup(_ context.Context) (bool, error) {
|
||||
return f.needsSetup, f.needsSetupErr
|
||||
}
|
||||
|
||||
func (f *fakeStore) CreateAdmin(_ context.Context, _, _, _ string) (int64, error) {
|
||||
return f.createAdminID, f.createAdminErr
|
||||
}
|
||||
|
||||
type fakeTokenIssuer struct {
|
||||
token string
|
||||
err error
|
||||
}
|
||||
|
||||
func (f *fakeTokenIssuer) IssueToken(_ int64, _ string) (string, error) {
|
||||
return f.token, f.err
|
||||
}
|
||||
|
||||
// Compile-time interface checks.
|
||||
var _ setup.Storer = (*fakeStore)(nil)
|
||||
var _ setup.TokenIssuer = (*fakeTokenIssuer)(nil)
|
||||
|
||||
// ---- helpers -------------------------------------------------------------
|
||||
|
||||
func do(t *testing.T, handler http.HandlerFunc, method, path, body string) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
var b *bytes.Reader
|
||||
if body != "" {
|
||||
b = bytes.NewReader([]byte(body))
|
||||
} else {
|
||||
b = bytes.NewReader(nil)
|
||||
}
|
||||
req := httptest.NewRequest(method, path, b)
|
||||
if body != "" {
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
}
|
||||
w := httptest.NewRecorder()
|
||||
handler.ServeHTTP(w, req)
|
||||
return w
|
||||
}
|
||||
|
||||
// ---- Status tests --------------------------------------------------------
|
||||
|
||||
func TestStatus_NeedsSetup(t *testing.T) {
|
||||
h := setup.NewHandlerFromInterfaces(
|
||||
&fakeStore{needsSetup: true},
|
||||
&fakeTokenIssuer{},
|
||||
)
|
||||
w := do(t, h.Status, "GET", "/api/v1/setup/status", "")
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("expected 200, got %d: %s", w.Code, w.Body)
|
||||
}
|
||||
var resp map[string]bool
|
||||
json.NewDecoder(w.Body).Decode(&resp)
|
||||
if !resp["needs_setup"] {
|
||||
t.Error("expected needs_setup=true")
|
||||
}
|
||||
}
|
||||
|
||||
func TestStatus_SetupDone(t *testing.T) {
|
||||
h := setup.NewHandlerFromInterfaces(
|
||||
&fakeStore{needsSetup: false},
|
||||
&fakeTokenIssuer{},
|
||||
)
|
||||
w := do(t, h.Status, "GET", "/api/v1/setup/status", "")
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("expected 200, got %d: %s", w.Code, w.Body)
|
||||
}
|
||||
var resp map[string]bool
|
||||
json.NewDecoder(w.Body).Decode(&resp)
|
||||
if resp["needs_setup"] {
|
||||
t.Error("expected needs_setup=false")
|
||||
}
|
||||
}
|
||||
|
||||
// ---- CreateAdmin tests ---------------------------------------------------
|
||||
|
||||
func TestCreateAdmin_Success(t *testing.T) {
|
||||
h := setup.NewHandlerFromInterfaces(
|
||||
&fakeStore{createAdminID: 1},
|
||||
&fakeTokenIssuer{token: "jwt-token"},
|
||||
)
|
||||
w := do(t, h.CreateAdmin, "POST", "/api/v1/setup/admin",
|
||||
`{"name":"Admin","email":"admin@example.com","password":"supersecret"}`)
|
||||
|
||||
if w.Code != http.StatusCreated {
|
||||
t.Fatalf("expected 201, got %d: %s", w.Code, w.Body)
|
||||
}
|
||||
var resp map[string]string
|
||||
json.NewDecoder(w.Body).Decode(&resp)
|
||||
if resp["token"] != "jwt-token" {
|
||||
t.Errorf("expected token jwt-token, got %q", resp["token"])
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateAdmin_AlreadyDone(t *testing.T) {
|
||||
h := setup.NewHandlerFromInterfaces(
|
||||
&fakeStore{createAdminErr: setup.ErrSetupAlreadyDone},
|
||||
&fakeTokenIssuer{},
|
||||
)
|
||||
w := do(t, h.CreateAdmin, "POST", "/api/v1/setup/admin",
|
||||
`{"name":"Admin","email":"admin@example.com","password":"supersecret"}`)
|
||||
|
||||
if w.Code != http.StatusForbidden {
|
||||
t.Fatalf("expected 403, got %d: %s", w.Code, w.Body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateAdmin_MissingFields(t *testing.T) {
|
||||
h := setup.NewHandlerFromInterfaces(
|
||||
&fakeStore{},
|
||||
&fakeTokenIssuer{},
|
||||
)
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
body string
|
||||
}{
|
||||
{"missing name", `{"email":"a@b.com","password":"supersecret"}`},
|
||||
{"missing email", `{"name":"Admin","password":"supersecret"}`},
|
||||
{"missing password", `{"name":"Admin","email":"a@b.com"}`},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
w := do(t, h.CreateAdmin, "POST", "/api/v1/setup/admin", tc.body)
|
||||
if w.Code != http.StatusBadRequest {
|
||||
t.Fatalf("expected 400, got %d: %s", w.Code, w.Body)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateAdmin_PasswordTooShort(t *testing.T) {
|
||||
h := setup.NewHandlerFromInterfaces(
|
||||
&fakeStore{},
|
||||
&fakeTokenIssuer{},
|
||||
)
|
||||
w := do(t, h.CreateAdmin, "POST", "/api/v1/setup/admin",
|
||||
`{"name":"Admin","email":"admin@example.com","password":"short"}`)
|
||||
|
||||
if w.Code != http.StatusBadRequest {
|
||||
t.Fatalf("expected 400, got %d: %s", w.Code, w.Body)
|
||||
}
|
||||
}
|
||||
68
internal/setup/setup.go
Normal file
68
internal/setup/setup.go
Normal file
@@ -0,0 +1,68 @@
|
||||
package setup
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
)
|
||||
|
||||
var ErrSetupAlreadyDone = errors.New("setup already completed")
|
||||
|
||||
// Storer is the interface for setup-related DB operations.
|
||||
type Storer interface {
|
||||
NeedsSetup(ctx context.Context) (bool, error)
|
||||
CreateAdmin(ctx context.Context, name, email, hashedPassword string) (int64, error)
|
||||
}
|
||||
|
||||
type Store struct {
|
||||
db *sql.DB
|
||||
}
|
||||
|
||||
func NewStore(db *sql.DB) *Store {
|
||||
return &Store{db: db}
|
||||
}
|
||||
|
||||
// NeedsSetup returns true when the volunteers table has zero rows.
|
||||
func (s *Store) NeedsSetup(ctx context.Context) (bool, error) {
|
||||
var count int
|
||||
err := s.db.QueryRowContext(ctx, `SELECT COUNT(*) FROM volunteers`).Scan(&count)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
return count == 0, nil
|
||||
}
|
||||
|
||||
// CreateAdmin atomically checks that no users exist and inserts the first admin.
|
||||
func (s *Store) CreateAdmin(ctx context.Context, name, email, hashedPassword string) (int64, error) {
|
||||
tx, err := s.db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
|
||||
var count int
|
||||
if err := tx.QueryRowContext(ctx, `SELECT COUNT(*) FROM volunteers`).Scan(&count); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if count > 0 {
|
||||
return 0, ErrSetupAlreadyDone
|
||||
}
|
||||
|
||||
res, err := tx.ExecContext(ctx,
|
||||
`INSERT INTO volunteers (name, email, password, role, active, operational_roles) VALUES (?, ?, ?, 'admin', 1, '')`,
|
||||
name, email, hashedPassword,
|
||||
)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
id, err := res.LastInsertId()
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
if err := tx.Commit(); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return id, nil
|
||||
}
|
||||
@@ -1,22 +1,56 @@
|
||||
package timeoff
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"git.unsupervised.ca/walkies/internal/respond"
|
||||
"git.unsupervised.ca/walkies/internal/server/middleware"
|
||||
"github.com/go-chi/chi/v5"
|
||||
)
|
||||
|
||||
type Handler struct {
|
||||
store *Store
|
||||
// Notifier is the subset of notification.Store the handler needs.
|
||||
type Notifier interface {
|
||||
CreateNotification(ctx context.Context, volunteerID int64, message string) error
|
||||
}
|
||||
|
||||
func NewHandler(store *Store) *Handler {
|
||||
return &Handler{store: store}
|
||||
// AdminLister returns admin volunteer IDs so the handler can notify them.
|
||||
type AdminLister interface {
|
||||
ListAdminIDs(ctx context.Context) ([]int64, error)
|
||||
}
|
||||
|
||||
// Storer is the interface the Handler depends on.
|
||||
type Storer interface {
|
||||
Create(ctx context.Context, volunteerID int64, in CreateInput) (*Request, error)
|
||||
GetByID(ctx context.Context, id int64) (*Request, error)
|
||||
List(ctx context.Context, volunteerID int64) ([]Request, error)
|
||||
Review(ctx context.Context, id, reviewerID int64, status string) (*Request, error)
|
||||
Update(ctx context.Context, id int64, in UpdateInput) (*Request, error)
|
||||
Delete(ctx context.Context, id int64) error
|
||||
ConflictingShifts(ctx context.Context, volunteerID int64, startsAt, endsAt string) ([]ConflictingShift, error)
|
||||
RemoveFromConflictingShifts(ctx context.Context, timeOffID, volunteerID int64, startsAt, endsAt string) ([]ConflictingShift, error)
|
||||
RemovedShiftsForTimeOff(ctx context.Context, timeOffID int64) ([]ConflictingShift, error)
|
||||
RestoreRemovedShifts(ctx context.Context, timeOffID int64) ([]ConflictingShift, error)
|
||||
}
|
||||
|
||||
type Handler struct {
|
||||
store Storer
|
||||
notifier Notifier
|
||||
adminLister AdminLister
|
||||
}
|
||||
|
||||
func NewHandler(store *Store, notifier Notifier, adminLister AdminLister) *Handler {
|
||||
return &Handler{store: store, notifier: notifier, adminLister: adminLister}
|
||||
}
|
||||
|
||||
// NewHandlerFromInterfaces constructs a Handler from interface values, intended for testing.
|
||||
func NewHandlerFromInterfaces(store Storer, notifier Notifier, adminLister AdminLister) *Handler {
|
||||
return &Handler{store: store, notifier: notifier, adminLister: adminLister}
|
||||
}
|
||||
|
||||
// GET /api/v1/timeoff
|
||||
@@ -38,6 +72,9 @@ func (h *Handler) List(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
|
||||
// POST /api/v1/timeoff
|
||||
// Creates time off with status "approved". If confirm_conflicts is true and the
|
||||
// volunteer is assigned to shifts in the date range, they are auto-removed and
|
||||
// admins are notified (FR-T03).
|
||||
func (h *Handler) Create(w http.ResponseWriter, r *http.Request) {
|
||||
claims := middleware.ClaimsFromContext(r.Context())
|
||||
var in CreateInput
|
||||
@@ -49,14 +86,181 @@ func (h *Handler) Create(w http.ResponseWriter, r *http.Request) {
|
||||
respond.Error(w, http.StatusBadRequest, "starts_at and ends_at are required")
|
||||
return
|
||||
}
|
||||
req, err := h.store.Create(r.Context(), claims.VolunteerID, in)
|
||||
|
||||
// Determine target volunteer (admin can create for others, FR-T05)
|
||||
targetVolunteerID := claims.VolunteerID
|
||||
if in.VolunteerID > 0 && claims.Role == "admin" {
|
||||
targetVolunteerID = in.VolunteerID
|
||||
}
|
||||
|
||||
// Check for conflicting shifts
|
||||
conflicts, err := h.store.ConflictingShifts(r.Context(), targetVolunteerID, in.StartsAt, in.EndsAt)
|
||||
if err != nil {
|
||||
respond.Error(w, http.StatusInternalServerError, "could not check conflicts")
|
||||
return
|
||||
}
|
||||
|
||||
// If there are conflicts and the user hasn't confirmed, return them
|
||||
if len(conflicts) > 0 && !in.ConfirmConflicts {
|
||||
respond.JSON(w, http.StatusConflict, map[string]any{
|
||||
"message": "Time off conflicts with assigned shifts. Confirm to proceed.",
|
||||
"conflicts": conflicts,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// Create with auto-approved status
|
||||
req, err := h.store.Create(r.Context(), targetVolunteerID, in)
|
||||
if err != nil {
|
||||
respond.Error(w, http.StatusInternalServerError, "could not create time off request")
|
||||
return
|
||||
}
|
||||
|
||||
// Auto-approve
|
||||
req, err = h.store.Review(r.Context(), req.ID, claims.VolunteerID, "approved")
|
||||
if err != nil {
|
||||
respond.Error(w, http.StatusInternalServerError, "could not approve time off request")
|
||||
return
|
||||
}
|
||||
|
||||
// Remove from conflicting shifts (FR-T03)
|
||||
if len(conflicts) > 0 {
|
||||
removed, err := h.store.RemoveFromConflictingShifts(r.Context(), req.ID, targetVolunteerID, in.StartsAt, in.EndsAt)
|
||||
if err != nil {
|
||||
respond.Error(w, http.StatusInternalServerError, "could not remove from conflicting shifts")
|
||||
return
|
||||
}
|
||||
// Notify admins
|
||||
h.notifyAdmins(r.Context(), targetVolunteerID, removed)
|
||||
}
|
||||
|
||||
respond.JSON(w, http.StatusCreated, req)
|
||||
}
|
||||
|
||||
// PUT /api/v1/timeoff/{id}
|
||||
// Volunteers can edit their own future time off (FR-T02). Admins can edit any (FR-T05).
|
||||
func (h *Handler) Update(w http.ResponseWriter, r *http.Request) {
|
||||
claims := middleware.ClaimsFromContext(r.Context())
|
||||
id, err := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64)
|
||||
if err != nil {
|
||||
respond.Error(w, http.StatusBadRequest, "invalid id")
|
||||
return
|
||||
}
|
||||
|
||||
existing, err := h.store.GetByID(r.Context(), id)
|
||||
if errors.Is(err, ErrNotFound) {
|
||||
respond.Error(w, http.StatusNotFound, "time off request not found")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
respond.Error(w, http.StatusInternalServerError, "could not get time off request")
|
||||
return
|
||||
}
|
||||
|
||||
// Permission: volunteers can only edit their own future time off
|
||||
if claims.Role != "admin" {
|
||||
if existing.VolunteerID != claims.VolunteerID {
|
||||
respond.Error(w, http.StatusForbidden, "cannot edit another volunteer's time off")
|
||||
return
|
||||
}
|
||||
if !existing.StartsAt.After(time.Now()) {
|
||||
respond.Error(w, http.StatusForbidden, "cannot edit past time off")
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
var in UpdateInput
|
||||
if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
|
||||
respond.Error(w, http.StatusBadRequest, "invalid request body")
|
||||
return
|
||||
}
|
||||
if in.StartsAt == "" || in.EndsAt == "" {
|
||||
respond.Error(w, http.StatusBadRequest, "starts_at and ends_at are required")
|
||||
return
|
||||
}
|
||||
|
||||
req, err := h.store.Update(r.Context(), id, in)
|
||||
if err != nil {
|
||||
respond.Error(w, http.StatusInternalServerError, "could not update time off request")
|
||||
return
|
||||
}
|
||||
respond.JSON(w, http.StatusOK, req)
|
||||
}
|
||||
|
||||
// DELETE /api/v1/timeoff/{id}
|
||||
// Volunteers can delete their own future time off (FR-T02).
|
||||
// Admin delete restores the volunteer to previously removed shifts (FR-T04).
|
||||
func (h *Handler) Delete(w http.ResponseWriter, r *http.Request) {
|
||||
claims := middleware.ClaimsFromContext(r.Context())
|
||||
id, err := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64)
|
||||
if err != nil {
|
||||
respond.Error(w, http.StatusBadRequest, "invalid id")
|
||||
return
|
||||
}
|
||||
|
||||
existing, err := h.store.GetByID(r.Context(), id)
|
||||
if errors.Is(err, ErrNotFound) {
|
||||
respond.Error(w, http.StatusNotFound, "time off request not found")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
respond.Error(w, http.StatusInternalServerError, "could not get time off request")
|
||||
return
|
||||
}
|
||||
|
||||
// Permission: volunteers can only delete their own future time off
|
||||
if claims.Role != "admin" {
|
||||
if existing.VolunteerID != claims.VolunteerID {
|
||||
respond.Error(w, http.StatusForbidden, "cannot delete another volunteer's time off")
|
||||
return
|
||||
}
|
||||
if !existing.StartsAt.After(time.Now()) {
|
||||
respond.Error(w, http.StatusForbidden, "cannot delete past time off")
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// If admin is deleting, restore volunteer to removed shifts (FR-T04)
|
||||
var restored []ConflictingShift
|
||||
if claims.Role == "admin" {
|
||||
restored, err = h.store.RestoreRemovedShifts(r.Context(), id)
|
||||
if err != nil {
|
||||
respond.Error(w, http.StatusInternalServerError, "could not restore shifts")
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
if err := h.store.Delete(r.Context(), id); err != nil {
|
||||
respond.Error(w, http.StatusInternalServerError, "could not delete time off request")
|
||||
return
|
||||
}
|
||||
|
||||
respond.JSON(w, http.StatusOK, map[string]any{
|
||||
"deleted": true,
|
||||
"restored_shifts": restored,
|
||||
})
|
||||
}
|
||||
|
||||
// GET /api/v1/timeoff/{id}/shifts
|
||||
// Returns shifts that were removed due to this time-off request (preview for FR-T04).
|
||||
func (h *Handler) RemovedShifts(w http.ResponseWriter, r *http.Request) {
|
||||
id, err := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64)
|
||||
if err != nil {
|
||||
respond.Error(w, http.StatusBadRequest, "invalid id")
|
||||
return
|
||||
}
|
||||
|
||||
shifts, err := h.store.RemovedShiftsForTimeOff(r.Context(), id)
|
||||
if err != nil {
|
||||
respond.Error(w, http.StatusInternalServerError, "could not get removed shifts")
|
||||
return
|
||||
}
|
||||
if shifts == nil {
|
||||
shifts = []ConflictingShift{}
|
||||
}
|
||||
respond.JSON(w, http.StatusOK, shifts)
|
||||
}
|
||||
|
||||
// PUT /api/v1/timeoff/{id}/review
|
||||
func (h *Handler) Review(w http.ResponseWriter, r *http.Request) {
|
||||
claims := middleware.ClaimsFromContext(r.Context())
|
||||
@@ -85,3 +289,19 @@ func (h *Handler) Review(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
respond.JSON(w, http.StatusOK, req)
|
||||
}
|
||||
|
||||
// notifyAdmins sends a notification to all admin users about a volunteer's
|
||||
// shift removals due to time off (FR-T03).
|
||||
func (h *Handler) notifyAdmins(ctx context.Context, volunteerID int64, removed []ConflictingShift) {
|
||||
if len(removed) == 0 {
|
||||
return
|
||||
}
|
||||
adminIDs, err := h.adminLister.ListAdminIDs(ctx)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
msg := fmt.Sprintf("Volunteer %d has been removed from %d shift(s) due to time off.", volunteerID, len(removed))
|
||||
for _, aid := range adminIDs {
|
||||
h.notifier.CreateNotification(ctx, aid, msg) //nolint:errcheck
|
||||
}
|
||||
}
|
||||
|
||||
521
internal/timeoff/handler_test.go
Normal file
521
internal/timeoff/handler_test.go
Normal file
@@ -0,0 +1,521 @@
|
||||
package timeoff_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.unsupervised.ca/walkies/internal/auth"
|
||||
"git.unsupervised.ca/walkies/internal/server/middleware"
|
||||
"git.unsupervised.ca/walkies/internal/timeoff"
|
||||
"github.com/go-chi/chi/v5"
|
||||
)
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Fakes
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
type fakeStore struct {
|
||||
requests []timeoff.Request
|
||||
createResult *timeoff.Request
|
||||
createErr error
|
||||
getResult *timeoff.Request
|
||||
getErr error
|
||||
updateResult *timeoff.Request
|
||||
updateErr error
|
||||
deleteErr error
|
||||
reviewResult *timeoff.Request
|
||||
reviewErr error
|
||||
conflicts []timeoff.ConflictingShift
|
||||
conflictsErr error
|
||||
removedShifts []timeoff.ConflictingShift
|
||||
removeErr error
|
||||
removedForTimeOff []timeoff.ConflictingShift
|
||||
removedForErr error
|
||||
restoredShifts []timeoff.ConflictingShift
|
||||
restoreErr error
|
||||
|
||||
removeCalled bool
|
||||
restoreCalled bool
|
||||
}
|
||||
|
||||
func (f *fakeStore) Create(_ context.Context, volunteerID int64, in timeoff.CreateInput) (*timeoff.Request, error) {
|
||||
if f.createErr != nil {
|
||||
return nil, f.createErr
|
||||
}
|
||||
if f.createResult != nil {
|
||||
return f.createResult, nil
|
||||
}
|
||||
return &timeoff.Request{
|
||||
ID: 1, VolunteerID: volunteerID,
|
||||
StartsAt: time.Date(2026, 5, 1, 0, 0, 0, 0, time.UTC),
|
||||
EndsAt: time.Date(2026, 5, 3, 0, 0, 0, 0, time.UTC),
|
||||
Status: "pending",
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (f *fakeStore) GetByID(_ context.Context, id int64) (*timeoff.Request, error) {
|
||||
if f.getErr != nil {
|
||||
return nil, f.getErr
|
||||
}
|
||||
if f.getResult != nil {
|
||||
return f.getResult, nil
|
||||
}
|
||||
return nil, timeoff.ErrNotFound
|
||||
}
|
||||
|
||||
func (f *fakeStore) List(_ context.Context, volunteerID int64) ([]timeoff.Request, error) {
|
||||
if volunteerID > 0 {
|
||||
var filtered []timeoff.Request
|
||||
for _, r := range f.requests {
|
||||
if r.VolunteerID == volunteerID {
|
||||
filtered = append(filtered, r)
|
||||
}
|
||||
}
|
||||
return filtered, nil
|
||||
}
|
||||
return f.requests, nil
|
||||
}
|
||||
|
||||
func (f *fakeStore) Review(_ context.Context, id, reviewerID int64, status string) (*timeoff.Request, error) {
|
||||
if f.reviewErr != nil {
|
||||
return nil, f.reviewErr
|
||||
}
|
||||
if f.reviewResult != nil {
|
||||
return f.reviewResult, nil
|
||||
}
|
||||
return &timeoff.Request{ID: id, Status: status}, nil
|
||||
}
|
||||
|
||||
func (f *fakeStore) Update(_ context.Context, id int64, in timeoff.UpdateInput) (*timeoff.Request, error) {
|
||||
if f.updateErr != nil {
|
||||
return nil, f.updateErr
|
||||
}
|
||||
if f.updateResult != nil {
|
||||
return f.updateResult, nil
|
||||
}
|
||||
return &timeoff.Request{ID: id, Status: "approved"}, nil
|
||||
}
|
||||
|
||||
func (f *fakeStore) Delete(_ context.Context, id int64) error {
|
||||
return f.deleteErr
|
||||
}
|
||||
|
||||
func (f *fakeStore) ConflictingShifts(_ context.Context, _ int64, _, _ string) ([]timeoff.ConflictingShift, error) {
|
||||
if f.conflictsErr != nil {
|
||||
return nil, f.conflictsErr
|
||||
}
|
||||
return f.conflicts, nil
|
||||
}
|
||||
|
||||
func (f *fakeStore) RemoveFromConflictingShifts(_ context.Context, _, _ int64, _, _ string) ([]timeoff.ConflictingShift, error) {
|
||||
f.removeCalled = true
|
||||
if f.removeErr != nil {
|
||||
return nil, f.removeErr
|
||||
}
|
||||
return f.removedShifts, nil
|
||||
}
|
||||
|
||||
func (f *fakeStore) RemovedShiftsForTimeOff(_ context.Context, _ int64) ([]timeoff.ConflictingShift, error) {
|
||||
if f.removedForErr != nil {
|
||||
return nil, f.removedForErr
|
||||
}
|
||||
return f.removedForTimeOff, nil
|
||||
}
|
||||
|
||||
func (f *fakeStore) RestoreRemovedShifts(_ context.Context, _ int64) ([]timeoff.ConflictingShift, error) {
|
||||
f.restoreCalled = true
|
||||
if f.restoreErr != nil {
|
||||
return nil, f.restoreErr
|
||||
}
|
||||
return f.restoredShifts, nil
|
||||
}
|
||||
|
||||
type fakeNotifier struct {
|
||||
notifications []struct {
|
||||
VolunteerID int64
|
||||
Message string
|
||||
}
|
||||
}
|
||||
|
||||
func (f *fakeNotifier) CreateNotification(_ context.Context, volunteerID int64, message string) error {
|
||||
f.notifications = append(f.notifications, struct {
|
||||
VolunteerID int64
|
||||
Message string
|
||||
}{volunteerID, message})
|
||||
return nil
|
||||
}
|
||||
|
||||
type fakeAdminLister struct {
|
||||
adminIDs []int64
|
||||
}
|
||||
|
||||
func (f *fakeAdminLister) ListAdminIDs(_ context.Context) ([]int64, error) {
|
||||
return f.adminIDs, nil
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
func jwtForRole(t *testing.T, id int64, role string) string {
|
||||
t.Helper()
|
||||
svc := auth.NewService(nil, "test-secret")
|
||||
token, err := svc.IssueToken(id, role)
|
||||
if err != nil {
|
||||
t.Fatalf("issue token: %v", err)
|
||||
}
|
||||
return token
|
||||
}
|
||||
|
||||
func newRouter(h *timeoff.Handler) http.Handler {
|
||||
realAuthSvc := auth.NewService(nil, "test-secret")
|
||||
r := chi.NewRouter()
|
||||
r.Group(func(r chi.Router) {
|
||||
r.Use(middleware.Authenticate(realAuthSvc))
|
||||
r.Get("/api/v1/timeoff", h.List)
|
||||
r.Post("/api/v1/timeoff", h.Create)
|
||||
r.Put("/api/v1/timeoff/{id}", h.Update)
|
||||
r.Delete("/api/v1/timeoff/{id}", h.Delete)
|
||||
r.Put("/api/v1/timeoff/{id}/review",
|
||||
middleware.RequireAdmin(http.HandlerFunc(h.Review)).ServeHTTP)
|
||||
r.Get("/api/v1/timeoff/{id}/shifts",
|
||||
middleware.RequireAdmin(http.HandlerFunc(h.RemovedShifts)).ServeHTTP)
|
||||
})
|
||||
return r
|
||||
}
|
||||
|
||||
func do(t *testing.T, router http.Handler, method, path, body, token string) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
var b *bytes.Reader
|
||||
if body != "" {
|
||||
b = bytes.NewReader([]byte(body))
|
||||
} else {
|
||||
b = bytes.NewReader(nil)
|
||||
}
|
||||
req := httptest.NewRequest(method, path, b)
|
||||
if body != "" {
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
}
|
||||
if token != "" {
|
||||
req.Header.Set("Authorization", "Bearer "+token)
|
||||
}
|
||||
w := httptest.NewRecorder()
|
||||
router.ServeHTTP(w, req)
|
||||
return w
|
||||
}
|
||||
|
||||
func setup(store *fakeStore) (*timeoff.Handler, http.Handler) {
|
||||
notifier := &fakeNotifier{}
|
||||
adminLister := &fakeAdminLister{adminIDs: []int64{1}}
|
||||
h := timeoff.NewHandlerFromInterfaces(store, notifier, adminLister)
|
||||
return h, newRouter(h)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Tests
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
func TestList_VolunteerSeesOwn(t *testing.T) {
|
||||
store := &fakeStore{
|
||||
requests: []timeoff.Request{
|
||||
{ID: 1, VolunteerID: 10, Status: "approved"},
|
||||
{ID: 2, VolunteerID: 20, Status: "pending"},
|
||||
},
|
||||
}
|
||||
_, router := setup(store)
|
||||
token := jwtForRole(t, 10, "volunteer")
|
||||
w := do(t, router, "GET", "/api/v1/timeoff", "", token)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("expected 200, got %d: %s", w.Code, w.Body)
|
||||
}
|
||||
var result []timeoff.Request
|
||||
json.NewDecoder(w.Body).Decode(&result)
|
||||
if len(result) != 1 {
|
||||
t.Fatalf("expected 1 request, got %d", len(result))
|
||||
}
|
||||
if result[0].VolunteerID != 10 {
|
||||
t.Errorf("expected volunteer_id=10, got %d", result[0].VolunteerID)
|
||||
}
|
||||
}
|
||||
|
||||
func TestList_AdminSeesAll(t *testing.T) {
|
||||
store := &fakeStore{
|
||||
requests: []timeoff.Request{
|
||||
{ID: 1, VolunteerID: 10, Status: "approved"},
|
||||
{ID: 2, VolunteerID: 20, Status: "pending"},
|
||||
},
|
||||
}
|
||||
_, router := setup(store)
|
||||
token := jwtForRole(t, 1, "admin")
|
||||
w := do(t, router, "GET", "/api/v1/timeoff", "", token)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("expected 200, got %d", w.Code)
|
||||
}
|
||||
var result []timeoff.Request
|
||||
json.NewDecoder(w.Body).Decode(&result)
|
||||
if len(result) != 2 {
|
||||
t.Errorf("expected 2 requests, got %d", len(result))
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreate_NoConflicts(t *testing.T) {
|
||||
store := &fakeStore{}
|
||||
_, router := setup(store)
|
||||
token := jwtForRole(t, 10, "volunteer")
|
||||
|
||||
body := `{"starts_at":"2026-05-01","ends_at":"2026-05-03","reason":"vacation"}`
|
||||
w := do(t, router, "POST", "/api/v1/timeoff", body, token)
|
||||
|
||||
if w.Code != http.StatusCreated {
|
||||
t.Fatalf("expected 201, got %d: %s", w.Code, w.Body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreate_ConflictReturns409(t *testing.T) {
|
||||
store := &fakeStore{
|
||||
conflicts: []timeoff.ConflictingShift{
|
||||
{InstanceID: 100, Name: "Morning Walk", Date: "2026-05-01", StartTime: "08:00:00", EndTime: "12:00:00"},
|
||||
},
|
||||
}
|
||||
_, router := setup(store)
|
||||
token := jwtForRole(t, 10, "volunteer")
|
||||
|
||||
body := `{"starts_at":"2026-05-01","ends_at":"2026-05-03"}`
|
||||
w := do(t, router, "POST", "/api/v1/timeoff", body, token)
|
||||
|
||||
if w.Code != http.StatusConflict {
|
||||
t.Fatalf("expected 409, got %d: %s", w.Code, w.Body)
|
||||
}
|
||||
var result map[string]any
|
||||
json.NewDecoder(w.Body).Decode(&result)
|
||||
conflicts := result["conflicts"].([]any)
|
||||
if len(conflicts) != 1 {
|
||||
t.Errorf("expected 1 conflict, got %d", len(conflicts))
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreate_ConfirmConflictsProceeds(t *testing.T) {
|
||||
store := &fakeStore{
|
||||
conflicts: []timeoff.ConflictingShift{
|
||||
{InstanceID: 100, Name: "Morning Walk", Date: "2026-05-01"},
|
||||
},
|
||||
removedShifts: []timeoff.ConflictingShift{
|
||||
{InstanceID: 100, Name: "Morning Walk", Date: "2026-05-01"},
|
||||
},
|
||||
}
|
||||
_, router := setup(store)
|
||||
token := jwtForRole(t, 10, "volunteer")
|
||||
|
||||
body := `{"starts_at":"2026-05-01","ends_at":"2026-05-03","confirm_conflicts":true}`
|
||||
w := do(t, router, "POST", "/api/v1/timeoff", body, token)
|
||||
|
||||
if w.Code != http.StatusCreated {
|
||||
t.Fatalf("expected 201, got %d: %s", w.Code, w.Body)
|
||||
}
|
||||
if !store.removeCalled {
|
||||
t.Error("expected RemoveFromConflictingShifts to be called")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreate_AdminForOtherVolunteer(t *testing.T) {
|
||||
store := &fakeStore{}
|
||||
_, router := setup(store)
|
||||
token := jwtForRole(t, 1, "admin")
|
||||
|
||||
body := `{"starts_at":"2026-05-01","ends_at":"2026-05-03","volunteer_id":20}`
|
||||
w := do(t, router, "POST", "/api/v1/timeoff", body, token)
|
||||
|
||||
if w.Code != http.StatusCreated {
|
||||
t.Fatalf("expected 201, got %d: %s", w.Code, w.Body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpdate_VolunteerOwnFuture(t *testing.T) {
|
||||
store := &fakeStore{
|
||||
getResult: &timeoff.Request{
|
||||
ID: 1, VolunteerID: 10, Status: "approved",
|
||||
StartsAt: time.Date(2026, 5, 1, 0, 0, 0, 0, time.UTC),
|
||||
EndsAt: time.Date(2026, 5, 3, 0, 0, 0, 0, time.UTC),
|
||||
},
|
||||
}
|
||||
_, router := setup(store)
|
||||
token := jwtForRole(t, 10, "volunteer")
|
||||
|
||||
body := `{"starts_at":"2026-05-02","ends_at":"2026-05-04","reason":"extended"}`
|
||||
w := do(t, router, "PUT", "/api/v1/timeoff/1", body, token)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("expected 200, got %d: %s", w.Code, w.Body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpdate_VolunteerCannotEditOthers(t *testing.T) {
|
||||
store := &fakeStore{
|
||||
getResult: &timeoff.Request{
|
||||
ID: 1, VolunteerID: 20, Status: "approved",
|
||||
StartsAt: time.Date(2026, 5, 1, 0, 0, 0, 0, time.UTC),
|
||||
},
|
||||
}
|
||||
_, router := setup(store)
|
||||
token := jwtForRole(t, 10, "volunteer")
|
||||
|
||||
body := `{"starts_at":"2026-05-02","ends_at":"2026-05-04"}`
|
||||
w := do(t, router, "PUT", "/api/v1/timeoff/1", body, token)
|
||||
|
||||
if w.Code != http.StatusForbidden {
|
||||
t.Fatalf("expected 403, got %d: %s", w.Code, w.Body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpdate_VolunteerCannotEditPast(t *testing.T) {
|
||||
store := &fakeStore{
|
||||
getResult: &timeoff.Request{
|
||||
ID: 1, VolunteerID: 10, Status: "approved",
|
||||
StartsAt: time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC),
|
||||
},
|
||||
}
|
||||
_, router := setup(store)
|
||||
token := jwtForRole(t, 10, "volunteer")
|
||||
|
||||
body := `{"starts_at":"2026-05-02","ends_at":"2026-05-04"}`
|
||||
w := do(t, router, "PUT", "/api/v1/timeoff/1", body, token)
|
||||
|
||||
if w.Code != http.StatusForbidden {
|
||||
t.Fatalf("expected 403, got %d: %s", w.Code, w.Body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDelete_VolunteerOwnFuture(t *testing.T) {
|
||||
store := &fakeStore{
|
||||
getResult: &timeoff.Request{
|
||||
ID: 1, VolunteerID: 10, Status: "approved",
|
||||
StartsAt: time.Date(2026, 5, 1, 0, 0, 0, 0, time.UTC),
|
||||
},
|
||||
}
|
||||
_, router := setup(store)
|
||||
token := jwtForRole(t, 10, "volunteer")
|
||||
|
||||
w := do(t, router, "DELETE", "/api/v1/timeoff/1", "", token)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("expected 200, got %d: %s", w.Code, w.Body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDelete_VolunteerCannotDeleteOthers(t *testing.T) {
|
||||
store := &fakeStore{
|
||||
getResult: &timeoff.Request{
|
||||
ID: 1, VolunteerID: 20, Status: "approved",
|
||||
StartsAt: time.Date(2026, 5, 1, 0, 0, 0, 0, time.UTC),
|
||||
},
|
||||
}
|
||||
_, router := setup(store)
|
||||
token := jwtForRole(t, 10, "volunteer")
|
||||
|
||||
w := do(t, router, "DELETE", "/api/v1/timeoff/1", "", token)
|
||||
|
||||
if w.Code != http.StatusForbidden {
|
||||
t.Fatalf("expected 403, got %d: %s", w.Code, w.Body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDelete_AdminRestoresShifts(t *testing.T) {
|
||||
store := &fakeStore{
|
||||
getResult: &timeoff.Request{
|
||||
ID: 1, VolunteerID: 10, Status: "approved",
|
||||
StartsAt: time.Date(2026, 5, 1, 0, 0, 0, 0, time.UTC),
|
||||
},
|
||||
restoredShifts: []timeoff.ConflictingShift{
|
||||
{InstanceID: 100, Name: "Morning Walk", Date: "2026-05-01"},
|
||||
},
|
||||
}
|
||||
_, router := setup(store)
|
||||
token := jwtForRole(t, 1, "admin")
|
||||
|
||||
w := do(t, router, "DELETE", "/api/v1/timeoff/1", "", token)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("expected 200, got %d: %s", w.Code, w.Body)
|
||||
}
|
||||
if !store.restoreCalled {
|
||||
t.Error("expected RestoreRemovedShifts to be called")
|
||||
}
|
||||
var result map[string]any
|
||||
json.NewDecoder(w.Body).Decode(&result)
|
||||
restored := result["restored_shifts"].([]any)
|
||||
if len(restored) != 1 {
|
||||
t.Errorf("expected 1 restored shift, got %d", len(restored))
|
||||
}
|
||||
}
|
||||
|
||||
func TestRemovedShifts_AdminOnly(t *testing.T) {
|
||||
store := &fakeStore{
|
||||
removedForTimeOff: []timeoff.ConflictingShift{
|
||||
{InstanceID: 100, Name: "Morning Walk", Date: "2026-05-01"},
|
||||
},
|
||||
}
|
||||
_, router := setup(store)
|
||||
|
||||
// Volunteer should get 403
|
||||
volToken := jwtForRole(t, 10, "volunteer")
|
||||
w := do(t, router, "GET", "/api/v1/timeoff/1/shifts", "", volToken)
|
||||
if w.Code != http.StatusForbidden {
|
||||
t.Fatalf("expected 403 for volunteer, got %d", w.Code)
|
||||
}
|
||||
|
||||
// Admin should get 200
|
||||
adminToken := jwtForRole(t, 1, "admin")
|
||||
w = do(t, router, "GET", "/api/v1/timeoff/1/shifts", "", adminToken)
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("expected 200 for admin, got %d: %s", w.Code, w.Body)
|
||||
}
|
||||
var shifts []timeoff.ConflictingShift
|
||||
json.NewDecoder(w.Body).Decode(&shifts)
|
||||
if len(shifts) != 1 {
|
||||
t.Errorf("expected 1 shift, got %d", len(shifts))
|
||||
}
|
||||
}
|
||||
|
||||
func TestReview_AdminOnly(t *testing.T) {
|
||||
store := &fakeStore{}
|
||||
_, router := setup(store)
|
||||
|
||||
volToken := jwtForRole(t, 10, "volunteer")
|
||||
body := `{"status":"approved"}`
|
||||
w := do(t, router, "PUT", "/api/v1/timeoff/1/review", body, volToken)
|
||||
if w.Code != http.StatusForbidden {
|
||||
t.Fatalf("expected 403 for volunteer, got %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReview_InvalidStatus(t *testing.T) {
|
||||
store := &fakeStore{}
|
||||
_, router := setup(store)
|
||||
|
||||
adminToken := jwtForRole(t, 1, "admin")
|
||||
body := `{"status":"maybe"}`
|
||||
w := do(t, router, "PUT", "/api/v1/timeoff/1/review", body, adminToken)
|
||||
if w.Code != http.StatusBadRequest {
|
||||
t.Fatalf("expected 400, got %d: %s", w.Code, w.Body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreate_MissingDates(t *testing.T) {
|
||||
store := &fakeStore{}
|
||||
_, router := setup(store)
|
||||
token := jwtForRole(t, 10, "volunteer")
|
||||
|
||||
body := `{"reason":"vacation"}`
|
||||
w := do(t, router, "POST", "/api/v1/timeoff", body, token)
|
||||
|
||||
if w.Code != http.StatusBadRequest {
|
||||
t.Fatalf("expected 400, got %d", w.Code)
|
||||
}
|
||||
}
|
||||
@@ -27,12 +27,37 @@ type CreateInput struct {
|
||||
StartsAt string `json:"starts_at"`
|
||||
EndsAt string `json:"ends_at"`
|
||||
Reason string `json:"reason"`
|
||||
VolunteerID int64 `json:"volunteer_id,omitempty"` // admin creating for another volunteer
|
||||
ConfirmConflicts bool `json:"confirm_conflicts,omitempty"` // acknowledge shift conflicts
|
||||
}
|
||||
|
||||
type UpdateInput struct {
|
||||
StartsAt string `json:"starts_at"`
|
||||
EndsAt string `json:"ends_at"`
|
||||
Reason string `json:"reason"`
|
||||
}
|
||||
|
||||
type ReviewInput struct {
|
||||
Status string `json:"status"` // "approved" | "rejected"
|
||||
}
|
||||
|
||||
// ConflictingShift is a shift instance that overlaps with a time-off period.
|
||||
type ConflictingShift struct {
|
||||
InstanceID int64 `json:"instance_id"`
|
||||
Name string `json:"name"`
|
||||
Date string `json:"date"`
|
||||
StartTime string `json:"start_time"`
|
||||
EndTime string `json:"end_time"`
|
||||
}
|
||||
|
||||
// RemovedShift records that a volunteer was removed from a shift due to time off.
|
||||
type RemovedShift struct {
|
||||
ID int64 `json:"id"`
|
||||
TimeOffID int64 `json:"time_off_id"`
|
||||
InstanceID int64 `json:"instance_id"`
|
||||
VolunteerID int64 `json:"volunteer_id"`
|
||||
}
|
||||
|
||||
type Store struct {
|
||||
db *sql.DB
|
||||
}
|
||||
@@ -55,25 +80,20 @@ func (s *Store) Create(ctx context.Context, volunteerID int64, in CreateInput) (
|
||||
|
||||
func (s *Store) GetByID(ctx context.Context, id int64) (*Request, error) {
|
||||
req := &Request{}
|
||||
var startsAt, endsAt, createdAt, updatedAt string
|
||||
var reason sql.NullString
|
||||
var reviewedBy sql.NullInt64
|
||||
var reviewedAt sql.NullString
|
||||
var reviewedAt sql.NullTime
|
||||
|
||||
err := s.db.QueryRowContext(ctx,
|
||||
`SELECT id, volunteer_id, starts_at, ends_at, reason, status, reviewed_by, reviewed_at, created_at, updated_at
|
||||
FROM time_off_requests WHERE id = ?`, id,
|
||||
).Scan(&req.ID, &req.VolunteerID, &startsAt, &endsAt, &reason, &req.Status, &reviewedBy, &reviewedAt, &createdAt, &updatedAt)
|
||||
).Scan(&req.ID, &req.VolunteerID, &req.StartsAt, &req.EndsAt, &reason, &req.Status, &reviewedBy, &reviewedAt, &req.CreatedAt, &req.UpdatedAt)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("get time off request: %w", err)
|
||||
}
|
||||
req.StartsAt, _ = time.Parse("2006-01-02 15:04:05", startsAt)
|
||||
req.EndsAt, _ = time.Parse("2006-01-02 15:04:05", endsAt)
|
||||
req.CreatedAt, _ = time.Parse("2006-01-02 15:04:05", createdAt)
|
||||
req.UpdatedAt, _ = time.Parse("2006-01-02 15:04:05", updatedAt)
|
||||
if reason.Valid {
|
||||
req.Reason = reason.String
|
||||
}
|
||||
@@ -81,8 +101,7 @@ func (s *Store) GetByID(ctx context.Context, id int64) (*Request, error) {
|
||||
req.ReviewedBy = &reviewedBy.Int64
|
||||
}
|
||||
if reviewedAt.Valid {
|
||||
t, _ := time.Parse("2006-01-02 15:04:05", reviewedAt.String)
|
||||
req.ReviewedAt = &t
|
||||
req.ReviewedAt = &reviewedAt.Time
|
||||
}
|
||||
return req, nil
|
||||
}
|
||||
@@ -105,17 +124,12 @@ func (s *Store) List(ctx context.Context, volunteerID int64) ([]Request, error)
|
||||
var requests []Request
|
||||
for rows.Next() {
|
||||
var req Request
|
||||
var startsAt, endsAt, createdAt, updatedAt string
|
||||
var reason sql.NullString
|
||||
var reviewedBy sql.NullInt64
|
||||
var reviewedAt sql.NullString
|
||||
if err := rows.Scan(&req.ID, &req.VolunteerID, &startsAt, &endsAt, &reason, &req.Status, &reviewedBy, &reviewedAt, &createdAt, &updatedAt); err != nil {
|
||||
var reviewedAt sql.NullTime
|
||||
if err := rows.Scan(&req.ID, &req.VolunteerID, &req.StartsAt, &req.EndsAt, &reason, &req.Status, &reviewedBy, &reviewedAt, &req.CreatedAt, &req.UpdatedAt); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
req.StartsAt, _ = time.Parse("2006-01-02 15:04:05", startsAt)
|
||||
req.EndsAt, _ = time.Parse("2006-01-02 15:04:05", endsAt)
|
||||
req.CreatedAt, _ = time.Parse("2006-01-02 15:04:05", createdAt)
|
||||
req.UpdatedAt, _ = time.Parse("2006-01-02 15:04:05", updatedAt)
|
||||
if reason.Valid {
|
||||
req.Reason = reason.String
|
||||
}
|
||||
@@ -123,8 +137,7 @@ func (s *Store) List(ctx context.Context, volunteerID int64) ([]Request, error)
|
||||
req.ReviewedBy = &reviewedBy.Int64
|
||||
}
|
||||
if reviewedAt.Valid {
|
||||
t, _ := time.Parse("2006-01-02 15:04:05", reviewedAt.String)
|
||||
req.ReviewedAt = &t
|
||||
req.ReviewedAt = &reviewedAt.Time
|
||||
}
|
||||
requests = append(requests, req)
|
||||
}
|
||||
@@ -141,3 +154,207 @@ func (s *Store) Review(ctx context.Context, id, reviewerID int64, status string)
|
||||
}
|
||||
return s.GetByID(ctx, id)
|
||||
}
|
||||
|
||||
// Update edits a time-off request's dates and reason.
|
||||
func (s *Store) Update(ctx context.Context, id int64, in UpdateInput) (*Request, error) {
|
||||
_, err := s.db.ExecContext(ctx,
|
||||
`UPDATE time_off_requests SET starts_at=?, ends_at=?, reason=?, updated_at=NOW() WHERE id=?`,
|
||||
in.StartsAt, in.EndsAt, in.Reason, id,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("update time off request: %w", err)
|
||||
}
|
||||
return s.GetByID(ctx, id)
|
||||
}
|
||||
|
||||
// Delete removes a time-off request.
|
||||
func (s *Store) Delete(ctx context.Context, id int64) error {
|
||||
result, err := s.db.ExecContext(ctx, `DELETE FROM time_off_requests WHERE id = ?`, id)
|
||||
if err != nil {
|
||||
return fmt.Errorf("delete time off request: %w", err)
|
||||
}
|
||||
affected, _ := result.RowsAffected()
|
||||
if affected == 0 {
|
||||
return ErrNotFound
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ConflictingShifts returns published shift instances where the volunteer is assigned
|
||||
// and the shift date falls within the given date range (inclusive).
|
||||
func (s *Store) ConflictingShifts(ctx context.Context, volunteerID int64, startsAt, endsAt string) ([]ConflictingShift, error) {
|
||||
rows, err := s.db.QueryContext(ctx,
|
||||
`SELECT si.id, si.name, si.date, si.start_time, si.end_time
|
||||
FROM shift_instances si
|
||||
JOIN shift_instance_volunteers siv ON siv.instance_id = si.id
|
||||
WHERE siv.volunteer_id = ?
|
||||
AND si.date >= ?
|
||||
AND si.date <= ?
|
||||
ORDER BY si.date`, volunteerID, startsAt, endsAt,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("query conflicting shifts: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var shifts []ConflictingShift
|
||||
for rows.Next() {
|
||||
var cs ConflictingShift
|
||||
if err := rows.Scan(&cs.InstanceID, &cs.Name, &cs.Date, &cs.StartTime, &cs.EndTime); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
shifts = append(shifts, cs)
|
||||
}
|
||||
return shifts, rows.Err()
|
||||
}
|
||||
|
||||
// RemoveFromConflictingShifts removes the volunteer from shifts that overlap with
|
||||
// the time-off period and records the removals for later restoration.
|
||||
func (s *Store) RemoveFromConflictingShifts(ctx context.Context, timeOffID, volunteerID int64, startsAt, endsAt string) ([]ConflictingShift, error) {
|
||||
conflicts, err := s.ConflictingShifts(ctx, volunteerID, startsAt, endsAt)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(conflicts) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
tx, err := s.db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("begin tx: %w", err)
|
||||
}
|
||||
defer tx.Rollback()
|
||||
|
||||
for _, c := range conflicts {
|
||||
// Record the removal
|
||||
if _, err := tx.ExecContext(ctx,
|
||||
`INSERT INTO time_off_removed_shifts (time_off_id, instance_id, volunteer_id) VALUES (?, ?, ?)`,
|
||||
timeOffID, c.InstanceID, volunteerID,
|
||||
); err != nil {
|
||||
return nil, fmt.Errorf("record removal: %w", err)
|
||||
}
|
||||
// Remove volunteer from shift
|
||||
if _, err := tx.ExecContext(ctx,
|
||||
`DELETE FROM shift_instance_volunteers WHERE instance_id = ? AND volunteer_id = ?`,
|
||||
c.InstanceID, volunteerID,
|
||||
); err != nil {
|
||||
return nil, fmt.Errorf("remove from shift: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
if err := tx.Commit(); err != nil {
|
||||
return nil, fmt.Errorf("commit: %w", err)
|
||||
}
|
||||
return conflicts, nil
|
||||
}
|
||||
|
||||
// RemovedShiftsForTimeOff returns shifts from which the volunteer was removed
|
||||
// due to the given time-off request (for preview before admin deletes time off).
|
||||
func (s *Store) RemovedShiftsForTimeOff(ctx context.Context, timeOffID int64) ([]ConflictingShift, error) {
|
||||
rows, err := s.db.QueryContext(ctx,
|
||||
`SELECT si.id, si.name, si.date, si.start_time, si.end_time
|
||||
FROM time_off_removed_shifts tors
|
||||
JOIN shift_instances si ON si.id = tors.instance_id
|
||||
WHERE tors.time_off_id = ?
|
||||
ORDER BY si.date`, timeOffID,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("query removed shifts: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var shifts []ConflictingShift
|
||||
for rows.Next() {
|
||||
var cs ConflictingShift
|
||||
if err := rows.Scan(&cs.InstanceID, &cs.Name, &cs.Date, &cs.StartTime, &cs.EndTime); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
shifts = append(shifts, cs)
|
||||
}
|
||||
return shifts, rows.Err()
|
||||
}
|
||||
|
||||
// RestoreRemovedShifts re-adds the volunteer to shifts they were removed from
|
||||
// when the given time-off request is deleted (FR-T04).
|
||||
func (s *Store) RestoreRemovedShifts(ctx context.Context, timeOffID int64) ([]ConflictingShift, error) {
|
||||
// Get the removals first
|
||||
rows, err := s.db.QueryContext(ctx,
|
||||
`SELECT tors.instance_id, tors.volunteer_id, si.name, si.date, si.start_time, si.end_time
|
||||
FROM time_off_removed_shifts tors
|
||||
JOIN shift_instances si ON si.id = tors.instance_id
|
||||
WHERE tors.time_off_id = ?`, timeOffID,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("query removals: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
type removal struct {
|
||||
instanceID int64
|
||||
volunteerID int64
|
||||
shift ConflictingShift
|
||||
}
|
||||
var removals []removal
|
||||
for rows.Next() {
|
||||
var r removal
|
||||
if err := rows.Scan(&r.instanceID, &r.volunteerID, &r.shift.Name, &r.shift.Date, &r.shift.StartTime, &r.shift.EndTime); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
r.shift.InstanceID = r.instanceID
|
||||
removals = append(removals, r)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if len(removals) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
tx, err := s.db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("begin tx: %w", err)
|
||||
}
|
||||
defer tx.Rollback()
|
||||
|
||||
var restored []ConflictingShift
|
||||
for _, r := range removals {
|
||||
// Re-add to shift (ignore duplicate if they were re-added manually)
|
||||
_, err := tx.ExecContext(ctx,
|
||||
`INSERT IGNORE INTO shift_instance_volunteers (instance_id, volunteer_id) VALUES (?, ?)`,
|
||||
r.instanceID, r.volunteerID,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("restore to shift: %w", err)
|
||||
}
|
||||
restored = append(restored, r.shift)
|
||||
}
|
||||
|
||||
// Clean up removal records (CASCADE will handle this on time-off delete,
|
||||
// but we clean up explicitly since we're restoring)
|
||||
if _, err := tx.ExecContext(ctx,
|
||||
`DELETE FROM time_off_removed_shifts WHERE time_off_id = ?`, timeOffID,
|
||||
); err != nil {
|
||||
return nil, fmt.Errorf("clean removals: %w", err)
|
||||
}
|
||||
|
||||
if err := tx.Commit(); err != nil {
|
||||
return nil, fmt.Errorf("commit: %w", err)
|
||||
}
|
||||
return restored, nil
|
||||
}
|
||||
|
||||
// HasApprovedTimeOff checks if a volunteer has approved time off covering the given date.
|
||||
func (s *Store) HasApprovedTimeOff(ctx context.Context, volunteerID int64, date string) (bool, error) {
|
||||
var count int
|
||||
err := s.db.QueryRowContext(ctx,
|
||||
`SELECT COUNT(*) FROM time_off_requests
|
||||
WHERE volunteer_id = ? AND status = 'approved'
|
||||
AND ? >= DATE(starts_at) AND ? <= DATE(ends_at)`,
|
||||
volunteerID, date, date,
|
||||
).Scan(&count)
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("check time off: %w", err)
|
||||
}
|
||||
return count > 0, nil
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package volunteer
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
@@ -8,43 +9,27 @@ import (
|
||||
|
||||
"git.unsupervised.ca/walkies/internal/auth"
|
||||
"git.unsupervised.ca/walkies/internal/respond"
|
||||
"git.unsupervised.ca/walkies/internal/server/middleware"
|
||||
"github.com/go-chi/chi/v5"
|
||||
)
|
||||
|
||||
// AuthServicer is the subset of auth.Service the Handler needs.
|
||||
type AuthServicer interface {
|
||||
Login(ctx context.Context, email, password string) (int64, string, error)
|
||||
}
|
||||
|
||||
type Handler struct {
|
||||
store *Store
|
||||
authSvc *auth.Service
|
||||
store Storer
|
||||
authSvc AuthServicer
|
||||
}
|
||||
|
||||
func NewHandler(store *Store, authSvc *auth.Service) *Handler {
|
||||
return &Handler{store: store, authSvc: authSvc}
|
||||
}
|
||||
|
||||
// POST /api/v1/auth/register
|
||||
func (h *Handler) Register(w http.ResponseWriter, r *http.Request) {
|
||||
var in CreateInput
|
||||
if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
|
||||
respond.Error(w, http.StatusBadRequest, "invalid request body")
|
||||
return
|
||||
}
|
||||
if in.Name == "" || in.Email == "" || in.Password == "" {
|
||||
respond.Error(w, http.StatusBadRequest, "name, email, and password are required")
|
||||
return
|
||||
}
|
||||
if in.Role == "" {
|
||||
in.Role = "volunteer"
|
||||
}
|
||||
hash, err := auth.HashPassword(in.Password)
|
||||
if err != nil {
|
||||
respond.Error(w, http.StatusInternalServerError, "could not hash password")
|
||||
return
|
||||
}
|
||||
v, err := h.store.Create(r.Context(), in.Name, in.Email, hash, in.Role)
|
||||
if err != nil {
|
||||
respond.Error(w, http.StatusConflict, "email already in use")
|
||||
return
|
||||
}
|
||||
respond.JSON(w, http.StatusCreated, v)
|
||||
// NewHandlerFromInterfaces constructs a Handler from interface values, intended for testing.
|
||||
func NewHandlerFromInterfaces(store Storer, authSvc AuthServicer) *Handler {
|
||||
return &Handler{store: store, authSvc: authSvc}
|
||||
}
|
||||
|
||||
// POST /api/v1/auth/login
|
||||
@@ -57,16 +42,82 @@ func (h *Handler) Login(w http.ResponseWriter, r *http.Request) {
|
||||
respond.Error(w, http.StatusBadRequest, "invalid request body")
|
||||
return
|
||||
}
|
||||
token, err := h.authSvc.Login(r.Context(), body.Email, body.Password)
|
||||
id, token, err := h.authSvc.Login(r.Context(), body.Email, body.Password)
|
||||
if err != nil {
|
||||
respond.Error(w, http.StatusUnauthorized, "invalid credentials")
|
||||
return
|
||||
}
|
||||
_ = h.store.RecordLogin(r.Context(), id)
|
||||
respond.JSON(w, http.StatusOK, map[string]string{"token": token})
|
||||
}
|
||||
|
||||
// POST /api/v1/auth/activate
|
||||
// Public endpoint — volunteer sets their password using an invite token.
|
||||
func (h *Handler) Activate(w http.ResponseWriter, r *http.Request) {
|
||||
var body struct {
|
||||
Token string `json:"token"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
||||
respond.Error(w, http.StatusBadRequest, "invalid request body")
|
||||
return
|
||||
}
|
||||
if body.Token == "" || body.Password == "" {
|
||||
respond.Error(w, http.StatusBadRequest, "token and password are required")
|
||||
return
|
||||
}
|
||||
hashed, err := auth.HashPassword(body.Password)
|
||||
if err != nil {
|
||||
respond.Error(w, http.StatusInternalServerError, "could not hash password")
|
||||
return
|
||||
}
|
||||
v, err := h.store.Activate(r.Context(), body.Token, hashed)
|
||||
if errors.Is(err, ErrInvalidToken) {
|
||||
respond.Error(w, http.StatusBadRequest, "invalid or expired invite token")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
respond.Error(w, http.StatusInternalServerError, "could not activate account")
|
||||
return
|
||||
}
|
||||
respond.JSON(w, http.StatusOK, v)
|
||||
}
|
||||
|
||||
// POST /api/v1/volunteers — admin only
|
||||
func (h *Handler) Create(w http.ResponseWriter, r *http.Request) {
|
||||
var in CreateInput
|
||||
if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
|
||||
respond.Error(w, http.StatusBadRequest, "invalid request body")
|
||||
return
|
||||
}
|
||||
if in.Name == "" || in.Email == "" {
|
||||
respond.Error(w, http.StatusBadRequest, "name and email are required")
|
||||
return
|
||||
}
|
||||
av, err := h.store.Create(r.Context(), in)
|
||||
if err != nil {
|
||||
respond.Error(w, http.StatusConflict, "email already in use")
|
||||
return
|
||||
}
|
||||
respond.JSON(w, http.StatusCreated, av)
|
||||
}
|
||||
|
||||
// GET /api/v1/volunteers
|
||||
func (h *Handler) List(w http.ResponseWriter, r *http.Request) {
|
||||
claims := middleware.ClaimsFromContext(r.Context())
|
||||
if claims != nil && claims.Role == "admin" {
|
||||
volunteers, err := h.store.ListAdmin(r.Context())
|
||||
if err != nil {
|
||||
respond.Error(w, http.StatusInternalServerError, "could not list volunteers")
|
||||
return
|
||||
}
|
||||
if volunteers == nil {
|
||||
volunteers = []AdminVolunteer{}
|
||||
}
|
||||
respond.JSON(w, http.StatusOK, volunteers)
|
||||
return
|
||||
}
|
||||
|
||||
volunteers, err := h.store.List(r.Context(), true)
|
||||
if err != nil {
|
||||
respond.Error(w, http.StatusInternalServerError, "could not list volunteers")
|
||||
@@ -85,6 +136,21 @@ func (h *Handler) Get(w http.ResponseWriter, r *http.Request) {
|
||||
respond.Error(w, http.StatusBadRequest, "invalid id")
|
||||
return
|
||||
}
|
||||
claims := middleware.ClaimsFromContext(r.Context())
|
||||
if claims != nil && claims.Role == "admin" {
|
||||
av, err := h.store.GetAdminByID(r.Context(), id)
|
||||
if errors.Is(err, ErrNotFound) {
|
||||
respond.Error(w, http.StatusNotFound, "volunteer not found")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
respond.Error(w, http.StatusInternalServerError, "could not get volunteer")
|
||||
return
|
||||
}
|
||||
respond.JSON(w, http.StatusOK, av)
|
||||
return
|
||||
}
|
||||
|
||||
v, err := h.store.GetByID(r.Context(), id)
|
||||
if errors.Is(err, ErrNotFound) {
|
||||
respond.Error(w, http.StatusNotFound, "volunteer not found")
|
||||
@@ -98,17 +164,35 @@ func (h *Handler) Get(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
|
||||
// PUT /api/v1/volunteers/{id}
|
||||
// Admins can update all fields. Volunteers can only update their own name and phone.
|
||||
func (h *Handler) Update(w http.ResponseWriter, r *http.Request) {
|
||||
id, err := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64)
|
||||
if err != nil {
|
||||
respond.Error(w, http.StatusBadRequest, "invalid id")
|
||||
return
|
||||
}
|
||||
claims := middleware.ClaimsFromContext(r.Context())
|
||||
if claims == nil {
|
||||
respond.Error(w, http.StatusUnauthorized, "unauthorized")
|
||||
return
|
||||
}
|
||||
|
||||
var in UpdateInput
|
||||
if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
|
||||
respond.Error(w, http.StatusBadRequest, "invalid request body")
|
||||
return
|
||||
}
|
||||
|
||||
// Volunteers can only update their own profile, and only name + phone.
|
||||
if claims.Role != "admin" {
|
||||
if claims.VolunteerID != id {
|
||||
respond.Error(w, http.StatusForbidden, "forbidden")
|
||||
return
|
||||
}
|
||||
restricted := UpdateInput{Name: in.Name, Phone: in.Phone}
|
||||
in = restricted
|
||||
}
|
||||
|
||||
v, err := h.store.Update(r.Context(), id, in)
|
||||
if errors.Is(err, ErrNotFound) {
|
||||
respond.Error(w, http.StatusNotFound, "volunteer not found")
|
||||
@@ -120,3 +204,18 @@ func (h *Handler) Update(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
respond.JSON(w, http.StatusOK, v)
|
||||
}
|
||||
|
||||
// POST /api/v1/volunteers/{id}/invite — admin only, resends invite token
|
||||
func (h *Handler) ResendInvite(w http.ResponseWriter, r *http.Request) {
|
||||
id, err := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64)
|
||||
if err != nil {
|
||||
respond.Error(w, http.StatusBadRequest, "invalid id")
|
||||
return
|
||||
}
|
||||
token, err := h.store.RotateInviteToken(r.Context(), id)
|
||||
if err != nil {
|
||||
respond.Error(w, http.StatusInternalServerError, "could not generate invite token")
|
||||
return
|
||||
}
|
||||
respond.JSON(w, http.StatusOK, map[string]string{"invite_token": token})
|
||||
}
|
||||
|
||||
442
internal/volunteer/handler_test.go
Normal file
442
internal/volunteer/handler_test.go
Normal file
@@ -0,0 +1,442 @@
|
||||
package volunteer_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.unsupervised.ca/walkies/internal/auth"
|
||||
"git.unsupervised.ca/walkies/internal/server/middleware"
|
||||
"git.unsupervised.ca/walkies/internal/volunteer"
|
||||
"github.com/go-chi/chi/v5"
|
||||
)
|
||||
|
||||
// ---- fakes ---------------------------------------------------------------
|
||||
|
||||
type fakeStore struct {
|
||||
volunteer *volunteer.Volunteer
|
||||
adminVol *volunteer.AdminVolunteer
|
||||
adminList []volunteer.AdminVolunteer
|
||||
volList []volunteer.Volunteer
|
||||
activateErr error
|
||||
createErr error
|
||||
updateResult *volunteer.Volunteer
|
||||
updateErr error
|
||||
inviteToken string
|
||||
recordCalled bool
|
||||
}
|
||||
|
||||
func (f *fakeStore) Create(_ context.Context, in volunteer.CreateInput) (*volunteer.AdminVolunteer, error) {
|
||||
if f.createErr != nil {
|
||||
return nil, f.createErr
|
||||
}
|
||||
tok := "test-invite-token"
|
||||
return &volunteer.AdminVolunteer{
|
||||
Volunteer: volunteer.Volunteer{ID: 99, Name: in.Name, Email: in.Email, Role: "volunteer", Active: true},
|
||||
InviteToken: &tok,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (f *fakeStore) GetByID(_ context.Context, id int64) (*volunteer.Volunteer, error) {
|
||||
if f.volunteer != nil && f.volunteer.ID == id {
|
||||
return f.volunteer, nil
|
||||
}
|
||||
return nil, volunteer.ErrNotFound
|
||||
}
|
||||
|
||||
func (f *fakeStore) GetAdminByID(_ context.Context, id int64) (*volunteer.AdminVolunteer, error) {
|
||||
if f.adminVol != nil && f.adminVol.ID == id {
|
||||
return f.adminVol, nil
|
||||
}
|
||||
return nil, volunteer.ErrNotFound
|
||||
}
|
||||
|
||||
func (f *fakeStore) List(_ context.Context, _ bool) ([]volunteer.Volunteer, error) {
|
||||
return f.volList, nil
|
||||
}
|
||||
|
||||
func (f *fakeStore) ListAdmin(_ context.Context) ([]volunteer.AdminVolunteer, error) {
|
||||
return f.adminList, nil
|
||||
}
|
||||
|
||||
func (f *fakeStore) Update(_ context.Context, id int64, in volunteer.UpdateInput) (*volunteer.Volunteer, error) {
|
||||
if f.updateErr != nil {
|
||||
return nil, f.updateErr
|
||||
}
|
||||
if f.updateResult != nil {
|
||||
return f.updateResult, nil
|
||||
}
|
||||
v := &volunteer.Volunteer{ID: id, Name: "Updated", Role: "volunteer", Active: true}
|
||||
return v, nil
|
||||
}
|
||||
|
||||
func (f *fakeStore) GetByInviteToken(_ context.Context, token string) (*volunteer.Volunteer, error) {
|
||||
if token == "valid-token" {
|
||||
return &volunteer.Volunteer{ID: 1, Name: "Alice", Email: "alice@example.com", Active: true}, nil
|
||||
}
|
||||
return nil, volunteer.ErrInvalidToken
|
||||
}
|
||||
|
||||
func (f *fakeStore) Activate(_ context.Context, token, _ string) (*volunteer.Volunteer, error) {
|
||||
if f.activateErr != nil {
|
||||
return nil, f.activateErr
|
||||
}
|
||||
if token != "valid-token" {
|
||||
return nil, volunteer.ErrInvalidToken
|
||||
}
|
||||
return &volunteer.Volunteer{ID: 1, Name: "Alice", Email: "alice@example.com", Active: true}, nil
|
||||
}
|
||||
|
||||
func (f *fakeStore) RotateInviteToken(_ context.Context, _ int64) (string, error) {
|
||||
if f.inviteToken != "" {
|
||||
return f.inviteToken, nil
|
||||
}
|
||||
return "new-invite-token", nil
|
||||
}
|
||||
|
||||
func (f *fakeStore) RecordLogin(_ context.Context, _ int64) error {
|
||||
f.recordCalled = true
|
||||
return nil
|
||||
}
|
||||
|
||||
type fakeAuthSvc struct {
|
||||
id int64
|
||||
token string
|
||||
err error
|
||||
}
|
||||
|
||||
func (f *fakeAuthSvc) Login(_ context.Context, _, _ string) (int64, string, error) {
|
||||
return f.id, f.token, f.err
|
||||
}
|
||||
|
||||
// ---- helpers -------------------------------------------------------------
|
||||
|
||||
func jwtForRole(t *testing.T, id int64, role string) string {
|
||||
t.Helper()
|
||||
svc := auth.NewService(nil, "test-secret")
|
||||
token, err := svc.IssueToken(id, role)
|
||||
if err != nil {
|
||||
t.Fatalf("issue token: %v", err)
|
||||
}
|
||||
return token
|
||||
}
|
||||
|
||||
func newRouter(h *volunteer.Handler, authSvc *auth.Service) http.Handler {
|
||||
r := chi.NewRouter()
|
||||
r.Post("/api/v1/auth/login", h.Login)
|
||||
r.Post("/api/v1/auth/activate", h.Activate)
|
||||
r.Group(func(r chi.Router) {
|
||||
r.Use(middleware.Authenticate(authSvc))
|
||||
r.Post("/api/v1/volunteers", middleware.RequireAdmin(http.HandlerFunc(h.Create)).ServeHTTP)
|
||||
r.Get("/api/v1/volunteers", h.List)
|
||||
r.Get("/api/v1/volunteers/{id}", h.Get)
|
||||
r.Put("/api/v1/volunteers/{id}", h.Update)
|
||||
r.Post("/api/v1/volunteers/{id}/invite",
|
||||
middleware.RequireAdmin(http.HandlerFunc(h.ResendInvite)).ServeHTTP)
|
||||
})
|
||||
return r
|
||||
}
|
||||
|
||||
func do(t *testing.T, router http.Handler, method, path, body, token string) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
var b *bytes.Reader
|
||||
if body != "" {
|
||||
b = bytes.NewReader([]byte(body))
|
||||
} else {
|
||||
b = bytes.NewReader(nil)
|
||||
}
|
||||
req := httptest.NewRequest(method, path, b)
|
||||
if body != "" {
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
}
|
||||
if token != "" {
|
||||
req.Header.Set("Authorization", "Bearer "+token)
|
||||
}
|
||||
w := httptest.NewRecorder()
|
||||
router.ServeHTTP(w, req)
|
||||
return w
|
||||
}
|
||||
|
||||
// ---- tests ----------------------------------------------------------------
|
||||
|
||||
func TestLogin_Success(t *testing.T) {
|
||||
store := &fakeStore{}
|
||||
authSvc := &fakeAuthSvc{id: 1, token: "jwt-token"}
|
||||
realAuthSvc := auth.NewService(nil, "test-secret")
|
||||
h := volunteer.NewHandlerFromInterfaces(store, authSvc)
|
||||
router := newRouter(h, realAuthSvc)
|
||||
|
||||
w := do(t, router, "POST", "/api/v1/auth/login",
|
||||
`{"email":"a@b.com","password":"pass"}`, "")
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("expected 200, got %d: %s", w.Code, w.Body)
|
||||
}
|
||||
var resp map[string]string
|
||||
json.NewDecoder(w.Body).Decode(&resp)
|
||||
if resp["token"] != "jwt-token" {
|
||||
t.Errorf("expected token jwt-token, got %q", resp["token"])
|
||||
}
|
||||
if !store.recordCalled {
|
||||
t.Error("RecordLogin was not called after successful login")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLogin_InvalidCredentials(t *testing.T) {
|
||||
store := &fakeStore{}
|
||||
authSvc := &fakeAuthSvc{err: auth.ErrInvalidCredentials}
|
||||
realAuthSvc := auth.NewService(nil, "test-secret")
|
||||
h := volunteer.NewHandlerFromInterfaces(store, authSvc)
|
||||
router := newRouter(h, realAuthSvc)
|
||||
|
||||
w := do(t, router, "POST", "/api/v1/auth/login",
|
||||
`{"email":"a@b.com","password":"wrong"}`, "")
|
||||
|
||||
if w.Code != http.StatusUnauthorized {
|
||||
t.Fatalf("expected 401, got %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestActivate_ValidToken(t *testing.T) {
|
||||
store := &fakeStore{}
|
||||
realAuthSvc := auth.NewService(nil, "test-secret")
|
||||
h := volunteer.NewHandlerFromInterfaces(store, &fakeAuthSvc{})
|
||||
router := newRouter(h, realAuthSvc)
|
||||
|
||||
w := do(t, router, "POST", "/api/v1/auth/activate",
|
||||
`{"token":"valid-token","password":"supersecret"}`, "")
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("expected 200, got %d: %s", w.Code, w.Body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestActivate_InvalidToken(t *testing.T) {
|
||||
store := &fakeStore{activateErr: volunteer.ErrInvalidToken}
|
||||
realAuthSvc := auth.NewService(nil, "test-secret")
|
||||
h := volunteer.NewHandlerFromInterfaces(store, &fakeAuthSvc{})
|
||||
router := newRouter(h, realAuthSvc)
|
||||
|
||||
w := do(t, router, "POST", "/api/v1/auth/activate",
|
||||
`{"token":"bad-token","password":"supersecret"}`, "")
|
||||
|
||||
if w.Code != http.StatusBadRequest {
|
||||
t.Fatalf("expected 400, got %d: %s", w.Code, w.Body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestActivate_MissingFields(t *testing.T) {
|
||||
store := &fakeStore{}
|
||||
realAuthSvc := auth.NewService(nil, "test-secret")
|
||||
h := volunteer.NewHandlerFromInterfaces(store, &fakeAuthSvc{})
|
||||
router := newRouter(h, realAuthSvc)
|
||||
|
||||
w := do(t, router, "POST", "/api/v1/auth/activate",
|
||||
`{"token":"valid-token"}`, "")
|
||||
|
||||
if w.Code != http.StatusBadRequest {
|
||||
t.Fatalf("expected 400, got %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreate_AdminOnly(t *testing.T) {
|
||||
store := &fakeStore{}
|
||||
realAuthSvc := auth.NewService(nil, "test-secret")
|
||||
h := volunteer.NewHandlerFromInterfaces(store, &fakeAuthSvc{})
|
||||
router := newRouter(h, realAuthSvc)
|
||||
|
||||
volunteerToken := jwtForRole(t, 2, "volunteer")
|
||||
w := do(t, router, "POST", "/api/v1/volunteers",
|
||||
`{"name":"Bob","email":"bob@example.com"}`, volunteerToken)
|
||||
|
||||
if w.Code != http.StatusForbidden {
|
||||
t.Fatalf("volunteer should be forbidden from creating accounts, got %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreate_Admin_Success(t *testing.T) {
|
||||
store := &fakeStore{}
|
||||
realAuthSvc := auth.NewService(nil, "test-secret")
|
||||
h := volunteer.NewHandlerFromInterfaces(store, &fakeAuthSvc{})
|
||||
router := newRouter(h, realAuthSvc)
|
||||
|
||||
adminToken := jwtForRole(t, 1, "admin")
|
||||
w := do(t, router, "POST", "/api/v1/volunteers",
|
||||
`{"name":"Bob","email":"bob@example.com"}`, adminToken)
|
||||
|
||||
if w.Code != http.StatusCreated {
|
||||
t.Fatalf("expected 201, got %d: %s", w.Code, w.Body)
|
||||
}
|
||||
var av volunteer.AdminVolunteer
|
||||
json.NewDecoder(w.Body).Decode(&av)
|
||||
if av.InviteToken == nil || *av.InviteToken == "" {
|
||||
t.Error("expected invite_token in response")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreate_MissingFields(t *testing.T) {
|
||||
store := &fakeStore{}
|
||||
realAuthSvc := auth.NewService(nil, "test-secret")
|
||||
h := volunteer.NewHandlerFromInterfaces(store, &fakeAuthSvc{})
|
||||
router := newRouter(h, realAuthSvc)
|
||||
|
||||
adminToken := jwtForRole(t, 1, "admin")
|
||||
w := do(t, router, "POST", "/api/v1/volunteers",
|
||||
`{"name":"Bob"}`, adminToken)
|
||||
|
||||
if w.Code != http.StatusBadRequest {
|
||||
t.Fatalf("expected 400, got %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestList_AdminGetsAdminVolunteers(t *testing.T) {
|
||||
notes := "some notes"
|
||||
store := &fakeStore{
|
||||
adminList: []volunteer.AdminVolunteer{
|
||||
{Volunteer: volunteer.Volunteer{ID: 1, Name: "Alice"}, AdminNotes: ¬es},
|
||||
},
|
||||
}
|
||||
realAuthSvc := auth.NewService(nil, "test-secret")
|
||||
h := volunteer.NewHandlerFromInterfaces(store, &fakeAuthSvc{})
|
||||
router := newRouter(h, realAuthSvc)
|
||||
|
||||
adminToken := jwtForRole(t, 1, "admin")
|
||||
w := do(t, router, "GET", "/api/v1/volunteers", "", adminToken)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("expected 200, got %d", w.Code)
|
||||
}
|
||||
body := w.Body.String()
|
||||
if !strings.Contains(body, "some notes") {
|
||||
t.Error("admin response should include admin_notes")
|
||||
}
|
||||
}
|
||||
|
||||
func TestList_VolunteerDoesNotSeeAdminNotes(t *testing.T) {
|
||||
notes := "secret notes"
|
||||
store := &fakeStore{
|
||||
volList: []volunteer.Volunteer{{ID: 2, Name: "Bob"}},
|
||||
adminList: []volunteer.AdminVolunteer{
|
||||
{Volunteer: volunteer.Volunteer{ID: 2, Name: "Bob"}, AdminNotes: ¬es},
|
||||
},
|
||||
}
|
||||
realAuthSvc := auth.NewService(nil, "test-secret")
|
||||
h := volunteer.NewHandlerFromInterfaces(store, &fakeAuthSvc{})
|
||||
router := newRouter(h, realAuthSvc)
|
||||
|
||||
volunteerToken := jwtForRole(t, 2, "volunteer")
|
||||
w := do(t, router, "GET", "/api/v1/volunteers", "", volunteerToken)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("expected 200, got %d", w.Code)
|
||||
}
|
||||
if strings.Contains(w.Body.String(), "secret notes") {
|
||||
t.Error("volunteer should not see admin_notes")
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpdate_VolunteerCanUpdateSelf(t *testing.T) {
|
||||
store := &fakeStore{
|
||||
volunteer: &volunteer.Volunteer{ID: 5, Name: "Carol", Email: "carol@example.com", Active: true},
|
||||
}
|
||||
realAuthSvc := auth.NewService(nil, "test-secret")
|
||||
h := volunteer.NewHandlerFromInterfaces(store, &fakeAuthSvc{})
|
||||
router := newRouter(h, realAuthSvc)
|
||||
|
||||
token := jwtForRole(t, 5, "volunteer")
|
||||
w := do(t, router, "PUT", "/api/v1/volunteers/5",
|
||||
`{"name":"Carol Updated","phone":"555-1234"}`, token)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("expected 200, got %d: %s", w.Code, w.Body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpdate_VolunteerCannotUpdateOther(t *testing.T) {
|
||||
store := &fakeStore{
|
||||
volunteer: &volunteer.Volunteer{ID: 6, Name: "Dave", Active: true},
|
||||
}
|
||||
realAuthSvc := auth.NewService(nil, "test-secret")
|
||||
h := volunteer.NewHandlerFromInterfaces(store, &fakeAuthSvc{})
|
||||
router := newRouter(h, realAuthSvc)
|
||||
|
||||
token := jwtForRole(t, 5, "volunteer") // ID 5 trying to update ID 6
|
||||
w := do(t, router, "PUT", "/api/v1/volunteers/6",
|
||||
`{"name":"Hacked"}`, token)
|
||||
|
||||
if w.Code != http.StatusForbidden {
|
||||
t.Fatalf("expected 403, got %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpdate_VolunteerCannotChangeRole(t *testing.T) {
|
||||
var capturedInput volunteer.UpdateInput
|
||||
store := &fakeStore{
|
||||
volunteer: &volunteer.Volunteer{ID: 5, Name: "Carol", Active: true},
|
||||
}
|
||||
// Patch update to capture the input — use a wrapper
|
||||
_ = capturedInput
|
||||
realAuthSvc := auth.NewService(nil, "test-secret")
|
||||
h := volunteer.NewHandlerFromInterfaces(store, &fakeAuthSvc{})
|
||||
router := newRouter(h, realAuthSvc)
|
||||
|
||||
token := jwtForRole(t, 5, "volunteer")
|
||||
// Attempt to escalate role to admin
|
||||
w := do(t, router, "PUT", "/api/v1/volunteers/5",
|
||||
`{"role":"admin"}`, token)
|
||||
|
||||
// The request should succeed (200) but the role change must be silently dropped.
|
||||
// We verify by checking the response doesn't say role: admin.
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("expected 200, got %d: %s", w.Code, w.Body)
|
||||
}
|
||||
var v volunteer.Volunteer
|
||||
json.NewDecoder(w.Body).Decode(&v)
|
||||
if v.Role == "admin" {
|
||||
t.Error("volunteer should not be able to elevate their own role")
|
||||
}
|
||||
}
|
||||
|
||||
func TestResendInvite_AdminOnly(t *testing.T) {
|
||||
store := &fakeStore{}
|
||||
realAuthSvc := auth.NewService(nil, "test-secret")
|
||||
h := volunteer.NewHandlerFromInterfaces(store, &fakeAuthSvc{})
|
||||
router := newRouter(h, realAuthSvc)
|
||||
|
||||
token := jwtForRole(t, 2, "volunteer")
|
||||
w := do(t, router, "POST", "/api/v1/volunteers/1/invite", `{}`, token)
|
||||
|
||||
if w.Code != http.StatusForbidden {
|
||||
t.Fatalf("expected 403, got %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResendInvite_Admin_Success(t *testing.T) {
|
||||
store := &fakeStore{inviteToken: "fresh-token"}
|
||||
realAuthSvc := auth.NewService(nil, "test-secret")
|
||||
h := volunteer.NewHandlerFromInterfaces(store, &fakeAuthSvc{})
|
||||
router := newRouter(h, realAuthSvc)
|
||||
|
||||
token := jwtForRole(t, 1, "admin")
|
||||
w := do(t, router, "POST", "/api/v1/volunteers/1/invite", `{}`, token)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("expected 200, got %d: %s", w.Code, w.Body)
|
||||
}
|
||||
var resp map[string]string
|
||||
json.NewDecoder(w.Body).Decode(&resp)
|
||||
if resp["invite_token"] != "fresh-token" {
|
||||
t.Errorf("expected fresh-token, got %q", resp["invite_token"])
|
||||
}
|
||||
}
|
||||
|
||||
// Ensure fakeStore satisfies Storer at compile time.
|
||||
var _ volunteer.Storer = (*fakeStore)(nil)
|
||||
|
||||
// Satisfy the unused time import if needed.
|
||||
var _ = time.Now
|
||||
@@ -2,13 +2,25 @@ package volunteer
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"database/sql"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
)
|
||||
|
||||
var ErrNotFound = fmt.Errorf("volunteer not found")
|
||||
var ErrInvalidToken = fmt.Errorf("invalid or expired invite token")
|
||||
|
||||
// OperationalRoles lists the valid operational role values.
|
||||
var OperationalRoles = []string{
|
||||
"Behaviour Team",
|
||||
"Dog Log Monitor",
|
||||
"Dog Shelter Volunteer",
|
||||
"Trainee",
|
||||
"Floater",
|
||||
}
|
||||
|
||||
type Volunteer struct {
|
||||
ID int64 `json:"id"`
|
||||
@@ -16,22 +28,64 @@ type Volunteer struct {
|
||||
Email string `json:"email"`
|
||||
Role string `json:"role"`
|
||||
Active bool `json:"active"`
|
||||
IsTrainee bool `json:"is_trainee"`
|
||||
Phone *string `json:"phone,omitempty"`
|
||||
OperationalRoles string `json:"operational_roles"`
|
||||
NotificationPreference string `json:"notification_preference"`
|
||||
LastLogin *string `json:"last_login,omitempty"`
|
||||
CompletedShifts int `json:"completed_shifts"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
// AdminVolunteer embeds Volunteer and adds admin-only fields.
|
||||
type AdminVolunteer struct {
|
||||
Volunteer
|
||||
AdminNotes *string `json:"admin_notes,omitempty"`
|
||||
InviteToken *string `json:"invite_token,omitempty"`
|
||||
}
|
||||
|
||||
// DisplayName returns "Name (inactive)" for deactivated volunteers.
|
||||
func (v *Volunteer) DisplayName() string {
|
||||
if !v.Active {
|
||||
return v.Name + " (inactive)"
|
||||
}
|
||||
return v.Name
|
||||
}
|
||||
|
||||
type CreateInput struct {
|
||||
Name string `json:"name"`
|
||||
Email string `json:"email"`
|
||||
Password string `json:"password"`
|
||||
Role string `json:"role"`
|
||||
IsTrainee bool `json:"is_trainee"`
|
||||
Phone *string `json:"phone"`
|
||||
OperationalRoles string `json:"operational_roles"`
|
||||
}
|
||||
|
||||
type UpdateInput struct {
|
||||
Name *string `json:"name"`
|
||||
Email *string `json:"email"`
|
||||
Phone *string `json:"phone"`
|
||||
Role *string `json:"role"`
|
||||
Active *bool `json:"active"`
|
||||
IsTrainee *bool `json:"is_trainee"`
|
||||
OperationalRoles *string `json:"operational_roles"`
|
||||
NotificationPreference *string `json:"notification_preference"`
|
||||
AdminNotes *string `json:"admin_notes"`
|
||||
}
|
||||
|
||||
// Storer is the interface the Handler depends on, enabling test fakes.
|
||||
type Storer interface {
|
||||
Create(ctx context.Context, in CreateInput) (*AdminVolunteer, error)
|
||||
GetByID(ctx context.Context, id int64) (*Volunteer, error)
|
||||
GetAdminByID(ctx context.Context, id int64) (*AdminVolunteer, error)
|
||||
List(ctx context.Context, activeOnly bool) ([]Volunteer, error)
|
||||
ListAdmin(ctx context.Context) ([]AdminVolunteer, error)
|
||||
Update(ctx context.Context, id int64, in UpdateInput) (*Volunteer, error)
|
||||
GetByInviteToken(ctx context.Context, token string) (*Volunteer, error)
|
||||
Activate(ctx context.Context, token, hashedPassword string) (*Volunteer, error)
|
||||
RotateInviteToken(ctx context.Context, id int64) (string, error)
|
||||
RecordLogin(ctx context.Context, id int64) error
|
||||
}
|
||||
|
||||
type Store struct {
|
||||
@@ -42,41 +96,107 @@ func NewStore(db *sql.DB) *Store {
|
||||
return &Store{db: db}
|
||||
}
|
||||
|
||||
func (s *Store) Create(ctx context.Context, name, email, hashedPassword, role string) (*Volunteer, error) {
|
||||
// Create inserts a new volunteer with an invite token (no password yet).
|
||||
func (s *Store) Create(ctx context.Context, in CreateInput) (*AdminVolunteer, error) {
|
||||
token, err := generateToken()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("generate invite token: %w", err)
|
||||
}
|
||||
expires := time.Now().Add(72 * time.Hour)
|
||||
|
||||
role := in.Role
|
||||
if role == "" {
|
||||
role = "volunteer"
|
||||
}
|
||||
isTrainee := 0
|
||||
if in.IsTrainee {
|
||||
isTrainee = 1
|
||||
}
|
||||
phone := (*string)(nil)
|
||||
if in.Phone != nil && *in.Phone != "" {
|
||||
phone = in.Phone
|
||||
}
|
||||
|
||||
res, err := s.db.ExecContext(ctx,
|
||||
`INSERT INTO volunteers (name, email, password, role) VALUES (?, ?, ?, ?)`,
|
||||
name, email, hashedPassword, role,
|
||||
`INSERT INTO volunteers (name, email, role, is_trainee, phone, operational_roles, invite_token, invite_expires_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
|
||||
in.Name, in.Email, role, isTrainee, phone, in.OperationalRoles, token, expires,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("insert volunteer: %w", err)
|
||||
}
|
||||
id, _ := res.LastInsertId()
|
||||
return s.GetByID(ctx, id)
|
||||
return s.getAdminByID(ctx, id)
|
||||
}
|
||||
|
||||
func (s *Store) GetByID(ctx context.Context, id int64) (*Volunteer, error) {
|
||||
v := &Volunteer{}
|
||||
v, err := s.getAdminByID(ctx, id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &v.Volunteer, nil
|
||||
}
|
||||
|
||||
func (s *Store) GetAdminByID(ctx context.Context, id int64) (*AdminVolunteer, error) {
|
||||
return s.getAdminByID(ctx, id)
|
||||
}
|
||||
|
||||
func (s *Store) getAdminByID(ctx context.Context, id int64) (*AdminVolunteer, error) {
|
||||
av := &AdminVolunteer{}
|
||||
v := &av.Volunteer
|
||||
var createdAt, updatedAt string
|
||||
err := s.db.QueryRowContext(ctx,
|
||||
`SELECT id, name, email, role, active, created_at, updated_at FROM volunteers WHERE id = ?`, id,
|
||||
).Scan(&v.ID, &v.Name, &v.Email, &v.Role, &v.Active, &createdAt, &updatedAt)
|
||||
var lastLogin, adminNotes, inviteToken sql.NullString
|
||||
var isTrainee int
|
||||
|
||||
err := s.db.QueryRowContext(ctx, `
|
||||
SELECT v.id, v.name, v.email, v.role, v.active, v.is_trainee,
|
||||
v.phone, v.operational_roles, v.notification_preference,
|
||||
v.last_login, v.admin_notes, v.invite_token,
|
||||
v.created_at, v.updated_at,
|
||||
COUNT(c.id) AS completed_shifts
|
||||
FROM volunteers v
|
||||
LEFT JOIN checkins c ON c.volunteer_id = v.id AND c.checked_out_at IS NOT NULL
|
||||
WHERE v.id = ?
|
||||
GROUP BY v.id`, id,
|
||||
).Scan(
|
||||
&v.ID, &v.Name, &v.Email, &v.Role, &v.Active, &isTrainee,
|
||||
&v.Phone, &v.OperationalRoles, &v.NotificationPreference,
|
||||
&lastLogin, &adminNotes, &inviteToken,
|
||||
&createdAt, &updatedAt, &v.CompletedShifts,
|
||||
)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("get volunteer: %w", err)
|
||||
}
|
||||
v.IsTrainee = isTrainee == 1
|
||||
v.CreatedAt, _ = time.Parse("2006-01-02 15:04:05", createdAt)
|
||||
v.UpdatedAt, _ = time.Parse("2006-01-02 15:04:05", updatedAt)
|
||||
return v, nil
|
||||
if lastLogin.Valid {
|
||||
av.Volunteer.LastLogin = &lastLogin.String
|
||||
}
|
||||
if adminNotes.Valid {
|
||||
av.AdminNotes = &adminNotes.String
|
||||
}
|
||||
if inviteToken.Valid {
|
||||
av.InviteToken = &inviteToken.String
|
||||
}
|
||||
return av, nil
|
||||
}
|
||||
|
||||
func (s *Store) List(ctx context.Context, activeOnly bool) ([]Volunteer, error) {
|
||||
query := `SELECT id, name, email, role, active, created_at, updated_at FROM volunteers`
|
||||
query := `
|
||||
SELECT v.id, v.name, v.email, v.role, v.active, v.is_trainee,
|
||||
v.phone, v.operational_roles, v.notification_preference,
|
||||
v.last_login, v.created_at, v.updated_at,
|
||||
COUNT(c.id) AS completed_shifts
|
||||
FROM volunteers v
|
||||
LEFT JOIN checkins c ON c.volunteer_id = v.id AND c.checked_out_at IS NOT NULL`
|
||||
if activeOnly {
|
||||
query += ` WHERE active = 1`
|
||||
query += ` WHERE v.active = 1`
|
||||
}
|
||||
query += ` ORDER BY name`
|
||||
query += ` GROUP BY v.id ORDER BY v.name`
|
||||
|
||||
rows, err := s.db.QueryContext(ctx, query)
|
||||
if err != nil {
|
||||
@@ -88,43 +208,218 @@ func (s *Store) List(ctx context.Context, activeOnly bool) ([]Volunteer, error)
|
||||
for rows.Next() {
|
||||
var v Volunteer
|
||||
var createdAt, updatedAt string
|
||||
if err := rows.Scan(&v.ID, &v.Name, &v.Email, &v.Role, &v.Active, &createdAt, &updatedAt); err != nil {
|
||||
var lastLogin sql.NullString
|
||||
var isTrainee int
|
||||
if err := rows.Scan(
|
||||
&v.ID, &v.Name, &v.Email, &v.Role, &v.Active, &isTrainee,
|
||||
&v.Phone, &v.OperationalRoles, &v.NotificationPreference,
|
||||
&lastLogin, &createdAt, &updatedAt, &v.CompletedShifts,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
v.IsTrainee = isTrainee == 1
|
||||
v.CreatedAt, _ = time.Parse("2006-01-02 15:04:05", createdAt)
|
||||
v.UpdatedAt, _ = time.Parse("2006-01-02 15:04:05", updatedAt)
|
||||
if lastLogin.Valid {
|
||||
v.LastLogin = &lastLogin.String
|
||||
}
|
||||
volunteers = append(volunteers, v)
|
||||
}
|
||||
return volunteers, rows.Err()
|
||||
}
|
||||
|
||||
// ListAdmin returns all volunteers (including inactive) with admin-only fields.
|
||||
func (s *Store) ListAdmin(ctx context.Context) ([]AdminVolunteer, error) {
|
||||
rows, err := s.db.QueryContext(ctx, `
|
||||
SELECT v.id, v.name, v.email, v.role, v.active, v.is_trainee,
|
||||
v.phone, v.operational_roles, v.notification_preference,
|
||||
v.last_login, v.admin_notes, v.invite_token,
|
||||
v.created_at, v.updated_at,
|
||||
COUNT(c.id) AS completed_shifts
|
||||
FROM volunteers v
|
||||
LEFT JOIN checkins c ON c.volunteer_id = v.id AND c.checked_out_at IS NOT NULL
|
||||
GROUP BY v.id ORDER BY v.name`)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("list volunteers (admin): %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var volunteers []AdminVolunteer
|
||||
for rows.Next() {
|
||||
var av AdminVolunteer
|
||||
v := &av.Volunteer
|
||||
var createdAt, updatedAt string
|
||||
var lastLogin, adminNotes, inviteToken sql.NullString
|
||||
var isTrainee int
|
||||
if err := rows.Scan(
|
||||
&v.ID, &v.Name, &v.Email, &v.Role, &v.Active, &isTrainee,
|
||||
&v.Phone, &v.OperationalRoles, &v.NotificationPreference,
|
||||
&lastLogin, &adminNotes, &inviteToken,
|
||||
&createdAt, &updatedAt, &v.CompletedShifts,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
v.IsTrainee = isTrainee == 1
|
||||
v.CreatedAt, _ = time.Parse("2006-01-02 15:04:05", createdAt)
|
||||
v.UpdatedAt, _ = time.Parse("2006-01-02 15:04:05", updatedAt)
|
||||
if lastLogin.Valid {
|
||||
v.LastLogin = &lastLogin.String
|
||||
}
|
||||
if adminNotes.Valid {
|
||||
av.AdminNotes = &adminNotes.String
|
||||
}
|
||||
if inviteToken.Valid {
|
||||
av.InviteToken = &inviteToken.String
|
||||
}
|
||||
volunteers = append(volunteers, av)
|
||||
}
|
||||
return volunteers, rows.Err()
|
||||
}
|
||||
|
||||
func (s *Store) Update(ctx context.Context, id int64, in UpdateInput) (*Volunteer, error) {
|
||||
v, err := s.GetByID(ctx, id)
|
||||
av, err := s.getAdminByID(ctx, id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
v := &av.Volunteer
|
||||
if in.Name != nil {
|
||||
v.Name = *in.Name
|
||||
}
|
||||
if in.Email != nil {
|
||||
v.Email = *in.Email
|
||||
}
|
||||
if in.Phone != nil {
|
||||
v.Phone = in.Phone
|
||||
}
|
||||
if in.Role != nil {
|
||||
v.Role = *in.Role
|
||||
}
|
||||
if in.Active != nil {
|
||||
v.Active = *in.Active
|
||||
}
|
||||
if in.IsTrainee != nil {
|
||||
v.IsTrainee = *in.IsTrainee
|
||||
}
|
||||
if in.OperationalRoles != nil {
|
||||
v.OperationalRoles = *in.OperationalRoles
|
||||
}
|
||||
if in.NotificationPreference != nil {
|
||||
v.NotificationPreference = *in.NotificationPreference
|
||||
}
|
||||
if in.AdminNotes != nil {
|
||||
av.AdminNotes = in.AdminNotes
|
||||
}
|
||||
|
||||
activeInt := 0
|
||||
if v.Active {
|
||||
activeInt = 1
|
||||
}
|
||||
isTraineeInt := 0
|
||||
if v.IsTrainee {
|
||||
isTraineeInt = 1
|
||||
}
|
||||
_, err = s.db.ExecContext(ctx,
|
||||
`UPDATE volunteers SET name=?, email=?, role=?, active=?, updated_at=NOW() WHERE id=?`,
|
||||
v.Name, v.Email, v.Role, activeInt, id,
|
||||
`UPDATE volunteers SET name=?, email=?, phone=?, role=?, active=?, is_trainee=?,
|
||||
operational_roles=?, notification_preference=?, admin_notes=?, updated_at=NOW() WHERE id=?`,
|
||||
v.Name, v.Email, v.Phone, v.Role, activeInt, isTraineeInt,
|
||||
v.OperationalRoles, v.NotificationPreference, av.AdminNotes, id,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("update volunteer: %w", err)
|
||||
}
|
||||
return s.GetByID(ctx, id)
|
||||
}
|
||||
|
||||
// GetByInviteToken returns a volunteer by their invite token if it's still valid.
|
||||
func (s *Store) GetByInviteToken(ctx context.Context, token string) (*Volunteer, error) {
|
||||
var id int64
|
||||
err := s.db.QueryRowContext(ctx,
|
||||
`SELECT id FROM volunteers WHERE invite_token = ? AND invite_expires_at > NOW() AND active = 1`,
|
||||
token,
|
||||
).Scan(&id)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return nil, ErrInvalidToken
|
||||
}
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("lookup invite token: %w", err)
|
||||
}
|
||||
return s.GetByID(ctx, id)
|
||||
}
|
||||
|
||||
// Activate sets a volunteer's password and clears the invite token.
|
||||
func (s *Store) Activate(ctx context.Context, token, hashedPassword string) (*Volunteer, error) {
|
||||
// Look up the ID first while the token is still valid.
|
||||
var id int64
|
||||
err := s.db.QueryRowContext(ctx,
|
||||
`SELECT id FROM volunteers WHERE invite_token = ? AND invite_expires_at > NOW()`,
|
||||
token,
|
||||
).Scan(&id)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return nil, ErrInvalidToken
|
||||
}
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("lookup invite token: %w", err)
|
||||
}
|
||||
|
||||
_, err = s.db.ExecContext(ctx,
|
||||
`UPDATE volunteers SET password=?, invite_token=NULL, invite_expires_at=NULL, updated_at=NOW()
|
||||
WHERE id=?`,
|
||||
hashedPassword, id,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("activate account: %w", err)
|
||||
}
|
||||
return s.GetByID(ctx, id)
|
||||
}
|
||||
|
||||
// RotateInviteToken generates a new invite token for a volunteer.
|
||||
func (s *Store) RotateInviteToken(ctx context.Context, id int64) (string, error) {
|
||||
token, err := generateToken()
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("generate token: %w", err)
|
||||
}
|
||||
expires := time.Now().Add(72 * time.Hour)
|
||||
_, err = s.db.ExecContext(ctx,
|
||||
`UPDATE volunteers SET invite_token=?, invite_expires_at=?, updated_at=NOW() WHERE id=?`,
|
||||
token, expires, id,
|
||||
)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("rotate invite token: %w", err)
|
||||
}
|
||||
return token, nil
|
||||
}
|
||||
|
||||
// RecordLogin updates last_login for a volunteer.
|
||||
func (s *Store) RecordLogin(ctx context.Context, id int64) error {
|
||||
_, err := s.db.ExecContext(ctx,
|
||||
`UPDATE volunteers SET last_login=NOW(), updated_at=NOW() WHERE id=?`, id,
|
||||
)
|
||||
return err
|
||||
}
|
||||
|
||||
// ListAdminIDs returns the IDs of all active admin users.
|
||||
func (s *Store) ListAdminIDs(ctx context.Context) ([]int64, error) {
|
||||
rows, err := s.db.QueryContext(ctx,
|
||||
`SELECT id FROM volunteers WHERE role = 'admin' AND active = 1`)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("list admin IDs: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
var ids []int64
|
||||
for rows.Next() {
|
||||
var id int64
|
||||
if err := rows.Scan(&id); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ids = append(ids, id)
|
||||
}
|
||||
return ids, rows.Err()
|
||||
}
|
||||
|
||||
func generateToken() (string, error) {
|
||||
b := make([]byte, 32)
|
||||
if _, err := rand.Read(b); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return hex.EncodeToString(b), nil
|
||||
}
|
||||
|
||||
8
web/.gitignore
vendored
8
web/.gitignore
vendored
@@ -1,15 +1,11 @@
|
||||
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
|
||||
|
||||
# dependencies
|
||||
/node_modules
|
||||
/.pnp
|
||||
.pnp.js
|
||||
|
||||
# testing
|
||||
/coverage
|
||||
|
||||
# production
|
||||
/build
|
||||
/dist
|
||||
|
||||
# misc
|
||||
.DS_Store
|
||||
@@ -19,5 +15,3 @@
|
||||
.env.production.local
|
||||
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
|
||||
1
web/.npmrc
Normal file
1
web/.npmrc
Normal file
@@ -0,0 +1 @@
|
||||
ignore-scripts=true
|
||||
@@ -1,46 +1,21 @@
|
||||
# Getting Started with Create React App
|
||||
# Walkies Frontend
|
||||
|
||||
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
|
||||
React + TypeScript frontend built with [Vite](https://vite.dev/). Tests run with [Vitest](https://vitest.dev/).
|
||||
|
||||
## Available Scripts
|
||||
|
||||
In the project directory, you can run:
|
||||
### `npm run dev`
|
||||
|
||||
### `npm start`
|
||||
|
||||
Runs the app in the development mode.\
|
||||
Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
|
||||
|
||||
The page will reload if you make edits.\
|
||||
You will also see any lint errors in the console.
|
||||
Starts the development server on [http://localhost:3000](http://localhost:3000) with hot module replacement. API requests to `/api` are proxied to `http://localhost:8080`.
|
||||
|
||||
### `npm test`
|
||||
|
||||
Launches the test runner in the interactive watch mode.\
|
||||
See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
|
||||
Runs all tests once using Vitest with jsdom.
|
||||
|
||||
### `npm run build`
|
||||
|
||||
Builds the app for production to the `build` folder.\
|
||||
It correctly bundles React in production mode and optimizes the build for the best performance.
|
||||
Type-checks with `tsc` then builds the app for production into the `dist` folder.
|
||||
|
||||
The build is minified and the filenames include the hashes.\
|
||||
Your app is ready to be deployed!
|
||||
### `npm run preview`
|
||||
|
||||
See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
|
||||
|
||||
### `npm run eject`
|
||||
|
||||
**Note: this is a one-way operation. Once you `eject`, you can’t go back!**
|
||||
|
||||
If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
|
||||
|
||||
Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own.
|
||||
|
||||
You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it.
|
||||
|
||||
## Learn More
|
||||
|
||||
You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
|
||||
|
||||
To learn React, check out the [React documentation](https://reactjs.org/).
|
||||
Serves the production build locally for previewing.
|
||||
|
||||
18
web/index.html
Normal file
18
web/index.html
Normal file
@@ -0,0 +1,18 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<link rel="icon" href="/favicon.ico" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<meta name="theme-color" content="#000000" />
|
||||
<meta name="description" content="Walkies - Volunteer scheduling" />
|
||||
<link rel="apple-touch-icon" href="/logo192.png" />
|
||||
<link rel="manifest" href="/manifest.json" />
|
||||
<title>Walkies</title>
|
||||
</head>
|
||||
<body>
|
||||
<noscript>You need to enable JavaScript to run this app.</noscript>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
18293
web/package-lock.json
generated
18293
web/package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@@ -2,45 +2,38 @@
|
||||
"name": "web",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"dependencies": {
|
||||
"@lavamoat/preinstall-always-fail": "^3.0.0",
|
||||
"react": "^19.2.4",
|
||||
"react-dom": "^19.2.4",
|
||||
"react-router-dom": "^7.13.1"
|
||||
},
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "tsc -b tsconfig.app.json && vite build",
|
||||
"preview": "vite preview",
|
||||
"test": "vitest run"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@lavamoat/allow-scripts": "^5.0.1",
|
||||
"@testing-library/dom": "^10.4.1",
|
||||
"@testing-library/jest-dom": "^6.9.1",
|
||||
"@testing-library/react": "^16.3.2",
|
||||
"@testing-library/user-event": "^13.5.0",
|
||||
"@types/jest": "^27.5.2",
|
||||
"@types/node": "^16.18.126",
|
||||
"@testing-library/user-event": "^14.6.1",
|
||||
"@types/node": "^25.5.2",
|
||||
"@types/react": "^19.2.14",
|
||||
"@types/react-dom": "^19.2.3",
|
||||
"@types/react-router-dom": "^5.3.3",
|
||||
"react": "^19.2.4",
|
||||
"react-dom": "^19.2.4",
|
||||
"react-router-dom": "^7.13.1",
|
||||
"react-scripts": "5.0.1",
|
||||
"typescript": "^4.9.5",
|
||||
"web-vitals": "^2.1.4"
|
||||
"@vitejs/plugin-react": "^6.0.1",
|
||||
"@vitest/coverage-v8": "^4.1.4",
|
||||
"jsdom": "^29.0.2",
|
||||
"typescript": "^6.0.2",
|
||||
"vite": "^8.0.8",
|
||||
"vitest": "^4.1.4"
|
||||
},
|
||||
"scripts": {
|
||||
"start": "react-scripts start",
|
||||
"build": "react-scripts build",
|
||||
"test": "react-scripts test",
|
||||
"eject": "react-scripts eject"
|
||||
},
|
||||
"eslintConfig": {
|
||||
"extends": [
|
||||
"react-app",
|
||||
"react-app/jest"
|
||||
]
|
||||
},
|
||||
"browserslist": {
|
||||
"production": [
|
||||
">0.2%",
|
||||
"not dead",
|
||||
"not op_mini all"
|
||||
],
|
||||
"development": [
|
||||
"last 1 chrome version",
|
||||
"last 1 firefox version",
|
||||
"last 1 safari version"
|
||||
]
|
||||
"lavamoat": {
|
||||
"allowScripts": {
|
||||
"@lavamoat/preinstall-always-fail": false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,43 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<meta name="theme-color" content="#000000" />
|
||||
<meta
|
||||
name="description"
|
||||
content="Web site created using create-react-app"
|
||||
/>
|
||||
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
|
||||
<!--
|
||||
manifest.json provides metadata used when your web app is installed on a
|
||||
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
|
||||
-->
|
||||
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
|
||||
<!--
|
||||
Notice the use of %PUBLIC_URL% in the tags above.
|
||||
It will be replaced with the URL of the `public` folder during the build.
|
||||
Only files inside the `public` folder can be referenced from the HTML.
|
||||
|
||||
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
|
||||
work correctly both with client-side routing and a non-root public URL.
|
||||
Learn how to configure a non-root public URL by running `npm run build`.
|
||||
-->
|
||||
<title>React App</title>
|
||||
</head>
|
||||
<body>
|
||||
<noscript>You need to enable JavaScript to run this app.</noscript>
|
||||
<div id="root"></div>
|
||||
<!--
|
||||
This HTML file is a template.
|
||||
If you open it directly in the browser, you will see an empty page.
|
||||
|
||||
You can add webfonts, meta tags, or analytics to this file.
|
||||
The build step will place the bundled scripts into the <body> tag.
|
||||
|
||||
To begin the development, run `npm start` or `yarn start`.
|
||||
To create a production bundle, use `npm run build` or `yarn build`.
|
||||
-->
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,9 +1,43 @@
|
||||
import React from 'react';
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import { vi, type Mock } from 'vitest';
|
||||
import App from './App';
|
||||
import { api } from './api';
|
||||
|
||||
test('renders learn react link', () => {
|
||||
render(<App />);
|
||||
const linkElement = screen.getByText(/learn react/i);
|
||||
expect(linkElement).toBeInTheDocument();
|
||||
vi.mock('./api', () => ({
|
||||
api: {
|
||||
getSetupStatus: vi.fn(),
|
||||
createSetupAdmin: vi.fn(),
|
||||
listVolunteers: vi.fn().mockResolvedValue([]),
|
||||
listSchedules: vi.fn().mockResolvedValue([]),
|
||||
listTimeOff: vi.fn().mockResolvedValue([]),
|
||||
listNotifications: vi.fn().mockResolvedValue([]),
|
||||
getVolunteer: vi.fn().mockResolvedValue(null),
|
||||
},
|
||||
OPERATIONAL_ROLES: [],
|
||||
}));
|
||||
|
||||
const mockGetSetupStatus = api.getSetupStatus as Mock;
|
||||
|
||||
beforeEach(() => {
|
||||
localStorage.clear();
|
||||
mockGetSetupStatus.mockResolvedValue({ needs_setup: false });
|
||||
});
|
||||
|
||||
test('renders login page when unauthenticated and setup done', async () => {
|
||||
render(<App />);
|
||||
expect(await screen.findByRole('heading', { name: /sign in/i })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
test('login page has email and password fields', async () => {
|
||||
render(<App />);
|
||||
expect(await screen.findByLabelText(/email/i)).toBeInTheDocument();
|
||||
expect(screen.getByLabelText(/password/i)).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: /sign in/i })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
test('redirects to setup when needs_setup is true', async () => {
|
||||
mockGetSetupStatus.mockResolvedValue({ needs_setup: true });
|
||||
render(<App />);
|
||||
expect(await screen.findByRole('heading', { name: /initial setup/i })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
@@ -1,11 +1,15 @@
|
||||
import React from 'react';
|
||||
import React, { createContext, useContext, useState, useEffect, ReactNode } from 'react';
|
||||
import { BrowserRouter, Routes, Route, NavLink, Navigate } from 'react-router-dom';
|
||||
import { AuthProvider, useAuth } from './auth';
|
||||
import { api } from './api';
|
||||
import Login from './pages/Login';
|
||||
import Activate from './pages/Activate';
|
||||
import Setup from './pages/Setup';
|
||||
import Dashboard from './pages/Dashboard';
|
||||
import Schedules from './pages/Schedules';
|
||||
import TimeOff from './pages/TimeOff';
|
||||
import Volunteers from './pages/Volunteers';
|
||||
import Profile from './pages/Profile';
|
||||
import './App.css';
|
||||
|
||||
function Nav() {
|
||||
@@ -16,6 +20,7 @@ function Nav() {
|
||||
<NavLink to="/">Dashboard</NavLink>
|
||||
<NavLink to="/schedules">Schedules</NavLink>
|
||||
<NavLink to="/timeoff">Time Off</NavLink>
|
||||
<NavLink to="/profile">Profile</NavLink>
|
||||
{role === 'admin' && <NavLink to="/volunteers">Volunteers</NavLink>}
|
||||
<button className="btn-link" onClick={logout}>Sign Out</button>
|
||||
</nav>
|
||||
@@ -31,8 +36,10 @@ function ProtectedLayout() {
|
||||
<main>
|
||||
<Routes>
|
||||
<Route path="/" element={<Dashboard />} />
|
||||
<Route path="/schedules/templates" element={<Schedules />} />
|
||||
<Route path="/schedules" element={<Schedules />} />
|
||||
<Route path="/timeoff" element={<TimeOff />} />
|
||||
<Route path="/profile" element={<Profile />} />
|
||||
<Route path="/volunteers" element={<Volunteers />} />
|
||||
</Routes>
|
||||
</main>
|
||||
@@ -46,14 +53,57 @@ function LoginRoute() {
|
||||
return <Login />;
|
||||
}
|
||||
|
||||
// Setup context lets the Setup page flip needsSetup after creating the admin.
|
||||
const SetupContext = createContext<{ setNeedsSetup: (v: boolean) => void }>({
|
||||
setNeedsSetup: () => {},
|
||||
});
|
||||
export const useSetup = () => useContext(SetupContext);
|
||||
|
||||
function SetupGate({ children }: { children: ReactNode }) {
|
||||
const [needsSetup, setNeedsSetup] = useState<boolean | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
api.getSetupStatus()
|
||||
.then(r => setNeedsSetup(r.needs_setup))
|
||||
.catch(() => setNeedsSetup(false));
|
||||
}, []);
|
||||
|
||||
if (needsSetup === null) return null;
|
||||
|
||||
if (needsSetup) {
|
||||
return (
|
||||
<SetupContext.Provider value={{ setNeedsSetup }}>
|
||||
<Routes>
|
||||
<Route path="/setup" element={<Setup />} />
|
||||
<Route path="*" element={<Navigate to="/setup" replace />} />
|
||||
</Routes>
|
||||
</SetupContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<SetupContext.Provider value={{ setNeedsSetup }}>
|
||||
<Routes>
|
||||
<Route path="/setup" element={<Navigate to="/login" replace />} />
|
||||
<Route path="/login" element={<LoginRoute />} />
|
||||
<Route path="/activate" element={<Activate />} />
|
||||
<Route path="/*" element={<ProtectedLayout />} />
|
||||
</Routes>
|
||||
</SetupContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
export default function App() {
|
||||
return (
|
||||
<AuthProvider>
|
||||
<BrowserRouter>
|
||||
<SetupGate>
|
||||
<Routes>
|
||||
<Route path="/login" element={<LoginRoute />} />
|
||||
<Route path="/activate" element={<Activate />} />
|
||||
<Route path="/*" element={<ProtectedLayout />} />
|
||||
</Routes>
|
||||
</SetupGate>
|
||||
</BrowserRouter>
|
||||
</AuthProvider>
|
||||
);
|
||||
|
||||
192
web/src/api.ts
192
web/src/api.ts
@@ -4,6 +4,16 @@ function getToken(): string | null {
|
||||
return localStorage.getItem('token');
|
||||
}
|
||||
|
||||
class ApiError extends Error {
|
||||
status: number;
|
||||
data: any;
|
||||
constructor(message: string, status: number, data: any) {
|
||||
super(message);
|
||||
this.status = status;
|
||||
this.data = data;
|
||||
}
|
||||
}
|
||||
|
||||
async function request<T>(method: string, path: string, body?: unknown): Promise<T> {
|
||||
const headers: Record<string, string> = { 'Content-Type': 'application/json' };
|
||||
const token = getToken();
|
||||
@@ -17,35 +27,68 @@ async function request<T>(method: string, path: string, body?: unknown): Promise
|
||||
|
||||
if (res.status === 204) return undefined as T;
|
||||
const data = await res.json();
|
||||
if (!res.ok) throw new Error(data.error || 'Request failed');
|
||||
if (!res.ok) throw new ApiError(data.error || data.message || 'Request failed', res.status, data);
|
||||
return data as T;
|
||||
}
|
||||
|
||||
export { ApiError };
|
||||
|
||||
export const api = {
|
||||
// Setup
|
||||
getSetupStatus: () =>
|
||||
request<{ needs_setup: boolean }>('GET', '/setup/status'),
|
||||
createSetupAdmin: (data: { name: string; email: string; password: string }) =>
|
||||
request<{ token: string }>('POST', '/setup/admin', data),
|
||||
|
||||
// Auth
|
||||
login: (email: string, password: string) =>
|
||||
request<{ token: string }>('POST', '/auth/login', { email, password }),
|
||||
register: (name: string, email: string, password: string, role = 'volunteer') =>
|
||||
request<Volunteer>('POST', '/auth/register', { name, email, password, role }),
|
||||
activate: (token: string, password: string) =>
|
||||
request<Volunteer>('POST', '/auth/activate', { token, password }),
|
||||
|
||||
// Volunteers
|
||||
listVolunteers: () => request<Volunteer[]>('GET', '/volunteers'),
|
||||
getVolunteer: (id: number) => request<Volunteer>('GET', `/volunteers/${id}`),
|
||||
updateVolunteer: (id: number, data: Partial<Volunteer>) =>
|
||||
createVolunteer: (data: CreateVolunteerInput) =>
|
||||
request<AdminVolunteer>('POST', '/volunteers', data),
|
||||
listVolunteers: () => request<Volunteer[] | AdminVolunteer[]>('GET', '/volunteers'),
|
||||
getVolunteer: (id: number) => request<Volunteer | AdminVolunteer>('GET', `/volunteers/${id}`),
|
||||
updateVolunteer: (id: number, data: Partial<UpdateVolunteerInput>) =>
|
||||
request<Volunteer>('PUT', `/volunteers/${id}`, data),
|
||||
resendInvite: (id: number) =>
|
||||
request<{ invite_token: string }>('POST', `/volunteers/${id}/invite`, {}),
|
||||
|
||||
// Schedules
|
||||
listSchedules: () => request<Schedule[]>('GET', '/schedules'),
|
||||
createSchedule: (data: CreateScheduleInput) => request<Schedule>('POST', '/schedules', data),
|
||||
updateSchedule: (id: number, data: Partial<CreateScheduleInput>) =>
|
||||
request<Schedule>('PUT', `/schedules/${id}`, data),
|
||||
deleteSchedule: (id: number) => request<void>('DELETE', `/schedules/${id}`),
|
||||
// Shift templates
|
||||
listShiftTemplates: () => request<ShiftTemplate[]>('GET', '/shift-templates'),
|
||||
createShiftTemplate: (data: CreateShiftTemplateInput) =>
|
||||
request<ShiftTemplate>('POST', '/shift-templates', data),
|
||||
updateShiftTemplate: (id: number, data: Partial<CreateShiftTemplateInput>) =>
|
||||
request<ShiftTemplate>('PUT', `/shift-templates/${id}`, data),
|
||||
deleteShiftTemplate: (id: number) => request<void>('DELETE', `/shift-templates/${id}`),
|
||||
|
||||
// Shift instances
|
||||
listShifts: (year: number, month: number) =>
|
||||
request<ShiftInstance[]>('GET', `/shifts?year=${year}&month=${month}`),
|
||||
generateShifts: (year: number, month: number) =>
|
||||
request<ShiftInstance[]>('POST', '/shifts/generate', { year, month }),
|
||||
publishShifts: (year: number, month: number) =>
|
||||
request<{ year: number; month: number }>('POST', '/shifts/publish', { year, month }),
|
||||
unpublishShifts: (year: number, month: number) =>
|
||||
request<{ year: number; month: number }>('POST', '/shifts/unpublish', { year, month }),
|
||||
updateShift: (id: number, data: UpdateShiftInput) =>
|
||||
request<ShiftInstance>('PUT', `/shifts/${id}`, data),
|
||||
confirmShift: (id: number) => request<void>('POST', `/shifts/${id}/confirm`, {}),
|
||||
|
||||
// Time off
|
||||
listTimeOff: () => request<TimeOffRequest[]>('GET', '/timeoff'),
|
||||
createTimeOff: (data: CreateTimeOffInput) => request<TimeOffRequest>('POST', '/timeoff', data),
|
||||
createTimeOff: (data: CreateTimeOffInput & { volunteer_id?: number; confirm_conflicts?: boolean }) =>
|
||||
request<TimeOffRequest | TimeOffConflictResponse>('POST', '/timeoff', data),
|
||||
updateTimeOff: (id: number, data: { starts_at: string; ends_at: string; reason?: string }) =>
|
||||
request<TimeOffRequest>('PUT', `/timeoff/${id}`, data),
|
||||
deleteTimeOff: (id: number) =>
|
||||
request<{ deleted: boolean; restored_shifts: ConflictingShift[] }>('DELETE', `/timeoff/${id}`),
|
||||
reviewTimeOff: (id: number, status: 'approved' | 'rejected') =>
|
||||
request<TimeOffRequest>('PUT', `/timeoff/${id}/review`, { status }),
|
||||
getRemovedShifts: (id: number) =>
|
||||
request<ConflictingShift[]>('GET', `/timeoff/${id}/shifts`),
|
||||
|
||||
// Check-in / out
|
||||
checkIn: (schedule_id?: number, notes?: string) =>
|
||||
@@ -64,27 +107,103 @@ export interface Volunteer {
|
||||
email: string;
|
||||
role: 'admin' | 'volunteer';
|
||||
active: boolean;
|
||||
is_trainee: boolean;
|
||||
phone?: string;
|
||||
operational_roles: string;
|
||||
notification_preference: string;
|
||||
last_login?: string;
|
||||
completed_shifts: number;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
export interface Schedule {
|
||||
export interface AdminVolunteer extends Volunteer {
|
||||
admin_notes?: string;
|
||||
invite_token?: string;
|
||||
}
|
||||
|
||||
export interface CreateVolunteerInput {
|
||||
name: string;
|
||||
email: string;
|
||||
role?: 'admin' | 'volunteer';
|
||||
is_trainee?: boolean;
|
||||
phone?: string;
|
||||
operational_roles?: string;
|
||||
}
|
||||
|
||||
export interface UpdateVolunteerInput {
|
||||
name?: string;
|
||||
email?: string;
|
||||
phone?: string;
|
||||
role?: 'admin' | 'volunteer';
|
||||
active?: boolean;
|
||||
is_trainee?: boolean;
|
||||
operational_roles?: string;
|
||||
notification_preference?: string;
|
||||
admin_notes?: string;
|
||||
}
|
||||
|
||||
export interface TemplateRole {
|
||||
id?: number;
|
||||
template_id?: number;
|
||||
role_name: string;
|
||||
count: number;
|
||||
}
|
||||
|
||||
export interface ShiftTemplate {
|
||||
id: number;
|
||||
volunteer_id: number;
|
||||
title: string;
|
||||
starts_at: string;
|
||||
ends_at: string;
|
||||
notes?: string;
|
||||
name: string;
|
||||
day_of_week: number; // 0=Sun, 1=Mon, ..., 6=Sat
|
||||
start_time: string;
|
||||
end_time: string;
|
||||
min_capacity: number;
|
||||
max_capacity: number;
|
||||
roles: TemplateRole[];
|
||||
volunteer_ids: number[];
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
export interface CreateScheduleInput {
|
||||
volunteer_id?: number;
|
||||
title: string;
|
||||
starts_at: string;
|
||||
ends_at: string;
|
||||
notes?: string;
|
||||
export interface CreateShiftTemplateInput {
|
||||
name: string;
|
||||
day_of_week: number;
|
||||
start_time: string;
|
||||
end_time: string;
|
||||
min_capacity: number;
|
||||
max_capacity: number;
|
||||
roles?: TemplateRole[];
|
||||
volunteer_ids?: number[];
|
||||
}
|
||||
|
||||
export interface InstanceVolunteer {
|
||||
instance_id: number;
|
||||
volunteer_id: number;
|
||||
name: string;
|
||||
confirmed: boolean;
|
||||
confirmed_at?: string;
|
||||
}
|
||||
|
||||
export interface ShiftInstance {
|
||||
id: number;
|
||||
template_id?: number;
|
||||
name: string;
|
||||
date: string; // "YYYY-MM-DD"
|
||||
start_time: string;
|
||||
end_time: string;
|
||||
min_capacity: number;
|
||||
max_capacity: number;
|
||||
status: 'draft' | 'published';
|
||||
year: number;
|
||||
month: number;
|
||||
volunteers: InstanceVolunteer[];
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
export interface UpdateShiftInput {
|
||||
volunteer_ids?: number[];
|
||||
min_capacity?: number;
|
||||
max_capacity?: number;
|
||||
}
|
||||
|
||||
export interface TimeOffRequest {
|
||||
@@ -106,6 +225,19 @@ export interface CreateTimeOffInput {
|
||||
reason?: string;
|
||||
}
|
||||
|
||||
export interface ConflictingShift {
|
||||
instance_id: number;
|
||||
name: string;
|
||||
date: string;
|
||||
start_time: string;
|
||||
end_time: string;
|
||||
}
|
||||
|
||||
export interface TimeOffConflictResponse {
|
||||
message: string;
|
||||
conflicts: ConflictingShift[];
|
||||
}
|
||||
|
||||
export interface CheckIn {
|
||||
id: number;
|
||||
volunteer_id: number;
|
||||
@@ -119,6 +251,14 @@ export interface Notification {
|
||||
id: number;
|
||||
volunteer_id: number;
|
||||
message: string;
|
||||
read: boolean;
|
||||
is_read: boolean;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
export const OPERATIONAL_ROLES = [
|
||||
'Behaviour Team',
|
||||
'Dog Log Monitor',
|
||||
'Dog Shelter Volunteer',
|
||||
'Trainee',
|
||||
'Floater',
|
||||
] as const;
|
||||
|
||||
@@ -1,19 +0,0 @@
|
||||
import React from 'react';
|
||||
import ReactDOM from 'react-dom/client';
|
||||
import './index.css';
|
||||
import App from './App';
|
||||
import reportWebVitals from './reportWebVitals';
|
||||
|
||||
const root = ReactDOM.createRoot(
|
||||
document.getElementById('root') as HTMLElement
|
||||
);
|
||||
root.render(
|
||||
<React.StrictMode>
|
||||
<App />
|
||||
</React.StrictMode>
|
||||
);
|
||||
|
||||
// If you want to start measuring performance in your app, pass a function
|
||||
// to log results (for example: reportWebVitals(console.log))
|
||||
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
|
||||
reportWebVitals();
|
||||
@@ -1 +0,0 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 841.9 595.3"><g fill="#61DAFB"><path d="M666.3 296.5c0-32.5-40.7-63.3-103.1-82.4 14.4-63.6 8-114.2-20.2-130.4-6.5-3.8-14.1-5.6-22.4-5.6v22.3c4.6 0 8.3.9 11.4 2.6 13.6 7.8 19.5 37.5 14.9 75.7-1.1 9.4-2.9 19.3-5.1 29.4-19.6-4.8-41-8.5-63.5-10.9-13.5-18.5-27.5-35.3-41.6-50 32.6-30.3 63.2-46.9 84-46.9V78c-27.5 0-63.5 19.6-99.9 53.6-36.4-33.8-72.4-53.2-99.9-53.2v22.3c20.7 0 51.4 16.5 84 46.6-14 14.7-28 31.4-41.3 49.9-22.6 2.4-44 6.1-63.6 11-2.3-10-4-19.7-5.2-29-4.7-38.2 1.1-67.9 14.6-75.8 3-1.8 6.9-2.6 11.5-2.6V78.5c-8.4 0-16 1.8-22.6 5.6-28.1 16.2-34.4 66.7-19.9 130.1-62.2 19.2-102.7 49.9-102.7 82.3 0 32.5 40.7 63.3 103.1 82.4-14.4 63.6-8 114.2 20.2 130.4 6.5 3.8 14.1 5.6 22.5 5.6 27.5 0 63.5-19.6 99.9-53.6 36.4 33.8 72.4 53.2 99.9 53.2 8.4 0 16-1.8 22.6-5.6 28.1-16.2 34.4-66.7 19.9-130.1 62-19.1 102.5-49.9 102.5-82.3zm-130.2-66.7c-3.7 12.9-8.3 26.2-13.5 39.5-4.1-8-8.4-16-13.1-24-4.6-8-9.5-15.8-14.4-23.4 14.2 2.1 27.9 4.7 41 7.9zm-45.8 106.5c-7.8 13.5-15.8 26.3-24.1 38.2-14.9 1.3-30 2-45.2 2-15.1 0-30.2-.7-45-1.9-8.3-11.9-16.4-24.6-24.2-38-7.6-13.1-14.5-26.4-20.8-39.8 6.2-13.4 13.2-26.8 20.7-39.9 7.8-13.5 15.8-26.3 24.1-38.2 14.9-1.3 30-2 45.2-2 15.1 0 30.2.7 45 1.9 8.3 11.9 16.4 24.6 24.2 38 7.6 13.1 14.5 26.4 20.8 39.8-6.3 13.4-13.2 26.8-20.7 39.9zm32.3-13c5.4 13.4 10 26.8 13.8 39.8-13.1 3.2-26.9 5.9-41.2 8 4.9-7.7 9.8-15.6 14.4-23.7 4.6-8 8.9-16.1 13-24.1zM421.2 430c-9.3-9.6-18.6-20.3-27.8-32 9 .4 18.2.7 27.5.7 9.4 0 18.7-.2 27.8-.7-9 11.7-18.3 22.4-27.5 32zm-74.4-58.9c-14.2-2.1-27.9-4.7-41-7.9 3.7-12.9 8.3-26.2 13.5-39.5 4.1 8 8.4 16 13.1 24 4.7 8 9.5 15.8 14.4 23.4zM420.7 163c9.3 9.6 18.6 20.3 27.8 32-9-.4-18.2-.7-27.5-.7-9.4 0-18.7.2-27.8.7 9-11.7 18.3-22.4 27.5-32zm-74 58.9c-4.9 7.7-9.8 15.6-14.4 23.7-4.6 8-8.9 16-13 24-5.4-13.4-10-26.8-13.8-39.8 13.1-3.1 26.9-5.8 41.2-7.9zm-90.5 125.2c-35.4-15.1-58.3-34.9-58.3-50.6 0-15.7 22.9-35.6 58.3-50.6 8.6-3.7 18-7 27.7-10.1 5.7 19.6 13.2 40 22.5 60.9-9.2 20.8-16.6 41.1-22.2 60.6-9.9-3.1-19.3-6.5-28-10.2zM310 490c-13.6-7.8-19.5-37.5-14.9-75.7 1.1-9.4 2.9-19.3 5.1-29.4 19.6 4.8 41 8.5 63.5 10.9 13.5 18.5 27.5 35.3 41.6 50-32.6 30.3-63.2 46.9-84 46.9-4.5-.1-8.3-1-11.3-2.7zm237.2-76.2c4.7 38.2-1.1 67.9-14.6 75.8-3 1.8-6.9 2.6-11.5 2.6-20.7 0-51.4-16.5-84-46.6 14-14.7 28-31.4 41.3-49.9 22.6-2.4 44-6.1 63.6-11 2.3 10.1 4.1 19.8 5.2 29.1zm38.5-66.7c-8.6 3.7-18 7-27.7 10.1-5.7-19.6-13.2-40-22.5-60.9 9.2-20.8 16.6-41.1 22.2-60.6 9.9 3.1 19.3 6.5 28.1 10.2 35.4 15.1 58.3 34.9 58.3 50.6-.1 15.7-23 35.6-58.4 50.6zM320.8 78.4z"/><circle cx="420.9" cy="296.5" r="45.7"/><path d="M520.5 78.1z"/></g></svg>
|
||||
|
Before Width: | Height: | Size: 2.6 KiB |
10
web/src/main.tsx
Normal file
10
web/src/main.tsx
Normal file
@@ -0,0 +1,10 @@
|
||||
import React from 'react';
|
||||
import ReactDOM from 'react-dom/client';
|
||||
import './index.css';
|
||||
import App from './App';
|
||||
|
||||
ReactDOM.createRoot(document.getElementById('root')!).render(
|
||||
<React.StrictMode>
|
||||
<App />
|
||||
</React.StrictMode>
|
||||
);
|
||||
93
web/src/pages/Activate.test.tsx
Normal file
93
web/src/pages/Activate.test.tsx
Normal file
@@ -0,0 +1,93 @@
|
||||
import React from 'react';
|
||||
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
|
||||
import { vi, type Mock } from 'vitest';
|
||||
import { MemoryRouter, Route, Routes } from 'react-router-dom';
|
||||
import Activate from './Activate';
|
||||
import { api } from '../api';
|
||||
import { AuthProvider } from '../auth';
|
||||
|
||||
vi.mock('../api', () => ({
|
||||
api: {
|
||||
activate: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
const mockActivate = api.activate as Mock;
|
||||
|
||||
function renderActivate(token = 'valid-token') {
|
||||
return render(
|
||||
<AuthProvider>
|
||||
<MemoryRouter initialEntries={[`/activate?token=${token}`]}>
|
||||
<Routes>
|
||||
<Route path="/activate" element={<Activate />} />
|
||||
<Route path="/login" element={<div>Login Page</div>} />
|
||||
</Routes>
|
||||
</MemoryRouter>
|
||||
</AuthProvider>,
|
||||
);
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
mockActivate.mockReset();
|
||||
});
|
||||
|
||||
test('renders password fields', () => {
|
||||
renderActivate();
|
||||
expect(screen.getByLabelText(/^password$/i)).toBeInTheDocument();
|
||||
expect(screen.getByLabelText(/confirm password/i)).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: /activate account/i })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
test('shows error when no token in URL', () => {
|
||||
render(
|
||||
<AuthProvider>
|
||||
<MemoryRouter initialEntries={['/activate']}>
|
||||
<Routes>
|
||||
<Route path="/activate" element={<Activate />} />
|
||||
</Routes>
|
||||
</MemoryRouter>
|
||||
</AuthProvider>,
|
||||
);
|
||||
expect(screen.getByText(/no invite token/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
test('shows error when passwords do not match', async () => {
|
||||
renderActivate();
|
||||
fireEvent.change(screen.getByLabelText(/^password$/i), { target: { value: 'password1' } });
|
||||
fireEvent.change(screen.getByLabelText(/confirm password/i), { target: { value: 'password2' } });
|
||||
fireEvent.click(screen.getByRole('button', { name: /activate account/i }));
|
||||
expect(await screen.findByText(/passwords do not match/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
test('shows error when password too short', async () => {
|
||||
renderActivate();
|
||||
fireEvent.change(screen.getByLabelText(/^password$/i), { target: { value: 'short' } });
|
||||
fireEvent.change(screen.getByLabelText(/confirm password/i), { target: { value: 'short' } });
|
||||
fireEvent.click(screen.getByRole('button', { name: /activate account/i }));
|
||||
expect(await screen.findByText(/at least 8 characters/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
test('calls api.activate and navigates to login on success', async () => {
|
||||
mockActivate.mockResolvedValueOnce({ id: 1, name: 'Alice' });
|
||||
renderActivate('valid-token');
|
||||
|
||||
fireEvent.change(screen.getByLabelText(/^password$/i), { target: { value: 'goodpassword' } });
|
||||
fireEvent.change(screen.getByLabelText(/confirm password/i), { target: { value: 'goodpassword' } });
|
||||
fireEvent.click(screen.getByRole('button', { name: /activate account/i }));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockActivate).toHaveBeenCalledWith('valid-token', 'goodpassword');
|
||||
});
|
||||
expect(await screen.findByText(/login page/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
test('shows error when api.activate fails', async () => {
|
||||
mockActivate.mockRejectedValueOnce(new Error('invalid or expired invite token'));
|
||||
renderActivate('bad-token');
|
||||
|
||||
fireEvent.change(screen.getByLabelText(/^password$/i), { target: { value: 'goodpassword' } });
|
||||
fireEvent.change(screen.getByLabelText(/confirm password/i), { target: { value: 'goodpassword' } });
|
||||
fireEvent.click(screen.getByRole('button', { name: /activate account/i }));
|
||||
|
||||
expect(await screen.findByText(/invalid or expired invite token/i)).toBeInTheDocument();
|
||||
});
|
||||
75
web/src/pages/Activate.tsx
Normal file
75
web/src/pages/Activate.tsx
Normal file
@@ -0,0 +1,75 @@
|
||||
import React, { useState, FormEvent, useEffect } from 'react';
|
||||
import { useNavigate, useSearchParams } from 'react-router-dom';
|
||||
import { api } from '../api';
|
||||
import { useAuth } from '../auth';
|
||||
|
||||
export default function Activate() {
|
||||
const [searchParams] = useSearchParams();
|
||||
const { login } = useAuth();
|
||||
const navigate = useNavigate();
|
||||
const [password, setPassword] = useState('');
|
||||
const [confirm, setConfirm] = useState('');
|
||||
const [error, setError] = useState('');
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const token = searchParams.get('token') ?? '';
|
||||
|
||||
useEffect(() => {
|
||||
if (!token) setError('No invite token provided. Check your invite link.');
|
||||
}, [token]);
|
||||
|
||||
async function handleSubmit(e: FormEvent) {
|
||||
e.preventDefault();
|
||||
setError('');
|
||||
if (password !== confirm) {
|
||||
setError('Passwords do not match.');
|
||||
return;
|
||||
}
|
||||
if (password.length < 8) {
|
||||
setError('Password must be at least 8 characters.');
|
||||
return;
|
||||
}
|
||||
setSubmitting(true);
|
||||
try {
|
||||
await api.activate(token, password);
|
||||
// After activation, prompt user to log in with their new password.
|
||||
navigate('/login?activated=1');
|
||||
} catch (err: any) {
|
||||
setError(err.message);
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="auth-page">
|
||||
<h1>Walkies</h1>
|
||||
<h2>Set Your Password</h2>
|
||||
<p>Welcome! Set a password to activate your account.</p>
|
||||
<form onSubmit={handleSubmit}>
|
||||
{error && <p className="error">{error}</p>}
|
||||
<label>
|
||||
Password
|
||||
<input
|
||||
type="password"
|
||||
value={password}
|
||||
onChange={e => setPassword(e.target.value)}
|
||||
required
|
||||
minLength={8}
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
Confirm password
|
||||
<input
|
||||
type="password"
|
||||
value={confirm}
|
||||
onChange={e => setConfirm(e.target.value)}
|
||||
required
|
||||
/>
|
||||
</label>
|
||||
<button type="submit" disabled={submitting || !token}>
|
||||
{submitting ? 'Activating…' : 'Activate Account'}
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,24 +1,25 @@
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import { api, CheckIn, Notification, Schedule } from '../api';
|
||||
import { api, CheckIn, Notification, ShiftInstance } from '../api';
|
||||
import { useAuth } from '../auth';
|
||||
|
||||
export default function Dashboard() {
|
||||
const { volunteerID } = useAuth();
|
||||
const [schedules, setSchedules] = useState<Schedule[]>([]);
|
||||
const now = new Date();
|
||||
const [schedules, setSchedules] = useState<ShiftInstance[]>([]);
|
||||
const [notifications, setNotifications] = useState<Notification[]>([]);
|
||||
const [activeCheckIn, setActiveCheckIn] = useState<CheckIn | null>(null);
|
||||
const [history, setHistory] = useState<CheckIn[]>([]);
|
||||
const [error, setError] = useState('');
|
||||
|
||||
useEffect(() => {
|
||||
api.listSchedules().then(setSchedules).catch(() => {});
|
||||
api.listShifts(now.getFullYear(), now.getMonth() + 1).then(setSchedules).catch(() => {});
|
||||
api.listNotifications().then(setNotifications).catch(() => {});
|
||||
api.getHistory().then(data => {
|
||||
setHistory(data);
|
||||
const active = data.find(c => !c.checked_out_at && c.volunteer_id === volunteerID);
|
||||
setActiveCheckIn(active ?? null);
|
||||
}).catch(() => {});
|
||||
}, [volunteerID]);
|
||||
}, [volunteerID]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
async function handleCheckIn() {
|
||||
try {
|
||||
@@ -43,15 +44,15 @@ export default function Dashboard() {
|
||||
async function handleMarkRead(id: number) {
|
||||
try {
|
||||
await api.markRead(id);
|
||||
setNotifications(prev => prev.map(n => n.id === id ? { ...n, read: true } : n));
|
||||
setNotifications(prev => prev.map(n => n.id === id ? { ...n, is_read: true } : n));
|
||||
} catch {}
|
||||
}
|
||||
|
||||
const upcomingSchedules = schedules
|
||||
.filter(s => new Date(s.starts_at) >= new Date())
|
||||
.filter(s => new Date(s.date) >= now)
|
||||
.slice(0, 5);
|
||||
|
||||
const unreadNotifications = notifications.filter(n => !n.read);
|
||||
const unreadNotifications = notifications.filter(n => !n.is_read);
|
||||
|
||||
return (
|
||||
<div className="page">
|
||||
@@ -78,7 +79,7 @@ export default function Dashboard() {
|
||||
<ul>
|
||||
{upcomingSchedules.map(s => (
|
||||
<li key={s.id}>
|
||||
<strong>{s.title}</strong> — {new Date(s.starts_at).toLocaleString()} to {new Date(s.ends_at).toLocaleString()}
|
||||
<strong>{s.name}</strong> — {s.date} {s.start_time.slice(0, 5)}–{s.end_time.slice(0, 5)}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
@@ -92,9 +93,9 @@ export default function Dashboard() {
|
||||
) : (
|
||||
<ul>
|
||||
{notifications.map(n => (
|
||||
<li key={n.id} className={n.read ? 'read' : 'unread'}>
|
||||
<li key={n.id} className={n.is_read ? 'read' : 'unread'}>
|
||||
{n.message}
|
||||
{!n.read && (
|
||||
{!n.is_read && (
|
||||
<button className="btn-small" onClick={() => handleMarkRead(n.id)}>Mark read</button>
|
||||
)}
|
||||
</li>
|
||||
|
||||
@@ -1,14 +1,16 @@
|
||||
import React, { useState, FormEvent } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useNavigate, useSearchParams } from 'react-router-dom';
|
||||
import { api } from '../api';
|
||||
import { useAuth } from '../auth';
|
||||
|
||||
export default function Login() {
|
||||
const { login } = useAuth();
|
||||
const navigate = useNavigate();
|
||||
const [searchParams] = useSearchParams();
|
||||
const [email, setEmail] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
const [error, setError] = useState('');
|
||||
const activated = searchParams.get('activated') === '1';
|
||||
|
||||
async function handleSubmit(e: FormEvent) {
|
||||
e.preventDefault();
|
||||
@@ -27,6 +29,7 @@ export default function Login() {
|
||||
<h1>Walkies</h1>
|
||||
<h2>Sign In</h2>
|
||||
<form onSubmit={handleSubmit}>
|
||||
{activated && <p className="success">Account activated! Sign in with your new password.</p>}
|
||||
{error && <p className="error">{error}</p>}
|
||||
<label>
|
||||
Email
|
||||
|
||||
112
web/src/pages/Profile.test.tsx
Normal file
112
web/src/pages/Profile.test.tsx
Normal file
@@ -0,0 +1,112 @@
|
||||
import React from 'react';
|
||||
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
|
||||
import { vi, type Mock } from 'vitest';
|
||||
import { MemoryRouter } from 'react-router-dom';
|
||||
import Profile from './Profile';
|
||||
import { api, Volunteer } from '../api';
|
||||
import { AuthProvider } from '../auth';
|
||||
|
||||
vi.mock('../api', () => ({
|
||||
api: {
|
||||
getVolunteer: vi.fn(),
|
||||
updateVolunteer: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
// Provide a pre-decoded token so AuthProvider exposes volunteerID = 5
|
||||
const FAKE_TOKEN = buildFakeJWT({ volunteer_id: 5, role: 'volunteer', exp: 9999999999 });
|
||||
|
||||
function buildFakeJWT(payload: object): string {
|
||||
const header = btoa(JSON.stringify({ alg: 'HS256', typ: 'JWT' }));
|
||||
const body = btoa(JSON.stringify(payload));
|
||||
return `${header}.${body}.fakesig`;
|
||||
}
|
||||
|
||||
const mockGetVolunteer = api.getVolunteer as Mock;
|
||||
const mockUpdateVolunteer = api.updateVolunteer as Mock;
|
||||
|
||||
const baseVolunteer: Volunteer = {
|
||||
id: 5,
|
||||
name: 'Carol',
|
||||
email: 'carol@example.com',
|
||||
role: 'volunteer',
|
||||
active: true,
|
||||
is_trainee: false,
|
||||
phone: '555-0100',
|
||||
operational_roles: 'Floater',
|
||||
notification_preference: 'email',
|
||||
completed_shifts: 3,
|
||||
created_at: '2026-01-01T00:00:00Z',
|
||||
updated_at: '2026-01-01T00:00:00Z',
|
||||
};
|
||||
|
||||
function renderProfile() {
|
||||
localStorage.setItem('token', FAKE_TOKEN);
|
||||
return render(
|
||||
<AuthProvider>
|
||||
<MemoryRouter>
|
||||
<Profile />
|
||||
</MemoryRouter>
|
||||
</AuthProvider>,
|
||||
);
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
mockGetVolunteer.mockReset();
|
||||
mockUpdateVolunteer.mockReset();
|
||||
localStorage.clear();
|
||||
});
|
||||
|
||||
test('renders volunteer name and email from API', async () => {
|
||||
mockGetVolunteer.mockResolvedValueOnce(baseVolunteer);
|
||||
renderProfile();
|
||||
expect(await screen.findByDisplayValue('Carol')).toBeInTheDocument();
|
||||
expect(screen.getByDisplayValue('carol@example.com')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
test('email field is read-only', async () => {
|
||||
mockGetVolunteer.mockResolvedValueOnce(baseVolunteer);
|
||||
renderProfile();
|
||||
await screen.findByDisplayValue('Carol');
|
||||
expect(screen.getByDisplayValue('carol@example.com')).toBeDisabled();
|
||||
});
|
||||
|
||||
test('submits updated name and phone', async () => {
|
||||
mockGetVolunteer.mockResolvedValueOnce(baseVolunteer);
|
||||
mockUpdateVolunteer.mockResolvedValueOnce({ ...baseVolunteer, name: 'Carol Updated' });
|
||||
renderProfile();
|
||||
|
||||
const nameInput = await screen.findByDisplayValue('Carol');
|
||||
fireEvent.change(nameInput, { target: { value: 'Carol Updated' } });
|
||||
fireEvent.click(screen.getByRole('button', { name: /save changes/i }));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockUpdateVolunteer).toHaveBeenCalledWith(5, expect.objectContaining({
|
||||
name: 'Carol Updated',
|
||||
}));
|
||||
});
|
||||
expect(await screen.findByText(/profile updated/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
test('shows error on save failure', async () => {
|
||||
mockGetVolunteer.mockResolvedValueOnce(baseVolunteer);
|
||||
mockUpdateVolunteer.mockRejectedValueOnce(new Error('Server error'));
|
||||
renderProfile();
|
||||
|
||||
await screen.findByDisplayValue('Carol');
|
||||
fireEvent.click(screen.getByRole('button', { name: /save changes/i }));
|
||||
|
||||
expect(await screen.findByText(/server error/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
test('shows completed shift count', async () => {
|
||||
mockGetVolunteer.mockResolvedValueOnce(baseVolunteer);
|
||||
renderProfile();
|
||||
expect(await screen.findByText(/completed shifts: 3/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
test('shows trainee badge when is_trainee is true', async () => {
|
||||
mockGetVolunteer.mockResolvedValueOnce({ ...baseVolunteer, is_trainee: true });
|
||||
renderProfile();
|
||||
expect(await screen.findByText(/trainee/i)).toBeInTheDocument();
|
||||
});
|
||||
77
web/src/pages/Profile.tsx
Normal file
77
web/src/pages/Profile.tsx
Normal file
@@ -0,0 +1,77 @@
|
||||
import React, { useEffect, useState, FormEvent } from 'react';
|
||||
import { api, Volunteer } from '../api';
|
||||
import { useAuth } from '../auth';
|
||||
|
||||
export default function Profile() {
|
||||
const { volunteerID } = useAuth();
|
||||
const [volunteer, setVolunteer] = useState<Volunteer | null>(null);
|
||||
const [name, setName] = useState('');
|
||||
const [phone, setPhone] = useState('');
|
||||
const [error, setError] = useState('');
|
||||
const [success, setSuccess] = useState('');
|
||||
const [saving, setSaving] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (!volunteerID) return;
|
||||
api.getVolunteer(volunteerID).then(v => {
|
||||
const vol = v as Volunteer;
|
||||
setVolunteer(vol);
|
||||
setName(vol.name);
|
||||
setPhone(vol.phone ?? '');
|
||||
}).catch(() => setError('Could not load profile.'));
|
||||
}, [volunteerID]);
|
||||
|
||||
async function handleSubmit(e: FormEvent) {
|
||||
e.preventDefault();
|
||||
setError('');
|
||||
setSuccess('');
|
||||
if (!volunteerID) return;
|
||||
setSaving(true);
|
||||
try {
|
||||
const updated = await api.updateVolunteer(volunteerID, { name, phone: phone || undefined });
|
||||
setVolunteer(updated);
|
||||
setSuccess('Profile updated.');
|
||||
} catch (err: any) {
|
||||
setError(err.message);
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
}
|
||||
|
||||
if (!volunteer) return <div className="page"><p>Loading…</p></div>;
|
||||
|
||||
return (
|
||||
<div className="page">
|
||||
<h2>My Profile</h2>
|
||||
{error && <p className="error">{error}</p>}
|
||||
{success && <p className="success">{success}</p>}
|
||||
<form onSubmit={handleSubmit} style={{ maxWidth: 400 }}>
|
||||
<label>
|
||||
Full name
|
||||
<input value={name} onChange={e => setName(e.target.value)} required />
|
||||
</label>
|
||||
<label>
|
||||
Email
|
||||
<input value={volunteer.email} disabled />
|
||||
</label>
|
||||
<label>
|
||||
Phone
|
||||
<input value={phone} onChange={e => setPhone(e.target.value)} placeholder="Optional" />
|
||||
</label>
|
||||
<label>
|
||||
Operational roles
|
||||
<input value={volunteer.operational_roles || '—'} disabled />
|
||||
</label>
|
||||
<label>
|
||||
Notification preference
|
||||
<input value={volunteer.notification_preference} disabled />
|
||||
</label>
|
||||
<p style={{ color: '#666', fontSize: '0.85em' }}>
|
||||
Completed shifts: {volunteer.completed_shifts}
|
||||
{volunteer.is_trainee && ' · Trainee'}
|
||||
</p>
|
||||
<button type="submit" disabled={saving}>{saving ? 'Saving…' : 'Save Changes'}</button>
|
||||
</form>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
215
web/src/pages/Schedules.test.tsx
Normal file
215
web/src/pages/Schedules.test.tsx
Normal file
@@ -0,0 +1,215 @@
|
||||
import React from 'react';
|
||||
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
|
||||
import { vi, type Mock } from 'vitest';
|
||||
import { MemoryRouter } from 'react-router-dom';
|
||||
import Schedules from './Schedules';
|
||||
import { api, ShiftInstance, ShiftTemplate } from '../api';
|
||||
|
||||
vi.mock('../api', async () => {
|
||||
const actual = await vi.importActual<typeof import('../api')>('../api');
|
||||
return {
|
||||
...actual,
|
||||
api: {
|
||||
listShifts: vi.fn(),
|
||||
listShiftTemplates: vi.fn(),
|
||||
listVolunteers: vi.fn(),
|
||||
listTimeOff: vi.fn(),
|
||||
generateShifts: vi.fn(),
|
||||
publishShifts: vi.fn(),
|
||||
unpublishShifts: vi.fn(),
|
||||
updateShift: vi.fn(),
|
||||
confirmShift: vi.fn(),
|
||||
createShiftTemplate: vi.fn(),
|
||||
updateShiftTemplate: vi.fn(),
|
||||
deleteShiftTemplate: vi.fn(),
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock('../auth', () => ({
|
||||
useAuth: vi.fn(),
|
||||
}));
|
||||
|
||||
const { useAuth } = await import('../auth');
|
||||
|
||||
const mockDraftInstance: ShiftInstance = {
|
||||
id: 1,
|
||||
name: 'Morning Shift',
|
||||
date: '2026-04-06',
|
||||
start_time: '09:00:00',
|
||||
end_time: '12:00:00',
|
||||
min_capacity: 2,
|
||||
max_capacity: 5,
|
||||
status: 'draft',
|
||||
year: 2026,
|
||||
month: 4,
|
||||
volunteers: [],
|
||||
created_at: '2026-04-01T00:00:00Z',
|
||||
updated_at: '2026-04-01T00:00:00Z',
|
||||
};
|
||||
|
||||
const mockPublishedInstance: ShiftInstance = {
|
||||
...mockDraftInstance,
|
||||
id: 2,
|
||||
status: 'published',
|
||||
volunteers: [{ instance_id: 2, volunteer_id: 10, name: 'Alice', confirmed: false }],
|
||||
};
|
||||
|
||||
const mockTemplate: ShiftTemplate = {
|
||||
id: 1,
|
||||
name: 'Morning Shift',
|
||||
day_of_week: 1,
|
||||
start_time: '09:00:00',
|
||||
end_time: '12:00:00',
|
||||
min_capacity: 2,
|
||||
max_capacity: 5,
|
||||
roles: [],
|
||||
volunteer_ids: [],
|
||||
created_at: '2026-04-01T00:00:00Z',
|
||||
updated_at: '2026-04-01T00:00:00Z',
|
||||
};
|
||||
|
||||
function renderAt(path: string) {
|
||||
return render(
|
||||
<MemoryRouter initialEntries={[path]}>
|
||||
<Schedules />
|
||||
</MemoryRouter>
|
||||
);
|
||||
}
|
||||
|
||||
describe('Schedules (volunteer view)', () => {
|
||||
beforeEach(() => {
|
||||
(useAuth as Mock).mockReturnValue({ role: 'volunteer', volunteerID: 10 });
|
||||
(api.listShifts as Mock).mockResolvedValue([mockPublishedInstance]);
|
||||
});
|
||||
|
||||
it('renders published shifts for a volunteer', async () => {
|
||||
renderAt('/schedules');
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('Morning Shift')).toBeInTheDocument();
|
||||
});
|
||||
expect(screen.getByText('published')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('does not show admin controls', async () => {
|
||||
renderAt('/schedules');
|
||||
await waitFor(() => expect(screen.getByText('Morning Shift')).toBeInTheDocument());
|
||||
expect(screen.queryByText('Generate')).not.toBeInTheDocument();
|
||||
expect(screen.queryByText('Publish')).not.toBeInTheDocument();
|
||||
expect(screen.queryByText('Manage Templates')).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Schedules (admin shifts view)', () => {
|
||||
beforeEach(() => {
|
||||
(useAuth as Mock).mockReturnValue({ role: 'admin', volunteerID: 1 });
|
||||
(api.listShifts as Mock).mockResolvedValue([mockDraftInstance]);
|
||||
(api.listShiftTemplates as Mock).mockResolvedValue([mockTemplate]);
|
||||
});
|
||||
|
||||
it('shows Generate and Publish buttons when drafts exist', async () => {
|
||||
renderAt('/schedules');
|
||||
await waitFor(() => expect(screen.getByText('Morning Shift')).toBeInTheDocument());
|
||||
expect(screen.getByText('Generate')).toBeInTheDocument();
|
||||
expect(screen.getByText('Publish')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('calls generateShifts on Generate click', async () => {
|
||||
(api.generateShifts as Mock).mockResolvedValue([mockDraftInstance]);
|
||||
renderAt('/schedules');
|
||||
await waitFor(() => expect(screen.getByText('Generate')).toBeInTheDocument());
|
||||
fireEvent.click(screen.getByText('Generate'));
|
||||
expect(api.generateShifts).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('calls publishShifts on Publish click', async () => {
|
||||
(api.publishShifts as Mock).mockResolvedValue({ year: 2026, month: 4 });
|
||||
(api.listShifts as Mock)
|
||||
.mockResolvedValueOnce([mockDraftInstance])
|
||||
.mockResolvedValue([{ ...mockDraftInstance, status: 'published' }]);
|
||||
|
||||
renderAt('/schedules');
|
||||
await waitFor(() => expect(screen.getByText('Publish')).toBeInTheDocument());
|
||||
fireEvent.click(screen.getByText('Publish'));
|
||||
expect(api.publishShifts).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('shows Unpublish button when all shifts are published', async () => {
|
||||
(api.listShifts as Mock).mockResolvedValue([mockPublishedInstance]);
|
||||
renderAt('/schedules');
|
||||
await waitFor(() => expect(screen.getByText('Unpublish')).toBeInTheDocument());
|
||||
});
|
||||
|
||||
it('shows Edit button on each shift row', async () => {
|
||||
renderAt('/schedules');
|
||||
await waitFor(() => expect(screen.getByText('Morning Shift')).toBeInTheDocument());
|
||||
expect(screen.getByText('Edit')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('opens edit form with volunteer checkboxes when Edit is clicked', async () => {
|
||||
(api.listVolunteers as Mock).mockResolvedValue([
|
||||
{ id: 5, name: 'Alice', active: true, operational_roles: 'Dog Shelter Volunteer', is_trainee: false },
|
||||
{ id: 6, name: 'Bob', active: true, operational_roles: 'Behaviour Team', is_trainee: false },
|
||||
]);
|
||||
(api.listTimeOff as Mock).mockResolvedValue([]);
|
||||
renderAt('/schedules');
|
||||
await waitFor(() => expect(screen.getByText('Edit')).toBeInTheDocument());
|
||||
fireEvent.click(screen.getByText('Edit'));
|
||||
await waitFor(() => expect(screen.getByText('Alice')).toBeInTheDocument());
|
||||
expect(screen.getByText('Bob')).toBeInTheDocument();
|
||||
expect(screen.getByText(/Edit Shift/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('hides volunteers with approved time off on the shift date', async () => {
|
||||
(api.listVolunteers as Mock).mockResolvedValue([
|
||||
{ id: 5, name: 'Alice', active: true, operational_roles: 'Dog Shelter Volunteer', is_trainee: false },
|
||||
{ id: 6, name: 'Bob', active: true, operational_roles: 'Behaviour Team', is_trainee: false },
|
||||
]);
|
||||
(api.listTimeOff as Mock).mockResolvedValue([
|
||||
{ id: 1, volunteer_id: 6, starts_at: '2026-04-06T00:00:00Z', ends_at: '2026-04-07T00:00:00Z', status: 'approved' },
|
||||
]);
|
||||
renderAt('/schedules');
|
||||
await waitFor(() => expect(screen.getByText('Edit')).toBeInTheDocument());
|
||||
fireEvent.click(screen.getByText('Edit'));
|
||||
await waitFor(() => expect(screen.getByText('Alice')).toBeInTheDocument());
|
||||
// Bob should not appear as a selectable volunteer
|
||||
expect(screen.queryByLabelText('Bob')).not.toBeInTheDocument();
|
||||
// But should be listed as on time off
|
||||
expect(screen.getByText(/On approved time off/)).toBeInTheDocument();
|
||||
expect(screen.getByText(/Bob/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('reads year and month from search params', async () => {
|
||||
renderAt('/schedules?year=2025&month=12');
|
||||
await waitFor(() => expect(api.listShifts).toHaveBeenCalledWith(2025, 12));
|
||||
});
|
||||
});
|
||||
|
||||
describe('Schedules (admin templates view)', () => {
|
||||
beforeEach(() => {
|
||||
(useAuth as Mock).mockReturnValue({ role: 'admin', volunteerID: 1 });
|
||||
(api.listShiftTemplates as Mock).mockResolvedValue([mockTemplate]);
|
||||
});
|
||||
|
||||
it('renders templates at /schedules/templates', async () => {
|
||||
renderAt('/schedules/templates');
|
||||
await waitFor(() => expect(screen.getByText('Shift Templates')).toBeInTheDocument());
|
||||
expect(screen.getByText('Morning Shift')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows template form when New Template is clicked', async () => {
|
||||
renderAt('/schedules/templates');
|
||||
await waitFor(() => expect(screen.getByText('+ New Template')).toBeInTheDocument());
|
||||
fireEvent.click(screen.getByText('+ New Template'));
|
||||
expect(screen.getByText('New Template')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('deletes a template', async () => {
|
||||
(api.deleteShiftTemplate as Mock).mockResolvedValue(undefined);
|
||||
window.confirm = vi.fn().mockReturnValue(true);
|
||||
renderAt('/schedules/templates');
|
||||
await waitFor(() => expect(screen.getAllByText('Delete')[0]).toBeInTheDocument());
|
||||
fireEvent.click(screen.getAllByText('Delete')[0]);
|
||||
expect(api.deleteShiftTemplate).toHaveBeenCalledWith(1);
|
||||
});
|
||||
});
|
||||
@@ -1,106 +1,636 @@
|
||||
import React, { useEffect, useState, FormEvent } from 'react';
|
||||
import { api, Schedule } from '../api';
|
||||
import React, { useEffect, useState, FormEvent, useCallback } from 'react';
|
||||
import { useLocation, useNavigate, useSearchParams } from 'react-router-dom';
|
||||
import {
|
||||
api,
|
||||
ShiftTemplate,
|
||||
ShiftInstance,
|
||||
Volunteer,
|
||||
TimeOffRequest,
|
||||
CreateShiftTemplateInput,
|
||||
TemplateRole,
|
||||
OPERATIONAL_ROLES,
|
||||
} from '../api';
|
||||
import { useAuth } from '../auth';
|
||||
|
||||
const DAY_NAMES = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
|
||||
const MONTH_NAMES = [
|
||||
'January', 'February', 'March', 'April', 'May', 'June',
|
||||
'July', 'August', 'September', 'October', 'November', 'December',
|
||||
];
|
||||
|
||||
function currentYearMonth() {
|
||||
const now = new Date();
|
||||
return { year: now.getFullYear(), month: now.getMonth() + 1 };
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Template form
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function blankTemplate(): CreateShiftTemplateInput {
|
||||
return {
|
||||
name: '',
|
||||
day_of_week: 1,
|
||||
start_time: '09:00:00',
|
||||
end_time: '17:00:00',
|
||||
min_capacity: 1,
|
||||
max_capacity: 5,
|
||||
roles: [],
|
||||
volunteer_ids: [],
|
||||
};
|
||||
}
|
||||
|
||||
interface TemplateFormProps {
|
||||
initial?: Partial<CreateShiftTemplateInput>;
|
||||
onSave: (data: CreateShiftTemplateInput) => Promise<void>;
|
||||
onCancel: () => void;
|
||||
title: string;
|
||||
}
|
||||
|
||||
function TemplateForm({ initial, onSave, onCancel, title }: TemplateFormProps) {
|
||||
const [form, setForm] = useState<CreateShiftTemplateInput>({ ...blankTemplate(), ...initial });
|
||||
const [roleRow, setRoleRow] = useState<TemplateRole>({ role_name: '', count: 1 });
|
||||
const [error, setError] = useState('');
|
||||
const [saving, setSaving] = useState(false);
|
||||
|
||||
async function handleSubmit(e: FormEvent) {
|
||||
e.preventDefault();
|
||||
setError('');
|
||||
setSaving(true);
|
||||
try {
|
||||
await onSave(form);
|
||||
} catch (err: any) {
|
||||
setError(err.message);
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
}
|
||||
|
||||
function addRole() {
|
||||
if (!roleRow.role_name) return;
|
||||
setForm(f => ({ ...f, roles: [...(f.roles ?? []), { ...roleRow }] }));
|
||||
setRoleRow({ role_name: '', count: 1 });
|
||||
}
|
||||
|
||||
function removeRole(idx: number) {
|
||||
setForm(f => ({ ...f, roles: (f.roles ?? []).filter((_, i) => i !== idx) }));
|
||||
}
|
||||
|
||||
return (
|
||||
<form className="card" onSubmit={handleSubmit}>
|
||||
<h3>{title}</h3>
|
||||
{error && <p className="error">{error}</p>}
|
||||
<label>
|
||||
Name
|
||||
<input value={form.name} onChange={e => setForm(f => ({ ...f, name: e.target.value }))} required />
|
||||
</label>
|
||||
<label>
|
||||
Day of Week
|
||||
<select value={form.day_of_week} onChange={e => setForm(f => ({ ...f, day_of_week: Number(e.target.value) }))}>
|
||||
{DAY_NAMES.map((d, i) => <option key={i} value={i}>{d}</option>)}
|
||||
</select>
|
||||
</label>
|
||||
<label>
|
||||
Start Time
|
||||
<input type="time" value={form.start_time.slice(0, 5)}
|
||||
onChange={e => setForm(f => ({ ...f, start_time: e.target.value + ':00' }))} required />
|
||||
</label>
|
||||
<label>
|
||||
End Time
|
||||
<input type="time" value={form.end_time.slice(0, 5)}
|
||||
onChange={e => setForm(f => ({ ...f, end_time: e.target.value + ':00' }))} required />
|
||||
</label>
|
||||
<label>
|
||||
Min Capacity
|
||||
<input type="number" min={1} value={form.min_capacity}
|
||||
onChange={e => setForm(f => ({ ...f, min_capacity: Number(e.target.value) }))} required />
|
||||
</label>
|
||||
<label>
|
||||
Max Capacity
|
||||
<input type="number" min={1} value={form.max_capacity}
|
||||
onChange={e => setForm(f => ({ ...f, max_capacity: Number(e.target.value) }))} required />
|
||||
</label>
|
||||
|
||||
<fieldset>
|
||||
<legend>Role Requirements</legend>
|
||||
{(form.roles ?? []).map((r, i) => (
|
||||
<div key={i} style={{ display: 'flex', gap: '0.5rem', alignItems: 'center', marginBottom: '0.25rem' }}>
|
||||
<span>{r.count}× {r.role_name}</span>
|
||||
<button type="button" className="btn-danger btn-small" onClick={() => removeRole(i)}>Remove</button>
|
||||
</div>
|
||||
))}
|
||||
<div style={{ display: 'flex', gap: '0.5rem', alignItems: 'flex-end' }}>
|
||||
<label style={{ flex: 1 }}>
|
||||
Role
|
||||
<select value={roleRow.role_name} onChange={e => setRoleRow(r => ({ ...r, role_name: e.target.value }))}>
|
||||
<option value="">Select role…</option>
|
||||
{OPERATIONAL_ROLES.map(r => <option key={r} value={r}>{r}</option>)}
|
||||
</select>
|
||||
</label>
|
||||
<label>
|
||||
Count
|
||||
<input type="number" min={1} value={roleRow.count} style={{ width: '4rem' }}
|
||||
onChange={e => setRoleRow(r => ({ ...r, count: Number(e.target.value) }))} />
|
||||
</label>
|
||||
<button type="button" onClick={addRole}>Add Role</button>
|
||||
</div>
|
||||
</fieldset>
|
||||
|
||||
<div style={{ display: 'flex', gap: '0.5rem', marginTop: '1rem' }}>
|
||||
<button type="submit" disabled={saving}>{saving ? 'Saving…' : 'Save'}</button>
|
||||
<button type="button" onClick={onCancel}>Cancel</button>
|
||||
</div>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Shift instance edit form
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
interface ShiftEditFormProps {
|
||||
instance: ShiftInstance;
|
||||
templateId: number | undefined;
|
||||
onSave: (inst: ShiftInstance) => void;
|
||||
onCancel: () => void;
|
||||
}
|
||||
|
||||
function ShiftEditForm({ instance, templateId, onSave, onCancel }: ShiftEditFormProps) {
|
||||
const [volunteers, setVolunteers] = useState<Volunteer[]>([]);
|
||||
const [templateRoles, setTemplateRoles] = useState<TemplateRole[]>([]);
|
||||
const [unavailableIds, setUnavailableIds] = useState<Set<number>>(new Set());
|
||||
const [selectedIds, setSelectedIds] = useState<Set<number>>(
|
||||
new Set(instance.volunteers.map(v => v.volunteer_id))
|
||||
);
|
||||
const [minCap, setMinCap] = useState(instance.min_capacity);
|
||||
const [maxCap, setMaxCap] = useState(instance.max_capacity);
|
||||
const [error, setError] = useState('');
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
const loads: Promise<void>[] = [
|
||||
api.listVolunteers().then((vols) => setVolunteers(vols as Volunteer[])),
|
||||
api.listTimeOff().then((requests: TimeOffRequest[]) => {
|
||||
const shiftDate = new Date(instance.date + 'T00:00:00');
|
||||
const off = new Set<number>();
|
||||
for (const r of requests) {
|
||||
if (r.status !== 'approved') continue;
|
||||
const start = new Date(r.starts_at);
|
||||
const end = new Date(r.ends_at);
|
||||
// Shift date falls within the approved time-off range
|
||||
if (shiftDate >= new Date(start.toDateString()) && shiftDate <= new Date(end.toDateString())) {
|
||||
off.add(r.volunteer_id);
|
||||
}
|
||||
}
|
||||
setUnavailableIds(off);
|
||||
}),
|
||||
];
|
||||
if (templateId) {
|
||||
loads.push(
|
||||
api.listShiftTemplates().then((tmpls) => {
|
||||
const tmpl = tmpls.find(t => t.id === templateId);
|
||||
if (tmpl) setTemplateRoles(tmpl.roles ?? []);
|
||||
})
|
||||
);
|
||||
}
|
||||
Promise.all(loads).finally(() => setLoading(false));
|
||||
}, [templateId, instance.date]);
|
||||
|
||||
function toggleVolunteer(id: number) {
|
||||
setSelectedIds(prev => {
|
||||
const next = new Set(prev);
|
||||
if (next.has(id)) next.delete(id);
|
||||
else next.add(id);
|
||||
return next;
|
||||
});
|
||||
}
|
||||
|
||||
async function handleSubmit(e: FormEvent) {
|
||||
e.preventDefault();
|
||||
setError('');
|
||||
setSaving(true);
|
||||
try {
|
||||
const updated = await api.updateShift(instance.id, {
|
||||
volunteer_ids: Array.from(selectedIds),
|
||||
min_capacity: minCap,
|
||||
max_capacity: maxCap,
|
||||
});
|
||||
onSave(updated);
|
||||
} catch (err: any) {
|
||||
setError(err.message);
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
}
|
||||
|
||||
// Group active, available volunteers by their operational roles for display
|
||||
const activeVolunteers = volunteers.filter(v => v.active && !unavailableIds.has(v.id));
|
||||
const onTimeOff = volunteers.filter(v => v.active && unavailableIds.has(v.id));
|
||||
|
||||
// Build a map of role → volunteers who hold that role
|
||||
const byRole = new Map<string, Volunteer[]>();
|
||||
for (const v of activeVolunteers) {
|
||||
const roles = v.operational_roles
|
||||
? v.operational_roles.split(',').map(r => r.trim()).filter(Boolean)
|
||||
: [];
|
||||
if (roles.length === 0) {
|
||||
const list = byRole.get('Unassigned') ?? [];
|
||||
list.push(v);
|
||||
byRole.set('Unassigned', list);
|
||||
} else {
|
||||
for (const r of roles) {
|
||||
const list = byRole.get(r) ?? [];
|
||||
list.push(v);
|
||||
byRole.set(r, list);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Order sections: template roles first, then any remaining
|
||||
const roleOrder: string[] = [];
|
||||
for (const tr of templateRoles) {
|
||||
if (!roleOrder.includes(tr.role_name)) roleOrder.push(tr.role_name);
|
||||
}
|
||||
byRole.forEach((_, key) => {
|
||||
if (!roleOrder.includes(key)) roleOrder.push(key);
|
||||
});
|
||||
|
||||
if (loading) return <div className="card"><p>Loading volunteers…</p></div>;
|
||||
|
||||
return (
|
||||
<form className="card" onSubmit={handleSubmit}>
|
||||
<h3>Edit Shift: {instance.name} — {instance.date}</h3>
|
||||
{error && <p className="error">{error}</p>}
|
||||
|
||||
{templateRoles.length > 0 && (
|
||||
<p style={{ marginBottom: '0.5rem', color: '#666' }}>
|
||||
<strong>Required:</strong>{' '}
|
||||
{templateRoles.map(r => `${r.count}× ${r.role_name}`).join(', ')}
|
||||
</p>
|
||||
)}
|
||||
|
||||
<fieldset>
|
||||
<legend>Volunteers ({selectedIds.size} selected)</legend>
|
||||
{roleOrder.map(roleName => {
|
||||
const vols = byRole.get(roleName);
|
||||
if (!vols || vols.length === 0) return null;
|
||||
const required = templateRoles.find(r => r.role_name === roleName);
|
||||
const selectedInRole = vols.filter(v => selectedIds.has(v.id)).length;
|
||||
return (
|
||||
<div key={roleName} style={{ marginBottom: '0.75rem' }}>
|
||||
<strong>
|
||||
{roleName}
|
||||
{required && (
|
||||
<span style={{ fontWeight: 'normal', color: selectedInRole >= required.count ? '#2a7' : '#c55' }}>
|
||||
{' '}({selectedInRole}/{required.count})
|
||||
</span>
|
||||
)}
|
||||
</strong>
|
||||
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(200px, 1fr))', gap: '0.25rem', marginTop: '0.25rem' }}>
|
||||
{vols.map(v => (
|
||||
<label key={v.id} style={{ display: 'flex', alignItems: 'center', gap: '0.5rem', cursor: 'pointer' }}>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={selectedIds.has(v.id)}
|
||||
onChange={() => toggleVolunteer(v.id)}
|
||||
/>
|
||||
<span>{v.name}{v.is_trainee ? ' (trainee)' : ''}</span>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</fieldset>
|
||||
|
||||
{onTimeOff.length > 0 && (
|
||||
<p style={{ marginTop: '0.5rem', color: '#999', fontSize: '0.9em' }}>
|
||||
<strong>On approved time off:</strong>{' '}
|
||||
{onTimeOff.map(v => v.name).join(', ')}
|
||||
</p>
|
||||
)}
|
||||
|
||||
<div style={{ display: 'flex', gap: '1rem', marginTop: '0.5rem' }}>
|
||||
<label>
|
||||
Min Capacity
|
||||
<input type="number" min={1} value={minCap} style={{ width: '5rem' }}
|
||||
onChange={e => setMinCap(Number(e.target.value))} />
|
||||
</label>
|
||||
<label>
|
||||
Max Capacity
|
||||
<input type="number" min={1} value={maxCap} style={{ width: '5rem' }}
|
||||
onChange={e => setMaxCap(Number(e.target.value))} />
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div style={{ display: 'flex', gap: '0.5rem', marginTop: '1rem' }}>
|
||||
<button type="submit" disabled={saving}>{saving ? 'Saving…' : 'Save'}</button>
|
||||
<button type="button" onClick={onCancel}>Cancel</button>
|
||||
</div>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Main page
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export default function Schedules() {
|
||||
const { role } = useAuth();
|
||||
const [schedules, setSchedules] = useState<Schedule[]>([]);
|
||||
const navigate = useNavigate();
|
||||
const location = useLocation();
|
||||
const [searchParams] = useSearchParams();
|
||||
|
||||
// Derive view from URL path
|
||||
const isTemplatesView = location.pathname === '/schedules/templates';
|
||||
|
||||
// Derive year/month from search params (shifts view only)
|
||||
const init = currentYearMonth();
|
||||
const year = Number(searchParams.get('year')) || init.year;
|
||||
const month = Number(searchParams.get('month')) || init.month;
|
||||
|
||||
// Data
|
||||
const [instances, setInstances] = useState<ShiftInstance[]>([]);
|
||||
const [templates, setTemplates] = useState<ShiftTemplate[]>([]);
|
||||
const [error, setError] = useState('');
|
||||
const [showForm, setShowForm] = useState(false);
|
||||
const [form, setForm] = useState({ title: '', starts_at: '', ends_at: '', notes: '' });
|
||||
|
||||
// UI state
|
||||
const [showTemplateForm, setShowTemplateForm] = useState(false);
|
||||
const [editingTemplate, setEditingTemplate] = useState<ShiftTemplate | null>(null);
|
||||
const [editingInstance, setEditingInstance] = useState<ShiftInstance | null>(null);
|
||||
|
||||
// Navigation helpers
|
||||
const goToShifts = useCallback((y: number, m: number) => {
|
||||
navigate(`/schedules?year=${y}&month=${m}`);
|
||||
}, [navigate]);
|
||||
|
||||
const goToTemplates = useCallback(() => {
|
||||
navigate('/schedules/templates');
|
||||
}, [navigate]);
|
||||
|
||||
useEffect(() => {
|
||||
api.listSchedules().then(setSchedules).catch(() => setError('Could not load schedules.'));
|
||||
}, []);
|
||||
if (isTemplatesView) {
|
||||
api.listShiftTemplates()
|
||||
.then(setTemplates)
|
||||
.catch(() => setError('Could not load templates.'));
|
||||
} else {
|
||||
api.listShifts(year, month)
|
||||
.then(setInstances)
|
||||
.catch(() => setError('Could not load shifts.'));
|
||||
}
|
||||
}, [isTemplatesView, year, month]);
|
||||
|
||||
async function handleCreate(e: FormEvent) {
|
||||
e.preventDefault();
|
||||
function prevMonth() {
|
||||
const m = month === 1 ? 12 : month - 1;
|
||||
const y = month === 1 ? year - 1 : year;
|
||||
goToShifts(y, m);
|
||||
}
|
||||
|
||||
function nextMonth() {
|
||||
const m = month === 12 ? 1 : month + 1;
|
||||
const y = month === 12 ? year + 1 : year;
|
||||
goToShifts(y, m);
|
||||
}
|
||||
|
||||
async function handleGenerate() {
|
||||
setError('');
|
||||
try {
|
||||
const sc = await api.createSchedule(form);
|
||||
setSchedules(prev => [...prev, sc]);
|
||||
setForm({ title: '', starts_at: '', ends_at: '', notes: '' });
|
||||
setShowForm(false);
|
||||
const newInstances = await api.generateShifts(year, month);
|
||||
setInstances(newInstances);
|
||||
} catch (err: any) {
|
||||
setError(err.message);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleDelete(id: number) {
|
||||
if (!window.confirm('Delete this schedule?')) return;
|
||||
async function handlePublish() {
|
||||
setError('');
|
||||
try {
|
||||
await api.deleteSchedule(id);
|
||||
setSchedules(prev => prev.filter(s => s.id !== id));
|
||||
await api.publishShifts(year, month);
|
||||
const updated = await api.listShifts(year, month);
|
||||
setInstances(updated);
|
||||
} catch (err: any) {
|
||||
setError(err.message);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleUnpublish() {
|
||||
if (!window.confirm(`Unpublish the ${MONTH_NAMES[month - 1]} ${year} schedule?`)) return;
|
||||
setError('');
|
||||
try {
|
||||
await api.unpublishShifts(year, month);
|
||||
const updated = await api.listShifts(year, month);
|
||||
setInstances(updated);
|
||||
} catch (err: any) {
|
||||
setError(err.message);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleConfirm(id: number) {
|
||||
setError('');
|
||||
try {
|
||||
await api.confirmShift(id);
|
||||
const updated = await api.listShifts(year, month);
|
||||
setInstances(updated);
|
||||
} catch (err: any) {
|
||||
setError(err.message);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleCreateTemplate(data: CreateShiftTemplateInput) {
|
||||
const t = await api.createShiftTemplate(data);
|
||||
setTemplates(prev => [...prev, t]);
|
||||
setShowTemplateForm(false);
|
||||
}
|
||||
|
||||
async function handleUpdateTemplate(data: CreateShiftTemplateInput) {
|
||||
if (!editingTemplate) return;
|
||||
const t = await api.updateShiftTemplate(editingTemplate.id, data);
|
||||
setTemplates(prev => prev.map(x => (x.id === t.id ? t : x)));
|
||||
setEditingTemplate(null);
|
||||
}
|
||||
|
||||
async function handleDeleteTemplate(id: number) {
|
||||
if (!window.confirm('Delete this template? Existing shifts will not be affected.')) return;
|
||||
setError('');
|
||||
try {
|
||||
await api.deleteShiftTemplate(id);
|
||||
setTemplates(prev => prev.filter(t => t.id !== id));
|
||||
} catch (err: any) {
|
||||
setError(err.message);
|
||||
}
|
||||
}
|
||||
|
||||
function handleInstanceSaved(updated: ShiftInstance) {
|
||||
setInstances(prev => prev.map(i => (i.id === updated.id ? updated : i)));
|
||||
setEditingInstance(null);
|
||||
}
|
||||
|
||||
const allPublished = instances.length > 0 && instances.every(i => i.status === 'published');
|
||||
const hasDraft = instances.some(i => i.status === 'draft');
|
||||
|
||||
return (
|
||||
<div className="page">
|
||||
<div className="page-header">
|
||||
<h2>Schedules</h2>
|
||||
{role === 'admin' && (
|
||||
<button onClick={() => setShowForm(v => !v)}>
|
||||
{showForm ? 'Cancel' : 'Add Shift'}
|
||||
<div style={{ display: 'flex', gap: '0.5rem' }}>
|
||||
<button onClick={() => isTemplatesView ? goToShifts(year, month) : goToTemplates()}>
|
||||
{isTemplatesView ? 'View Shifts' : 'Manage Templates'}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{error && <p className="error">{error}</p>}
|
||||
|
||||
{showForm && (
|
||||
<form className="card" onSubmit={handleCreate}>
|
||||
<h3>New Shift</h3>
|
||||
<label>
|
||||
Title
|
||||
<input value={form.title} onChange={e => setForm(f => ({ ...f, title: e.target.value }))} required />
|
||||
</label>
|
||||
<label>
|
||||
Starts At
|
||||
<input type="datetime-local" value={form.starts_at} onChange={e => setForm(f => ({ ...f, starts_at: e.target.value }))} required />
|
||||
</label>
|
||||
<label>
|
||||
Ends At
|
||||
<input type="datetime-local" value={form.ends_at} onChange={e => setForm(f => ({ ...f, ends_at: e.target.value }))} required />
|
||||
</label>
|
||||
<label>
|
||||
Notes
|
||||
<textarea value={form.notes} onChange={e => setForm(f => ({ ...f, notes: e.target.value }))} />
|
||||
</label>
|
||||
<button type="submit">Create</button>
|
||||
</form>
|
||||
{/* ---- Templates view ---- */}
|
||||
{isTemplatesView && role === 'admin' && (
|
||||
<>
|
||||
<div className="page-header" style={{ marginBottom: '1rem' }}>
|
||||
<h3>Shift Templates</h3>
|
||||
<button onClick={() => { setShowTemplateForm(true); setEditingTemplate(null); }}>
|
||||
+ New Template
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{showTemplateForm && !editingTemplate && (
|
||||
<TemplateForm
|
||||
title="New Template"
|
||||
onSave={handleCreateTemplate}
|
||||
onCancel={() => setShowTemplateForm(false)}
|
||||
/>
|
||||
)}
|
||||
|
||||
{schedules.length === 0 ? (
|
||||
<p>No schedules found.</p>
|
||||
{editingTemplate && (
|
||||
<TemplateForm
|
||||
title={`Edit: ${editingTemplate.name}`}
|
||||
initial={editingTemplate}
|
||||
onSave={handleUpdateTemplate}
|
||||
onCancel={() => setEditingTemplate(null)}
|
||||
/>
|
||||
)}
|
||||
|
||||
{templates.length === 0 ? (
|
||||
<p>No templates yet.</p>
|
||||
) : (
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Title</th>
|
||||
<th>Starts</th>
|
||||
<th>Ends</th>
|
||||
<th>Notes</th>
|
||||
{role === 'admin' && <th>Actions</th>}
|
||||
<th>Name</th>
|
||||
<th>Day</th>
|
||||
<th>Time</th>
|
||||
<th>Capacity</th>
|
||||
<th>Roles</th>
|
||||
<th>Actions</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{schedules.map(s => (
|
||||
<tr key={s.id}>
|
||||
<td>{s.title}</td>
|
||||
<td>{new Date(s.starts_at).toLocaleString()}</td>
|
||||
<td>{new Date(s.ends_at).toLocaleString()}</td>
|
||||
<td>{s.notes ?? '—'}</td>
|
||||
{role === 'admin' && (
|
||||
{templates.map(t => (
|
||||
<tr key={t.id}>
|
||||
<td>{t.name}</td>
|
||||
<td>{DAY_NAMES[t.day_of_week]}</td>
|
||||
<td>{t.start_time.slice(0, 5)}–{t.end_time.slice(0, 5)}</td>
|
||||
<td>{t.min_capacity}–{t.max_capacity}</td>
|
||||
<td>{(t.roles ?? []).map(r => `${r.count}× ${r.role_name}`).join(', ') || '—'}</td>
|
||||
<td>
|
||||
<button className="btn-danger btn-small" onClick={() => handleDelete(s.id)}>Delete</button>
|
||||
<button className="btn-small" onClick={() => { setEditingTemplate(t); setShowTemplateForm(false); }}>Edit</button>
|
||||
{' '}
|
||||
<button className="btn-danger btn-small" onClick={() => handleDeleteTemplate(t.id)}>Delete</button>
|
||||
</td>
|
||||
)}
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* ---- Shifts view ---- */}
|
||||
{!isTemplatesView && (
|
||||
<>
|
||||
{/* Month navigation */}
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: '1rem', marginBottom: '1rem' }}>
|
||||
<button onClick={prevMonth}>‹</button>
|
||||
<strong>{MONTH_NAMES[month - 1]} {year}</strong>
|
||||
<button onClick={nextMonth}>›</button>
|
||||
|
||||
{role === 'admin' && (
|
||||
<div style={{ display: 'flex', gap: '0.5rem', marginLeft: 'auto' }}>
|
||||
<button onClick={handleGenerate}>Generate</button>
|
||||
{hasDraft && <button onClick={handlePublish}>Publish</button>}
|
||||
{allPublished && (
|
||||
<button className="btn-danger" onClick={handleUnpublish}>Unpublish</button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Instance edit form */}
|
||||
{editingInstance && (
|
||||
<ShiftEditForm
|
||||
instance={editingInstance}
|
||||
templateId={editingInstance.template_id}
|
||||
onSave={handleInstanceSaved}
|
||||
onCancel={() => setEditingInstance(null)}
|
||||
/>
|
||||
)}
|
||||
|
||||
{instances.length === 0 ? (
|
||||
<p>No shifts for {MONTH_NAMES[month - 1]} {year}.{role === 'admin' && ' Use Generate to create shifts from templates.'}</p>
|
||||
) : (
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Date</th>
|
||||
<th>Shift</th>
|
||||
<th>Time</th>
|
||||
<th>Status</th>
|
||||
<th>Volunteers</th>
|
||||
<th>Capacity</th>
|
||||
{role === 'admin' && <th>Actions</th>}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{instances.map(inst => {
|
||||
const confirmed = inst.volunteers.some(v => v.confirmed);
|
||||
return (
|
||||
<tr key={inst.id}>
|
||||
<td>{inst.date}</td>
|
||||
<td>{inst.name}</td>
|
||||
<td>{inst.start_time.slice(0, 5)}–{inst.end_time.slice(0, 5)}</td>
|
||||
<td>
|
||||
<span className={inst.status === 'published' ? 'badge-success' : 'badge-neutral'}>
|
||||
{inst.status}
|
||||
</span>
|
||||
</td>
|
||||
<td>
|
||||
{inst.volunteers.length === 0 ? '—' : inst.volunteers.map(v => (
|
||||
<span key={v.volunteer_id} title={v.confirmed ? 'Confirmed' : 'Unconfirmed'}>
|
||||
{v.name}{v.confirmed ? ' ✓' : ' ⚠'}
|
||||
{' '}
|
||||
</span>
|
||||
))}
|
||||
</td>
|
||||
<td>{inst.volunteers.length}/{inst.max_capacity}</td>
|
||||
{role === 'admin' && (
|
||||
<td>
|
||||
<button className="btn-small" onClick={() => setEditingInstance(inst)}>Edit</button>
|
||||
</td>
|
||||
)}
|
||||
{role !== 'admin' && inst.status === 'published' && !confirmed && (
|
||||
<td>
|
||||
<button className="btn-small" onClick={() => handleConfirm(inst.id)}>Confirm</button>
|
||||
</td>
|
||||
)}
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
105
web/src/pages/Setup.test.tsx
Normal file
105
web/src/pages/Setup.test.tsx
Normal file
@@ -0,0 +1,105 @@
|
||||
import React from 'react';
|
||||
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
|
||||
import { vi, type Mock } from 'vitest';
|
||||
import { MemoryRouter, Route, Routes } from 'react-router-dom';
|
||||
import Setup from './Setup';
|
||||
import { api } from '../api';
|
||||
import { AuthProvider } from '../auth';
|
||||
|
||||
vi.mock('../api', () => ({
|
||||
api: {
|
||||
getSetupStatus: vi.fn(),
|
||||
createSetupAdmin: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
// Mock useSetup from App to provide setNeedsSetup
|
||||
const mockSetNeedsSetup = vi.fn();
|
||||
vi.mock('../App', () => ({
|
||||
useSetup: () => ({ setNeedsSetup: mockSetNeedsSetup }),
|
||||
}));
|
||||
|
||||
const mockCreateSetupAdmin = api.createSetupAdmin as Mock;
|
||||
|
||||
function renderSetup() {
|
||||
return render(
|
||||
<AuthProvider>
|
||||
<MemoryRouter initialEntries={['/setup']}>
|
||||
<Routes>
|
||||
<Route path="/setup" element={<Setup />} />
|
||||
<Route path="/" element={<div>Dashboard</div>} />
|
||||
</Routes>
|
||||
</MemoryRouter>
|
||||
</AuthProvider>,
|
||||
);
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
mockCreateSetupAdmin.mockReset();
|
||||
mockSetNeedsSetup.mockReset();
|
||||
});
|
||||
|
||||
test('renders all form fields', () => {
|
||||
renderSetup();
|
||||
expect(screen.getByLabelText(/name/i)).toBeInTheDocument();
|
||||
expect(screen.getByLabelText(/email/i)).toBeInTheDocument();
|
||||
expect(screen.getByLabelText(/^password$/i)).toBeInTheDocument();
|
||||
expect(screen.getByLabelText(/confirm password/i)).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: /create admin account/i })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
test('shows error when passwords do not match', async () => {
|
||||
renderSetup();
|
||||
fireEvent.change(screen.getByLabelText(/name/i), { target: { value: 'Admin' } });
|
||||
fireEvent.change(screen.getByLabelText(/email/i), { target: { value: 'admin@example.com' } });
|
||||
fireEvent.change(screen.getByLabelText(/^password$/i), { target: { value: 'password1' } });
|
||||
fireEvent.change(screen.getByLabelText(/confirm password/i), { target: { value: 'password2' } });
|
||||
fireEvent.click(screen.getByRole('button', { name: /create admin account/i }));
|
||||
expect(await screen.findByText(/passwords do not match/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
test('shows error when password too short', async () => {
|
||||
renderSetup();
|
||||
fireEvent.change(screen.getByLabelText(/name/i), { target: { value: 'Admin' } });
|
||||
fireEvent.change(screen.getByLabelText(/email/i), { target: { value: 'admin@example.com' } });
|
||||
fireEvent.change(screen.getByLabelText(/^password$/i), { target: { value: 'short' } });
|
||||
fireEvent.change(screen.getByLabelText(/confirm password/i), { target: { value: 'short' } });
|
||||
fireEvent.click(screen.getByRole('button', { name: /create admin account/i }));
|
||||
expect(await screen.findByText(/at least 8 characters/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
test('calls api.createSetupAdmin and navigates on success', async () => {
|
||||
mockCreateSetupAdmin.mockResolvedValueOnce({ token: 'jwt-token' });
|
||||
renderSetup();
|
||||
|
||||
fireEvent.change(screen.getByLabelText(/name/i), { target: { value: 'Admin' } });
|
||||
fireEvent.change(screen.getByLabelText(/email/i), { target: { value: 'admin@example.com' } });
|
||||
fireEvent.change(screen.getByLabelText(/^password$/i), { target: { value: 'goodpassword' } });
|
||||
fireEvent.change(screen.getByLabelText(/confirm password/i), { target: { value: 'goodpassword' } });
|
||||
fireEvent.click(screen.getByRole('button', { name: /create admin account/i }));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockCreateSetupAdmin).toHaveBeenCalledWith({
|
||||
name: 'Admin',
|
||||
email: 'admin@example.com',
|
||||
password: 'goodpassword',
|
||||
});
|
||||
});
|
||||
await waitFor(() => {
|
||||
expect(mockSetNeedsSetup).toHaveBeenCalledWith(false);
|
||||
});
|
||||
expect(await screen.findByText(/dashboard/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
test('shows error when API returns failure', async () => {
|
||||
mockCreateSetupAdmin.mockRejectedValueOnce(new Error('setup already completed'));
|
||||
renderSetup();
|
||||
|
||||
fireEvent.change(screen.getByLabelText(/name/i), { target: { value: 'Admin' } });
|
||||
fireEvent.change(screen.getByLabelText(/email/i), { target: { value: 'admin@example.com' } });
|
||||
fireEvent.change(screen.getByLabelText(/^password$/i), { target: { value: 'goodpassword' } });
|
||||
fireEvent.change(screen.getByLabelText(/confirm password/i), { target: { value: 'goodpassword' } });
|
||||
fireEvent.click(screen.getByRole('button', { name: /create admin account/i }));
|
||||
|
||||
expect(await screen.findByText(/setup already completed/i)).toBeInTheDocument();
|
||||
});
|
||||
77
web/src/pages/Setup.tsx
Normal file
77
web/src/pages/Setup.tsx
Normal file
@@ -0,0 +1,77 @@
|
||||
import React, { useState, FormEvent } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { api } from '../api';
|
||||
import { useAuth } from '../auth';
|
||||
import { useSetup } from '../App';
|
||||
|
||||
export default function Setup() {
|
||||
const { login } = useAuth();
|
||||
const { setNeedsSetup } = useSetup();
|
||||
const navigate = useNavigate();
|
||||
const [name, setName] = useState('');
|
||||
const [email, setEmail] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
const [confirm, setConfirm] = useState('');
|
||||
const [error, setError] = useState('');
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
|
||||
async function handleSubmit(e: FormEvent) {
|
||||
e.preventDefault();
|
||||
setError('');
|
||||
|
||||
if (!name || !email || !password) {
|
||||
setError('All fields are required');
|
||||
return;
|
||||
}
|
||||
if (password.length < 8) {
|
||||
setError('Password must be at least 8 characters');
|
||||
return;
|
||||
}
|
||||
if (password !== confirm) {
|
||||
setError('Passwords do not match');
|
||||
return;
|
||||
}
|
||||
|
||||
setSubmitting(true);
|
||||
try {
|
||||
const { token } = await api.createSetupAdmin({ name, email, password });
|
||||
login(token);
|
||||
setNeedsSetup(false);
|
||||
navigate('/');
|
||||
} catch (err: any) {
|
||||
setError(err.message);
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="auth-page">
|
||||
<h1>Walkies</h1>
|
||||
<h2>Initial Setup</h2>
|
||||
<p>Create the first admin account to get started.</p>
|
||||
<form onSubmit={handleSubmit}>
|
||||
{error && <p className="error">{error}</p>}
|
||||
<label>
|
||||
Name
|
||||
<input type="text" value={name} onChange={e => setName(e.target.value)} required />
|
||||
</label>
|
||||
<label>
|
||||
Email
|
||||
<input type="email" value={email} onChange={e => setEmail(e.target.value)} required />
|
||||
</label>
|
||||
<label>
|
||||
Password
|
||||
<input type="password" value={password} onChange={e => setPassword(e.target.value)} required />
|
||||
</label>
|
||||
<label>
|
||||
Confirm Password
|
||||
<input type="password" value={confirm} onChange={e => setConfirm(e.target.value)} required />
|
||||
</label>
|
||||
<button type="submit" disabled={submitting}>
|
||||
{submitting ? 'Creating...' : 'Create Admin Account'}
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
236
web/src/pages/TimeOff.test.tsx
Normal file
236
web/src/pages/TimeOff.test.tsx
Normal file
@@ -0,0 +1,236 @@
|
||||
import React from 'react';
|
||||
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
|
||||
import { vi, type Mock } from 'vitest';
|
||||
import { MemoryRouter } from 'react-router-dom';
|
||||
import TimeOff from './TimeOff';
|
||||
import { api, TimeOffRequest, ApiError } from '../api';
|
||||
import { AuthProvider } from '../auth';
|
||||
|
||||
vi.mock('../api', () => {
|
||||
class MockApiError extends Error {
|
||||
status: number;
|
||||
data: any;
|
||||
constructor(message: string, status: number, data: any) {
|
||||
super(message);
|
||||
this.status = status;
|
||||
this.data = data;
|
||||
}
|
||||
}
|
||||
return {
|
||||
api: {
|
||||
listTimeOff: vi.fn(),
|
||||
createTimeOff: vi.fn(),
|
||||
updateTimeOff: vi.fn(),
|
||||
deleteTimeOff: vi.fn(),
|
||||
reviewTimeOff: vi.fn(),
|
||||
getRemovedShifts: vi.fn(),
|
||||
listVolunteers: vi.fn(),
|
||||
},
|
||||
ApiError: MockApiError,
|
||||
};
|
||||
});
|
||||
|
||||
const mockListTimeOff = api.listTimeOff as Mock;
|
||||
const mockCreateTimeOff = api.createTimeOff as Mock;
|
||||
const mockDeleteTimeOff = api.deleteTimeOff as Mock;
|
||||
const mockReviewTimeOff = api.reviewTimeOff as Mock;
|
||||
const mockGetRemovedShifts = api.getRemovedShifts as Mock;
|
||||
const mockListVolunteers = api.listVolunteers as Mock;
|
||||
|
||||
function buildFakeJWT(payload: object): string {
|
||||
const header = btoa(JSON.stringify({ alg: 'HS256', typ: 'JWT' }));
|
||||
const body = btoa(JSON.stringify(payload));
|
||||
return `${header}.${body}.fakesig`;
|
||||
}
|
||||
|
||||
const ADMIN_TOKEN = buildFakeJWT({ volunteer_id: 1, role: 'admin', exp: 9999999999 });
|
||||
const VOL_TOKEN = buildFakeJWT({ volunteer_id: 10, role: 'volunteer', exp: 9999999999 });
|
||||
|
||||
const futureRequest: TimeOffRequest = {
|
||||
id: 1,
|
||||
volunteer_id: 10,
|
||||
starts_at: '2026-06-01T00:00:00Z',
|
||||
ends_at: '2026-06-03T00:00:00Z',
|
||||
reason: 'vacation',
|
||||
status: 'approved',
|
||||
created_at: '2026-04-01T00:00:00Z',
|
||||
updated_at: '2026-04-01T00:00:00Z',
|
||||
};
|
||||
|
||||
const pastRequest: TimeOffRequest = {
|
||||
id: 2,
|
||||
volunteer_id: 10,
|
||||
starts_at: '2020-01-01T00:00:00Z',
|
||||
ends_at: '2020-01-03T00:00:00Z',
|
||||
reason: 'sick',
|
||||
status: 'approved',
|
||||
created_at: '2020-01-01T00:00:00Z',
|
||||
updated_at: '2020-01-01T00:00:00Z',
|
||||
};
|
||||
|
||||
function renderAsVolunteer() {
|
||||
localStorage.setItem('token', VOL_TOKEN);
|
||||
return render(
|
||||
<AuthProvider>
|
||||
<MemoryRouter>
|
||||
<TimeOff />
|
||||
</MemoryRouter>
|
||||
</AuthProvider>,
|
||||
);
|
||||
}
|
||||
|
||||
function renderAsAdmin() {
|
||||
localStorage.setItem('token', ADMIN_TOKEN);
|
||||
return render(
|
||||
<AuthProvider>
|
||||
<MemoryRouter>
|
||||
<TimeOff />
|
||||
</MemoryRouter>
|
||||
</AuthProvider>,
|
||||
);
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
localStorage.clear();
|
||||
mockListVolunteers.mockResolvedValue([]);
|
||||
});
|
||||
|
||||
describe('TimeOff page', () => {
|
||||
it('renders empty state', async () => {
|
||||
mockListTimeOff.mockResolvedValue([]);
|
||||
renderAsVolunteer();
|
||||
await waitFor(() => expect(screen.getByText('No time off requests.')).toBeInTheDocument());
|
||||
});
|
||||
|
||||
it('renders request list for volunteer', async () => {
|
||||
mockListTimeOff.mockResolvedValue([futureRequest]);
|
||||
renderAsVolunteer();
|
||||
await waitFor(() => expect(screen.getByText('vacation')).toBeInTheDocument());
|
||||
expect(screen.getByText('approved')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows edit and delete buttons for own future time off', async () => {
|
||||
mockListTimeOff.mockResolvedValue([futureRequest]);
|
||||
renderAsVolunteer();
|
||||
await waitFor(() => expect(screen.getByText('Edit')).toBeInTheDocument());
|
||||
expect(screen.getByText('Delete')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('does not show edit/delete for past time off as volunteer', async () => {
|
||||
mockListTimeOff.mockResolvedValue([pastRequest]);
|
||||
renderAsVolunteer();
|
||||
await waitFor(() => expect(screen.getByText('sick')).toBeInTheDocument());
|
||||
expect(screen.queryByText('Edit')).not.toBeInTheDocument();
|
||||
expect(screen.queryByText('Delete')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows create form when button clicked', async () => {
|
||||
mockListTimeOff.mockResolvedValue([]);
|
||||
renderAsVolunteer();
|
||||
await waitFor(() => expect(screen.getByText('Request Time Off')).toBeInTheDocument());
|
||||
fireEvent.click(screen.getByText('Request Time Off'));
|
||||
expect(screen.getByText('New Request')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('creates time off request successfully', async () => {
|
||||
mockListTimeOff.mockResolvedValue([]);
|
||||
mockCreateTimeOff.mockResolvedValue(futureRequest);
|
||||
renderAsVolunteer();
|
||||
|
||||
fireEvent.click(screen.getByText('Request Time Off'));
|
||||
fireEvent.change(screen.getByLabelText('From'), { target: { value: '2026-06-01' } });
|
||||
fireEvent.change(screen.getByLabelText('To'), { target: { value: '2026-06-03' } });
|
||||
fireEvent.click(screen.getByText('Submit'));
|
||||
|
||||
await waitFor(() => expect(mockCreateTimeOff).toHaveBeenCalled());
|
||||
});
|
||||
|
||||
it('shows conflict warning on 409 and allows confirmation', async () => {
|
||||
mockListTimeOff.mockResolvedValue([]);
|
||||
const { ApiError: MockApiError } = await vi.importMock<typeof import('../api')>('../api');
|
||||
mockCreateTimeOff
|
||||
.mockRejectedValueOnce(
|
||||
new (MockApiError as any)('conflict', 409, {
|
||||
message: 'Time off conflicts with assigned shifts.',
|
||||
conflicts: [
|
||||
{ instance_id: 100, name: 'Morning Walk', date: '2026-06-01', start_time: '08:00', end_time: '12:00' },
|
||||
],
|
||||
}),
|
||||
)
|
||||
.mockResolvedValueOnce(futureRequest);
|
||||
|
||||
renderAsVolunteer();
|
||||
fireEvent.click(screen.getByText('Request Time Off'));
|
||||
fireEvent.change(screen.getByLabelText('From'), { target: { value: '2026-06-01' } });
|
||||
fireEvent.change(screen.getByLabelText('To'), { target: { value: '2026-06-03' } });
|
||||
fireEvent.click(screen.getByText('Submit'));
|
||||
|
||||
await waitFor(() => expect(screen.getByText(/conflicts with 1 assigned shift/)).toBeInTheDocument());
|
||||
expect(screen.getByText(/Morning Walk/)).toBeInTheDocument();
|
||||
expect(screen.getByText('Confirm & Submit')).toBeInTheDocument();
|
||||
|
||||
fireEvent.click(screen.getByText('Confirm & Submit'));
|
||||
await waitFor(() =>
|
||||
expect(mockCreateTimeOff).toHaveBeenLastCalledWith(
|
||||
expect.objectContaining({ confirm_conflicts: true }),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it('admin sees volunteer column and approve/reject buttons', async () => {
|
||||
const pendingReq: TimeOffRequest = { ...futureRequest, status: 'pending', volunteer_id: 10 };
|
||||
mockListTimeOff.mockResolvedValue([pendingReq]);
|
||||
mockListVolunteers.mockResolvedValue([{ id: 10, name: 'Alice' }]);
|
||||
renderAsAdmin();
|
||||
|
||||
await waitFor(() => expect(screen.getByText('Volunteer')).toBeInTheDocument());
|
||||
expect(screen.getByText('Approve')).toBeInTheDocument();
|
||||
expect(screen.getByText('Reject')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('admin can approve a request', async () => {
|
||||
const pendingReq: TimeOffRequest = { ...futureRequest, status: 'pending' };
|
||||
mockListTimeOff.mockResolvedValue([pendingReq]);
|
||||
mockReviewTimeOff.mockResolvedValue({ ...pendingReq, status: 'approved' });
|
||||
mockListVolunteers.mockResolvedValue([]);
|
||||
renderAsAdmin();
|
||||
|
||||
await waitFor(() => expect(screen.getByText('Approve')).toBeInTheDocument());
|
||||
fireEvent.click(screen.getByText('Approve'));
|
||||
await waitFor(() => expect(mockReviewTimeOff).toHaveBeenCalledWith(1, 'approved'));
|
||||
});
|
||||
|
||||
it('admin sees shift restoration preview when deleting', async () => {
|
||||
mockListTimeOff.mockResolvedValue([futureRequest]);
|
||||
mockGetRemovedShifts.mockResolvedValue([
|
||||
{ instance_id: 100, name: 'Morning Walk', date: '2026-06-01', start_time: '08:00', end_time: '12:00' },
|
||||
]);
|
||||
mockDeleteTimeOff.mockResolvedValue({ deleted: true, restored_shifts: [] });
|
||||
mockListVolunteers.mockResolvedValue([{ id: 10, name: 'Alice' }]);
|
||||
renderAsAdmin();
|
||||
|
||||
await waitFor(() => expect(screen.getByText('Delete')).toBeInTheDocument());
|
||||
fireEvent.click(screen.getByText('Delete'));
|
||||
|
||||
await waitFor(() =>
|
||||
expect(screen.getByText('Delete Time Off — Shift Restoration Preview')).toBeInTheDocument(),
|
||||
);
|
||||
expect(screen.getByText(/Morning Walk/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('admin sees volunteer picker in create form', async () => {
|
||||
mockListTimeOff.mockResolvedValue([]);
|
||||
mockListVolunteers.mockResolvedValue([
|
||||
{ id: 10, name: 'Alice' },
|
||||
{ id: 20, name: 'Bob' },
|
||||
]);
|
||||
renderAsAdmin();
|
||||
|
||||
await waitFor(() => expect(screen.getByText('Request Time Off')).toBeInTheDocument());
|
||||
fireEvent.click(screen.getByText('Request Time Off'));
|
||||
expect(screen.getByText('Volunteer')).toBeInTheDocument();
|
||||
expect(screen.getByText('Alice')).toBeInTheDocument();
|
||||
expect(screen.getByText('Bob')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -1,31 +1,96 @@
|
||||
import React, { useEffect, useState, FormEvent } from 'react';
|
||||
import { api, TimeOffRequest } from '../api';
|
||||
import { api, ApiError, TimeOffRequest, ConflictingShift, Volunteer } from '../api';
|
||||
import { useAuth } from '../auth';
|
||||
|
||||
export default function TimeOff() {
|
||||
const { role } = useAuth();
|
||||
const { role, volunteerID } = useAuth();
|
||||
const [requests, setRequests] = useState<TimeOffRequest[]>([]);
|
||||
const [volunteers, setVolunteers] = useState<Volunteer[]>([]);
|
||||
const [error, setError] = useState('');
|
||||
const [showForm, setShowForm] = useState(false);
|
||||
const [form, setForm] = useState({ starts_at: '', ends_at: '', reason: '' });
|
||||
const [form, setForm] = useState({ starts_at: '', ends_at: '', reason: '', volunteer_id: 0 });
|
||||
const [editingId, setEditingId] = useState<number | null>(null);
|
||||
const [conflicts, setConflicts] = useState<ConflictingShift[] | null>(null);
|
||||
const [deletePreview, setDeletePreview] = useState<{ id: number; shifts: ConflictingShift[] } | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
api.listTimeOff().then(setRequests).catch(() => setError('Could not load requests.'));
|
||||
}, []);
|
||||
if (role === 'admin') {
|
||||
api.listVolunteers().then(vols => setVolunteers(vols as Volunteer[]));
|
||||
}
|
||||
}, [role]);
|
||||
|
||||
async function handleCreate(e: FormEvent) {
|
||||
e.preventDefault();
|
||||
setError('');
|
||||
try {
|
||||
const req = await api.createTimeOff(form);
|
||||
setRequests(prev => [req, ...prev]);
|
||||
setForm({ starts_at: '', ends_at: '', reason: '' });
|
||||
setShowForm(false);
|
||||
const payload: any = { starts_at: form.starts_at, ends_at: form.ends_at, reason: form.reason };
|
||||
if (role === 'admin' && form.volunteer_id > 0) {
|
||||
payload.volunteer_id = form.volunteer_id;
|
||||
}
|
||||
if (conflicts) {
|
||||
payload.confirm_conflicts = true;
|
||||
}
|
||||
const result = await api.createTimeOff(payload);
|
||||
setRequests(prev => [result as TimeOffRequest, ...prev]);
|
||||
resetForm();
|
||||
} catch (err: any) {
|
||||
if (err instanceof ApiError && err.status === 409 && err.data?.conflicts) {
|
||||
setConflicts(err.data.conflicts);
|
||||
return;
|
||||
}
|
||||
setError(err.message);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleUpdate(e: FormEvent) {
|
||||
e.preventDefault();
|
||||
if (!editingId) return;
|
||||
setError('');
|
||||
try {
|
||||
const req = await api.updateTimeOff(editingId, {
|
||||
starts_at: form.starts_at,
|
||||
ends_at: form.ends_at,
|
||||
reason: form.reason,
|
||||
});
|
||||
setRequests(prev => prev.map(r => r.id === editingId ? req : r));
|
||||
resetForm();
|
||||
} catch (err: any) {
|
||||
setError(err.message);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleDelete(id: number) {
|
||||
setError('');
|
||||
try {
|
||||
const result = await api.deleteTimeOff(id);
|
||||
setRequests(prev => prev.filter(r => r.id !== id));
|
||||
setDeletePreview(null);
|
||||
if (result.restored_shifts?.length > 0) {
|
||||
setError(`Restored volunteer to ${result.restored_shifts.length} shift(s).`);
|
||||
}
|
||||
} catch (err: any) {
|
||||
setError(err.message);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleDeleteClick(id: number) {
|
||||
if (role === 'admin') {
|
||||
try {
|
||||
const shifts = await api.getRemovedShifts(id);
|
||||
if (shifts.length > 0) {
|
||||
setDeletePreview({ id, shifts });
|
||||
return;
|
||||
}
|
||||
} catch {
|
||||
// If we can't fetch preview, proceed with confirm
|
||||
}
|
||||
}
|
||||
if (window.confirm('Delete this time off request?')) {
|
||||
handleDelete(id);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleReview(id: number, status: 'approved' | 'rejected') {
|
||||
try {
|
||||
const req = await api.reviewTimeOff(id, status);
|
||||
@@ -35,71 +100,150 @@ export default function TimeOff() {
|
||||
}
|
||||
}
|
||||
|
||||
function startEdit(r: TimeOffRequest) {
|
||||
setEditingId(r.id);
|
||||
setForm({
|
||||
starts_at: r.starts_at.split('T')[0],
|
||||
ends_at: r.ends_at.split('T')[0],
|
||||
reason: r.reason ?? '',
|
||||
volunteer_id: 0,
|
||||
});
|
||||
setShowForm(true);
|
||||
setConflicts(null);
|
||||
}
|
||||
|
||||
function resetForm() {
|
||||
setForm({ starts_at: '', ends_at: '', reason: '', volunteer_id: 0 });
|
||||
setShowForm(false);
|
||||
setEditingId(null);
|
||||
setConflicts(null);
|
||||
}
|
||||
|
||||
function canEditOrDelete(r: TimeOffRequest): boolean {
|
||||
if (role === 'admin') return true;
|
||||
if (r.volunteer_id !== volunteerID) return false;
|
||||
return new Date(r.starts_at) > new Date();
|
||||
}
|
||||
|
||||
const statusClass = (status: string) => {
|
||||
if (status === 'approved') return 'status-approved';
|
||||
if (status === 'rejected') return 'status-rejected';
|
||||
return 'status-pending';
|
||||
};
|
||||
|
||||
const volunteerName = (vid: number) => {
|
||||
const v = volunteers.find(v => v.id === vid);
|
||||
return v ? v.name : `#${vid}`;
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="page">
|
||||
<div className="page-header">
|
||||
<h2>Time Off Requests</h2>
|
||||
<button onClick={() => setShowForm(v => !v)}>
|
||||
<button onClick={() => { if (showForm) resetForm(); else setShowForm(true); }}>
|
||||
{showForm ? 'Cancel' : 'Request Time Off'}
|
||||
</button>
|
||||
</div>
|
||||
{error && <p className="error">{error}</p>}
|
||||
|
||||
{showForm && (
|
||||
<form className="card" onSubmit={handleCreate}>
|
||||
<h3>New Request</h3>
|
||||
<form className="card" onSubmit={editingId ? handleUpdate : handleCreate}>
|
||||
<h3>{editingId ? 'Edit Request' : 'New Request'}</h3>
|
||||
{role === 'admin' && !editingId && (
|
||||
<label>
|
||||
Volunteer
|
||||
<select
|
||||
value={form.volunteer_id}
|
||||
onChange={e => setForm(f => ({ ...f, volunteer_id: Number(e.target.value) }))}
|
||||
>
|
||||
<option value={0}>Myself</option>
|
||||
{volunteers.filter(v => v.id !== volunteerID).map(v => (
|
||||
<option key={v.id} value={v.id}>{v.name}</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
)}
|
||||
<label>
|
||||
From
|
||||
<input type="date" value={form.starts_at} onChange={e => setForm(f => ({ ...f, starts_at: e.target.value }))} required />
|
||||
<input type="date" value={form.starts_at} onChange={e => { setForm(f => ({ ...f, starts_at: e.target.value })); setConflicts(null); }} required />
|
||||
</label>
|
||||
<label>
|
||||
To
|
||||
<input type="date" value={form.ends_at} onChange={e => setForm(f => ({ ...f, ends_at: e.target.value }))} required />
|
||||
<input type="date" value={form.ends_at} onChange={e => { setForm(f => ({ ...f, ends_at: e.target.value })); setConflicts(null); }} required />
|
||||
</label>
|
||||
<label>
|
||||
Reason
|
||||
<textarea value={form.reason} onChange={e => setForm(f => ({ ...f, reason: e.target.value }))} />
|
||||
</label>
|
||||
<button type="submit">Submit</button>
|
||||
|
||||
{conflicts && (
|
||||
<div className="card" style={{ background: '#fff3cd', border: '1px solid #ffc107', marginBottom: '1rem' }}>
|
||||
<p><strong>Warning:</strong> This time off conflicts with {conflicts.length} assigned shift(s):</p>
|
||||
<ul>
|
||||
{conflicts.map(c => (
|
||||
<li key={c.instance_id}>{c.name} on {c.date} ({c.start_time}–{c.end_time})</li>
|
||||
))}
|
||||
</ul>
|
||||
<p>You will be removed from these shifts. Continue?</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<button type="submit">
|
||||
{conflicts ? 'Confirm & Submit' : editingId ? 'Save Changes' : 'Submit'}
|
||||
</button>
|
||||
</form>
|
||||
)}
|
||||
|
||||
{deletePreview && (
|
||||
<div className="card" style={{ background: '#d4edda', border: '1px solid #28a745', marginBottom: '1rem' }}>
|
||||
<h3>Delete Time Off — Shift Restoration Preview</h3>
|
||||
<p>Deleting this time off will restore the volunteer to {deletePreview.shifts.length} shift(s):</p>
|
||||
<ul>
|
||||
{deletePreview.shifts.map(s => (
|
||||
<li key={s.instance_id}>{s.name} on {s.date} ({s.start_time}–{s.end_time})</li>
|
||||
))}
|
||||
</ul>
|
||||
<button onClick={() => handleDelete(deletePreview.id)}>Confirm Delete & Restore</button>
|
||||
<button onClick={() => setDeletePreview(null)} style={{ marginLeft: '0.5rem' }}>Cancel</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{requests.length === 0 ? (
|
||||
<p>No time off requests.</p>
|
||||
) : (
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
{role === 'admin' && <th>Volunteer</th>}
|
||||
<th>From</th>
|
||||
<th>To</th>
|
||||
<th>Reason</th>
|
||||
<th>Status</th>
|
||||
{role === 'admin' && <th>Actions</th>}
|
||||
<th>Actions</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{requests.map(r => (
|
||||
<tr key={r.id}>
|
||||
<td>{new Date(r.starts_at).toLocaleDateString()}</td>
|
||||
<td>{new Date(r.ends_at).toLocaleDateString()}</td>
|
||||
{role === 'admin' && <td>{volunteerName(r.volunteer_id)}</td>}
|
||||
<td>{new Date(r.starts_at).toLocaleDateString(undefined, { year: 'numeric', month: 'long', day: 'numeric' })}</td>
|
||||
<td>{new Date(r.ends_at).toLocaleDateString(undefined, { year: 'numeric', month: 'long', day: 'numeric' })}</td>
|
||||
<td>{r.reason ?? '—'}</td>
|
||||
<td><span className={statusClass(r.status)}>{r.status}</span></td>
|
||||
{role === 'admin' && (
|
||||
<td>
|
||||
{r.status === 'pending' && (
|
||||
{role === 'admin' && r.status === 'pending' && (
|
||||
<>
|
||||
<button className="btn-small" onClick={() => handleReview(r.id, 'approved')}>Approve</button>
|
||||
<button className="btn-small btn-danger" onClick={() => handleReview(r.id, 'rejected')}>Reject</button>
|
||||
</>
|
||||
)}
|
||||
</td>
|
||||
{canEditOrDelete(r) && (
|
||||
<>
|
||||
<button className="btn-small" onClick={() => startEdit(r)}>Edit</button>
|
||||
<button className="btn-small btn-danger" onClick={() => handleDeleteClick(r.id)}>Delete</button>
|
||||
</>
|
||||
)}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
|
||||
172
web/src/pages/Volunteers.test.tsx
Normal file
172
web/src/pages/Volunteers.test.tsx
Normal file
@@ -0,0 +1,172 @@
|
||||
import React from 'react';
|
||||
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
|
||||
import { vi, type Mock } from 'vitest';
|
||||
import { MemoryRouter } from 'react-router-dom';
|
||||
import Volunteers from './Volunteers';
|
||||
import { api, AdminVolunteer } from '../api';
|
||||
import { AuthProvider } from '../auth';
|
||||
|
||||
vi.mock('../api', () => ({
|
||||
api: {
|
||||
listVolunteers: vi.fn(),
|
||||
createVolunteer: vi.fn(),
|
||||
updateVolunteer: vi.fn(),
|
||||
resendInvite: vi.fn(),
|
||||
},
|
||||
OPERATIONAL_ROLES: ['Behaviour Team', 'Dog Log Monitor', 'Dog Shelter Volunteer', 'Trainee', 'Floater'],
|
||||
}));
|
||||
|
||||
const mockListVolunteers = api.listVolunteers as Mock;
|
||||
const mockCreateVolunteer = api.createVolunteer as Mock;
|
||||
const mockUpdateVolunteer = api.updateVolunteer as Mock;
|
||||
const mockResendInvite = api.resendInvite as Mock;
|
||||
|
||||
function buildFakeJWT(payload: object): string {
|
||||
const header = btoa(JSON.stringify({ alg: 'HS256', typ: 'JWT' }));
|
||||
const body = btoa(JSON.stringify(payload));
|
||||
return `${header}.${body}.fakesig`;
|
||||
}
|
||||
|
||||
const ADMIN_TOKEN = buildFakeJWT({ volunteer_id: 1, role: 'admin', exp: 9999999999 });
|
||||
|
||||
const alice: AdminVolunteer = {
|
||||
id: 1,
|
||||
name: 'Alice',
|
||||
email: 'alice@example.com',
|
||||
role: 'volunteer',
|
||||
active: true,
|
||||
is_trainee: false,
|
||||
operational_roles: 'Floater',
|
||||
notification_preference: 'email',
|
||||
completed_shifts: 5,
|
||||
created_at: '2026-01-01T00:00:00Z',
|
||||
updated_at: '2026-01-01T00:00:00Z',
|
||||
};
|
||||
|
||||
const trainee: AdminVolunteer = {
|
||||
...alice,
|
||||
id: 2,
|
||||
name: 'Bob',
|
||||
email: 'bob@example.com',
|
||||
is_trainee: true,
|
||||
completed_shifts: 1,
|
||||
};
|
||||
|
||||
function renderVolunteers() {
|
||||
localStorage.setItem('token', ADMIN_TOKEN);
|
||||
return render(
|
||||
<AuthProvider>
|
||||
<MemoryRouter>
|
||||
<Volunteers />
|
||||
</MemoryRouter>
|
||||
</AuthProvider>,
|
||||
);
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
mockListVolunteers.mockReset();
|
||||
mockCreateVolunteer.mockReset();
|
||||
mockUpdateVolunteer.mockReset();
|
||||
mockResendInvite.mockReset();
|
||||
localStorage.clear();
|
||||
});
|
||||
|
||||
test('renders volunteer list', async () => {
|
||||
mockListVolunteers.mockResolvedValueOnce([alice]);
|
||||
renderVolunteers();
|
||||
expect(await screen.findByText('Alice')).toBeInTheDocument();
|
||||
expect(screen.getByText('alice@example.com')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
test('shows trainee badge for trainee volunteers', async () => {
|
||||
mockListVolunteers.mockResolvedValueOnce([trainee]);
|
||||
renderVolunteers();
|
||||
await screen.findByText('Bob');
|
||||
expect(screen.getByText('Trainee')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
test('shows promote button with shift count for trainees', async () => {
|
||||
mockListVolunteers.mockResolvedValueOnce([trainee]);
|
||||
renderVolunteers();
|
||||
await screen.findByText('Bob');
|
||||
expect(screen.getByRole('button', { name: /promote.*1 shift/i })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
test('shows add volunteer button', async () => {
|
||||
mockListVolunteers.mockResolvedValueOnce([]);
|
||||
renderVolunteers();
|
||||
expect(await screen.findByRole('button', { name: /add volunteer/i })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
test('create form appears on Add Volunteer click', async () => {
|
||||
mockListVolunteers.mockResolvedValueOnce([]);
|
||||
renderVolunteers();
|
||||
fireEvent.click(await screen.findByRole('button', { name: /add volunteer/i }));
|
||||
expect(screen.getByRole('heading', { name: /new volunteer/i })).toBeInTheDocument();
|
||||
expect(screen.getByLabelText(/name/i)).toBeInTheDocument();
|
||||
expect(screen.getByLabelText(/email/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
test('creates volunteer and shows invite link', async () => {
|
||||
mockListVolunteers.mockResolvedValueOnce([]);
|
||||
const inviteToken = 'abc123invite';
|
||||
mockCreateVolunteer.mockResolvedValueOnce({
|
||||
...alice,
|
||||
id: 10,
|
||||
name: 'New Person',
|
||||
email: 'new@example.com',
|
||||
invite_token: inviteToken,
|
||||
});
|
||||
renderVolunteers();
|
||||
|
||||
fireEvent.click(await screen.findByRole('button', { name: /add volunteer/i }));
|
||||
fireEvent.change(screen.getByLabelText(/^name/i), { target: { value: 'New Person' } });
|
||||
fireEvent.change(screen.getByLabelText(/^email/i), { target: { value: 'new@example.com' } });
|
||||
fireEvent.click(screen.getByRole('button', { name: /create.*invite/i }));
|
||||
|
||||
await waitFor(() => expect(mockCreateVolunteer).toHaveBeenCalled());
|
||||
expect(await screen.findByText(new RegExp(inviteToken))).toBeInTheDocument();
|
||||
});
|
||||
|
||||
test('deactivates volunteer on Deactivate click', async () => {
|
||||
mockListVolunteers.mockResolvedValueOnce([alice]);
|
||||
mockUpdateVolunteer.mockResolvedValueOnce({ ...alice, active: false });
|
||||
renderVolunteers();
|
||||
|
||||
fireEvent.click(await screen.findByRole('button', { name: /deactivate/i }));
|
||||
|
||||
await waitFor(() =>
|
||||
expect(mockUpdateVolunteer).toHaveBeenCalledWith(alice.id, { active: false }),
|
||||
);
|
||||
});
|
||||
|
||||
test('promotes trainee to volunteer', async () => {
|
||||
mockListVolunteers.mockResolvedValueOnce([trainee]);
|
||||
mockUpdateVolunteer.mockResolvedValueOnce({ ...trainee, is_trainee: false });
|
||||
renderVolunteers();
|
||||
|
||||
await screen.findByText('Bob');
|
||||
fireEvent.click(screen.getByRole('button', { name: /promote/i }));
|
||||
|
||||
await waitFor(() =>
|
||||
expect(mockUpdateVolunteer).toHaveBeenCalledWith(trainee.id, { is_trainee: false }),
|
||||
);
|
||||
});
|
||||
|
||||
test('shows error when list fails', async () => {
|
||||
mockListVolunteers.mockRejectedValueOnce(new Error('Network error'));
|
||||
renderVolunteers();
|
||||
expect(await screen.findByText(/could not load volunteers/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
test('resend invite shows new link', async () => {
|
||||
const volWithToken: AdminVolunteer = { ...alice, invite_token: 'old-token' };
|
||||
mockListVolunteers.mockResolvedValueOnce([volWithToken]);
|
||||
mockResendInvite.mockResolvedValueOnce({ invite_token: 'new-fresh-token' });
|
||||
renderVolunteers();
|
||||
|
||||
await screen.findByText('Alice');
|
||||
fireEvent.click(screen.getByRole('button', { name: /resend invite/i }));
|
||||
|
||||
expect(await screen.findByText(/new-fresh-token/i)).toBeInTheDocument();
|
||||
});
|
||||
@@ -1,27 +1,172 @@
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import { api, Volunteer } from '../api';
|
||||
import { api, AdminVolunteer, CreateVolunteerInput, OPERATIONAL_ROLES } from '../api';
|
||||
|
||||
const EMPTY_FORM: CreateVolunteerInput = {
|
||||
name: '',
|
||||
email: '',
|
||||
role: 'volunteer',
|
||||
is_trainee: false,
|
||||
phone: '',
|
||||
operational_roles: '',
|
||||
};
|
||||
|
||||
export default function Volunteers() {
|
||||
const [volunteers, setVolunteers] = useState<Volunteer[]>([]);
|
||||
const [volunteers, setVolunteers] = useState<AdminVolunteer[]>([]);
|
||||
const [error, setError] = useState('');
|
||||
const [showCreate, setShowCreate] = useState(false);
|
||||
const [form, setForm] = useState<CreateVolunteerInput>(EMPTY_FORM);
|
||||
const [creating, setCreating] = useState(false);
|
||||
const [inviteLink, setInviteLink] = useState<{ name: string; token: string } | null>(null);
|
||||
const [expandedId, setExpandedId] = useState<number | null>(null);
|
||||
const [editNotes, setEditNotes] = useState<{ id: number; notes: string } | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
api.listVolunteers().then(setVolunteers).catch(() => setError('Could not load volunteers.'));
|
||||
load();
|
||||
}, []);
|
||||
|
||||
async function handleToggleActive(v: Volunteer) {
|
||||
function load() {
|
||||
api.listVolunteers()
|
||||
.then(vs => setVolunteers(vs as AdminVolunteer[]))
|
||||
.catch(() => setError('Could not load volunteers.'));
|
||||
}
|
||||
|
||||
async function handleCreate(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
setCreating(true);
|
||||
try {
|
||||
const av = await api.createVolunteer(form);
|
||||
setVolunteers(prev => [...prev, av]);
|
||||
setShowCreate(false);
|
||||
setForm(EMPTY_FORM);
|
||||
if (av.invite_token) {
|
||||
setInviteLink({ name: av.name, token: av.invite_token });
|
||||
}
|
||||
} catch (err: any) {
|
||||
setError(err.message);
|
||||
} finally {
|
||||
setCreating(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleToggleActive(v: AdminVolunteer) {
|
||||
try {
|
||||
const updated = await api.updateVolunteer(v.id, { active: !v.active });
|
||||
setVolunteers(prev => prev.map(vol => vol.id === v.id ? updated : vol));
|
||||
setVolunteers(prev => prev.map(vol => vol.id === v.id ? { ...vol, ...updated } : vol));
|
||||
} catch (err: any) {
|
||||
setError(err.message);
|
||||
}
|
||||
}
|
||||
|
||||
async function handlePromoteTrainee(v: AdminVolunteer) {
|
||||
try {
|
||||
const updated = await api.updateVolunteer(v.id, { is_trainee: false });
|
||||
setVolunteers(prev => prev.map(vol => vol.id === v.id ? { ...vol, ...updated } : vol));
|
||||
} catch (err: any) {
|
||||
setError(err.message);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleSaveNotes(id: number, notes: string) {
|
||||
try {
|
||||
await api.updateVolunteer(id, { admin_notes: notes });
|
||||
setVolunteers(prev => prev.map(v => v.id === id ? { ...v, admin_notes: notes } : v));
|
||||
setEditNotes(null);
|
||||
} catch (err: any) {
|
||||
setError(err.message);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleResendInvite(v: AdminVolunteer) {
|
||||
try {
|
||||
const { invite_token } = await api.resendInvite(v.id);
|
||||
setInviteLink({ name: v.name, token: invite_token });
|
||||
} catch (err: any) {
|
||||
setError(err.message);
|
||||
}
|
||||
}
|
||||
|
||||
function toggleOpsRole(role: string) {
|
||||
const current = form.operational_roles ? form.operational_roles.split(',').filter(Boolean) : [];
|
||||
const next = current.includes(role)
|
||||
? current.filter(r => r !== role)
|
||||
: [...current, role];
|
||||
setForm(f => ({ ...f, operational_roles: next.join(',') }));
|
||||
}
|
||||
|
||||
const inviteUrl = inviteLink
|
||||
? `${window.location.origin}/activate?token=${inviteLink.token}`
|
||||
: '';
|
||||
|
||||
return (
|
||||
<div className="page">
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
|
||||
<h2>Volunteers</h2>
|
||||
<button onClick={() => setShowCreate(s => !s)}>
|
||||
{showCreate ? 'Cancel' : '+ Add Volunteer'}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{error && <p className="error">{error}</p>}
|
||||
|
||||
{inviteLink && (
|
||||
<div className="notice">
|
||||
<strong>Invite link for {inviteLink.name}:</strong>
|
||||
<br />
|
||||
<code style={{ wordBreak: 'break-all' }}>{inviteUrl}</code>
|
||||
<br />
|
||||
<button className="btn-small" onClick={() => { navigator.clipboard.writeText(inviteUrl); }}>
|
||||
Copy
|
||||
</button>
|
||||
<button className="btn-small" style={{ marginLeft: 8 }} onClick={() => setInviteLink(null)}>
|
||||
Dismiss
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{showCreate && (
|
||||
<form className="card" onSubmit={handleCreate}>
|
||||
<h3>New Volunteer</h3>
|
||||
<label>
|
||||
Name *
|
||||
<input value={form.name} onChange={e => setForm(f => ({ ...f, name: e.target.value }))} required />
|
||||
</label>
|
||||
<label>
|
||||
Email *
|
||||
<input type="email" value={form.email} onChange={e => setForm(f => ({ ...f, email: e.target.value }))} required />
|
||||
</label>
|
||||
<label>
|
||||
Phone
|
||||
<input value={form.phone ?? ''} onChange={e => setForm(f => ({ ...f, phone: e.target.value }))} />
|
||||
</label>
|
||||
<label>
|
||||
Account type
|
||||
<select value={form.role} onChange={e => setForm(f => ({ ...f, role: e.target.value as 'admin' | 'volunteer' }))}>
|
||||
<option value="volunteer">Volunteer</option>
|
||||
<option value="admin">Admin</option>
|
||||
</select>
|
||||
</label>
|
||||
<label>
|
||||
<input type="checkbox" checked={form.is_trainee ?? false}
|
||||
onChange={e => setForm(f => ({ ...f, is_trainee: e.target.checked }))} />
|
||||
{' '}Trainee (blocks open shift claiming)
|
||||
</label>
|
||||
<fieldset>
|
||||
<legend>Operational roles</legend>
|
||||
{OPERATIONAL_ROLES.map(r => (
|
||||
<label key={r} style={{ display: 'block' }}>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={(form.operational_roles ?? '').split(',').includes(r)}
|
||||
onChange={() => toggleOpsRole(r)}
|
||||
/>
|
||||
{' '}{r}
|
||||
</label>
|
||||
))}
|
||||
</fieldset>
|
||||
<button type="submit" disabled={creating}>{creating ? 'Creating…' : 'Create & Send Invite'}</button>
|
||||
</form>
|
||||
)}
|
||||
|
||||
{volunteers.length === 0 ? (
|
||||
<p>No volunteers found.</p>
|
||||
) : (
|
||||
@@ -31,23 +176,74 @@ export default function Volunteers() {
|
||||
<th>Name</th>
|
||||
<th>Email</th>
|
||||
<th>Role</th>
|
||||
<th>Op. Roles</th>
|
||||
<th>Shifts</th>
|
||||
<th>Status</th>
|
||||
<th>Actions</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{volunteers.map(v => (
|
||||
<tr key={v.id}>
|
||||
<td>{v.name}</td>
|
||||
<React.Fragment key={v.id}>
|
||||
<tr>
|
||||
<td>
|
||||
{v.active ? v.name : `${v.name} (inactive)`}
|
||||
{v.is_trainee && <span className="badge">Trainee</span>}
|
||||
</td>
|
||||
<td>{v.email}</td>
|
||||
<td>{v.role}</td>
|
||||
<td>{v.operational_roles || '—'}</td>
|
||||
<td>{v.completed_shifts}</td>
|
||||
<td>{v.active ? 'Active' : 'Inactive'}</td>
|
||||
<td>
|
||||
<button className="btn-small" onClick={() => handleToggleActive(v)}>
|
||||
{v.active ? 'Deactivate' : 'Activate'}
|
||||
</button>
|
||||
{v.is_trainee && (
|
||||
<button className="btn-small" style={{ marginLeft: 4 }} onClick={() => handlePromoteTrainee(v)}>
|
||||
Promote ({v.completed_shifts} shifts)
|
||||
</button>
|
||||
)}
|
||||
{v.invite_token && (
|
||||
<button className="btn-small" style={{ marginLeft: 4 }} onClick={() => handleResendInvite(v)}>
|
||||
Resend Invite
|
||||
</button>
|
||||
)}
|
||||
<button className="btn-small" style={{ marginLeft: 4 }}
|
||||
onClick={() => setExpandedId(expandedId === v.id ? null : v.id)}>
|
||||
{expandedId === v.id ? 'Hide Notes' : 'Notes'}
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
{expandedId === v.id && (
|
||||
<tr>
|
||||
<td colSpan={7}>
|
||||
{editNotes?.id === v.id ? (
|
||||
<div>
|
||||
<textarea
|
||||
rows={3}
|
||||
style={{ width: '100%' }}
|
||||
value={editNotes.notes}
|
||||
onChange={e => setEditNotes({ id: v.id, notes: e.target.value })}
|
||||
/>
|
||||
<button className="btn-small" onClick={() => handleSaveNotes(v.id, editNotes.notes)}>Save</button>
|
||||
<button className="btn-small" style={{ marginLeft: 4 }} onClick={() => setEditNotes(null)}>Cancel</button>
|
||||
</div>
|
||||
) : (
|
||||
<div>
|
||||
<em style={{ color: '#666' }}>Admin notes:</em>{' '}
|
||||
{v.admin_notes || <span style={{ color: '#999' }}>None</span>}
|
||||
<button className="btn-small" style={{ marginLeft: 8 }}
|
||||
onClick={() => setEditNotes({ id: v.id, notes: v.admin_notes ?? '' })}>
|
||||
Edit
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
{v.last_login && <div style={{ marginTop: 4, color: '#666', fontSize: '0.85em' }}>Last login: {v.last_login}</div>}
|
||||
</td>
|
||||
</tr>
|
||||
)}
|
||||
</React.Fragment>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
1
web/src/react-app-env.d.ts
vendored
1
web/src/react-app-env.d.ts
vendored
@@ -1 +0,0 @@
|
||||
/// <reference types="react-scripts" />
|
||||
@@ -1,15 +0,0 @@
|
||||
import { ReportHandler } from 'web-vitals';
|
||||
|
||||
const reportWebVitals = (onPerfEntry?: ReportHandler) => {
|
||||
if (onPerfEntry && onPerfEntry instanceof Function) {
|
||||
import('web-vitals').then(({ getCLS, getFID, getFCP, getLCP, getTTFB }) => {
|
||||
getCLS(onPerfEntry);
|
||||
getFID(onPerfEntry);
|
||||
getFCP(onPerfEntry);
|
||||
getLCP(onPerfEntry);
|
||||
getTTFB(onPerfEntry);
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
export default reportWebVitals;
|
||||
@@ -1,5 +1,22 @@
|
||||
// jest-dom adds custom jest matchers for asserting on DOM nodes.
|
||||
// allows you to do things like:
|
||||
// expect(element).toHaveTextContent(/react/i)
|
||||
// learn more: https://github.com/testing-library/jest-dom
|
||||
import '@testing-library/jest-dom';
|
||||
|
||||
// Node 22+ ships a native localStorage (getter on globalThis) that lacks
|
||||
// .clear()/.getItem()/etc. jsdom doesn't override it. Delete the native
|
||||
// property and replace it with a spec-compliant Storage implementation.
|
||||
const store = new Map<string, string>();
|
||||
const storage: Storage = {
|
||||
getItem: (key: string) => store.get(key) ?? null,
|
||||
setItem: (key: string, value: string) => { store.set(key, String(value)); },
|
||||
removeItem: (key: string) => { store.delete(key); },
|
||||
clear: () => { store.clear(); },
|
||||
key: (index: number) => [...store.keys()][index] ?? null,
|
||||
get length() { return store.size; },
|
||||
};
|
||||
|
||||
delete (globalThis as any).localStorage;
|
||||
Object.defineProperty(globalThis, 'localStorage', {
|
||||
value: storage,
|
||||
writable: true,
|
||||
configurable: true,
|
||||
enumerable: true,
|
||||
});
|
||||
|
||||
1
web/src/vite-env.d.ts
vendored
Normal file
1
web/src/vite-env.d.ts
vendored
Normal file
@@ -0,0 +1 @@
|
||||
/// <reference types="vite/client" />
|
||||
21
web/tsconfig.app.json
Normal file
21
web/tsconfig.app.json
Normal file
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2020",
|
||||
"lib": ["dom", "dom.iterable", "esnext"],
|
||||
"allowJs": true,
|
||||
"skipLibCheck": true,
|
||||
"esModuleInterop": true,
|
||||
"allowSyntheticDefaultImports": true,
|
||||
"strict": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "bundler",
|
||||
"resolveJsonModule": true,
|
||||
"isolatedModules": true,
|
||||
"noEmit": true,
|
||||
"jsx": "react-jsx"
|
||||
},
|
||||
"include": ["src"],
|
||||
"exclude": ["src/**/*.test.tsx", "src/**/*.test.ts", "src/setupTests.ts"]
|
||||
}
|
||||
1
web/tsconfig.app.tsbuildinfo
Normal file
1
web/tsconfig.app.tsbuildinfo
Normal file
@@ -0,0 +1 @@
|
||||
{"root":["./src/app.tsx","./src/api.ts","./src/auth.tsx","./src/main.tsx","./src/vite-env.d.ts","./src/pages/activate.tsx","./src/pages/dashboard.tsx","./src/pages/login.tsx","./src/pages/profile.tsx","./src/pages/schedules.tsx","./src/pages/setup.tsx","./src/pages/timeoff.tsx","./src/pages/volunteers.tsx"],"version":"6.0.2"}
|
||||
@@ -1,11 +1,7 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "es5",
|
||||
"lib": [
|
||||
"dom",
|
||||
"dom.iterable",
|
||||
"esnext"
|
||||
],
|
||||
"target": "ES2020",
|
||||
"lib": ["dom", "dom.iterable", "esnext"],
|
||||
"allowJs": true,
|
||||
"skipLibCheck": true,
|
||||
"esModuleInterop": true,
|
||||
@@ -13,14 +9,13 @@
|
||||
"strict": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"module": "esnext",
|
||||
"moduleResolution": "node",
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "bundler",
|
||||
"resolveJsonModule": true,
|
||||
"isolatedModules": true,
|
||||
"noEmit": true,
|
||||
"jsx": "react-jsx"
|
||||
"jsx": "react-jsx",
|
||||
"types": ["vitest/globals"]
|
||||
},
|
||||
"include": [
|
||||
"src"
|
||||
]
|
||||
"include": ["src", "vite.config.ts"]
|
||||
}
|
||||
|
||||
1
web/tsconfig.tsbuildinfo
Normal file
1
web/tsconfig.tsbuildinfo
Normal file
@@ -0,0 +1 @@
|
||||
{"root":["./src/app.test.tsx","./src/app.tsx","./src/api.ts","./src/auth.tsx","./src/main.tsx","./src/setuptests.ts","./src/vite-env.d.ts","./src/pages/activate.test.tsx","./src/pages/activate.tsx","./src/pages/dashboard.tsx","./src/pages/login.tsx","./src/pages/profile.test.tsx","./src/pages/profile.tsx","./src/pages/schedules.test.tsx","./src/pages/schedules.tsx","./src/pages/setup.test.tsx","./src/pages/setup.tsx","./src/pages/timeoff.tsx","./src/pages/volunteers.test.tsx","./src/pages/volunteers.tsx","./vite.config.ts"],"errors":true,"version":"6.0.2"}
|
||||
23
web/vite.config.ts
Normal file
23
web/vite.config.ts
Normal file
@@ -0,0 +1,23 @@
|
||||
/// <reference types="vitest/config" />
|
||||
import { defineConfig } from 'vite';
|
||||
import react from '@vitejs/plugin-react';
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [react()],
|
||||
server: {
|
||||
port: 3000,
|
||||
proxy: {
|
||||
'/api': 'http://localhost:8080',
|
||||
},
|
||||
},
|
||||
build: {
|
||||
outDir: 'dist',
|
||||
},
|
||||
test: {
|
||||
globals: true,
|
||||
environment: 'jsdom',
|
||||
setupFiles: './src/setupTests.ts',
|
||||
css: true,
|
||||
unstubGlobals: true,
|
||||
},
|
||||
});
|
||||
Reference in New Issue
Block a user