diff --git a/README.md b/README.md index 77ea5dd..bbd9204 100644 --- a/README.md +++ b/README.md @@ -74,3 +74,5 @@ 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). Verified product reviews and moderation: see [Phase 4B API guide](docs/product-reviews-api.md). + +Seasonal campaigns and scheduled collection discovery: see [Phase 4C API guide](docs/seasonal-campaigns-api.md). diff --git a/docs/roadmap.md b/docs/roadmap.md index 87fad34..9e14658 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -56,6 +56,7 @@ Wishlist, verified reviews/moderation, seasonal campaigns, discounts, cart recov - 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. - 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. ## Phase 5: Community and optimization diff --git a/docs/seasonal-campaigns-api.md b/docs/seasonal-campaigns-api.md index c606736..64d5b68 100644 --- a/docs/seasonal-campaigns-api.md +++ b/docs/seasonal-campaigns-api.md @@ -8,7 +8,7 @@ Seasonal campaigns promote existing catalog collections during an explicit time | GET | `/campaigns/:id` | `campaigns.read`; scoped campaign and live status | | POST | `/campaigns` | `campaigns.manage`; create draft with a reusable UUID idempotency key | | PATCH | `/campaigns/:id` | `campaigns.manage`; edit draft with its current version | -| POST | `/campaigns/:id/publication` | `campaigns.manage`; publish/schedule draft; empty body or `{}` | +| POST | `/campaigns/:id/publication` | `campaigns.manage`; publish/schedule the specified draft version | | POST | `/campaigns/:id/cancellation` | `campaigns.manage`; cancel with a reason | | GET | `/storefront/:organizationId/campaigns` | Public; active campaigns only | | GET | `/storefront/:organizationId/campaigns/:slug` | Public; active campaign by slug | @@ -19,9 +19,9 @@ Create body: `slug` (existing collection slug format, at most 100 characters), ` PATCH takes the current integer `version` plus one or more of `title`, `summary`, `collectionId`, `startsAt`, or `endsAt`. Slug and original creation identity are fixed. A stale version returns 409; callers should refetch after an ambiguous timeout before deciding whether to retry. A patch that changes no values leaves version and audit history unchanged. Actual changes increment version. -Persisted `state` is `DRAFT`, `PUBLISHED`, or `CANCELLED`. Staff responses also include computed `status`: `DRAFT`, `SCHEDULED`, `ACTIVE`, `ENDED`, or `CANCELLED`. Active visibility uses `startsAt <= now < endsAt`; it requires no scheduler, worker, or cron job. Publication requires an unexpired end time and a collection in the caller's organization containing at least one published product with an active variant. +Persisted `state` is `DRAFT`, `PUBLISHED`, or `CANCELLED`. Staff responses also include computed `status`: `DRAFT`, `SCHEDULED`, `ACTIVE`, `ENDED`, or `CANCELLED`. Status describes the lifecycle/time window; public visibility additionally requires an eligible collection. Active visibility uses `startsAt <= now < endsAt`; it requires no scheduler, worker, or cron job. Publication requires an unexpired end time and a collection in the caller's organization containing at least one published product with an active variant. -Published campaign terms cannot be edited. Repeating publication for an already published campaign returns its current representation without another audit event. Cancelled campaigns cannot be published. Cancellation body is `{ "reason": "Campaign withdrawn" }` (3–500 characters). Cancellation applies to drafts and published campaigns; repeating the same reason returns the current record, while a conflicting reason returns 409. Cancellation metadata is immutable. No hard-delete endpoint exists. +Publication body is `{ "version": 0 }`, using the draft version just read. A stale version returns 409. Published campaign terms cannot be edited. Repeating the original publication version returns its current representation without another audit event; a different version conflicts. Cancelled campaigns cannot be published. Cancellation body is `{ "reason": "Campaign withdrawn" }` (3–500 characters). Cancellation applies to drafts and published campaigns; repeating the same reason returns the current record, while a conflicting reason returns 409. Cancellation metadata is immutable. No hard-delete endpoint exists. Public responses include only campaign ID, slug, title, summary, UTC start/end, and collection ID/name/slug. Drafts, future, expired, and cancelled campaigns are absent. Changing a linked group to a category or removing all eligible products also hides the campaign. An inactive or unknown public slug returns 404. Public collection links can use the existing storefront product list with `groupId`. diff --git a/src/campaigns/campaign-lifecycle.store.ts b/src/campaigns/campaign-lifecycle.store.ts new file mode 100644 index 0000000..117f667 --- /dev/null +++ b/src/campaigns/campaign-lifecycle.store.ts @@ -0,0 +1,92 @@ +import { Injectable } from '@nestjs/common'; +import { AccessStore } from '../identity/access.store'; +import { AppError } from '../common/errors/app-error'; +import { recordAudit } from '../identity/audit'; +import type { Principal } from '../identity/identity.types'; +import { + campaignInclude, + eligibleCampaignCollection, + nextCampaignVersion, + requireCampaign, +} from './campaign-lookup'; +import { campaignStatus } from './campaign-policy'; + +@Injectable() +export class CampaignLifecycleStore { + constructor(private readonly access: AccessStore) {} + + publish(actor: Principal, id: string, version: number) { + return this.access.mutate(actor, 'campaigns.manage', async (tx) => { + const campaign = await requireCampaign(tx, actor.organizationId, id); + if (campaign.state === 'PUBLISHED') { + if (campaign.version !== version + 1) + throw new AppError('CAMPAIGN_CHANGED'); + return { ...campaign, status: campaignStatus(campaign) }; + } + if (campaign.state !== 'DRAFT') + throw new AppError('CAMPAIGN_STATE_CONFLICT'); + if (campaign.version !== version) throw new AppError('CAMPAIGN_CHANGED'); + if ( + !(await tx.catalogGroup.findFirst({ + where: { + ...eligibleCampaignCollection, + id: campaign.collectionId, + organizationId: actor.organizationId, + }, + select: { id: true }, + })) + ) + throw new AppError('CAMPAIGN_COLLECTION_EMPTY'); + const now = new Date(); + if (campaign.endsAt <= now) throw new AppError('CAMPAIGN_EXPIRED'); + const published = await tx.seasonalCampaign.update({ + where: { id }, + data: { + state: 'PUBLISHED', + publishedAt: now, + publishedById: actor.userId, + version: nextCampaignVersion(campaign.version), + }, + include: campaignInclude, + }); + await recordAudit( + tx, + actor.organizationId, + actor.userId, + 'campaign.published', + id, + ); + return { ...published, status: campaignStatus(published) }; + }); + } + + cancel(actor: Principal, id: string, reason: string) { + return this.access.mutate(actor, 'campaigns.manage', async (tx) => { + const campaign = await requireCampaign(tx, actor.organizationId, id); + if (campaign.state === 'CANCELLED') { + if (campaign.cancellationReason !== reason) + throw new AppError('CAMPAIGN_CANCELLATION_CONFLICT'); + return { ...campaign, status: campaignStatus(campaign) }; + } + const cancelled = await tx.seasonalCampaign.update({ + where: { id }, + data: { + state: 'CANCELLED', + cancelledAt: new Date(), + cancelledById: actor.userId, + cancellationReason: reason, + version: nextCampaignVersion(campaign.version), + }, + include: campaignInclude, + }); + await recordAudit( + tx, + actor.organizationId, + actor.userId, + 'campaign.cancelled', + id, + ); + return { ...cancelled, status: campaignStatus(cancelled) }; + }); + } +} diff --git a/src/campaigns/campaign-read.store.ts b/src/campaigns/campaign-read.store.ts index 9ab6306..ffb8f57 100644 --- a/src/campaigns/campaign-read.store.ts +++ b/src/campaigns/campaign-read.store.ts @@ -1,13 +1,50 @@ import { Injectable } from '@nestjs/common'; import { DatabaseService } from '../database/database.service'; import type { Principal } from '../identity/identity.types'; -import { campaignStatus } from './campaign-policy'; -import { campaignInclude, requireCampaign } from './campaign-lookup'; +import { campaignStatus, publicCampaignView } from './campaign-policy'; +import { + campaignInclude, + eligibleCampaignCollection, + requireCampaign, +} from './campaign-lookup'; +import { AppError } from '../common/errors/app-error'; +import type { PageInput } from '../identity/identity.schemas'; +import type { Prisma } from '../generated/prisma/client'; import type { CampaignQuery } from './campaign.schemas'; @Injectable() export class CampaignReadStore { constructor(private readonly db: DatabaseService) {} + private publicWhere( + organizationId: string, + now: Date, + ): Prisma.SeasonalCampaignWhereInput { + return { + organizationId, + state: 'PUBLISHED', + startsAt: { lte: now }, + endsAt: { gt: now }, + collection: eligibleCampaignCollection, + }; + } + async publicList(organizationId: string, page: PageInput, now = new Date()) { + const campaigns = await this.db.seasonalCampaign.findMany({ + where: this.publicWhere(organizationId, now), + include: campaignInclude, + orderBy: [{ startsAt: 'desc' }, { id: 'asc' }], + take: page.limit, + skip: page.offset, + }); + return campaigns.map(publicCampaignView); + } + async publicGet(organizationId: string, slug: string) { + const campaign = await this.db.seasonalCampaign.findFirst({ + where: { ...this.publicWhere(organizationId, new Date()), slug }, + include: campaignInclude, + }); + if (!campaign) throw new AppError('CAMPAIGN_NOT_FOUND'); + return publicCampaignView(campaign); + } async list(actor: Principal, query: CampaignQuery) { const campaigns = await this.db.seasonalCampaign.findMany({ where: { diff --git a/src/campaigns/campaign.schemas.ts b/src/campaigns/campaign.schemas.ts index 57b8385..1ee8103 100644 --- a/src/campaigns/campaign.schemas.ts +++ b/src/campaigns/campaign.schemas.ts @@ -13,6 +13,7 @@ const fields = { startsAt: timestamp, endsAt: timestamp, }; +const version = z.number().int().min(0).max(2147483647); export const campaignCreateSchema = z .object({ ...fields, @@ -29,14 +30,14 @@ export const campaignPatchSchema = z .object(fields) .partial() .extend({ - version: z.number().int().min(0).max(2147483647), + version, }) .strict() .refine( (value) => Object.keys(value).some((key) => key !== 'version'), 'Provide at least one field', ); -export const campaignPublicationSchema = z.object({}).strict().default({}); +export const campaignPublicationSchema = z.object({ version }).strict(); export const campaignCancellationSchema = z .object({ reason: text(500, 3) }) .strict(); diff --git a/src/campaigns/campaigns.controller.ts b/src/campaigns/campaigns.controller.ts index c43cd9d..e89881c 100644 --- a/src/campaigns/campaigns.controller.ts +++ b/src/campaigns/campaigns.controller.ts @@ -16,6 +16,11 @@ import type { Principal } from '../identity/identity.types'; import { SchemaPipe } from '../common/validation.pipe'; import { CampaignDraftStore } from './campaign-draft.store'; import { CampaignReadStore } from './campaign-read.store'; +import { CampaignLifecycleStore } from './campaign-lifecycle.store'; +import { + campaignPublicationSchema, + campaignCancellationSchema, +} from './campaign.schemas'; import { campaignCreateSchema, campaignPatchSchema, @@ -30,6 +35,7 @@ export class CampaignsController { constructor( private readonly drafts: CampaignDraftStore, private readonly campaigns: CampaignReadStore, + private readonly lifecycle: CampaignLifecycleStore, ) {} @Get() @RequirePermission('campaigns.read') @@ -39,6 +45,25 @@ export class CampaignsController { ) { return this.campaigns.list(actor, query); } + @Post(':id/publication') + @RequirePermission('campaigns.manage') + publish( + @CurrentPrincipal() actor: Principal, + @Param('id', ParseUUIDPipe) id: string, + @Body(new SchemaPipe(campaignPublicationSchema)) + input: { version: number }, + ) { + return this.lifecycle.publish(actor, id, input.version); + } + @Post(':id/cancellation') + @RequirePermission('campaigns.manage') + cancel( + @CurrentPrincipal() actor: Principal, + @Param('id', ParseUUIDPipe) id: string, + @Body(new SchemaPipe(campaignCancellationSchema)) input: { reason: string }, + ) { + return this.lifecycle.cancel(actor, id, input.reason); + } @Get(':id') @RequirePermission('campaigns.read') get( diff --git a/src/campaigns/campaigns.module.ts b/src/campaigns/campaigns.module.ts index f432aba..9bd2a52 100644 --- a/src/campaigns/campaigns.module.ts +++ b/src/campaigns/campaigns.module.ts @@ -4,10 +4,18 @@ import { IdentityModule } from '../identity/identity.module'; import { CampaignsController } from './campaigns.controller'; import { CampaignDraftStore } from './campaign-draft.store'; import { CampaignReadStore } from './campaign-read.store'; +import { CampaignLifecycleStore } from './campaign-lifecycle.store'; +import { PublicCampaignsController } from './public-campaigns.controller'; +import { StorefrontGuard } from '../catalog/storefront.guard'; @Module({ imports: [DatabaseModule, IdentityModule], - controllers: [CampaignsController], - providers: [CampaignDraftStore, CampaignReadStore], + controllers: [CampaignsController, PublicCampaignsController], + providers: [ + CampaignDraftStore, + CampaignReadStore, + CampaignLifecycleStore, + StorefrontGuard, + ], }) export class CampaignsModule {} diff --git a/src/campaigns/public-campaigns.controller.ts b/src/campaigns/public-campaigns.controller.ts new file mode 100644 index 0000000..dd65340 --- /dev/null +++ b/src/campaigns/public-campaigns.controller.ts @@ -0,0 +1,35 @@ +import { + Controller, + Get, + Param, + ParseUUIDPipe, + Query, + UseGuards, +} from '@nestjs/common'; +import { Public } from '../identity/access.decorator'; +import { StorefrontGuard } from '../catalog/storefront.guard'; +import { pageSchema, type PageInput } from '../identity/identity.schemas'; +import { SchemaPipe } from '../common/validation.pipe'; +import { CampaignReadStore } from './campaign-read.store'; +import { campaignSlugSchema } from './campaign.schemas'; + +@Public() +@UseGuards(StorefrontGuard) +@Controller('storefront/:organizationId/campaigns') +export class PublicCampaignsController { + constructor(private readonly campaigns: CampaignReadStore) {} + @Get() + list( + @Param('organizationId', ParseUUIDPipe) organizationId: string, + @Query(new SchemaPipe(pageSchema)) page: PageInput, + ) { + return this.campaigns.publicList(organizationId, page); + } + @Get(':slug') + get( + @Param('organizationId', ParseUUIDPipe) organizationId: string, + @Param('slug', new SchemaPipe(campaignSlugSchema)) slug: string, + ) { + return this.campaigns.publicGet(organizationId, slug); + } +} diff --git a/src/common/errors/campaign-errors.ts b/src/common/errors/campaign-errors.ts index a1c96b4..edd832e 100644 --- a/src/common/errors/campaign-errors.ts +++ b/src/common/errors/campaign-errors.ts @@ -1,4 +1,19 @@ export const CAMPAIGN_ERRORS = { + CAMPAIGN_COLLECTION_EMPTY: [ + 409, + 'Collection needs a published product with an active variant', + 'Campaign collection publication eligibility failed', + ], + CAMPAIGN_EXPIRED: [ + 409, + 'Campaign end time has passed', + 'Expired campaign publication rejected', + ], + CAMPAIGN_CANCELLATION_CONFLICT: [ + 409, + 'Campaign was cancelled with a different reason', + 'Cancellation replay mismatch', + ], CAMPAIGN_NOT_FOUND: [ 404, 'Campaign not found', diff --git a/test/seasonal-campaign-drafts.spec.ts b/test/seasonal-campaign-drafts.spec.ts index 15cd839..a8ddc2b 100644 --- a/test/seasonal-campaign-drafts.spec.ts +++ b/test/seasonal-campaign-drafts.spec.ts @@ -164,4 +164,26 @@ describe('seasonal campaign drafts', () => { const docs = await ctx.api().get('/api/docs-json').expect(200); expect(docs.body.paths[url]).toBeDefined(); }); + + it('enforces immutable identity, valid windows and collection organization scope in the database', async () => { + const body = await input(); + const created = await create(body).expect(201); + await expect( + ctx.executeSql( + `UPDATE seasonal_campaigns SET slug = 'rewritten-slug', version = version + 1 WHERE id = '${created.body.id}'`, + ), + ).rejects.toThrow('identity'); + await expect( + ctx.executeSql( + `UPDATE seasonal_campaigns SET ends_at = starts_at, version = version + 1 WHERE id = '${created.body.id}'`, + ), + ).rejects.toThrow(); + const outsider = await secondActor(ctx, false); + await expect( + ctx.executeSql(`INSERT INTO seasonal_campaigns + (id, organization_id, collection_id, created_by_id, slug, title, summary, starts_at, ends_at, idempotency_key, request_hash, updated_at) + SELECT '${randomUUID()}', '${outsider.organizationId}', collection_id, '${outsider.userId}', 'cross-${randomUUID()}', title, summary, starts_at, ends_at, '${randomUUID()}', request_hash, NOW() + FROM seasonal_campaigns WHERE id = '${created.body.id}'`), + ).rejects.toThrow(); + }); }); diff --git a/test/seasonal-campaign-publication.spec.ts b/test/seasonal-campaign-publication.spec.ts new file mode 100644 index 0000000..aba2d17 --- /dev/null +++ b/test/seasonal-campaign-publication.spec.ts @@ -0,0 +1,252 @@ +import { randomUUID } from 'node:crypto'; +import { identityApp, type IdentityApp } from './helpers/identity-app'; +import { seedProduct } from './helpers/commerce'; +import { CampaignReadStore } from '../src/campaigns/campaign-read.store'; + +describe('seasonal campaign publication', () => { + let ctx: IdentityApp; + const auth = { type: 'bearer' as const }; + const url = '/api/v1/campaigns'; + beforeAll(async () => { + ctx = await identityApp(true); + }, 60000); + afterAll(async () => { + await ctx?.close(); + }); + beforeEach(async () => { + await ctx.clearLimits(); + }); + + async function fixture( + startsAt = new Date(Date.now() - 60000), + endsAt = new Date(Date.now() + 3600000), + populated = true, + ) { + const collection = await ctx + .api() + .post('/api/v1/catalog-groups') + .auth(ctx.token, auth) + .send({ + name: 'Gift collection', + slug: 'gifts-' + randomUUID(), + kind: 'COLLECTION', + }) + .expect(201); + const item = await seedProduct(ctx, true); + if (populated) + await ctx.db.productGroup.create({ + data: { + organizationId: ctx.owner.organizationId, + productId: item.product.id, + groupId: collection.body.id, + }, + }); + const body = { + slug: 'season-' + randomUUID(), + title: 'Seasonal gifts', + summary: 'Explore our candles', + collectionId: collection.body.id as string, + startsAt: startsAt.toISOString(), + endsAt: endsAt.toISOString(), + idempotencyKey: randomUUID(), + }; + const campaign = await ctx + .api() + .post(url) + .auth(ctx.token, auth) + .send(body) + .expect(201); + const publicBase = `/api/v1/storefront/${ctx.owner.organizationId}/campaigns`; + return { + ...item, + collection: collection.body as { id: string; slug: string }, + body, + campaign: campaign.body as { id: string; version: number }, + publicBase, + publicUrl: `${publicBase}/${body.slug}`, + }; + } + const publish = (id: string, version = 0) => + ctx + .api() + .post(`${url}/${id}/publication`) + .auth(ctx.token, auth) + .send({ version }); + + it('publishes eligible campaigns once and exposes only public fields', async () => { + const f = await fixture(); + await ctx.api().get(f.publicUrl).expect(404); + const [first, retry] = await Promise.all([ + publish(f.campaign.id).expect(201), + publish(f.campaign.id).expect(201), + ]); + expect(first.body).toMatchObject({ + state: 'PUBLISHED', + status: 'ACTIVE', + version: 1, + }); + expect(retry.body.publishedAt).toBe(first.body.publishedAt); + const publicResult = await ctx.api().get(f.publicUrl).expect(200); + expect(publicResult.body).toMatchObject({ + id: f.campaign.id, + title: f.body.title, + collection: { id: f.collection.id }, + }); + for (const field of [ + 'organizationId', + 'createdById', + 'publishedById', + 'requestHash', + 'idempotencyKey', + 'version', + 'cancellationReason', + ]) + expect(publicResult.body).not.toHaveProperty(field); + const list = await ctx.api().get(`${f.publicBase}?limit=1`).expect(200); + expect(list.body).toHaveLength(1); + await ctx + .api() + .patch(`${url}/${f.campaign.id}`) + .auth(ctx.token, auth) + .send({ version: 1, title: 'Changed published copy' }) + .expect(409); + await expect( + ctx.executeSql( + `UPDATE seasonal_campaigns SET title = 'Changed copy', version = version + 1 WHERE id = '${f.campaign.id}'`, + ), + ).rejects.toThrow('immutable'); + expect( + await ctx.db.auditEvent.count({ + where: { targetId: f.campaign.id, action: 'campaign.published' }, + }), + ).toBe(1); + }); + + it('rejects publication of a draft changed since the staff member read it', async () => { + const f = await fixture(); + await ctx + .api() + .patch(`${url}/${f.campaign.id}`) + .auth(ctx.token, auth) + .send({ version: 0, title: 'Reviewed replacement' }) + .expect(200); + expect( + (await publish(f.campaign.id).send({ version: 0 }).expect(409)).body.code, + ).toBe('CAMPAIGN_CHANGED'); + const published = await publish(f.campaign.id) + .send({ version: 1 }) + .expect(201); + expect(published.body.version).toBe(2); + await publish(f.campaign.id).send({ version: 1 }).expect(201); + await publish(f.campaign.id).send({ version: 0 }).expect(409); + }); + + it('uses exact database window boundaries and hides future or expired campaigns', async () => { + const startsAt = new Date('2030-10-01T00:00:00.000Z'); + const endsAt = new Date('2030-10-02T00:00:00.000Z'); + const f = await fixture(startsAt, endsAt); + expect((await publish(f.campaign.id).expect(201)).body.status).toBe( + 'SCHEDULED', + ); + await ctx.api().get(f.publicUrl).expect(404); + const reads = ctx.app.get(CampaignReadStore); + const page = { limit: 100, offset: 0 }; + const contains = (rows: { id: string }[]) => + rows.some((row) => row.id === f.campaign.id); + expect( + contains( + await reads.publicList( + ctx.owner.organizationId, + page, + new Date(startsAt.getTime() - 1), + ), + ), + ).toBe(false); + expect( + contains( + await reads.publicList(ctx.owner.organizationId, page, startsAt), + ), + ).toBe(true); + expect( + contains(await reads.publicList(ctx.owner.organizationId, page, endsAt)), + ).toBe(false); + const expired = await fixture( + new Date(Date.now() - 120000), + new Date(Date.now() - 60000), + ); + expect((await publish(expired.campaign.id).expect(409)).body.code).toBe( + 'CAMPAIGN_EXPIRED', + ); + }); + + it('rejects empty collections at publication and suppresses campaigns when eligibility changes', async () => { + const empty = await fixture(undefined, undefined, false); + expect((await publish(empty.campaign.id).expect(409)).body.code).toBe( + 'CAMPAIGN_COLLECTION_EMPTY', + ); + const f = await fixture(); + await publish(f.campaign.id).expect(201); + await ctx.db.productVariant.update({ + where: { id: f.variant.id }, + data: { active: false }, + }); + await ctx.api().get(f.publicUrl).expect(404); + await ctx.db.productVariant.update({ + where: { id: f.variant.id }, + data: { active: true }, + }); + await ctx.api().get(f.publicUrl).expect(200); + await ctx + .api() + .put(`/api/v1/catalog-groups/${f.collection.id}`) + .auth(ctx.token, auth) + .send({ + name: 'Gift category', + slug: f.collection.slug, + kind: 'CATEGORY', + }) + .expect(200); + await ctx.api().get(f.publicUrl).expect(404); + }); + + it('cancels drafts and publications permanently with repeatable reasons', async () => { + for (const published of [false, true]) { + const f = await fixture(); + if (published) await publish(f.campaign.id).expect(201); + const cancellation = `${url}/${f.campaign.id}/cancellation`; + const body = { reason: 'Campaign withdrawn' }; + const first = await ctx + .api() + .post(cancellation) + .auth(ctx.token, auth) + .send(body) + .expect(201); + const retry = await ctx + .api() + .post(cancellation) + .auth(ctx.token, auth) + .send(body) + .expect(201); + expect(first.body.status).toBe('CANCELLED'); + expect(retry.body.version).toBe(first.body.version); + await ctx + .api() + .post(cancellation) + .auth(ctx.token, auth) + .send({ reason: 'Different reason' }) + .expect(409); + await publish(f.campaign.id).expect(409); + await ctx.api().get(f.publicUrl).expect(404); + await expect( + ctx.executeSql( + `DELETE FROM seasonal_campaigns WHERE id = '${f.campaign.id}'`, + ), + ).rejects.toThrow(); + expect( + await ctx.db.auditEvent.count({ + where: { targetId: f.campaign.id, action: 'campaign.cancelled' }, + }), + ).toBe(1); + } + }); +});