20 Commits

Author SHA1 Message Date
f3c02ee9f7 end of project 2026-11-05 15:22:25 -05:00
179a9b450a added a larger config setup file 2026-11-02 18:44:05 -05:00
dfe4c493a3 after step 6 2026-11-02 18:25:46 -05:00
231cefbcd4 claude version of first prompt 2026-11-01 19:00:54 -05:00
6546c86bcc updated task-brief with the first prompt and notes additions 2026-11-01 18:48:22 -05:00
cd9b7a095b may be the final 2026-11-01 16:58:57 -05:00
7bde8c3b85 updates to the questions
Answers:

 1. Checked against code:
     - Project dropdown: project_id / project_name ✓ (Project model)
     - "+ New Task" URL: /new_task/ ✓ (urls.py name=new_task)
     - View URL: /task_information/{task_id}/ ✓ (urls.py
       name=task_information)

 2. Updated sources/view-mockup-generation.md — now matches all decisions
    (6 statuses, higher-order badges, 3 priority color groups, real sort
    fields, numeric filter IDs, elided pagination).

 3. Unassigned filter value: 0 (numeric), not "unassigned". View treats
    assignee=0 as task_assigned_to__isnull=True.

 4. Mobile check: Can't render here — you'll need to open the generated
    wireframe in a browser and narrow to <1024px.

 5. Commit: Noted — I haven't committed anything.
2026-11-01 16:17:35 -05:00
ff653b9a97 after priority 2026-11-01 16:13:12 -05:00
93a1948e8b after pagination 2026-11-01 15:58:10 -05:00
0fd7e77ce7 up to sorting is now mocked 2026-11-01 15:33:07 -05:00
28899110bf create view mockup and updated specs 2026-11-01 15:08:48 -05:00
eb6677c9fa rewrote specs, added new ui generation spec
- task-brief is the essential 3 questions answers
- tdd - is the revised tdd plan
- wireframe-gen - is 1st cut at writing up the mockup instructions
- view-mockup - is the 2nd cut
2026-11-01 14:19:06 -05:00
63453fa3ed updated project-rules, expanding all sections 2026-11-01 13:39:36 -05:00
2460343d79 add new sources
- permissions - all about the permission system
- selected task - requirements for the task
- list-wireframe - html mock of the page
- tdd - tdd step through implemention
2026-11-01 13:12:28 -05:00
3d5135c8b8 add UI conventions doc and convo log up to 261030 2026-10-31 19:39:11 -04:00
c6ee18c1d3 added candidates tasks doc 2026-10-30 18:53:53 -04:00
1ad38e24ca new file 2026-10-30 13:19:41 -04:00
ef252a02e5 initial NearBeach 2026-10-28 21:00:21 -04:00
3d61b05194 fix up the project-rules.md 2026-10-27 18:41:09 -04:00
e76914c977 prep 2026-10-27 18:23:57 -04:00
31 changed files with 23226 additions and 1503 deletions

View File

@@ -34,7 +34,7 @@ This Code of Conduct applies both within project spaces and in public spaces whe
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at support@nearbeach.org. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately.
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at support@nearbeahc.org. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership.

View File

@@ -34,7 +34,7 @@ This Code of Conduct applies both within project spaces and in public spaces whe
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at support@nearbeach.org. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately.
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at support@nearbeahc.org. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership.

File diff suppressed because it is too large Load Diff

View File

@@ -123,7 +123,7 @@ class ApiAdminPermissionTests(APITestCase):
"customer_title": 2,
"customer_first_name": "Socks",
"customer_last_name": "Fluffy Butt",
"customer_email": "sock@nearbeach.org",
"customer_email": "sock@nearbeahc.org",
"organisation": 1
},
201,
@@ -136,7 +136,7 @@ class ApiAdminPermissionTests(APITestCase):
"customer_title": 2,
"customer_first_name": "Socks",
"customer_last_name": "Fluffy Butt",
"customer_email": "sock@nearbeach.org",
"customer_email": "sock@nearbeahc.org",
},
200,
"PUT"

View File

@@ -116,7 +116,7 @@ class ApiAdminPermissionTests(APITestCase):
"customer_title": 2,
"customer_first_name": "Socks",
"customer_last_name": "Fluffy Butt",
"customer_email": "sock@nearbeach.org",
"customer_email": "sock@nearbeahc.org",
"organisation": 1
},
201,
@@ -129,7 +129,7 @@ class ApiAdminPermissionTests(APITestCase):
"customer_title": 2,
"customer_first_name": "Socks",
"customer_last_name": "Fluffy Butt",
"customer_email": "sock@nearbeach.org",
"customer_email": "sock@nearbeahc.org",
},
200,
"PUT"

View File

@@ -140,7 +140,7 @@ def initalize_org(user):
submit_organisation = Organisation(
organisation_name="No Organisation",
organisation_website="https://nearbeach.org",
organisation_email="noreply@nearbeach.org",
organisation_email="noreply@nearbeahc.org",
change_user=user,
)
submit_organisation.save()

View File

@@ -0,0 +1,267 @@
import json
import sys
from copy import deepcopy
# Load original fixture
with open('/home/eric/workspaces/dataannotation/project-5/NearBeach/NearBeach/fixtures/NearBeach_basic_setup.json') as f:
original = json.load(f)
# Find max PK for each model to avoid collisions
max_pk = {}
for obj in original:
model = obj['model']
pk = obj['pk']
# Only track integer PKs for auto-increment models
if isinstance(pk, int):
if model not in max_pk or pk > max_pk[model]:
max_pk[model] = pk
print("Max PKs:", max_pk)
# Models that should be duplicated (core test data)
DUPLICATE_MODELS = {
'auth.user', # users
'knox.authtoken', # auth tokens (needed by extendsauthtoken)
'NearBeach.group', # groups
'NearBeach.permissionset',
'NearBeach.usergroup',
'NearBeach.project',
'NearBeach.task',
'NearBeach.objectassignment',
'NearBeach.listofprojectstatus',
'NearBeach.listoftaskstatus',
'NearBeach.listofrequirementitemstatus',
'NearBeach.listofrequirementitemtype',
'NearBeach.listofrequirementtype',
'NearBeach.listofrequirementstatus',
'NearBeach.customer',
'NearBeach.organisation',
'NearBeach.requirement',
'NearBeach.requirementitem',
'NearBeach.sprint',
'NearBeach.sprintobjectassignment',
'NearBeach.kanbanboard',
'NearBeach.kanbancolumn',
'NearBeach.kanbancard',
'NearBeach.kanbanlevel',
'NearBeach.document',
'NearBeach.documentpermission',
'NearBeach.tag',
'NearBeach.tagassignment',
'NearBeach.objectnote',
'NearBeach.scheduledobject',
'NearBeach.userjob',
'NearBeach.changetask',
'NearBeach.requestforchange',
'NearBeach.usersetting',
'NearBeach.listoftitle',
'NearBeach.objecttemplate',
'NearBeach.objecttemplategroup',
'NearBeach.publiclink',
'NearBeach.extendsauthtoken',
'NearBeach.notification',
}
# Models that should NOT be duplicated (singletons, config)
SKIP_MODELS = {
'sessions.session',
'NearBeach.bugclient',
'NearBeach.listofbugclient',
}
new_objects = []
pk_offset = {model: max_pk.get(model, 0) for model in DUPLICATE_MODELS if model in max_pk}
# For FK references that need remapping
fk_remap = {} # (model, old_pk) -> new_pk
import uuid
# Special: extendsauthtoken and knox_authtoken share PK (1:1)
# Pre-generate UUID pairs for all duplicated auth tokens
authtoken_new_pks = {}
for obj in original:
if obj['model'] == 'NearBeach.extendsauthtoken':
old_pk = obj['pk']
authtoken_new_pks[old_pk] = str(uuid.uuid4()).replace('-', '')
def get_new_pk(model, old_pk=None):
if model in max_pk:
pk_offset[model] += 1
return pk_offset[model]
else:
# UUID-based models - use pre-generated UUID for auth tokens
if model == 'NearBeach.extendsauthtoken' and old_pk in authtoken_new_pks:
return authtoken_new_pks[old_pk]
if model == 'knox.authtoken' and old_pk in authtoken_new_pks:
return authtoken_new_pks[old_pk]
return str(uuid.uuid4()).replace('-', '')
def make_unique(field_value, field_name, new_pk):
"""Modify unique fields for duplicated objects"""
if field_value is None:
return None
# Fields that must be unique - append _copy or PK suffix
if field_name in ('username', 'email', 'group_name', 'project_name',
'customer_name', 'organisation_name',
'requirement_title', 'requirement_item_title',
'task_short_description', 'sprint_name',
'kanban_board_name', 'kanban_column_name',
'tag_name', 'document_title',
'listofprojectstatus_name', 'listoftaskstatus_name',
'listofrequirementitemstatus_name',
'listofrequirementitemtype_name',
'listofrequirementtype_name',
'listofrequirementstatus_name',
'listoftitle_name',
'bugclient_name'):
if isinstance(field_value, str):
return f'{field_value}_copy{new_pk}'
return field_value
def remap_fk(field_value, field_name):
"""Remap foreign key references in fields"""
if field_value is None:
return None
# Common FK field patterns
fk_fields = {
'user': 'auth.user',
'username': 'auth.user',
'group': 'NearBeach.group',
'group_id': 'NearBeach.group',
'permission_set': 'NearBeach.permissionset',
'permission_set_id': 'NearBeach.permissionset',
'project': 'NearBeach.project',
'project_id': 'NearBeach.project',
'task': 'NearBeach.task',
'task_id': 'NearBeach.task',
'requirement': 'NearBeach.requirement',
'requirement_id': 'NearBeach.requirement',
'requirement_item': 'NearBeach.requirementitem',
'requirement_item_id': 'NearBeach.requirementitem',
'sprint': 'NearBeach.sprint',
'sprint_id': 'NearBeach.sprint',
'customer': 'NearBeach.customer',
'customer_id': 'NearBeach.customer',
'organisation': 'NearBeach.organisation',
'organisation_id': 'NearBeach.organisation',
'tag': 'NearBeach.tag',
'tag_id': 'NearBeach.tag',
'document': 'NearBeach.document',
'document_id': 'NearBeach.document',
'kanban_board': 'NearBeach.kanbanboard',
'kanban_board_id': 'NearBeach.kanbanboard',
'kanban_column': 'NearBeach.kanbancolumn',
'kanban_column_id': 'NearBeach.kanbancolumn',
'kanban_card': 'NearBeach.kanbancard',
'kanban_card_id': 'NearBeach.kanbancard',
'change_user': 'auth.user',
'change_user_id': 'auth.user',
'user': 'auth.user',
'user_id': 'auth.user',
}
target_model = fk_fields.get(field_name)
if target_model and target_model in DUPLICATE_MODELS:
return fk_remap.get((target_model, field_value), field_value)
return field_value
# First pass: keep ALL originals, then add duplicates
for obj in original:
model = obj['model']
if model in SKIP_MODELS:
continue
# Keep all originals
new_objects.append(obj)
# Second pass: create duplicates for DUPLICATE_MODELS
for obj in original:
model = obj['model']
if model in SKIP_MODELS:
continue
if model not in DUPLICATE_MODELS:
# Singletons - already kept above, don't duplicate
continue
old_pk = obj['pk']
new_pk = get_new_pk(model, old_pk)
fk_remap[(model, old_pk)] = new_pk
new_obj = deepcopy(obj)
new_obj['pk'] = new_pk
# Remap FK fields and make unique fields unique
if 'fields' in new_obj:
for field_name, field_value in new_obj['fields'].items():
new_obj['fields'][field_name] = remap_fk(field_value, field_name)
new_obj['fields'][field_name] = make_unique(new_obj['fields'][field_name], field_name, new_pk)
new_objects.append(new_obj)
# Second pass: for M2M fields (like group_list in some objects), we need special handling
# But Django fixtures don't typically include M2M in the same way
print(f"Original: {len(original)} objects")
print(f"New: {len(new_objects)} objects")
# Sort by model dependency so FK targets load before dependents
# knox.authtoken must load before NearBeach.extendsauthtoken
model_order = [
'auth.user',
'knox.authtoken',
'NearBeach.extendsauthtoken',
'NearBeach.permissionset',
'NearBeach.group',
'NearBeach.usergroup',
'NearBeach.project',
'NearBeach.customer',
'NearBeach.organisation',
'NearBeach.listofprojectstatus',
'NearBeach.listoftaskstatus',
'NearBeach.listofrequirementstatus',
'NearBeach.listofrequirementtype',
'NearBeach.listofrequirementitemtype',
'NearBeach.listofrequirementitemstatus',
'NearBeach.task',
'NearBeach.requirement',
'NearBeach.requirementitem',
'NearBeach.sprint',
'NearBeach.sprintobjectassignment',
'NearBeach.kanbanboard',
'NearBeach.kanbancolumn',
'NearBeach.kanbanlevel',
'NearBeach.kanbancard',
'NearBeach.document',
'NearBeach.documentpermission',
'NearBeach.tag',
'NearBeach.tagassignment',
'NearBeach.objectnote',
'NearBeach.scheduledobject',
'NearBeach.userjob',
'NearBeach.changetask',
'NearBeach.requestforchange',
'NearBeach.usersetting',
'NearBeach.listoftitle',
'NearBeach.objecttemplate',
'NearBeach.objecttemplategroup',
'NearBeach.publiclink',
'NearBeach.notification',
'NearBeach.objectassignment',
'NearBeach.bugclient',
'NearBeach.listofbugclient',
]
model_priority = {m: i for i, m in enumerate(model_order)}
new_objects.sort(key=lambda o: model_priority.get(o['model'], 999))
# Write new fixture
output_path = '/home/eric/workspaces/dataannotation/project-5/NearBeach/NearBeach/fixtures/NearBeach_doubled_setup.json'
with open(output_path, 'w') as f:
json.dump(new_objects, f, indent=2)
print(f"Written to {output_path}")
# Verify
with open(output_path) as f:
data = json.load(f)
from collections import Counter
models = Counter(obj['model'] for obj in data)
for model, count in models.most_common():
print(f' {model}: {count}')

1
README.md Normal file
View File

@@ -0,0 +1 @@
The X-man, Wolverine, was Hugh Jackman

BIN
Woverine.pdf Normal file

Binary file not shown.

File diff suppressed because it is too large Load Diff

17
sources/Test prompt.md Normal file
View File

@@ -0,0 +1,17 @@
prompt
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
Run test - should FAIL
Implementation prompt
Ensure all filters/sort/pagination work together:
- In view: apply filters then sort then paginate in that order
- Template: all filter/sort/page_size inputs in same `<form method="GET">`, pagination links preserve all query params via templatetags
- Clear Filters link = `/tasks/` (drops all params)
Run test - should PASS

View File

