Skip to content

refactor(web): align the line-item components with the dialog pattern - #32

Merged
aek676 merged 1 commit into
mainfrom
refactor/web-line-items
Aug 12, 2026
Merged

aek676 merged 1 commit into
mainfrom
refactor/web-line-items

Conversation

@aek676

@aek676 aek676 commented Aug 12, 2026 •

Copy link
Copy Markdown
Owner

Summary

Restructures the line-item dialogs to follow the pattern established by edit-receipt-total.tsx: each dialog is one self-contained file that owns its open state and its own form. The api/ modules are untouched.

Changes

  • Merged trigger + modal pairs into single files. edit-line-item.tsx now holds the trigger, the dialog, and its private EditLineItemForm; edit-line-item-modal.tsx is gone (same for add). Each form keeps its own useForm and validates with the schema from its own API module.
  • Self-controlled disclosure. Dialog open/onOpenChange + DialogTrigger render instead of the parent conditionally mounting the modal, and DialogClose instead of an onCancel prop threaded down.
  • Gave "add" a real trigger component. The raw button and adding state move out of line-item-list.tsx into add-line-item.tsx; the list is now stateless.
  • Renamed the edit form's initial prop to lineItem to match the codebase vocabulary.

No behavior change: add-line-item.ts and update-line-item.ts are byte-for-byte unchanged, each keeping its own zod schema, and the submit gate stays !canSubmit || isPending as before.

Review feedback

Pullfrog caught that an !isDirty submit gate added in an earlier revision made low-confidence items unclearable — the API lifts aiConfidence back to 1 on any field patch, so pressing Save on a correctly-extracted flagged item is the accept gesture, and ConfirmSessionButton stays disabled while any item is flagged. Fixed in c50c12a by dropping the gate. The other two review notes predate #33 landing and no longer apply: the branch now carries only the refactor, and confirmSession already uses an atomic findOneAndUpdate({ _id, status: 'draft' }).

Verification

  • bun nx run-many -t lint test build -p web — all green (75 unit tests), plus bun nx test api (158 tests).
  • tsc --noEmit -p apps/web/tsconfig.app.json reports no errors in the changed files. (It does report 5 pre-existing Bun type errors in apps/api sources pulled in through the Eden client types — they fail on a clean checkout of main too, unrelated to this change.)

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

Important

The dialog refactor itself is clean, but the shared form's new !isDirty submit gate removes the only path a user has to clear an item's low-confidence flag — which in turn keeps the Confirm button permanently disabled for those sessions.

Reviewed changes

This branch moves every line-item dialog from conditional mounting to the self-controlled Dialog/DialogTrigger pattern, and carries 14 commits of the unmerged feat/join-session API work along with it.

  • Trigger + modal pairs collapse into single files (add-line-item.tsx, edit-line-item.tsx); the duplicated field markup extracts into line-item-form.tsx, and the two identical zod schemas collapse into api/line-item-draft.ts.
  • LOW_CONFIDENCE_THRESHOLD moves into line-item/utils/confidence.ts and is consumed by line-item-row.tsx and session-draft.tsx.
  • session.totalCents stops being a running tally and becomes a snapshot; a new totalSource: 'receipt' | 'items' field decides whether it is frozen or recomputed from the item sum on every line-item write.
  • New PATCH /sessions/:sessionId (merchant/date/totalCents/totalSource) and POST /sessions/:sessionId/confirm (gates on draft status, non-empty items, no low-confidence item, exact total match; then mints an 8-char share code with 5 retries against the unique partial index).
  • receiptTotals on the web drops its ±2c tolerance so matches is exact equality, matching the new server gate.

ℹ️ 14 of the 15 commits are feat/join-session, not the advertised refactor

Only the tip commit (62e7d1d) is the web dialog refactor. Everything else — the totalSource state machine, updateSession, confirmSession, the share-code generator, and their tests — is feat/join-session, which is not on main yet. The PR body acknowledges this and expects the diff to shrink once that branch merges, but as the PR stands today, merging it lands the entire API feature, and the refactor cannot be reviewed in isolation from this diff. That is a sequencing call only you can make — either rebase once feat/join-session is in, or retarget this PR's base at that branch so the diff shows the 30-line refactor it advertises.

