Skip to content

feat(ops): remaining Operations surfaces (overview through audit) - #4

Merged
rqms40 merged 2 commits into
mainfrom
fm/gridgo-web-ops
Aug 9, 2026
Merged

rqms40 merged 2 commits into
mainfrom
fm/gridgo-web-ops

Conversation

@rqms40

@rqms40 rqms40 commented Aug 8, 2026 •

Copy link
Copy Markdown
Collaborator

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.

Route What it does
/ops/overview Operational picture: QA / matching / production / delivery / blocked / SLA risk, plus one next action (not a counter wall)
/ops/matching Explainable eligibility via getEligibleSuppliers (reasons, services, capacity, zone, verification) → assign with transitionOrder
/ops/recovery Exception paths with a next step on every row; resolve issues with recorded resolution (payout release stays on Claims)
/ops/dispatch Delivery-state board; location via getDispatchLocation with honest stale / not-tracking; never persisted
/ops/claims Raise / hold / release with required reasons, attribution, timestamps, claim timeline
/ops/schedule Week default, day/week switch, Today, exact range, semantic filters; agenda below 768px; events open existing workspaces only
/ops/audit Platform audit log: who / what / when / which record, filterable, plain language

Pure helpers live under src/app/ops/_lib/ (lane isolation — did not edit src/lib/ or nav structure). Tests cover overview buckets, matching reasons, stale location, recovery, and schedule range filtering.

Lane notes for integrators

  • ROLE_NAV ready flags for ops items (except QA) are still false so this PR does not collide with the shared spine. Flip to true when 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 in approved_for_matching in demo data. Rider directory remains demo-id (same honesty as QA workspace).

Design critique (addendum pass)

  1. Yellow budget: page-level primary only on Overview next action, Claims “Raise claim”, and dialog confirms — no yellow row grids.
  2. Status always icon + label via StatusChip.
  3. No snake_case state/action codes on screen (local presenters).
  4. Empty/error states invite the next action.
  5. Cut: avoided a second dashboard of decorative metrics; overview leads with next action.

