90 lines
2.6 KiB
TypeScript
90 lines
2.6 KiB
TypeScript
import { randomUUID } from 'node:crypto';
|
|
import type { IdentityApp } from './identity-app';
|
|
import { checkoutFixture, couponInput } from './checkout';
|
|
|
|
export async function campaignDiscountFixture(
|
|
ctx: IdentityApp,
|
|
options: {
|
|
fixed?: string;
|
|
minimumSubtotal?: string;
|
|
maxUses?: number;
|
|
publish?: boolean;
|
|
future?: boolean;
|
|
couponStartsAt?: string;
|
|
couponEndsAt?: string;
|
|
} = {},
|
|
) {
|
|
const auth = { type: 'bearer' as const };
|
|
const checkout = await checkoutFixture(ctx);
|
|
const group = await ctx
|
|
.api()
|
|
.post('/api/v1/catalog-groups')
|
|
.auth(ctx.token, auth)
|
|
.send({
|
|
name: 'Offer collection',
|
|
slug: 'offer-' + randomUUID(),
|
|
kind: 'COLLECTION',
|
|
})
|
|
.expect(201);
|
|
await ctx.db.productGroup.create({
|
|
data: {
|
|
organizationId: ctx.owner.organizationId,
|
|
productId: checkout.product.id,
|
|
groupId: group.body.id,
|
|
},
|
|
});
|
|
const campaign = await ctx
|
|
.api()
|
|
.post('/api/v1/campaigns')
|
|
.auth(ctx.token, auth)
|
|
.send({
|
|
slug: 'sale-' + randomUUID(),
|
|
title: 'Collection offer',
|
|
collectionId: group.body.id,
|
|
startsAt: new Date(
|
|
Date.now() + (options.future ? 60000 : -120000),
|
|
).toISOString(),
|
|
endsAt: new Date(Date.now() + 7200000).toISOString(),
|
|
idempotencyKey: randomUUID(),
|
|
})
|
|
.expect(201);
|
|
const base = couponInput();
|
|
const { percentBps, ...fixed } = base;
|
|
const couponBody = {
|
|
...(options.fixed
|
|
? { ...fixed, kind: 'FIXED', amount: options.fixed }
|
|
: { ...base, percentBps }),
|
|
minimumSubtotal: options.minimumSubtotal ?? base.minimumSubtotal,
|
|
maxUses: options.maxUses ?? base.maxUses,
|
|
startsAt:
|
|
options.couponStartsAt ??
|
|
(options.future
|
|
? new Date(Date.now() + 120000).toISOString()
|
|
: base.startsAt),
|
|
endsAt: options.couponEndsAt ?? base.endsAt,
|
|
campaignId: campaign.body.id as string,
|
|
campaignVersion: 0,
|
|
};
|
|
const coupon = await ctx
|
|
.api()
|
|
.post('/api/v1/coupons')
|
|
.auth(ctx.token, auth)
|
|
.send(couponBody)
|
|
.expect(201);
|
|
if (options.publish !== false)
|
|
await ctx
|
|
.api()
|
|
.post(`/api/v1/campaigns/${campaign.body.id}/publication`)
|
|
.auth(ctx.token, auth)
|
|
.send({ version: 1 })
|
|
.expect(201);
|
|
return {
|
|
...checkout,
|
|
campaignId: campaign.body.id as string,
|
|
groupId: group.body.id as string,
|
|
coupon: coupon.body as { id: string; code: string },
|
|
input: { ...checkout.input, couponCode: coupon.body.code as string },
|
|
publicUrl: `/api/v1/storefront/${ctx.owner.organizationId}/campaigns/${campaign.body.slug}`,
|
|
};
|
|
}
|