Merge pull request 'feat/campaign-discounts' (#40) from feat/campaign-discounts into main
continuous-integration/drone/push Build is failing
Details
continuous-integration/drone/push Build is failing
Details
Reviewed-on: #40
This commit is contained in:
commit
6ac37fdea0
|
|
@ -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).
|
||||
|
|
|
|||
|
|
@ -0,0 +1,17 @@
|
|||
# Campaign discounts (Phase 4D)
|
||||
|
||||
Campaign offers reuse existing coupons and exact checkout money rules. A campaign can have one coupon, created while the campaign is a draft. Coupon terms and association are immutable; the existing coupon status endpoint can pause/resume the code. Configure the campaign window first, then its coupon, then publish the updated campaign version.
|
||||
|
||||
`POST /api/v1/coupons` accepts the existing fixed/percentage coupon body plus optional `campaignId` and `campaignVersion`. Both must be supplied together. Linking requires `coupons.manage` and `campaigns.manage`, a draft in the caller's organization, and its current version. The coupon's start/end must fit inside the campaign window. Successful creation increments campaign version atomically, preventing publication of an offer not seen in the staff member's last read. Existing unlinked coupon requests retain their behavior.
|
||||
|
||||
Draft edits must keep the campaign window around its linked coupon. Terms cannot be replaced by another code in this milestone; create a new campaign/code for a different offer. The code remains the coupon creation identity; duplicate code or campaign association returns a conflict. No existing applied migration is edited.
|
||||
|
||||
Public campaign responses gain an optional `offer` with code, currency, kind, fixed amount/percentage basis points, minimum subtotal, and coupon start/end dates. It appears only when both the campaign and coupon are active and within their windows. Usage limits and per-customer eligibility remain authoritative at checkout; published terms do not promise a reservation or remaining use. Internal coupon IDs and usage counts are not public.
|
||||
|
||||
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/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.
|
||||
|
||||
Deploy the additive migration before the application. Existing coupons receive a null campaign link and remain generic. New scoped foreign keys/unique constraints prevent cross-organization or duplicate binding; native guards freeze linked coupon terms and prevent invalid linked campaign rescheduling. Rollback to older code requires disabling campaign-linked coupons first so an older checkout cannot treat them as generic coupons. Preserve rows, order snapshots and audit history. No new dependencies or provider accounts are required.
|
||||
|
|
@ -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
|
||||
|
||||
|
|
|
|||
|
|
@ -29,6 +29,8 @@ model SeasonalCampaign {
|
|||
createdBy User @relation("CampaignCreator", fields: [createdById, organizationId], references: [id, organizationId], onDelete: Restrict)
|
||||
publishedBy User? @relation("CampaignPublisher", fields: [publishedById, organizationId], references: [id, organizationId], onDelete: Restrict)
|
||||
cancelledBy User? @relation("CampaignCanceller", fields: [cancelledById, organizationId], references: [id, organizationId], onDelete: Restrict)
|
||||
coupon Coupon?
|
||||
@@unique([id, organizationId])
|
||||
@@unique([organizationId, slug])
|
||||
@@unique([organizationId, idempotencyKey])
|
||||
@@index([organizationId, state, startsAt, endsAt, id])
|
||||
|
|
|
|||
|
|
@ -31,6 +31,7 @@ model CartLine {
|
|||
model Coupon {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
organizationId String @map("organization_id") @db.Uuid
|
||||
campaignId String? @unique @map("campaign_id") @db.Uuid
|
||||
code String @db.VarChar(40)
|
||||
kind CouponKind
|
||||
currency String @db.Char(3)
|
||||
|
|
@ -44,6 +45,8 @@ model Coupon {
|
|||
active Boolean @default(true)
|
||||
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Restrict)
|
||||
orders Order[]
|
||||
campaign SeasonalCampaign? @relation(fields: [campaignId, organizationId], references: [id, organizationId], onDelete: Restrict)
|
||||
@@unique([campaignId, organizationId])
|
||||
@@unique([organizationId, code])
|
||||
@@unique([id, organizationId])
|
||||
@@map("coupons")
|
||||
|
|
|
|||
|
|
@ -45,5 +45,6 @@
|
|||
"20261004010000_b2b_partner_reporting": "44086ecc27278b9499fbcf5fa97ed754f056fcf49f6b155e1ed377527616dc89",
|
||||
"20261005120000_private_wishlists": "8ded2f27a4e08ea6af3e5ae92f15b832cea66156a7489f28e178d3df6404f5e4",
|
||||
"20261005160000_verified_product_reviews": "1f71f6d49622c48a37c88f2eb7740174cbc9aea7d0027f6fc27d81301d87c757",
|
||||
"20261006120000_seasonal_campaigns": "4f81582f91a8d3cb30bf49051281ca05c862b794925c0643a7237d1a1efb6f40"
|
||||
"20261006120000_seasonal_campaigns": "4f81582f91a8d3cb30bf49051281ca05c862b794925c0643a7237d1a1efb6f40",
|
||||
"20261006160000_campaign_discounts": "99485a5b252f01057dfa6300c567c79586555a76cec5c2dc0d9c3fef9fc61017"
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,52 @@
|
|||
-- AlterTable
|
||||
ALTER TABLE "coupons" ADD COLUMN "campaign_id" UUID;
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "seasonal_campaigns_id_organization_id_key" ON "seasonal_campaigns"("id", "organization_id");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "coupons_campaign_id_key" ON "coupons"("campaign_id");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "coupons_campaign_id_organization_id_key" ON "coupons"("campaign_id", "organization_id");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "coupons" ADD CONSTRAINT "coupons_campaign_id_organization_id_fkey" FOREIGN KEY ("campaign_id", "organization_id") REFERENCES "seasonal_campaigns"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
CREATE FUNCTION guard_campaign_coupon() RETURNS trigger LANGUAGE plpgsql AS $$
|
||||
DECLARE campaign seasonal_campaigns%ROWTYPE;
|
||||
BEGIN
|
||||
IF TG_OP = 'DELETE' THEN
|
||||
IF OLD.campaign_id IS NOT NULL THEN RAISE EXCEPTION 'Campaign coupon association is immutable'; END IF;
|
||||
RETURN OLD;
|
||||
END IF;
|
||||
IF NEW.campaign_id IS NULL THEN RETURN NEW; END IF;
|
||||
SELECT * INTO campaign FROM seasonal_campaigns
|
||||
WHERE id = NEW.campaign_id AND organization_id = NEW.organization_id FOR UPDATE;
|
||||
IF campaign.id IS NULL OR campaign.state <> 'DRAFT' THEN RAISE EXCEPTION 'Coupon requires an organization-scoped draft campaign'; END IF;
|
||||
IF NEW.starts_at < campaign.starts_at OR NEW.ends_at > campaign.ends_at
|
||||
THEN RAISE EXCEPTION 'Coupon dates must fit campaign window'; END IF;
|
||||
RETURN NEW;
|
||||
END;
|
||||
$$;
|
||||
CREATE TRIGGER coupons_campaign_guard BEFORE INSERT OR DELETE ON coupons
|
||||
FOR EACH ROW EXECUTE FUNCTION guard_campaign_coupon();
|
||||
|
||||
CREATE FUNCTION bump_campaign_coupon_version() RETURNS trigger LANGUAGE plpgsql AS $$
|
||||
BEGIN
|
||||
UPDATE seasonal_campaigns SET version = version + 1, updated_at = CURRENT_TIMESTAMP WHERE id = NEW.campaign_id;
|
||||
RETURN NEW;
|
||||
END;
|
||||
$$;
|
||||
CREATE TRIGGER coupons_campaign_version AFTER INSERT ON coupons
|
||||
FOR EACH ROW WHEN (NEW.campaign_id IS NOT NULL) EXECUTE FUNCTION bump_campaign_coupon_version();
|
||||
|
||||
CREATE FUNCTION check_campaign_coupon_window() RETURNS trigger LANGUAGE plpgsql AS $$
|
||||
BEGIN
|
||||
IF EXISTS (SELECT 1 FROM coupons WHERE campaign_id = NEW.id AND (starts_at < NEW.starts_at OR ends_at > NEW.ends_at))
|
||||
THEN RAISE EXCEPTION 'Campaign window must contain its coupon window'; END IF;
|
||||
RETURN NEW;
|
||||
END;
|
||||
$$;
|
||||
CREATE TRIGGER seasonal_campaigns_coupon_window BEFORE UPDATE ON seasonal_campaigns
|
||||
FOR EACH ROW EXECUTE FUNCTION check_campaign_coupon_window();
|
||||
|
|
@ -11,6 +11,7 @@ import {
|
|||
requireCampaignCollection,
|
||||
} from './campaign-lookup';
|
||||
import { campaignStatus } from './campaign-policy';
|
||||
import { assertCampaignCouponWindow } from '../coupons/campaign-coupon-policy';
|
||||
import type {
|
||||
CampaignCreateInput,
|
||||
CampaignPatchInput,
|
||||
|
|
@ -96,6 +97,7 @@ export class CampaignDraftStore {
|
|||
};
|
||||
if (values.endsAt <= values.startsAt)
|
||||
throw new AppError('CAMPAIGN_INVALID_WINDOW');
|
||||
if (campaign.coupon) assertCampaignCouponWindow(values, campaign.coupon);
|
||||
await requireCampaignCollection(
|
||||
tx,
|
||||
actor.organizationId,
|
||||
|
|
|
|||
|
|
@ -1,10 +1,12 @@
|
|||
import { AppError } from '../common/errors/app-error';
|
||||
import type { DatabaseService } from '../database/database.service';
|
||||
import type { Prisma } from '../generated/prisma/client';
|
||||
import { campaignCouponSelect } from '../coupons/campaign-coupon-policy';
|
||||
|
||||
type Db = DatabaseService | Prisma.TransactionClient;
|
||||
export const campaignInclude = {
|
||||
collection: { select: { id: true, name: true, slug: true } },
|
||||
coupon: { select: campaignCouponSelect },
|
||||
} as const;
|
||||
export const eligibleCampaignCollection: Prisma.CatalogGroupWhereInput = {
|
||||
kind: 'COLLECTION',
|
||||
|
|
|
|||
|
|
@ -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,4 +1,19 @@
|
|||
export const CAMPAIGN_ERRORS = {
|
||||
CAMPAIGN_COUPON_EXISTS: [
|
||||
409,
|
||||
'Campaign already has a coupon',
|
||||
'Duplicate campaign coupon association',
|
||||
],
|
||||
CAMPAIGN_COUPON_WINDOW: [
|
||||
400,
|
||||
'Coupon dates must fit inside the campaign window',
|
||||
'Campaign coupon window mismatch',
|
||||
],
|
||||
COUPON_CAMPAIGN_INELIGIBLE: [
|
||||
409,
|
||||
'Campaign coupon is not eligible for this cart',
|
||||
'Campaign coupon scope or lifecycle gate failed',
|
||||
],
|
||||
CAMPAIGN_COLLECTION_EMPTY: [
|
||||
409,
|
||||
'Collection needs a published product with an active variant',
|
||||
|
|
|
|||
|
|
@ -0,0 +1,105 @@
|
|||
import { minor, decimal } from '../checkout/money';
|
||||
import { AppError } from '../common/errors/app-error';
|
||||
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,
|
||||
currency: true,
|
||||
kind: true,
|
||||
amount: true,
|
||||
percentBps: true,
|
||||
minimumSubtotal: true,
|
||||
startsAt: true,
|
||||
endsAt: true,
|
||||
active: true,
|
||||
} as const;
|
||||
export function assertCampaignCouponWindow(
|
||||
campaign: { startsAt: Date; endsAt: Date },
|
||||
coupon: { startsAt: Date; endsAt: Date },
|
||||
) {
|
||||
if (coupon.startsAt < campaign.startsAt || coupon.endsAt > campaign.endsAt)
|
||||
throw new AppError('CAMPAIGN_COUPON_WINDOW');
|
||||
}
|
||||
export type CampaignCouponOffer = Prisma.CouponGetPayload<{
|
||||
select: typeof campaignCouponSelect;
|
||||
}>;
|
||||
|
||||
export type PricedCartLine = { variantId: string; lineTotal: string };
|
||||
export function campaignEligibleSubtotal(
|
||||
lines: readonly PricedCartLine[],
|
||||
eligible: ReadonlySet<string>,
|
||||
) {
|
||||
return lines.reduce(
|
||||
(sum, line) =>
|
||||
sum + (eligible.has(line.variantId) ? minor(line.lineTotal) : 0n),
|
||||
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,13 +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 },
|
||||
},
|
||||
});
|
||||
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,
|
||||
|
|
@ -47,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,
|
||||
|
|
|
|||
|
|
@ -4,6 +4,8 @@ import { couponCode } from '../checkout/checkout.schemas';
|
|||
const amount = z.string().regex(/^(0|[1-9]\d{0,9})\.\d{2}$/);
|
||||
const common = z.object({
|
||||
code: couponCode,
|
||||
campaignId: z.uuid().optional(),
|
||||
campaignVersion: z.number().int().min(0).max(2147483647).optional(),
|
||||
currency: z.enum(CURRENCIES),
|
||||
minimumSubtotal: amount.default('0.00'),
|
||||
maxUses: z.number().int().min(1).max(1000000),
|
||||
|
|
@ -33,6 +35,12 @@ export const couponSchema = z
|
|||
.refine((value) => value.endsAt > value.startsAt, { path: ['endsAt'] })
|
||||
.refine((value) => value.perUserLimit <= value.maxUses, {
|
||||
path: ['perUserLimit'],
|
||||
});
|
||||
})
|
||||
.refine(
|
||||
(value) =>
|
||||
(value.campaignId === undefined) ===
|
||||
(value.campaignVersion === undefined),
|
||||
{ path: ['campaignVersion'] },
|
||||
);
|
||||
export const couponStatusSchema = z.object({ active: z.boolean() }).strict();
|
||||
export type CouponInput = z.infer<typeof couponSchema>;
|
||||
|
|
|
|||
|
|
@ -5,6 +5,11 @@ import type { Principal } from '../identity/identity.types';
|
|||
import { recordAudit } from '../identity/audit';
|
||||
import { AppError } from '../common/errors/app-error';
|
||||
import type { CouponInput } from './coupon.schema';
|
||||
import {
|
||||
requireCampaign,
|
||||
nextCampaignVersion,
|
||||
} from '../campaigns/campaign-lookup';
|
||||
import { assertCampaignCouponWindow } from './campaign-coupon-policy';
|
||||
|
||||
@Injectable()
|
||||
export class CouponStore {
|
||||
|
|
@ -21,9 +26,27 @@ export class CouponStore {
|
|||
});
|
||||
}
|
||||
create(actor: Principal, input: CouponInput) {
|
||||
return this.access.mutate(actor, 'coupons.manage', async (tx) => {
|
||||
const { campaignVersion, ...data } = input;
|
||||
return this.access.mutate(actor, 'coupons.manage', async (tx, current) => {
|
||||
if (input.campaignId) {
|
||||
if (!current.permissions.includes('campaigns.manage'))
|
||||
throw new AppError('ACCESS_DENIED');
|
||||
const campaign = await requireCampaign(
|
||||
tx,
|
||||
actor.organizationId,
|
||||
input.campaignId,
|
||||
);
|
||||
if (campaign.state !== 'DRAFT')
|
||||
throw new AppError('CAMPAIGN_STATE_CONFLICT');
|
||||
if (campaign.version !== campaignVersion)
|
||||
throw new AppError('CAMPAIGN_CHANGED');
|
||||
if (campaign.coupon) throw new AppError('CAMPAIGN_COUPON_EXISTS');
|
||||
assertCampaignCouponWindow(campaign, input);
|
||||
// The insert trigger increments the draft version; check capacity before writing.
|
||||
nextCampaignVersion(campaign.version);
|
||||
}
|
||||
const coupon = await tx.coupon.create({
|
||||
data: { ...input, organizationId: actor.organizationId },
|
||||
data: { ...data, organizationId: actor.organizationId },
|
||||
});
|
||||
await recordAudit(
|
||||
tx,
|
||||
|
|
@ -32,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,150 @@
|
|||
import { randomUUID } from 'node:crypto';
|
||||
import { identityApp, type IdentityApp } from './helpers/identity-app';
|
||||
import { couponInput } from './helpers/checkout';
|
||||
import { secondActor } from './helpers/commerce';
|
||||
|
||||
describe('draft campaign coupon binding', () => {
|
||||
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();
|
||||
});
|
||||
async function draft() {
|
||||
const group = await ctx
|
||||
.api()
|
||||
.post('/api/v1/catalog-groups')
|
||||
.auth(ctx.token, auth)
|
||||
.send({
|
||||
name: 'Campaign collection',
|
||||
slug: 'group-' + randomUUID(),
|
||||
kind: 'COLLECTION',
|
||||
})
|
||||
.expect(201);
|
||||
return (
|
||||
await ctx
|
||||
.api()
|
||||
.post('/api/v1/campaigns')
|
||||
.auth(ctx.token, auth)
|
||||
.send({
|
||||
slug: 'discount-' + randomUUID(),
|
||||
title: 'Collection offer',
|
||||
collectionId: group.body.id,
|
||||
startsAt: new Date(Date.now() - 120000).toISOString(),
|
||||
endsAt: new Date(Date.now() + 7200000).toISOString(),
|
||||
idempotencyKey: randomUUID(),
|
||||
})
|
||||
.expect(201)
|
||||
).body.id as string;
|
||||
}
|
||||
const bind = (campaignId: string, campaignVersion = 0) => ({
|
||||
...couponInput(),
|
||||
campaignId,
|
||||
campaignVersion,
|
||||
});
|
||||
|
||||
it('links one coupon atomically and increments the draft publication version', async () => {
|
||||
const campaignId = await draft();
|
||||
const body = bind(campaignId);
|
||||
const created = await ctx
|
||||
.api()
|
||||
.post('/api/v1/coupons')
|
||||
.auth(ctx.token, auth)
|
||||
.send(body)
|
||||
.expect(201);
|
||||
expect(created.body.campaignId).toBe(campaignId);
|
||||
expect(
|
||||
(
|
||||
await ctx
|
||||
.api()
|
||||
.get(`/api/v1/campaigns/${campaignId}`)
|
||||
.auth(ctx.token, auth)
|
||||
.expect(200)
|
||||
).body.version,
|
||||
).toBe(1);
|
||||
await ctx
|
||||
.api()
|
||||
.post('/api/v1/coupons')
|
||||
.auth(ctx.token, auth)
|
||||
.send(bind(campaignId, 1))
|
||||
.expect(409);
|
||||
expect(await ctx.db.coupon.count({ where: { campaignId } })).toBe(1);
|
||||
await expect(
|
||||
ctx.executeSql(
|
||||
`UPDATE coupons SET percent_bps = 5000 WHERE id = '${created.body.id}'`,
|
||||
),
|
||||
).rejects.toThrow('Create a new coupon');
|
||||
await ctx
|
||||
.api()
|
||||
.patch(`/api/v1/campaigns/${campaignId}`)
|
||||
.auth(ctx.token, auth)
|
||||
.send({ version: 1, endsAt: new Date(Date.now() + 1000).toISOString() })
|
||||
.expect(400);
|
||||
await expect(
|
||||
ctx.executeSql(
|
||||
`UPDATE seasonal_campaigns SET ends_at = starts_at + INTERVAL '1 second', version = version + 1 WHERE id = '${campaignId}'`,
|
||||
),
|
||||
).rejects.toThrow();
|
||||
});
|
||||
|
||||
it('requires both permissions, a current version and an organization-scoped draft', async () => {
|
||||
const campaignId = await draft();
|
||||
const couponsOnly = await secondActor(ctx, true, ['coupons.manage']);
|
||||
await ctx
|
||||
.api()
|
||||
.post('/api/v1/coupons')
|
||||
.auth(couponsOnly.token, auth)
|
||||
.send(bind(campaignId))
|
||||
.expect(403);
|
||||
const outsider = await secondActor(ctx, false, [
|
||||
'coupons.manage',
|
||||
'campaigns.manage',
|
||||
]);
|
||||
await ctx
|
||||
.api()
|
||||
.post('/api/v1/coupons')
|
||||
.auth(outsider.token, auth)
|
||||
.send(bind(campaignId))
|
||||
.expect(404);
|
||||
await ctx
|
||||
.api()
|
||||
.post('/api/v1/coupons')
|
||||
.auth(ctx.token, auth)
|
||||
.send(bind(campaignId, 1))
|
||||
.expect(409);
|
||||
await ctx
|
||||
.api()
|
||||
.post('/api/v1/coupons')
|
||||
.auth(ctx.token, auth)
|
||||
.send({
|
||||
...bind(campaignId),
|
||||
startsAt: new Date(Date.now() - 3600000).toISOString(),
|
||||
})
|
||||
.expect(400);
|
||||
const { campaignVersion: _version, ...missingVersion } = bind(campaignId);
|
||||
await ctx
|
||||
.api()
|
||||
.post('/api/v1/coupons')
|
||||
.auth(ctx.token, auth)
|
||||
.send(missingVersion)
|
||||
.expect(400);
|
||||
const empty = await draft();
|
||||
await ctx
|
||||
.api()
|
||||
.post(`/api/v1/campaigns/${empty}/cancellation`)
|
||||
.auth(ctx.token, auth)
|
||||
.send({ reason: 'Withdraw draft' })
|
||||
.expect(201);
|
||||
await ctx
|
||||
.api()
|
||||
.post('/api/v1/coupons')
|
||||
.auth(ctx.token, auth)
|
||||
.send(bind(empty))
|
||||
.expect(409);
|
||||
});
|
||||
});
|
||||
|
|
@ -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,41 @@
|
|||
import { campaignEligibleSubtotal } from '../src/coupons/campaign-coupon-policy';
|
||||
import { discountFor } from '../src/checkout/money';
|
||||
|
||||
describe('campaign collection discount base', () => {
|
||||
const lines = [
|
||||
{ variantId: 'eligible', lineTotal: '10.10' },
|
||||
{ variantId: 'outside', lineTotal: '89.90' },
|
||||
{ variantId: 'eligible-second', lineTotal: '0.01' },
|
||||
];
|
||||
it('counts only collection merchandise with exact minor-unit precision', () => {
|
||||
expect(
|
||||
campaignEligibleSubtotal(lines, new Set(['eligible', 'eligible-second'])),
|
||||
).toBe(1011n);
|
||||
});
|
||||
it('rounds a percentage on the eligible subtotal rather than the whole cart', () => {
|
||||
const subtotal = campaignEligibleSubtotal(
|
||||
lines,
|
||||
new Set(['eligible', 'eligible-second']),
|
||||
);
|
||||
expect(
|
||||
discountFor(subtotal, {
|
||||
kind: 'PERCENT',
|
||||
amount: null,
|
||||
percentBps: 5000,
|
||||
}),
|
||||
).toBe(506n);
|
||||
});
|
||||
it('caps a fixed discount at the eligible merchandise value', () => {
|
||||
const subtotal = campaignEligibleSubtotal(lines, new Set(['eligible']));
|
||||
expect(
|
||||
discountFor(subtotal, {
|
||||
kind: 'FIXED',
|
||||
amount: '20.00',
|
||||
percentBps: null,
|
||||
}),
|
||||
).toBe(1010n);
|
||||
});
|
||||
it('returns zero when the cart contains no campaign collection variants', () => {
|
||||
expect(campaignEligibleSubtotal(lines, new Set())).toBe(0n);
|
||||
});
|
||||
});
|
||||
|
|
@ -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