manicanldes-backend/test/seasonal-campaign-publicati...

253 lines
7.9 KiB
TypeScript

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);
}
});
});