diff --git a/docs/seasonal-campaigns-api.md b/docs/seasonal-campaigns-api.md new file mode 100644 index 0000000..c606736 --- /dev/null +++ b/docs/seasonal-campaigns-api.md @@ -0,0 +1,32 @@ +# Seasonal campaigns (Phase 4C) + +Seasonal campaigns promote existing catalog collections during an explicit time window. They contain public title/summary copy and a collection link. Collection membership remains live; checkout prices and coupon eligibility continue to use the existing commerce rules. + +| Method | Path under `/api/v1` | Access | +| ------ | --------------------------------------------- | --------------------------------------------------------------------- | +| GET | `/campaigns` | `campaigns.read`; optional persisted `state` filter | +| 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/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 | + +Lists use the existing `limit` (1–100, default 25) and `offset` (0–10,000, default 0) contract. Staff resources are organization-scoped. Public routes share the existing storefront rate limit. + +Create body: `slug` (existing collection slug format, at most 100 characters), `title` (1–160), `summary` (0–500; default empty), `collectionId` (UUID), `startsAt`, `endsAt`, and `idempotencyKey` (UUID). Times must be ISO timestamps with a timezone/UTC offset and are normalized to UTC milliseconds; end must be after start at that precision. Unknown fields and HTML/control characters in copy are rejected. + +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. + +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. + +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`. + +Creation keys are organization-scoped and retained with the campaign. Identical retries return the current representation; different original content using the same key returns 409. Unique slugs are organization-scoped. All actual writes record audit events within the existing transaction/organization lock. Inputs derive organization and staff identity from the bearer session. + +Acceptance: private drafts; exact start/end boundaries; versioned edits; immutable published terms; repeatable publication/cancellation; scoped permissions/collections; dynamic collection suppression; public-field allowlist; preserved checkout behavior. Verify with `pnpm check` and `pnpm db:test`, plus focused Jest campaign tests. Implementation lives in `src/campaigns`, tests in `test`, and the additive migration in `prisma/migrations`. + +Deploy the migration before the application. It adds one campaign table, scoped foreign keys, unique/index/time constraints, and lifecycle guards, and grants `campaigns.read`/`campaigns.manage` to existing system Owner roles. Custom roles require explicit grants. Rollback can redeploy the previous application while retaining the new table and audit history. This milestone provides collection discovery; campaign discounts, media assets, outbound messaging, and channel integrations are separate work. diff --git a/src/campaigns/campaign-policy.ts b/src/campaigns/campaign-policy.ts new file mode 100644 index 0000000..204ec21 --- /dev/null +++ b/src/campaigns/campaign-policy.ts @@ -0,0 +1,35 @@ +type CampaignTime = { + state: 'DRAFT' | 'PUBLISHED' | 'CANCELLED'; + startsAt: Date; + endsAt: Date; +}; + +export function campaignStatus(campaign: CampaignTime, now = new Date()) { + if (campaign.state !== 'PUBLISHED') return campaign.state; + if (now < campaign.startsAt) return 'SCHEDULED'; + return now >= campaign.endsAt ? 'ENDED' : 'ACTIVE'; +} + +export function publicCampaignView( + campaign: CampaignTime & { + id: string; + slug: string; + title: string; + summary: string; + collection: { id: string; name: string; slug: string }; + }, +) { + return { + id: campaign.id, + slug: campaign.slug, + title: campaign.title, + summary: campaign.summary, + startsAt: campaign.startsAt, + endsAt: campaign.endsAt, + collection: { + id: campaign.collection.id, + name: campaign.collection.name, + slug: campaign.collection.slug, + }, + }; +} diff --git a/src/campaigns/campaign.schemas.ts b/src/campaigns/campaign.schemas.ts new file mode 100644 index 0000000..57b8385 --- /dev/null +++ b/src/campaigns/campaign.schemas.ts @@ -0,0 +1,49 @@ +import { z } from 'zod'; +import { text } from '../common/input'; +import { groupSchema } from '../catalog/catalog.schemas'; +import { pageSchema } from '../identity/identity.schemas'; + +const timestamp = z.iso + .datetime({ offset: true }) + .transform((value) => new Date(value)); +const fields = { + title: text(160), + summary: text(500, 0), + collectionId: z.uuid(), + startsAt: timestamp, + endsAt: timestamp, +}; +export const campaignCreateSchema = z + .object({ + ...fields, + summary: fields.summary.default(''), + slug: groupSchema.shape.slug, + idempotencyKey: z.uuid(), + }) + .strict() + .refine((value) => value.endsAt > value.startsAt, { + message: 'End must follow start', + path: ['endsAt'], + }); +export const campaignPatchSchema = z + .object(fields) + .partial() + .extend({ + version: z.number().int().min(0).max(2147483647), + }) + .strict() + .refine( + (value) => Object.keys(value).some((key) => key !== 'version'), + 'Provide at least one field', + ); +export const campaignPublicationSchema = z.object({}).strict().default({}); +export const campaignCancellationSchema = z + .object({ reason: text(500, 3) }) + .strict(); +export const campaignQuerySchema = pageSchema + .extend({ state: z.enum(['DRAFT', 'PUBLISHED', 'CANCELLED']).optional() }) + .strict(); +export const campaignSlugSchema = groupSchema.shape.slug; +export type CampaignCreateInput = z.infer; +export type CampaignPatchInput = z.infer; +export type CampaignQuery = z.infer; diff --git a/test/seasonal-campaign-policy.spec.ts b/test/seasonal-campaign-policy.spec.ts new file mode 100644 index 0000000..13dab75 --- /dev/null +++ b/test/seasonal-campaign-policy.spec.ts @@ -0,0 +1,105 @@ +import { randomUUID } from 'node:crypto'; +import { + campaignStatus, + publicCampaignView, +} from '../src/campaigns/campaign-policy'; +import { + campaignCreateSchema, + campaignPatchSchema, +} from '../src/campaigns/campaign.schemas'; + +const startsAt = new Date('2030-10-01T00:00:00.000Z'); +const endsAt = new Date('2030-10-02T00:00:00.000Z'); +const campaign = { state: 'PUBLISHED' as const, startsAt, endsAt }; +const input = { + slug: 'seasonal-gifts', + title: 'Seasonal gifts', + summary: '', + collectionId: randomUUID(), + startsAt: startsAt.toISOString(), + endsAt: endsAt.toISOString(), + idempotencyKey: randomUUID(), +}; + +describe('seasonal campaign contract', () => { + it('includes the start and excludes the end of the live window', () => { + expect(campaignStatus(campaign, new Date(startsAt.getTime() - 1))).toBe( + 'SCHEDULED', + ); + expect(campaignStatus(campaign, startsAt)).toBe('ACTIVE'); + expect(campaignStatus(campaign, new Date(endsAt.getTime() - 1))).toBe( + 'ACTIVE', + ); + expect(campaignStatus(campaign, endsAt)).toBe('ENDED'); + }); + it('keeps drafts and cancelled campaigns private regardless of the clock', () => { + expect(campaignStatus({ ...campaign, state: 'DRAFT' }, startsAt)).toBe( + 'DRAFT', + ); + expect(campaignStatus({ ...campaign, state: 'CANCELLED' }, startsAt)).toBe( + 'CANCELLED', + ); + }); + it('normalizes timezone offsets and rejects collapsed or invalid windows', () => { + const parsed = campaignCreateSchema.parse({ + ...input, + startsAt: '2030-10-01T05:30:00+05:30', + }); + expect(parsed.startsAt.toISOString()).toBe(startsAt.toISOString()); + for (const endsAt of [ + input.startsAt, + '2030-09-30T00:00:00Z', + '2030-10-01T00:00:00.000001Z', + ]) { + expect(campaignCreateSchema.safeParse({ ...input, endsAt }).success).toBe( + false, + ); + } + expect( + campaignCreateSchema.safeParse({ + ...input, + startsAt: '2030-10-01T00:00:00', + }).success, + ).toBe(false); + }); + it('rejects forged lifecycle/ownership fields and empty edits', () => { + for (const fields of [ + { state: 'PUBLISHED' }, + { organizationId: randomUUID() }, + { title: 'Offer' }, + { slug: '../unsafe' }, + ]) + expect( + campaignCreateSchema.safeParse({ ...input, ...fields }).success, + ).toBe(false); + expect(campaignPatchSchema.safeParse({ version: 0 }).success).toBe(false); + expect( + campaignPatchSchema.safeParse({ version: -1, title: 'Offer' }).success, + ).toBe(false); + expect( + campaignPatchSchema.safeParse({ version: 0, title: 'Offer' }).success, + ).toBe(true); + }); + it('allowlists public content without staff identifiers or replay metadata', () => { + const record = { + ...campaign, + id: 'campaign', + slug: 'seasonal-gifts', + title: 'Seasonal gifts', + summary: '', + organizationId: 'private-org', + createdById: 'private-staff', + requestHash: 'private-hash', + collection: { id: 'collection', name: 'Gifts', slug: 'gifts' }, + }; + const result = publicCampaignView(record); + expect(result.collection.id).toBe('collection'); + for (const field of [ + 'state', + 'organizationId', + 'createdById', + 'requestHash', + ]) + expect(result).not.toHaveProperty(field); + }); +});