Files
project-work/sources/tdd-task-list-plan.md
2026-11-02 18:25:46 -05:00

425 lines
20 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# TDD Plan: Task List View with Filtering, Sorting, Pagination
*Use this in LiveCompare — each step = one test + implementation cycle*
---
## UI Specification (from task-brief.md)
**Template**: `NearBeach/templates/NearBeach/tasks/task_list.html` (server-rendered Django, no Vue component)
**URL**: `path("tasks/", views.task_list, name="task_list")`
**Filter Sidebar** (GET form, `action="/tasks/"`):
| Param | Control | Query |
|-------|---------|-------|
| `status` (repeatable) | Checkboxes; value = `task_status_id` | `task_status_id__in=[...]` |
| `assignee` | Select; value = user `id` (0 = Unassigned) | `task_assigned_to=<id>` / `task_assigned_to__isnull=True` |
| `project` | Select; value = `project_id` | Tasks linked via `ObjectAssignment` |
| `start_date` | `<input type="date">`, optional | `task_start_date__date__gte=value` |
| `end_date` | `<input type="date">`, optional | `task_end_date__date__lte=value` |
- Status options from `ListOfTaskStatus` ordered by `task_status_sort_order`
- Assignee options: "All", users with task access in accessible projects, "Unassigned" (0)
- Project options: "All", projects user can reach through their groups
- Clear Filters = link to `/tasks/` (drops all params); Apply = form submit
- Hidden `sort` input in form carries current sort; hidden `page_size` dropdown in form
**Table (9 columns):**
| Column | Sort Field | Rendering |
|--------|------------|-----------|
| Title | `task_short_description` | Bold description + `#T-{task_id}` small |
| Status | `task_status__task_status_sort_order` | Badge: `badge-{{ higher_order_status\|lower }}` |
| Priority | `task_priority` | 8px dot + `{{ get_task_priority_display }}` |
| Assignee | `task_assigned_to__username` | Username or `-` |
| Project | `first_project_name` (annotated) | Via `ObjectAssignment` subquery |
| Start Date | `task_start_date` | `Y-m-d` |
| End Date | `task_end_date` | `Y-m-d` |
| Created | `date_created` | `Y-m-d` (default sort: `-date_created`) |
| Actions | — | "View" → `{% url 'task_information' task.task_id %}` |
**Status Badges** (4 classes by `task_higher_order_status`):
- `badge-backlog` (New, Backlog) — yellow
- `badge-normal` (In Progress, Test/Review) — blue
- `badge-blocked` (Blocked) — red
- `badge-closed` (Closed) — green
**Priority** (3 color groups):
- `priority-high` (0=Highest, 1=High) — red
- `priority-normal` (2=Normal) — orange
- `priority-low` (3=Low, 4=Lowest) — blue
**Sorting:**
- `?sort=field` = ASC (▲), `?sort=-field` = DESC (▼)
- Click active column → toggle; click different column → ASC
- Allowed fields: the 8 above only; invalid falls back to default
- Header links keep all other params, reset `page=1`
- Hidden `sort` input in filter form persists current sort
**Pagination:**
- `page_size`: 10/25/50/100 (default 25); invalid → 25; dropdown in filter form, auto-submits
- `page`: `Paginator.get_page()` (safe); elided range: `on_each_side=2, on_ends=1`
- Prev/Next: disabled (`<span>`) on first/last page
- All page links preserve filters, sort, page_size; change only `page`
- Apply / sort click / page_size change / Clear Filters → reset to `page=1`
- Results: `Showing {{ page_obj.start_index }}–{{ page_obj.end_index }} of {{ paginator.count }} tasks`
**Actions Column:** Pinned right (`th:last-child, td:last-child { position: sticky; right: 0; }`); other columns scroll sideways inside container
**Empty State:** `{% empty %}` row with `colspan="9"`, centered "No tasks found"; count shows "0–0 of 0"
**Permissions (DB-level, not template):**
- Queryset limited to tasks from projects user's groups can reach via `ObjectAssignment`
- Superusers see all
- `user_level` = max task permission across groups
- "+ New Task" button: `user_level >= 3`
- "View" button: `user_level >= 1`
- Filter sidebar: always visible
**Styling:**
- New partial: `src/sass/components/_task_list.scss` → imported in `main.scss`
- Add `--nb-*` tokens for new colors in both `_light_theme.scss` and `_dark_theme.scss`
- Reuse: `btn btn-primary`, `btn btn-secondary`, `form-control`, `badge`, card/spacing styles
- Layout: desktop = sidebar (~280px) + table; <1024px = stacked
- Table cells: 12px 16px padding
- Badge text + background readable in both themes
- Wrap table in `<div v-pre>` to prevent Vue interpolation of `{{ ... }}` in task descriptions
**Tests:** 12 test methods in `NearBeach/tests/tests_views/tests_task/test_task_list.py`
---
## Test File Location
```
NearBeach/tests/tests_views/tests_task/test_task_list.py
```
## Run Single Test Command
```bash
cd /workspace/nearbeach
python3 manage.py test NearBeach.tests.tests_views.tests_task.test_task_list.TestTaskList.<test_method-v 2
```
---
## STEP 1: URL + Template Rendering
### TEST PROMPT (send to model)
Write a test `test_task_list_url_accessible` in `test_task_list.py` that:
- Creates a superuser
- Logs in the client using `client.login(user=superuser)`
- GETs `/tasks/`
- Asserts status code 200
- Asserts template `NearBeach/tasks/task_list.html` is used
- Asserts "All Tasks" appears in response content
- Asserts context contains `tasks`, `filter_form`, `user_level`, `user_group_permissions`
>
Run it — it should FAIL (no view/URL/template exists yet).
### IMPL PROMPT (after test fails)
Implement the code to make `test_task_list_url_accessible` pass:
1. Add `task_list(request)` view in `NearBeach/views/task_views.py` with `@login_required`, returns render of `NearBeach/tasks/task_list.html` with context including `nearbeach_title`, `tasks` (empty queryset), `filter_form` (TaskListFilterForm instance), `user_level` (4 for superuser), `user_group_permissions`
2. Add URL route `path("tasks/", views.task_list, name="task_list")` in `NearBeach/urls.py`
3. Create `TaskListFilterForm` in `NearBeach/forms.py` with fields: status, assignee, project, start_date, end_date, sort, page_size, page — choices built in `__init__` with `user=` param for scoping; `clean_*` methods for sort/page_size/page fallbacks
4. Create **full template** `NearBeach/templates/NearBeach/tasks/task_list.html` matching the spec:
- Extends base template
- Header with title + New Task button (conditional on `user_level >= 3`)
- Sidebar with all filter sections (status checkboxes, assignee dropdown, project dropdown, date range inputs, Clear/Apply buttons, page_size auto-submit, hidden sort input)
- Table with all 9 columns (Title, Status, Priority, Assignee, Project, Start Date, End Date, Created, Actions)
- Status badges with 4 CSS classes (`badge-backlog`, `badge-normal`, `badge-blocked`, `badge-closed`) derived from `task_higher_order_status`
- Priority indicators with colored dots (`priority-high`, `priority-normal`, `priority-low`)
- Pagination controls (page size selector, page numbers with ellipsis, prev/next)
- Results info line
- Empty state handling
- Sortable column headers with ▲/▼ indicators
- Wrap table in `<div v-pre>`
5. Create `src/sass/components/_task_list.scss` + import in `main.scss`; add `--nb-*` tokens in both theme files
6. Create templatetags `task_list_sort_link`, `task_list_sort_indicator`, `task_list_page_link` for query string rebuilding
7. Run the test again — should PASS
---
## STEP 2: Permission Filtering (Core)
### TEST PROMPT
Write test `test_task_list_filters_by_user_projects`:
- Create two users: `user_alpha`, `user_beta`
- Create two groups: `group_alpha`, `group_beta` with `permission_set__task=2`
- Create two projects: `project_alpha`, `project_beta`
- Create `ObjectAssignment(group_alpha, project_alpha)` and `ObjectAssignment(group_beta, project_beta)`
- Create tasks: `task_alpha` linked via `ObjectAssignment(task_alpha, project_alpha)`, `task_beta` linked via `ObjectAssignment(task_beta, project_beta)`
- Login as `user_alpha` → GET `/tasks/` → assert `task_alpha` in response, `task_beta` NOT in response
- Login as `user_beta` → GET `/tasks/` → assert `task_beta` in response, `task_alpha` NOT in response
- Login as superuser → GET `/tasks/` → assert BOTH tasks in response
- Verify `user_level` in context equals max `permission_set__task` across accessible projects (2 for these users)
### IMPL PROMPT
Update `task_list` view to filter tasks by user's project access via `ObjectAssignment`:
1. Get user's groups: `UserGroup.objects.filter(is_deleted=False, username=request.user).values('group_id')`
2. Get accessible project IDs: `ObjectAssignment.objects.filter(is_deleted=False, group_id__in=user_groups, project_id__isnull=False).values_list('project_id', flat=True).distinct()`
3. Get accessible task IDs: `ObjectAssignment.objects.filter(is_deleted=False, task_id__isnull=False, project_id__in=accessible_project_ids).values_list('task_id', flat=True).distinct()`
4. If superuser: `Task.objects.filter(is_deleted=False)` else: `Task.objects.filter(is_deleted=False, task_id__in=accessible_task_ids)`
5. Compute `user_level = UserGroup.objects.filter(...).aggregate(Max("permission_set__task"))["permission_set__task__max"] or 0` (4 for superuser)
6. Pass `tasks` queryset, `user_level`, `user_group_permissions = get_user_group_permission(request.user, ["task"])` to template
7. Run test — should PASS
---
## STEP 3: Filter by Status
### TEST PROMPT
Write test `test_task_list_filter_by_status`:
- Setup: user with access to project, 3 tasks with different statuses from fixture (e.g., New, In Progress, Closed)
- GET `/tasks/?status={in_progress_id}` → assert only "In Progress" task shown
- GET `/tasks/?status={new_id}&status={closed_id}` → assert New and Closed shown, In Progress hidden
- GET `/tasks/` (no filter) → assert all 3 shown
- Invalid status ID → form invalid, no filters applied (per Q1 decision), all tasks shown
### IMPL PROMPT
Add status filtering to `task_list` view:
1. In `TaskListFilterForm.__init__`: build `status` choices from `ListOfTaskStatus.objects.filter(is_deleted=False).order_by('task_status_sort_order')` as `MultipleChoiceField` with `CheckboxSelectMultiple`
2. In view: instantiate form with `request.GET` and `user=request.user`; if `form.is_valid()` and `status` in cleaned_data → `tasks_qs = tasks_qs.filter(task_status__in=form.cleaned_data['status'])`
3. If form invalid → apply no filters, reset to page 1
4. Pass `filter_form` to template (sidebar renders checkboxes)
5. Run test — should PASS
---
## STEP 4: Filter by Assignee
### TEST PROMPT
Write test `test_task_list_filter_by_assignee`:
- Setup: user with project access, 2 assignees (user1, user2) in same projects, 4 tasks (2 assigned to user1, 1 to user2, 1 unassigned)
- GET `/tasks/?assignee={user1_id}` → assert only user1's tasks shown
- GET `/tasks/?assignee=0` → assert only unassigned task shown
- GET `/tasks/?assignee={user1_id}` (assignee is single select, not multi) → assert correct behavior
- GET `/tasks/` (no filter) → assert all 4 shown
### IMPL PROMPT
Add assignee filtering:
1. In `TaskListFilterForm.__init__`: build `assignee` choices as `ChoiceField` — `[("", "All Assignees"), ("0", "Unassigned")]` + users with task permission >= 1 in accessible projects
2. In view: if `assignee == "0"` → `tasks_qs.filter(task_assigned_to__isnull=True)`; elif assignee ID → `tasks_qs.filter(task_assigned_to_id=assignee)`
3. Pass form to template (sidebar renders dropdown)
4. Run test — should PASS
---
## STEP 5: Filter by Project
### TEST PROMPT
Write test `test_task_list_filter_by_project`:
- Setup: user with access to 2 projects (project_a, project_b), tasks in each (linked via ObjectAssignment)
- GET `/tasks/?project={project_a_id}` → assert only project_a tasks shown
- GET `/tasks/?project={project_b_id}` → assert only project_b tasks shown
- GET `/tasks/` (no filter) → assert tasks from both projects shown
### IMPL PROMPT
Add project filtering:
1. In `TaskListFilterForm.__init__`: build `project` choices as `ChoiceField` — `[("", "All Projects")]` + user's accessible projects (from Step 2 queryset)
2. In view: if project selected → `tasks_qs.filter(task_id__in=ObjectAssignment.objects.filter(is_deleted=False, project_id=project, task_id__isnull=False).values_list('task_id', flat=True))`
3. Pass form to template (sidebar renders dropdown)
4. Run test — should PASS
---
## STEP 6: Filter by Date Range
### TEST PROMPT
Write test `test_task_list_filter_by_date_range`:
- Setup: tasks with start_date/end_date across October 2025
- GET `/tasks/?start_date=2025-10-15&end_date=2025-10-25` → assert only tasks with start_date >= 15th AND end_date <= 25th shown
- GET `/tasks/?start_date=2025-10-01` (only start) → assert tasks with start_date >= 1st
- GET `/tasks/?end_date=2025-10-31` (only end) → assert tasks with end_date <= 31st
- Invalid date format → form invalid, no filters applied, all tasks shown
### IMPL PROMPT
Add date range filtering:
1. In `TaskListFilterForm`: `start_date = forms.DateField(required=False, widget=forms.DateInput(attrs={'type': 'date'}))`, `end_date` same
2. In view: if `start_date` → `tasks_qs.filter(task_start_date__date__gte=start_date)`; if `end_date` → `tasks_qs.filter(task_end_date__date__lte=end_date)`
3. Pass form to template (sidebar renders date inputs)
4. Run test — should PASS
---
## STEP 7: Sorting by Column Headers
### TEST PROMPT
Write test `test_task_list_sorting`:
- Setup: 5 tasks with different created, start_date, end_date, priority, status, project
- GET `/tasks/?sort=created` → assert tasks ordered by created ASC
- GET `/tasks/?sort=-created` → assert tasks ordered by created DESC
- GET `/tasks/?sort=priority` → assert priority order (High Normal Low) using Case/When
- GET `/tasks/?sort=start_date` → assert ordered by start_date ASC
- GET `/tasks/?sort=end_date` → assert ordered by end_date ASC
- GET `/tasks/?sort=status` → assert ordered by task_status__task_status_sort_order
- GET `/tasks/?sort=project` → assert ordered by first_project_name (annotated)
- Invalid sort param → defaults to `-date_created`
- Click same column again → reverses order; click different column → ASC
### IMPL PROMPT
Add sorting:
1. In `TaskListFilterForm`: `sort` field with `clean_sort()` validating against allowed fields (`created`, `-created`, `start_date`, `-start_date`, `end_date`, `-end_date`, `priority`, `-priority`, `status`, `-status`, `project`, `-project`), default `-created`
2. In view: apply `.order_by(sort_field)` to queryset; for `priority` use `Case/When` (0,1=1; 2=2; 3,4=3); for `project` annotate `first_project_name` via subquery
3. Template: header links use `task_list_sort_link` templatetag to preserve all params, reset `page=1`
4. Hidden `sort` input in filter form carries current sort
5. Run test — should PASS
---
## STEP 8: Pagination
### TEST PROMPT
Write test `test_task_list_pagination`:
- Setup: 50 tasks in user's project
- GET `/tasks/?page_size=10&page=1` → assert 10 tasks shown, page 1 active
- GET `/tasks/?page_size=10&page=3` → assert tasks 21-30 shown
- GET `/tasks/?page_size=25` → assert 25 tasks shown
- GET `/tasks/?page_size=100` → assert all 50 shown (single page)
- GET `/tasks/?page_size=999` (invalid) → defaults to 25
- Verify page navigation: prev/next (disabled on first/last), page numbers with ellipsis (elided range: on_each_side=2, on_ends=1)
- Page links preserve all filter/sort params; change only `page`
- Apply / sort click / page_size change / Clear Filters → reset to `page=1`
- Results line: `Showing {{ page_obj.start_index }}–{{ page_obj.end_index }} of {{ paginator.count }} tasks`
### IMPL PROMPT
Add pagination:
1. In `TaskListFilterForm`: `page_size` field with choices `[(10, "10"), (25, "25"), (50, "50"), (100, "100")]`, `clean_page_size()` default 25; `page` field with `clean_page()` default 1
2. In view: `paginator = Paginator(tasks_qs, page_size)`, `page_obj = paginator.get_page(page_number)`
3. Pass `page_obj`, `paginator`, `page_size` to template
4. Template: pagination links use `task_list_page_link` templatetag; page_size dropdown in filter form auto-submits
5. Run test — should PASS
---
## STEP 9: Combined Filters + Sort + Pagination
### TEST PROMPT
Write test `test_task_list_combined_filters_sort_pagination`:
- Setup: 100 tasks across 3 projects, various statuses, assignees, dates
- GET `/tasks/?status={in_progress_id}&project={proj1_id}&sort=-priority&page_size=10&page=2`
- Assert: only In Progress tasks from proj1, sorted by priority DESC, page 2 (items 11-20)
- Verify all filter/sort/pagination params work together correctly
### IMPL PROMPT
Ensure all filters/sort/pagination work together:
1. In view: apply filters → sort → paginate in that order
2. Template: all filter/sort/page_size inputs in same `<form method="GET">`, pagination links preserve all query params via templatetags
3. Clear Filters link = `/tasks/` (drops all params)
4. Run test — should PASS
---
## STEP 10: UI Permissions (user_level, user_group_permissions)
### TEST PROMPT
Write test `test_task_list_ui_permissions`:
- Setup: user with task permission level 1 (read only), user with level 3 (create)
- Login as level 1 → GET `/tasks/` → assert "New Task" button NOT in response, "View" button IS in response
- Login as level 3 → GET `/tasks/` → assert "New Task" button IS in response
- Verify `user_level` in context equals max `permission_set__task` across accessible projects
- Verify `user_group_permissions` passed to template
### IMPL PROMPT
Add permission context to template:
1. In view: compute `user_level = UserGroup.objects.filter(is_deleted=False, username=request.user, group_id__isnull=False).aggregate(Max("permission_set__task"))["permission_set__task__max"] or 0` (4 for superuser)
2. Pass `user_level` and `user_group_permissions = get_user_group_permission(request.user, ["task"])` to template
3. Template: `{% if user_level >= 3 %}<a href="{% url 'new_task' %}" class="btn btn-primary">+ New Task</a>{% endif %}` and `{% if user_level >= 1 %}<a href="{% url 'task_information' task.task_id %}">View</a>{% endif %}`
4. Run test — should PASS
---
## STEP 11: Empty State + Edge Cases
### TEST PROMPT
Write test `test_task_list_edge_cases`:
- User with no project access → GET `/tasks/` → assert "No tasks found" message, 0 tasks, count shows "0–0 of 0"
- Filter returns no results → assert "No tasks found", count shows "0–0 of 0"
- Invalid page number (e.g., 999) → `Paginator.get_page()` returns last page gracefully
- Invalid sort param → defaults to `-date_created`
- Invalid page_size → defaults to 25
- Invalid filter values (bad date, bad status ID) → form invalid, no filters applied, page reset to 1
### IMPL PROMPT
Handle edge cases:
1. Template: `{% empty %}` clause in task loop showing "No tasks found" with `colspan="9"`
2. View: `Paginator.get_page()` handles invalid pages gracefully
3. View: `clean_sort()`, `clean_page_size()`, `clean_page()` validate and default
4. View: if `not form.is_valid()` → apply no filters, `page=1`
5. Run test — should PASS
---
## STEP 12: Full Test Suite Run
### FINAL VERIFICATION PROMPT
Run the complete test suite:
```bash
python3 manage.py test NearBeach.tests.tests_views.tests_task -v 2
```
Should report **12 tests passing** covering all verification steps from the task brief.
---
## Quick Reference: Test Class Structure
```python
# NearBeach/tests/tests_views/tests_task/test_task_list.py
from django.test import TestCase, Client
from django.urls import reverse
from django.contrib.auth import get_user_model
from NearBeach.models import *
class TestTaskList(TestCase):
def setUp(self):
# Common setup: users, groups, projects, ObjectAssignments, tasks
pass
def test_task_list_url_accessible(self):
pass # Step 1
def test_task_list_filters_by_user_projects(self):
pass # Step 2
def test_task_list_filter_by_status(self):
pass # Step 3
def test_task_list_filter_by_assignee(self):
pass # Step 4
def test_task_list_filter_by_project(self):
pass # Step 5
def test_task_list_filter_by_date_range(self):
pass # Step 6
def test_task_list_sorting(self):
pass # Step 7
def test_task_list_pagination(self):
pass # Step 8
def test_task_list_combined_filters_sort_pagination(self):
pass # Step 9
def test_task_list_ui_permissions(self):
pass # Step 10
def test_task_list_edge_cases(self):
pass # Step 11
# 12th test could be added for comprehensive integration
```
---
## LiveCompare Session Tips
1. **Send TEST PROMPT first** → model writes test
2. **Run in Sandbox** → confirm FAIL
3. **Send IMPL PROMPT** → model implements
4. **Run in Sandbox** → confirm PASS
5. **Commit/continue** to next step
If model writes buggy implementation → test fails → you say "Test still fails, here's the error: [paste error]" → model fixes.
This gives you **granular control** and **visible progress** at each step.