Skip to content

Generalize receipt storage and let a draft be discarded - #29

Merged
aek676 merged 9 commits into
mainfrom
refactor/object-storage
Aug 11, 2026
Merged

aek676 merged 9 commits into
mainfrom
refactor/object-storage

Conversation

@aek676

@aek676 aek676 commented Aug 10, 2026

Copy link
Copy Markdown
Owner

What

Turns the receipt-specific GCS wrapper into a generic keyed object storage, adds DELETE /sessions/:sessionId, and wires the web app's "Retake photo" button to it so abandoning a draft no longer leaks a session document and an orphaned image.

Changes

Storage (apps/api/src/storage)

  • ObjectStorage is now a plain keyed interface — save(key, bytes, mediaType), get(key), delete(key) — with no knowledge of receipts. GcsObjectStorage takes a prefix so other kinds of objects can share the same bucket later.
  • Key naming (<uuid>.<ext>) and the /receipts/<id> URL mapping move to apps/api/src/modules/receipt/service.ts, where they belong. createReceiptStorage() in storage/index.ts is the single composition point.

Session deletion

  • DELETE /sessions/:sessionId, owner-only, removes the session document and then best-effort deletes its receipt image. A storage failure does not fail the request — the document is already gone, and a stray object is cheaper than a dangling session.
  • Returns 204; 401/403 come from the existing auth plugin.

Web

  • New useDeleteSession hook: deletes the session, clears its device token from the browser, and drops the cached session query.
  • "Retake photo" is now a button that discards the draft before navigating home, instead of a link that silently abandoned it. The header back link is gone for the same reason — the review screen should not be left with an unresolved draft.

Shared types / dev setup

  • SUPPORTED_IMAGE_MIME_TYPES and EXT_BY_MEDIA_TYPE move from the API to @repo/shared-types, so the web upload validation and the API agree on one list.
  • compose.yaml mounts .dev/gcs into fake-gcs-server, so the dev bucket exists on boot. The app never creates buckets itself; in production the bucket is provisioned by infra.

Testing

  • bun nx test api and bun nx test:integration api — unit specs for the new storage composition, receipt key helpers, and session deletion; integration coverage for the delete route's auth and 204 path.
  • bun nx lint web / bun nx typecheck web.

Note: typecheck needs bun nx build shared-types to have emitted into dist/out-tsc first — a stale or missing build there surfaces as "no exported member" errors from @repo/shared-types.

aek676 added 5 commits August 9, 2026 23:59
The web read EXT_BY_MEDIA_TYPE and SUPPORTED_IMAGE_MIME_TYPES through
`@repo/api/constants`, coupling the frontend to the backend just to know
which MIME types the receipt upload accepts. Move them to
`@repo/shared-types`, which both apps already depend on, and drop the
api's `./constants` entry point along with its barrel file.
fake-gcs-server creates buckets from the layout under /data on startup, so
mounting `.dev/gcs` gives the dev stack the `snapsplit-receipts` bucket
without the app having to create it on first use.
`ReceiptStorage` mixed three concerns: talking to GCS, minting the file id
from the media type, and creating the bucket on demand when running
against the emulator. That made the interface untestable in isolation and
tied every caller to receipts.

Split them apart:

- `ObjectStorage` now takes the key explicitly, so it knows nothing about
  receipts. `GcsObjectStorage` receives its prefix, bucket and endpoint
  through the constructor instead of reading `Bun.env` on the spot.
- `createReceiptStorage(env)` in `storage/index.ts` wires the receipts
  bucket and is the only place that touches the environment.
- The receipt-specific rules — how a file id is minted and how it maps to
  the public `/receipts/:fileId` path — move to `modules/receipt/service.ts`
  and are now covered by unit tests.
- `ensureBucket()` is gone: the dev bucket is seeded from `.dev/gcs`, and
  in production the bucket is provisioned by infra.

`createReceiptModule(storage)` mirrors `createSessionModule` so the route
can be exercised with a fake storage.
`DELETE /sessions/:sessionId` lets the payer discard a session — a draft
they no longer want, or a settled bill. Only the owner may call it, so the
route reuses the `owner: true` guard from the auth plugin and answers 204
with an empty body.

The stored image is dropped alongside the document, mapping the session's
`receiptImageUrl` back to a storage key with `receiptFileId`. A failing
storage delete does not fail the request: the document is already gone and
a leftover object is cheaper than a session the owner cannot remove.
"Retake photo" was a plain link back to home, which left the draft
session and its receipt image behind on the server. It now deletes the
session first, drops its device token and cached query, and navigates
home once the request settles.

Also drop the header back link: leaving the review screen without
resolving the draft is exactly what that route no longer allows.

@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 storage refactor is clean and behaviour-preserving, but the new DELETE /sessions/:sessionId accepts sessions in any status — including open and closed, where it destroys every participant's embedded line items and claims. Worth settling the intended scope before merge.

