Repository navigation
feat(ops): remaining Operations surfaces (overview through audit) - #4
Conversation
Replace Coming Next placeholders for overview, matching, recovery, dispatch, claims, schedule, and audit with real pages on the typed API client. QA queue and workspace are unchanged. Pure helpers under src/app/ops/_lib keep presentation and queue logic out of components (and out of the shared src/lib spine) with tests for SLA bucketing, explainable matching, stale location freshness, recovery paths, and schedule events. Nav ROLE_NAV ready flags are left false to avoid colliding with the shared spine; flip them when integrating.
|
Warning Review limit reached
Next review available in: 11 minutes Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available. How can I continue?After more reviews become available, a review can be triggered using the To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews. How do review limits work?CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability. For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window. Please refer docs for additional details. Review details⚙️ Run configurationConfiguration used: defaults Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (1)
📝 WalkthroughWalkthroughThe Operations area now includes functional overview, matching, dispatch, claims, recovery, schedule, and audit pages. Pure helper modules derive queues, actions, events, recovery items, supplier explanations, location states, and display labels. Tests cover the helper behavior. ChangesOperations helper foundation
Estimated code review effort: 5 (Critical) | ~120 minutes Sequence Diagram(s)sequenceDiagram
participant OpsOverviewPage
participant Operations APIs
participant overview helpers
participant Operations UI
OpsOverviewPage->>Operations APIs: Load orders, claims, and issues
Operations APIs-->>OpsOverviewPage: Return operational data
OpsOverviewPage->>overview helpers: Build buckets and next action
overview helpers-->>OpsOverviewPage: Return queue summaries and action
OpsOverviewPage->>Operations UI: Render action card and queue cards
Possibly related PRs
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
🧪 Generate unit tests (beta)
Comment |
Claims keeps one page-surface primary (Raise claim). The second primary is the dialog footer submit — a bounded panel CTA, not a repeated row action.
Yellow budget check —
|
There was a problem hiding this comment.
Actionable comments posted: 14
🧹 Nitpick comments (11)
src/app/ops/_lib/recovery.ts (1)
33-40: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueRemove
client_correctionfromFAILED_PATH_STATES.Line 111 excludes
client_correctionfrom the failed-path branch because the dedicated branch at line 96 already handles it. Keeping the state in the set and then excluding it makes the intent unclear.♻️ Proposed refactor
const FAILED_PATH_STATES = new Set([ - "client_correction", // Defensive: if API ever surfaces these explicit failures "delivery_failed", "supplier_declined", "cancelled", "failed_qc", ]); @@ - if (FAILED_PATH_STATES.has(order.state) && order.state !== "client_correction") { + if (FAILED_PATH_STATES.has(order.state)) {Also applies to: 111-111
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/app/ops/_lib/recovery.ts` around lines 33 - 40, Remove "client_correction" from the FAILED_PATH_STATES set, leaving the dedicated client_correction handling branch unchanged and preserving the remaining failed-path states.src/app/ops/_lib/overview.ts (1)
61-100: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueExtract the shared deadline parsing.
isSlaAtRiskandisSlaBreachedrepeat the same candidate parsing and the same terminal-state exclusions. Line 88 also repeatspayout_released, whichTERMINAL_STATESalready contains.A single helper removes the drift risk between the two predicates.
♻️ Proposed refactor
+const SLA_EXEMPT_STATES = new Set([ + ...TERMINAL_STATES, + "completed", + "delivered", +]); + +function soonestDeadlineMs( + order: Pick<Order, "state" | "deadline" | "promisedDate">, +): number | null { + if (SLA_EXEMPT_STATES.has(order.state)) return null; + const candidates = [order.deadline, order.promisedDate] + .filter((v): v is string => Boolean(v)) + .map((v) => Date.parse(v)) + .filter((t) => !Number.isNaN(t)); + return candidates.length ? Math.min(...candidates) : null; +} + export function isSlaAtRisk( order: Pick<Order, "state" | "deadline" | "promisedDate">, nowMs: number = Date.now(), ): boolean { - if (TERMINAL_STATES.has(order.state)) return false; - if (order.state === "completed" || order.state === "delivered") return false; - - const candidates = [order.deadline, order.promisedDate] - .filter((v): v is string => Boolean(v)) - .map((v) => Date.parse(v)) - .filter((t) => !Number.isNaN(t)); - - if (!candidates.length) return false; - - const soonest = Math.min(...candidates); - const windowMs = SLA_NEAR_HOURS * 60 * 60 * 1000; - return soonest <= nowMs + windowMs; + const soonest = soonestDeadlineMs(order); + if (soonest === null) return false; + return soonest <= nowMs + SLA_NEAR_HOURS * 60 * 60 * 1000; } export function isSlaBreached( order: Pick<Order, "state" | "deadline" | "promisedDate">, nowMs: number = Date.now(), ): boolean { - if (TERMINAL_STATES.has(order.state)) return false; - if ( - order.state === "completed" || - order.state === "delivered" || - order.state === "payout_released" - ) { - return false; - } - - const candidates = [order.deadline, order.promisedDate] - .filter((v): v is string => Boolean(v)) - .map((v) => Date.parse(v)) - .filter((t) => !Number.isNaN(t)); - - if (!candidates.length) return false; - return Math.min(...candidates) < nowMs; + const soonest = soonestDeadlineMs(order); + if (soonest === null) return false; + return soonest < nowMs; }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/app/ops/_lib/overview.ts` around lines 61 - 100, Extract the shared terminal-state check and deadline parsing from isSlaAtRisk and isSlaBreached into a private helper, then reuse its result in both predicates while preserving their existing time comparisons. Remove the redundant completed/delivered checks and the explicit payout_released exclusion, relying on TERMINAL_STATES for all terminal states.src/app/ops/recovery/page.tsx (1)
338-355: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick winDo not render a Resolve control that cannot act.
issues.find((i) => i.id === r.issueId)can returnundefined. The Button still renders, and the click handler then does nothing. The operator gets no dialog and no message.
buildRecoveryItemsbuildsopen_issuerows from the sameissuesarray, so the lookup normally succeeds. It can still fail if a later refactor filters the rows or the arrays diverge between renders. Compute the issue before you decide what to render.♻️ Proposed refactor
rowActions={(r) => { - if (r.kind === "open_issue" && r.issueId) { - const issue = issues.find((i) => i.id === r.issueId); - return ( - <Button - variant="secondary" - onClick={() => { - if (issue) { - setResolveTarget(issue); - setResolution(""); - setActionError(null); - } - }} - > - Resolve - </Button> - ); - } + const issue = + r.kind === "open_issue" && r.issueId + ? issues.find((i) => i.id === r.issueId) + : undefined; + if (issue) { + return ( + <Button + variant="secondary" + onClick={() => { + setResolveTarget(issue); + setResolution(""); + setActionError(null); + }} + > + Resolve + </Button> + ); + }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/app/ops/recovery/page.tsx` around lines 338 - 355, Update the rowActions callback to resolve the matching issue before rendering the control, and return no Resolve button when the lookup is undefined. Keep the existing click behavior for valid issues, using the resolved issue consistently when setting resolveTarget.src/app/ops/overview/page.tsx (2)
181-202: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winDo not rely on
aria-labelon a<p>element, and surfacebucket.urgent.Two points in this card:
- Line 196-201 puts
aria-labelon a<p>.aria-labelis not reliably exposed on a static, non-landmark element. Screen reader users can hear the bare number without its queue name. Use visible text plus a visually hidden label instead.buildOverviewBucketscomputesurgentand the type documents it as "the recommended next focus", butBucketCardnever reads it. The derived priority signal is dropped. If you render it, useStatusChipso the signal is not carried by color alone, per the coding guidelines.As per coding guidelines: "Status must never be conveyed by color alone; use
StatusChipwith an icon, label, and tone, readable in greyscale."♻️ Proposed refactor
function BucketCard({ bucket }: { bucket: OverviewBucket }) { return ( <li className="gg-card flex flex-col gap-2"> <div className="flex items-start justify-between gap-2"> <div className="min-w-0"> <p className="text-body text-text-primary m-0" style={{ fontFamily: "var(--font-medium)" }} > {bucket.label} </p> <p className="text-caption text-text-muted m-0 mt-1"> {bucket.description} </p> + {bucket.urgent ? ( + <div className="mt-2"> + <StatusChip + tone="warning" + label="Needs attention" + icon="triangle-alert" + /> + </div> + ) : null} </div> - <p - className="text-h2 text-text-primary m-0 tabular-nums" - aria-label={`${bucket.count} in ${bucket.label}`} - > - {bucket.count} - </p> + <p className="text-h2 text-text-primary m-0 tabular-nums"> + <span aria-hidden>{bucket.count}</span> + <span className="sr-only">{`${bucket.count} in ${bucket.label}`}</span> + </p> </div>🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/app/ops/overview/page.tsx` around lines 181 - 202, Update BucketCard to remove aria-label from the static count paragraph, render the bucket label as visible context alongside the count, and add a visually hidden label where needed for screen-reader clarity. Surface bucket.urgent with StatusChip, including an icon, explicit label, and appropriate tone so urgency is not conveyed by color alone.Source: Coding guidelines
82-84: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winGive the Refresh control feedback while a reload runs.
loading && !datashowsLoadingBlockonly on the first load. When the operator presses Refresh,loadingbecomestruebut the screen does not change and the button stays enabled. The operator can queue several concurrent loads with no signal.Disable the control and label it while
loadingis true.♻️ Proposed refactor
- <Button variant="secondary" onClick={() => void load()}> - Refresh - </Button> + <Button + variant="secondary" + onClick={() => void load()} + disabled={loading} + > + {loading ? "Refreshing…" : "Refresh"} + </Button>Also applies to: 109-111
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/app/ops/overview/page.tsx` around lines 82 - 84, Update the Refresh control in the operations overview component to use the existing loading state: disable it while loading is true and show a loading-specific label instead of “Refresh.” Keep the initial LoadingBlock behavior for loading without data unchanged, and ensure the control returns to its normal enabled label after loading completes.src/app/ops/matching/page.tsx (2)
397-413: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winMove the category-code formatting into a pure helper.
Lines 400-407 re-implement the title-casing logic that already exists in
presentZone(src/app/ops/_lib/present.ts:31-35). Add apresentCategoryCodehelper insrc/app/ops/_lib/present.tsand add its test undersrc/app/ops/_lib/__tests__/. This keeps the page free of formatting logic and removes the duplication.As per coding guidelines: "Keep ops-only pure helpers in
src/app/ops/_lib/and place their tests undersrc/app/ops/_lib/__tests__/."♻️ Proposed extraction
Add to
src/app/ops/_lib/present.ts:export function presentCategoryCode(code: string): string { return code .split(/[_-]/) .filter(Boolean) .map((part) => part.charAt(0).toUpperCase() + part.slice(1)) .join(" "); }Then in the page:
{c.services.length ? c.services - .map((s) => { - const cat = s.categoryCode - .split(/[_-]/) - .map( - (p) => - p.charAt(0).toUpperCase() + - p.slice(1), - ) - .join(" "); - return `${cat} (${presentServiceState(s.state).label})`; - }) + .map( + (s) => + `${presentCategoryCode(s.categoryCode)} (${presentServiceState(s.state).label})`, + ) .join("; ") : "None listed"}🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/app/ops/matching/page.tsx` around lines 397 - 413, Extract the category-code title-casing logic from the services rendering in the matching page into a pure presentCategoryCode helper in present.ts, including filtering empty segments as shown by the requested behavior. Update the page to import and use presentCategoryCode while preserving the existing service-state formatting and “None listed” fallback, and add focused tests under the ops _lib __tests__ directory.Source: Coding guidelines
97-121: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick winGuard against stale eligible-supplier responses.
loadEligiblehas no cancellation. If the operator changes the selected order while a request is in flight, a late response can overwrite the newer result, because state is set without checking the requestedorderId. Add an abort or a request-id guard in the effect.♻️ Proposed guard using an effect-scoped flag
- const loadEligible = useCallback(async (orderId: string) => { + const loadEligible = useCallback(async ( + orderId: string, + isCurrent: () => boolean = () => true, + ) => { setLoadingEligible(true); setEligibleError(null); setEligible(null); setActionError(null); try { const result = await getEligibleSuppliers(orderId); - setEligible(result); + if (isCurrent()) setEligible(result); } catch (err) { - setEligible(null); + if (!isCurrent()) return; + setEligible(null); if (err instanceof ApiError) { setEligibleError( `Could not load eligible suppliers (${err.code}).`, ); } else { setEligibleError("Network error loading eligible suppliers."); } } finally { - setLoadingEligible(false); + if (isCurrent()) setLoadingEligible(false); } }, []); useEffect(() => { - if (selectedId) void loadEligible(selectedId); + if (!selectedId) return; + let active = true; + void loadEligible(selectedId, () => active); + return () => { + active = false; + }; }, [selectedId, loadEligible]);🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/app/ops/matching/page.tsx` around lines 97 - 121, Guard the loadEligible state updates against responses from superseded requests when selectedId changes. Add an effect-scoped cancellation flag or request identifier around the loadEligible invocation, and check it before applying eligible data or errors; ensure cleanup invalidates the prior request while preserving loading cleanup for the active request.src/app/ops/dispatch/page.tsx (1)
99-113: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick winReset
locLoadingin afinallyblock.Line 113 runs only if
await Promise.all(...)resolves. Each inner task catches its own error today, so a rejection is unlikely. The flag is still not protected against a future change that lets a rejection escape. If that happens, the "Refresh location" button stays disabled for the session. Move both state updates into afinallyblock.♻️ Proposed fix
setLocLoading(true); const next: LocationMap = {}; - await Promise.all( - trackable.map(async (o) => { - try { - const ping = await getDispatchLocation(o.id); - next[o.id] = presentLocation(ping, o.state); - } catch { - next[o.id] = presentLocation(null, o.state); - } - }), - ); - // In-memory only for this view refresh. - setLocations(next); - setLocLoading(false); + try { + await Promise.all( + trackable.map(async (o) => { + try { + const ping = await getDispatchLocation(o.id); + next[o.id] = presentLocation(ping, o.state); + } catch { + next[o.id] = presentLocation(null, o.state); + } + }), + ); + // In-memory only for this view refresh. + setLocations(next); + } finally { + setLocLoading(false); + }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/app/ops/dispatch/page.tsx` around lines 99 - 113, Update the location refresh flow around the trackable Promise.all operation so setLocations(next) and setLocLoading(false) execute in a finally block, ensuring the loading flag resets even if a task rejection escapes. Preserve the existing per-item fallback behavior and only finalize the view state after the refresh attempt completes.Source: Linters/SAST tools
src/app/ops/audit/page.tsx (2)
363-367: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winThe inline error block is unreachable.
The catch at Line 109 always sets
entriestonull, so the guard at Line 242 (error && !entries) returnsErrorStatebefore this markup renders. Either keep the previous entries on a failed refresh and show this inline alert, or delete the block. Keeping the previous entries is the better behavior for a refresh failure, because the operator does not lose the loaded table.♻️ Proposed change
} catch (err) { - setEntries(null); if (err instanceof ApiError) {Keep the guard at Line 242 as
error && !entries, so the first load still showsErrorStateand a later refresh failure shows the inline alert.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/app/ops/audit/page.tsx` around lines 363 - 367, Update the audit page refresh error handling so the catch path preserves existing entries instead of always setting entries to null. Keep the existing error && !entries guard and inline error rendering, ensuring initial-load failures use ErrorState while refresh failures retain the table and display the alert.
34-84: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueExtract the repeated title-case helper.
Lines 43-68 repeat the same
split(/[_-]/) → capitalize → join(" ")chain four times.src/app/ops/_lib/present.tsalready holds the ops label helpers. Move atitleCasehelper there and reuse it here.♻️ Proposed refactor
+import { titleCase } from "`@/app/ops/_lib/present`"; + function detailSummary(detail: Record<string, unknown> | null): string { @@ if (typeof detail.status === "string") { - parts.push( - `Status ${String(detail.status) - .split(/[_-]/) - .map((p) => p.charAt(0).toUpperCase() + p.slice(1)) - .join(" ")}`, - ); + parts.push(`Status ${titleCase(detail.status)}`); } if (typeof detail.kind === "string") { - parts.push( - String(detail.kind) - .split(/[_-]/) - .map((p) => p.charAt(0).toUpperCase() + p.slice(1)) - .join(" "), - ); + parts.push(titleCase(detail.kind)); }Apply the same change to
detail.categoryCode.As per coding guidelines: "Keep ops-only pure helpers in
src/app/ops/_lib/".🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/app/ops/audit/page.tsx` around lines 34 - 84, Extract the repeated underscore/hyphen label formatting from detailSummary into a titleCase helper in the existing ops presentation helper module src/app/ops/_lib/present.ts, then import and reuse it for detail.status, detail.kind, and detail.categoryCode. Preserve the current capitalization and spacing behavior, including the categoryCode formatting.Source: Coding guidelines
src/app/ops/schedule/page.tsx (1)
265-284: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winComplete the ARIA grid structure or drop the grid roles.
The container uses
role="grid"and the children userole="gridcell". Agridcellmust be a child of an element withrole="row". Without a row, assistive technology reports an invalid grid and can skip the cells. The simplest fix is to remove the grid roles and use a list, because this layout is a set of day columns, not a data grid.♿ Proposed fix
- <div - className="grid grid-cols-7 gap-2" - role="grid" - aria-label="Week schedule" - > + <ul + className="m-0 grid list-none grid-cols-7 gap-2 p-0" + aria-label="Week schedule" + >- <div + <li key={day.toISOString()} - role="gridcell" className="gg-card min-h-[8rem] flex flex-col gap-2 p-2" >Close the elements with
</li>and</ul>.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/app/ops/schedule/page.tsx` around lines 265 - 284, Remove the `role="grid"` and `role="gridcell"` attributes from the schedule container and day elements, and convert the wrapper and mapped day columns to the appropriate `ul`/`li` structure. Preserve the existing seven-day layout and content while closing each day item with `</li>` and the list with `</ul>`.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@src/app/ops/_lib/dispatch.ts`:
- Around line 65-115: Update the location-status function so every orderState
outside TRACKING_ACTIVE_STATES returns the appropriate not_tracking result
before evaluating ping, including rider_assigned orders with a ping. Preserve
the existing ready_for_dispatch and fallback labels, and add a regression test
covering rider_assigned with a ping that expects freshness not_tracking.
In `@src/app/ops/_lib/overview.ts`:
- Around line 273-307: Update the SLA sorting in the breached and near-order
selection to reuse one timestamp helper that takes the minimum valid timestamp
from deadline and promisedDate, matching isSlaBreached and isSlaAtRisk. Make the
helper return Infinity when both dates are missing or unparsable, and use it in
both comparators instead of the current promisedDate-first Date.parse
expressions.
In `@src/app/ops/_lib/recovery.ts`:
- Line 42: Update the stalled-assignment detection using STALL_STATES so
supplier_assigned orders are included only when order.updatedAt exceeds the
established assignment-age threshold; preserve the existing stalled_assignment
row creation for qualifying orders and exclude recent assignments from the
recovery queue.
In `@src/app/ops/_lib/schedule.ts`:
- Around line 210-219: Remove the entire no-op promised-date conditional block
after the existing event-generation logic in the schedule construction flow,
including its Date.parse check and events.some scan; retain the surrounding
behavior and comments unrelated to this dead code.
- Around line 276-299: Update groupEventsByDay to derive dayKey from the Date’s
local year, month, and day components instead of d.toISOString(), preserving the
existing invalid-date skip, sorting, labels, and event ordering so grouping
matches rangeForView, filterEventsInRange, and WeekGrid local-day behavior.
In `@src/app/ops/audit/page.tsx`:
- Around line 96-126: Update the audit page’s load/effect flow to stop automatic
requests when orderId or actorId changes: store those text-filter values in
useRef (or equivalent call-time state), have load read the current ref values,
and remove them from load’s callback dependencies. Keep the initial effect and
Select-filter refetch behavior intact, while preserving the explicit “Apply
filters” submission for text filters.
In `@src/app/ops/claims/page.tsx`:
- Around line 116-124: Update openDialog to default raiseOrderId from the first
non-draft order, matching the predicate used by the Select options; also render
the same claimableOrders collection in the Select so the default always
corresponds to a selectable order.
In `@src/app/ops/dispatch/page.tsx`:
- Around line 58-65: Update the dispatch page flow around listDispatchOffers and
the component state to capture offer-loading failures in an offersError state
instead of converting them silently to an empty list. Render an honest
unavailable message for the offers section when offersError is set, while
preserving the normal empty-list rendering for successful responses with no
offers.
- Around line 320-326: Remove defaultSortId="status" from the DataTable in the
dispatch board so the ordering produced by filterDispatchOrders is preserved;
leave the existing columns and row data unchanged.
- Around line 190-218: Update the location column cell rendering to show a
loading label and non-error loading presentation while locLoading is true,
instead of treating absent locations as missing via presentLocation(null,
o.state). Add locLoading to the relevant useMemo dependency array so the column
updates during initial loading and refreshes, while preserving the existing
location display once loading completes.
In `@src/app/ops/matching/page.tsx`:
- Around line 261-269: Update the selected-state variant in the rowActions
Button to use an allowed dense queue action variant, replacing "default" with
"outline" or "secondary"; keep the unselected variant and selection behavior
unchanged.
In `@src/app/ops/page.tsx`:
- Line 4: Update the ROLE_NAV.ops_admin entry for /ops/overview to set ready:
true and remove or clear placeholderBody, then revise the associated readiness
test to expect the route as available rather than a placeholder.
In `@src/app/ops/recovery/page.tsx`:
- Around line 393-408: Update the Resolution Textarea in the recovery page to
expose submitResolve validation state to assistive technology: set aria-invalid
when actionError exists and aria-describedby to the error paragraph’s stable id,
and assign that id to the paragraph. Keep the existing error rendering and
required behavior unchanged.
In `@src/app/ops/schedule/page.tsx`:
- Around line 111-118: Update toggleKind to pass null when the resulting kinds
set is empty, while preserving the Set for non-empty selections. Ensure
filterEventsInRange continues treating null as no kind filter so deselecting
every event type produces the intended empty state and matching copy.
---
Nitpick comments:
In `@src/app/ops/_lib/overview.ts`:
- Around line 61-100: Extract the shared terminal-state check and deadline
parsing from isSlaAtRisk and isSlaBreached into a private helper, then reuse its
result in both predicates while preserving their existing time comparisons.
Remove the redundant completed/delivered checks and the explicit payout_released
exclusion, relying on TERMINAL_STATES for all terminal states.
In `@src/app/ops/_lib/recovery.ts`:
- Around line 33-40: Remove "client_correction" from the FAILED_PATH_STATES set,
leaving the dedicated client_correction handling branch unchanged and preserving
the remaining failed-path states.
In `@src/app/ops/audit/page.tsx`:
- Around line 363-367: Update the audit page refresh error handling so the catch
path preserves existing entries instead of always setting entries to null. Keep
the existing error && !entries guard and inline error rendering, ensuring
initial-load failures use ErrorState while refresh failures retain the table and
display the alert.
- Around line 34-84: Extract the repeated underscore/hyphen label formatting
from detailSummary into a titleCase helper in the existing ops presentation
helper module src/app/ops/_lib/present.ts, then import and reuse it for
detail.status, detail.kind, and detail.categoryCode. Preserve the current
capitalization and spacing behavior, including the categoryCode formatting.
In `@src/app/ops/dispatch/page.tsx`:
- Around line 99-113: Update the location refresh flow around the trackable
Promise.all operation so setLocations(next) and setLocLoading(false) execute in
a finally block, ensuring the loading flag resets even if a task rejection
escapes. Preserve the existing per-item fallback behavior and only finalize the
view state after the refresh attempt completes.
In `@src/app/ops/matching/page.tsx`:
- Around line 397-413: Extract the category-code title-casing logic from the
services rendering in the matching page into a pure presentCategoryCode helper
in present.ts, including filtering empty segments as shown by the requested
behavior. Update the page to import and use presentCategoryCode while preserving
the existing service-state formatting and “None listed” fallback, and add
focused tests under the ops _lib __tests__ directory.
- Around line 97-121: Guard the loadEligible state updates against responses
from superseded requests when selectedId changes. Add an effect-scoped
cancellation flag or request identifier around the loadEligible invocation, and
check it before applying eligible data or errors; ensure cleanup invalidates the
prior request while preserving loading cleanup for the active request.
In `@src/app/ops/overview/page.tsx`:
- Around line 181-202: Update BucketCard to remove aria-label from the static
count paragraph, render the bucket label as visible context alongside the count,
and add a visually hidden label where needed for screen-reader clarity. Surface
bucket.urgent with StatusChip, including an icon, explicit label, and
appropriate tone so urgency is not conveyed by color alone.
- Around line 82-84: Update the Refresh control in the operations overview
component to use the existing loading state: disable it while loading is true
and show a loading-specific label instead of “Refresh.” Keep the initial
LoadingBlock behavior for loading without data unchanged, and ensure the control
returns to its normal enabled label after loading completes.
In `@src/app/ops/recovery/page.tsx`:
- Around line 338-355: Update the rowActions callback to resolve the matching
issue before rendering the control, and return no Resolve button when the lookup
is undefined. Keep the existing click behavior for valid issues, using the
resolved issue consistently when setting resolveTarget.
In `@src/app/ops/schedule/page.tsx`:
- Around line 265-284: Remove the `role="grid"` and `role="gridcell"` attributes
from the schedule container and day elements, and convert the wrapper and mapped
day columns to the appropriate `ul`/`li` structure. Preserve the existing
seven-day layout and content while closing each day item with `</li>` and the
list with `</ul>`.
🪄 Autofix
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro Plus
Run ID: ba974d9e-9af0-44db-ba9c-ecd6f62897d6
📒 Files selected for processing (16)
AGENTS.mdsrc/app/ops/_lib/__tests__/ops-helpers.test.tssrc/app/ops/_lib/dispatch.tssrc/app/ops/_lib/matching.tssrc/app/ops/_lib/overview.tssrc/app/ops/_lib/present.tssrc/app/ops/_lib/recovery.tssrc/app/ops/_lib/schedule.tssrc/app/ops/audit/page.tsxsrc/app/ops/claims/page.tsxsrc/app/ops/dispatch/page.tsxsrc/app/ops/matching/page.tsxsrc/app/ops/overview/page.tsxsrc/app/ops/page.tsxsrc/app/ops/recovery/page.tsxsrc/app/ops/schedule/page.tsx
| if (!TRACKING_ACTIVE_STATES.has(orderState) && !ping) { | ||
| if (orderState === "ready_for_dispatch") { | ||
| return { | ||
| freshness: "not_tracking", | ||
| label: "No rider yet", | ||
| }; | ||
| } | ||
| if (orderState === "rider_assigned") { | ||
| return { | ||
| freshness: "not_tracking", | ||
| label: "Tracking starts at pickup", | ||
| }; | ||
| } | ||
| return { | ||
| freshness: "missing", | ||
| label: "No location", | ||
| }; | ||
| } | ||
|
|
||
| if (!ping) { | ||
| return { | ||
| freshness: "missing", | ||
| label: "No location yet", | ||
| }; | ||
| } | ||
|
|
||
| const atMs = Date.parse(ping.at); | ||
| const ageMs = Number.isNaN(atMs) ? Number.POSITIVE_INFINITY : nowMs - atMs; | ||
|
|
||
| if (ageMs > staleAfterMs) { | ||
| return { | ||
| freshness: "stale", | ||
| label: "Location stale", | ||
| lat: ping.lat, | ||
| lng: ping.lng, | ||
| accuracy: ping.accuracy, | ||
| at: ping.at, | ||
| ageMs, | ||
| }; | ||
| } | ||
|
|
||
| return { | ||
| freshness: "live", | ||
| label: "Location live", | ||
| lat: ping.lat, | ||
| lng: ping.lng, | ||
| accuracy: ping.accuracy, | ||
| at: ping.at, | ||
| ageMs, | ||
| }; | ||
| } |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
Do not present location tracking before pickup.
OpsDispatchPage.refreshLocations fetches pings for "rider_assigned" orders. If the API returns a ping, this function skips the not_tracking branch and returns "Location live" or "Location stale".
Gate every state outside TRACKING_ACTIVE_STATES before evaluating ping. Add a regression test with a ping and "rider_assigned" state that expects not_tracking.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@src/app/ops/_lib/dispatch.ts` around lines 65 - 115, Update the
location-status function so every orderState outside TRACKING_ACTIVE_STATES
returns the appropriate not_tracking result before evaluating ping, including
rider_assigned orders with a ping. Preserve the existing ready_for_dispatch and
fallback labels, and add a regression test covering rider_assigned with a ping
that expects freshness not_tracking.
| const breached = active | ||
| .filter((o) => isSlaBreached(o, nowMs)) | ||
| .sort((a, b) => { | ||
| const ta = Date.parse(a.promisedDate || a.deadline || "") || 0; | ||
| const tb = Date.parse(b.promisedDate || b.deadline || "") || 0; | ||
| return ta - tb; | ||
| })[0]; | ||
| if (breached) { | ||
| return { | ||
| title: "SLA breached", | ||
| body: `${breached.title} is past its deadline or promised date.`, | ||
| href: `/ops/qa/${breached.id}`, | ||
| cta: "Open order", | ||
| orderId: breached.id, | ||
| orderTitle: breached.title, | ||
| }; | ||
| } | ||
|
|
||
| const near = active | ||
| .filter((o) => isSlaAtRisk(o, nowMs)) | ||
| .sort((a, b) => { | ||
| const ta = Date.parse(a.promisedDate || a.deadline || "") || 0; | ||
| const tb = Date.parse(b.promisedDate || b.deadline || "") || 0; | ||
| return ta - tb; | ||
| })[0]; | ||
| if (near) { | ||
| return { | ||
| title: "Deadline approaching", | ||
| body: `${near.title} is within the next ${SLA_NEAR_HOURS} hours.`, | ||
| href: `/ops/qa/${near.id}`, | ||
| cta: "Open order", | ||
| orderId: near.id, | ||
| orderTitle: near.title, | ||
| }; | ||
| } |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
Align the SLA sort key with the SLA predicates.
isSlaBreached and isSlaAtRisk use the minimum of deadline and promisedDate. Both comparators here use promisedDate first and read deadline only when promisedDate is falsy. An order whose promisedDate is later than its deadline therefore sorts by a date that did not trigger the breach.
Date.parse(...) || 0 also maps an unparsable date string to 0. That order then sorts as the most overdue and wins the next-action slot.
Reuse one timestamp helper and map missing or unparsable values to Infinity.
🐛 Proposed fix
+function slaSortKey(order: Order): number {
+ const candidates = [order.deadline, order.promisedDate]
+ .filter((v): v is string => Boolean(v))
+ .map((v) => Date.parse(v))
+ .filter((t) => !Number.isNaN(t));
+ return candidates.length ? Math.min(...candidates) : Number.POSITIVE_INFINITY;
+}
+
const breached = active
.filter((o) => isSlaBreached(o, nowMs))
- .sort((a, b) => {
- const ta = Date.parse(a.promisedDate || a.deadline || "") || 0;
- const tb = Date.parse(b.promisedDate || b.deadline || "") || 0;
- return ta - tb;
- })[0];
+ .sort((a, b) => slaSortKey(a) - slaSortKey(b))[0];
@@
const near = active
.filter((o) => isSlaAtRisk(o, nowMs))
- .sort((a, b) => {
- const ta = Date.parse(a.promisedDate || a.deadline || "") || 0;
- const tb = Date.parse(b.promisedDate || b.deadline || "") || 0;
- return ta - tb;
- })[0];
+ .sort((a, b) => slaSortKey(a) - slaSortKey(b))[0];📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| const breached = active | |
| .filter((o) => isSlaBreached(o, nowMs)) | |
| .sort((a, b) => { | |
| const ta = Date.parse(a.promisedDate || a.deadline || "") || 0; | |
| const tb = Date.parse(b.promisedDate || b.deadline || "") || 0; | |
| return ta - tb; | |
| })[0]; | |
| if (breached) { | |
| return { | |
| title: "SLA breached", | |
| body: `${breached.title} is past its deadline or promised date.`, | |
| href: `/ops/qa/${breached.id}`, | |
| cta: "Open order", | |
| orderId: breached.id, | |
| orderTitle: breached.title, | |
| }; | |
| } | |
| const near = active | |
| .filter((o) => isSlaAtRisk(o, nowMs)) | |
| .sort((a, b) => { | |
| const ta = Date.parse(a.promisedDate || a.deadline || "") || 0; | |
| const tb = Date.parse(b.promisedDate || b.deadline || "") || 0; | |
| return ta - tb; | |
| })[0]; | |
| if (near) { | |
| return { | |
| title: "Deadline approaching", | |
| body: `${near.title} is within the next ${SLA_NEAR_HOURS} hours.`, | |
| href: `/ops/qa/${near.id}`, | |
| cta: "Open order", | |
| orderId: near.id, | |
| orderTitle: near.title, | |
| }; | |
| } | |
| function slaSortKey(order: Order): number { | |
| const candidates = [order.deadline, order.promisedDate] | |
| .filter((v): v is string => Boolean(v)) | |
| .map((v) => Date.parse(v)) | |
| .filter((t) => !Number.isNaN(t)); | |
| return candidates.length ? Math.min(...candidates) : Number.POSITIVE_INFINITY; | |
| } | |
| const breached = active | |
| .filter((o) => isSlaBreached(o, nowMs)) | |
| .sort((a, b) => slaSortKey(a) - slaSortKey(b))[0]; | |
| if (breached) { | |
| return { | |
| title: "SLA breached", | |
| body: `${breached.title} is past its deadline or promised date.`, | |
| href: `/ops/qa/${breached.id}`, | |
| cta: "Open order", | |
| orderId: breached.id, | |
| orderTitle: breached.title, | |
| }; | |
| } | |
| const near = active | |
| .filter((o) => isSlaAtRisk(o, nowMs)) | |
| .sort((a, b) => slaSortKey(a) - slaSortKey(b))[0]; | |
| if (near) { | |
| return { | |
| title: "Deadline approaching", | |
| body: `${near.title} is within the next ${SLA_NEAR_HOURS} hours.`, | |
| href: `/ops/qa/${near.id}`, | |
| cta: "Open order", | |
| orderId: near.id, | |
| orderTitle: near.title, | |
| }; | |
| } |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@src/app/ops/_lib/overview.ts` around lines 273 - 307, Update the SLA sorting
in the breached and near-order selection to reuse one timestamp helper that
takes the minimum valid timestamp from deadline and promisedDate, matching
isSlaBreached and isSlaAtRisk. Make the helper return Infinity when both dates
are missing or unparsable, and use it in both comparators instead of the current
promisedDate-first Date.parse expressions.
| "failed_qc", | ||
| ]); | ||
|
|
||
| const STALL_STATES = new Set(["supplier_assigned"]); |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Add an age threshold before an assignment counts as stalled.
Every order in supplier_assigned becomes a stalled_assignment row as soon as Operations assigns a supplier. The recovery queue is for exception paths. A supplier that received an offer one minute ago is not an exception.
Gate the row on order.updatedAt age so that only genuinely stalled assignments appear.
🐛 Proposed fix
const STALL_STATES = new Set(["supplier_assigned"]);
+
+/** Hours an assignment may sit unaccepted before recovery lists it. */
+export const STALL_AFTER_HOURS = 4;
@@
export function buildRecoveryItems(
orders: Order[],
claims: Claim[],
issues: Issue[],
+ nowMs: number = Date.now(),
): RecoveryItem[] {
@@
- if (STALL_STATES.has(order.state)) {
+ const assignedAt = Date.parse(order.updatedAt);
+ const stalled =
+ STALL_STATES.has(order.state) &&
+ !Number.isNaN(assignedAt) &&
+ nowMs - assignedAt >= STALL_AFTER_HOURS * 60 * 60 * 1000;
+ if (stalled) {Also applies to: 145-158
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@src/app/ops/_lib/recovery.ts` at line 42, Update the stalled-assignment
detection using STALL_STATES so supplier_assigned orders are included only when
order.updatedAt exceeds the established assignment-age threshold; preserve the
existing stalled_assignment row creation for qualifying orders and exclude
recent assignments from the recovery queue.
| // Explicit deadline / promised markers when parseable and not already covered | ||
| if (order.promisedDate && !Number.isNaN(Date.parse(order.promisedDate))) { | ||
| if ( | ||
| !events.some( | ||
| (e) => e.orderId === order.id && e.at === order.promisedDate, | ||
| ) | ||
| ) { | ||
| // already using promised as anchor above — no extra row needed | ||
| } | ||
| } |
There was a problem hiding this comment.
📐 Maintainability & Code Quality | 🟠 Major | ⚡ Quick win
Remove the dead promised-date block.
Lines 210-219 compute a condition and then do nothing in both branches. The if body contains only a comment. This is dead code and it also runs an extra events.some scan per order.
♻️ Proposed removal
- // Explicit deadline / promised markers when parseable and not already covered
- if (order.promisedDate && !Number.isNaN(Date.parse(order.promisedDate))) {
- if (
- !events.some(
- (e) => e.orderId === order.id && e.at === order.promisedDate,
- )
- ) {
- // already using promised as anchor above — no extra row needed
- }
- }📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| // Explicit deadline / promised markers when parseable and not already covered | |
| if (order.promisedDate && !Number.isNaN(Date.parse(order.promisedDate))) { | |
| if ( | |
| !events.some( | |
| (e) => e.orderId === order.id && e.at === order.promisedDate, | |
| ) | |
| ) { | |
| // already using promised as anchor above — no extra row needed | |
| } | |
| } |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@src/app/ops/_lib/schedule.ts` around lines 210 - 219, Remove the entire no-op
promised-date conditional block after the existing event-generation logic in the
schedule construction flow, including its Date.parse check and events.some scan;
retain the surrounding behavior and comments unrelated to this dead code.
| export function groupEventsByDay( | ||
| events: ScheduleEvent[], | ||
| ): { dayKey: string; dayLabel: string; events: ScheduleEvent[] }[] { | ||
| const map = new Map<string, ScheduleEvent[]>(); | ||
| for (const ev of events) { | ||
| const d = new Date(ev.at); | ||
| if (Number.isNaN(d.getTime())) continue; | ||
| const key = d.toISOString().slice(0, 10); | ||
| const list = map.get(key) ?? []; | ||
| list.push(ev); | ||
| map.set(key, list); | ||
| } | ||
| return [...map.entries()] | ||
| .sort(([a], [b]) => a.localeCompare(b)) | ||
| .map(([dayKey, dayEvents]) => ({ | ||
| dayKey, | ||
| dayLabel: new Intl.DateTimeFormat("en-PH", { | ||
| weekday: "short", | ||
| month: "short", | ||
| day: "numeric", | ||
| }).format(new Date(dayKey + "T12:00:00")), | ||
| events: dayEvents.sort((a, b) => a.at.localeCompare(b.at)), | ||
| })); | ||
| } |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
Fix the timezone mismatch in day grouping.
groupEventsByDay derives dayKey from d.toISOString().slice(0, 10), which is a UTC calendar day. rangeForView and filterEventsInRange use local-time day and week boundaries, and WeekGrid matches events with isSameDay in local time. Philippine time is UTC+8, so any event between 00:00 and 08:00 local falls into the previous UTC day. The agenda then shows the event under a different date than the week grid, and the day view can group an in-range event under a day label outside the selected range.
Derive the key from local date parts to match the rest of the schedule logic.
🐛 Proposed fix
+import { format } from "date-fns";
+
export function groupEventsByDay(
events: ScheduleEvent[],
): { dayKey: string; dayLabel: string; events: ScheduleEvent[] }[] {
const map = new Map<string, ScheduleEvent[]>();
for (const ev of events) {
const d = new Date(ev.at);
if (Number.isNaN(d.getTime())) continue;
- const key = d.toISOString().slice(0, 10);
+ const key = format(d, "yyyy-MM-dd");
const list = map.get(key) ?? [];
list.push(ev);
map.set(key, list);
}
return [...map.entries()]
.sort(([a], [b]) => a.localeCompare(b))
.map(([dayKey, dayEvents]) => ({
dayKey,
dayLabel: new Intl.DateTimeFormat("en-PH", {
weekday: "short",
month: "short",
day: "numeric",
+ timeZone: "Asia/Manila",
}).format(new Date(dayKey + "T12:00:00")),
events: dayEvents.sort((a, b) => a.at.localeCompare(b.at)),
}));
}📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| export function groupEventsByDay( | |
| events: ScheduleEvent[], | |
| ): { dayKey: string; dayLabel: string; events: ScheduleEvent[] }[] { | |
| const map = new Map<string, ScheduleEvent[]>(); | |
| for (const ev of events) { | |
| const d = new Date(ev.at); | |
| if (Number.isNaN(d.getTime())) continue; | |
| const key = d.toISOString().slice(0, 10); | |
| const list = map.get(key) ?? []; | |
| list.push(ev); | |
| map.set(key, list); | |
| } | |
| return [...map.entries()] | |
| .sort(([a], [b]) => a.localeCompare(b)) | |
| .map(([dayKey, dayEvents]) => ({ | |
| dayKey, | |
| dayLabel: new Intl.DateTimeFormat("en-PH", { | |
| weekday: "short", | |
| month: "short", | |
| day: "numeric", | |
| }).format(new Date(dayKey + "T12:00:00")), | |
| events: dayEvents.sort((a, b) => a.at.localeCompare(b.at)), | |
| })); | |
| } | |
| import { format } from "date-fns"; | |
| export function groupEventsByDay( | |
| events: ScheduleEvent[], | |
| ): { dayKey: string; dayLabel: string; events: ScheduleEvent[] }[] { | |
| const map = new Map<string, ScheduleEvent[]>(); | |
| for (const ev of events) { | |
| const d = new Date(ev.at); | |
| if (Number.isNaN(d.getTime())) continue; | |
| const key = format(d, "yyyy-MM-dd"); | |
| const list = map.get(key) ?? []; | |
| list.push(ev); | |
| map.set(key, list); | |
| } | |
| return [...map.entries()] | |
| .sort(([a], [b]) => a.localeCompare(b)) | |
| .map(([dayKey, dayEvents]) => ({ | |
| dayKey, | |
| dayLabel: new Intl.DateTimeFormat("en-PH", { | |
| weekday: "short", | |
| month: "short", | |
| day: "numeric", | |
| timeZone: "Asia/Manila", | |
| }).format(new Date(dayKey + "T12:00:00")), | |
| events: dayEvents.sort((a, b) => a.at.localeCompare(b.at)), | |
| })); | |
| } |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@src/app/ops/_lib/schedule.ts` around lines 276 - 299, Update groupEventsByDay
to derive dayKey from the Date’s local year, month, and day components instead
of d.toISOString(), preserving the existing invalid-date skip, sorting, labels,
and event ordering so grouping matches rangeForView, filterEventsInRange, and
WeekGrid local-day behavior.
| <DataTable | ||
| columns={columns} | ||
| data={board} | ||
| getRowId={(o) => o.id} | ||
| caption="Dispatch board" | ||
| filterPlaceholder="Filter dispatch…" | ||
| defaultSortId="status" |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
defaultSortId="status" discards the priority ordering from filterDispatchOrders.
filterDispatchOrders (src/app/ops/_lib/dispatch.ts:42-53) ranks ready_for_dispatch first, then rider_assigned, then the rest by recency. DataTable applies defaultSortId on mount and re-sorts the rows alphabetically by the presented status label. "Out for delivery" then precedes "Ready for dispatch", so the rows that need operator action move to the bottom. Remove defaultSortId to keep the helper ordering, or give the status column a sortValue that returns the priority rank.
🛠️ Proposed fix
getRowId={(o) => o.id}
caption="Dispatch board"
filterPlaceholder="Filter dispatch…"
- defaultSortId="status"
rowActions={(o) => (📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| <DataTable | |
| columns={columns} | |
| data={board} | |
| getRowId={(o) => o.id} | |
| caption="Dispatch board" | |
| filterPlaceholder="Filter dispatch…" | |
| defaultSortId="status" | |
| <DataTable | |
| columns={columns} | |
| data={board} | |
| getRowId={(o) => o.id} | |
| caption="Dispatch board" | |
| filterPlaceholder="Filter dispatch…" |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@src/app/ops/dispatch/page.tsx` around lines 320 - 326, Remove
defaultSortId="status" from the DataTable in the dispatch board so the ordering
produced by filterDispatchOrders is preserved; leave the existing columns and
row data unchanged.
| rowActions={(o) => ( | ||
| <Button | ||
| variant={o.id === selectedId ? "default" : "secondary"} | ||
| aria-pressed={o.id === selectedId} | ||
| onClick={() => setSelectedId(o.id)} | ||
| > | ||
| {o.id === selectedId ? "Selected" : "Select"} | ||
| </Button> | ||
| )} |
There was a problem hiding this comment.
📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Inspect the Button variant definitions to confirm what `default` renders.
fd -t f 'button.tsx' -p src/components/ui --exec cat -n {}Repository: rqms40/gridgo-web
Length of output: 4476
Use an allowed variant for the selected queue action.
default is a filled structural style, not the primary yellow style. Dense queue actions must use outline or secondary; replace the selected-state default variant with one of these variants.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@src/app/ops/matching/page.tsx` around lines 261 - 269, Update the
selected-state variant in the rowActions Button to use an allowed dense queue
action variant, replacing "default" with "outline" or "secondary"; keep the
unselected variant and selection behavior unchanged.
Source: Coding guidelines
|
|
||
| export default function OpsIndex() { | ||
| redirect("/ops/qa"); | ||
| redirect("/ops/overview"); |
There was a problem hiding this comment.
📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Locate ROLE_NAV and inspect the ops entries, focusing on /ops/overview and ready flags.
set -euo pipefail
fd -t f -e ts -e tsx | xargs rg -n -C 3 'ROLE_NAV' | head -60
echo "---- ops nav hrefs and ready flags ----"
fd -t f -e ts -e tsx | xargs rg -n -C 4 "'/ops/overview'|\"/ops/overview\"" | head -60
echo "---- any ready flag definitions ----"
fd -t f -e ts -e tsx | xargs rg -n -B 2 -A 2 '\bready\s*:' | rg -n -C 2 '/ops/' | head -80Repository: rqms40/gridgo-web
Length of output: 5035
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "---- operations navigation definition ----"
sed -n '100,145p' src/lib/nav.ts
echo "---- operations overview route ----"
if [ -f src/app/ops/overview/page.tsx ]; then
cat -n src/app/ops/overview/page.tsx
fi
echo "---- readiness behavior ----"
rg -n -C 5 'ready|navForRole|navItemForPath' src/lib src/components src/app/opsRepository: rqms40/gridgo-web
Length of output: 50373
Mark /ops/overview as ready in ROLE_NAV. The route is implemented, but ROLE_NAV.ops_admin sets ready: false, so the landing route is labeled “Soon” and conflicts with the placeholder contract. Set ready: true, clear placeholderBody, and update the readiness test.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@src/app/ops/page.tsx` at line 4, Update the ROLE_NAV.ops_admin entry for
/ops/overview to set ready: true and remove or clear placeholderBody, then
revise the associated readiness test to expect the route as available rather
than a placeholder.
| <Field> | ||
| <FieldLabel htmlFor="resolution">Resolution</FieldLabel> | ||
| <Textarea | ||
| id="resolution" | ||
| value={resolution} | ||
| onChange={(e) => setResolution(e.target.value)} | ||
| placeholder="e.g. Reprinted and redelivered" | ||
| rows={3} | ||
| required | ||
| /> | ||
| </Field> | ||
| {actionError ? ( | ||
| <p className="text-body text-error m-0" role="alert"> | ||
| {actionError} | ||
| </p> | ||
| ) : null} |
There was a problem hiding this comment.
📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win
Associate the validation message with the Resolution field.
The required attribute on line 401 has no effect. The Textarea is not inside a <form>, and the submit path is a click handler, so the browser never runs constraint validation. submitResolve performs the real check.
The error paragraph at line 404-408 is also not linked to the field. A screen reader user who lands on the textarea does not hear why the submission failed. Set aria-invalid and aria-describedby on the control.
🛡️ Proposed fix
<Field>
<FieldLabel htmlFor="resolution">Resolution</FieldLabel>
<Textarea
id="resolution"
value={resolution}
onChange={(e) => setResolution(e.target.value)}
placeholder="e.g. Reprinted and redelivered"
rows={3}
- required
+ aria-required="true"
+ aria-invalid={actionError ? true : undefined}
+ aria-describedby={
+ actionError ? "resolution-error" : undefined
+ }
/>
</Field>
{actionError ? (
- <p className="text-body text-error m-0" role="alert">
+ <p
+ id="resolution-error"
+ className="text-body text-error m-0"
+ role="alert"
+ >
{actionError}
</p>
) : null}📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| <Field> | |
| <FieldLabel htmlFor="resolution">Resolution</FieldLabel> | |
| <Textarea | |
| id="resolution" | |
| value={resolution} | |
| onChange={(e) => setResolution(e.target.value)} | |
| placeholder="e.g. Reprinted and redelivered" | |
| rows={3} | |
| required | |
| /> | |
| </Field> | |
| {actionError ? ( | |
| <p className="text-body text-error m-0" role="alert"> | |
| {actionError} | |
| </p> | |
| ) : null} | |
| <Field> | |
| <FieldLabel htmlFor="resolution">Resolution</FieldLabel> | |
| <Textarea | |
| id="resolution" | |
| value={resolution} | |
| onChange={(e) => setResolution(e.target.value)} | |
| placeholder="e.g. Reprinted and redelivered" | |
| rows={3} | |
| aria-required="true" | |
| aria-invalid={actionError ? true : undefined} | |
| aria-describedby={ | |
| actionError ? "resolution-error" : undefined | |
| } | |
| /> | |
| </Field> | |
| {actionError ? ( | |
| <p | |
| id="resolution-error" | |
| className="text-body text-error m-0" | |
| role="alert" | |
| > | |
| {actionError} | |
| </p> | |
| ) : null} |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@src/app/ops/recovery/page.tsx` around lines 393 - 408, Update the Resolution
Textarea in the recovery page to expose submitResolve validation state to
assistive technology: set aria-invalid when actionError exists and
aria-describedby to the error paragraph’s stable id, and assign that id to the
paragraph. Keep the existing error rendering and required behavior unchanged.
Source: Coding guidelines
| function toggleKind(kind: ScheduleKind) { | ||
| setKinds((prev) => { | ||
| const next = new Set(prev); | ||
| if (next.has(kind)) next.delete(kind); | ||
| else next.add(kind); | ||
| return next; | ||
| }); | ||
| } |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
Fix the filter behavior when the user turns off every event type.
filterEventsInRange skips kind filtering when the set is empty: if (kinds && kinds.size > 0 && !kinds.has(ev.kind)). If the user deselects all type buttons, kinds.size becomes 0 and the page shows all events instead of none. The empty-state copy at Line 228 also tells the user to "turn filters back on", which never matches this behavior.
Pass null when no kind is selected, or treat an empty set as "no events". The first option keeps the helper contract and makes the copy correct.
🐛 Proposed fix
const visible = useMemo(
- () => filterEventsInRange(allEvents, start, end, kinds),
+ () => (kinds.size ? filterEventsInRange(allEvents, start, end, kinds) : []),
[allEvents, start, end, kinds],
);🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@src/app/ops/schedule/page.tsx` around lines 111 - 118, Update toggleKind to
pass null when the resulting kinds set is empty, while preserving the Set for
non-empty selections. Ensure filterEventsInRange continues treating null as no
kind filter so deselecting every event type produces the intended empty state
and matching copy.
Summary
Ships the remaining Supplier Operations Admin surfaces on top of the shared API client and component kit. QA queue + workspace are left as-is.
/ops/overview/ops/matchinggetEligibleSuppliers(reasons, services, capacity, zone, verification) → assign withtransitionOrder/ops/recovery/ops/dispatchgetDispatchLocationwith honest stale / not-tracking; never persisted/ops/claims/ops/schedule/ops/auditPure helpers live under
src/app/ops/_lib/(lane isolation — did not editsrc/lib/or nav structure). Tests cover overview buckets, matching reasons, stale location, recovery, and schedule range filtering.Lane notes for integrators
ROLE_NAVreadyflags for ops items (except QA) are stillfalseso this PR does not collide with the shared spine. Flip totruewhen integrating so the rail drops “Soon”.needs-decision:none for missing endpoints used by these screens; APIs exercised were present. Matching still depends on orders inapproved_for_matchingin demo data. Rider directory remains demo-id (same honesty as QA workspace).Design critique (addendum pass)
StatusChip.Verification
npm run typecheck— passnpm run lint— passnpm test— 42 pass (including 12 new ops helper tests)npm run build— pass (all/ops/*routes compile)http://127.0.0.1:8787asops@gridgo.local/demo: confirmedlistOrders,listClaims,listIssues,listAudit,listDispatchOffers,getDispatchLocation,getEligibleSuppliersreturn shapes these pages consumeops_adminaway from/ops/*; supplier token gets403on/auditmd+, schedule agenda mobile-first; claims/matching dialogs use FieldGroup formsTest plan
ops@gridgo.local/demo/ops/*by URLready: truefor shipped ops items when merging with spineSummary by CodeRabbit