@@ -1,366 +0,0 @@
<title>NearBeach Backend Shape</title>
<meta name="claude:viewport-fit-sides" content="cover">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Instrument+Sans:wght@400;500;600;700&family=JetBrains+Mono:wght@400;500&display=swap">
<style>
/* Layout: single reading column (~72ch) with wide breakouts for diagrams and tables; section labels in the margin on desktop. */
:root {
--bg: #f6f7f5;
--surface: #ffffff;
--fg: #17201c;
--muted: #56635d;
--line: #d9dfdb;
--accent: #1f6b52;
--accent-soft: #e2efe9;
--good: #2c7a3f;
--bad: #a8402b;
--warn: #946200;
--code-bg: #eef1ef;
--font-display: "Instrument Sans", "Segoe UI", system-ui, sans-serif;
--font-body: "Instrument Sans", "Segoe UI", system-ui, sans-serif;
--font-mono: "JetBrains Mono", ui-monospace, "SFMono-Regular", Menlo, monospace;
}
@media (prefers-color-scheme: dark) {
:root:not([data-theme="light"]) {
--bg: #111613; --surface: #18201c; --fg: #e4ebe7; --muted: #9aa8a1; --line: #2c3832;
--accent: #6cc6a2; --accent-soft: #1d3329; --good: #7ccf8e; --bad: #ef8f78; --warn: #e2b54f; --code-bg: #1e2823;
color-scheme: dark;
}
}
:root[data-theme="dark"] {
--bg: #111613; --surface: #18201c; --fg: #e4ebe7; --muted: #9aa8a1; --line: #2c3832;
--accent: #6cc6a2; --accent-soft: #1d3329; --good: #7ccf8e; --bad: #ef8f78; --warn: #e2b54f; --code-bg: #1e2823;
color-scheme: dark;
}
* { box-sizing: border-box; }
body {
background: var(--bg); color: var(--fg);
font-family: var(--font-body); font-size: 1rem; line-height: 1.6;
padding-left: max(16px, env(safe-area-inset-left, 0px));
padding-right: max(16px, env(safe-area-inset-right, 0px));
padding-block: 3rem 5rem;
}
.wrap { max-width: 60rem; margin: 0 auto; display: grid; gap: 3.5rem; }
header { display: grid; gap: .9rem; max-width: 46rem; }
.eyebrow { font-family: var(--font-mono); font-size: .75rem; letter-spacing: .08em; text-transform: uppercase; color: var(--accent); }
h1 { font-family: var(--font-display); font-size: clamp(2rem, 5vw, 2.9rem); line-height: 1.1; margin: 0; font-weight: 700; letter-spacing: -.02em; text-wrap: balance; }
h2 { font-family: var(--font-display); font-size: 1.55rem; line-height: 1.2; margin: 0; font-weight: 650; letter-spacing: -.01em; text-wrap: balance; }
h3 { font-size: 1.05rem; margin: 0; font-weight: 650; }
p { margin: 0; max-width: 68ch; }
.lede { font-size: 1.15rem; color: var(--muted); }
section { display: grid; gap: 1.2rem; }
.sec-head { display: grid; gap: .4rem; border-top: 1px solid var(--line); padding-top: 1.4rem; }
code, .mono { font-family: var(--font-mono); font-size: .86em; }
code { background: var(--code-bg); padding: .08em .35em; border-radius: 4px; overflow-wrap: anywhere; }
ul { margin: 0; padding-left: 1.2rem; display: grid; gap: .45rem; max-width: 70ch; }
a { color: var(--accent); }
.facts { display: grid; grid-template-columns: repeat(auto-fit, minmax(10.5rem, 1fr)); gap: 0; border: 1px solid var(--line); border-radius: 8px; background: var(--surface); overflow: hidden; }
.fact { padding: .9rem 1rem; border-right: 1px solid var(--line); border-bottom: 1px solid var(--line); display: grid; gap: .15rem; margin: 0 -1px -1px 0; }
.fact b { font-family: var(--font-mono); font-size: 1.35rem; font-weight: 500; font-variant-numeric: tabular-nums; }
.fact span { font-size: .84rem; color: var(--muted); line-height: 1.35; }
.fact.alert b { color: var(--bad); }
.diagram { background: var(--surface); border: 1px solid var(--line); border-radius: 8px; padding: 1.2rem; overflow-x: auto; }
.diagram svg { display: block; min-width: 760px; width: 100%; height: auto; }
.diagram svg text { font-family: var(--font-body); fill: var(--fg); }
.diagram svg .small { font-size: 11px; fill: var(--muted); font-family: var(--font-mono); }
.diagram svg .lbl { font-size: 13px; font-weight: 600; }
.diagram svg .box { fill: var(--surface); stroke: var(--line); stroke-width: 1.5; }
.diagram svg .box.hl { fill: var(--accent-soft); stroke: var(--accent); }
.diagram svg .lane { fill: var(--code-bg); stroke: none; }
.diagram svg .arrow { stroke: var(--muted); stroke-width: 1.5; fill: none; }
.diagram svg .arrow.hl { stroke: var(--accent); }
.diagram svg .ah { fill: var(--muted); }
.diagram svg .ah.hl { fill: var(--accent); }
.caption { font-size: .85rem; color: var(--muted); }
.surfaces { display: grid; grid-template-columns: repeat(auto-fit, minmax(16rem, 1fr)); gap: 1rem; }
.surface { background: var(--surface); border: 1px solid var(--line); border-radius: 8px; padding: 1.1rem; display: grid; gap: .55rem; align-content: start; min-width: 0; }
.surface .path { font-family: var(--font-mono); font-size: .8rem; color: var(--accent); }
.surface p { font-size: .93rem; }
.surface dl { display: grid; grid-template-columns: auto 1fr; gap: .25rem .8rem; margin: .3rem 0 0; font-size: .85rem; }
.surface dt { color: var(--muted); }
.surface dd { margin: 0; min-width: 0; }
.flow { display: grid; gap: .8rem; }
.flow-steps { list-style: none; padding: 0; margin: 0; display: grid; gap: 0; counter-reset: s; border-left: 2px solid var(--line); max-width: none; }
.flow-steps li { counter-increment: s; position: relative; padding: .55rem 0 .55rem 1.6rem; display: grid; grid-template-columns: minmax(0, 15rem) minmax(0, 1fr); gap: 1rem; }
.flow-steps li::before { content: counter(s); position: absolute; left: -.72rem; top: .6rem; width: 1.3rem; height: 1.3rem; border-radius: 50%; background: var(--bg); border: 2px solid var(--accent); color: var(--accent); font: 600 .7rem/1.05rem var(--font-mono); text-align: center; }
.flow-steps .where { font-family: var(--font-mono); font-size: .8rem; color: var(--muted); overflow-wrap: anywhere; }
.flow-steps .what { font-size: .93rem; }
@media (max-width: 640px) { .flow-steps li { grid-template-columns: minmax(0, 1fr); gap: .2rem; } }
pre.snip { background: var(--code-bg); border-radius: 6px; padding: .9rem 1rem; margin: 0; overflow-x: auto; font-family: var(--font-mono); font-size: .8rem; line-height: 1.55; }
pre.snip .c { color: var(--muted); }
.tbl { overflow-x: auto; border: 1px solid var(--line); border-radius: 8px; background: var(--surface); }
table { width: 100%; border-collapse: collapse; font-size: .92rem; min-width: 640px; }
th, td { text-align: left; vertical-align: top; padding: .7rem .9rem; border-bottom: 1px solid var(--line); }
th { font-size: .74rem; text-transform: uppercase; letter-spacing: .07em; color: var(--muted); font-weight: 600; background: var(--code-bg); }
tr:last-child td { border-bottom: 0; }
td:first-child { font-weight: 600; width: 22%; }
.pro { color: var(--good); }
.con { color: var(--bad); }
.risks { display: grid; gap: .7rem; }
.risk { display: grid; grid-template-columns: 6.5rem minmax(0, 1fr); gap: 1rem; padding: .9rem 1rem; background: var(--surface); border: 1px solid var(--line); border-radius: 8px; }
.risk p { font-size: .93rem; }
.sev { font-family: var(--font-mono); font-size: .7rem; text-transform: uppercase; letter-spacing: .07em; padding: .2rem .5rem; border-radius: 99px; height: fit-content; text-align: center; border: 1px solid currentColor; }
.sev.high { color: var(--bad); }
.sev.med { color: var(--warn); }
.sev.low { color: var(--muted); }
@media (max-width: 560px) { .risk { grid-template-columns: minmax(0, 1fr); gap: .4rem; } .sev { width: fit-content; } }
.note { border-left: 3px solid var(--accent); background: var(--accent-soft); padding: .8rem 1rem; border-radius: 0 6px 6px 0; font-size: .93rem; max-width: 72ch; }
footer { font-size: .82rem; color: var(--muted); border-top: 1px solid var(--line); padding-top: 1rem; }
</style>
<div class="wrap">
<header>
<div class="eyebrow">Architecture briefing · NearBeach codebase</div>
<h1>A Django monolith that renders a shell and hands everything to Vue</h1>
<p class="lede">NearBeach is one Django app with three HTTP surfaces on top of a shared ORM. Django owns routing, auth, permissions and persistence. The UI is a set of Vue components mounted inside Django templates, and they talk mainly to undocumented internal JSON endpoints, not to the public REST API.</p>
</header>
<section>
<div class="facts">
<div class="fact"><b>1</b><span>Django app, packaged as an installable library</span></div>
<div class="fact"><b>246</b><span><code>path()</code> routes in <code>NearBeach/urls.py</code> (pages + AJAX)</span></div>
<div class="fact"><b>24</b><span>DRF viewsets under <code>/api/v0/</code></span></div>
<div class="fact"><b>~50</b><span>models in a single 2,000-line <code>models.py</code></span></div>
<div class="fact"><b>440</b><span><code>is_deleted=False</code> filters written by hand</span></div>
<div class="fact alert"><b>0</b><span><code>transaction.atomic</code> or <code>select_related</code> calls</span></div>
</div>
<p class="caption">Counts come from grep over <code>NearBeach/</code>, excluding migrations, tests and vendored static files.</p>
</section>
<section>
<div class="sec-head">
<div class="eyebrow">Structure</div>
<h2>The layer map</h2>
</div>
<p>Every request, whatever its surface, goes through the same stack: route, auth decorator, NearBeach's own permission decorator, a view function, then the ORM. The interesting part is that the two API-style surfaces duplicate the same business logic.</p>
<div class="diagram">
<svg viewBox="0 0 900 520" role="img" aria-label="Layer diagram of NearBeach request handling">
<defs>
<marker id="a" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse"><path class="ah" d="M0,0 L10,5 L0,10 z"/></marker>
<marker id="ah" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse"><path class="ah hl" d="M0,0 L10,5 L0,10 z"/></marker>
</defs>
<!-- clients -->
<rect class="lane" x="10" y="10" width="880" height="80" rx="6"/>
<text class="small" x="22" y="28">CLIENTS</text>
<rect class="box hl" x="40" y="36" width="360" height="44" rx="5"/>
<text class="lbl" x="56" y="57">Browser: Django HTML + Vue 3 components</text>
<text class="small" x="56" y="72">webpack → NearBeach/static/NearBeach · Vuex · axios</text>
<rect class="box" x="560" y="36" width="300" height="44" rx="5"/>
<text class="lbl" x="576" y="57">External integrations</text>
<text class="small" x="576" y="72">knox token · Basic · session</text>
<!-- surfaces -->
<rect class="lane" x="10" y="110" width="880" height="96" rx="6"/>
<text class="small" x="22" y="128">URL SURFACES</text>
<rect class="box" x="40" y="138" width="230" height="58" rx="5"/>
<text class="lbl" x="54" y="160">Page routes</text>
<text class="small" x="54" y="178">NearBeach/urls.py → HTML</text>
<rect class="box hl" x="300" y="138" width="230" height="58" rx="5"/>
<text class="lbl" x="314" y="160">Internal AJAX routes</text>
<text class="small" x="314" y="178">same urls.py → JSON / text</text>
<rect class="box" x="560" y="138" width="300" height="58" rx="5"/>
<text class="lbl" x="574" y="160">Public REST API</text>
<text class="small" x="574" y="178">urls_api_v0.py · SimpleRouter</text>
<!-- cross-cutting -->
<rect class="lane" x="10" y="226" width="880" height="70" rx="6"/>
<text class="small" x="22" y="244">CROSS-CUTTING</text>
<rect class="box" x="40" y="252" width="490" height="34" rx="5"/>
<text class="small" x="54" y="273">@login_required · @require_http_methods · @check_*_permissions → injects user_level</text>
<rect class="box" x="560" y="252" width="300" height="34" rx="5"/>
<text class="small" x="574" y="273">@check_user_api_permissions (v0)</text>
<!-- handlers -->
<rect class="lane" x="10" y="316" width="880" height="80" rx="6"/>
<text class="small" x="22" y="334">HANDLERS</text>
<rect class="box" x="40" y="342" width="490" height="44" rx="5"/>
<text class="lbl" x="54" y="362">Function views (views/*.py)</text>
<text class="small" x="54" y="378">Django Form validates → model built by hand → serializers.serialize</text>
<rect class="box" x="560" y="342" width="300" height="44" rx="5"/>
<text class="lbl" x="574" y="362">DRF ModelViewSets</text>
<text class="small" x="574" y="378">ModelSerializer (serializers/)</text>
<!-- data -->
<rect class="lane" x="10" y="416" width="880" height="94" rx="6"/>
<text class="small" x="22" y="434">DATA</text>
<rect class="box hl" x="40" y="442" width="300" height="56" rx="5"/>
<text class="lbl" x="54" y="464">Django ORM · models.py</text>
<text class="small" x="54" y="482">soft delete · ObjectAssignment ACL</text>
<rect class="box" x="370" y="442" width="200" height="56" rx="5"/>
<text class="lbl" x="384" y="464">SQL database</text>
<text class="small" x="384" y="482">SQLite in dev</text>
<rect class="box" x="600" y="442" width="260" height="56" rx="5"/>
<text class="lbl" x="614" y="464">File storage</text>
<text class="small" x="614" y="482">private FS · S3/R2 · Azure</text>
<!-- arrows -->
<path class="arrow" d="M150 80 V138" marker-end="url(#a)"/>
<path class="arrow hl" d="M300 80 L400 138" marker-end="url(#ah)"/>
<path class="arrow" d="M370 80 L640 138" marker-end="url(#a)" stroke-dasharray="4 4"/>
<text class="small" x="478" y="104">5 Vue files</text>
<path class="arrow" d="M710 80 V138" marker-end="url(#a)"/>
<path class="arrow" d="M285 196 V252" marker-end="url(#a)"/>
<path class="arrow" d="M710 196 V252" marker-end="url(#a)"/>
<path class="arrow" d="M285 286 V342" marker-end="url(#a)"/>
<path class="arrow" d="M710 286 V342" marker-end="url(#a)"/>
<path class="arrow hl" d="M285 386 L200 442" marker-end="url(#ah)"/>
<path class="arrow hl" d="M710 386 L300 442" marker-end="url(#ah)"/>
<path class="arrow" d="M340 470 H370" marker-end="url(#a)"/>
<path class="arrow" d="M570 470 H600" marker-end="url(#a)"/>
</svg>
</div>
<p class="caption">The dashed arrow is the thin path: only 5 frontend files call <code>/api/v0/</code>. The rest of the roughly 140 axios-using files call internal routes such as <code>project_information/&lt;id&gt;/save/</code>.</p>
</section>
<section>
<div class="sec-head">
<div class="eyebrow">Surfaces</div>
<h2>Three ways in, two codebases of business logic</h2>
</div>
<div class="surfaces">
<div class="surface">
<h3>Page routes</h3>
<div class="path">GET /project_information/&lt;id&gt;/</div>
<p>The function view computes context, encodes it as JSON strings and renders a template. The template does little more than mount Vue.</p>
<dl><dt>Auth</dt><dd>Session + optional 2FA</dd><dt>Output</dt><dd>HTML with JSON in props</dd><dt>Contract</dt><dd>Template ↔ component props</dd></dl>
</div>
<div class="surface">
<h3>Internal AJAX</h3>
<div class="path">POST /project_information/&lt;id&gt;/save/</div>
<p>This is the real application API. Vue sends <code>FormData</code>, a Django <code>Form</code> validates it, and the view writes to models and returns serialized JSON or a URL string.</p>
<dl><dt>Auth</dt><dd>Session + CSRF header</dd><dt>Output</dt><dd>Ad hoc JSON / text</dd><dt>Contract</dt><dd>Undocumented, unversioned</dd></dl>
</div>
<div class="surface">
<h3>REST API v0</h3>
<div class="path">POST /api/v0/project/</div>
<p>DRF viewsets with drf-spectacular docs. This re-implements creates and updates for the same objects, including side effects such as <code>transfer_new_object_uploads</code>.</p>
<dl><dt>Auth</dt><dd>knox token, Basic, session</dd><dt>Output</dt><dd>ModelSerializer JSON</dd><dt>Contract</dt><dd>OpenAPI schema</dd></dl>
</div>
</div>
<p class="note">This means a rule change, such as "a project needs at least one group", has to be made in two places: <code>views/project_views.py</code> with <code>forms.py</code>, and <code>views/api/project_api_view.py</code> with <code>serializers/project_serializer.py</code>. Nothing keeps them in sync except tests.</p>
</section>
<section>
<div class="sec-head">
<div class="eyebrow">Data flow</div>
<h2>Following a project through the system</h2>
</div>
<div class="flow">
<h3>Read path: opening a project page</h3>
<ol class="flow-steps">
<li><span class="where">urls.py</span><span class="what">The <code>project_information/&lt;int:project_id&gt;/</code> route resolves to a plain function view.</span></li>
<li><span class="where">@login_required</span><span class="what">Redirects to the two_factor login if there's no session.</span></li>
<li><span class="where">check_specific_object_permissions</span><span class="what">Looks up <code>project_permissions</code> in <code>FUNCTION_DICT</code>. It intersects the user's <code>UserGroup</code> rows with the project's <code>ObjectAssignment</code> groups, then takes <code>Max("permission_set__project")</code>. The result (0–4) is passed into the view as <code>kwargs["user_level"]</code>. Superusers skip all of this and get 4.</span></li>
<li><span class="where">views/project_views.py</span><span class="what">Runs several <code>.values()</code> / <code>serializers.serialize()</code> queries and turns each result into a JSON string.</span></li>
<li><span class="where">templates/…/project_information.html</span><span class="what">Writes the JSON into attributes such as <code>v-bind:project-results="{{project_results}}"</code>. Django HTML-escapes it, the browser unescapes it, and Vue evaluates it as a JS expression.</span></li>
<li><span class="where">src/js/app.js</span><span class="what">One Vue app mounts on <code>#app</code> and registers every component globally. Each component then fetches its sub-modules (notes, documents, links) over internal AJAX.</span></li>
</ol>
</div>
<div class="flow">
<h3>Write path: saving from the UI</h3>
<pre class="snip"><span class="c">// Vue component (ProjectInformation.vue)</span>
const data_to_send = new FormData();
data_to_send.set("project_name", this.projectNameModel);
this.axios.post(`${this.rootUrl}project_information/${id}/save/`, data_to_send) <span class="c">// X-CSRFTOKEN from cookie</span>
<span class="c"># Django view</span>
form = ProjectForm(request.POST) <span class="c"># validation only, never rendered</span>
if not form.is_valid(): return HttpResponseBadRequest(form.errors)
project.project_name = form.cleaned_data["project_name"]; project.save()
<span class="c"># ...then ObjectAssignment rows, upload transfers, kanban card sync: separate saves, no transaction</span></pre>
</div>
<div class="flow">
<h3>Generic "object data" path</h3>
<p>Notes, tags, links, groups, users, documents and sprints attach to any object type through string-dispatched routes such as <code>object_data/&lt;destination&gt;/&lt;location_id&gt;/add_link/</code> and <code>documentation/&lt;destination&gt;/&lt;location_id&gt;/…</code>. The <code>destination</code> segment selects a model from one of several <code>OBJECT_DICT</code> tables. It's also used directly as an ORM keyword, as in <code>ObjectAssignment.objects.filter(**{destination: location_id})</code>. That's how one view serves ten object types.</p>
</div>
<div class="flow">
<h3>Background path</h3>
<ol class="flow-steps">
<li><span class="where">updatecrontab</span><span class="what">A management command writes cron entries. There's no Celery and no task queue.</span></li>
<li><span class="where">runscheduler</span><span class="what">Reads <code>ScheduledObject</code> and <code>ObjectTemplate</code>, then creates Tasks, Projects or Kanban cards from templates.</span></li>
<li><span class="where">event_hooks.emit()</span><span class="what">A home-made, type-checked event registry used instead of Django signals. Hooks run synchronously in the same process.</span></li>
</ol>
</div>
</section>
<section>
<div class="sec-head">
<div class="eyebrow">The data model</div>
<h2>Permissions live in data, not in Django's auth tables</h2>
</div>
<ul>
<li><strong>Access and capability are separate.</strong> <code>ObjectAssignment</code> answers "can this group see this object". It's one table with about ten nullable foreign keys (project, task, requirement, kanban board…) instead of a <code>GenericForeignKey</code>. <code>PermissionSet</code> answers "what can members of this group do", with a 0–4 level per object type.</li>
<li><strong>The custom <code>Group</code> / <code>UserGroup</code> models replace <code>django.contrib.auth</code> groups and permissions.</strong> <code>has_perm</code> isn't used anywhere. Child objects (change task, kanban card, requirement item) inherit permission from their parent through <code>_fetch_parent_details</code>.</li>
<li><strong>Soft delete is done by hand.</strong> Every model has <code>is_deleted</code>, and there's no custom manager. Each query has to remember the filter, which is why there are 440 of them.</li>
<li><strong>Audit columns are repeated on every model.</strong> <code>date_created</code>, <code>date_modified</code>, <code>change_user</code> and <code>creation_user</code> are copied into each one with no abstract base.</li>
<li><strong>The user model is swappable.</strong> <code>OVERRIDE_AUTH_USER_MODEL</code> sets <code>AUTH_USER_MODEL</code>. Models resolve it through <code>getattr(settings, "AUTH_USER_MODEL", User)</code>.</li>
</ul>
</section>
<section>
<div class="sec-head">
<div class="eyebrow">Trade-offs</div>
<h2>What the structure buys and what it costs</h2>
</div>
<div class="tbl">
<table>
<thead><tr><th>Decision</th><th>Pros</th><th>Cons</th></tr></thead>
<tbody>
<tr><td>Single installable Django app</td><td class="pro">Easy to self-host or pip-install, with one migration history and one deploy unit.</td><td class="con">No internal module boundaries. <code>models.py</code>, <code>forms.py</code> and <code>urls.py</code> are each over 1,000 lines, and every view can import every model.</td></tr>
<tr><td>Django templates mounting Vue</td><td class="pro">Server-side auth and routing come for free. There's no SPA router, and each page ships its data with it, so first paint needs no extra request.</td><td class="con">The data contract is a template string. Props are JS expressions built from escaped JSON. One global bundle registers every component on every page.</td></tr>
<tr><td>Internal AJAX alongside the REST API</td><td class="pro">The UI can change endpoints freely without versioning.</td><td class="con">Business rules are duplicated between Form-based views and DRF serializers, and the UI's real API is undocumented.</td></tr>
<tr><td>Function views + decorators</td><td class="pro">Very explicit and easy to grep. The permission check is visible on every handler.</td><td class="con">Boilerplate is repeated, and decorator order matters. Injecting <code>user_level</code> through kwargs couples every view signature to the decorator.</td></tr>
<tr><td>Custom group/permission-set model</td><td class="pro">Matches the product's domain (teams and object-level access) and can be managed in the UI.</td><td class="con">Bypasses Django's auth tooling. Every check is several queries, computed on every request with no caching.</td></tr>
<tr><td>String-dispatched <code>destination</code> routes</td><td class="pro">One implementation of notes, tags and links serves all object types.</td><td class="con">Stringly-typed polymorphism spread across several <code>OBJECT_DICT</code> copies. URL input reaches ORM keyword names.</td></tr>
<tr><td>Hand-written soft delete and audit fields</td><td class="pro">No hidden manager magic, and recovery is easy.</td><td class="con">One missed filter leaks deleted rows. There are hundreds of chances to miss one.</td></tr>
<tr><td>Cron + management commands</td><td class="pro">No broker or worker infrastructure to run.</td><td class="con">Jobs only run at cron granularity, with no retries or visibility. Event hooks run inline.</td></tr>
</tbody>
</table>
</div>
</section>
<section>
<div class="sec-head">
<div class="eyebrow">For discussion</div>
<h2>Risks a senior reviewer should look at first</h2>
</div>
<div class="risks">
<div class="risk"><span class="sev high">Integrity</span><p><strong>No transactions anywhere.</strong> <code>new_project_save</code> saves the project, then N <code>ObjectAssignment</code> rows, then moves uploads. A failure partway through leaves a project with no groups, which also means nobody but superusers can see it.</p></div>
<div class="risk"><span class="sev high">Security</span><p><strong>URL segments become ORM lookups.</strong> <code>&lt;destination&gt;</code> is an unconstrained <code>str</code> converter, and it reaches <code>filter(**{object_lookup: location_id})</code> in <code>generic_permissions.py</code>. I haven't checked whether a crafted lookup like <code>a__b__startswith</code> can be exploited. Either way, the input should be checked against an allow-list before it reaches the ORM.</p></div>
<div class="risk"><span class="sev med">Performance</span><p><strong>N+1 queries are likely.</strong> There are no <code>select_related</code> or <code>prefetch_related</code> calls. <code>len(queryset)</code> is used where <code>.exists()</code> would do, and permission checks run several queries on every request.</p></div>
<div class="risk"><span class="sev med">Maintainability</span><p><strong>Two write paths per object.</strong> Form views and DRF viewsets drift. Moving the UI onto <code>/api/v0/</code>, or pulling shared logic into a service layer, would remove one of them.</p></div>
<div class="risk"><span class="sev low">Hygiene</span><p><strong>Packaging drift.</strong> <code>pyproject.toml</code> declares <code>Django&gt;=3.1</code> and leaves out DRF, knox and two-factor, while <code>requirements.txt</code> pins 4.2.17+ with them. The <code>local/</code> settings hardcode <code>SECRET_KEY</code> and <code>DEBUG=True</code>, which is acceptable only because it's test-only.</p></div>
</div>
</section>
<section>
<div class="sec-head">
<div class="eyebrow">Orientation</div>
<h2>Where to start reading</h2>
</div>
<ul>
<li><code>local/settings.py</code>: installed apps, middleware order, DRF and knox configuration, storage switches.</li>
<li><code>NearBeach/urls.py</code> and <code>urls_api_v0.py</code>: the full route surface.</li>
<li><code>decorators/check_user_permissions/object_permissions.py</code> and <code>partials/</code>: the permission model in code.</li>
<li><code>models.py</code> around <code>ObjectAssignment</code> (line 989) and <code>PermissionSet</code> (line 1239).</li>
<li><code>views/project_views.py</code> next to <code>views/api/project_api_view.py</code>: the duplication, side by side.</li>
<li><code>views/object_data_views.py</code>: the generic <code>destination</code> pattern, 1,500 lines.</li>
</ul>
</section>
<footer>Based on a read-only static review of the <code>NearBeach/</code> directory on branch <code>project-6</code>. Nothing was executed. Counts come from grep and are approximate.</footer>
</div>

View File

@@ -1,64 +0,0 @@
# Project Idea: Django Security Configuration Auditor
From the security audit, this was the first recommended project:
> **Django Security Configuration Auditor** - Scans Django settings for production readiness (DEBUG, SECRET_KEY, security headers, password validators, token expiry, etc.)
## How this fits the project rules
**✅ Real task** - This is a genuine security tool that Django projects need. The NearBeach audit itself revealed exactly the kinds of issues this tool would catch (hardcoded SECRET_KEY, DEBUG=True, missing security headers, non-expiring tokens).
**✅ Checkable** - Clear completion criteria:
- Run against a test Django project with known issues → tool reports them
- Run against a hardened Django project → tool reports clean
- CLI with exit codes for CI/CD integration
**✅ Big enough** - Multiple components:
- Settings parser (handles `settings.py`, `local_settings.py`, environment-based configs)
- Rule engine (50+ security checks across categories)
- CLI with multiple output formats (JSON, SARIF, human-readable)
- CI/CD integration (GitHub Actions, GitLab CI)
- Extensible rule system for custom checks
**✅ Not already solved** - Existing tools like `django-check-secrets` or `bandit` don't do Django-specific settings analysis comprehensively.
**✅ Safe** - No credentials, no external API calls, pure static analysis.
---
## Suggested Task Breakdown (for 8-15 turns)
| Turn | Focus |
|------|-------|
| 1-2 | Project scaffold: CLI entry point, settings discovery/loading |
| 3-4 | Core rule engine + first 10 rules (SECRET_KEY, DEBUG, ALLOWED_HOSTS, security headers) |
| 5-6 | More rules: password validators, token settings, CORS, CSP, file upload settings |
| 7-8 | Output formats (JSON, SARIF, table), exit codes |
| 9-10 | CI/CD integration examples, GitHub Action |
| 11+ | Extensibility: custom rules, config file, ignore patterns |
---
## Why this is a strong choice for this project
1. **You're the target user** - You just did a manual audit of NearBeach. This tool would automate what you did.
2. **Leverages the repo** - NearBeach's own `local/settings.py` is the perfect test case (has the CRITICAL issues).
3. **Clear "Other notes for reviewer"** - You can explain: "I built this because I manually audited NearBeach and found 17 issues. This tool would have caught them all automatically."
4. **Measurable completion** - Run it on NearBeach zip → shows 17 findings. Fix settings → shows 0.
---
## Questions before we start
1. **Scope**: Just Django settings, or also scan `requirements.txt` / `pyproject.toml` for vulnerable dependencies?
2. **Language**: Python (obviously), but any preference on CLI framework (Click, Typer, argparse)?
3. **Test strategy**: Use NearBeach as the primary test fixture, or create a separate minimal Django project with injected issues?
---
## Next Steps
If proceeding with this as the task:
1. Draft the **Task brief** (description, completion criteria, other notes) for LiveCompare
2. Mount the NearBeach zip
3. Begin the session

View File

@@ -1,63 +0,0 @@
### 1. Task Description
Build a Django Security Configuration Auditor — a CLI tool that scans Django settings files for production readiness issues. The tool parses Django settings (including `settings.py`, `local_settings.py`, and environment-based configurations) and runs 50+ security checks across categories: DEBUG/SECRET_KEY exposure, security headers (CSP, HSTS, X-Frame-Options), password validators, token/session expiry, CORS, file upload limits, SSL/HTTPS settings, and more. Output formats include human-readable table, JSON, and SARIF for CI/CD integration with exit codes for pipeline gating.
This is a genuine security tool that Django projects need. The NearBeach audit itself revealed exactly the kinds of issues this tool would catch (hardcoded SECRET_KEY, DEBUG=True, missing security headers, non-expiring tokens). Existing tools like `django-check-secrets` or `bandit` don't do Django-specific settings analysis comprehensively.
---
### 2. How to Judge Completion
**Primary check (NearBeach test case):**
1. Mount the NearBeach zip and run the auditor against its `local/settings.py`:
```bash
python -m djangosecauditor /path/to/nearbeach/local/settings.py --format table
```
2. The tool should report **17+ findings** including at minimum:
- CRITICAL: `DEBUG = True`
- CRITICAL: Hardcoded `SECRET_KEY`
- HIGH: Missing `SECURE_SSL_REDIRECT`, `SECURE_HSTS_SECONDS`, `SECURE_CONTENT_TYPE_NOSNIFF`
- HIGH: Missing `X_FRAME_OPTIONS` or set to `SAMEORIGIN` instead of `DENY`
- HIGH: Missing CSP headers (`CONTENT_SECURITY_POLICY`)
- MEDIUM: Weak/absent password validators
- MEDIUM: Missing/short token expiry (`REST_FRAMEWORK` token settings, `SIMPLE_JWT` settings)
- MEDIUM: `ALLOWED_HOSTS` too permissive or `['*']`
- MEDIUM: Missing `SECURE_REFERRER_POLICY`, `SECURE_CROSS_ORIGIN_OPENER_POLICY`
**Hardened settings check:**
3. Create a minimal hardened Django settings file (or fix NearBeach's settings) and run again:
```bash
python -m djangosecauditor /path/to/hardened/settings.py --format json
```
Should report **0 findings** (exit code 0).
**CI/CD integration check:**
4. Run with SARIF output and verify valid SARIF 2.1.0:
```bash
python -m djangosecauditor /path/to/settings.py --format sarif --output results.sarif
```
Validate with `jq` or a SARIF viewer — each finding should have `ruleId`, `level`, `message`, `locations`.
**Test suite:**
5. Run the project's test suite:
```bash
python -m pytest tests/ -v
```
Should pass with 50+ test cases covering rule logic, settings parsing (various formats), output formats, and edge cases.
**Exit codes:**
6. Verify exit codes: `0` = clean, `1` = findings present, `2` = error (invalid settings, parse failure).
---
### 3. Other Notes for Reviewer
This tool automates the manual Django security audit I just performed on NearBeach, which uncovered 17 production-readiness issues. The problem it solves: Django projects ship with insecure defaults, and developers often miss settings that must be explicitly hardened for production. Existing tools (`bandit`, `django-check-secrets`, `safety`) focus on code vulnerabilities or dependency scanning, not Django-specific configuration analysis.
**Why this matters:** A single misconfigured setting (e.g., `DEBUG=True`, weak `SECRET_KEY`, missing HSTS) can lead to full compromise. This tool makes "secure by default" enforceable in CI/CD.
**Architecture:** Pure static analysis — no Django runtime, no database, no network calls. Parses settings as Python AST with env-branch modeling to handle `os.environ.get()`, `django-environ`, `python-decouple`, and conditional blocks (`if "KEY" in os.environ:`) without booting the project. Rule engine is extensible: each check is a class with `check(settings_dict) -> List[Finding]`.
**Scope:** Django settings only. Not scanning `requirements.txt`/`pyproject.toml` for vulnerable dependencies (that's a separate tool's job).
**Safety:** No credentials, no external API calls, no code execution beyond AST parsing. Safe to share and run on any codebase.

View File

@@ -0,0 +1,104 @@
# Conversation Log: NearBeach Review & UI Conventions
Scope: the `NearBeach/` folder in the project-5 worktree (branch `project-5`). The only files written are under `sources/`; no NearBeach code was changed.
---
## 1. Codebase review
**Request:** Review `NearBeach/`, stay inside that folder, then wait.
**Overview:** NearBeach is a Django and Vue 3 project-management app.
- The backend is in `NearBeach/NearBeach/`: models, about 1,200 lines of URL routes, around 35 view modules, and a REST API at `/api/v0/`.
- The frontend is in `src/`, built with Webpack.
- Access is controlled by permission decorators in `decorators/check_user_permissions/`.
**Main findings:**
1. **Wrong object in permission checks (high).** In `partials/generic_permissions.py`, `_fetch_parent_details` loads the wrong model for cards and requirement items:
- for `kanban_card` it runs `KanbanBoard.objects.get(pk=card_id)`
- for `requirement_item` it runs `Requirement.objects.get(...)`
The tag, link and note API routes reach this code, so permission is checked against an unrelated object. If no such object exists, the request fails with a 500 error.
2. **`document_remove` deletes before checking (high).** It soft-deletes the document before confirming the document belongs to the given object. A user with edit rights on one object can delete another object's document.
3. **Response raised as an exception (low).** `raise HttpResponseBadRequest(...)` raises a response object, which isn't an exception, so Python raises a `TypeError` instead.
**Smaller issues:**
- **Unchecked object types:** the type name from the URL isn't validated, so a bad one causes a 500 error.
- **No admin shortcut:** two API permission decorators don't let admins through automatically.
- **Unhandled missing sprint:** `Sprint.objects.get` has no handling for a missing sprint.
- **Users with no groups:** their permission level comes back as `None`, which crashes the comparison with a `TypeError`.
- **Dev settings:** `local/settings.py` has a hardcoded `SECRET_KEY` and `DEBUG=True`.
**Tests:** 114 backend tests ran and all passed. They don't cover the code paths behind the findings above, and the total seems low, so some test folders may not be discovered.
## 2. How users see data
The app has these main views:
- **Dashboard:** My Objects, To Do Today, RFC approvals, Kanban list, bugs, and admin widgets.
- **Record pages:** an information card on top, with tabs underneath (`ParentModules.vue`): Groups & Users, Documents, Links, Customers, Sprints, Misc, Notes, and Delete for level 4.
- **Kanban boards:** cards are dragged between columns and rows.
- **Search and list pages.**
- **Other views:** My Planner, Sprints/Gantt, scheduled objects, profile, admin pages, and public read-only share links.
**Possible security issue:** `search/search.html` puts the user's search text inside a Vue expression with `v-bind:search-input="'{{search_input}}'"`. Because the app compiles its templates in the browser, this could allow cross-site scripting. Not yet tested.
## 3. Search scope
- **Single-type search pages:** customers, organisations, groups, users, permission sets, notifications, sprints and tags. They match on names or text.
- **"List All Objects":** covers only six types: projects, tasks, requirements, requirement items, RFCs and Kanban boards. It matches titles only (or the ID if a word is a number), and every word must match. Results are limited to the user's groups and to open records unless "include closed" is ticked.
- **Not searchable anywhere:** Kanban cards and change tasks. Scheduled objects have a search function but no menu entry.
## 4. Filtering by date or user
Neither is possible in any search.
**Closest existing views:**
- My Planner: the user's own plan, next 7 days.
- Gantt: a timeline for one project's or requirement's sprints.
- Dashboard "My Objects": only the current user's objects.
No screen shows another user's assignments. The data needed already exists (`ObjectAssignment.assigned_user` and the start/end date fields), so the filters could be added by extending `SearchObjectsForm` and `_get_single_search_object`.
## 5. UI conventions guide
**Request:** Find the right way to describe the UX so new views match the existing look and feel.
**Planning:**
- Two read-only explorations mapped the page shell and the Vue component conventions.
- The user chose a **guide only** (no starter files and no CLAUDE.md), stored in **`sources/`**.
**Output:** `sources/NearBeach-UI-conventions.md`. It covers:
- **Page shell and views:** base templates, how Django data is passed into Vue, and view, decorator and URL conventions.
- **Navigation:** adding links to the navbar.
- **Component layout:** the card, the `col-md-4`/`col-md-8` section pattern, read-only rules and lifecycle.
- **Libraries:** Naive UI for inputs only, Bootstrap for everything else, TinyMCE for rich text.
- **Reusable pieces:** modals, tabs, validation, render components and composables.
- **Saving and feedback:** axios with FormData, and toasts.
- **Styling:** `--nb-*` theme variables.
- **Setup:** component registration, the build, and tests.
- **A new-view checklist** and quirks not to copy.
The details were checked against the code, and the TinyMCE toolbar excerpt was corrected after checking.
## 6. Recipe for a global task list
**Request:** A brief, recipe-style explanation of adding a global task list that can be grouped by user, by date or by assignment.
**Answer:** a nine-step recipe:
1. Add URLs.
2. Add a `TaskListForm`.
3. Add a page view and a POST JSON data view. The data view must limit tasks to the user's groups.
4. Add the template.
5. Add `TaskList.vue`.
6. Register it in `components.js` and `app.js`.
7. Add a navbar link.
8. Add backend and frontend tests.
9. Build and check in both themes.
**Follow-up:** the user said "no", then clarified "do not build it". Nothing was built.
---
## Files produced
- `sources/NearBeach-UI-conventions.md`
- `sources/conversation-log-261020.md` (this file)

View File

@@ -0,0 +1,50 @@
# Conversation Log - Project 5 / NearBeach Task Planning
**Date**: 2025-10-29
**Repo**: NearBeach (Django/Vue project management tool)
**Selected Task**: Task List View with Filtering, Sorting, and Pagination
---
## Summary
User selected "Task List View with Filtering, Sorting, and Pagination" (score: 25/25) from the find-candidate-tasks workflow. Created wireframe at `workflows/find-candidate-tasks/stages/04_user-selection/output/task-list-wireframe.html`.
Key discussion points:
- Project rules reviewed from `sources/project-rules.md`
- Clarified workflow: local exploration with Claude Code → mount zip in LiveCompare → implement with model
- "Working out" permission logic (ObjectAssignment group-based system) should happen locally before LiveCompare session
- Task brief ready for LiveCompare with verification steps
---
## Task Brief (Ready for LiveCompare)
**Task Description**: NearBeach has task detail views (`task_information`) and task creation (`new_task`), but **no general task list view** for users to see all their tasks across projects. Users must navigate through individual projects or kanban boards to find tasks, which is inefficient for project managers overseeing multiple projects. A dedicated task list with filtering, sorting, and pagination is a standard project management feature that would significantly improve task discoverability and workflow.
**How to Judge Completion**:
1. Navigate to `/tasks/` - paginated table of all tasks user has permission to view
2. Filter by status, assignee, project, date range
3. Sort by column headers (Created, Start Date, End Date, Priority, Status, Project)
4. Pagination: page size selector (10, 25, 50, 100) and page navigation
5. Tests: `python3 manage.py test NearBeach.tests.tests_views.tests_task` - 10+ new tests
6. Permission enforcement: second user without project access cannot see those tasks
**Key Files Likely Involved**:
- `NearBeach/views/task_views.py` - new `task_list` view
- `NearBeach/urls.py` - route for `/tasks/`
- `NearBeach/templates/NearBeach/tasks/task_list.html` - template with filter sidebar, table, pagination
- `NearBeach/forms.py` - `TaskFilterForm`
- `NearBeach/tests/tests_views/tests_task/` - new test files
**Permission Challenge**: Must respect existing `ObjectAssignment` group-based system
---
## Next Steps for User
1. Copy Task Brief into LiveCompare (Task Description, How to Judge Completion, Other Notes for Reviewer)
2. Download NearBeach repo zip from approved repos table
3. Mount archive in LiveCompare before first message
4. File Source URL: `https://github.com/nearbeach/NearBeach`
5. Start conversation with model using Task Description as first message

View File

@@ -0,0 +1,267 @@
import json
import sys
from copy import deepcopy
# Load original fixture
with open('/home/eric/workspaces/dataannotation/project-5/NearBeach/NearBeach/fixtures/NearBeach_basic_setup.json') as f:
original = json.load(f)
# Find max PK for each model to avoid collisions
max_pk = {}
for obj in original:
model = obj['model']
pk = obj['pk']
# Only track integer PKs for auto-increment models
if isinstance(pk, int):
if model not in max_pk or pk > max_pk[model]:
max_pk[model] = pk
print("Max PKs:", max_pk)
# Models that should be duplicated (core test data)
DUPLICATE_MODELS = {
'auth.user', # users
'knox.authtoken', # auth tokens (needed by extendsauthtoken)
'NearBeach.group', # groups
'NearBeach.permissionset',
'NearBeach.usergroup',
'NearBeach.project',
'NearBeach.task',
'NearBeach.objectassignment',
'NearBeach.listofprojectstatus',
'NearBeach.listoftaskstatus',
'NearBeach.listofrequirementitemstatus',
'NearBeach.listofrequirementitemtype',
'NearBeach.listofrequirementtype',
'NearBeach.listofrequirementstatus',
'NearBeach.customer',
'NearBeach.organisation',
'NearBeach.requirement',
'NearBeach.requirementitem',
'NearBeach.sprint',
'NearBeach.sprintobjectassignment',
'NearBeach.kanbanboard',
'NearBeach.kanbancolumn',
'NearBeach.kanbancard',
'NearBeach.kanbanlevel',
'NearBeach.document',
'NearBeach.documentpermission',
'NearBeach.tag',
'NearBeach.tagassignment',
'NearBeach.objectnote',
'NearBeach.scheduledobject',
'NearBeach.userjob',
'NearBeach.changetask',
'NearBeach.requestforchange',
'NearBeach.usersetting',
'NearBeach.listoftitle',
'NearBeach.objecttemplate',
'NearBeach.objecttemplategroup',
'NearBeach.publiclink',
'NearBeach.extendsauthtoken',
'NearBeach.notification',
}
# Models that should NOT be duplicated (singletons, config)
SKIP_MODELS = {
'sessions.session',
'NearBeach.bugclient',
'NearBeach.listofbugclient',
}
new_objects = []
pk_offset = {model: max_pk.get(model, 0) for model in DUPLICATE_MODELS if model in max_pk}
# For FK references that need remapping
fk_remap = {} # (model, old_pk) -> new_pk
import uuid
# Special: extendsauthtoken and knox_authtoken share PK (1:1)
# Pre-generate UUID pairs for all duplicated auth tokens
authtoken_new_pks = {}
for obj in original:
if obj['model'] == 'NearBeach.extendsauthtoken':
old_pk = obj['pk']
authtoken_new_pks[old_pk] = str(uuid.uuid4()).replace('-', '')
def get_new_pk(model, old_pk=None):
if model in max_pk:
pk_offset[model] += 1
return pk_offset[model]
else:
# UUID-based models - use pre-generated UUID for auth tokens
if model == 'NearBeach.extendsauthtoken' and old_pk in authtoken_new_pks:
return authtoken_new_pks[old_pk]
if model == 'knox.authtoken' and old_pk in authtoken_new_pks:
return authtoken_new_pks[old_pk]
return str(uuid.uuid4()).replace('-', '')
def make_unique(field_value, field_name, new_pk):
"""Modify unique fields for duplicated objects"""
if field_value is None:
return None
# Fields that must be unique - append _copy or PK suffix
if field_name in ('username', 'email', 'group_name', 'project_name',
'customer_name', 'organisation_name',
'requirement_title', 'requirement_item_title',
'task_short_description', 'sprint_name',
'kanban_board_name', 'kanban_column_name',
'tag_name', 'document_title',
'listofprojectstatus_name', 'listoftaskstatus_name',
'listofrequirementitemstatus_name',
'listofrequirementitemtype_name',
'listofrequirementtype_name',
'listofrequirementstatus_name',
'listoftitle_name',
'bugclient_name'):
if isinstance(field_value, str):
return f'{field_value}_copy{new_pk}'
return field_value
def remap_fk(field_value, field_name):
"""Remap foreign key references in fields"""
if field_value is None:
return None
# Common FK field patterns
fk_fields = {
'user': 'auth.user',
'username': 'auth.user',
'group': 'NearBeach.group',
'group_id': 'NearBeach.group',
'permission_set': 'NearBeach.permissionset',
'permission_set_id': 'NearBeach.permissionset',
'project': 'NearBeach.project',
'project_id': 'NearBeach.project',
'task': 'NearBeach.task',
'task_id': 'NearBeach.task',
'requirement': 'NearBeach.requirement',
'requirement_id': 'NearBeach.requirement',
'requirement_item': 'NearBeach.requirementitem',
'requirement_item_id': 'NearBeach.requirementitem',
'sprint': 'NearBeach.sprint',
'sprint_id': 'NearBeach.sprint',
'customer': 'NearBeach.customer',
'customer_id': 'NearBeach.customer',
'organisation': 'NearBeach.organisation',
'organisation_id': 'NearBeach.organisation',
'tag': 'NearBeach.tag',
'tag_id': 'NearBeach.tag',
'document': 'NearBeach.document',
'document_id': 'NearBeach.document',
'kanban_board': 'NearBeach.kanbanboard',
'kanban_board_id': 'NearBeach.kanbanboard',
'kanban_column': 'NearBeach.kanbancolumn',
'kanban_column_id': 'NearBeach.kanbancolumn',
'kanban_card': 'NearBeach.kanbancard',
'kanban_card_id': 'NearBeach.kanbancard',
'change_user': 'auth.user',
'change_user_id': 'auth.user',
'user': 'auth.user',
'user_id': 'auth.user',
}
target_model = fk_fields.get(field_name)
if target_model and target_model in DUPLICATE_MODELS:
return fk_remap.get((target_model, field_value), field_value)
return field_value
# First pass: keep ALL originals, then add duplicates
for obj in original:
model = obj['model']
if model in SKIP_MODELS:
continue
# Keep all originals
new_objects.append(obj)
# Second pass: create duplicates for DUPLICATE_MODELS
for obj in original:
model = obj['model']
if model in SKIP_MODELS:
continue
if model not in DUPLICATE_MODELS:
# Singletons - already kept above, don't duplicate
continue
old_pk = obj['pk']
new_pk = get_new_pk(model, old_pk)
fk_remap[(model, old_pk)] = new_pk
new_obj = deepcopy(obj)
new_obj['pk'] = new_pk
# Remap FK fields and make unique fields unique
if 'fields' in new_obj:
for field_name, field_value in new_obj['fields'].items():
new_obj['fields'][field_name] = remap_fk(field_value, field_name)
new_obj['fields'][field_name] = make_unique(new_obj['fields'][field_name], field_name, new_pk)
new_objects.append(new_obj)
# Second pass: for M2M fields (like group_list in some objects), we need special handling
# But Django fixtures don't typically include M2M in the same way
print(f"Original: {len(original)} objects")
print(f"New: {len(new_objects)} objects")
# Sort by model dependency so FK targets load before dependents
# knox.authtoken must load before NearBeach.extendsauthtoken
model_order = [
'auth.user',
'knox.authtoken',
'NearBeach.extendsauthtoken',
'NearBeach.permissionset',
'NearBeach.group',
'NearBeach.usergroup',
'NearBeach.project',
'NearBeach.customer',
'NearBeach.organisation',
'NearBeach.listofprojectstatus',
'NearBeach.listoftaskstatus',
'NearBeach.listofrequirementstatus',
'NearBeach.listofrequirementtype',
'NearBeach.listofrequirementitemtype',
'NearBeach.listofrequirementitemstatus',
'NearBeach.task',
'NearBeach.requirement',
'NearBeach.requirementitem',
'NearBeach.sprint',
'NearBeach.sprintobjectassignment',
'NearBeach.kanbanboard',
'NearBeach.kanbancolumn',
'NearBeach.kanbanlevel',
'NearBeach.kanbancard',
'NearBeach.document',
'NearBeach.documentpermission',
'NearBeach.tag',
'NearBeach.tagassignment',
'NearBeach.objectnote',
'NearBeach.scheduledobject',
'NearBeach.userjob',
'NearBeach.changetask',
'NearBeach.requestforchange',
'NearBeach.usersetting',
'NearBeach.listoftitle',
'NearBeach.objecttemplate',
'NearBeach.objecttemplategroup',
'NearBeach.publiclink',
'NearBeach.notification',
'NearBeach.objectassignment',
'NearBeach.bugclient',
'NearBeach.listofbugclient',
]
model_priority = {m: i for i, m in enumerate(model_order)}
new_objects.sort(key=lambda o: model_priority.get(o['model'], 999))
# Write new fixture
output_path = '/home/eric/workspaces/dataannotation/project-5/NearBeach/NearBeach/fixtures/NearBeach_doubled_setup.json'
with open(output_path, 'w') as f:
json.dump(new_objects, f, indent=2)
print(f"Written to {output_path}")
# Verify
with open(output_path) as f:
data = json.load(f)
from collections import Counter
models = Counter(obj['model'] for obj in data)
for model, count in models.most_common():
print(f' {model}: {count}')

Binary file not shown.

View File

@@ -0,0 +1,87 @@
Add a cross-project task list page at `/tasks/` to NearBeach. Today users can only find tasks by going through individual projects or kanban boards. This page gives them one place to see every task they're allowed to see, with filtering, sorting and pagination.
Build it as a server-rendered Django page: a view in `NearBeach/views/task_views.py`, a URL route, a filter form and a template. All page state lives in the query string (GET), so every state of the list has its own URL.
**Access**
- Limit the queryset in the database to tasks from projects the user's groups can access through `ObjectAssignment`. Follow the pattern in the existing `sprint_list` view, and never filter in the template. Superusers see all tasks.
- `user_level` is the user's highest task permission across their groups.
- Show "+ New Task" only when `user_level >= 3`.
- Show each row's "View" button only when `user_level >= 1`.
- The filters are always visible.
**Layout**
- **Header:** the title "All Tasks" on the left, and a "+ New Task" button (linking to `new_task`) on the right.
- **Below the header:** a filter sidebar on the left (about 280px) and the results on the right. Below 1024px wide, stack them into a single column.
**Filters**
All filters are in one GET form and are applied with an Apply button.
- **Status:** a checkbox for every `ListOfTaskStatus`, ordered by `task_status_sort_order`. More than one can be ticked. The parameter `status` holds the `task_status_id` and can repeat.
- **Assignee:** a dropdown with "All Assignees", then the users with task access in the current user's accessible projects, then "Unassigned".
- The parameter `assignee` holds the user id.
- `0` means unassigned (`task_assigned_to__isnull=True`).
- **Project:** a dropdown with "All Projects", then the projects the user can access through their groups. The parameter `project` holds the `project_id`.
- **Date range:** two optional date inputs that work independently.
- `start_date` filters `task_start_date >= value`.
- `end_date` filters `task_end_date <= value`.
- **Buttons:** "Clear Filters" is a link to `/tasks/`, so it drops every parameter. "Apply" submits the form.
**Results area**
- **Top row:**
- Left: "Showing X–Y of Z tasks", using the paginator's numbers.
- Right: a page-size dropdown with 10, 25, 50 and 100 (default 25, parameter `page_size`).
- Page size is the only control that submits as soon as it changes. It keeps the active filters and sort.
- **Table:** nine columns, in this order:
1. **Title:** the task's short description in bold, with `#T-{task_id}` in small muted text below it.
2. **Status:** a badge showing the status name.
3. **Priority:** a small colored dot plus the label from `get_task_priority_display`.
4. **Assignee:** the username, or `-` if there isn't one.
5. **Project:** the project name.
6. **Start Date**, 7. **End Date** and 8. **Created:** all formatted `YYYY-MM-DD`.
9. **Actions:** a "View" button linking to `task_information` for that task. When the table scrolls sideways, keep this column pinned to the right edge.
- **Empty state:** when the queryset is empty, show one row spanning all columns, with "No tasks found" centered.
**Sorting**
- **Which columns:** every column except Actions can be sorted.
- **URL format:** `?sort=field` sorts ascending and shows ▲ in the header. `?sort=-field` sorts descending and shows ▼.
- **Clicking:** clicking the active column flips the direction. Clicking a different column sorts it ascending.
- **Default:** `-date_created`.
- **Allowed values:** only these (anything else falls back to the default):
- `task_short_description`
- `task_status__task_status_sort_order`
- `task_priority`
- `task_assigned_to__username`
- `project`: map this to the project lookup through `ObjectAssignment`
- `task_start_date`
- `task_end_date`
- `date_created`
- **Priority order:** `task_priority` is an `ObjectPriority` integer where 0 means Highest, so ascending puts Highest first.
**Pagination**
- **Page numbers:** use `Paginator.get_page()`, and `get_elided_page_range(on_each_side=2, on_ends=1)` for the page links.
- **Prev and Next:** "◀ Prev" is disabled on page 1 and "Next ▶" on the last page. Highlight the current page.
- **Keeping parameters:** every sort, page and page-size link keeps all the other active parameters.
- **Returning to page 1:** applying filters, changing the sort or changing the page size goes back to page 1.
- **Invalid page size:** any value other than 10, 25, 50 or 100 falls back to 25.
**Badge and priority classes**
- **Status badge:** the class comes from the status's higher-order status: `badge badge-{{ task_higher_order_status|lower }}`.
- `backlog`: New, Backlog
- `normal`: In Progress, Test/Review
- `blocked`: Blocked
- `closed`: Closed
- **Priority dot:** `priority-high` for Highest and High, `priority-normal` for Normal, and `priority-low` for Low and Lowest.
**Styling**
- Use the app's existing theme and Bootstrap classes, with no hard-coded colors.
- Add any new colors as `--nb-*` tokens in both the light and dark theme files. Put the page's styles in a new SCSS partial.
- **Color intent:**
- Badges: backlog beige, normal cyan, blocked pink, closed green.
- Priority dots: red for high, orange for normal, blue for low.
- We'll refine the look in later turns.
**Tests**
Add at least 10 tests under `NearBeach/tests/tests_views/tests_task/`. They should cover:
- each filter
- sorting, including an invalid sort value
- pagination and page size
- permissions: a user without access to a project must not see its tasks, and a superuser sees everything

View File

@@ -1,112 +0,0 @@
### 1. Task Description
NearBeach is a Django/Vue project management tool that currently has task detail views and task creation, but lacks a general task list view for users to see all their tasks across projects. Users must navigate through individual projects or kanban boards to find tasks, which is inefficient for project managers overseeing multiple projects. This task adds a dedicated 'tasks' page with filtering (status, assignee, project, date range), sortable columns, and pagination.
---
### 2. How to Judge Completion
Run the NearBeach setup commands (install, migrate, create superuser, runserver), log in as admin/password, and navigate to 'tasks' - a paginated table of tasks the user has permission to view should appear.
Test filtering by status, assignee, project, and date range; verify column headers toggle ascending/descending sort; confirm page size selector (10/25/50/100) and page navigation work.
- Run `python3 manage.py test NearBeach.tests.tests_views.tests_task` - 10+ new tests covering filtering, sorting, pagination, and permissions should pass.
- Create a second user without access to a project, log in as them, and verify they cannot see tasks from that project.
---
### 3. Other Notes for Reviewer
NearBeach uses a group-based permission system via ObjectAssignment - users only see tasks from projects their groups are assigned to. The implementation must filter the queryset at the database level (not in templates) following the existing pattern in 'sprint_list' view. Superusers bypass all filters. The task touches Django views, templates, URL routing, forms, and requires comprehensive tests to ensure permission filtering works correctly across all filter/sort/pagination combinations.
---
### Implementation Essentials (for Model)
**View & Template:**
- Server-rendered Django template (no Vue component): `NearBeach/templates/NearBeach/tasks/task_list.html`
- URL: `path("tasks/", views.task_list, name="task_list")`
- Follows `sprint_list` pattern for permission filtering via `ObjectAssignment` → `UserGroup` → `Group`
- All state (filters, sort, page, page_size) lives in the query string; every link rebuilds it
**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__gte=value` |
| `end_date` | `<input type="date">`, optional | `task_end_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
**Tests:** 12 test methods in `NearBeach/tests/tests_views/tests_task/test_task_list.py`

File diff suppressed because it is too large Load Diff

View File

@@ -1,190 +0,0 @@
# Security Audit Report - NearBeach
Based on my review of the NearBeach codebase, here are the security issues I found, organized by severity and category.
---
## 🔴 CRITICAL Issues
### 1. **Hardcoded SECRET_KEY in Repository** (`local/settings.py:23`)
```python
SECRET_KEY = 'jz0k8%ecl#k!z+(9+5(^do1w!11ysus21m41m@i9c#u)*vk($o'
```
- **Impact**: This is committed to the repo. In production, this would allow session hijacking, CSRF token forgery, and signing key compromise.
- **Project Idea**: Build a **Secret Scanner/Detector** that scans Django projects for hardcoded secrets and integrates with CI/CD pipelines.
### 2. **DEBUG = True in Settings** (`local/settings.py:26`)
```python
DEBUG = True
```
- **Impact**: Information disclosure (stack traces, env vars, SQL queries). Should never be True in production.
- **Project Idea**: **Django Security Configuration Validator** - automated check for production-ready settings.
---
## 🟠 HIGH Issues
### 3. **Missing File Type Validation on Upload** (`document_views.py`, `DocumentUploadForm`)
- **Issue**: No MIME type validation, no file extension allowlist/denylist. Only checks file size.
- **Risk**: Attackers can upload `.php`, `.jsp`, `.exe`, `.html` with JavaScript, `.svg` with scripts, polyglot files.
- **Location**: `NearBeach/forms.py:441-456` (`DocumentUploadForm`), `document_views.py:266-315`
- **Project Idea**: **Secure File Upload Framework for Django** - content-type sniffing, magic bytes validation, allowlist-based filtering, sandboxed storage.
### 4. **Path Traversal Risk in File Storage** (`private_media.py`, `LocalFileHandler`)
- **Issue**: Document key is UUID but file path construction uses user-controlled filename:
```python
# document_views.py:293
document_submit.document = f"private/{document_submit.document_key}/{file}"
```
If `file` name contains `../`, could escape private directory.
- **Project Idea**: **Path Traversal Scanner for Django FileField** - static analysis tool detecting unsafe path construction.
### 5. **No CSRF Protection on Some API Endpoints**
- **Issue**: REST Framework uses SessionAuthentication + BasicAuth but some views may lack CSRF enforcement for state-changing operations.
- **Check**: `REST_FRAMEWORK` config has `SessionAuthentication` but no explicit `CsrfViewMiddleware` enforcement on API.
### 6. **Insecure Direct Object Reference (IDOR) Potential**
- **Issue**: Public links (`public_views.py`) use UUID but API endpoints use numeric IDs directly in URLs without explicit ownership checks in all cases.
- **Example**: `urls_api_v0.py` routes like `project/(?P<project_id>[0-9]+)/...` rely solely on permission decorators.
- **Project Idea**: **IDOR Detection Tool for Django REST Framework** - automated testing for object-level authorization bypasses.
---
## 🟡 MEDIUM Issues
### 7. **Weak Password Reset Implementation** (`forms.py:623-634`)
```python
class PasswordResetForm(forms.Form):
password = forms.CharField(max_length=50, required=True)
username = forms.ModelChoiceField(queryset=USER_MODEL.objects.all(), required=True)
```
- **Issues**:
- No token-based reset (just username + new password)
- No rate limiting
- `max_length=50` on password is artificially limiting
- Admin can reset any user's password without audit trail
### 8. **Token Authentication with No Expiry** (`settings.py:104-117`)
```python
REST_KNOX = {
'TOKEN_TTL': None, # Tokens never expire!
'TOKEN_LIMIT_PER_USER': None, # Unlimited tokens per user
'AUTO_REFRESH': False,
}
```
- **Impact**: Stolen tokens provide permanent access. No rotation, no limit.
### 9. **SQL Injection Vectors via Raw Query Construction** (`search_objects.py`, `search_views.py`)
- **Issue**: Dynamic field names constructed via f-strings in queryset filters:
```python
# search_objects.py:122
results = results.filter(**{F"{data['title']}__icontains": split_row})
```
While `data['title']` comes from a hardcoded dict, the pattern is risky if extended.
- **Project Idea**: **Django ORM Safety Linter** - detects dynamic queryset construction patterns.
### 10. **Information Disclosure in Error Handling** (`middleware/HandleErrorPages.py`)
- **Issue**: In DEBUG mode, returns full Django error pages. Template middleware catches errors but could leak info in edge cases.
### 11. **Missing Security Headers**
- **Missing**: `SECURE_HSTS_SECONDS`, `SECURE_SSL_REDIRECT`, `SESSION_COOKIE_SECURE`, `CSRF_COOKIE_SECURE`, `X_FRAME_OPTIONS = 'DENY'` (only middleware), `SECURE_CONTENT_TYPE_NOSNIFF`
---
## 🔵 LOW / DEFENSE-IN-DEPTH Issues
### 12. **Permissive CORS/ALLOWED_HOSTS** (`settings.py:28`)
```python
ALLOWED_HOSTS = ['localhost', '0.0.0.0', '192.168.1.105']
```
- Should be restricted to actual production domains.
### 13. **No Rate Limiting on Auth Endpoints**
- Login, password reset, API token creation have no throttling.
### 14. **User Enumeration via Login** (`authentication/login_view.py`)
- Different error messages for "invalid password" vs "user not in groups" allows username enumeration.
### 15. **Insecure Default File Permissions** (`LocalFileHandler.py:101`)
```python
file_permissions = 0o755 # World-readable directories
```
- Private media directories world-readable.
### 16. **Missing Content Security Policy (CSP)**
- No CSP headers configured. TinyMCE usage increases XSS risk.
### 17. **Public Link UUID Guessability**
- Uses `uuid.uuid4()` which is cryptographically random, but no rate limiting on public link access.
---
## 📋 Summary Table
| # | Issue | Severity | File(s) |
|---|-------|----------|---------|
| 1 | Hardcoded SECRET_KEY | CRITICAL | `local/settings.py` |
| 2 | DEBUG=True in repo | CRITICAL | `local/settings.py` |
| 3 | Missing file type validation | HIGH | `forms.py`, `document_views.py` |
| 4 | Path traversal in file upload | HIGH | `document_views.py`, `private_media.py` |
| 5 | Missing CSRF on API | HIGH | `settings.py`, API views |
| 6 | IDOR potential | HIGH | `urls_api_v0.py`, permission decorators |
| 7 | Weak password reset | MEDIUM | `forms.py` |
| 8 | Non-expiring API tokens | MEDIUM | `settings.py` (REST_KNOX) |
| 9 | Dynamic queryset construction | MEDIUM | `search_objects.py` |
| 10 | Error info disclosure | MEDIUM | `middleware/HandleErrorPages.py` |
| 11 | Missing security headers | MEDIUM | `settings.py` |
| 12 | Permissive ALLOWED_HOSTS | LOW | `settings.py` |
| 13 | No rate limiting | LOW | Auth endpoints |
| 14 | User enumeration | LOW | `login_view.py` |
| 15 | Insecure file permissions | LOW | `LocalFileHandler.py` |
| 16 | Missing CSP | LOW | `settings.py` |
| 17 | Public link brute force | LOW | `public_views.py` |
---
## 🎯 Recommended Project Ideas
Based on these findings, here are **security tooling projects** you could build:
### 1. **Django Security Configuration Auditor**
Scans Django settings for production readiness (DEBUG, SECRET_KEY, security headers, password validators, token expiry, etc.)
### 2. **Secure File Upload Middleware for Django**
Drop-in replacement for FileField handling with:
- Magic byte detection (python-magic)
- MIME type allowlisting
- Filename sanitization
- Virus scanning integration (ClamAV)
- Path traversal prevention
### 3. **IDOR/Authorization Testing Framework for DRF**
Automated penetration testing tool that:
- Enumerates all API endpoints
- Tests object-level permissions with different user contexts
- Reports bypasses
### 4. **Django Secret Scanner**
Pre-commit/CI tool that detects:
- Hardcoded secrets (keys, passwords, tokens)
- Insecure settings patterns
- Debug configurations in production branches
### 5. **API Token Security Manager**
Enhances django-rest-knox with:
- Mandatory token expiry
- Token rotation policies
- Per-user token limits
- Suspicious activity detection (geo-velocity, concurrent sessions)
### 6. **Django ORM Injection Linter**
Static analysis for dangerous queryset patterns using dynamic field names.
---
## 📝 Next Steps for NearBeach Maintainers
1. **Immediate**: Move SECRET_KEY to environment variable, set DEBUG=False for production
2. **High Priority**: Implement file upload validation, add security headers, configure token expiry
3. **Medium**: Add rate limiting, fix password reset flow, implement CSP
4. **Ongoing**: Security code reviews, dependency scanning (bandit is already in dev deps - good!)

View File

@@ -0,0 +1,64 @@
# Selected Task for LiveCompare
## User Selection
- **Chosen**: Task List View with Filtering, Sorting, and Pagination
- **Score**: 25/25
- **Selection Date**: 2025-10-29
- **User Notes**: No modifications - use Task Brief as-is
## Complete Task Brief (Ready for LiveCompare)
### Task Description
NearBeach has task detail views (`task_information`) and task creation (`new_task`), but **no general task list view** for users to see all their tasks across projects. Users must navigate through individual projects or kanban boards to find tasks, which is inefficient for project managers overseeing multiple projects. A dedicated task list with filtering, sorting, and pagination is a standard project management feature that would significantly improve task discoverability and workflow.
### How to Judge Completion
In the repo folder, run the NearBeach start commands:
```bash
cd /workspace/nearbeach
python3 -m pip install --user --break-system-packages -r requirements.txt
python3 manage.py migrate
DJANGO_SUPERUSER_USERNAME=admin DJANGO_SUPERUSER_EMAIL=admin@example.com DJANGO_SUPERUSER_PASSWORD=password python3 manage.py createsuperuser --noinput
python3 manage.py runserver 0.0.0.0:8000
```
Then open `http://localhost:8000` and log in as `admin` / `password`.
**Verification steps:**
1. Navigate to `/tasks/` (new URL) - should display a paginated table of all tasks the user has permission to view
2. Test filtering: select a status from dropdown → table updates to show only tasks with that status
3. Test filtering: select an assignee → shows only tasks assigned to that user
4. Test filtering: select a project → shows only tasks in that project
5. Test filtering: enter date range for start/end dates → shows only tasks in range
6. Test sorting: click column headers (Created, Start Date, End Date, Priority, Status, Project) → toggles asc/desc
7. Test pagination: page size selector (10, 25, 50, 100) and page navigation work
8. Run `python3 manage.py test NearBeach.tests.tests_views.tests_task` - should pass with 10+ new tests covering filtering, sorting, pagination, and permissions
9. Verify permission enforcement: create a second user without access to a project, log in as that user, verify they cannot see tasks from that project
### Other Notes for Reviewer
NearBeach is an open-source Django/Vue project management tool for tracking requirements, projects, tasks, kanban boards, sprints, and RFCs. It's used by small teams to enterprises. The missing task list view is a significant UX gap - users currently have no central place to view all their tasks across projects. This task adds a core feature that project managers would expect, improving daily workflow for anyone managing multiple projects. The implementation touches Django views, templates, URL routing, the existing permission system (group-based via ObjectAssignment), and requires comprehensive tests to ensure permission filtering works correctly.
### Practical Details
- **Setup Commands**:
```bash
cd /workspace/nearbeach
python3 -m pip install --user --break-system-packages -r requirements.txt
python3 manage.py migrate
DJANGO_SUPERUSER_USERNAME=admin DJANGO_SUPERUSER_EMAIL=admin@example.com DJANGO_SUPERUSER_PASSWORD=password python3 manage.py createsuperuser --noinput
python3 manage.py runserver 0.0.0.0:8000
```
- **Key Files Likely Involved**:
- `NearBeach/views/task_views.py` - new `task_list` view function
- `NearBeach/urls.py` - new route for `/tasks/`
- `NearBeach/templates/NearBeach/tasks/task_list.html` - new template with filter sidebar, table, pagination
- `NearBeach/forms.py` - new `TaskFilterForm` for filter validation
- `NearBeach/tests/tests_views/tests_task/` - new test files
- **Potential Challenges**:
- Permission filtering must respect existing `ObjectAssignment` group-based system
- Filter combinations (status + assignee + project + date range) need efficient queryset construction
- Vue frontend may need updates if task list integrates with existing UI patterns
## Next Steps for User
1. Copy the Task Brief above into LiveCompare (Task Description, How to Judge Completion, Other Notes for Reviewer)
2. Download the NearBeach repo zip from the approved repos table in project-rules.md
3. Mount the archive in LiveCompare before your first message
4. Use the File Source URL: `https://github.com/nearbeach/NearBeach`
5. Start the conversation with the model using the Task Description as your first message

View File

@@ -1,57 +1,27 @@
### 1. Task Description
NearBeach's search tests need to be expanded. The HTTP-status checks can be made into deterministic, data-driven tests verifying actual search results. There are explicit TODOs in `NearBeach/tests/tests_views/tests_search/test_search.py` for customer, organisation search. Address those gaps and extend coverage across main, customer, organisation, group, user, sprint, tag, notification, and permission-set searches.
Add at least 20 new test methods covering matching semantics, result counts, pagination, permissions, and closed/include_closed behaviour wherever those features exist in the code. This is a test-engineering task, not a search redesign: preserve existing endpoint contract.
NearBeach is a Django/Vue project management tool that currently has task detail views and task creation, but lacks a general task list view for users to see all their tasks across projects. Users must navigate through individual projects or kanban boards to find tasks, which is inefficient for project managers overseeing multiple projects. This task adds a dedicated 'tasks' page with filtering (status, assignee, project, date range), sortable columns, and pagination.
---
### 2. How to Judge Completion
Start at the NearBeach repository root, create a virtual environment and install the project requirements plus coverage:
Run the NearBeach setup commands (install, migrate, create superuser, runserver), log in as admin/password, and navigate to 'tasks' - a paginated table of tasks the user has permission to view should appear.
```bash
python3 -m venv .venv
source .venv/bin/activate
python3 -m pip install -r requirements.txt
python3 -m pip install coverage
```
Test filtering by status, assignee, project, and date range; verify column headers toggle ascending/descending sort; confirm page size selector (10/25/50/100) and page navigation work.
Use the supplied repository's documented Django settings and database configuration. Run the existing search suite before making changes and record the baseline. Django's test runner should create and migrate its test database, so a running development server or manually created superuser is not required.
```bash
python3 manage.py test NearBeach.tests.tests_views.tests_search -v 2
```
After implementation, rerun that command. All existing search tests and at least 20 additional test methods should pass, with assertions on returned object identities, counts, or pagination metadata rather than only HTTP 200 responses. Inspect the tests to confirm that each of the nine search categories above has meaningful result assertions and that permission cases use ordinary users, not only superusers.
Run for coverage:
```bash
coverage run --source=NearBeach.views.search_views,NearBeach.views.search \
manage.py test NearBeach.tests.tests_views.tests_search
coverage report -m
```
Both `NearBeach/views/search_views.py` and `NearBeach/views/search/search_objects.py` should individually reach at least 80% statement coverage. Record the actual percentages and uncovered lines; do not omit difficult branches or alter coverage exclusions merely to meet the target.
Finally, run the complete existing suite:
```bash
python3 manage.py test
```
There should be no new failures. If the supplied environment has pre-existing failures or unavailable dependencies, document the exact commands, failures, and comparison with the baseline rather than reporting an unverified pass.
- Run `python3 manage.py test NearBeach.tests.tests_views.tests_task` - 10+ new tests covering filtering, sorting, pagination, and permissions should pass.
- Create a second user without access to a project, log in as them, and verify they cannot see tasks from that project.
---
### 3. Other Notes for Reviewer
NearBeach is an open-source Django/Vue project management application used to track projects, tasks, requirements, and related team activity. Search is a navigation mechanism across multiple business objects and administrative records, so a successful HTTP response alone does not show that users can find the right records or that restricted records stay hidden.
NearBeach uses a group-based permission system via ObjectAssignment - users only see tasks from projects their groups are assigned to. The implementation must filter the queryset at the database level (not in templates) following the existing pattern in 'sprint_list' view. Superusers bypass all filters. The task touches Django views, templates, URL routing, forms, and requires comprehensive tests to ensure permission filtering works correctly across all filter/sort/pagination combinations.
Research finds gaps explicitly documented as TODOs in the existing search tests. Deterministic fixtures and result-level assertions will make filtering and permission regressions visible, providing a safety net for future search maintenance without changing the user interface or adding a new search API. Permission tests are especially important because a search can return plausible results while silently including objects outside a user's authorised groups.
Endpoint capabilities and permission rules must be confirmed against the supplied repository before encoding expectations. Not every search type necessarily supports pagination, closed-state filtering, or the same ObjectAssignment-based visibility rules; tests should exercise the actual contract for each type rather than invent uniform behaviour. This document describes planned acceptance criteria, not evidence that the code has already been inspected, changed, or tested.

View File

@@ -0,0 +1,138 @@
# Task List Mockup — Implementation Notes
Companion to `task-list-mockup.html`. The mockup is the visual and structural target for the new `/tasks/` page; these notes cover the behavior and rules that the HTML can't show on its own.
---
## 1. Remove before building
These exist only so the mockup works as a standalone file:
- **Yellow "Mockup controls" bar**: simulates `user_level`, shows the empty state, and prints the GET URL the form would produce.
- **The entire `<script>` block**: client-side sorting, pagination, and the form/link interception. On the real page, all of this happens on the server through normal links and form submits.
- **Sample data**: the 10 rows, usernames, project names, task IDs, dates and "142 tasks" total are placeholders.
The Django template code lives in HTML comments throughout the mockup. Use those comments for the real template.
---
## 2. Rendering approach
- **Server-rendered:** a Django template with a plain GET form, as in the mockup.
- **URL as state:** all state (filters, sort, page, page size) lives in the query string.
- **Links:** every link rebuilds that query string.
---
## 3. Filters
All filters belong to one GET form (`action="/tasks/"`) and are applied with the **Apply** button.
| Param | Control | Query |
|---|---|---|
| `status` (repeatable) | Checkboxes; value = `task_status_id` | `task_status_id__in=[...]` |
| `assignee` | Select; value = user `id` | `task_assigned_to=<id>` |
| `assignee=0` | "Unassigned" option | `task_assigned_to__isnull=True` |
| `project` | Select; value = `project_id` | Tasks linked to that project via `ObjectAssignment` |
| `start_date` | `<input type="date">`, optional | `task_start_date >= value` |
| `end_date` | `<input type="date">`, optional | `task_end_date <= value` |
- **Empty values:** an empty field means no filter. Each date can be used without the other.
- **Assignee options:** "All Assignees", then the users with task access in the current user's accessible projects, then "Unassigned".
- **Project options:** "All Projects", then the projects the user can reach through their groups (`ObjectAssignment`).
- **Status options:** come from `ListOfTaskStatus`, ordered by `task_status_sort_order`.
- **Clear Filters:** a link to `/tasks/`, not a reset button. It drops every query parameter.
---
## 4. Sorting
| Column | `sort` value |
|---|---|
| Title | `task_short_description` |
| Status | `task_status__task_status_sort_order` (workflow order) |
| Priority | `task_priority` |
| Assignee | `task_assigned_to__username` |
| Project | `project` (alias; the view maps it to the project lookup via `ObjectAssignment`) |
| Start Date | `task_start_date` |
| End Date | `task_end_date` |
| Created | `date_created` |
- **Parameter format:** `?sort=field` sorts ascending (▲ on the header); `?sort=-field` sorts descending (▼).
- **Clicking headers:** clicking the active column flips its direction. Clicking a different column sorts it ascending.
- **Default:** `-date_created` (newest first).
- **Allowed values:** only the eight values above. Anything else falls back to the default; never pass raw input to `order_by`.
- **Priority:** ascending puts Highest (0) first, because lower numbers mean higher priority.
- **Header links:** keep all other active parameters and reset to page 1.
- **Current sort in the form:** a hidden `sort` input in the filter form carries the current sort, so Apply and page-size changes keep it.
---
## 5. Pagination
- **Page size:** `page_size` accepts 10, 25, 50 or 100, default 25. Any other value falls back to 25.
- The dropdown sits above the table but belongs to the filter form (`form="task-filter-form"`).
- It submits on change. This is the only control that submits automatically.
- **Page number:** use `Paginator.get_page()` so a bad or out-of-range `page` doesn't raise an error.
- **Page numbers shown:** `paginator.get_elided_page_range(page_obj.number, on_each_side=2, on_ends=1)`. With 6 or fewer pages, all are shown.
- **Prev / Next:** "◀ Prev" is disabled (a `<span>`, not a link) on page 1, and "Next ▶" on the last page.
- **Links:** every page link keeps all filters, sort and `page_size`, and changes only `page`.
- **Reset to page 1:** Apply, a page-size change, a sort click and Clear Filters all return to page 1.
- **Results count:** `Showing {{ page_obj.start_index }}–{{ page_obj.end_index }} of {{ page_obj.paginator.count }} tasks`.
---
## 6. Table rendering
- **Title:** `task_short_description` in bold, with `#T-{task_id}` in small muted text below it.
- **Status badge:** `badge badge-{{ task.task_status.task_higher_order_status|lower }}`.
| Class | Statuses |
|---|---|
| `badge-backlog` | New, Backlog |
| `badge-normal` | In Progress, Test/Review |
| `badge-blocked` | Blocked |
| `badge-closed` | Closed |
- **Priority:** an 8px dot plus the label from `{{ task.get_task_priority_display }}`. The class comes from the value.
| Class | Values |
|---|---|
| `priority-high` | 0 Highest, 1 High |
| `priority-normal` | 2 Normal |
| `priority-low` | 3 Low, 4 Lowest |
- **Assignee:** the username, or `-` if unassigned.
- **Dates:** formatted `Y-m-d`.
- **Actions:** a "View" button linking to `{% url 'task_information' task.task_id %}`.
- The Actions column (`col-actions`) is pinned to the table's right edge (`position: sticky`). The other columns scroll sideways inside the table container, so the page itself never scrolls sideways.
- **Empty state:** `{% empty %}` renders one row with `colspan="9"` and centered "No tasks found". The count reads "Showing 0–0 of 0 tasks".
---
## 7. Permissions
- **Database-level filtering:** the queryset is limited to tasks from projects the user's groups can reach through `ObjectAssignment`. Follow the existing `sprint_list` view, and never filter in the template.
- **Superusers:** they skip that filter and see every task and every UI element.
- **`user_level`:** the user's highest task permission across their groups.
| Element | Shown when |
|---|---|
| "+ New Task" (`{% url 'new_task' %}`) | `user_level >= 3` |
| "View" button | `user_level >= 1` |
| Filter sidebar | Always |
---
## 8. Styling and theme
- **Colors:** use the app's theme colors, not the hex values in the mockup. Those hex values only show what's intended: neutral surfaces, a blue primary, and the badge and priority color groups.
- Add a `--nb-*` token for each new color to **both** `src/sass/themes/_light_theme.scss` and `_dark_theme.scss`, and reference it with `var(--nb-...)`.
- The page must look right in both light and dark themes.
- Badge text and its background must stay readable in both themes.
- **Where new styles go:** a new partial `src/sass/components/_task_list.scss`, imported in `src/sass/main.scss`.
- **Existing classes to reuse:** `btn btn-primary`, `btn btn-secondary`, `form-control` and `badge`, plus the app's existing card and spacing styles.
- **Layout:**
- On desktop, a fixed-width sidebar (about 280px) sits beside the table.
- Below 1024px, the layout stacks into one column.
- Table cells use 12px 16px padding.

View File

@@ -0,0 +1,901 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Task List Mockup</title>
<style>
:root {
--page-bg: #f6f8fa;
--surface: #ffffff;
--text: #24292e;
--text-muted: #6a737d;
--border: #e1e4e8;
--primary: #0366d6;
--primary-hover: #0256b9;
--secondary-bg: #fafbfc;
--secondary-hover: #f3f4f6;
--demo-bg: #fff8c5;
--demo-border: #d4a72c;
}
* { box-sizing: border-box; }
body {
margin: 0;
background: var(--page-bg);
color: var(--text);
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
font-size: 14px;
line-height: 1.5;
}
/* ---------- Mockup-only controls (not part of the real UI) ---------- */
.demo-bar {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 8px 16px;
padding: 8px 16px;
background: var(--demo-bg);
border-bottom: 1px solid var(--demo-border);
font-size: 13px;
}
.demo-bar strong { font-weight: 600; }
.demo-bar select { padding: 2px 6px; font-size: 13px; }
.demo-output {
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
word-break: break-all;
}
/* ---------- Page ---------- */
.page {
max-width: 1400px;
margin: 0 auto;
padding: 16px;
}
/* Header bar */
.page-header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 16px;
padding-bottom: 16px;
margin-bottom: 16px;
border-bottom: 1px solid var(--border);
}
.page-header h1 {
margin: 0;
font-size: 24px;
font-weight: 600;
}
/* Two-column layout: sidebar left, table right; stacks below 1024px */
.layout {
display: grid;
grid-template-columns: 280px 1fr;
gap: 16px;
align-items: start;
}
@media (max-width: 1023.98px) {
.layout { grid-template-columns: 1fr; }
}
/* ---------- Buttons & form controls ---------- */
.btn {
display: inline-flex;
align-items: center;
justify-content: center;
padding: 6px 16px;
border: 1px solid transparent;
border-radius: 6px;
font-size: 14px;
font-weight: 500;
line-height: 20px;
text-decoration: none;
cursor: pointer;
white-space: nowrap;
}
.btn-primary {
background: var(--primary);
border-color: var(--primary);
color: #fff;
}
.btn-primary:hover { background: var(--primary-hover); }
.btn-secondary {
background: var(--secondary-bg);
border-color: var(--border);
color: var(--text);
}
.btn-secondary:hover { background: var(--secondary-hover); }
.form-control {
display: block;
width: 100%;
padding: 6px 8px;
border: 1px solid var(--border);
border-radius: 6px;
background: var(--surface);
color: var(--text);
font-size: 14px;
font-family: inherit;
}
.form-control:focus {
outline: none;
border-color: var(--primary);
box-shadow: 0 0 0 3px rgba(3, 102, 214, 0.2);
}
/* ---------- Sidebar filters ---------- */
.sidebar {
background: var(--surface);
border: 1px solid var(--border);
border-radius: 6px;
padding: 16px;
}
.filter-section + .filter-section {
margin-top: 16px;
padding-top: 16px;
border-top: 1px solid var(--border);
}
.filter-label {
display: block;
margin: 0 0 8px;
padding: 0;
font-size: 13px;
font-weight: 600;
}
fieldset.filter-section {
margin: 0;
padding: 0;
border: 0;
min-width: 0;
}
.filter-section + .filter-section { border-top: 1px solid var(--border); }
/* Float the legend so it doesn't sit inside the fieldset's top border */
fieldset.filter-section > legend { float: left; width: 100%; }
fieldset.filter-section > legend + * { clear: both; }
.checkbox-list {
display: flex;
flex-direction: column;
gap: 4px;
}
.checkbox-list label {
display: flex;
align-items: center;
gap: 8px;
cursor: pointer;
}
.date-field + .date-field { margin-top: 8px; }
.date-field span {
display: block;
margin-bottom: 4px;
font-size: 12px;
color: var(--text-muted);
}
.filter-actions {
display: flex;
gap: 8px;
}
.filter-actions .btn { flex: 1; }
/* ---------- Main area (placeholder until specified) ---------- */
.main {
background: var(--surface);
border: 1px solid var(--border);
border-radius: 6px;
padding: 16px;
min-width: 0;
}
/* Results header: count left, page size right */
.results-header {
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: space-between;
gap: 8px 16px;
margin-bottom: 16px;
}
.results-count { color: var(--text-muted); }
.results-count strong { color: var(--text); font-weight: 600; }
.page-size {
display: flex;
align-items: center;
gap: 8px;
color: var(--text-muted);
}
.page-size .form-control { width: auto; }
/* ---------- Data table ---------- */
.table-wrap {
overflow-x: auto;
border: 1px solid var(--border);
border-radius: 6px;
margin-bottom: 16px;
}
.task-table {
width: 100%;
border-collapse: collapse;
white-space: nowrap;
}
.task-table th,
.task-table td {
padding: 12px 16px;
text-align: left;
vertical-align: middle;
border-bottom: 1px solid var(--border);
}
.task-table thead th {
background: var(--secondary-bg);
font-size: 12px;
font-weight: 600;
color: var(--text-muted);
text-transform: uppercase;
letter-spacing: 0.03em;
}
.sort-link {
display: inline-flex;
align-items: center;
gap: 4px;
color: inherit;
text-decoration: none;
}
.sort-link:hover { color: var(--primary); }
th[aria-sort="ascending"] .sort-link,
th[aria-sort="descending"] .sort-link { color: var(--text); }
.sort-indicator { font-size: 10px; }
.task-table tbody tr:last-child td { border-bottom: 0; }
.task-table tbody tr:hover { background: var(--secondary-bg); }
.task-title { font-weight: 600; white-space: normal; min-width: 200px; }
.task-id { display: block; font-size: 12px; color: var(--text-muted); }
/* Status badge: base + modifier from ListOfTaskStatus.task_higher_order_status (lowercased) */
.badge {
display: inline-block;
padding: 2px 8px;
border-radius: 12px;
font-size: 12px;
font-weight: 500;
background: #eaecef;
color: var(--text);
}
/* Higher-order Backlog: New, Backlog */
.badge-backlog { background: #f5efe0; color: #7a1f1f; }
/* Higher-order Normal: In Progress, Test/Review */
.badge-normal { background: #cff4fc; color: #000000; }
/* Higher-order Blocked: Blocked */
.badge-blocked { background: #f8d7da; color: #7a1f1f; }
/* Higher-order Closed: Closed */
.badge-closed { background: #d4edda; color: #155724; }
/* Priority: 8px dot + label */
.priority { display: inline-flex; align-items: center; gap: 6px; }
.priority-indicator {
width: 8px;
height: 8px;
border-radius: 50%;
flex-shrink: 0;
}
/* Three color groups for ObjectPriority's five values:
0 Highest, 1 High -> high (red); 2 Normal -> normal (orange); 3 Low, 4 Lowest -> low (blue) */
.priority-high .priority-indicator { background: #cb2431; }
.priority-normal .priority-indicator { background: #e67e22; }
.priority-low .priority-indicator { background: #1e88e5; }
.btn-sm { padding: 3px 12px; font-size: 12px; }
/* Actions column pinned to the right edge while the other columns scroll */
.task-table .col-actions {
position: sticky;
right: 0;
background: var(--surface);
box-shadow: inset 1px 0 0 var(--border), -6px 0 6px -6px rgba(0, 0, 0, 0.15);
}
.task-table thead .col-actions { background: var(--secondary-bg); }
.task-table tbody tr:hover .col-actions { background: var(--secondary-bg); }
/* ---------- Pagination ---------- */
.pagination {
display: flex;
justify-content: center;
}
.pagination-list {
display: flex;
flex-wrap: wrap;
justify-content: center;
gap: 4px;
margin: 0;
padding: 0;
list-style: none;
}
.page-link {
display: inline-flex;
align-items: center;
justify-content: center;
min-width: 32px;
height: 32px;
padding: 0 10px;
border: 1px solid var(--border);
border-radius: 6px;
background: var(--surface);
color: var(--text);
text-decoration: none;
}
a.page-link:hover { background: var(--secondary-hover); }
.page-link.active {
background: var(--primary);
border-color: var(--primary);
color: #fff;
font-weight: 600;
}
.page-link.disabled {
color: var(--text-muted);
background: var(--secondary-bg);
opacity: 0.6;
cursor: not-allowed;
}
.page-ellipsis {
border-color: transparent;
background: none;
color: var(--text-muted);
}
/* Empty state: single row spanning all columns */
.empty-row td {
padding: 32px 16px;
text-align: center;
color: var(--text-muted);
}
.placeholder {
color: var(--text-muted);
text-align: center;
border: 2px dashed var(--border);
border-radius: 6px;
padding: 32px 16px;
width: 100%;
}
</style>
</head>
<body>
<!-- =====================================================================
MOCKUP-ONLY CONTROLS — not part of the real UI. Remove when building.
===================================================================== -->
<div class="demo-bar" role="region" aria-label="Mockup controls">
<strong>Mockup controls</strong>
<label>
Simulated user_level:
<select id="demo-user-level">
<option value="0">0 – no access</option>
<option value="1">1 – read</option>
<option value="2">2 – edit</option>
<option value="3">3 – create</option>
<option value="4" selected>4 – full</option>
</select>
</label>
<label><input type="checkbox" id="demo-empty"> Show empty state</label>
<span>Last submitted query: <span class="demo-output" id="demo-query">(none)</span></span>
</div>
<div class="page">
<!-- Header bar -->
<header class="page-header">
<h1>All Tasks</h1>
<!-- {% if user_level >= 3 %} href="{% url 'new_task' %}" -->
<a href="/new_task/" class="btn btn-primary" id="new-task-btn" data-requires-user-level="3">+ New Task</a>
<!-- {% endif %} -->
</header>
<div class="layout">
<!-- ================= Sidebar filters ================= -->
<aside class="sidebar" aria-label="Filters">
<!-- All filters in a single GET form; selections appear in the URL query string. -->
<form method="get" action="/tasks/" id="task-filter-form">
<!-- Carries the active sort so Apply and page-size changes keep it. Default: -date_created -->
<input type="hidden" name="sort" id="sort-input" value="-date_created">
<!-- 1. Status — multi-select checkboxes; values come from ListOfTaskStatus -->
<fieldset class="filter-section">
<legend class="filter-label">Status</legend>
<div class="checkbox-list">
<!-- {% for status in status_options %}
<input type="checkbox" name="status" value="{{ status.task_status_id }}"> {{ status.task_status }} -->
<label><input type="checkbox" name="status" value="1"> New</label>
<label><input type="checkbox" name="status" value="2"> Backlog</label>
<label><input type="checkbox" name="status" value="3"> Blocked</label>
<label><input type="checkbox" name="status" value="4"> In Progress</label>
<label><input type="checkbox" name="status" value="5"> Test/Review</label>
<label><input type="checkbox" name="status" value="6"> Closed</label>
<!-- {% endfor %} -->
</div>
</fieldset>
<!-- 2. Assignee — "All Assignees" + users with task access in the
current user's accessible projects + "Unassigned" -->
<div class="filter-section">
<label class="filter-label" for="filter-assignee">Assignee</label>
<select class="form-control" id="filter-assignee" name="assignee">
<option value="">All Assignees</option>
<!-- {% for user in assignee_options %}
<option value="{{ user.id }}">{{ user.username }}</option> -->
<option value="2">alex.chen</option>
<option value="3">jordan.lee</option>
<option value="4">riley.ng</option>
<option value="5">sam.patel</option>
<option value="6">taylor.kim</option>
<!-- {% endfor %} -->
<!-- assignee=0 -> view filters task_assigned_to__isnull=True -->
<option value="0">Unassigned</option>
</select>
</div>
<!-- 3. Project — "All Projects" + projects the user has
ObjectAssignment access to (via their groups) -->
<div class="filter-section">
<label class="filter-label" for="filter-project">Project</label>
<select class="form-control" id="filter-project" name="project">
<option value="">All Projects</option>
<!-- {% for project in project_options %}
<option value="{{ project.project_id }}">{{ project.project_name }}</option> -->
<option value="1">Website Redesign</option>
<option value="2">Mobile App v2</option>
<option value="3">Data Migration</option>
<option value="4">Internal Tools</option>
<!-- {% endfor %} -->
</select>
</div>
<!-- 4. Date Range — both optional, independently
Start Date: task_start_date >= value
End Date: task_end_date <= value -->
<fieldset class="filter-section">
<legend class="filter-label">Date Range</legend>
<label class="date-field">
<span>Start Date</span>
<input class="form-control" type="date" name="start_date">
</label>
<label class="date-field">
<span>End Date</span>
<input class="form-control" type="date" name="end_date">
</label>
</fieldset>
<!-- 5. Actions -->
<div class="filter-section">
<div class="filter-actions">
<!-- Link (not a reset button) so all query params are cleared -->
<a href="/tasks/" class="btn btn-secondary" id="clear-filters">Clear Filters</a>
<button type="submit" class="btn btn-primary">Apply</button>
</div>
</div>
</form>
</aside>
<!-- ================= Main table area ================= -->
<main class="main">
<!-- Results header -->
<div class="results-header">
<!-- Uses paginator: page_obj.start_index, page_obj.end_index, paginator.count -->
<div class="results-count">
Showing <strong id="range-start">1</strong>–<strong id="range-end">25</strong>
of <strong id="total-count">142</strong> tasks
<!-- Showing {{ page_obj.start_index }}–{{ page_obj.end_index }} of {{ page_obj.paginator.count }} tasks -->
</div>
<!-- Belongs to the filter form (form= attribute) so changing it keeps all
active filters; auto-submits on change. Default 25. -->
<label class="page-size">
Page size
<select class="form-control" name="page_size" id="page-size" form="task-filter-form">
<option value="10">10</option>
<option value="25" selected>25</option>
<option value="50">50</option>
<option value="100">100</option>
</select>
</label>
</div>
<!-- Data table. Sample rows are a subset of one page; the real page renders page_obj.
Sorting: click a sortable header to toggle ASC/DESC.
?sort=field -> ascending (header shows ▲)
?sort=-field -> descending (header shows ▼)
Clicking a different column starts ascending.
Status sorts by workflow order (task_status__task_status_sort_order), not alphabetically. Default sort: -date_created (newest first).
Each header link keeps all other active query params (filters, page_size). -->
<div class="table-wrap">
<table class="task-table">
<thead>
<tr>
<th data-sort-field="task_short_description"><a class="sort-link" href="?sort=task_short_description">Title <span class="sort-indicator"></span></a></th>
<th data-sort-field="task_status__task_status_sort_order"><a class="sort-link" href="?sort=task_status__task_status_sort_order">Status <span class="sort-indicator"></span></a></th>
<th data-sort-field="task_priority"><a class="sort-link" href="?sort=task_priority">Priority <span class="sort-indicator"></span></a></th>
<th data-sort-field="task_assigned_to__username"><a class="sort-link" href="?sort=task_assigned_to__username">Assignee <span class="sort-indicator"></span></a></th>
<th data-sort-field="project"><a class="sort-link" href="?sort=project">Project <span class="sort-indicator"></span></a></th>
<th data-sort-field="task_start_date"><a class="sort-link" href="?sort=task_start_date">Start Date <span class="sort-indicator"></span></a></th>
<th data-sort-field="task_end_date"><a class="sort-link" href="?sort=task_end_date">End Date <span class="sort-indicator"></span></a></th>
<th data-sort-field="date_created" aria-sort="descending"><a class="sort-link" href="?sort=date_created">Created <span class="sort-indicator">▼</span></a></th>
<th class="col-actions">Actions</th>
</tr>
</thead>
<tbody>
<!-- {% for task in page_obj %}
<tr>
<td class="task-title">{{ task.task_short_description }}<span class="task-id">#T-{{ task.task_id }}</span></td>
<td><span class="badge badge-{{ task.task_status.task_higher_order_status|lower }}">{{ task.task_status.task_status }}</span></td>
<td><span class="priority priority-{% if task.task_priority <= 1 %}high{% elif task.task_priority == 2 %}normal{% else %}low{% endif %}"><span class="priority-indicator"></span>{{ task.get_task_priority_display }}</span></td>
<td>{{ assigned username|default:"-" }}</td>
<td>{{ project name }}</td>
<td>{{ task.task_start_date|date:"Y-m-d" }}</td>
<td>{{ task.task_end_date|date:"Y-m-d" }}</td>
<td>{{ task.date_created|date:"Y-m-d" }}</td>
<td class="col-actions">{% if user_level >= 1 %}<a class="btn btn-secondary btn-sm" href="{% url 'task_information' task.task_id %}">View</a>{% endif %}</td>
</tr>
{% empty %}
<tr class="empty-row"><td colspan="9">No tasks found</td></tr>
{% endfor %} -->
<tr>
<td class="task-title">Migrate customer table to new schema<span class="task-id">#T-1287</span></td>
<td><span class="badge badge-normal">In Progress</span></td>
<td><span class="priority priority-high"><span class="priority-indicator"></span>Highest</span></td>
<td>sam.patel</td>
<td>Data Migration</td>
<td>2026-10-20</td>
<td>2026-11-14</td>
<td>2026-10-31</td>
<td class="col-actions"><a class="btn btn-secondary btn-sm" data-requires-user-level="1" href="/task_information/1287/">View</a></td>
</tr>
<tr>
<td class="task-title">Design new pricing page layout<span class="task-id">#T-1284</span></td>
<td><span class="badge badge-backlog">New</span></td>
<td><span class="priority priority-normal"><span class="priority-indicator"></span>Normal</span></td>
<td>-</td>
<td>Website Redesign</td>
<td>2026-11-03</td>
<td>2026-11-21</td>
<td>2026-10-30</td>
<td class="col-actions"><a class="btn btn-secondary btn-sm" data-requires-user-level="1" href="/task_information/1284/">View</a></td>
</tr>
<tr>
<td class="task-title">Push notification permissions on Android 15<span class="task-id">#T-1279</span></td>
<td><span class="badge badge-blocked">Blocked</span></td>
<td><span class="priority priority-high"><span class="priority-indicator"></span>High</span></td>
<td>jordan.lee</td>
<td>Mobile App v2</td>
<td>2026-10-13</td>
<td>2026-10-31</td>
<td>2026-10-28</td>
<td class="col-actions"><a class="btn btn-secondary btn-sm" data-requires-user-level="1" href="/task_information/1279/">View</a></td>
</tr>
<tr>
<td class="task-title">Review accessibility audit findings<span class="task-id">#T-1275</span></td>
<td><span class="badge badge-normal">Test/Review</span></td>
<td><span class="priority priority-normal"><span class="priority-indicator"></span>Normal</span></td>
<td>alex.chen</td>
<td>Website Redesign</td>
<td>2026-10-06</td>
<td>2026-10-24</td>
<td>2026-10-25</td>
<td class="col-actions"><a class="btn btn-secondary btn-sm" data-requires-user-level="1" href="/task_information/1275/">View</a></td>
</tr>
<tr>
<td class="task-title">Add CSV export to admin reports<span class="task-id">#T-1270</span></td>
<td><span class="badge badge-backlog">Backlog</span></td>
<td><span class="priority priority-low"><span class="priority-indicator"></span>Lowest</span></td>
<td>-</td>
<td>Internal Tools</td>
<td>2026-11-17</td>
<td>2026-12-05</td>
<td>2026-10-22</td>
<td class="col-actions"><a class="btn btn-secondary btn-sm" data-requires-user-level="1" href="/task_information/1270/">View</a></td>
</tr>
<tr>
<td class="task-title">Set up staging environment for v2 beta<span class="task-id">#T-1266</span></td>
<td><span class="badge badge-closed">Closed</span></td>
<td><span class="priority priority-high"><span class="priority-indicator"></span>High</span></td>
<td>taylor.kim</td>
<td>Mobile App v2</td>
<td>2026-09-29</td>
<td>2026-10-10</td>
<td>2026-10-18</td>
<td class="col-actions"><a class="btn btn-secondary btn-sm" data-requires-user-level="1" href="/task_information/1266/">View</a></td>
</tr>
<tr>
<td class="task-title">Validate migrated invoice totals<span class="task-id">#T-1261</span></td>
<td><span class="badge badge-normal">Test/Review</span></td>
<td><span class="priority priority-high"><span class="priority-indicator"></span>Highest</span></td>
<td>riley.ng</td>
<td>Data Migration</td>
<td>2026-10-01</td>
<td>2026-10-17</td>
<td>2026-10-15</td>
<td class="col-actions"><a class="btn btn-secondary btn-sm" data-requires-user-level="1" href="/task_information/1261/">View</a></td>
</tr>
<tr>
<td class="task-title">Refresh onboarding illustrations<span class="task-id">#T-1258</span></td>
<td><span class="badge badge-normal">In Progress</span></td>
<td><span class="priority priority-low"><span class="priority-indicator"></span>Low</span></td>
<td>alex.chen</td>
<td>Website Redesign</td>
<td>2026-10-12</td>
<td>2026-11-07</td>
<td>2026-10-11</td>
<td class="col-actions"><a class="btn btn-secondary btn-sm" data-requires-user-level="1" href="/task_information/1258/">View</a></td>
</tr>
<tr>
<td class="task-title">Clean up unused feature flags<span class="task-id">#T-1252</span></td>
<td><span class="badge badge-backlog">Backlog</span></td>
<td><span class="priority priority-normal"><span class="priority-indicator"></span>Normal</span></td>
<td>sam.patel</td>
<td>Internal Tools</td>
<td>2026-11-24</td>
<td>2026-12-12</td>
<td>2026-10-08</td>
<td class="col-actions"><a class="btn btn-secondary btn-sm" data-requires-user-level="1" href="/task_information/1252/">View</a></td>
</tr>
<tr>
<td class="task-title">Offline mode for task checklist<span class="task-id">#T-1247</span></td>
<td><span class="badge badge-backlog">New</span></td>
<td><span class="priority priority-low"><span class="priority-indicator"></span>Lowest</span></td>
<td>-</td>
<td>Mobile App v2</td>
<td>2026-12-01</td>
<td>2026-12-19</td>
<td>2026-10-04</td>
<td class="col-actions"><a class="btn btn-secondary btn-sm" data-requires-user-level="1" href="/task_information/1247/">View</a></td>
</tr>
<!-- Empty state: rendered by {% empty %} when the queryset has no tasks -->
<tr class="empty-row" id="empty-row" hidden>
<td colspan="9">No tasks found</td>
</tr>
</tbody>
</table>
</div>
<!-- Pagination footer.
"◀ Prev" disabled on page 1, "Next ▶" disabled on the last page.
Page numbers come from paginator.get_elided_page_range(page_obj.number, on_each_side=2, on_ends=1),
e.g. 1 … 6 7 [8] 9 10 … 15; with 6 or fewer pages, all are shown.
Every link keeps all active filters, sort and page_size, changing only page
(e.g. {% querystring page=n %} on Django 5.1+, or rebuild from request.GET).
{% if page_obj.has_previous %}<a class="page-link" href="?{...}page={{ page_obj.previous_page_number }}">◀ Prev</a>
{% else %}<span class="page-link disabled" aria-disabled="true">◀ Prev</span>{% endif %}
{% for n in elided_page_range %}
{% if n == page_obj.paginator.ELLIPSIS %}<span class="page-link page-ellipsis">…</span>
{% elif n == page_obj.number %}<span class="page-link active" aria-current="page">{{ n }}</span>
{% else %}<a class="page-link" href="?{...}page={{ n }}">{{ n }}</a>{% endif %}
{% endfor %}
{% if page_obj.has_next %}<a class="page-link" href="?{...}page={{ page_obj.next_page_number }}">Next ▶</a>
{% else %}<span class="page-link disabled" aria-disabled="true">Next ▶</span>{% endif %} -->
<nav class="pagination" aria-label="Pagination">
<ul class="pagination-list" id="pagination">
<li><span class="page-link disabled" aria-disabled="true">◀ Prev</span></li>
<li><span class="page-link active" aria-current="page">1</span></li>
<li><a class="page-link" href="?sort=-date_created&amp;page_size=25&amp;page=2">2</a></li>
<li><a class="page-link" href="?sort=-date_created&amp;page_size=25&amp;page=3">3</a></li>
<li><a class="page-link" href="?sort=-date_created&amp;page_size=25&amp;page=4">4</a></li>
<li><a class="page-link" href="?sort=-date_created&amp;page_size=25&amp;page=5">5</a></li>
<li><a class="page-link" href="?sort=-date_created&amp;page_size=25&amp;page=6">6</a></li>
<li><a class="page-link" href="?sort=-date_created&amp;page_size=25&amp;page=2">Next ▶</a></li>
</ul>
</nav>
</main>
</div>
</div>
<script>
// Mockup-only behaviour. The real page relies on the server for all of this.
(function () {
var levelSelect = document.getElementById('demo-user-level');
var form = document.getElementById('task-filter-form');
var clearLink = document.getElementById('clear-filters');
var queryOut = document.getElementById('demo-query');
// "+ New Task" needs user_level >= 3; "View" needs user_level >= 1.
function applyUserLevel() {
var level = Number(levelSelect.value);
document.querySelectorAll('[data-requires-user-level]').forEach(function (el) {
el.hidden = level < Number(el.dataset.requiresUserLevel);
});
}
levelSelect.addEventListener('change', applyUserLevel);
applyUserLevel();
// Standalone file has no server: show the GET URL instead of navigating.
function buildQuery(page) {
var params = new URLSearchParams();
new FormData(form).forEach(function (value, key) {
if (value !== '') params.append(key, value);
});
if (page) params.set('page', page);
return params.toString();
}
function showQuery(page) {
var qs = buildQuery(page);
queryOut.textContent = form.getAttribute('action') + (qs ? '?' + qs : '');
}
// Applying filters returns to page 1.
form.addEventListener('submit', function (e) {
e.preventDefault();
currentPage = 1;
renderPagination();
showQuery();
});
// Sorting: toggle ASC/DESC on the clicked column; a new column starts ASC.
var sortInput = document.getElementById('sort-input');
var tbody = document.querySelector('.task-table tbody');
var sortHeaders = Array.prototype.slice.call(document.querySelectorAll('.task-table th[data-sort-field]'));
// ObjectPriority values: ascending puts Highest (0) first
var PRIORITY_RANK = { Highest: 0, High: 1, Normal: 2, Low: 3, Lowest: 4 };
// ListOfTaskStatus.task_status_sort_order from the seed data
var STATUS_SORT_ORDER = { 'New': 1, 'Backlog': 2, 'Blocked': 3, 'In Progress': 4, 'Test/Review': 5, 'Closed': 6 };
function renderSort() {
var sort = sortInput.value;
var desc = sort.charAt(0) === '-';
var field = desc ? sort.slice(1) : sort;
var activeIndex = -1;
sortHeaders.forEach(function (th) {
var active = th.dataset.sortField === field;
th.querySelector('.sort-indicator').textContent = active ? (desc ? '▼' : '▲') : '';
if (active) {
th.setAttribute('aria-sort', desc ? 'descending' : 'ascending');
activeIndex = th.cellIndex;
} else {
th.removeAttribute('aria-sort');
}
});
if (activeIndex < 0) return;
// Mockup-only: reorder sample rows. The real page sorts the queryset server-side.
var emptyRow = document.getElementById('empty-row');
var rows = Array.prototype.slice.call(tbody.querySelectorAll('tr:not(.empty-row)'));
rows.sort(function (a, b) {
var x = a.cells[activeIndex].textContent.trim();
var y = b.cells[activeIndex].textContent.trim();
var cmp = field === 'task_priority' ? PRIORITY_RANK[x] - PRIORITY_RANK[y]
: field === 'task_status__task_status_sort_order' ? STATUS_SORT_ORDER[x] - STATUS_SORT_ORDER[y]
: x.localeCompare(y);
return desc ? -cmp : cmp;
});
rows.forEach(function (row) { tbody.insertBefore(row, emptyRow); });
}
sortHeaders.forEach(function (th) {
th.querySelector('.sort-link').addEventListener('click', function (e) {
e.preventDefault();
var field = th.dataset.sortField;
sortInput.value = sortInput.value === field ? '-' + field : field;
renderSort();
currentPage = 1;
renderPagination();
showQuery();
});
});
// Pagination. Mockup has a fixed sample total; every page shows the same sample rows.
var SAMPLE_TOTAL = 142;
var currentPage = 1;
var pageSize = document.getElementById('page-size');
var demoEmpty = document.getElementById('demo-empty');
var pagination = document.getElementById('pagination');
function totalTasks() { return demoEmpty.checked ? 0 : SAMPLE_TOTAL; }
function numPages() { return Math.max(1, Math.ceil(totalTasks() / Number(pageSize.value))); }
// Same output as Django's Paginator.get_elided_page_range(number, on_each_side=2, on_ends=1).
function elidedPageRange(number, count) {
var onEachSide = 2, onEnds = 1, out = [], i;
if (count <= (onEachSide + onEnds) * 2) {
for (i = 1; i <= count; i++) out.push(i);
return out;
}
if (number > 1 + onEachSide + onEnds + 1) {
for (i = 1; i <= onEnds; i++) out.push(i);
out.push('…');
for (i = number - onEachSide; i <= number; i++) out.push(i);
} else {
for (i = 1; i <= number; i++) out.push(i);
}
if (number < count - onEachSide - onEnds - 1) {
for (i = number + 1; i <= number + onEachSide; i++) out.push(i);
out.push('…');
for (i = count - onEnds + 1; i <= count; i++) out.push(i);
} else {
for (i = number + 1; i <= count; i++) out.push(i);
}
return out;
}
function pageItem(label, page, kind) {
var li = document.createElement('li');
var el;
if (kind === 'link') {
el = document.createElement('a');
el.href = '?' + buildQuery(page);
el.dataset.page = page;
} else {
el = document.createElement('span');
if (kind === 'disabled') el.setAttribute('aria-disabled', 'true');
if (kind === 'active') el.setAttribute('aria-current', 'page');
}
el.className = 'page-link' + (kind === 'link' ? '' : ' ' + (kind === 'ellipsis' ? 'page-ellipsis' : kind));
el.textContent = label;
li.appendChild(el);
return li;
}
function renderPagination() {
var total = totalTasks();
var size = Number(pageSize.value);
var count = numPages();
if (currentPage > count) currentPage = count;
document.getElementById('range-start').textContent = total ? (currentPage - 1) * size + 1 : 0;
document.getElementById('range-end').textContent = Math.min(currentPage * size, total);
document.getElementById('total-count').textContent = total;
pagination.innerHTML = '';
pagination.appendChild(currentPage > 1
? pageItem('◀ Prev', currentPage - 1, 'link')
: pageItem('◀ Prev', null, 'disabled'));
elidedPageRange(currentPage, count).forEach(function (n) {
if (n === '…') pagination.appendChild(pageItem('…', null, 'ellipsis'));
else if (n === currentPage) pagination.appendChild(pageItem(String(n), null, 'active'));
else pagination.appendChild(pageItem(String(n), n, 'link'));
});
pagination.appendChild(currentPage < count
? pageItem('Next ▶', currentPage + 1, 'link')
: pageItem('Next ▶', null, 'disabled'));
}
pagination.addEventListener('click', function (e) {
var link = e.target.closest('a.page-link');
if (!link) return;
e.preventDefault();
currentPage = Number(link.dataset.page);
renderPagination();
showQuery(currentPage);
});
// Page size auto-submits on change and returns to page 1.
pageSize.addEventListener('change', function () {
form.requestSubmit();
});
// Mockup-only: preview the empty state (paginator gives 0–0 of 0, one page).
demoEmpty.addEventListener('change', function () {
tbody.querySelectorAll('tr:not(.empty-row)').forEach(function (row) { row.hidden = demoEmpty.checked; });
document.getElementById('empty-row').hidden = !demoEmpty.checked;
currentPage = 1;
renderPagination();
});
renderPagination();
clearLink.addEventListener('click', function (e) {
e.preventDefault();
form.reset();
sortInput.value = '-date_created';
renderSort();
currentPage = 1;
renderPagination();
queryOut.textContent = clearLink.getAttribute('href');
});
})();
</script>
</body>
</html>

View File

@@ -0,0 +1,312 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>NearBeach - Task List View Wireframe</title>
<style>
* { box-sizing: border-box; margin: 0; padding: 0; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; }
body { background: #f5f6f8; min-height: 100vh; padding: 20px; }
.container { max-width: 1400px; margin: 0 auto; background: white; border-radius: 8px; box-shadow: 0 1px 3px rgba(0,0,0,0.1); overflow: hidden; }
/* Header */
.header { padding: 20px 24px; border-bottom: 1px solid #e1e4e8; display: flex; justify-content: space-between; align-items: center; }
.header h1 { font-size: 1.5rem; font-weight: 600; color: #24292e; }
.btn { padding: 8px 16px; border-radius: 6px; font-size: 0.875rem; font-weight: 500; cursor: pointer; border: none; transition: all 0.15s; }
.btn-primary { background: #0366d6; color: white; }
.btn-primary:hover { background: #0256c7; }
.btn-secondary { background: #fafbfc; color: #24292e; border: 1px solid #e1e4e8; }
.btn-secondary:hover { background: #f3f4f6; }
/* Main Layout */
.main { display: flex; min-height: 600px; }
/* Filter Sidebar */
.sidebar { width: 280px; border-right: 1px solid #e1e4e8; padding: 20px; background: #fafbfc; overflow-y: auto; }
.filter-section { margin-bottom: 24px; }
.filter-section h3 { font-size: 0.75rem; font-weight: 600; text-transform: uppercase; letter-spacing: 0.5px; color: #586069; margin-bottom: 12px; }
.form-group { margin-bottom: 16px; }
.form-group label { display: block; font-size: 0.875rem; font-weight: 500; color: #24292e; margin-bottom: 6px; }
.form-control { width: 100%; padding: 8px 12px; border: 1px solid #e1e4e8; border-radius: 6px; font-size: 0.875rem; background: white; }
.form-control:focus { outline: none; border-color: #0366d6; box-shadow: 0 0 0 3px rgba(3,102,214,0.15); }
.checkbox-group { display: flex; flex-direction: column; gap: 8px; }
.checkbox-label { display: flex; align-items: center; gap: 8px; font-size: 0.875rem; color: #24292e; cursor: pointer; }
.checkbox-label input { width: 16px; height: 16px; accent-color: #0366d6; }
.date-range { display: flex; gap: 8px; }
.date-range .form-control { flex: 1; }
.filter-actions { display: flex; gap: 8px; margin-top: 24px; padding-top: 16px; border-top: 1px solid #e1e4e8; }
/* Table Area */
.table-area { flex: 1; padding: 20px 24px; overflow-x: auto; }
.table-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 16px; }
.results-info { font-size: 0.875rem; color: #586069; }
.page-size select { padding: 6px 10px; border: 1px solid #e1e4e8; border-radius: 6px; font-size: 0.875rem; background: white; }
table { width: 100%; border-collapse: collapse; font-size: 0.875rem; }
th { text-align: left; padding: 12px 16px; font-weight: 600; color: #586069; background: #fafbfc; border-bottom: 1px solid #e1e4e8; white-space: nowrap; cursor: pointer; user-select: none; transition: background 0.15s; }
th:hover { background: #f3f4f6; }
th.sorted-asc::after { content: " ▲"; font-size: 0.7rem; color: #0366d6; }
th.sorted-desc::after { content: " ▼"; font-size: 0.7rem; color: #0366d6; }
td { padding: 12px 16px; border-bottom: 1px solid #e1e4e8; color: #24292e; vertical-align: middle; }
tr:hover td { background: #fafbfc; }
/* Status Badges */
.badge { display: inline-block; padding: 3px 8px; border-radius: 12px; font-size: 0.75rem; font-weight: 500; text-transform: capitalize; }
.badge-todo { background: #fff3cd; color: #856404; }
.badge-in-progress { background: #cce5ff; color: #004085; }
.badge-review { background: #e2d9f3; color: #5a32a3; }
.badge-done { background: #d4edda; color: #155724; }
.badge-blocked { background: #f8d7da; color: #721c24; }
/* Priority */
.priority { display: inline-flex; align-items: center; gap: 4px; font-size: 0.8125rem; font-weight: 500; }
.priority-high { color: #cb2431; }
.priority-medium { color: #e67e22; }
.priority-low { color: #28a745; }
.priority-indicator { width: 8px; height: 8px; border-radius: 50%; }
.priority-high .priority-indicator { background: #cb2431; }
.priority-medium .priority-indicator { background: #e67e22; }
.priority-low .priority-indicator { background: #28a745; }
/* Pagination */
.pagination { display: flex; justify-content: center; align-items: center; gap: 4px; margin-top: 20px; padding-top: 16px; border-top: 1px solid #e1e4e8; }
.pagination button { min-width: 36px; height: 36px; padding: 0 12px; border: 1px solid #e1e4e8; background: white; border-radius: 6px; font-size: 0.875rem; color: #24292e; cursor: pointer; transition: all 0.15s; }
.pagination button:hover:not(:disabled) { background: #f3f4f6; border-color: #d1d5da; }
.pagination button.active { background: #0366d6; color: white; border-color: #0366d6; }
.pagination button:disabled { opacity: 0.5; cursor: not-allowed; }
.pagination .ellipsis { padding: 0 8px; color: #586069; }
/* Empty State */
.empty-state { text-align: center; padding: 60px 20px; color: #586069; }
.empty-state svg { width: 64px; height: 64px; margin-bottom: 16px; opacity: 0.5; }
.empty-state h3 { font-size: 1.125rem; font-weight: 600; color: #24292e; margin-bottom: 8px; }
/* Responsive */
@media (max-width: 1024px) {
.main { flex-direction: column; }
.sidebar { width: 100%; border-right: none; border-bottom: 1px solid #e1e4e8; }
}
</style>
</head>
<body>
<div class="container">
<!-- Header -->
<header class="header">
<h1>All Tasks</h1>
<button class="btn btn-primary">+ New Task</button>
</header>
<!-- Main Content -->
<div class="main">
<!-- Filter Sidebar -->
<aside class="sidebar">
<div class="filter-section">
<h3>Status</h3>
<div class="checkbox-group">
<label class="checkbox-label"><input type="checkbox" name="status" value="todo"> To Do</label>
<label class="checkbox-label"><input type="checkbox" name="status" value="in_progress"> In Progress</label>
<label class="checkbox-label"><input type="checkbox" name="status" value="review"> In Review</label>
<label class="checkbox-label"><input type="checkbox" name="status" value="done"> Done</label>
<label class="checkbox-label"><input type="checkbox" name="status" value="blocked"> Blocked</label>
</div>
</div>
<div class="filter-section">
<h3>Assignee</h3>
<select class="form-control" id="assignee-filter">
<option value="">All Assignees</option>
<option value="1">Alex Johnson</option>
<option value="2">Sam Chen</option>
<option value="3">Maria Rodriguez</option>
<option value="4">James Wilson</option>
<option value="unassigned">Unassigned</option>
</select>
</div>
<div class="filter-section">
<h3>Project</h3>
<select class="form-control" id="project-filter">
<option value="">All Projects</option>
<option value="1">Website Redesign</option>
<option value="2">API v2 Migration</option>
<option value="3">Mobile App Launch</option>
<option value="4">Security Audit</option>
</select>
</div>
<div class="filter-section">
<h3>Date Range</h3>
<div class="form-group">
<label>Start Date</label>
<div class="date-range">
<input type="date" class="form-control" id="start-date">
<input type="date" class="form-control" id="end-date">
</div>
</div>
</div>
<div class="filter-actions">
<button class="btn btn-secondary" style="flex: 1">Clear Filters</button>
<button class="btn btn-primary" style="flex: 1">Apply</button>
</div>
</aside>
<!-- Task Table -->
<section class="table-area">
<div class="table-header">
<span class="results-info">Showing 1–25 of 142 tasks</span>
<div class="page-size">
<select id="page-size">
<option value="10">10 per page</option>
<option value="25" selected>25 per page</option>
<option value="50">50 per page</option>
<option value="100">100 per page</option>
</select>
</div>
</div>
<table id="task-table">
<thead>
<tr>
<th data-sort="title">Title</th>
<th data-sort="status">Status</th>
<th data-sort="priority">Priority</th>
<th data-sort="assignee">Assignee</th>
<th data-sort="project">Project</th>
<th data-sort="start_date">Start Date</th>
<th data-sort="end_date">End Date</th>
<th data-sort="created">Created</th>
<th style="width: 60px;">Actions</th>
</tr>
</thead>
<tbody>
<tr>
<td><strong>Design new dashboard layout</strong><br><span style="font-size:0.75rem;color:#586069">#T-1247</span></td>
<td><span class="badge badge-in-progress">In Progress</span></td>
<td><span class="priority priority-high"><span class="priority-indicator"></span>High</span></td>
<td>Alex Johnson</td>
<td>Website Redesign</td>
<td>2025-10-15</td>
<td>2025-11-01</td>
<td>2025-10-10</td>
<td><button class="btn btn-secondary" style="padding:4px 8px;font-size:0.75rem">View</button></td>
</tr>
<tr>
<td><strong>Implement JWT authentication</strong><br><span style="font-size:0.75rem;color:#586069">#T-1245</span></td>
<td><span class="badge badge-todo">To Do</span></td>
<td><span class="priority priority-high"><span class="priority-indicator"></span>High</span></td>
<td>Sam Chen</td>
<td>API v2 Migration</td>
<td>2025-10-20</td>
<td>2025-10-30</td>
<td>2025-10-12</td>
<td><button class="btn btn-secondary" style="padding:4px 8px;font-size:0.75rem">View</button></td>
</tr>
<tr>
<td><strong>Write API documentation</strong><br><span style="font-size:0.75rem;color:#586069">#T-1242</span></td>
<td><span class="badge badge-review">In Review</span></td>
<td><span class="priority priority-medium"><span class="priority-indicator"></span>Medium</span></td>
<td>Maria Rodriguez</td>
<td>API v2 Migration</td>
<td>2025-10-01</td>
<td>2025-10-25</td>
<td>2025-09-28</td>
<td><button class="btn btn-secondary" style="padding:4px 8px;font-size:0.75rem">View</button></td>
</tr>
<tr>
<td><strong>Setup CI/CD pipeline</strong><br><span style="font-size:0.75rem;color:#586069">#T-1238</span></td>
<td><span class="badge badge-done">Done</span></td>
<td><span class="priority priority-medium"><span class="priority-indicator"></span>Medium</span></td>
<td>James Wilson</td>
<td>Mobile App Launch</td>
<td>2025-09-15</td>
<td>2025-10-05</td>
<td>2025-09-10</td>
<td><button class="btn btn-secondary" style="padding:4px 8px;font-size:0.75rem">View</button></td>
</tr>
<tr>
<td><strong>Fix memory leak in data processor</strong><br><span style="font-size:0.75rem;color:#586069">#T-1235</span></td>
<td><span class="badge badge-blocked">Blocked</span></td>
<td><span class="priority priority-high"><span class="priority-indicator"></span>High</span></td>
<td>Alex Johnson</td>
<td>Security Audit</td>
<td>2025-10-05</td>
<td>2025-10-20</td>
<td>2025-10-01</td>
<td><button class="btn btn-secondary" style="padding:4px 8px;font-size:0.75rem">View</button></td>
</tr>
<tr>
<td><strong>Create user onboarding flow</strong><br><span style="font-size:0.75rem;color:#586069">#T-1231</span></td>
<td><span class="badge badge-todo">To Do</span></td>
<td><span class="priority priority-low"><span class="priority-indicator"></span>Low</span></td>
<td>—</td>
<td>Website Redesign</td>
<td>2025-11-01</td>
<td>2025-11-15</td>
<td>2025-10-18</td>
<td><button class="btn btn-secondary" style="padding:4px 8px;font-size:0.75rem">View</button></td>
</tr>
<tr>
<td><strong>Performance audit for dashboard</strong><br><span style="font-size:0.75rem;color:#586069">#T-1228</span></td>
<td><span class="badge badge-in-progress">In Progress</span></td>
<td><span class="priority priority-medium"><span class="priority-indicator"></span>Medium</span></td>
<td>Sam Chen</td>
<td>Website Redesign</td>
<td>2025-10-18</td>
<td>2025-11-05</td>
<td>2025-10-15</td>
<td><button class="btn btn-secondary" style="padding:4px 8px;font-size:0.75rem">View</button></td>
</tr>
<tr>
<td><strong>Add dark mode support</strong><br><span style="font-size:0.75rem;color:#586069">#T-1224</span></td>
<td><span class="badge badge-todo">To Do</span></td>
<td><span class="priority priority-low"><span class="priority-indicator"></span>Low</span></td>
<td>Maria Rodriguez</td>
<td>Mobile App Launch</td>
<td>2025-11-10</td>
<td>2025-11-25</td>
<td>2025-10-20</td>
<td><button class="btn btn-secondary" style="padding:4px 8px;font-size:0.75rem">View</button></td>
</tr>
</tbody>
</table>
<!-- Pagination -->
<nav class="pagination" aria-label="Task pagination">
<button disabled>« Previous</button>
<button class="active">1</button>
<button>2</button>
<button>3</button>
<button>4</button>
<button>5</button>
<span class="ellipsis">…</button>
<button>6</button>
<button>Next »</button>
</nav>
</section>
</div>
</div>
<script>
// Simple sort toggle demo
document.querySelectorAll('th[data-sort]').forEach(th => {
th.addEventListener('click', () => {
document.querySelectorAll('th[data-sort]').forEach(other => {
if (other !== th) other.classList.remove('sorted-asc', 'sorted-desc');
});
if (th.classList.contains('sorted-asc')) {
th.classList.replace('sorted-asc', 'sorted-desc');
} else {
th.classList.add('sorted-asc');
th.classList.remove('sorted-desc');
}
});
});
// Page size change
document.getElementById('page-size').addEventListener('change', (e) => {
console.log('Page size changed to:', e.target.value);
});
</script>
</body>
</html>

View File

@@ -1,105 +1,425 @@
# Search Test Coverage — Test-Engineering Plan
# TDD Plan: Task List View with Filtering, Sorting, Pagination
This plan follows `sources/task-brief.md`. Because the deliverable is a regression test suite for existing behaviour, the steps use implementation prompts rather than artificial pairs of test and production-code prompts. Each prompt is intended for a separate turn; review the changes and run the relevant checks before moving to the next step, adapting subsequent prompts to what was actually found.
*Use this in LiveCompare — each step = one test + implementation cycle*
The target is at least 20 additional test methods across nine search categories, with at least 80% statement coverage individually for `search_views.py` and `search/search_objects.py`. Existing endpoint contracts must remain unchanged. The source brief overstates the TODO count: explicit TODOs were found for customer and organisation search, while main search also lacks result assertions but has no equivalent TODO.
---
### Step 1 - Establish Search Contracts and the Test Baseline
## UI Specification (from task-brief.md)
**Implementation prompt:**
**Template**: `NearBeach/templates/NearBeach/tasks/task_list.html` (server-rendered Django, no Vue component)
> Inspect the existing search tests, search views, SearchObjects implementation, URL routing, forms, permission helpers, and relevant models. Map the main, customer, organisation, group, user, sprint, tag, notification, and permission-set search categories to their endpoints. For each, identify request parameters, response structure, matching rules, ordering, pagination, closed-state support, and access rules. Distinguish main-search object types from the nine endpoint categories; do not assume all categories share one contract.
**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`
>
> Set up the documented Python environment using a virtual environment, and run the existing search suite with verbose output. Capture baseline test counts and failures, and measure baseline coverage for the two target modules. Also establish the full-suite baseline so later failures can be classified accurately. Report environment blockers and actual command output rather than claiming success. Do not change production code or add tests yet; give me a concise contract map and a proposed allocation of at least 20 new test methods.
Run it — it should FAIL (no view/URL/template exists yet).
### Step 2 - Build Deterministic Search Test Data and the First Result Assertions
### 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
**Implementation prompt:**
---
> Using the contracts established in Step 1, introduce minimal reusable test setup following the repository's conventions. Prefer Django TestCase and setUpTestData where compatible; avoid a broad fixture rewrite or transactional tests without a concrete need. Create synthetic users, groups, permissions, object assignments, and a small dataset with deliberately matching, near-matching, unrelated, and restricted records. Control timestamps only where they affect behaviour under test.
>
> Add initial result-level tests for customer and organisation search, addressing their explicit TODOs. Assert exact returned identities and exposed counts, with positive and negative cases, rather than merely HTTP statuses. Keep the fixture design understandable and extend it only when later steps need additional data. Run the new tests and existing search suite, and report the exact commands and results. Do not remove a TODO until its intended coverage exists.
## STEP 2: Permission Filtering (Core)
### Step 3 - Cover Main Search Object Selection and Result Structure
### 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)
**Implementation prompt:**
### 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
> Expand main-search result tests even though that section has no explicit TODO. The existing main-search methods check HTTP statuses, including for a numeric query and include_closed, but do not verify returned records. Distinguish the search page endpoint, which renders the interface, from search_data, which returns the actual JSON results; posting to the page is not a substitute for testing the data endpoint.
>
> Exercise each of SearchObjects' six configured types: kanban_board, project, request_for_change, requirement, requirement_item, and task. Use validated form choices to confirm which types are reachable through the public endpoint. Assert the normalised id, title, and status values, along with each selected type's number_of_pages and current_page metadata. Verify both single-type selection and a multi-type request: unrequested types should not appear, and matching objects should stay in their own result lists. Use records sharing a title or numeric ID across types to detect accidental cross-type mixing.
>
> Test a selected type with no matches: its result list should be empty and its page metadata should reflect the actual contract. Do not invent a total-count field; the current helper exposes page counts. Use subtests for repeated type mappings rather than creating superficial copies of the same test. Run the focused tests and existing search suite, and report any configured type that the form does not actually expose.
---
### Step 3A - Cover Main Search Text and Numeric Matching
## STEP 3: Filter by Status
**Implementation prompt:**
### 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
> Add focused main-search tests for the matching branches in SearchObjects. Verify exact and partial title matches, case-insensitive matching, and multi-term AND logic. Include a full match, a first-term-only match, a second-term-only match, and an unrelated record so replacing AND with OR would fail the test. Verify empty and no-match queries against the validated form behaviour.
>
> Cover numeric tokens with deliberately controlled data: one record matching by primary key but not title, another matching a numeric substring in its title but having a different primary key, and an unrelated record. Both legitimate matches should be returned. Add a mixed text/numeric query to prove that the numeric ID-or-title condition still combines with the other token using AND. Cover the RFC's rfc_id mapping and the requirement item's own ID, not just the default task mapping.
>
> Keep datasets below the page limit unless pagination is the subject of the test. Do not assume unsupported tokenisation, fuzzy matching, exact-only numeric matching, or stable ordering. Run the focused tests and search suite. If the existing behaviour conflicts with the intended contract, explain the discrepancy before modifying production code or accepting it as correct.
### 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 3B - Cover Main Search Visibility and Soft Deletion
---
**Implementation prompt:**
## STEP 4: Filter by Assignee
> Add main-search-specific visibility tests using real users, groups, memberships, and ObjectAssignment rows. Verify that an ordinary user cannot bypass group visibility by sending include_all_groups. For a superuser, separately exercise the default group-limited behaviour and the explicit include_all_groups opt-in: the current helper bypasses group limits only when both conditions hold. Do not assume superusers always see every object.
>
> Verify that soft-deleted objects remain absent even when include_closed or the superuser all-groups option is enabled. Isolate deleted ObjectAssignment and deleted UserGroup cases: give each test record only the relationship under examination so another active relationship cannot accidentally grant access. Assert both visible and excluded identities and the resulting page metadata.
>
> Add requirement-item tests proving that access follows the parent requirement's assignment, while returned and numerically searched IDs belong to the requirement item itself. Give the parent and child deliberately different IDs so using the wrong key is detectable. Include an inaccessible parent's item and an item with overlapping authorised group assignments. Coordinate with the later general permission step to avoid duplicating these cases. Run the focused tests and search suite without changing production visibility rules.
### 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
### Step 3C - Cover Exclusion of Already-Linked Main Search Results
### 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
**Implementation prompt:**
---
> Inspect the real callers of exclude_destination and exclude_location_id, then build tests for supported source/destination combinations used to find objects available for linking. Create a matching object already linked to the specified destination, an unlinked match, and a match linked only to a different destination. Assert that only the link to the requested destination excludes a record.
>
> Add a soft-deleted assignment case to prove that an inactive link does not incorrectly exclude an otherwise visible match. Keep the active group assignment granting visibility separate from the destination link being tested. Exercise omission of either exclusion parameter according to the existing form/helper contract, and assert that exclusion affects the returned page count before pagination. Use representative real combinations, including special ID mappings only where supported; do not generate a Cartesian product of speculative object relationships.
>
> Run the focused tests and search suite. Explain any genuine defect exposed by these cases and ask before changing production code. The objective is to cover the existing linking workflow, not create a new exclusion API.
## STEP 5: Filter by Project
### Step 4 - Add Result Assertions for the Remaining Search Categories
### 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
**Implementation prompt:**
### 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
> Add meaningful result-level coverage for group, user, sprint, tag, notification, and permission-set searches. Reuse the test setup where it makes the tests clearer, but preserve each endpoint's distinct access and request rules. Cover matching and exclusion, no-match results, and response totals where available. Add partial, case-insensitive, and multi-term variants only where the inspected endpoint contract supports them.
>
> Use descriptive test methods and subtests for closely related input variants. Keep at least 20 additional test methods as the overall target rather than treating subtest iterations as separate methods. Run the affected tests and existing search suite. Report which of the nine categories now have exact result assertions and which still need work.
---
### Step 5 - Verify Permissions and Result Isolation
## STEP 6: Filter by Date Range
**Implementation prompt:**
### 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
> Expand permission tests using ordinary users with explicit group and permission assignments. For endpoints using ObjectAssignment-based visibility, assert both that authorised records are returned and restricted records are absent. Cover users with no relevant access and an object reachable through multiple accessible groups, checking that identities and counts are not duplicated. Verify that inaccessible matches do not inflate returned totals.
>
> Test administrative endpoints against their actual access rules rather than assuming group-based visibility applies everywhere. For notifications, verify recipient isolation where the contract supports it. Keep superuser behaviour in separate tests so it cannot hide missing permission setup. Run the permission cases and existing search suite, and summarise the access boundaries each test protects. Do not alter production permissions as part of this step.
### 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 6 - Exercise Pagination and Closed-State Boundaries
---
**Implementation prompt:**
## STEP 7: Sorting by Column Headers
> For main search, explicitly cover the distinct closed-status branches: RFC statuses 5 and 6, kanban's Closed string, and the higher-order Closed status on the remaining supported types. Verify include_closed changes status filtering without restoring deleted or inaccessible records. Exercise per-type pagination in a multi-type request, including different page counts and an empty list for a type whose results are exhausted. Test zero and negative destination_page inputs against the existing first-page slicing behaviour, and distinguish slice selection from the echoed current_page metadata; raise any misleading metadata as a contract question rather than silently redefining it.
>
> Add pagination tests only for endpoints that actually paginate. Create enough controlled records to test page one, page two, the final page boundary, and a page beyond the results. Assert exact membership, page sizes, totals, and metadata where exposed, and verify there is no overlap or loss across valid pages. Respect documented or implemented invalid-page handling and assert ordering only when it is part of the contract.
>
> For each search path supporting closed/include_closed filtering, create accessible open and closed records and verify the default behaviour and supported toggle values. Include a restricted closed record to ensure enabling the toggle cannot bypass visibility filtering. Where an endpoint lacks either feature, record that limitation instead of adding it. Run the new cases and the entire search suite, then report results and any unresolved contract questions.
### 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
### Step 7 - Check Test Sensitivity and Close Coverage Gaps
### 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
**Implementation prompt:**
---
> Review the new suite against the brief's coverage matrix: exact/partial matching, case handling, multi-term AND logic, empty/no-match results, pagination, permissions, closed-state filtering, counts, and all nine search categories. Include the expanded main-search checks for six configured object types, numeric ID/title matching, selected-type isolation, parent-based requirement-item access, soft deletion, the all-groups opt-in, and exclusion of already-linked objects. Treat at least 20 additional test methods as a floor, not a cap or a reason to split repetitive assertions into artificial tests. Identify missing cases using both that matrix and a fresh coverage report. Run coverage with NearBeach.views.search_views and NearBeach.views.search as the source modules, and report uncovered lines for both target files.
>
> Add focused tests for meaningful uncovered behaviour until search_views.py and search/search_objects.py each reach at least 80% statement coverage. Do not lower the target, change exclusions, or mock away the filtering being tested. If reaching the target requires scope beyond the agreed task, explain that before expanding the work.
>
> Check representative tests for sensitivity: temporarily give a result assertion a deliberately wrong expected identity or count and confirm that the focused test fails for that reason, then restore the correct assertion and rerun it. Keep these checks temporary, do not leave failing assertions or modified production logic behind, and report what was actually verified. Review that assertions reject incorrect results rather than merely exercising branches.
## STEP 8: Pagination
### Step 8 - Run Final Regression Checks and Review the Diff
### 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`
**Implementation prompt:**
### 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
> Review the final diff for unnecessary fixture changes, duplicated setup, brittle ordering assumptions, mocks that bypass real search behaviour, and accidental production changes. Confirm that at least 20 new test methods have been added and each of the nine search categories has meaningful result assertions. Remove addressed TODOs only where justified; leave unrelated gaps alone.
>
> Run the search suite with verbose output, the agreed coverage command and report, and the complete existing Django suite. Compare the results with the baseline, explicitly separating pre-existing failures and environment blockers from new regressions. Report the commands, actual test counts, individual coverage percentages for both target modules, changed test and fixture files, and any remaining limitations. Do not describe the task as complete unless the agreed acceptance criteria have been checked; surface any unmet criterion plainly.
---
## 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.

View File

@@ -0,0 +1,125 @@
# Task List View Mockup - Design
**Purpose**: Centralized, cross-project task list with filtering, sorting, pagination
## Page Layout
Two-column responsive layout (sidebar left, table right on desktop; stacked on mobile <1024px).
**Header bar**: "All Tasks" title on left; "+ New Task" button on right (visible only to users with create permission, `user_level >= 3`). Links to `/new_task/`.
---
## Sidebar Filters (Fixed Width ~280px)
All filters in a single GET form. Five filter sections, each with a label and control:
1. `Status` - six checkboxes (New, Backlog, Blocked, In Progress, Test/Review, Closed). Multi-select. Values come from `ListOfTaskStatus` model (user-configurable; defaults shown). Form values are numeric `task_status_id`.
2. `Assignee` - a dropdown: "All Assignees" + all users who have task access in the current user's accessible projects + "Unassigned" (value `0`). Form values are numeric user `id`.
3. `Project` - a dropdown: "All Projects" + projects the user has `ObjectAssignment` access to (via their groups). Form values are numeric `project_id`, labels are `project_name`.
4. `Date Range` - two HTML5 date inputs: "Start Date" (filters `task_start_date__gte`) and "End Date" (filters `task_end_date__lte`). Each optional independently.
5. `Actions` - two buttons: "Clear Filters" (secondary style, links to base `/tasks/` URL) and "Apply" (primary style, submits form).
---
## Main Table Area
### Results Header
- Left: "Showing X–Y of Z tasks" (uses paginator `start_index`, `end_index`, `count`)
- Right: Page size dropdown (10, 25, 50, 100; default 25). Auto-submits on change.
### Data Table (9 Columns)
| Column | Sortable | Sort Field | Content |
|--------|----------|------------|---------|
| Title | Yes | `task_short_description` | Bold task short description + small gray task ID (`#T-{id}`) |
| Status | Yes | `task_status__task_status_sort_order` | Colored badge by higher-order status |
| Priority | Yes | `task_priority` | Colored dot (8px) + label: Highest/High (red), Normal (orange), Low/Lowest (blue) |
| Assignee | Yes | `task_assigned_to__username` | Username or hyphen if unassigned |
| Project | Yes | `first_project_name` (annotated) | First project name via ObjectAssignment |
| Start Date | Yes | `task_start_date` | YYYY-MM-DD |
| End Date | Yes | `task_end_date` | YYYY-MM-DD |
| Created | Yes | `date_created` | YYYY-MM-DD |
| Actions | No | — | "View" button linking to `/task_information/{id}/` |
### Sorting
- Click any sortable header → toggles ASC/DESC.
- URL param: `?sort=field` (asc) or `?sort=-field` (desc).
- Header shows ▲ (asc) or ▼ (desc) next to column name.
- Default sort: `-date_created` (newest first).
- Clicking a different column starts ascending; re-clicking active column toggles.
### Status Badges (By Higher-Order Status)
| Higher-Order Status | Example Statuses | Background | Text | CSS Class |
|---------------------|------------------|------------|------|-----------|
| Backlog | New, Backlog | `#fff3cd` | `#856404` | `badge badge-backlog` |
| Normal | In Progress, Test/Review | `#cce5ff` | `#004085` | `badge badge-normal` |
| Blocked | Blocked | `#f8d7da` | `#721c24` | `badge badge-blocked` |
| Closed | Closed | `#d4edda` | `#155724` | `badge badge-closed` |
Template: `badge badge-{{ task.task_status.task_higher_order_status|lower }}` with label `{{ task.task_status.task_status }}`.
### Priority Indicators (Three Color Groups)
| Priority Values | Labels | Color | CSS Class |
|-----------------|--------|-------|-----------|
| 0, 1 (Highest, High) | Highest, High | Red `#cb2431` | `priority-high` |
| 2 (Normal) | Normal | Orange `#e67e22` | `priority-normal` |
| 3, 4 (Low, Lowest) | Low, Lowest | Blue `#3498db` | `priority-low` |
Template maps value: `<=1 → high`, `2 → normal`, `>=3 → low`. Label via `{{ task.get_task_priority_display }}`. Sort ascending on `task_priority` puts Highest (0) first.
### Empty State
When queryset empty: single row spanning all columns, centered "No tasks found" text.
### Pagination Footer
- "◀ Prev" (disabled on page 1)
- Page numbers: Django's `paginator.get_elided_page_range()` — e.g., 1 2 3 4 5 … 6
- "Next ▶" (disabled on last page)
- All links preserve every active filter, sort, and page_size query parameter.
---
## Permission Awareness
| Element | Condition |
|---------|-----------|
| "+ New Task" button | `user_level >= 3` |
| "View" action links | `user_level >= 1` |
| Filter sidebar | Always visible (read-only users can filter) |
`user_level` = max `permission_set__task` across user's groups for accessible projects. Superusers see all tasks and all UI elements.
---
## Design System Conformance
- Buttons: `btn btn-primary` / `btn btn-secondary`
- Form controls: `form-control` class on all inputs/selects
- Table: standard HTML table with 12px 16px cell padding
- Badges: `badge` base + status modifier
- Colors: Primary `#0366d6`, text `#24292e`, borders `#e1e4e8`
- Spacing: 8px base unit, 16px section gaps
---
## What Is Explicitly Excluded
No bulk actions, no column visibility toggle, no saved filter presets, no real-time updates, no drag-and-drop, no live collaboration indicators. This is a read/list view only.
---
## Deliverable Expectation
A single self-contained HTML file with embedded CSS/JS that:
- Renders correctly standalone in a browser
- Uses realistic sample data (8–10 rows covering all 6 default statuses and 5 priority levels in 3 color groups)
- Contains Django template syntax (`{% for %}`, `{% if %}`, form field rendering)
- Matches every component, color, and behavior described above
- Serves as the exact visual and structural target for implementation

View File

@@ -0,0 +1,212 @@
# Wireframe Generation Instructions for Task List View
*Give these to the LLM that will generate the production wireframe*
---
## Context
**Project**: NearBeach (Django/Vue project management tool)
**Feature**: Task List View at `/tasks/` with filtering, sorting, pagination
**Permission Model**: Group-based via `ObjectAssignment` — users see only tasks from projects their groups have access to
---
## Required Wireframe Components
### 1. Page Structure
```
┌─────────────────────────────────────────────────────────────┐
│ Header: "All Tasks" [+ New Task] btn │
├──────────────┬──────────────────────────────────────────────┤
│ │ │
│ SIDEBAR │ MAIN TABLE AREA │
│ (280px) │ │
│ │ ┌────────────────────────────────────────┐ │
│ Filters: │ │ Results: "Showing 1–25 of 142 tasks" │ │
│ • Status │ │ Page size: [25 ▼] │ │
│ ☐ To Do │ └────────────────────────────────────────┘ │
│ ☐ In Prog │ ┌────────────────────────────────────────┐ │
│ ☐ Review │ │ ▼Title ▲Status Priority Assignee... │ │
│ ☐ Done │ │ ────────────────────────────────────── │ │
│ ☐ Blocked │ │ Task Name │ View │ │
│ • Assignee │ │ #T-1247 In Progress ●High Alex ... │ │
│ [All ▼] │ │ Task Name │ View │ │
│ • Project │ │ #T-1245 To Do ●High Sam ... │ │
│ [All ▼] │ │ ... │ │
│ • Date Range│ └────────────────────────────────────────┘ │
│ [from] │ ┌────────────────────────────────────────┐ │
│ [to] │ │ ◀ Prev 1 2 3 4 5 ... 6 Next ▶ │ │
│ [Clear] │ └────────────────────────────────────────┘ │
│ [Apply] │ │
│ │ │
└──────────────┴──────────────────────────────────────────────┘
```
### 2. Sidebar Filters (Exact Fields)
| Filter | Type | Options Source |
|--------|------|----------------|
| **Status** | Multi-checkbox | `ListOfTaskStatus` model (New, Backlog, Blocked, In Progress, Test/Review, Closed — user-configurable, defaults shown) |
| **Assignee** | Single select | Users with task access in user's projects + "Unassigned" |
| **Project** | Single select | Projects user has `ObjectAssignment` access to |
| **Start Date** | Date input | HTML5 `<input type="date">` |
| **End Date** | Date input | HTML5 `<input type="date">` |
| **Actions** | Buttons | "Clear Filters" (secondary), "Apply" (primary) |
### 3. Table Columns (Exact Order + Behavior)
| Column | Sortable | Rendering |
|--------|----------|-----------|
| **Title** | Yes | `<strong>task_short_description</strong><br><small>#T-{task_id}</small>` |
| **Status** | Yes | Badge based on `task_higher_order_status`: `badge-backlog` (New, Backlog), `badge-normal` (In Progress, Test/Review), `badge-blocked`, `badge-closed` |
| **Priority** | Yes | Colored dot + text: `● High` (red), `● Medium` (orange), `● Low` (green) |
| **Assignee** | Yes | `assigned_user.username` or `—` |
| **Project** | Yes | `project.project_name` |
| **Start Date** | Yes | `task_start_date` (YYYY-MM-DD) |
| **End Date** | Yes | `task_end_date` (YYYY-MM-DD) |
| **Created** | Yes | `created_date` (YYYY-MM-DD) |
| **Actions** | No | `[View]` button → links to `task_information` |
### 4. Status Badge CSS Classes (Must Match — Based on Higher-Order Status)
```css
.badge-backlog { background: #fff3cd; color: #856404; } /* New, Backlog */
.badge-normal { background: #cce5ff; color: #004085; } /* In Progress, Test/Review */
.badge-blocked { background: #f8d7da; color: #721c24; } /* Blocked */
.badge-closed { background: #d4edda; color: #155724; } /* Closed */
```
Template renders: `<span class="badge badge-{{ task.task_status.task_higher_order_status|lower }}">{{ task.task_status.task_status }}</span>`
### 5. Priority Indicator
```html
<span class="priority priority-high">
<span class="priority-indicator"></span>High
</span>
<!-- priority-medium, priority-low similarly -->
.priority-indicator { width: 8px; height: 8px; border-radius: 50%; display: inline-block; }
.priority-high .priority-indicator { background: #cb2431; }
.priority-medium .priority-indicator { background: #e67e22; }
.priority-low .priority-indicator { background: #28a745; }
```
### 6. Pagination (Exact Behavior)
- **Page size selector**: 10, 25, 50, 100 (default 25)
- **Page numbers**: 1 2 3 4 5 … 6 (ellipsis after 5)
- **Prev/Next**: Disabled on first/last page
- **All links preserve**: All current filter/sort query params
### 7. Sorting Behavior
- Click column header → toggles ASC/DESC
- URL param: `?sort=created` (asc) or `?sort=-created` (desc)
- Visual indicator: ▲ for asc, ▼ for desc (append to header text)
- Default sort: `-created` (newest first)
### 8. Permission-Aware UI Elements
| Element | Shown When |
|---------|------------|
| **+ New Task button** | `user_level >= 3` (create permission) |
| **Edit/View links in Actions** | `user_level >= 1` (read permission) |
| **Filter sidebar** | Always (read-only users can still filter) |
---
## Technical Requirements
### Template Structure
```html
{% extends "NearBeach/base.html" %}
{% block content %}
<div class="task-list-container">
<header class="task-list-header">...</header>
<div class="task-list-main">
<aside class="task-list-sidebar">
<form method="GET" class="filter-form">
<!-- All filter fields -->
<button type="submit" name="apply">Apply</button>
<a href="{% url 'task_list' %}" class="btn btn-secondary">Clear</a>
</form>
</aside>
<section class="task-list-table-area">
<div class="table-header">
<span class="results-info">Showing {{ page_obj.start_index }}–{{ page_obj.end_index }} of {{ paginator.count }} tasks</span>
<select name="page_size" onchange="this.form.submit()">...</select>
</div>
<table class="task-table">
<thead>
<tr>
<th><a href="?sort=created&...">Title {% if sort == 'created' %}▲{% elif sort == '-created' %}▼{% endif %}</a></th>
<!-- ... all columns -->
</tr>
</thead>
<tbody>
{% for task in page_obj %}
<tr>...</tr>
{% empty %}
<tr><td colspan="9" class="empty-state">No tasks found</td></tr>
{% endfor %}
</tbody>
</table>
<nav class="pagination">
<!-- Prev, page numbers, Next -->
</nav>
</section>
</div>
</div>
{% endblock %}
```
### Form Handling
- All filters in **single `<form method="GET">`** in sidebar
- Pagination links are `<a href="?page=2&status=in_progress&...">` preserving all params
- Page size selector: `<select name="page_size" onchange="this.form.submit()">`
### Responsive Breakpoint
- **≥1024px**: Sidebar left, table right (flex)
- **<1024px**: Sidebar stacks above table (full width)
---
## What NOT to Include
| ❌ Don't Add | Reason |
|-------------|--------|
| Live collaboration indicators | Not in scope |
| Bulk actions (checkboxes + dropdown) | Future enhancement |
| Column visibility toggle | Future enhancement |
| Saved filter presets | Future enhancement |
| Real-time updates (WebSocket) | Not in NearBeach |
| Drag-and-drop reordering | Not a kanban board |
---
## Design System Consistency
**Match NearBeach existing patterns:**
- Button classes: `btn btn-primary`, `btn btn-secondary`
- Form controls: `form-control` class on inputs/selects
- Table: `table` class with `th`/`td` padding 12px 16px
- Badges: `badge` base + `badge-{status}` modifier
- Colors: Use existing CSS variables or match `#0366d6` (primary), `#24292e` (text), `#e1e4e8` (borders)
---
## Deliverable
**Single HTML file** (like the current wireframe) that:
1. Renders correctly standalone (open in browser)
2. Has all CSS embedded (no external dependencies)
3. Includes minimal JS for sort toggle demo
4. Uses realistic sample data (8-10 rows showing all statuses/priorities)
5. Matches the component list above exactly (6 default statuses, 3 priorities)
---
## Prompt to Give the LLM
> "Generate a production-ready HTML wireframe for NearBeach's Task List View at `/tasks/`. Use the specifications in `wireframe-generation-instructions.md`. The wireframe must be a single self-contained HTML file with embedded CSS/JS, matching the exact component list, status badges (4 higher-order classes), priority indicators, pagination, sorting behavior, and permission-aware UI elements described. Use NearBeach's design system (btn, form-control, badge classes). Include realistic sample data demonstrating all 6 default statuses (New, Backlog, Blocked, In Progress, Test/Review, Closed) and 3 priority levels. The template structure must be Django-ready (show {% for %} loops, {% if %} conditionals for permissions, form field rendering). Use higher-order status for badge class: `badge-{{ task.task_status.task_higher_order_status|lower }}`."