Reviewed changes — full diff of all 26 files at fd4e085, plus local verification of the lint, sync and unit-test gates.

  • ObjectStorage generalization — save() now takes a caller-supplied key and returns void; GcsObjectStorage is constructed with { prefix, bucketName, apiEndpoint } rather than reaching into Bun.env itself.
  • Key/URL logic relocated — newReceiptFileId, receiptUrl, receiptFileId and RECEIPT_BASE_PATH move to modules/receipt/service.ts; createReceiptStorage() in storage/index.ts becomes the single composition point.
  • ensureBucket() deleted — emulator bucket auto-creation is replaced by seeding fake-gcs-server from a new ./.dev/gcs:/data compose mount.
  • New DELETE /sessions/:sessionId — owner: true, returns 204, hard-deletes the document then best-effort deletes the receipt image.
  • Web discard flow — new useDeleteSession hook; "Retake photo" becomes a button that discards before navigating, and the header back-link is removed.
  • Media types moved to @repo/shared-types — the @repo/api/constants subpath export is dropped.

I confirmed the stored object layout is receipts/<uuid>.<ext> both before and after, so existing images and existing receiptImageUrl values keep resolving — no migration needed. doc.deleteOne() is a valid Mongoose document method in the installed version, and receiptImageUrl defaults to '' with receiptFileId('') returning null, so the no-image path is safe. Locally: bun nx test api 121 pass, bunx nx lint web exit 0, bunx nx sync:check up to date.

⚠️ Nothing proves the session document is actually deleted

The PR body states the change ships "integration coverage for the delete route's auth and 204 path", but apps/api/test/ gains no new spec — the only change there is fixtures.ts type renames. Every test of the delete path mocks Session.prototype.deleteOne, so the suite would stay green if the call never reached Mongo at all.

Technical details
# Delete path has no real-database coverage

## Affected sites
- `apps/api/src/modules/session/__test__/service.spec.ts:251` — `spyOn(Session.prototype, 'deleteOne').mockImplementation(...)`; asserts the spy was called, not that a document was removed.
- `apps/api/src/modules/session/__test__/index.spec.ts:383` — same mock at the route level.
- `apps/api/test/` — contains only `auth-flow.spec.ts`, `session-participants.spec.ts`, `fixtures.ts`, `setup.ts`. No delete spec was added.

## Required outcome
- Either add a `test:integration` spec that issues `DELETE /sessions/:sessionId` against the real Mongo testcontainer and asserts the document is gone afterward, or correct the PR description so it does not claim coverage that is not present.

## Open questions for the human
- Docker is unavailable in this review sandbox, so the integration suite could not be executed here — this finding comes from reading the file list, not from a failing run.

ℹ️ Nitpicks

  • apps/web/src/features/session/components/session-draft.tsx:7 — ChevronLeft is now unused; removing the header <Link> removed its only consumer. bunx biome lint flags it as lint/correctness/noUnusedImports. It does not fail nx lint web (warnings are non-fatal in this repo) but it is new noise introduced by this PR.
  • apps/api/src/storage/gcs.ts:22 — objectName() guards with this.prefix ? ... : key, but prefix is a required non-optional field of GcsObjectStorageOptions and the sole construction site passes the literal 'receipts'. The empty-prefix branch is unreachable.

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

Comment thread apps/api/src/modules/session/index.ts Resolved
Comment thread apps/api/src/app.ts Resolved
@pullfrog

pullfrog Bot commented Aug 10, 2026

Copy link
Copy Markdown

Follow-up to my review — one correction, one firmer finding

Some verification finished after I submitted my review above. Where this comment and that review disagree, this one is right.

Correction: failed deletes are not silent

In my inline comment on session-draft.tsx:130 I wrote that a failed DELETE surfaces "no error anywhere." That is wrong — apologies for the noise. apps/web/src/lib/api-client.ts:21-25 is a global Eden onResponse hook that toasts on any non-ok, non-401 response, so a 403 or 500 does show the user an error toast.

The narrower concern that survives:

  • The toast fires, but onSettled navigates to / regardless, so the user is bounced home as the error appears — and clearToken/removeQueries (hook onSuccess) never run, leaving the orphaned session this PR set out to prevent.
  • A pure network failure rejects before any Response exists, so it never reaches onResponse and genuinely is silent. That blind spot is app-wide and pre-existing, not introduced here.

For what it's worth, add-line-item-modal.tsx:45 and delete-line-item.tsx:56 both gate their UI transition on onSuccess, leaving the surface up on failure so the user can retry. RetakePhotoButton is the only place that leaves the screen unconditionally.

Firmer: the missing draft guard breaks an existing convention

I raised the missing status guard as a design question. It is more concrete than that — deleteSession is the only mutation in SessionService that omits a guard its three siblings all implement:

Method Guard
addLineItem service.ts:129-130 — status !== 'draft' → 409
updateLineItem service.ts:150-151 — status !== 'draft' → 409
deleteLineItem service.ts:178-179 — status !== 'draft' → 409
deleteSession (none)

The response type already exists — sessionNotDraft: t.Literal('Session is not editable') at model.ts:54, already wired as 409 on all three sibling routes at index.ts:74, :96, :117. So this is a one-line inconsistency against an established pattern, not a new abstraction to design.

