diff --git a/README.md b/README.md index 37f9b3b..f3464ba 100644 --- a/README.md +++ b/README.md @@ -78,3 +78,5 @@ Verified product reviews and moderation: see [Phase 4B API guide](docs/product-r Seasonal campaigns and scheduled collection discovery: see [Phase 4C API guide](docs/seasonal-campaigns-api.md). Campaign-linked collection discounts: see [Phase 4D API guide](docs/campaign-discounts-api.md). + +Private idle cart recovery: see [Phase 4E API guide](docs/cart-recovery-api.md). diff --git a/docs/cart-recovery-api.md b/docs/cart-recovery-api.md new file mode 100644 index 0000000..a99df6e --- /dev/null +++ b/docs/cart-recovery-api.md @@ -0,0 +1,20 @@ +# Private cart recovery (Phase 4E) + +Authenticated customers can resume their persisted cart after at least 24 hours without a successful cart edit, recovery, or checkout. Cart reads and failed commands do not refresh activity. A cart must contain at least one line and have a known activity timestamp. This milestone provides in-app recovery; outbound reminders require the later consent-aware messaging milestone. + +All routes use the caller's live active session and own organization/user scope. No staff permission, user ID parameter, public token, customer directory, or new provider is involved. Existing access rate limits apply. + +| Method | Route | Behavior | +| ------ | ----------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- | +| GET | `/api/v1/cart/recovery` | Returns `version`, nullable `lastActivityAt`, `recoverable`, and current lines; does not create a cart or change activity. | +| POST | `/api/v1/cart/recovery` | Strict body `{ "version": 1 }`; resumes the eligible cart at its current version. Returns 201 with the next `version` and `removedVariantIds`. | + +Each preview line contains `variantId`, `quantity`, `available`, and `variant`. Available variants expose current name, SKU, decimal price, currency, and product name. Inactive variants and unpublished products return `available: false, variant: null`; their private catalog details are redacted. The response contains no user profile or contact details. + +The customer explicitly confirms removal of unavailable lines when posting recovery. Resumption rechecks catalog availability, preserves all available quantities, removes unavailable lines atomically, refreshes activity, increments the cart version once, and appends `cart.recovered` to the audit trail. A competing edit, checkout, or recovery is serialized by the existing organization lock. Stale versions return `CART_CHANGED` (409); empty, undated, or recently active carts return `CART_NOT_RECOVERABLE` (409). Invalid bodies return 400; missing/inactive sessions are rejected by the existing access guard. A lost successful response is resolved by reading the new version, rather than blindly retrying the old command. + +Availability means currently active and published merchandise, not a stock reservation. Recovery neither freezes prices nor copies coupons from earlier orders. Checkout remains authoritative for current prices, currency consistency, campaign/coupon eligibility, stock, and immutable order snapshots. Customers can edit the recovered cart with the existing versioned cart endpoints. + +Deploy the additive nullable `last_activity_at` migration before the application. Existing carts retain all lines but have unknown historical activity; they become eligible only after a new successful cart edit followed by 24 idle hours. This avoids inventing old activity timestamps. No historical migrations are edited. Older code ignores the new column; if rolling back and later re-enabling recovery, clear timestamps for carts that may have been edited by the older code before enabling recovery again. Preserve cart lines, orders, and audit history. + +Acceptance covers the exact 24-hour boundary, empty/unknown/future activity, current prices, read-only activity semantics, customer and organization isolation, schema validation, stale and concurrent commands, audit uniqueness, inactive/unpublished redaction and removal, and edit/checkout reset. Native PostgreSQL concurrency checks remain subject to the project's existing CI database setup. diff --git a/docs/roadmap.md b/docs/roadmap.md index 5a40ad6..abf889c 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -58,6 +58,7 @@ Wishlist, verified reviews/moderation, seasonal campaigns, discounts, cart recov - 4B (implemented): customer reviews gated by independent staff verification of external purchase evidence, immutable submissions, independent approval/rejection/hiding, evidence revocation, and a privacy-preserving public feed. Automated checkout/payment verification, review revisions, and rating analytics remain separate milestones. - 4C (implemented): organization-scoped seasonal campaign drafts, versioned editing/publication, immutable published terms, reasoned cancellation, and time-windowed public collection discovery. Campaign discounts, media assets, outbound messaging, and channel integrations remain separate milestones. - 4D (implemented): draft-bound campaign coupons, version-aware offer publication, public offer terms, and collection-only fixed/percentage checkout discounts with exact eligible-subtotal snapshots. Generic coupons retain their behavior; payment enablement, media assets and messaging remain separate milestones. +- 4E (implemented): private discovery and versioned resumption of carts idle for 24 hours, current catalog previews, unavailable-item redaction/removal, and audited activity tracking. Outbound recovery reminders remain dependent on consent-aware messaging and provider enablement. ## Phase 5: Community and optimization diff --git a/prisma/checkout.prisma b/prisma/checkout.prisma index d496e39..1d29477 100644 --- a/prisma/checkout.prisma +++ b/prisma/checkout.prisma @@ -11,6 +11,7 @@ model Cart { organizationId String @map("organization_id") @db.Uuid userId String @map("user_id") @db.Uuid version Int @default(0) + lastActivityAt DateTime? @map("last_activity_at") @db.Timestamptz(3) user User @relation(fields: [userId, organizationId], references: [id, organizationId], onDelete: Restrict) lines CartLine[] @@unique([userId, organizationId]) diff --git a/prisma/migration-checksums.json b/prisma/migration-checksums.json index f8ee4c8..a11d73b 100644 --- a/prisma/migration-checksums.json +++ b/prisma/migration-checksums.json @@ -46,5 +46,6 @@ "20261005120000_private_wishlists": "8ded2f27a4e08ea6af3e5ae92f15b832cea66156a7489f28e178d3df6404f5e4", "20261005160000_verified_product_reviews": "1f71f6d49622c48a37c88f2eb7740174cbc9aea7d0027f6fc27d81301d87c757", "20261006120000_seasonal_campaigns": "4f81582f91a8d3cb30bf49051281ca05c862b794925c0643a7237d1a1efb6f40", - "20261006160000_campaign_discounts": "99485a5b252f01057dfa6300c567c79586555a76cec5c2dc0d9c3fef9fc61017" + "20261006160000_campaign_discounts": "99485a5b252f01057dfa6300c567c79586555a76cec5c2dc0d9c3fef9fc61017", + "20261007120000_cart_recovery": "a415f3b458c55bf37a95f8d2f3b31dfc7ae4427f04aabc9f0910f1201caa6d31" } diff --git a/prisma/migrations/20261007120000_cart_recovery/migration.sql b/prisma/migrations/20261007120000_cart_recovery/migration.sql new file mode 100644 index 0000000..b843c20 --- /dev/null +++ b/prisma/migrations/20261007120000_cart_recovery/migration.sql @@ -0,0 +1,2 @@ +-- Historical carts have unknown activity; reads must not invent abandonment times. +ALTER TABLE "carts" ADD COLUMN "last_activity_at" TIMESTAMPTZ(3); diff --git a/src/checkout/cart-recovery.store.ts b/src/checkout/cart-recovery.store.ts new file mode 100644 index 0000000..bee03cc --- /dev/null +++ b/src/checkout/cart-recovery.store.ts @@ -0,0 +1,115 @@ +import { Injectable } from '@nestjs/common'; +import { AccessStore } from '../identity/access.store'; +import type { Principal } from '../identity/identity.types'; +import { recordAudit } from '../identity/audit'; +import { AppError } from '../common/errors/app-error'; + +export function isRecoverable( + lastActivityAt: Date | null, + count: number, + now: Date, +) { + return ( + count > 0 && + lastActivityAt !== null && + now.getTime() - lastActivityAt.getTime() >= 24 * 3600000 + ); +} + +const recoveryInclude = { + lines: { + orderBy: { id: 'asc' as const }, + select: { + variantId: true, + quantity: true, + variant: { + select: { + name: true, + sku: true, + price: true, + currency: true, + active: true, + product: { select: { name: true, status: true } }, + }, + }, + }, + }, +}; +const available = (variant: { active: boolean; product: { status: string } }) => + variant.active && variant.product.status === 'PUBLISHED'; + +@Injectable() +export class CartRecoveryStore { + constructor(private readonly access: AccessStore) {} + get(actor: Principal) { + return this.access.mutate(actor, null, async (tx) => { + const cart = await tx.cart.findUnique({ + where: { + userId_organizationId: { + userId: actor.userId, + organizationId: actor.organizationId, + }, + }, + include: recoveryInclude, + }); + return { + version: cart?.version ?? 0, + lastActivityAt: cart?.lastActivityAt ?? null, + recoverable: isRecoverable( + cart?.lastActivityAt ?? null, + cart?.lines.length ?? 0, + new Date(), + ), + lines: (cart?.lines ?? []).map(({ variantId, quantity, variant }) => ({ + variantId, + quantity, + available: available(variant), + variant: available(variant) + ? { + name: variant.name, + sku: variant.sku, + price: variant.price, + currency: variant.currency, + productName: variant.product.name, + } + : null, + })), + }; + }); + } + resume(actor: Principal, version: number) { + return this.access.mutate(actor, null, async (tx) => { + const cart = await tx.cart.findUnique({ + where: { + userId_organizationId: { + userId: actor.userId, + organizationId: actor.organizationId, + }, + }, + include: recoveryInclude, + }); + if (cart && cart.version !== version) throw new AppError('CART_CHANGED'); + const now = new Date(); + if (!cart || !isRecoverable(cart.lastActivityAt, cart.lines.length, now)) + throw new AppError('CART_NOT_RECOVERABLE'); + const removedVariantIds = cart.lines + .filter((line) => !available(line.variant)) + .map((line) => line.variantId); + await tx.cartLine.deleteMany({ + where: { cartId: cart.id, variantId: { in: removedVariantIds } }, + }); + await tx.cart.update({ + where: { id: cart.id }, + data: { version: { increment: 1 }, lastActivityAt: now }, + }); + await recordAudit( + tx, + actor.organizationId, + actor.userId, + 'cart.recovered', + cart.id, + ); + return { version: version + 1, removedVariantIds }; + }); + } +} diff --git a/src/checkout/cart.controller.ts b/src/checkout/cart.controller.ts index 4f4d0d9..a684170 100644 --- a/src/checkout/cart.controller.ts +++ b/src/checkout/cart.controller.ts @@ -5,6 +5,7 @@ import { Get, Param, ParseUUIDPipe, + Post, Put, } from '@nestjs/common'; import { CurrentPrincipal } from '../identity/access.decorator'; @@ -12,9 +13,24 @@ import type { Principal } from '../identity/identity.types'; import { SchemaPipe } from '../common/validation.pipe'; import { cartLineSchema, cartVersionSchema } from './checkout.schemas'; import { CartStore } from './cart.store'; +import { CartRecoveryStore } from './cart-recovery.store'; @Controller('cart') export class CartController { - constructor(private readonly carts: CartStore) {} + constructor( + private readonly carts: CartStore, + private readonly recovery: CartRecoveryStore, + ) {} + @Get('recovery') + recoverable(@CurrentPrincipal() actor: Principal) { + return this.recovery.get(actor); + } + @Post('recovery') + resume( + @CurrentPrincipal() actor: Principal, + @Body(new SchemaPipe(cartVersionSchema)) input: { version: number }, + ) { + return this.recovery.resume(actor, input.version); + } @Get() get(@CurrentPrincipal() actor: Principal) { return this.carts.get(actor); diff --git a/src/checkout/cart.store.ts b/src/checkout/cart.store.ts index b580654..4072e5e 100644 --- a/src/checkout/cart.store.ts +++ b/src/checkout/cart.store.ts @@ -88,7 +88,7 @@ export class CartStore { } await tx.cart.update({ where: { id: cart.id }, - data: { version: { increment: 1 } }, + data: { version: { increment: 1 }, lastActivityAt: new Date() }, }); return { version: version + 1 }; }); diff --git a/src/checkout/checkout.module.ts b/src/checkout/checkout.module.ts index b2b2e6b..b8f95ba 100644 --- a/src/checkout/checkout.module.ts +++ b/src/checkout/checkout.module.ts @@ -2,6 +2,7 @@ import { Module } from '@nestjs/common'; import { DatabaseModule } from '../database/database.module'; import { IdentityModule } from '../identity/identity.module'; import { CartStore } from './cart.store'; +import { CartRecoveryStore } from './cart-recovery.store'; import { CartController } from './cart.controller'; import { CheckoutStore } from './checkout.store'; import { OrderStore } from './order.store'; @@ -18,6 +19,12 @@ import { CouponsController } from '../coupons/coupons.controller'; OrderAdminController, CouponsController, ], - providers: [CartStore, CheckoutStore, OrderStore, CouponStore], + providers: [ + CartStore, + CartRecoveryStore, + CheckoutStore, + OrderStore, + CouponStore, + ], }) export class CheckoutModule {} diff --git a/src/checkout/checkout.store.ts b/src/checkout/checkout.store.ts index 00d1cf7..07570c6 100644 --- a/src/checkout/checkout.store.ts +++ b/src/checkout/checkout.store.ts @@ -73,7 +73,7 @@ export class CheckoutStore { await tx.cartLine.deleteMany({ where: { cartId } }); await tx.cart.update({ where: { id: cartId }, - data: { version: { increment: 1 } }, + data: { version: { increment: 1 }, lastActivityAt: now }, }); await recordAudit( tx, diff --git a/src/common/errors/checkout-errors.ts b/src/common/errors/checkout-errors.ts index 6d91099..ed1fbba 100644 --- a/src/common/errors/checkout-errors.ts +++ b/src/common/errors/checkout-errors.ts @@ -1,4 +1,9 @@ export const CHECKOUT_ERRORS = { + CART_NOT_RECOVERABLE: [ + 409, + 'Cart is not eligible for recovery', + 'Empty, recently active or undated cart recovery rejected', + ], CART_EMPTY: [ 409, 'Add items before checkout', diff --git a/test/cart-recovery-policy.spec.ts b/test/cart-recovery-policy.spec.ts new file mode 100644 index 0000000..506f0a5 --- /dev/null +++ b/test/cart-recovery-policy.spec.ts @@ -0,0 +1,11 @@ +import { isRecoverable } from '../src/checkout/cart-recovery.store'; + +it('requires a nonempty, dated cart idle for at least 24 hours', () => { + const now = new Date('2026-10-07T12:00:00Z'); + const boundary = new Date(now.getTime() - 24 * 3600000); + expect(isRecoverable(boundary, 1, now)).toBe(true); + expect(isRecoverable(new Date(boundary.getTime() + 1), 1, now)).toBe(false); + expect(isRecoverable(boundary, 0, now)).toBe(false); + expect(isRecoverable(null, 1, now)).toBe(false); + expect(isRecoverable(new Date(now.getTime() + 1), 1, now)).toBe(false); +}); diff --git a/test/cart-recovery.spec.ts b/test/cart-recovery.spec.ts new file mode 100644 index 0000000..63c7dab --- /dev/null +++ b/test/cart-recovery.spec.ts @@ -0,0 +1,239 @@ +import { identityApp, type IdentityApp } from './helpers/identity-app'; +import { checkoutFixture } from './helpers/checkout'; +import { secondActor } from './helpers/commerce'; + +describe('private idle cart recovery', () => { + let ctx: IdentityApp; + beforeAll(async () => { + ctx = await identityApp(); + }); + afterAll(async () => { + await ctx.close(); + }); + beforeEach(async () => { + await ctx.clearLimits(); + }); + const idle = async (userId: string) => { + await ctx.db.cart.updateMany({ + where: { userId }, + data: { lastActivityAt: new Date(Date.now() - 25 * 3600000) }, + }); + }; + it('discovers retained carts privately without refreshing activity on reads', async () => { + const f = await checkoutFixture(ctx); + const read = () => + ctx + .api() + .get('/api/v1/cart/recovery') + .auth(f.actor.token, { type: 'bearer' }); + expect((await read().expect(200)).body.recoverable).toBe(false); + await idle(f.actor.userId); + await ctx.db.productVariant.update({ + where: { id: f.variant.id }, + data: { price: '549.25' }, + }); + const result = await read().expect(200); + expect(result.body).toMatchObject({ + recoverable: true, + version: 1, + lines: [ + { + variantId: f.variant.id, + quantity: 2, + available: true, + variant: { price: '549.25', currency: 'INR' }, + }, + ], + }); + await ctx + .api() + .get('/api/v1/cart') + .auth(f.actor.token, { type: 'bearer' }) + .expect(200); + expect((await read().expect(200)).body.lastActivityAt).toBe( + result.body.lastActivityAt, + ); + for (const sameOrganization of [true, false]) { + const other = await secondActor(ctx, sameOrganization); + expect( + ( + await ctx + .api() + .get('/api/v1/cart/recovery') + .auth(other.token, { type: 'bearer' }) + .expect(200) + ).body, + ).toEqual({ + recoverable: false, + version: 0, + lastActivityAt: null, + lines: [], + }); + } + await ctx.api().get('/api/v1/cart/recovery').expect(401); + await ctx + .api() + .post('/api/v1/cart/recovery') + .send({ version: 1 }) + .expect(401); + }); + it('resumes once at the reviewed version and records an audit', async () => { + const f = await checkoutFixture(ctx); + const resume = (body: object) => + ctx + .api() + .post('/api/v1/cart/recovery') + .auth(f.actor.token, { type: 'bearer' }) + .send(body); + expect((await resume({ version: 1 }).expect(409)).body.code).toBe( + 'CART_NOT_RECOVERABLE', + ); + await idle(f.actor.userId); + expect((await resume({ version: 0 }).expect(409)).body.code).toBe( + 'CART_CHANGED', + ); + await resume({ version: 1, userId: ctx.owner.userId }).expect(400); + expect((await resume({ version: 1 }).expect(201)).body).toEqual({ + version: 2, + removedVariantIds: [], + }); + expect((await resume({ version: 1 }).expect(409)).body.code).toBe( + 'CART_CHANGED', + ); + const cart = await ctx + .api() + .get('/api/v1/cart') + .auth(f.actor.token, { type: 'bearer' }) + .expect(200); + expect(cart.body).toMatchObject({ version: 2, lines: [{ quantity: 2 }] }); + expect( + await ctx.db.auditEvent.count({ + where: { actorId: f.actor.userId, action: 'cart.recovered' }, + }), + ).toBe(1); + }); + it('redacts unavailable merchandise and removes it only on explicit resume', async () => { + const f = await checkoutFixture(ctx); + await idle(f.actor.userId); + await ctx.db.productVariant.update({ + where: { id: f.variant.id }, + data: { active: false }, + }); + const result = await ctx + .api() + .get('/api/v1/cart/recovery') + .auth(f.actor.token, { type: 'bearer' }) + .expect(200); + expect(result.body.lines).toEqual([ + { variantId: f.variant.id, quantity: 2, available: false, variant: null }, + ]); + const resumed = await ctx + .api() + .post('/api/v1/cart/recovery') + .auth(f.actor.token, { type: 'bearer' }) + .send({ version: 1 }) + .expect(201); + expect(resumed.body).toEqual({ + version: 2, + removedVariantIds: [f.variant.id], + }); + expect( + ( + await ctx + .api() + .get('/api/v1/cart/recovery') + .auth(f.actor.token, { type: 'bearer' }) + .expect(200) + ).body.recoverable, + ).toBe(false); + }); + it('editing or checking out ends recovery eligibility', async () => { + const f = await checkoutFixture(ctx); + await idle(f.actor.userId); + await ctx + .api() + .put('/api/v1/cart/lines/' + f.variant.id) + .auth(f.actor.token, { type: 'bearer' }) + .send({ version: 1, quantity: 1 }) + .expect(200); + expect( + ( + await ctx + .api() + .get('/api/v1/cart/recovery') + .auth(f.actor.token, { type: 'bearer' }) + .expect(200) + ).body.recoverable, + ).toBe(false); + await idle(f.actor.userId); + await ctx + .api() + .post('/api/v1/checkout') + .auth(f.actor.token, { type: 'bearer' }) + .send({ ...f.input, cartVersion: 2 }) + .expect(201); + const result = await ctx + .api() + .get('/api/v1/cart/recovery') + .auth(f.actor.token, { type: 'bearer' }) + .expect(200); + expect(result.body).toMatchObject({ + recoverable: false, + version: 3, + lines: [], + }); + expect(Date.now() - Date.parse(result.body.lastActivityAt)).toBeLessThan( + 60000, + ); + }); + it('serializes competing recovery commands and leaves undated carts alone', async () => { + const f = await checkoutFixture(ctx); + await ctx.db.cart.updateMany({ + where: { userId: f.actor.userId }, + data: { lastActivityAt: null }, + }); + const resume = () => + ctx + .api() + .post('/api/v1/cart/recovery') + .auth(f.actor.token, { type: 'bearer' }) + .send({ version: 1 }); + expect((await resume().expect(409)).body.code).toBe('CART_NOT_RECOVERABLE'); + const other = await secondActor(ctx); + await ctx + .api() + .post('/api/v1/cart/recovery') + .auth(other.token, { type: 'bearer' }) + .send({ version: 1 }) + .expect(409); + await idle(f.actor.userId); + const results = await Promise.all([resume(), resume()]); + expect(results.map((r) => r.status).sort()).toEqual([201, 409]); + expect( + await ctx.db.auditEvent.count({ + where: { actorId: f.actor.userId, action: 'cart.recovered' }, + }), + ).toBe(1); + }); + it('rechecks product publication at resume even after a successful preview', async () => { + const f = await checkoutFixture(ctx); + await idle(f.actor.userId); + const preview = await ctx + .api() + .get('/api/v1/cart/recovery') + .auth(f.actor.token, { type: 'bearer' }) + .expect(200); + expect(preview.body.lines[0].available).toBe(true); + await ctx.db.product.update({ + where: { id: f.product.id }, + data: { status: 'DRAFT' }, + }); + const resumed = await ctx + .api() + .post('/api/v1/cart/recovery') + .auth(f.actor.token, { type: 'bearer' }) + .send({ version: 1 }) + .expect(201); + expect(resumed.body.removedVariantIds).toEqual([f.variant.id]); + }); +});