feat(discounts): bind immutable coupons to versioned campaign drafts
This commit is contained in:
parent
8431fbca4b
commit
ceb881e30a
|
|
@ -29,6 +29,8 @@ model SeasonalCampaign {
|
||||||
createdBy User @relation("CampaignCreator", fields: [createdById, organizationId], references: [id, organizationId], onDelete: Restrict)
|
createdBy User @relation("CampaignCreator", fields: [createdById, organizationId], references: [id, organizationId], onDelete: Restrict)
|
||||||
publishedBy User? @relation("CampaignPublisher", fields: [publishedById, 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)
|
cancelledBy User? @relation("CampaignCanceller", fields: [cancelledById, organizationId], references: [id, organizationId], onDelete: Restrict)
|
||||||
|
coupon Coupon?
|
||||||
|
@@unique([id, organizationId])
|
||||||
@@unique([organizationId, slug])
|
@@unique([organizationId, slug])
|
||||||
@@unique([organizationId, idempotencyKey])
|
@@unique([organizationId, idempotencyKey])
|
||||||
@@index([organizationId, state, startsAt, endsAt, id])
|
@@index([organizationId, state, startsAt, endsAt, id])
|
||||||
|
|
|
||||||
|
|
@ -31,6 +31,7 @@ model CartLine {
|
||||||
model Coupon {
|
model Coupon {
|
||||||
id String @id @default(uuid()) @db.Uuid
|
id String @id @default(uuid()) @db.Uuid
|
||||||
organizationId String @map("organization_id") @db.Uuid
|
organizationId String @map("organization_id") @db.Uuid
|
||||||
|
campaignId String? @unique @map("campaign_id") @db.Uuid
|
||||||
code String @db.VarChar(40)
|
code String @db.VarChar(40)
|
||||||
kind CouponKind
|
kind CouponKind
|
||||||
currency String @db.Char(3)
|
currency String @db.Char(3)
|
||||||
|
|
@ -44,6 +45,8 @@ model Coupon {
|
||||||
active Boolean @default(true)
|
active Boolean @default(true)
|
||||||
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Restrict)
|
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Restrict)
|
||||||
orders Order[]
|
orders Order[]
|
||||||
|
campaign SeasonalCampaign? @relation(fields: [campaignId, organizationId], references: [id, organizationId], onDelete: Restrict)
|
||||||
|
@@unique([campaignId, organizationId])
|
||||||
@@unique([organizationId, code])
|
@@unique([organizationId, code])
|
||||||
@@unique([id, organizationId])
|
@@unique([id, organizationId])
|
||||||
@@map("coupons")
|
@@map("coupons")
|
||||||
|
|
|
||||||
|
|
@ -45,5 +45,6 @@
|
||||||
"20261004010000_b2b_partner_reporting": "44086ecc27278b9499fbcf5fa97ed754f056fcf49f6b155e1ed377527616dc89",
|
"20261004010000_b2b_partner_reporting": "44086ecc27278b9499fbcf5fa97ed754f056fcf49f6b155e1ed377527616dc89",
|
||||||
"20261005120000_private_wishlists": "8ded2f27a4e08ea6af3e5ae92f15b832cea66156a7489f28e178d3df6404f5e4",
|
"20261005120000_private_wishlists": "8ded2f27a4e08ea6af3e5ae92f15b832cea66156a7489f28e178d3df6404f5e4",
|
||||||
"20261005160000_verified_product_reviews": "1f71f6d49622c48a37c88f2eb7740174cbc9aea7d0027f6fc27d81301d87c757",
|
"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,
|
requireCampaignCollection,
|
||||||
} from './campaign-lookup';
|
} from './campaign-lookup';
|
||||||
import { campaignStatus } from './campaign-policy';
|
import { campaignStatus } from './campaign-policy';
|
||||||
|
import { assertCampaignCouponWindow } from '../coupons/campaign-coupon-policy';
|
||||||
import type {
|
import type {
|
||||||
CampaignCreateInput,
|
CampaignCreateInput,
|
||||||
CampaignPatchInput,
|
CampaignPatchInput,
|
||||||
|
|
@ -96,6 +97,7 @@ export class CampaignDraftStore {
|
||||||
};
|
};
|
||||||
if (values.endsAt <= values.startsAt)
|
if (values.endsAt <= values.startsAt)
|
||||||
throw new AppError('CAMPAIGN_INVALID_WINDOW');
|
throw new AppError('CAMPAIGN_INVALID_WINDOW');
|
||||||
|
if (campaign.coupon) assertCampaignCouponWindow(values, campaign.coupon);
|
||||||
await requireCampaignCollection(
|
await requireCampaignCollection(
|
||||||
tx,
|
tx,
|
||||||
actor.organizationId,
|
actor.organizationId,
|
||||||
|
|
|
||||||
|
|
@ -1,10 +1,12 @@
|
||||||
import { AppError } from '../common/errors/app-error';
|
import { AppError } from '../common/errors/app-error';
|
||||||
import type { DatabaseService } from '../database/database.service';
|
import type { DatabaseService } from '../database/database.service';
|
||||||
import type { Prisma } from '../generated/prisma/client';
|
import type { Prisma } from '../generated/prisma/client';
|
||||||
|
import { campaignCouponSelect } from '../coupons/campaign-coupon-policy';
|
||||||
|
|
||||||
type Db = DatabaseService | Prisma.TransactionClient;
|
type Db = DatabaseService | Prisma.TransactionClient;
|
||||||
export const campaignInclude = {
|
export const campaignInclude = {
|
||||||
collection: { select: { id: true, name: true, slug: true } },
|
collection: { select: { id: true, name: true, slug: true } },
|
||||||
|
coupon: { select: campaignCouponSelect },
|
||||||
} as const;
|
} as const;
|
||||||
export const eligibleCampaignCollection: Prisma.CatalogGroupWhereInput = {
|
export const eligibleCampaignCollection: Prisma.CatalogGroupWhereInput = {
|
||||||
kind: 'COLLECTION',
|
kind: 'COLLECTION',
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,19 @@
|
||||||
export const CAMPAIGN_ERRORS = {
|
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: [
|
CAMPAIGN_COLLECTION_EMPTY: [
|
||||||
409,
|
409,
|
||||||
'Collection needs a published product with an active variant',
|
'Collection needs a published product with an active variant',
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,28 @@
|
||||||
import { minor } from '../checkout/money';
|
import { minor } from '../checkout/money';
|
||||||
|
import { AppError } from '../common/errors/app-error';
|
||||||
|
import type { Prisma } from '../generated/prisma/client';
|
||||||
|
|
||||||
|
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 type PricedCartLine = { variantId: string; lineTotal: string };
|
||||||
export function campaignEligibleSubtotal(
|
export function campaignEligibleSubtotal(
|
||||||
|
|
|
||||||
|
|
@ -38,6 +38,8 @@ export async function priceCoupon(
|
||||||
organizationId_code: { organizationId: actor.organizationId, code },
|
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 where = {
|
const where = {
|
||||||
couponId: coupon?.id ?? '00000000-0000-0000-0000-000000000000',
|
couponId: coupon?.id ?? '00000000-0000-0000-0000-000000000000',
|
||||||
status: 'PENDING_PAYMENT' as const,
|
status: 'PENDING_PAYMENT' as const,
|
||||||
|
|
|
||||||
|
|
@ -4,6 +4,8 @@ import { couponCode } from '../checkout/checkout.schemas';
|
||||||
const amount = z.string().regex(/^(0|[1-9]\d{0,9})\.\d{2}$/);
|
const amount = z.string().regex(/^(0|[1-9]\d{0,9})\.\d{2}$/);
|
||||||
const common = z.object({
|
const common = z.object({
|
||||||
code: couponCode,
|
code: couponCode,
|
||||||
|
campaignId: z.uuid().optional(),
|
||||||
|
campaignVersion: z.number().int().min(0).max(2147483647).optional(),
|
||||||
currency: z.enum(CURRENCIES),
|
currency: z.enum(CURRENCIES),
|
||||||
minimumSubtotal: amount.default('0.00'),
|
minimumSubtotal: amount.default('0.00'),
|
||||||
maxUses: z.number().int().min(1).max(1000000),
|
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.endsAt > value.startsAt, { path: ['endsAt'] })
|
||||||
.refine((value) => value.perUserLimit <= value.maxUses, {
|
.refine((value) => value.perUserLimit <= value.maxUses, {
|
||||||
path: ['perUserLimit'],
|
path: ['perUserLimit'],
|
||||||
});
|
})
|
||||||
|
.refine(
|
||||||
|
(value) =>
|
||||||
|
(value.campaignId === undefined) ===
|
||||||
|
(value.campaignVersion === undefined),
|
||||||
|
{ path: ['campaignVersion'] },
|
||||||
|
);
|
||||||
export const couponStatusSchema = z.object({ active: z.boolean() }).strict();
|
export const couponStatusSchema = z.object({ active: z.boolean() }).strict();
|
||||||
export type CouponInput = z.infer<typeof couponSchema>;
|
export type CouponInput = z.infer<typeof couponSchema>;
|
||||||
|
|
|
||||||
|
|
@ -5,6 +5,11 @@ import type { Principal } from '../identity/identity.types';
|
||||||
import { recordAudit } from '../identity/audit';
|
import { recordAudit } from '../identity/audit';
|
||||||
import { AppError } from '../common/errors/app-error';
|
import { AppError } from '../common/errors/app-error';
|
||||||
import type { CouponInput } from './coupon.schema';
|
import type { CouponInput } from './coupon.schema';
|
||||||
|
import {
|
||||||
|
requireCampaign,
|
||||||
|
nextCampaignVersion,
|
||||||
|
} from '../campaigns/campaign-lookup';
|
||||||
|
import { assertCampaignCouponWindow } from './campaign-coupon-policy';
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class CouponStore {
|
export class CouponStore {
|
||||||
|
|
@ -21,9 +26,27 @@ export class CouponStore {
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
create(actor: Principal, input: CouponInput) {
|
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({
|
const coupon = await tx.coupon.create({
|
||||||
data: { ...input, organizationId: actor.organizationId },
|
data: { ...data, organizationId: actor.organizationId },
|
||||||
});
|
});
|
||||||
await recordAudit(
|
await recordAudit(
|
||||||
tx,
|
tx,
|
||||||
|
|
|
||||||
|
|
@ -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 = NOW() + 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);
|
||||||
|
});
|
||||||
|
});
|
||||||
Loading…
Reference in New Issue