ℹ️ POST /sessions/:sessionId/confirm ships with no client, and confirmSession has no optimistic concurrency

ConfirmButton in session-draft.tsx still carries // TODO: Implement backend endpoint and mutation and a console.log, so the endpoint this PR adds is unreachable from the app. Separately, confirmSession reads session.status, mutates, and saves with no version guard: sessionSchema does not set optimisticConcurrency, and mongoose's default __v check only covers array modifications. Two overlapping confirms can both pass status !== 'draft', draw different codes, and last-write-wins — one caller gets handed a code that is not what is stored. Not reachable today precisely because the button is unwired, but it goes live the moment it is.

Technical details
## Affected sites

- `apps/api/src/modules/session/service.ts` — `confirmSession`, the `for (let attempt = 0; attempt < CODE_ATTEMPTS; attempt++)` save loop.
- `apps/api/src/schemas/session.ts` — `sessionSchema` options; no `optimisticConcurrency: true`.
- `apps/web/src/features/session/components/session-draft.tsx` — `ConfirmButton`.

## Required outcome

Either wire `ConfirmButton` to the new endpoint in this PR (so the feature is
end-to-end and the concurrency question becomes testable), or land the endpoint
knowing it is dead code and track the client work.

Independently, a second confirm on an already-confirmed session should lose
rather than overwrite.

## Suggested approach

Set `optimisticConcurrency: true` on `sessionSchema`, or make the transition a
conditional update (`findOneAndUpdate({ _id, status: 'draft' }, ...)`) so the
draft check and the write are one atomic operation.

## Open questions for the human

- Is `POST /confirm` intentionally landing ahead of its client, or was the
  `session-draft.tsx` TODO missed?

ℹ️ docs/srs.md no longer matches the Session model

The Session data model in docs/srs.md still lists total_cents with no total_source alongside it, and nothing in the doc records that total_cents stopped being a running tally mutated on every line-item write and became a snapshot of the printed receipt total. CLAUDE.md points contributors at that file as the spec, so it is worth updating in the same change that alters the semantics.

ℹ️ Nitpicks

  • LOW_CONFIDENCE_THRESHOLD = 0.7 now lives in two places: apps/api/src/modules/session/service.ts:19 and apps/web/src/features/session/line-item/utils/confidence.ts. If they drift, the web enables the Confirm button against a server that will 409 with sessionNeedsReview.
  • In update-session.ts, apiError(error.value, 'Failed to update the receipt total') is also the fallback for the totalSource: 'items' handover, where "update the receipt total" is the wrong description of what the user did.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using Claude Opus | 𝕏

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

Important

The merge does what it set out to do — the diff is the 9-file refactor the title advertises, and three of the four points from the last review went away with it. The open thread on line-item-form.tsx:142 did not, and main has since turned it from a latent dead end into a live one.

Reviewed changes

The only commit since the prior review at 62e7d1d is the merge of main after #33 landed; no line of the refactor itself changed.

  • Dropped the stacked API work out of the diff. The totalSource state machine, PATCH /sessions/:sessionId, POST /sessions/:sessionId/confirm and their tests are on main now. The merged tree diverges from main only in the 9 web files, so nothing was lost in the resolution, and no stale reference to add-line-item-modal.tsx, edit-line-item-modal.tsx, or the two old draft schemas survives anywhere in the repo.
  • Re-pointed the confidence threshold at @repo/shared-types. The branch's line-item/utils/confidence.ts is gone; line-item-row.tsx, confirm-session-button.tsx, and the API service all read LOW_CONFIDENCE_THRESHOLD from libs/shared-types, which retires the duplication nit from the last review.
  • Inherited a wired Confirm button. ConfirmSessionButton replaced the console.log placeholder and calls the confirm endpoint, and confirmSession now performs the draft→open transition through a conditional findOneAndUpdate, settling the concurrency point from the last review.

⚠️ The !isDirty gate now blocks a shipped flow rather than a placeholder

line-item-form.tsx:142 still disables Save unless the form is dirty, so an AI-flagged item whose extracted values are already correct has no accept gesture — and ConfirmSessionButton is gated on !hasLowConfidence, which at 62e7d1d was a console.log TODO and is now a real call to POST /sessions/:sessionId/confirm. A session holding one flagged-but-correct item is unconfirmable through the UI. The existing thread on that line carries the full analysis; the merge changed neither the gate nor the API's flag-clearing rule.