Two things that should inform which way you go:

  • docs/srs.md:148-156 defines only draft→open, open→closed and closed→open, and describes no delete/discard transition — the spec neither authorizes nor forbids this.
  • The web confirm action is still a stub (session-draft.tsx:95-96), so the UI cannot yet produce an open session to delete. The gap is reachable only by direct API call today, which makes it cheap to close now rather than after confirm is wired up.

Cleared: dev bucket seeding

I flagged the ensureBucket() removal as unverifiable. It has since been checked against fake-gcs-server's sources and needs no action: the image's ENTRYPOINT already carries -data /data and compose.yaml overrides only command:, so the new ./.dev/gcs:/data mount is read as the seed directory; -filesystem-root defaults to /storage, a separate path, so the existing fake-gcs-data volume is untouched; seeding runs every start but bucket creation is a no-op when the bucket exists; and a directory holding only .gitkeep still registers as a bucket.

Pullfrog  | View workflow run | via Pullfrog | Using Claude Opus | 𝕏

aek676 added 4 commits August 11, 2026 11:07
`app.ts` re-exported `EXT_BY_MEDIA_TYPE`, `SUPPORTED_IMAGE_MIME_TYPES` and
`SupportedImageMimeType` next to the `App` type, but nothing consumed them:
`apps/web/src/lib/api-client.ts` is the only importer of `@repo/api` and it
takes `import type { App }` alone. The `./constants` subpath they used to be
reachable through is gone too.

They are value exports on a module that transitively pulls in `mongoose` and
`@google-cloud/storage`, so importing them from here would drag the server
into the browser bundle — the coupling that moving the media types to
`@repo/shared-types` set out to remove. Consumers already take them from
`@repo/shared-types` or from `storage/object-storage`.
`clearToken` and `removeQueries` ran in the mutation's `onSuccess` while the
button navigated home on `onSettled`, so a failed `DELETE` left for home with
the device token still stored and the session still cached. Pressing back
returned the user to the draft they had just discarded, alive and editable.

Discarding is local-first: "Retake photo" is both a delete and an intent to
move on, and the intent does not hang on the server answering. The device now
forgets the session either way, and a document left behind expires with its
TTL. Clearing the token before leaving is safe because `expireSession` treats
a session it holds no token for as already handled, so a late refetch neither
toasts nor redirects.
Removing the header back link took away the icon's only consumer. Biome
reports it as `lint/correctness/noUnusedImports`, but only as a warning, so
`nx lint web` stayed green with it in place.
`src/model.ts` held a single Elysia schema and sat next to `index.ts` and
`app.ts`, where the rest of the tree is folders by responsibility. It also
collided by name with the per-module `modules/session/model.ts` and
`modules/auth/model.ts`, so `'../model'` and `'../../model'` read as if they
pointed at a module's own schemas when they pointed at a global one.

It now lives in `src/common/model.ts`, alongside `plugins/`, `schemas/` and
`storage/`, which leaves an obvious home for the next validation schema shared
across modules. The two importers, `plugins/auth.ts` and
`modules/session/model.ts`, are the only ones in the repo.

`OBJECT_ID_PATTERN` stays in `@repo/shared-types`. The binding to `t.String`
does not follow it there: that lib is framework-agnostic and `apps/web`
consumes it through a `export *` barrel, so an Elysia schema would pull
typebox into the browser bundle's type graph.

@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 the four commits since the last review. Not an approval only because the earlier DELETE /sessions/:sessionId scope thread is still open.

Reviewed changes — the four commits added since the prior pullfrog review at fd4e085, plus a re-run of the repo's CI gates.

  • Dropped the dead media-type re-export — app.ts no longer re-exports EXT_BY_MEDIA_TYPE / SUPPORTED_IMAGE_MIME_TYPES; @repo/shared-types is now the single source and nothing pulls those constants through a module that transitively imports mongoose and @google-cloud/storage.
  • Moved the discard cleanup to onSettled — useDeleteSession now runs clearToken and removeQueries regardless of outcome, so the hook and the button's navigation finally agree on what "discarded" means. React Query invokes hook-level callbacks before mutate-level ones, so cleanup still precedes the navigation.
  • Removed the orphaned ChevronLeft import — clears the noUnusedImports warning the removed header link left behind.
  • Relocated the shared objectId schema — src/model.ts → src/common/model.ts, with plugins/auth.ts and modules/session/model.ts updated. Verified no ../model imports still point at the old root path.

Locally: bunx nx sync:check up to date, nx run-many -t tsc:typecheck format:check green for all six projects, bun nx test api 121 pass, bun nx lint web exit 0 with only pre-existing noExplicitAny warnings. On the failure path introduced by b8c10f9: a failed DELETE does leave a server-side orphan the user can no longer reach, but sessionSchema carries a 90-day TTL on createdAt and the global Eden onResponse hook toasts the error, so it degrades to the pre-PR status quo rather than to something worse.

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

@aek676
aek676 merged commit 3673870 into main Aug 11, 2026
1 check passed
@aek676
aek676 deleted the refactor/object-storage branch August 11, 2026 21:50
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