From 5a8087b51aac054d3da086a0cdc546fdad99b844 Mon Sep 17 00:00:00 2001 From: mihir Date: Mon, 5 Oct 2026 09:54:51 +0530 Subject: [PATCH] feat(wishlist): add private variant wishlists --- README.md | 2 + docs/roadmap.md | 2 + docs/wishlist-api.md | 17 ++ prisma/catalog.prisma | 1 + prisma/migration-checksums.json | 3 +- .../migration.sql | 22 ++ prisma/schema.prisma | 1 + prisma/wishlist.prisma | 12 ++ src/app.module.ts | 2 + src/common/errors/error-catalog.ts | 2 + src/common/errors/wishlist-errors.ts | 12 ++ src/wishlist/wishlist-view.ts | 39 ++++ src/wishlist/wishlist.controller.ts | 48 +++++ src/wishlist/wishlist.module.ts | 12 ++ src/wishlist/wishlist.schemas.ts | 5 + src/wishlist/wishlist.store.ts | 84 ++++++++ test/wishlist-view.spec.ts | 70 +++++++ test/wishlist.spec.ts | 189 ++++++++++++++++++ 18 files changed, 522 insertions(+), 1 deletion(-) create mode 100644 docs/wishlist-api.md create mode 100644 prisma/migrations/20261005120000_private_wishlists/migration.sql create mode 100644 prisma/wishlist.prisma create mode 100644 src/common/errors/wishlist-errors.ts create mode 100644 src/wishlist/wishlist-view.ts create mode 100644 src/wishlist/wishlist.controller.ts create mode 100644 src/wishlist/wishlist.module.ts create mode 100644 src/wishlist/wishlist.schemas.ts create mode 100644 src/wishlist/wishlist.store.ts create mode 100644 test/wishlist-view.spec.ts create mode 100644 test/wishlist.spec.ts diff --git a/README.md b/README.md index 12195e6..8578f78 100644 --- a/README.md +++ b/README.md @@ -70,3 +70,5 @@ B2B partner partial payments: see [Phase 3H API guide](docs/b2b-partner-payments B2B custom candle requests and staff review: see [Phase 3I API guide](docs/b2b-custom-candles-api.md). B2B partner reports: see [Phase 3J API guide](docs/b2b-partner-reporting-api.md). + +Private wishlists: see [Phase 4A API guide](docs/wishlist-api.md). diff --git a/docs/roadmap.md b/docs/roadmap.md index d1cd0be..ceab99c 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -54,6 +54,8 @@ Business verification, price lists, MOQ, quotations, credit policies, samples, b Wishlist, verified reviews/moderation, seasonal campaigns, discounts, cart recovery, consent-aware messaging, Instagram, Etsy, WhatsApp, blogs/SEO and segmentation. +- 4A (implemented): private user wishlists with published-variant eligibility, duplicate-safe saves, repeatable removal, paginated current catalog views, unavailable-item redaction, and a per-user quota. Public sharing, guest lists, cart conversion, and notifications remain separate milestones. + ## Phase 5: Community and optimization Moderated forums, advanced analytics, forecasts, accounting adapters, profitability and workflow automation. SaaS tenancy/billing requires a separate architecture decision before implementation; an organization table alone does not provide tenant isolation. diff --git a/docs/wishlist-api.md b/docs/wishlist-api.md new file mode 100644 index 0000000..5fa31c4 --- /dev/null +++ b/docs/wishlist-api.md @@ -0,0 +1,17 @@ +# Private wishlists (Phase 4A) + +Endpoints under `/api/v1/wishlist` require an active bearer session. Like private addresses and carts, they need no staff permission. Ownership comes exclusively from the session; there is no staff endpoint for another user's wishlist and caller-supplied ownership fields are rejected. + +| Method | Path | Purpose | +| ------ | ------------- | ---------------------------------------------------------------------------------- | +| GET | `/` | List own saved variants; `limit` defaults to 25 (1–100), `offset` to 0 (0–10,000) | +| PUT | `/:variantId` | Save a published, active variant in the current organization; send no body or `{}` | +| DELETE | `/:variantId` | Remove own saved variant; returns 204, including when already absent | + +Each list/save response item contains `id`, `variantId`, `savedAt`, `available`, and `variant`. Available items include current variant name, SKU, exact two-decimal price, currency, and product ID/name/slug. Prices are live catalog prices, not frozen checkout prices. `available` means published and active; it does not indicate warehouse stock or reserve inventory. + +Unpublished, archived, or inactive saved variants remain in the list with `available: false` and `variant: null`. This prevents leaking private catalog details while allowing removal. Repeating PUT for an existing saved item returns its current representation, even if it has become unavailable. A new save of an unavailable, missing, or out-of-organization variant returns 404 (`WISHLIST_ITEM_UNAVAILABLE`). + +A user may save at most 100 variants. A new item at the limit returns 409 (`WISHLIST_LIMIT`); existing-item retries remain valid. List ordering is newest saved first, with ID as a stable tie-breaker. PUT retries keep the same ID and timestamp. After deletion, a later save creates a new item. Concurrent API mutations use the existing transaction/organization lock; a database unique constraint also prevents duplicate user/organization/variant entries. + +Save/remove actions produce one audit event per actual change. There are no public shares, guest wishlists, notifications, cart conversion, or inventory effects in this milestone. Composite database foreign keys enforce user and variant organization scope. Deploy the append-only migration before the application; existing records and permissions are unchanged. diff --git a/prisma/catalog.prisma b/prisma/catalog.prisma index b99bb7a..5c906cb 100644 --- a/prisma/catalog.prisma +++ b/prisma/catalog.prisma @@ -36,6 +36,7 @@ model ProductVariant { active Boolean @default(true) stockItems StockItem[] cartLines CartLine[] + wishlistItems WishlistItem[] orderLines OrderLine[] boms ProductBom[] b2bPriceListItems B2bPriceListItem[] diff --git a/prisma/migration-checksums.json b/prisma/migration-checksums.json index 90f5667..40a4856 100644 --- a/prisma/migration-checksums.json +++ b/prisma/migration-checksums.json @@ -42,5 +42,6 @@ "20261003151400_b2b_partner_orders": "ffbba39ed98a16c122b0756a97d721adde9268904f9a7d9770407f341ef848ba", "20261003183000_b2b_partner_payments": "bc43c5a713c62aa201affa2f2595156a2fc68882774504cdf12ac4cf0f641452", "20261004003000_b2b_custom_candle_requests": "ab78d0a7e214ab226e042f29b42e961ddbae3a3e338fd65983d5aa87e2c736ac", - "20261004010000_b2b_partner_reporting": "44086ecc27278b9499fbcf5fa97ed754f056fcf49f6b155e1ed377527616dc89" + "20261004010000_b2b_partner_reporting": "44086ecc27278b9499fbcf5fa97ed754f056fcf49f6b155e1ed377527616dc89", + "20261005120000_private_wishlists": "8ded2f27a4e08ea6af3e5ae92f15b832cea66156a7489f28e178d3df6404f5e4" } diff --git a/prisma/migrations/20261005120000_private_wishlists/migration.sql b/prisma/migrations/20261005120000_private_wishlists/migration.sql new file mode 100644 index 0000000..7c42667 --- /dev/null +++ b/prisma/migrations/20261005120000_private_wishlists/migration.sql @@ -0,0 +1,22 @@ +-- CreateTable +CREATE TABLE "wishlist_items" ( + "id" UUID NOT NULL, + "organization_id" UUID NOT NULL, + "user_id" UUID NOT NULL, + "variant_id" UUID NOT NULL, + "created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT "wishlist_items_pkey" PRIMARY KEY ("id") +); + +-- CreateIndex +CREATE INDEX "wishlist_items_user_id_organization_id_created_at_id_idx" ON "wishlist_items"("user_id", "organization_id", "created_at", "id"); + +-- CreateIndex +CREATE UNIQUE INDEX "wishlist_items_user_id_organization_id_variant_id_key" ON "wishlist_items"("user_id", "organization_id", "variant_id"); + +-- AddForeignKey +ALTER TABLE "wishlist_items" ADD CONSTRAINT "wishlist_items_user_id_organization_id_fkey" FOREIGN KEY ("user_id", "organization_id") REFERENCES "users"("id", "organization_id") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "wishlist_items" ADD CONSTRAINT "wishlist_items_variant_id_organization_id_fkey" FOREIGN KEY ("variant_id", "organization_id") REFERENCES "product_variants"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE; diff --git a/prisma/schema.prisma b/prisma/schema.prisma index 942881d..9333025 100644 --- a/prisma/schema.prisma +++ b/prisma/schema.prisma @@ -89,6 +89,7 @@ model User { sessions Session[] recoveryTokens RecoveryToken[] addresses Address[] + wishlistItems WishlistItem[] purchaseOrders PurchaseOrder[] goodsReceipts GoodsReceipt[] receiptInspections ReceiptInspection[] diff --git a/prisma/wishlist.prisma b/prisma/wishlist.prisma new file mode 100644 index 0000000..6184e6a --- /dev/null +++ b/prisma/wishlist.prisma @@ -0,0 +1,12 @@ +model WishlistItem { + id String @id @default(uuid()) @db.Uuid + organizationId String @map("organization_id") @db.Uuid + userId String @map("user_id") @db.Uuid + variantId String @map("variant_id") @db.Uuid + createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3) + user User @relation(fields: [userId, organizationId], references: [id, organizationId], onDelete: Cascade) + variant ProductVariant @relation(fields: [variantId, organizationId], references: [id, organizationId], onDelete: Restrict) + @@unique([userId, organizationId, variantId]) + @@index([userId, organizationId, createdAt, id]) + @@map("wishlist_items") +} diff --git a/src/app.module.ts b/src/app.module.ts index 4301f06..c9227c7 100644 --- a/src/app.module.ts +++ b/src/app.module.ts @@ -11,9 +11,11 @@ import { EnvironmentModule } from './config/environment.module'; import { IdentityModule } from './identity/identity.module'; import { HealthModule } from './health/health.module'; import { B2bModule } from './b2b/b2b.module'; +import { WishlistModule } from './wishlist/wishlist.module'; @Module({ imports: [ + WishlistModule, EnvironmentModule, HealthModule, IdentityModule, diff --git a/src/common/errors/error-catalog.ts b/src/common/errors/error-catalog.ts index 8029e3d..9268820 100644 --- a/src/common/errors/error-catalog.ts +++ b/src/common/errors/error-catalog.ts @@ -1,4 +1,5 @@ import { B2B_CUSTOM_CANDLE_ERRORS } from './b2b-custom-candle-errors'; +import { WISHLIST_ERRORS } from './wishlist-errors'; import { CHECKOUT_ERRORS } from './checkout-errors'; import { OPERATIONS_ERRORS } from './operations-errors'; import { PLATFORM_ERRORS } from './platform-errors'; @@ -12,6 +13,7 @@ import { B2B_ARTWORK_ERRORS } from './b2b-artwork-errors'; import { B2B_ORDER_ERRORS } from './b2b-order-errors'; import { B2B_PAYMENT_ERRORS } from './b2b-payment-errors'; export const ERRORS = { + ...WISHLIST_ERRORS, ...B2B_CUSTOM_CANDLE_ERRORS, ...PLATFORM_ERRORS, ...COMMERCE_ERRORS, diff --git a/src/common/errors/wishlist-errors.ts b/src/common/errors/wishlist-errors.ts new file mode 100644 index 0000000..ff3de5d --- /dev/null +++ b/src/common/errors/wishlist-errors.ts @@ -0,0 +1,12 @@ +export const WISHLIST_ERRORS = { + WISHLIST_ITEM_UNAVAILABLE: [ + 404, + 'Product variant is unavailable for saving', + 'Wishlist variant eligibility failed', + ], + WISHLIST_LIMIT: [ + 409, + 'Wishlist item limit reached', + 'Private wishlist quota exceeded', + ], +} as const; diff --git a/src/wishlist/wishlist-view.ts b/src/wishlist/wishlist-view.ts new file mode 100644 index 0000000..c18b817 --- /dev/null +++ b/src/wishlist/wishlist-view.ts @@ -0,0 +1,39 @@ +import type { Prisma } from '../generated/prisma/client'; + +export const wishlistInclude = { + variant: { + select: { + name: true, + sku: true, + price: true, + currency: true, + active: true, + product: { select: { id: true, name: true, slug: true, status: true } }, + }, + }, +} as const; +type Item = Prisma.WishlistItemGetPayload<{ include: typeof wishlistInclude }>; + +export function wishlistView(item: Item) { + const available = + item.variant.active && item.variant.product.status === 'PUBLISHED'; + return { + id: item.id, + variantId: item.variantId, + savedAt: item.createdAt, + available, + variant: available + ? { + name: item.variant.name, + sku: item.variant.sku, + price: item.variant.price.toFixed(2), + currency: item.variant.currency, + product: { + id: item.variant.product.id, + name: item.variant.product.name, + slug: item.variant.product.slug, + }, + } + : null, + }; +} diff --git a/src/wishlist/wishlist.controller.ts b/src/wishlist/wishlist.controller.ts new file mode 100644 index 0000000..f5331f4 --- /dev/null +++ b/src/wishlist/wishlist.controller.ts @@ -0,0 +1,48 @@ +import { + Body, + Controller, + Delete, + Get, + HttpCode, + Param, + ParseUUIDPipe, + Put, + Query, +} from '@nestjs/common'; +import { CurrentPrincipal } from '../identity/access.decorator'; +import type { Principal } from '../identity/identity.types'; +import type { PageInput } from '../identity/identity.schemas'; +import { SchemaPipe } from '../common/validation.pipe'; +import { WishlistStore } from './wishlist.store'; +import { wishlistQuerySchema, wishlistSaveSchema } from './wishlist.schemas'; + +@Controller('wishlist') +export class WishlistController { + constructor(private readonly wishlist: WishlistStore) {} + + @Get() + list( + @CurrentPrincipal() actor: Principal, + @Query(new SchemaPipe(wishlistQuerySchema)) query: PageInput, + ) { + return this.wishlist.list(actor, query); + } + + @Put(':variantId') + save( + @CurrentPrincipal() actor: Principal, + @Param('variantId', ParseUUIDPipe) variantId: string, + @Body(new SchemaPipe(wishlistSaveSchema)) _input: Record, + ) { + return this.wishlist.save(actor, variantId); + } + + @Delete(':variantId') + @HttpCode(204) + remove( + @CurrentPrincipal() actor: Principal, + @Param('variantId', ParseUUIDPipe) variantId: string, + ) { + return this.wishlist.remove(actor, variantId); + } +} diff --git a/src/wishlist/wishlist.module.ts b/src/wishlist/wishlist.module.ts new file mode 100644 index 0000000..317078b --- /dev/null +++ b/src/wishlist/wishlist.module.ts @@ -0,0 +1,12 @@ +import { Module } from '@nestjs/common'; +import { DatabaseModule } from '../database/database.module'; +import { IdentityModule } from '../identity/identity.module'; +import { WishlistController } from './wishlist.controller'; +import { WishlistStore } from './wishlist.store'; + +@Module({ + imports: [DatabaseModule, IdentityModule], + controllers: [WishlistController], + providers: [WishlistStore], +}) +export class WishlistModule {} diff --git a/src/wishlist/wishlist.schemas.ts b/src/wishlist/wishlist.schemas.ts new file mode 100644 index 0000000..a81388f --- /dev/null +++ b/src/wishlist/wishlist.schemas.ts @@ -0,0 +1,5 @@ +import { z } from 'zod'; +import { pageSchema } from '../identity/identity.schemas'; + +export const wishlistQuerySchema = pageSchema.strict(); +export const wishlistSaveSchema = z.object({}).strict().default({}); diff --git a/src/wishlist/wishlist.store.ts b/src/wishlist/wishlist.store.ts new file mode 100644 index 0000000..4bd360a --- /dev/null +++ b/src/wishlist/wishlist.store.ts @@ -0,0 +1,84 @@ +import { Injectable } from '@nestjs/common'; +import { DatabaseService } from '../database/database.service'; +import { AppError } from '../common/errors/app-error'; +import { AccessStore } from '../identity/access.store'; +import { recordAudit } from '../identity/audit'; +import type { Principal } from '../identity/identity.types'; +import type { PageInput } from '../identity/identity.schemas'; +import { wishlistInclude, wishlistView } from './wishlist-view'; + +@Injectable() +export class WishlistStore { + constructor( + private readonly db: DatabaseService, + private readonly access: AccessStore, + ) {} + + async list(actor: Principal, query: PageInput) { + const items = await this.db.wishlistItem.findMany({ + where: { userId: actor.userId, organizationId: actor.organizationId }, + include: wishlistInclude, + orderBy: [{ createdAt: 'desc' }, { id: 'desc' }], + take: query.limit, + skip: query.offset, + }); + return items.map(wishlistView); + } + + save(actor: Principal, variantId: string) { + return this.access.mutate(actor, null, async (tx) => { + const where = { + userId: actor.userId, + organizationId: actor.organizationId, + }; + const replay = await tx.wishlistItem.findFirst({ + where: { ...where, variantId }, + include: wishlistInclude, + }); + if (replay) return wishlistView(replay); + const variant = await tx.productVariant.findFirst({ + where: { + id: variantId, + organizationId: actor.organizationId, + active: true, + product: { status: 'PUBLISHED' }, + }, + }); + if (!variant) throw new AppError('WISHLIST_ITEM_UNAVAILABLE'); + if ((await tx.wishlistItem.count({ where })) >= 100) + throw new AppError('WISHLIST_LIMIT'); + const item = await tx.wishlistItem.create({ + data: { ...where, variantId }, + include: wishlistInclude, + }); + await recordAudit( + tx, + actor.organizationId, + actor.userId, + 'wishlist.saved', + item.id, + ); + return wishlistView(item); + }); + } + + remove(actor: Principal, variantId: string) { + return this.access.mutate(actor, null, async (tx) => { + const where = { + userId: actor.userId, + organizationId: actor.organizationId, + variantId, + }; + const item = await tx.wishlistItem.findFirst({ where }); + if (!item) return; + await tx.wishlistItem.delete({ where: { id: item.id } }); + await recordAudit( + tx, + actor.organizationId, + actor.userId, + 'wishlist.removed', + item.id, + ); + }); + } +} diff --git a/test/wishlist-view.spec.ts b/test/wishlist-view.spec.ts new file mode 100644 index 0000000..41db84f --- /dev/null +++ b/test/wishlist-view.spec.ts @@ -0,0 +1,70 @@ +import { Prisma } from '../src/generated/prisma/client'; +import { wishlistView, wishlistInclude } from '../src/wishlist/wishlist-view'; +import { + wishlistQuerySchema, + wishlistSaveSchema, +} from '../src/wishlist/wishlist.schemas'; + +const item: Prisma.WishlistItemGetPayload<{ include: typeof wishlistInclude }> = + { + id: 'item', + userId: 'user', + organizationId: 'organization', + variantId: 'variant', + createdAt: new Date('2026-10-05T00:00:00Z'), + variant: { + name: 'Rose', + sku: 'ROSE', + price: new Prisma.Decimal('499.10'), + currency: 'INR', + active: true, + product: { + id: 'product', + name: 'Candle', + slug: 'candle', + status: 'PUBLISHED', + }, + }, + }; +describe('wishlist presentation and validation', () => { + it('returns public current catalog details with exact price and no private ownership fields', () => { + const result = wishlistView(item); + expect(result.variant?.price).toBe('499.10'); + expect(result).not.toHaveProperty('userId'); + expect(result.variant?.product).not.toHaveProperty('status'); + }); + it('redacts draft, archived and inactive variants while retaining removal identifiers', () => { + for (const status of ['DRAFT', 'ARCHIVED'] as const) { + expect( + wishlistView({ + ...item, + variant: { + ...item.variant, + product: { ...item.variant.product, status }, + }, + }), + ).toMatchObject({ + variantId: 'variant', + available: false, + variant: null, + }); + } + expect( + wishlistView({ ...item, variant: { ...item.variant, active: false } }) + .variant, + ).toBeNull(); + }); + it('bounds pagination and forbids caller-supplied ownership', () => { + expect(wishlistQuerySchema.parse({})).toEqual({ limit: 25, offset: 0 }); + for (const query of [ + { limit: 101 }, + { offset: -1 }, + { userId: 'another-user' }, + ]) + expect(wishlistQuerySchema.safeParse(query).success).toBe(false); + expect(wishlistSaveSchema.parse(undefined)).toEqual({}); + expect( + wishlistSaveSchema.safeParse({ userId: 'another-user' }).success, + ).toBe(false); + }); +}); diff --git a/test/wishlist.spec.ts b/test/wishlist.spec.ts new file mode 100644 index 0000000..dbed39f --- /dev/null +++ b/test/wishlist.spec.ts @@ -0,0 +1,189 @@ +import { randomUUID } from 'node:crypto'; +import { identityApp, type IdentityApp } from './helpers/identity-app'; +import { seedProduct, secondActor } from './helpers/commerce'; + +describe('private wishlists', () => { + let ctx: IdentityApp; + const auth = { type: 'bearer' as const }; + const url = '/api/v1/wishlist'; + beforeAll(async () => { + ctx = await identityApp(true); + }, 60000); + afterAll(async () => { + await ctx?.close(); + }); + beforeEach(async () => { + await ctx.clearLimits(); + }); + const save = (id: string, token = ctx.token) => + ctx.api().put(`${url}/${id}`).auth(token, auth); + + it('saves and removes idempotently without duplicate audit events', async () => { + const { variant } = await seedProduct(ctx, true); + const [first, retry] = await Promise.all([ + save(variant.id).expect(200), + save(variant.id).expect(200), + ]); + expect(retry.body).toEqual(first.body); + expect(first.body).toMatchObject({ + variantId: variant.id, + available: true, + variant: { sku: variant.sku, price: '499.00', currency: 'INR' }, + }); + expect(first.body).not.toHaveProperty('userId'); + expect(first.body).not.toHaveProperty('organizationId'); + expect( + await ctx.db.auditEvent.count({ + where: { targetId: first.body.id, action: 'wishlist.saved' }, + }), + ).toBe(1); + for (let attempt = 0; attempt < 2; attempt++) + await ctx + .api() + .delete(`${url}/${variant.id}`) + .auth(ctx.token, auth) + .expect(204); + expect( + await ctx.db.auditEvent.count({ + where: { targetId: first.body.id, action: 'wishlist.removed' }, + }), + ).toBe(1); + expect((await save(variant.id).expect(200)).body.id).not.toBe( + first.body.id, + ); + }); + + it('keeps user lists private and rejects cross-organization variants', async () => { + const { variant } = await seedProduct(ctx, true); + await save(variant.id).expect(200); + const other = await secondActor(ctx); + expect( + (await ctx.api().get(url).auth(other.token, auth).expect(200)).body, + ).toEqual([]); + await ctx + .api() + .delete(`${url}/${variant.id}`) + .auth(other.token, auth) + .expect(204); + expect( + await ctx.db.wishlistItem.count({ + where: { userId: ctx.owner.userId, variantId: variant.id }, + }), + ).toBe(1); + await save(variant.id, other.token).expect(200); + const outsider = await secondActor(ctx, false); + await save(variant.id, outsider.token).expect(404); + expect( + (await ctx.api().get(url).auth(outsider.token, auth).expect(200)).body, + ).toEqual([]); + await expect( + ctx.executeSql(`INSERT INTO wishlist_items + (id, organization_id, user_id, variant_id) + VALUES ('${randomUUID()}', '${outsider.organizationId}', '${outsider.userId}', '${variant.id}')`), + ).rejects.toThrow(); + }); + + it('retains unavailable items without disclosing unpublished catalog details', async () => { + const { product, variant } = await seedProduct(ctx, true); + await save(variant.id).expect(200); + await ctx + .api() + .patch(`/api/v1/products/${product.id}/status`) + .auth(ctx.token, auth) + .send({ status: 'DRAFT' }) + .expect(200); + const actor = await secondActor(ctx); + await save(variant.id, actor.token).expect(404); + expect((await save(variant.id).expect(200)).body).toMatchObject({ + available: false, + variant: null, + }); + const listed = await ctx.api().get(url).auth(ctx.token, auth).expect(200); + expect( + listed.body.find( + (item: { variantId: string }) => item.variantId === variant.id, + ).variant, + ).toBeNull(); + await ctx + .api() + .delete(`${url}/${variant.id}`) + .auth(ctx.token, auth) + .expect(204); + await save(variant.id).expect(404); + await ctx.db.productVariant.update({ + where: { id: variant.id }, + data: { active: false }, + }); + await save(variant.id).expect(404); + }); + + it('validates pagination, identifiers and ownership injection, and exposes Swagger', async () => { + await ctx.api().get(url).expect(401); + const actor = await secondActor(ctx); + const variants = await Promise.all([ + seedProduct(ctx, true), + seedProduct(ctx, true), + ]); + for (const { variant } of variants) + await save(variant.id, actor.token).expect(200); + const page = (offset: number) => + ctx + .api() + .get(`${url}?limit=1&offset=${offset}`) + .auth(actor.token, auth) + .expect(200); + const first = (await page(0)).body; + const next = (await page(1)).body; + expect(first).toHaveLength(1); + expect(next).toHaveLength(1); + expect(first[0].id).not.toBe(next[0].id); + await ctx + .api() + .get(`${url}?userId=${ctx.owner.userId}`) + .auth(actor.token, auth) + .expect(400); + await save(variants[0].variant.id, actor.token) + .send({ userId: ctx.owner.userId }) + .expect(400); + await save('invalid').expect(400); + await save(randomUUID()).expect(404); + const docs = await ctx.api().get('/api/docs-json').expect(200); + expect(docs.body.paths['/api/v1/wishlist/{variantId}']).toBeDefined(); + }); + + it('enforces the 100-item quota and allows existing-item retries at the limit', async () => { + const actor = await secondActor(ctx); + const { product, variant } = await seedProduct(ctx, true); + const ids = Array.from({ length: 100 }, () => randomUUID()); + await ctx.db.productVariant.createMany({ + data: ids.map((id) => ({ + id, + productId: product.id, + organizationId: actor.organizationId, + name: 'Quota fixture', + sku: id, + price: '100.00', + })), + }); + await ctx.db.wishlistItem.createMany({ + data: ids.map((variantId) => ({ + organizationId: actor.organizationId, + userId: actor.userId, + variantId, + })), + }); + expect((await save(variant.id, actor.token).expect(409)).body.code).toBe( + 'WISHLIST_LIMIT', + ); + await save(ids[0], actor.token).expect(200); + await ctx + .api() + .delete(`${url}/${ids[0]}`) + .auth(actor.token, auth) + .expect(204); + await save(variant.id, actor.token).expect(200); + expect( + await ctx.db.wishlistItem.count({ where: { userId: actor.userId } }), + ).toBe(100); + }); +});