date in the modal header was "2026-05-15" — now reads
"Friday, 15 May 2026". Server-side strftime on the already-loaded
log.date — zero DB / compute overhead. Touches only the modal's
date field; other date fields in the JSON (paid_date,
pay_period_*) still use the ISO format because they don't render
into a human-facing header.
CLAUDE.md changes:
- 'What's mid-flight' breadcrumb updated: SiteReport/Absences
migrations are LIVE on prod; only the 4 latest UX commits await
a pull-and-restart (no migration / collectstatic needed).
- URL Routes table entries for /workers/ and /history/ now document
the new ?team= filter (and team=none for unassigned / no-team cases).
- Worker Management UI inline description mentions the team filter
+ Absences tab on the worker detail page.
- Two new Coding Style gotchas captured: (1) Bootstrap dropdowns
inside .card elements get clipped by sibling cards — fix is to
lift the wrapping card with position:relative + z-index;
(2) JS reading from data-worker-id was unreliable on production —
read input[name="workers"][value] directly (the attendance-form
pattern that's been working for years).
parked-work.md changes:
- Pending-deploy section rewritten: the BIG deploy (migrations +
collectstatic) is DONE; only 4 small commits await a pull +
service restart.
- 'Recently shipped' grew two new entries: the team filters on
/workers/ + /history/, and the two absences UX polish fixes.
- Updated timestamp to 15 May 2026.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Mirrors the team filter just added to /workers/. WorkLog.team is a
nullable FK, so the filter accepts:
- empty → all logs (default)
- digit → logs tagged with that team
- 'none' → logs with no team set (ad-hoc attendance)
Filter row reflowed to col-md-3 col-lg-2 so all four selects fit on
a single row on wide screens; mobile stacks them. CSV export link
now passes &team=… through. Supervisors only see teams they
supervise in the dropdown.
4 regression tests covering filter narrowing, no-team match,
empty=show-all, and filter_params round-trip for the List/Calendar
toggle links.
New ?team=<id> URL param narrows the worker list to that team's
members via the Team.workers M2M. ?team=none filters to workers
not assigned to any team. Default (empty) still shows all
matching workers across all teams.
UI: new "Team" dropdown in the filter row, between Search and
Status. Lists active teams alphabetically. Layout reflowed to
col-md-4 / col-md-3 / col-md-3 / col-md-2.
Konrad's checkpoint feedback: "in the worker page - can i have a
filter for teams so i can easely see who is in what team".
4 regression tests covering no-filter, by-team, no-team, and
dropdown options.
The Reasons multi-checkbox dropdown was rendering BEHIND the table
rows even with z-index: 1050 applied. Root cause: the filter card
and the table card are sibling .card elements, both creating their
own stacking contexts. The dropdown's z-index was being measured
inside the filter card's local stacking context, but the table card
(next sibling in document order) sat on top of the whole filter
card in the page's stacking order.
Fix: set position: relative + z-index: 10 on the wrapping <form
class="card mb-3"> so the entire filter card lifts above the table
card globally. The dropdown's z-index: 1050 inside it now resolves
correctly.
Pure template change — no behaviour change, no test change.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Konrad reported that selecting a team on /absences/log/ hid ALL
workers, not just non-team. Root cause: the JS read row.dataset.workerId
to filter, which depends on how Django renders choice_value for
ModelMultipleChoiceField iteration — not reliable. Switched to read
the actual <input name='workers'> value attribute, matching the
attendance_log's proven pattern. Same UX intent (hide non-team
workers); more robust implementation.
Also uses an O(1) object lookup instead of array.indexOf, and adds
defensive fallback for both string and numeric team-id keys.
Worker Absences feature shipped (bf6f0a5..27fe05e), so it's no
longer the active queue item. Promoted the pending production
deploy (run /run-migrate/, collectstatic, restart service) to the
top of parked-work.md — production /history/ is 500ing until those
migrations run. CLAUDE.md breadcrumb updated to flag this as the
next operator action when a fresh session starts.
Also captured the small polish follow-ups from the absences code
reviews (AbsenceQuickForm dead code, N+1 in team_workers_map,
duplicated CSV filter block, etc.) so they don't get lost in a
future janitorial pass.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
- /absences/ Reasons multi-checkbox dropdown: z-index 1050 so it
renders above the table rows (was hiding the bottom 4 options).
- /absences/log/confirm/: action-oriented copy, pre-checked
'remove from work log' (the common case), explicit Cancel button.
Was confusing: 'Also remove from WorkLog' didn't read as the
natural fix for the conflict. New language explains both branches
in plain English. +1 regression test for the new copy.
Three small fixes from the final review:
- AbsenceAdmin.save_model() now runs _sync_absence_payroll_adjustment
so toggling is_paid via /admin/ updates the linked Bonus consistently
with the friendly UI.
- _delete_adjustment_with_cascade clears absence.is_paid when deleting
a Bonus linked to an Absence — closes the state-drift window after
bulk-delete from /payroll/?status=adjustments.
- base.html — Resources dropdown 'Absences' entry now shows for
supervisors as well as staff (was staff-only). View-layer permission
helpers (_absence_user_queryset, _user_can_log_absences) already
enforce the real access boundary; this just makes the menu honest.
2 regression tests.
#5 from checkpoint feedback: /workers/<id>/ now has an Absences tab
showing YTD totals (chip row) + 50 most-recent absences (table).
Admin dashboard adds a conditional 'X absent in last 7 days' alert
card (only renders when count > 0; links to filtered /absences/).
CLAUDE.md gets a new Absence model entry + URL routes + dedicated
'Absence-to-PayrollAdjustment cascade' section. Reason-badge CSS
moved to static/css/custom.css as single source of truth. 4 new tests.
After logging attendance, admins can jump straight to /absences/log/
with the date, team, and project pre-filled — no need to re-pick them.
Default Submit button keeps the existing SiteReport flow unchanged.
4 new tests covering both submit paths and URL-param prefill.
Migration 0015 adds Project FK (SET_NULL, nullable) to Absence.
When is_paid=True, the auto-Bonus PayrollAdjustment inherits the
project for cost-attribution. Form + admin + list + edit + log
templates expose the field. List view filter now uses
absence.project_id directly (was indirect via worker__work_logs).
5 new tests.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
CLAUDE.md gotcha #5: multi-line {# ... #} blocks render as literal text
in Django templates. Converted to {% comment %} blocks in edit.html
and list.html (also scanned log.html / log_confirm.html for safety).
Adds an 'Absences' entry to the Resources dropdown in base.html so the
feature is discoverable from the topbar.
Three forms covering the three entry points: standalone date-range form
(/absences/log/), quick-action modal (/attendance/log/), and edit one
existing record. Log form expands (worker, date) pairs respecting
Sat/Sun toggles, validates uniqueness, surfaces WorkLog conflicts as a
non-blocking warning via conflicting_worklogs(). 6 tests.
Two helpers covering the recurring 'which absences can this user see'
and 'sync is_paid with the linked Bonus PayrollAdjustment' patterns.
The sync helper refuses to delete an already-paid adjustment — caller
surfaces this to the user. Mirrors _delete_adjustment_with_cascade
semantics. 8 tests.
Per-worker dated records with 8 reason choices (Sick/Family/Annual/
Personal-Unpaid/IOD/Suspension/Absconded/Other), is_paid flag, optional
OneToOne to PayrollAdjustment for the auto-Bonus path, audit fields.
Unique-per-day at DB layer. 4 model tests.
Captures the deferred work (Phase A.2 manual JournalEntry UI,
Phase B Letterly webhook) and queues the next brainstorm topic
(worker absence records). Adds an 8-line breadcrumb at the top
of CLAUDE.md so a fresh session sees it in the first 20 lines.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Companion to attendance: capture WHAT was done on site each day,
alongside WHO worked. Optional 1:1 with WorkLog. Mobile-first form
auto-redirected from /attendance/log/ on success (with a Skip link).
Why this design (vs. extending WorkLog or per-project templates):
- Hybrid schema. Stable + queryable fields are real columns
(`weather`, `temperature_min`, `temperature_max`, `notes`,
`created_by`, `created_at`, `updated_at`). The METRICS that change
per project / over time live in a single JSONField with shape
`{counts: {key: int}, checks: {key: bool}}` — driven by
`core/site_report_schema.py`. Adding a new metric is a one-line
edit to that file, NO migration required. Old reports without the
new key just render as 0 / unchecked.
- Two-step flow. Attendance form is unchanged; on successful POST
the supervisor lands on `/site-report/<work_log_id>/edit/` for the
most-recently-created log. They can fill in progress details
(~30 sec on a phone) or click "Skip" to home. WorkLogs without a
SiteReport are completely valid historic rows.
- Permission scope mirrors WorkLog access. Anyone who can see the
parent log (admin / log's supervisor / project's supervisors) can
see + edit its SiteReport. Wraps the existing pattern from
`work_history()` in a small helper `_can_access_site_report()`.
What ships:
Models:
- SiteReport (1:1 → WorkLog, weather choices, IntegerField temps,
JSONField metrics defaulting to {})
- Migration 0013_add_site_report (pure CreateModel, no schema
changes to existing tables)
Schema:
- core/site_report_schema.py (NEW) — single source of truth for
the metric list. Currently 7 counts + 4 checks per Konrad's
v1 spec. Helpers: get_count_keys, get_check_keys, label_for,
empty_metrics.
Form:
- SiteReportForm (in core/forms.py) — ModelForm with the four
stable fields PLUS dynamic IntegerField/BooleanField per
metric in __init__. save() serializes both halves into the
JSON blob. clean() validates min ≤ max temperature.
Views:
- site_report_edit — create-or-update; stamps created_by on
first save; preserves it on subsequent admin edits
- site_report_detail — read-only display; 404 when no report
- attendance_log redirect updated to two-step flow
- _can_access_site_report — shared permission helper
URLs:
- /site-report/<work_log_id>/edit/ (name: site_report_edit)
- /site-report/<work_log_id>/ (name: site_report_detail)
Templates:
- site_report_edit.html — mobile-first stack of inputs, weather
as a chunky icon-button row (☀️☁️🌧️⛈️🥵🥶💨), counts in a
2-col grid, checks as toggle switches, Notes textarea, Skip
+ Save buttons. Iterates pre-built (metric, bound_field)
pairs from the view to avoid needing a new template filter.
- site_report_detail.html — counts as accent-coloured value
cards, checks as a check-list, weather + temp + notes + edit
link.
- work_history.html — added a small clipboard icon next to
each row's date: filled (linked to detail) when a report
exists, muted outline (linked to edit) when not. Click is
event.stopPropagation()-ed so the row's payroll-modal
handler doesn't also fire.
Performance:
- work_history queryset adds .select_related('site_report') so
the new template indicator doesn't introduce an N+1.
Admin:
- SiteReport registered with raw_id_fields on work_log +
created_by, list filters on weather + project + date.
Tests (16 new, full suite 85/85):
- SiteReportModelTests — defaults, 1:1 reverse accessor,
arbitrary-key JSON round-trip
- SiteReportFormTests — dynamic field generation, save
serialisation, temp validation, instance pre-fill
- SiteReportEditViewTests — admin GET/POST, project
supervisor allowed, outsider supervisor 403, created_by
preserved on subsequent admin edits
- SiteReportDetailViewTests — 404 when absent, displays data
when present
- AttendanceLogRedirectsToSiteReportTests — confirms the
two-step flow
CLAUDE.md updates:
- SiteReport added to "Key Models" with shape + reverse-accessor note
- New "SiteReport metric schema" section near "UI-vs-DB
naming drift" — explains the JSON-column-with-Python-source
pattern, when it's safe, what NOT to do (rename a key with
data), and where the keys appear across the codebase
- URL Routes table gets the two new endpoints
What's NOT in this commit (deferred per the brainstorm plan):
- JournalEntry model + manual web-entry UI (Phase A.2 — depends
on Konrad's Q7 answer about Vi/recipient field)
- Letterly inbound webhook (Phase B — integrations branch only,
depends on Q5 sample payload)
- Photos on site reports (Q9, defaulted to "future")
- Per-project metric templates (Q4, defaulted to "same set for all v1")
Reference plan: ~/.claude/plans/prancy-painting-brook.md (local).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
First integration: when a PayrollRecord is created, the app POSTs a
JSON summary to WEBHOOK_PAYSLIP_URL (env var) if set. Unset = feature
OFF; no network call, no behaviour change. Typical destination: a
Make.com / Zapier / n8n Catch-Hook URL that fans the event out to
Google Sheets / Airtable / Slack / etc. — no more Python required.
This is the highest-leverage starter integration per the research plan
at ~/.claude/plans/prancy-painting-brook.md (Section B). One webhook
sender unlocks 5000+ downstream destinations via visual workflow UIs,
and the pattern (post_save signal + env-var gate + try/except) becomes
the template for future event types.
Implementation:
- core/signals.py (new) — post_save receiver on PayrollRecord;
fires only on created=True; short-circuits when env var empty;
swallows all network errors with a WARNING log so payslip save
is never blocked
- core/apps.py — ready() imports signals for dispatcher registration
- config/settings.py — reads WEBHOOK_PAYSLIP_URL env var (default "")
- requirements.txt — adds requests>=2.32.0 (de facto Python HTTP lib,
no prior outbound-HTTP code in the codebase)
- CLAUDE.md — documents the env var + the non-fatal failure contract
+ points at PayslipWebhookTests for the behavioural spec
Payload shape: event, payslip_id, worker_id, worker_name, amount_paid
(as string for Decimal safety), payslip_date (ISO), work_log_count,
adjustment_count, admin_url. No unbounded text fields; no secrets.
Tests (4 new, PayslipWebhookTests):
- fires when configured with right payload
- no-op when env var unset
- swallows ConnectionError without breaking PayrollRecord.save()
- does NOT refire on subsequent .save() of an existing record
Full suite: 73/73.
Risks + rollback: trivial. Revert the commit, no data impact. Make.com
handles its own retries; if the webhook is down we just miss events
until it comes back.
Out of scope for v1 (deferred): other event types (adjustment.created,
loan.issued), HMAC signing, in-app retry queue, inbound webhooks, AI
integrations, public read-only API. All are on the roadmap in the plan
doc; each follows the same signal-based pattern and is cheap to add.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
The 4 action buttons at the top of /payroll/ were previously a mix
of btn-outline-info / btn-primary / btn-outline-success /
btn-outline-warning — three different treatments, with a lone solid
btn-primary (Batch Pay) pulling the eye disproportionately. Konrad
asked for a more uniform + pastel look.
New .btn-action-soft base class with per-button colour modifiers:
- Worker Lookup → soft blue (new --btn-action-lookup tokens)
- Batch Pay → soft amber (new --btn-action-pay tokens;
slightly deeper saturation to preserve its
"primary" role without breaking the uniform look)
- Add Adjustment → reuses --badge-bonus-* (green, "adding money"
semantic matches Bonus)
- Price Overtime → reuses --badge-overtime-* (mauve, same colour
as the Overtime badge on the Adjustments tab —
so the button matches the data it acts on)
All 4 now share:
- No border, solid pastel fill, contrasting text
- Same height, padding, border-radius (0.5rem)
- Subtle box-shadow lift on hover (filter: brightness)
- 1px press-down on active
- Accessible focus-visible outline in --accent
- Icons inherit text colour
Net CSS change: 4 new tokens (2 per theme × 2 themes) + 5 new
classes. Removes shadow-sm, btn-sm, btn-md-normal, fw-bold
one-offs — all handled by the base class.
docs/design-tokens.md updated to record the new token pairs.
Tests: 69/69.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Four buttons at top of /payroll/ currently mix 3 treatments (outline
+ solid btn-primary one-off). Design swaps all 4 to a unified
.btn-action-soft base class with per-button colour modifiers
(Lookup=blue, Pay=amber, Add=green, Price=mauve). Reuses existing
--badge-*-bg tokens for the Add + Price buttons; adds 2 new token
pairs for Lookup + Pay. Removes the shadow-sm / btn-sm / fw-bold
one-offs — the new class handles sizing + weight.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Konrad caught that /payroll/?status=loans was still using Bootstrap
defaults (bg-primary for Loan, bg-info for Advance) while the other
three tabs had moved to the semantic palette. The Preview-payslip
modal's Active Loans card had the same inconsistency in its JS-built
badge.
- Added .advance-flag-badge as a sibling to .loan-flag-badge; both
just reference the existing --badge-loan-* / --badge-advance-*
tokens so no new colours introduced.
- /payroll/?status=loans row badge: bg-primary/bg-info → loan-flag-
badge/advance-flag-badge.
- Worker-lookup / Preview-payslip modal JS: same swap on the badge
className.
Loan-family items now wear the same amber/blue colour pair on every
tab + modal they appear on. Transactional status (Active/Paid Off)
stays on Bootstrap greens/yellows — they're lifecycle, not type.
docs/design-tokens.md updated to record the new class + every place
the --badge-loan-* / --badge-advance-* tokens now appear.
Tests: 69/69.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Final whole-impl review on bce2619 caught two user-facing surfaces
still showing DB values instead of display labels:
1. By-Type group headers - _group_adjustments() used adj.type as
both the visible label AND the CSS data-type attribute. Split
into group.label (short display, for visible text) and
group.type_key (raw DB value, for the [data-type="X"] CSS
border-left selector).
2. Type filter popover checkboxes - adj_type_choices was a flat
list of DB values, so checkbox labels read "New Loan" /
"Advance Payment" / "Advance Repayment". Replaced with
PayrollAdjustment.TYPE_CHOICES (already a (db_value,
display_label) tuple list), and updated the template loop to
unpack both - label in <span>, DB value in the input value=.
Both surfaces now show Loan / Advance / Advance Repaid while
preserving the canonical DB values for CSS selectors + filter
form submissions.
Tests: 69/69.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Root cause of Konrad's narrow-wrap screenshot: display:flex was set
on .adj-group-header (a <tr>), which causes the browser to remove
the row from table layout. A flex-mode <tr> ignores colspan and
shrinks to intrinsic content width — which is why a row with
colspan=10 ended up rendering at ~80-100px and wrapping the meta
text into a 5-char column.
Moved display:flex, align-items, gap, and padding onto the single
<td> child. The td is a normal block box and flexes correctly,
putting icon + label + meta in a horizontal row with the meta
pushed to the right via margin-left:auto (now working since its
parent is a real flex container).
Also added white-space:nowrap on .adj-group-meta so the meta never
wraps mid-phrase even if a narrow viewport squeezes the cell.
Inline comment documents the <tr> vs <td> distinction so future
sessions don't re-introduce the bug.
Tests: 69/69.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Replaces the 4-branch Bootstrap-state conditional on the Pending
and History tabs with the semantic .badge-type-{{ adj.type|type_slug }}
palette that the Adjustments tab has been using. Now "Loan" badges
are the same colour in every tab instead of Pending=yellow /
Adjustments=amber.
Also recolours the Pending-tab "Loan" worker flag to the same amber
(.loan-flag-badge class). "Overdue" flag stays red - it's an urgency
signal, not a type signal, and we deliberately keep transactional
state colours (Bootstrap bg-success/bg-warning/bg-danger) separate
from the type palette so a green badge can only mean "Bonus" and
never ambiguously "Paid".
Threads 'additive_types' (list(ADDITIVE_TYPES)) into the base
payroll_dashboard context so the +/- sign logic works on Pending
and History too (was previously only set in the Adjustments-tab
branch).
Tests: 69/69.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Code-review follow-up on 1cf1304. /admin/core/payrolladjustment/
was still showing raw DB values (New Loan / Advance Payment /
Advance Repayment) in the Type list column because list_display
was the bare field name 'type', which Django renders via
str(obj.type).
Added a @admin.display method that returns obj.get_type_display()
and referenced it in list_display instead. Column header stays
'Type' and the column is still sortable by the underlying field.
list_filter kept on 'type' (DB value) - filter sidebar correctness
doesn't require the display label, and filtering works off the
canonical stored value.
Closes the last known "users see shorter labels everywhere" gap
from the Path A rename.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Closes the Task 3 design-goal gap: two user-facing modals (work-log
payroll preview in base.html, split-payslip preview in
payroll_dashboard.html) render adjustment types via JS reading AJAX
JSON. After Task 3's TYPE_CHOICES rename they were still showing
the old long labels because the backend endpoints
(work_log_payroll_ajax, preview_payslip) only emitted adj.type (DB
value), not the display label.
Added a 'type_label' field to the JSON payloads alongside the
existing 'type' field. JS at both render sites now reads
`adj.type_label || adj.type` — with the fallback so any stale
client-side JSON degrades gracefully to the DB value rather than
rendering blank.
Path A still holds: adj.type in JSON stays the DB value for any
identifier purposes; the new type_label is additive.
Tests: 69/69.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Path A rename - DB values untouched, only TYPE_CHOICES display
labels change:
'New Loan' -> shown as 'Loan'
'Advance Payment' -> shown as 'Advance'
'Advance Repayment' -> shown as 'Advance Repaid'
Templates that render the type as visible text switched from
{{ adj.type }} to {{ adj.get_type_display }}. Data attributes and
CSS class slugs keep the raw DB value (identifiers, not labels).
Zero data migration. Zero changes to ADDITIVE_TYPES / DEDUCTIVE_TYPES
constants, hardcoded string comparisons, CSS class names, test
fixtures, or any other code that references the canonical DB value.
Every historic PayrollAdjustment row keeps type='New Loan' /
'Advance Payment' / 'Advance Repayment' as stored.
Django's makemigrations generated a no-op AlterField migration to
record the choices-metadata change.
Tests: 69/69.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Adds a new CLAUDE.md section documenting the display/DB gap that
Path A of the UX Polish Pass creates: user sees 'Loan' / 'Advance'
/ 'Advance Repaid' while DB stores 'New Loan' / 'Advance Payment'
/ 'Advance Repayment'. Includes a lookup table, the rule for when
to use which (DB for logic, display for templates), and the failure
symptom so future Claude sessions don't chase ghost filters.
Ships BEFORE the rename so the doc is searchable from minute one.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
New doc covering the semantic colour palette: every badge token, its
hex values in both themes, its CSS class, and where it's used across
the app. Categorises tokens into "type-of-adjustment" (custom semantic
palette) vs "transactional state" (Bootstrap defaults) and explains
why the two must not share colours.
Intended to be the single source of truth for UI colour decisions.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Five tasks: (1) docs/design-tokens.md as the canonical colour
reference; (2) CLAUDE.md UI-vs-DB naming-drift note (ships BEFORE
the rename so it's searchable from minute one); (3) display-only
TYPE_CHOICES rename + auto-migration + template visible-text swap
to get_type_display; (4) badge colour unification on Pending +
History tabs + loan-flag recolor; (5) CSS root-cause fix for the
group-summary narrow-wrap bug (move display:flex from <tr> to <td>).
Execute via subagent-driven-development. Auto mode — no mid-execution
checkpoints.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Four UX asks bundled in one pass:
1+2. Display-only rename of adjustment types: 'New Loan' (DB) →
'Loan' (UI), 'Advance Payment' → 'Advance', 'Advance Repayment'
→ 'Advance Repaid'. DB values preserved forever — zero data
migration, zero formula / constant / CSS / test changes.
3. Unify badge colours across all payroll tabs using the existing
.badge-type-* semantic palette. Recolour Pending "With loans"
flag to match the Loan type colour.
4. Fix CSS bug in .adj-group-meta (margin-left:auto doesn't work
in a <td> — make the td a flex container).
Plus: new docs/design-tokens.md as the canonical colour reference,
and a crucial CLAUDE.md section documenting the UI-vs-DB naming
drift so future Claude sessions don't chase ghosts when writing
formulas / filters / ORM queries that reference the display label
instead of the DB value.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Three additions from this session's work:
1. Django ORM gotcha — PayrollAdjustment project double-attribution.
Documents the Coalesce pattern that solved the Apr 2026 perf-pass
double-count bug on Overtime adjustments.
2. Payroll dashboard query-count baselines — target ranges for /
and the four /payroll/ tabs after the perf pass, plus the
"spotting a regression" heuristic (>50% jump = N+1 reintroduced).
3. Profiling locally — Django Debug Toolbar — what it is, how it's
triple-gated, how to use it for N+1 hunting. Flags that the
package is already in requirements.txt so future sessions don't
need to install it.
Net: +35 lines, three new sections, no deletions.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Final whole-impl review catch on the Perf Quick-Wins Pass. Step 3
said "the mtime of the collected copy under staticfiles/ stays the
same, so the token doesn't bump." That's backwards — the token is
read from static/css/custom.css (the SOURCE file), so editing the
source DOES bump the token and Cloudflare correctly misses on the
next request. What actually breaks is the VM's response to the miss:
Apache serves stale bytes from staticfiles/ because collectstatic
hasn't refreshed the collected copy. New URL, old bytes behind it.
Rewording makes the causal chain correct so future Gemini/Claude
debugging "CSS change deployed but old file still shows" reaches
the right conclusion (run collectstatic on the VM) via the right
reasoning.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Spec-review catch on 61c485f: the batched GROUP BY aggregates for
unpaid-per-project and paid-per-project x month were running TWO
filtered queries and summing them in Python. Any adjustment with
BOTH project FK AND work_log.project set was double-counted.
Every Overtime adjustment fits that shape (price_overtime sets
both). So every unpaid Overtime was silently inflating the
outstanding-costs dashboard by its own amount, and every paid
Overtime inflated the Per-project-monthly-payroll stacked chart.
Fix: annotate Coalesce('project_id', 'work_log__project_id') so
each adjustment contributes to exactly one project (matches the
original Q(...) | Q(...) OR-filter semantics).
New regression test locks in the "count once" behaviour with an
Overtime adjustment that has both FKs set. Previously there was no
test covering the sum correctness of outstanding-costs - only
context-key presence.
Tests: 69/69. Query counts per tab: pending 24q / history 24q /
loans 25q / adjustments 32q (2 fewer per tab than 61c485f because
Coalesce folded two filtered queries into one).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Profiled /payroll/ under Django Debug Toolbar and confirmed heavy N+1
patterns in the shared payroll_dashboard() code path (shared by all four
tabs). Main wins:
1. outstanding_project_costs loop + project_chart_data loop previously
fired one PayrollAdjustment SELECT per project (outstanding) and per
(project x 6 months) (chart) — ~42+7 = 49 round-trips on a 7-project
dataset. Replaced with 4 GROUP BY aggregate queries keyed by
project_id / (project_id, month), merged in Python.
2. Per-worker Loan.exists() and get_worker_active_team() checks inside
the workers_data loop — pre-computed into a set + dict once, up-front.
3. team_workers_map loop used `team.workers.filter(active=True)` which
bypasses the prefetch cache; switched to a Prefetch(to_attr=) that
returns already-filtered active workers, dropping 6 duplicate SELECTs.
4. Adjustments tab: reused `paginator.count` for the "Total" stat card
(was firing a second identical COUNT(*)) and reused existing
all_workers / all_teams querysets instead of re-querying for the
filter popovers.
5. Hoisted shared lookups (all_workers, active_projects_list, chart
date-window) so duplicate ordering-identical SELECTs from multiple
call sites collapse into a single evaluated queryset.
===== Quick-Wins Pass A - before/after query counts =====
/ 15q, no duplicates (healthy, no fix)
/payroll/?status=pending 157q (before) -> 26q (after), 0 dupes
/payroll/?status=history 157q -> 26q, 0 dupes
/payroll/?status=loans 158q -> 27q, 0 dupes
/payroll/?status=adjustments 168q -> 34q, 0 dupes
CSS cache-bust token (0c42cde) is still expected to be the biggest
user-felt improvement of this pass — custom.css now holds at
Cloudflare's edge for its full 4h TTL instead of being re-fetched
from the VM on every page load. The payroll-dashboard query-count
cut (~131 SQL round-trips trimmed per render) is a meaningful
admin-UX latency win on top of that, especially under MySQL over
the Flatlogic network.
WeasyPrint confirmed still lazy-imported.
Test suite: 68/68.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Three followups on 7075269:
- config/urls.py: drop dead try/except ImportError fallback.
The settings.py gate already guarantees debug_toolbar is
importable before we reach this line, so the except branch
was unreachable and the re-import of include/path was
redundant (both imported at top of file).
- config/settings.py: SHOW_TOOLBAR_CALLBACK now returns True
unconditionally. The triple gate passed at settings-load time,
so re-checking DEBUG and _IS_DEV inside the lambda was
redundant. Comment corrected — the callback has nothing to
do with "stale cached pages".
- requirements.txt: inline comment noting django-debug-toolbar
is dev-only and gated.
No behavioural change. Tests: 68/68.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Double-gated install: only loads when DEBUG=true AND USE_SQLITE=true,
never in prod. Lets us profile SQL query counts on the dashboard and
payroll pages before attacking N+1 hotspots.
requirements.txt adds django-debug-toolbar==6.0.0
config/settings.py conditionally appends to INSTALLED_APPS + MIDDLEWARE
config/urls.py conditionally includes __debug__ route
No behavioural change to production.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Code-review followups on 16d4399:
- CLAUDE.md's "When CSS changes don't appear" diagnostic steps
were written for the old per-request token. Under mtime-based
caching, a stable ?v= number is the healthy expected state,
not a broken one. Rewrote steps 1 + 3 so someone debugging
a real production CSS issue gets the right advice.
- Dropped unused `original = cp._compute_cache_bust_token` line
in test_token_falls_back_if_file_missing - it misled readers
into thinking the function itself was patched. Added a one-
line comment clarifying the monkey-patch is path-only.
Tests: still 68/68.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
deployment_timestamp was int(time.time()) per-request, giving every
page load a new ?v=... query string on custom.css. Cloudflare treats
each unique URL as a new resource, so the CSS was fetched from the VM
on every page load — 64 KB over the wire per navigation.
Token now tied to static/css/custom.css mtime. The URL only changes
when the CSS actually changes, so Cloudflare can hold the file for
its full 4h TTL. Degraded-mode fallback preserves today's behaviour
if the file isn't on disk.
3 new CacheBustTokenTests; all 68 tests pass.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Four tasks: mtime cache-bust token + tests; install & gate Django
Debug Toolbar dev-only; profile + fix N+1 on /; profile + fix N+1 on
/payroll/ (all four tabs) with before/after summary in the final
commit message.
Execute via subagent-driven-development. Auto mode — no mid-execution
checkpoints.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Short design covering four changes: mtime-based CSS cache-bust token,
Django Debug Toolbar (dev-only) for profiling, N+1 fixes on Dashboard
and Payroll pages, and a before/after measurement in the commit message.
Scope is deliberately tight — plan B (template splitting) and plan C
(full audit) are deferred until plan A evidence lands.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Audit revealed several stale / missing items:
1. Wrong CSS selector for light theme — said `:root.light`, actual is
`[data-theme="light"]`. Task 2 of Adjustments caught this in the
implementer's self-review; the doc didn't get updated. Now correct.
2. `_report_config_modal (partial)` removed from templates list — the
file was deleted in commit 1d00a3a (retire modal).
3. `_adjustment_row.html` added to templates list — new partial, shared
by flat + grouped views on the Adjustments tab.
4. `format_tags.py` now lists all 5 filters: money, money_abs, type_slug,
url_replace, dictlookup (was just 'money').
5. New narrative paragraphs for:
- Inline Filters on /report/ (pill popovers, cross-filter, JSON gotcha)
- Adjustments tab (filter pills, badge palette, group-by, bulk delete)
- _delete_adjustment_with_cascade helper (shared by single+bulk)
- Pill-popover filter pattern (.adj-hidden-inputs + OK-rewrites-inputs)
6. Two new schema name-drifts: PayrollRecord.amount_paid (not total_amount
/ days_worked); Loan.principal_amount (not principal). Both bit an
implementer this session when writing test fixtures.
7. Two new Coding Style rules in the top section:
- Multi-line {# #} template comments are INVALID — use {% comment %}
(bit us 4× in this session). With caveat that literal {# or #} can't
appear inside a {% comment %} block either.
- Duplicate id= attributes silently steal event handlers — grep before
assigning (caught adjSelectAll collision between table header + modal).
Now 707 lines, 24 sections. Future sessions should have the context to
avoid the mistakes this session made.
Konrad's feedback on the shipped Adjustments tab: "this interface
layout is very ugly. And the selection dropdown menus text is a bit
large." Plus: the 'Show as' toggle sits too close to the filter bar.
Design doc: docs/plans/2026-04-23-adjustments-filter-bar-v2-design.md
Changes:
1. All 5 filters become pill-popovers of identical shape
- Type / Workers / Teams: unchanged (already pills)
- Status: was <select> + <label>, now pill → popover with 3 radios
- Date: was inline inputs + preset links + '...' toggle, now pill →
popover with Single/Range mode toggle + picker(s) + presets + OK/Cancel
- Pill labels update to 'Status: Unpaid' / 'Date: 24 Apr 2026' /
'Date: 20 Apr – 26 Apr 2026' for at-a-glance state
- Apply + Clear pushed to right end via .adj-apply-group (margin-left: auto)
2. Popover density pass
- .adj-checkbox-list / .adj-radio-list font-size 0.8rem (~12.8px)
- .adj-cb-row padding trimmed to 0.15rem 0.25rem
- Checkbox visual size 0.9em
- Popover footer buttons 0.75rem font, 0.25rem 0.6rem padding
- Popover max-width 360px (was ~420px)
- 7-type popover drops from ~320px tall to ~240px
3. Spacing fix above 'Show as:' toggle
- .adj-groupby-toggle now has margin-top: 1rem + margin-bottom: 0.75rem
- Clear visual separation from the sticky filter bar
4. Filter-bar alignment
- align-items: center (was end, now all children are same height)
- Gap tightened to 0.5rem
Backend contract unchanged (query params identical). No test changes
(65/65 still pass). Committed popover JS uses the same
.adj-hidden-inputs pattern as the checkbox filters — Status + Date
each have their own commit/revert logic that rewrites their hidden
inputs on OK. XSS-safe throughout (replaceChildren() + textContent,
no innerHTML with user data).
Gated the generic checkbox-popover OK/Cancel handler to
['type', 'worker', 'team'] so the new Status/Date popovers aren't
accidentally re-committed via commitCheckboxes.