Technical details
# The low-confidence flag has no clearing gesture

## Affected sites

- `apps/web/src/features/session/line-item/components/line-item-form.tsx:142` —
  `disabled={!canSubmit || !isDirty || isPending}`.
- `apps/web/src/features/session/components/confirm-session-button.tsx:19` —
  `canConfirm = totals.matches && hasItems && !hasLowConfidence`.
- `apps/api/src/modules/session/service.ts:207-212` — `updateLineItem` raises
  `aiConfidence` to `1` only when a `name` / `quantity` / `unitPriceCents` patch
  arrives, which is exactly what this form always submits.

## Required outcome

- A user must be able to accept an AI-flagged item whose extracted values are
  already correct, without fabricating an edit.

## Suggested approach

- Drop `isDirty` from the line-item gate (a no-op save is cheap and idempotent),
  or keep it only for items at or above the threshold. `edit-receipt-total.tsx`
  can keep its `isDirty` unchanged — no flag sits behind that form, which is why
  the pattern transplanted cleanly everywhere except here.

## Open questions for the human

- Would a dedicated "looks right" action on the row be preferable to loosening
  the submit gate?

Pullfrog  | Fix it ➔ | View workflow run | Using Claude Opus | 𝕏

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

ℹ️ No new issues in this delta. The API-module revert is behaviour-neutral and every web gate passes on the checkout. Not approving only because the open thread on line-item-form.tsx:147 from the previous review is unchanged by these commits.

Reviewed changes

The only commit since the prior review at da66a1c is 1ddbba2, which reverts the schema consolidation and moves the validator to a prop. The refactor itself — the dialog pattern, the deleted *-modal.tsx files, the stateless list — is unchanged.

  • Restored the two line-item API modules to their main state. api/line-item-draft.ts and its shared lineItemDraftInputSchema are deleted; add-line-item.ts and update-line-item.ts are byte-for-byte identical to main again, each keeping its own schema and inferred *DraftInput type. The PR now touches 6 files, all components.
  • Made LineItemForm schema-agnostic. It declares its own LineItemFormValues interface and takes schema: z.ZodType<LineItemFormValues, LineItemFormValues>, which it feeds to validators.onSubmit. AddLineItem passes addLineItemDraftInputSchema, EditLineItem passes updateLineItemDraftInputSchema.

The change is type-level only — the runtime value reaching validators.onSubmit is the same ZodObject it was before, and the two schemas carry identical rules, so validation behaviour is untouched. Verified on the checkout: no reference to line-item-draft, LineItemDraftInput, AddLineItemModal or EditLineItemModal survives repo-wide, and web:tsc:typecheck, web:format:check, web:lint and web:test (75 tests) all pass. The three-field shape is now declared three times, but the z.ZodType<LineItemFormValues, LineItemFormValues> bound makes any drift between the form and either schema a compile error, so it is a cosmetic cost rather than a risk.

The !isDirty gate on line-item-form.tsx:147 is still the one thing standing between this PR and merge — the existing thread carries the analysis, and nothing in 1ddbba2 moved either the gate or the API's flag-clearing rule.

Pullfrog  | Fix it ➔ | View workflow run | Using Claude Opus | 𝕏

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

Important

The un-extraction is faithful — the two inlined forms are byte-identical to each other apart from the mutation name, and to the line-item-form.tsx they replace. But b9dbe9e rewrote the !isDirty submit gate into two new locations without changing it, so the low-confidence dead end from the previous review is still live and now has a fresh anchor at edit-line-item.tsx:198.

Reviewed changes

