Repository navigation
refactor(web): align the line-item components with the dialog pattern - #32
Conversation
There was a problem hiding this comment.
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 intoline-item-form.tsx, and the two identical zod schemas collapse intoapi/line-item-draft.ts. LOW_CONFIDENCE_THRESHOLDmoves intoline-item/utils/confidence.tsand is consumed byline-item-row.tsxandsession-draft.tsx.session.totalCentsstops being a running tally and becomes a snapshot; a newtotalSource: '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) andPOST /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). receiptTotalson the web drops its ±2c tolerance somatchesis 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.7now lives in two places:apps/api/src/modules/session/service.ts:19andapps/web/src/features/session/line-item/utils/confidence.ts. If they drift, the web enables the Confirm button against a server that will 409 withsessionNeedsReview.- In
update-session.ts,apiError(error.value, 'Failed to update the receipt total')is also the fallback for thetotalSource: 'items'handover, where "update the receipt total" is the wrong description of what the user did.
Claude Opus | 𝕏
There was a problem hiding this comment.
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
totalSourcestate machine,PATCH /sessions/:sessionId,POST /sessions/:sessionId/confirmand their tests are onmainnow. The merged tree diverges frommainonly in the 9 web files, so nothing was lost in the resolution, and no stale reference toadd-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'sline-item/utils/confidence.tsis gone;line-item-row.tsx,confirm-session-button.tsx, and the API service all readLOW_CONFIDENCE_THRESHOLDfromlibs/shared-types, which retires the duplication nit from the last review. - Inherited a wired Confirm button.
ConfirmSessionButtonreplaced theconsole.logplaceholder and calls the confirm endpoint, andconfirmSessionnow performs the draft→open transition through a conditionalfindOneAndUpdate, 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?Claude Opus | 𝕏
There was a problem hiding this comment.
ℹ️ No new issues in this delta. The API-module revert is behaviour-neutral and every
webgate passes on the checkout. Not approving only because the open thread online-item-form.tsx:147from 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
mainstate.api/line-item-draft.tsand its sharedlineItemDraftInputSchemaare deleted;add-line-item.tsandupdate-line-item.tsare byte-for-byte identical tomainagain, each keeping its own schema and inferred*DraftInputtype. The PR now touches 6 files, all components. - Made
LineItemFormschema-agnostic. It declares its ownLineItemFormValuesinterface and takesschema: z.ZodType<LineItemFormValues, LineItemFormValues>, which it feeds tovalidators.onSubmit.AddLineItempassesaddLineItemDraftInputSchema,EditLineItempassesupdateLineItemDraftInputSchema.
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.
Claude Opus | 𝕏
There was a problem hiding this comment.
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 itsDialogFooterare now inlined verbatim into the privateAddLineItemFormandEditLineItemForminsideadd-line-item.tsxandedit-line-item.tsx. The PR now touches 5 files. - Each form owns its own
useFormagain.defaultValues,validators.onSubmit(the module's own zod schema), andonSubmit(the mutation call) are declared per dialog; theschema/defaultValues/isPending/onSubmitprop plumbing and the exportedLineItemFormValuesinterface are gone, andisPendingreads directly offaddLineItem/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.
Claude Opus | 𝕏
There was a problem hiding this comment.
✅ No new issues found.
c50c12afixes 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:188andedit-line-item.tsx:197are back todisabled={!canSubmit || isPending}, and theform.Subscribeselectors no longer readisDirty.
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.
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.
c50c12a to
57170d9
Compare

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. Theapi/modules are untouched.Changes
edit-line-item.tsxnow holds the trigger, the dialog, and its privateEditLineItemForm;edit-line-item-modal.tsxis gone (same for add). Each form keeps its ownuseFormand validates with the schema from its own API module.Dialog open/onOpenChange+DialogTrigger renderinstead of the parent conditionally mounting the modal, andDialogCloseinstead of anonCancelprop threaded down.addingstate move out ofline-item-list.tsxintoadd-line-item.tsx; the list is now stateless.initialprop tolineItemto match the codebase vocabulary.No behavior change:
add-line-item.tsandupdate-line-item.tsare byte-for-byte unchanged, each keeping its own zod schema, and the submit gate stays!canSubmit || isPendingas before.Review feedback
Pullfrog caught that an
!isDirtysubmit gate added in an earlier revision made low-confidence items unclearable — the API liftsaiConfidenceback to 1 on any field patch, so pressing Save on a correctly-extracted flagged item is the accept gesture, andConfirmSessionButtonstays 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, andconfirmSessionalready uses an atomicfindOneAndUpdate({ _id, status: 'draft' }).Verification
bun nx run-many -t lint test build -p web— all green (75 unit tests), plusbun nx test api(158 tests).tsc --noEmit -p apps/web/tsconfig.app.jsonreports no errors in the changed files. (It does report 5 pre-existingBuntype errors inapps/apisources pulled in through the Eden client types — they fail on a clean checkout ofmaintoo, unrelated to this change.)