Verification

  • npm run typecheck — pass
  • npm run lint — pass
  • npm test — 42 pass (including 12 new ops helper tests)
  • npm run build — pass (all /ops/* routes compile)
  • API at http://127.0.0.1:8787 as ops@gridgo.local / demo: confirmed listOrders, listClaims, listIssues, listAudit, listDispatchOffers, getDispatchLocation, getEligibleSuppliers return shapes these pages consume
  • Role isolation: middleware continues to redirect non-ops_admin away from /ops/*; supplier token gets 403 on /audit
  • Breakpoints: layout uses DataTable card mode <768, week grid md+, schedule agenda mobile-first; claims/matching dialogs use FieldGroup forms
  • Light/dark: semantic tokens only (no new hex)
  • Keyboard: tables/dialogs use existing shadcn/Base UI primitives; row actions are real buttons/links with 44×44 floor

Test plan

  • Log in as ops@gridgo.local / demo
  • Walk overview → matching → recovery → dispatch → claims → schedule → audit
  • Confirm QA queue/workspace unchanged
  • Confirm supplier/admin still cannot open /ops/* by URL
  • On claims: raise with reason, hold, release — reasons visible on detail timeline
  • On dispatch: stale vs missing location labels (never “live” for old pings)
  • On schedule <768: agenda list, not squeezed grid; event opens existing workspace
  • Flip nav ready: true for shipped ops items when merging with spine

Summary by CodeRabbit

  • New Features
    • Replaced Operations placeholder pages with functional overview, claims, dispatch, supplier matching, recovery, schedule, and audit interfaces.
    • Added queue summaries, prioritized next actions, filtering, sorting, navigation, refresh, retry, and error states.
    • Added claim and payout-hold actions, rider assignment, supplier assignment, issue resolution, and live location refresh.
    • Added day/week schedule views and searchable audit logs.
  • Tests
    • Added comprehensive coverage for Operations workflows, formatting, matching, recovery, dispatch, and scheduling.

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.
@coderabbitai

coderabbitai Bot commented Aug 8, 2026 •

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

@rqms40, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 11 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

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 configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: ab2b5594-fe81-4044-b294-9e98111b7ac2

📥 Commits

Reviewing files that changed from the base of the PR and between ed884ba and e85cca7.

📒 Files selected for processing (1)
  • src/app/ops/claims/page.tsx
📝 Walkthrough

Walkthrough

The 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.

Changes

Operations helper foundation

Layer / File(s) Summary
Presentation and workflow helpers
src/app/ops/_lib/*, src/app/ops/_lib/__tests__/*, AGENTS.md
Added typed presentation helpers, supplier matching explanations, dispatch filtering and location freshness logic, plus shared fixtures and helper tests.
Overview and recovery queues
src/app/ops/_lib/overview.ts, src/app/ops/_lib/recovery.ts, src/app/ops/overview/page.tsx, src/app/ops/recovery/page.tsx
Added queue buckets, SLA actions, recovery items, issue resolution, loading states, retry handling, and operational navigation.
Matching and dispatch workflows
src/app/ops/matching/page.tsx, src/app/ops/dispatch/page.tsx
Added supplier selection and assignment, dispatch order filtering, rider assignment, location refresh, offer display, and action error handling.
Claims, schedule, and audit surfaces
src/app/ops/claims/page.tsx, src/app/ops/schedule/page.tsx, src/app/ops/audit/page.tsx, src/app/ops/page.tsx
Added claims management, schedule event views, audit filtering and tables, and redirect behavior from /ops/qa to /ops/overview.

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
Loading

Possibly related PRs

  • rqms40/gridgo-api#2: Provides the APIs and data models used by the Operations matching, dispatch, claims, issue, schedule, and audit surfaces.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 7.32% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the main change: adding the remaining Operations surfaces from overview through audit.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fm/gridgo-web-ops

Comment @coderabbitai help to get the list of available commands.

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.
@rqms40

rqms40 commented Aug 8, 2026

Copy link
Copy Markdown
Collaborator Author

Yellow budget check — /ops/claims

No demotion needed: the two primary buttons are on different surfaces.

  1. Page surface (toolbar): “Raise claim” — sole page-level yellow CTA.
  2. Dialog footer: raise / hold / release confirm — bounded dialog panel (allowed to stay yellow).

Row actions and empty-state “Raise claim” remain secondary/outline. Documented in commit e85cca7 on this branch.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 14

🧹 Nitpick comments (11)
src/app/ops/_lib/recovery.ts (1)

33-40: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Remove client_correction from FAILED_PATH_STATES.

Line 111 excludes client_correction from 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 value

Extract the shared deadline parsing.

isSlaAtRisk and isSlaBreached repeat the same candidate parsing and the same terminal-state exclusions. Line 88 also repeats payout_released, which TERMINAL_STATES already 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 win

Do not render a Resolve control that cannot act.

issues.find((i) => i.id === r.issueId) can return undefined. The Button still renders, and the click handler then does nothing. The operator gets no dialog and no message.

buildRecoveryItems builds open_issue rows from the same issues array, 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 win

Do not rely on aria-label on a <p> element, and surface bucket.urgent.

Two points in this card:

  1. Line 196-201 puts aria-label on a <p>. aria-label is 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.
  2. buildOverviewBuckets computes urgent and the type documents it as "the recommended next focus", but BucketCard never reads it. The derived priority signal is dropped. If you render it, use StatusChip so 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 StatusChip with 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 win

Give the Refresh control feedback while a reload runs.

loading && !data shows LoadingBlock only on the first load. When the operator presses Refresh, loading becomes true but 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 loading is 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 win

Move 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 a presentCategoryCode helper in src/app/ops/_lib/present.ts and add its test under src/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 under src/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 win

Guard against stale eligible-supplier responses.

loadEligible has 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 requested orderId. 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 win

Reset locLoading in a finally block.

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 a finally block.

♻️ 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 win

The inline error block is unreachable.

The catch at Line 109 always sets entries to null, so the guard at Line 242 (error && !entries) returns ErrorState before 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 shows ErrorState and 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 value

Extract the repeated title-case helper.

Lines 43-68 repeat the same split(/[_-]/) → capitalize → join(" ") chain four times. src/app/ops/_lib/present.ts already holds the ops label helpers. Move a titleCase helper 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 win

Complete the ARIA grid structure or drop the grid roles.

The container uses role="grid" and the children use role="gridcell". A gridcell must be a child of an element with role="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

📥 Commits

Reviewing files that changed from the base of the PR and between 428900f and ed884ba.

📒 Files selected for processing (16)
  • AGENTS.md
  • src/app/ops/_lib/__tests__/ops-helpers.test.ts
  • src/app/ops/_lib/dispatch.ts
  • src/app/ops/_lib/matching.ts
  • src/app/ops/_lib/overview.ts
  • src/app/ops/_lib/present.ts
  • src/app/ops/_lib/recovery.ts
  • src/app/ops/_lib/schedule.ts
  • src/app/ops/audit/page.tsx
  • src/app/ops/claims/page.tsx
  • src/app/ops/dispatch/page.tsx
  • src/app/ops/matching/page.tsx
  • src/app/ops/overview/page.tsx
  • src/app/ops/page.tsx
  • src/app/ops/recovery/page.tsx
  • src/app/ops/schedule/page.tsx

Comment on lines +65 to +115
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,
};
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 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.

Comment on lines +273 to +307
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,
};
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 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.

Suggested change
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"]);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 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.

Comment on lines +210 to +219
// 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
}
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 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.

Suggested change
// 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.

Comment on lines +276 to +299
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)),
}));
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 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.

Suggested change
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.

Comment on lines +320 to +326
<DataTable
columns={columns}
data={board}
getRowId={(o) => o.id}
caption="Dispatch board"
filterPlaceholder="Filter dispatch…"
defaultSortId="status"

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 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.

Suggested change
<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.

Comment on lines +261 to +269
rowActions={(o) => (
<Button
variant={o.id === selectedId ? "default" : "secondary"}
aria-pressed={o.id === selectedId}
onClick={() => setSelectedId(o.id)}
>
{o.id === selectedId ? "Selected" : "Select"}
</Button>
)}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 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

Comment thread src/app/ops/page.tsx

export default function OpsIndex() {
redirect("/ops/qa");
redirect("/ops/overview");

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 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 -80

Repository: 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/ops

Repository: 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.

Comment on lines +393 to +408
<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}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 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.

Suggested change
<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

Comment on lines +111 to +118
function toggleKind(kind: ScheduleKind) {
setKinds((prev) => {
const next = new Set(prev);
if (next.has(kind)) next.delete(kind);
else next.add(kind);
return next;
});
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 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.

@rqms40
rqms40 merged commit 8701d90 into main Aug 9, 2026
1 check passed
@rqms40
rqms40 deleted the fm/gridgo-web-ops branch August 13, 2026 03:19
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant