feat(discounts): apply campaign offers to eligible collection merchandise
This commit is contained in:
parent
9f12fc686e
commit
7bcce6fe4d
|
|
@ -76,3 +76,5 @@ 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).
|
||||
|
||||
Campaign-linked collection discounts: see [Phase 4D API guide](docs/campaign-discounts-api.md).
|
||||
|
|
|
|||
|
|
@ -10,7 +10,7 @@ Public campaign responses gain an optional `offer` with code, currency, kind, fi
|
|||
|
||||
Customers continue submitting one `couponCode` to the existing checkout endpoint. A linked code additionally requires an active published campaign and a current collection. Only cart variants belonging to that collection contribute to the discount base and minimum-spend test. Other cart lines keep their full price. Percentage rounding and fixed-amount caps use the existing minor-unit arithmetic. No matching lines, draft/future/ended/cancelled campaigns, wrong currency, disabled/expired coupons, and exhausted limits fail before order/stock/cart writes.
|
||||
|
||||
New campaign-coupon order snapshots also retain campaign ID/slug, collection ID, campaign window, and exact eligible subtotal. These facts are frozen alongside coupon/price snapshots. Retrying a successful checkout returns its original order even after campaign cancellation or coupon disablement. New attempts use current eligibility. Order cancellation/expiry retain the existing usage-release behavior. Payment enablement, tax, shipping and gateway behavior do not change.
|
||||
New campaign-coupon order snapshots also retain campaign ID/slug, collection ID, campaign/coupon windows, eligible variant IDs, and exact eligible subtotal. These facts are frozen alongside coupon/price snapshots. Retrying a successful checkout returns its original order even after campaign cancellation or coupon disablement. New attempts use current eligibility. Order cancellation/expiry retain the existing usage-release behavior. Payment enablement, tax, shipping and gateway behavior do not change.
|
||||
|
||||
Acceptance: collection-only discounts in mixed carts; exact fixed/percentage amounts; scoped binding and version checks; window compatibility; public offer privacy; campaign/coupon cancellation gates; coupon quotas; checkout rollback/idempotency; immutable linkage and order evidence; unchanged generic coupons.
|
||||
|
||||
|
|
|
|||
|
|
@ -57,6 +57,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.
|
||||
- 4D (implemented): draft-bound campaign coupons, version-aware offer publication, public offer terms, and collection-only fixed/percentage checkout discounts with exact eligible-subtotal snapshots. Generic coupons retain their behavior; payment enablement, media assets and messaging remain separate milestones.
|
||||
|
||||
## Phase 5: Community and optimization
|
||||
|
||||
|
|
|
|||
|
|
@ -1,3 +1,5 @@
|
|||
import type { CampaignCouponOffer } from '../coupons/campaign-coupon-policy';
|
||||
|
||||
type CampaignTime = {
|
||||
state: 'DRAFT' | 'PUBLISHED' | 'CANCELLED';
|
||||
startsAt: Date;
|
||||
|
|
@ -17,8 +19,28 @@ export function publicCampaignView(
|
|||
title: string;
|
||||
summary: string;
|
||||
collection: { id: string; name: string; slug: string };
|
||||
coupon?: CampaignCouponOffer | null;
|
||||
},
|
||||
now = new Date(),
|
||||
) {
|
||||
const coupon = campaign.coupon;
|
||||
const offer =
|
||||
coupon &&
|
||||
coupon.active &&
|
||||
campaignStatus(campaign, now) === 'ACTIVE' &&
|
||||
coupon.startsAt <= now &&
|
||||
coupon.endsAt > now
|
||||
? {
|
||||
code: coupon.code,
|
||||
currency: coupon.currency,
|
||||
kind: coupon.kind,
|
||||
amount: coupon.amount?.toFixed(2) ?? null,
|
||||
percentBps: coupon.percentBps,
|
||||
minimumSubtotal: coupon.minimumSubtotal.toFixed(2),
|
||||
startsAt: coupon.startsAt,
|
||||
endsAt: coupon.endsAt,
|
||||
}
|
||||
: null;
|
||||
return {
|
||||
id: campaign.id,
|
||||
slug: campaign.slug,
|
||||
|
|
@ -31,5 +53,6 @@ export function publicCampaignView(
|
|||
name: campaign.collection.name,
|
||||
slug: campaign.collection.slug,
|
||||
},
|
||||
...(offer ? { offer } : {}),
|
||||
};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -35,15 +35,16 @@ export class CampaignReadStore {
|
|||
take: page.limit,
|
||||
skip: page.offset,
|
||||
});
|
||||
return campaigns.map(publicCampaignView);
|
||||
return campaigns.map((campaign) => publicCampaignView(campaign, now));
|
||||
}
|
||||
async publicGet(organizationId: string, slug: string) {
|
||||
const now = new Date();
|
||||
const campaign = await this.db.seasonalCampaign.findFirst({
|
||||
where: { ...this.publicWhere(organizationId, new Date()), slug },
|
||||
where: { ...this.publicWhere(organizationId, now), slug },
|
||||
include: campaignInclude,
|
||||
});
|
||||
if (!campaign) throw new AppError('CAMPAIGN_NOT_FOUND');
|
||||
return publicCampaignView(campaign);
|
||||
return publicCampaignView(campaign, now);
|
||||
}
|
||||
async list(actor: Principal, query: CampaignQuery) {
|
||||
const campaigns = await this.db.seasonalCampaign.findMany({
|
||||
|
|
|
|||
|
|
@ -51,13 +51,14 @@ export async function checkoutSnapshot(
|
|||
};
|
||||
});
|
||||
const subtotal = lines.reduce((sum, line) => sum + minor(line.lineTotal), 0n);
|
||||
const { coupon, discount } = await priceCoupon(
|
||||
const { coupon, discount, campaignSnapshot } = await priceCoupon(
|
||||
tx,
|
||||
actor,
|
||||
input.couponCode,
|
||||
currency,
|
||||
subtotal,
|
||||
new Date(),
|
||||
lines,
|
||||
);
|
||||
return {
|
||||
cartId: cart.id,
|
||||
|
|
@ -74,6 +75,7 @@ export async function checkoutSnapshot(
|
|||
amount: coupon.amount?.toString() ?? null,
|
||||
percentBps: coupon.percentBps,
|
||||
minimumSubtotal: coupon.minimumSubtotal.toString(),
|
||||
...(campaignSnapshot ? { campaign: campaignSnapshot } : {}),
|
||||
}
|
||||
: undefined,
|
||||
addressSnapshot: {
|
||||
|
|
|
|||
|
|
@ -1,6 +1,8 @@
|
|||
import { minor } from '../checkout/money';
|
||||
import { minor, decimal } from '../checkout/money';
|
||||
import { AppError } from '../common/errors/app-error';
|
||||
import type { Prisma } from '../generated/prisma/client';
|
||||
import type { Coupon, Prisma } from '../generated/prisma/client';
|
||||
import type { Principal } from '../identity/identity.types';
|
||||
import { campaignStatus } from '../campaigns/campaign-policy';
|
||||
|
||||
export const campaignCouponSelect = {
|
||||
code: true,
|
||||
|
|
@ -35,3 +37,69 @@ export function campaignEligibleSubtotal(
|
|||
0n,
|
||||
);
|
||||
}
|
||||
|
||||
export async function campaignCouponContext(
|
||||
tx: Prisma.TransactionClient,
|
||||
actor: Principal,
|
||||
coupon: Coupon | null,
|
||||
lines: readonly PricedCartLine[],
|
||||
subtotal: bigint,
|
||||
now: Date,
|
||||
) {
|
||||
if (!coupon?.campaignId)
|
||||
return { eligibleSubtotal: subtotal, campaignSnapshot: null };
|
||||
const campaign = await tx.seasonalCampaign.findFirst({
|
||||
where: { id: coupon.campaignId, organizationId: actor.organizationId },
|
||||
select: {
|
||||
id: true,
|
||||
slug: true,
|
||||
collectionId: true,
|
||||
state: true,
|
||||
startsAt: true,
|
||||
endsAt: true,
|
||||
collection: { select: { kind: true } },
|
||||
},
|
||||
});
|
||||
if (
|
||||
!campaign ||
|
||||
campaignStatus(campaign, now) !== 'ACTIVE' ||
|
||||
campaign.collection.kind !== 'COLLECTION'
|
||||
)
|
||||
throw new AppError('COUPON_CAMPAIGN_INELIGIBLE');
|
||||
const variants = await tx.productVariant.findMany({
|
||||
where: {
|
||||
organizationId: actor.organizationId,
|
||||
id: { in: lines.map((line) => line.variantId) },
|
||||
active: true,
|
||||
product: {
|
||||
status: 'PUBLISHED',
|
||||
groups: {
|
||||
some: {
|
||||
groupId: campaign.collectionId,
|
||||
organizationId: actor.organizationId,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
const eligible = new Set(variants.map((variant) => variant.id));
|
||||
const eligibleSubtotal = campaignEligibleSubtotal(lines, eligible);
|
||||
if (eligibleSubtotal === 0n) throw new AppError('COUPON_CAMPAIGN_INELIGIBLE');
|
||||
return {
|
||||
eligibleSubtotal,
|
||||
campaignSnapshot: {
|
||||
id: campaign.id,
|
||||
slug: campaign.slug,
|
||||
collectionId: campaign.collectionId,
|
||||
startsAt: campaign.startsAt.toISOString(),
|
||||
endsAt: campaign.endsAt.toISOString(),
|
||||
couponStartsAt: coupon.startsAt.toISOString(),
|
||||
couponEndsAt: coupon.endsAt.toISOString(),
|
||||
eligibleSubtotal: decimal(eligibleSubtotal),
|
||||
eligibleVariantIds: lines
|
||||
.filter((line) => eligible.has(line.variantId))
|
||||
.map((line) => line.variantId),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2,6 +2,10 @@ import type { Coupon, Prisma } from '../generated/prisma/client';
|
|||
import type { Principal } from '../identity/identity.types';
|
||||
import { AppError } from '../common/errors/app-error';
|
||||
import { minor, discountFor } from '../checkout/money';
|
||||
import {
|
||||
campaignCouponContext,
|
||||
type PricedCartLine,
|
||||
} from './campaign-coupon-policy';
|
||||
|
||||
export function assertCoupon(
|
||||
coupon: Coupon | null,
|
||||
|
|
@ -31,15 +35,22 @@ export async function priceCoupon(
|
|||
currency: string,
|
||||
subtotal: bigint,
|
||||
now: Date,
|
||||
lines: readonly PricedCartLine[] = [],
|
||||
) {
|
||||
if (!code) return { discount: 0n, coupon: null };
|
||||
if (!code) return { discount: 0n, coupon: null, campaignSnapshot: null };
|
||||
const coupon = await tx.coupon.findUnique({
|
||||
where: {
|
||||
organizationId_code: { organizationId: actor.organizationId, code },
|
||||
},
|
||||
});
|
||||
// Linked codes stay fail-closed until collection-aware checkout is enabled.
|
||||
if (coupon?.campaignId) throw new AppError('COUPON_CAMPAIGN_INELIGIBLE');
|
||||
const { eligibleSubtotal, campaignSnapshot } = await campaignCouponContext(
|
||||
tx,
|
||||
actor,
|
||||
coupon,
|
||||
lines,
|
||||
subtotal,
|
||||
now,
|
||||
);
|
||||
const where = {
|
||||
couponId: coupon?.id ?? '00000000-0000-0000-0000-000000000000',
|
||||
status: 'PENDING_PAYMENT' as const,
|
||||
|
|
@ -49,10 +60,11 @@ export async function priceCoupon(
|
|||
const userUses = await tx.order.count({
|
||||
where: { ...where, userId: actor.userId },
|
||||
});
|
||||
assertCoupon(coupon, currency, subtotal, now, uses, userUses);
|
||||
assertCoupon(coupon, currency, eligibleSubtotal, now, uses, userUses);
|
||||
return {
|
||||
coupon,
|
||||
discount: discountFor(subtotal, {
|
||||
campaignSnapshot,
|
||||
discount: discountFor(eligibleSubtotal, {
|
||||
kind: coupon.kind,
|
||||
amount: coupon.amount?.toString() ?? null,
|
||||
percentBps: coupon.percentBps,
|
||||
|
|
|
|||
|
|
@ -55,6 +55,14 @@ export class CouponStore {
|
|||
'coupon.created',
|
||||
coupon.id,
|
||||
);
|
||||
if (input.campaignId)
|
||||
await recordAudit(
|
||||
tx,
|
||||
actor.organizationId,
|
||||
actor.userId,
|
||||
'campaign.coupon.linked',
|
||||
input.campaignId,
|
||||
);
|
||||
return coupon;
|
||||
});
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,193 @@
|
|||
import { randomUUID } from 'node:crypto';
|
||||
import { identityApp, type IdentityApp } from './helpers/identity-app';
|
||||
import { seedStock } from './helpers/commerce';
|
||||
import { campaignDiscountFixture } from './helpers/campaign-discounts';
|
||||
|
||||
describe('campaign collection discounts at checkout', () => {
|
||||
let ctx: IdentityApp;
|
||||
const auth = { type: 'bearer' as const };
|
||||
beforeAll(async () => {
|
||||
ctx = await identityApp(true);
|
||||
}, 60000);
|
||||
afterAll(async () => {
|
||||
await ctx?.close();
|
||||
});
|
||||
beforeEach(async () => {
|
||||
await ctx.clearLimits();
|
||||
});
|
||||
|
||||
it('discounts only eligible lines in a mixed cart and freezes campaign evidence', async () => {
|
||||
const f = await campaignDiscountFixture(ctx);
|
||||
const outside = await seedStock(ctx);
|
||||
await ctx.db.productVariant.update({
|
||||
where: { id: outside.variant.id },
|
||||
data: { price: '100.00' },
|
||||
});
|
||||
await ctx
|
||||
.api()
|
||||
.put(`/api/v1/cart/lines/${outside.variant.id}`)
|
||||
.auth(f.actor.token, auth)
|
||||
.send({ version: 1, quantity: 1 })
|
||||
.expect(200);
|
||||
const input = { ...f.input, cartVersion: 2 };
|
||||
const created = await ctx
|
||||
.api()
|
||||
.post('/api/v1/checkout')
|
||||
.auth(f.actor.token, auth)
|
||||
.send(input)
|
||||
.expect(201);
|
||||
expect(created.body).toMatchObject({
|
||||
subtotal: '1098',
|
||||
discount: '99.8',
|
||||
merchandiseTotal: '998.2',
|
||||
paymentAvailable: false,
|
||||
coupon: {
|
||||
campaign: {
|
||||
id: f.campaignId,
|
||||
collectionId: f.groupId,
|
||||
eligibleSubtotal: '998.00',
|
||||
eligibleVariantIds: [f.variant.id],
|
||||
},
|
||||
},
|
||||
});
|
||||
await ctx
|
||||
.api()
|
||||
.post(`/api/v1/campaigns/${f.campaignId}/cancellation`)
|
||||
.auth(ctx.token, auth)
|
||||
.send({ reason: 'End campaign' })
|
||||
.expect(201);
|
||||
const replay = await ctx
|
||||
.api()
|
||||
.post('/api/v1/checkout')
|
||||
.auth(f.actor.token, auth)
|
||||
.send(input)
|
||||
.expect(201);
|
||||
expect(replay.body).toEqual(created.body);
|
||||
expect(
|
||||
await ctx.db.order.count({ where: { userId: f.actor.userId } }),
|
||||
).toBe(1);
|
||||
});
|
||||
|
||||
it('caps fixed discounts at collection value rather than discounting outside items', async () => {
|
||||
const f = await campaignDiscountFixture(ctx, { fixed: '2000.00' });
|
||||
const outside = await seedStock(ctx);
|
||||
await ctx
|
||||
.api()
|
||||
.put(`/api/v1/cart/lines/${outside.variant.id}`)
|
||||
.auth(f.actor.token, auth)
|
||||
.send({ version: 1, quantity: 1 })
|
||||
.expect(200);
|
||||
const order = await ctx
|
||||
.api()
|
||||
.post('/api/v1/checkout')
|
||||
.auth(f.actor.token, auth)
|
||||
.send({ ...f.input, cartVersion: 2 })
|
||||
.expect(201);
|
||||
expect(order.body).toMatchObject({
|
||||
subtotal: '1497',
|
||||
discount: '998',
|
||||
merchandiseTotal: '499',
|
||||
});
|
||||
});
|
||||
|
||||
it('uses collection subtotal for minimum spend and preserves cart/stock on failure', async () => {
|
||||
const f = await campaignDiscountFixture(ctx, {
|
||||
minimumSubtotal: '1000.00',
|
||||
});
|
||||
const outside = await seedStock(ctx);
|
||||
await ctx
|
||||
.api()
|
||||
.put(`/api/v1/cart/lines/${outside.variant.id}`)
|
||||
.auth(f.actor.token, auth)
|
||||
.send({ version: 1, quantity: 1 })
|
||||
.expect(200);
|
||||
expect(
|
||||
(
|
||||
await ctx
|
||||
.api()
|
||||
.post('/api/v1/checkout')
|
||||
.auth(f.actor.token, auth)
|
||||
.send({ ...f.input, cartVersion: 2 })
|
||||
.expect(409)
|
||||
).body.code,
|
||||
).toBe('COUPON_INELIGIBLE');
|
||||
expect(
|
||||
await ctx.db.order.count({ where: { userId: f.actor.userId } }),
|
||||
).toBe(0);
|
||||
expect(
|
||||
await ctx.db.stockReservation.count({
|
||||
where: { userId: f.actor.userId },
|
||||
}),
|
||||
).toBe(0);
|
||||
expect(
|
||||
await ctx.db.cartLine.count({
|
||||
where: { cart: { userId: f.actor.userId } },
|
||||
}),
|
||||
).toBe(2);
|
||||
});
|
||||
|
||||
it('blocks drafts, cancelled campaigns, and carts no longer in the collection', async () => {
|
||||
for (const mode of ['draft', 'future', 'cancelled', 'removed'] as const) {
|
||||
const f = await campaignDiscountFixture(ctx, {
|
||||
publish: mode !== 'draft',
|
||||
future: mode === 'future',
|
||||
});
|
||||
if (mode === 'cancelled')
|
||||
await ctx
|
||||
.api()
|
||||
.post(`/api/v1/campaigns/${f.campaignId}/cancellation`)
|
||||
.auth(ctx.token, auth)
|
||||
.send({ reason: 'Campaign withdrawn' })
|
||||
.expect(201);
|
||||
if (mode === 'removed')
|
||||
await ctx.db.productGroup.deleteMany({ where: { groupId: f.groupId } });
|
||||
expect(
|
||||
(
|
||||
await ctx
|
||||
.api()
|
||||
.post('/api/v1/checkout')
|
||||
.auth(f.actor.token, auth)
|
||||
.send(f.input)
|
||||
.expect(409)
|
||||
).body.code,
|
||||
).toBe('COUPON_CAMPAIGN_INELIGIBLE');
|
||||
expect(
|
||||
await ctx.db.order.count({ where: { userId: f.actor.userId } }),
|
||||
).toBe(0);
|
||||
}
|
||||
});
|
||||
|
||||
it('preserves coupon limits and releases capacity on order cancellation', async () => {
|
||||
const f = await campaignDiscountFixture(ctx, { maxUses: 1 });
|
||||
const first = await ctx
|
||||
.api()
|
||||
.post('/api/v1/checkout')
|
||||
.auth(f.actor.token, auth)
|
||||
.send(f.input)
|
||||
.expect(201);
|
||||
await ctx
|
||||
.api()
|
||||
.put(`/api/v1/cart/lines/${f.variant.id}`)
|
||||
.auth(f.actor.token, auth)
|
||||
.send({ version: 2, quantity: 1 })
|
||||
.expect(200);
|
||||
const next = { ...f.input, cartVersion: 3, idempotencyKey: randomUUID() };
|
||||
await ctx
|
||||
.api()
|
||||
.post('/api/v1/checkout')
|
||||
.auth(f.actor.token, auth)
|
||||
.send(next)
|
||||
.expect(409);
|
||||
await ctx
|
||||
.api()
|
||||
.post(`/api/v1/orders/${first.body.id}/cancel`)
|
||||
.auth(f.actor.token, auth)
|
||||
.expect(201);
|
||||
await ctx
|
||||
.api()
|
||||
.post('/api/v1/checkout')
|
||||
.auth(f.actor.token, auth)
|
||||
.send(next)
|
||||
.expect(201);
|
||||
});
|
||||
});
|
||||
|
|
@ -0,0 +1,100 @@
|
|||
import { identityApp, type IdentityApp } from './helpers/identity-app';
|
||||
import { campaignDiscountFixture } from './helpers/campaign-discounts';
|
||||
|
||||
describe('public campaign offer terms', () => {
|
||||
let ctx: IdentityApp;
|
||||
const auth = { type: 'bearer' as const };
|
||||
beforeAll(async () => {
|
||||
ctx = await identityApp();
|
||||
}, 60000);
|
||||
afterAll(async () => {
|
||||
await ctx?.close();
|
||||
});
|
||||
beforeEach(async () => {
|
||||
await ctx.clearLimits();
|
||||
});
|
||||
|
||||
it('exposes active offer terms without internal IDs or usage limits', async () => {
|
||||
const f = await campaignDiscountFixture(ctx);
|
||||
const publicRow = (await ctx.api().get(f.publicUrl).expect(200)).body;
|
||||
expect(publicRow.offer).toMatchObject({
|
||||
code: f.coupon.code,
|
||||
kind: 'PERCENT',
|
||||
percentBps: 1000,
|
||||
amount: null,
|
||||
currency: 'INR',
|
||||
minimumSubtotal: '100.00',
|
||||
});
|
||||
for (const field of [
|
||||
'id',
|
||||
'campaignId',
|
||||
'organizationId',
|
||||
'maxUses',
|
||||
'perUserLimit',
|
||||
'active',
|
||||
])
|
||||
expect(publicRow.offer).not.toHaveProperty(field);
|
||||
const rows = (
|
||||
await ctx
|
||||
.api()
|
||||
.get(
|
||||
`/api/v1/storefront/${ctx.owner.organizationId}/campaigns?limit=100`,
|
||||
)
|
||||
.expect(200)
|
||||
).body;
|
||||
expect(
|
||||
rows.find((row: { id: string }) => row.id === f.campaignId).offer.code,
|
||||
).toBe(f.coupon.code);
|
||||
});
|
||||
|
||||
it('suppresses paused offers while retaining collection discovery and blocking new discount use', async () => {
|
||||
const f = await campaignDiscountFixture(ctx, { fixed: '100.00' });
|
||||
expect(
|
||||
(await ctx.api().get(f.publicUrl).expect(200)).body.offer.amount,
|
||||
).toBe('100.00');
|
||||
await ctx
|
||||
.api()
|
||||
.patch(`/api/v1/coupons/${f.coupon.id}/status`)
|
||||
.auth(ctx.token, auth)
|
||||
.send({ active: false })
|
||||
.expect(200);
|
||||
expect(
|
||||
(await ctx.api().get(f.publicUrl).expect(200)).body,
|
||||
).not.toHaveProperty('offer');
|
||||
expect(
|
||||
(
|
||||
await ctx
|
||||
.api()
|
||||
.post('/api/v1/checkout')
|
||||
.auth(f.actor.token, auth)
|
||||
.send(f.input)
|
||||
.expect(409)
|
||||
).body.code,
|
||||
).toBe('COUPON_INELIGIBLE');
|
||||
await ctx
|
||||
.api()
|
||||
.patch(`/api/v1/coupons/${f.coupon.id}/status`)
|
||||
.auth(ctx.token, auth)
|
||||
.send({ active: true })
|
||||
.expect(200);
|
||||
expect((await ctx.api().get(f.publicUrl).expect(200)).body.offer.code).toBe(
|
||||
f.coupon.code,
|
||||
);
|
||||
});
|
||||
|
||||
it('does not advertise a coupon before its own window begins', async () => {
|
||||
const f = await campaignDiscountFixture(ctx, {
|
||||
couponStartsAt: new Date(Date.now() + 1800000).toISOString(),
|
||||
couponEndsAt: new Date(Date.now() + 3600000).toISOString(),
|
||||
});
|
||||
expect(
|
||||
(await ctx.api().get(f.publicUrl).expect(200)).body,
|
||||
).not.toHaveProperty('offer');
|
||||
await ctx
|
||||
.api()
|
||||
.post('/api/v1/checkout')
|
||||
.auth(f.actor.token, auth)
|
||||
.send(f.input)
|
||||
.expect(409);
|
||||
});
|
||||
});
|
||||
|
|
@ -0,0 +1,89 @@
|
|||
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}`,
|
||||
};
|
||||
}
|
||||
Loading…
Reference in New Issue