The only commit since the prior review at 1ddbba2 is b9dbe9e, which reverses the form extraction. The dialog pattern itself — Dialog open/onOpenChange, DialogTrigger render, DialogClose, the stateless line-item-list.tsx — is untouched by this delta.

  • Deleted the shared line-item-form.tsx. Its ~110 lines of name / unit-price / quantity markup and its DialogFooter are now inlined verbatim into the private AddLineItemForm and EditLineItemForm inside add-line-item.tsx and edit-line-item.tsx. The PR now touches 5 files.
  • Each form owns its own useForm again. defaultValues, validators.onSubmit (the module's own zod schema), and onSubmit (the mutation call) are declared per dialog; the schema / defaultValues / isPending / onSubmit prop plumbing and the exported LineItemFormValues interface are gone, and isPending reads directly off addLineItem / updateLineItem.

Verified on the checkout: diffing the two form bodies yields exactly one differing line (addLineItem.isPending vs updateLineItem.isPending), so the copies have not silently diverged; no reference to line-item-form, LineItemFormValues, AddLineItemModal, EditLineItemModal, or line-item-draft survives repo-wide. web:tsc:typecheck, web:lint, web:format:check and web:test (75 tests) all pass. The web:typecheck target does fail, but only inside src/features/session/api/*.ts, src/app/provider.tsx and sessions.$sessionId.review.tsx with Eden's "Please install Elysia before using Eden" degradation — none of those files are in this diff, and the composite tsc:typecheck build that resolves the api types first is clean.

Both deleted modals gated Save on !canSubmit || isPending only, so !isDirty is new to the add path as well as the edit path relative to main. On the add path it is harmless: addLineItemDraftInputSchema requires name.min(1), so any submittable add is dirty by construction. Only the edit path has the problem.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using Claude Opus | 𝕏

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

✅ No new issues found. c50c12a fixes the last open finding, and the fix holds end-to-end.

Reviewed changes

The only commit since the prior review at b9dbe9e is c50c12a, which deletes four lines — the isDirty selector and gate term in each of the two dialogs. Nothing else in the refactor moved.

  • Restored main's submit gate in both line-item dialogs. add-line-item.tsx:188 and edit-line-item.tsx:197 are back to disabled={!canSubmit || isPending}, and the form.Subscribe selectors no longer read isDirty.

Traced the fix rather than taking it on faith. @tanstack/form-core computes canSubmit = submissionAttempts === 0 && !isTouched && !hasOnMountError || ..., so an untouched edit form reports canSubmit === true and Save is enabled on open. The form always submits all three fields, and apps/api/src/modules/session/service.ts:207-212 sets aiConfidence = 1 on any name / quantity / unitPriceCents patch with no compare-and-skip — so a no-op Save really does lift the flag, and confirm-session-button.tsx:19 (totals.matches && hasItems && !hasLowConfidence) unblocks. The dead end is closed; both threads are resolved.

The add path is unaffected as expected: addLineItemDraftInputSchema requires name.min(1), so an empty-form Save still runs validators.onSubmit, marks every field touched and renders the errors, exactly as the deleted AddLineItemModal did on main.

Gates re-run on the checkout with --skip-nx-cache: web:lint, web:test (75 tests), web:tsc:typecheck, web:format:check all pass.

One thing worth naming for the record rather than as a change request: Save is now the accept-as-correct gesture for a flagged item, so pressing it unchanged sends a PATCH whose only effect is clearing aiConfidence. That is the behaviour main had and it is idempotent, so it is fine as shipped — the earlier suggestion of a dedicated "looks right" row action remains a product call, not a blocker.

Pullfrog  | View workflow run | Using Claude Opus | 𝕏

…l pattern

Each dialog becomes one self-contained file that owns its open state and
its own form, so the trigger/modal pairs collapse: edit-line-item.tsx
holds the trigger, the dialog and a private EditLineItemForm, and
edit-line-item-modal.tsx is gone (same for add). Disclosure is
self-controlled through Dialog open/onOpenChange and DialogTrigger
instead of the parent mounting the modal, and DialogClose replaces the
onCancel prop threaded down from the list.

The add button becomes a real trigger component, which leaves
LineItemList stateless. Each form keeps its own useForm and validates
with the schema from its own API module, so the api/ directory is
untouched and behaviour is unchanged.
@aek676
aek676 force-pushed the refactor/web-line-items branch from c50c12a to 57170d9 Compare August 12, 2026 23:12
@aek676
aek676 merged commit 96eeaf0 into main Aug 12, 2026
2 checks passed
@aek676
aek676 deleted the refactor/web-line-items branch August 12, 2026 23:15
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