Compare commits
No commits in common. "55e00986bd2cc646d78ecb11301bb8a80792d4b0" and "7849be81934905abbf663c1864252227b824e1b3" have entirely different histories.
55e00986bd
...
7849be8193
|
|
@ -74,5 +74,3 @@ B2B partner reports: see [Phase 3J API guide](docs/b2b-partner-reporting-api.md)
|
||||||
Private wishlists: see [Phase 4A API guide](docs/wishlist-api.md).
|
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).
|
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).
|
|
||||||
|
|
|
||||||
|
|
@ -56,7 +56,6 @@ 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.
|
- 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.
|
- 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.
|
|
||||||
|
|
||||||
## Phase 5: Community and optimization
|
## Phase 5: Community and optimization
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,32 +0,0 @@
|
||||||
# Seasonal campaigns (Phase 4C)
|
|
||||||
|
|
||||||
Seasonal campaigns promote existing catalog collections during an explicit time window. They contain public title/summary copy and a collection link. Collection membership remains live; checkout prices and coupon eligibility continue to use the existing commerce rules.
|
|
||||||
|
|
||||||
| Method | Path under `/api/v1` | Access |
|
|
||||||
| ------ | --------------------------------------------- | --------------------------------------------------------------------- |
|
|
||||||
| GET | `/campaigns` | `campaigns.read`; optional persisted `state` filter |
|
|
||||||
| GET | `/campaigns/:id` | `campaigns.read`; scoped campaign and live status |
|
|
||||||
| POST | `/campaigns` | `campaigns.manage`; create draft with a reusable UUID idempotency key |
|
|
||||||
| PATCH | `/campaigns/:id` | `campaigns.manage`; edit draft with its current version |
|
|
||||||
| POST | `/campaigns/:id/publication` | `campaigns.manage`; publish/schedule the specified draft version |
|
|
||||||
| POST | `/campaigns/:id/cancellation` | `campaigns.manage`; cancel with a reason |
|
|
||||||
| GET | `/storefront/:organizationId/campaigns` | Public; active campaigns only |
|
|
||||||
| GET | `/storefront/:organizationId/campaigns/:slug` | Public; active campaign by slug |
|
|
||||||
|
|
||||||
Lists use the existing `limit` (1–100, default 25) and `offset` (0–10,000, default 0) contract. Staff resources are organization-scoped. Public routes share the existing storefront rate limit.
|
|
||||||
|
|
||||||
Create body: `slug` (existing collection slug format, at most 100 characters), `title` (1–160), `summary` (0–500; default empty), `collectionId` (UUID), `startsAt`, `endsAt`, and `idempotencyKey` (UUID). Times must be ISO timestamps with a timezone/UTC offset and are normalized to UTC milliseconds; end must be after start at that precision. Unknown fields and HTML/control characters in copy are rejected.
|
|
||||||
|
|
||||||
PATCH takes the current integer `version` plus one or more of `title`, `summary`, `collectionId`, `startsAt`, or `endsAt`. Slug and original creation identity are fixed. A stale version returns 409; callers should refetch after an ambiguous timeout before deciding whether to retry. A patch that changes no values leaves version and audit history unchanged. Actual changes increment version.
|
|
||||||
|
|
||||||
Persisted `state` is `DRAFT`, `PUBLISHED`, or `CANCELLED`. Staff responses also include computed `status`: `DRAFT`, `SCHEDULED`, `ACTIVE`, `ENDED`, or `CANCELLED`. Status describes the lifecycle/time window; public visibility additionally requires an eligible collection. Active visibility uses `startsAt <= now < endsAt`; it requires no scheduler, worker, or cron job. Publication requires an unexpired end time and a collection in the caller's organization containing at least one published product with an active variant.
|
|
||||||
|
|
||||||
Publication body is `{ "version": 0 }`, using the draft version just read. A stale version returns 409. Published campaign terms cannot be edited. Repeating the original publication version returns its current representation without another audit event; a different version conflicts. Cancelled campaigns cannot be published. Cancellation body is `{ "reason": "Campaign withdrawn" }` (3–500 characters). Cancellation applies to drafts and published campaigns; repeating the same reason returns the current record, while a conflicting reason returns 409. Cancellation metadata is immutable. No hard-delete endpoint exists.
|
|
||||||
|
|
||||||
Public responses include only campaign ID, slug, title, summary, UTC start/end, and collection ID/name/slug. Drafts, future, expired, and cancelled campaigns are absent. Changing a linked group to a category or removing all eligible products also hides the campaign. An inactive or unknown public slug returns 404. Public collection links can use the existing storefront product list with `groupId`.
|
|
||||||
|
|
||||||
Creation keys are organization-scoped and retained with the campaign. Identical retries return the current representation; different original content using the same key returns 409. Unique slugs are organization-scoped. All actual writes record audit events within the existing transaction/organization lock. Inputs derive organization and staff identity from the bearer session.
|
|
||||||
|
|
||||||
Acceptance: private drafts; exact start/end boundaries; versioned edits; immutable published terms; repeatable publication/cancellation; scoped permissions/collections; dynamic collection suppression; public-field allowlist; preserved checkout behavior. Verify with `pnpm check` and `pnpm db:test`, plus focused Jest campaign tests. Implementation lives in `src/campaigns`, tests in `test`, and the additive migration in `prisma/migrations`.
|
|
||||||
|
|
||||||
Deploy the migration before the application. It adds one campaign table, scoped foreign keys, unique/index/time constraints, and lifecycle guards, and grants `campaigns.read`/`campaigns.manage` to existing system Owner roles. Custom roles require explicit grants. Rollback can redeploy the previous application while retaining the new table and audit history. This milestone provides collection discovery; campaign discounts, media assets, outbound messaging, and channel integrations are separate work.
|
|
||||||
|
|
@ -1,37 +0,0 @@
|
||||||
enum CampaignState {
|
|
||||||
DRAFT
|
|
||||||
PUBLISHED
|
|
||||||
CANCELLED
|
|
||||||
}
|
|
||||||
|
|
||||||
model SeasonalCampaign {
|
|
||||||
id String @id @default(uuid()) @db.Uuid
|
|
||||||
organizationId String @map("organization_id") @db.Uuid
|
|
||||||
collectionId String @map("collection_id") @db.Uuid
|
|
||||||
createdById String @map("created_by_id") @db.Uuid
|
|
||||||
slug String @db.VarChar(100)
|
|
||||||
title String @db.VarChar(160)
|
|
||||||
summary String @default("") @db.VarChar(500)
|
|
||||||
startsAt DateTime @map("starts_at") @db.Timestamptz(3)
|
|
||||||
endsAt DateTime @map("ends_at") @db.Timestamptz(3)
|
|
||||||
state CampaignState @default(DRAFT)
|
|
||||||
version Int @default(0)
|
|
||||||
idempotencyKey String @map("idempotency_key") @db.Uuid
|
|
||||||
requestHash String @map("request_hash") @db.Char(64)
|
|
||||||
publishedById String? @map("published_by_id") @db.Uuid
|
|
||||||
publishedAt DateTime? @map("published_at") @db.Timestamptz(3)
|
|
||||||
cancelledById String? @map("cancelled_by_id") @db.Uuid
|
|
||||||
cancelledAt DateTime? @map("cancelled_at") @db.Timestamptz(3)
|
|
||||||
cancellationReason String? @map("cancellation_reason") @db.VarChar(500)
|
|
||||||
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3)
|
|
||||||
updatedAt DateTime @updatedAt @map("updated_at") @db.Timestamptz(3)
|
|
||||||
collection CatalogGroup @relation(fields: [collectionId, 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)
|
|
||||||
cancelledBy User? @relation("CampaignCanceller", fields: [cancelledById, organizationId], references: [id, organizationId], onDelete: Restrict)
|
|
||||||
@@unique([organizationId, slug])
|
|
||||||
@@unique([organizationId, idempotencyKey])
|
|
||||||
@@index([organizationId, state, startsAt, endsAt, id])
|
|
||||||
@@index([organizationId, createdAt, id])
|
|
||||||
@@map("seasonal_campaigns")
|
|
||||||
}
|
|
||||||
|
|
@ -52,7 +52,6 @@ model ProductVariant {
|
||||||
@@map("product_variants")
|
@@map("product_variants")
|
||||||
}
|
}
|
||||||
model CatalogGroup {
|
model CatalogGroup {
|
||||||
seasonalCampaigns SeasonalCampaign[]
|
|
||||||
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
|
||||||
name String @db.VarChar(100)
|
name String @db.VarChar(100)
|
||||||
|
|
|
||||||
|
|
@ -44,6 +44,5 @@
|
||||||
"20261004003000_b2b_custom_candle_requests": "ab78d0a7e214ab226e042f29b42e961ddbae3a3e338fd65983d5aa87e2c736ac",
|
"20261004003000_b2b_custom_candle_requests": "ab78d0a7e214ab226e042f29b42e961ddbae3a3e338fd65983d5aa87e2c736ac",
|
||||||
"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"
|
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,104 +0,0 @@
|
||||||
-- CreateEnum
|
|
||||||
CREATE TYPE "CampaignState" AS ENUM ('DRAFT', 'PUBLISHED', 'CANCELLED');
|
|
||||||
|
|
||||||
-- CreateTable
|
|
||||||
CREATE TABLE "seasonal_campaigns" (
|
|
||||||
"id" UUID NOT NULL,
|
|
||||||
"organization_id" UUID NOT NULL,
|
|
||||||
"collection_id" UUID NOT NULL,
|
|
||||||
"created_by_id" UUID NOT NULL,
|
|
||||||
"slug" VARCHAR(100) NOT NULL,
|
|
||||||
"title" VARCHAR(160) NOT NULL,
|
|
||||||
"summary" VARCHAR(500) NOT NULL DEFAULT '',
|
|
||||||
"starts_at" TIMESTAMPTZ(3) NOT NULL,
|
|
||||||
"ends_at" TIMESTAMPTZ(3) NOT NULL,
|
|
||||||
"state" "CampaignState" NOT NULL DEFAULT 'DRAFT',
|
|
||||||
"version" INTEGER NOT NULL DEFAULT 0,
|
|
||||||
"idempotency_key" UUID NOT NULL,
|
|
||||||
"request_hash" CHAR(64) NOT NULL,
|
|
||||||
"published_by_id" UUID,
|
|
||||||
"published_at" TIMESTAMPTZ(3),
|
|
||||||
"cancelled_by_id" UUID,
|
|
||||||
"cancelled_at" TIMESTAMPTZ(3),
|
|
||||||
"cancellation_reason" VARCHAR(500),
|
|
||||||
"created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
|
||||||
"updated_at" TIMESTAMPTZ(3) NOT NULL,
|
|
||||||
|
|
||||||
CONSTRAINT "seasonal_campaigns_pkey" PRIMARY KEY ("id")
|
|
||||||
);
|
|
||||||
|
|
||||||
-- CreateIndex
|
|
||||||
CREATE INDEX "seasonal_campaigns_organization_id_state_starts_at_ends_at__idx" ON "seasonal_campaigns"("organization_id", "state", "starts_at", "ends_at", "id");
|
|
||||||
|
|
||||||
-- CreateIndex
|
|
||||||
CREATE INDEX "seasonal_campaigns_organization_id_created_at_id_idx" ON "seasonal_campaigns"("organization_id", "created_at", "id");
|
|
||||||
|
|
||||||
-- CreateIndex
|
|
||||||
CREATE UNIQUE INDEX "seasonal_campaigns_organization_id_slug_key" ON "seasonal_campaigns"("organization_id", "slug");
|
|
||||||
|
|
||||||
-- CreateIndex
|
|
||||||
CREATE UNIQUE INDEX "seasonal_campaigns_organization_id_idempotency_key_key" ON "seasonal_campaigns"("organization_id", "idempotency_key");
|
|
||||||
|
|
||||||
-- AddForeignKey
|
|
||||||
ALTER TABLE "seasonal_campaigns" ADD CONSTRAINT "seasonal_campaigns_collection_id_organization_id_fkey" FOREIGN KEY ("collection_id", "organization_id") REFERENCES "catalog_groups"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
|
||||||
|
|
||||||
-- AddForeignKey
|
|
||||||
ALTER TABLE "seasonal_campaigns" ADD CONSTRAINT "seasonal_campaigns_created_by_id_organization_id_fkey" FOREIGN KEY ("created_by_id", "organization_id") REFERENCES "users"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
|
||||||
|
|
||||||
-- AddForeignKey
|
|
||||||
ALTER TABLE "seasonal_campaigns" ADD CONSTRAINT "seasonal_campaigns_published_by_id_organization_id_fkey" FOREIGN KEY ("published_by_id", "organization_id") REFERENCES "users"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
|
||||||
|
|
||||||
-- AddForeignKey
|
|
||||||
ALTER TABLE "seasonal_campaigns" ADD CONSTRAINT "seasonal_campaigns_cancelled_by_id_organization_id_fkey" FOREIGN KEY ("cancelled_by_id", "organization_id") REFERENCES "users"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
|
||||||
|
|
||||||
ALTER TABLE seasonal_campaigns
|
|
||||||
ADD CONSTRAINT campaign_window CHECK (ends_at > starts_at),
|
|
||||||
ADD CONSTRAINT campaign_version CHECK (version >= 0),
|
|
||||||
ADD CONSTRAINT campaign_slug CHECK (slug ~ '^[a-z0-9]+(-[a-z0-9]+)*$'),
|
|
||||||
ADD CONSTRAINT campaign_title CHECK (char_length(btrim(title)) >= 1),
|
|
||||||
ADD CONSTRAINT campaign_hash CHECK (request_hash ~ '^[a-f0-9]{64}$'),
|
|
||||||
ADD CONSTRAINT campaign_publication_fields CHECK ((published_at IS NULL) = (published_by_id IS NULL)),
|
|
||||||
ADD CONSTRAINT campaign_cancellation_fields CHECK (
|
|
||||||
(state <> 'CANCELLED' AND cancelled_at IS NULL AND cancelled_by_id IS NULL AND cancellation_reason IS NULL)
|
|
||||||
OR (state = 'CANCELLED' AND cancelled_at IS NOT NULL AND cancelled_by_id IS NOT NULL AND cancellation_reason IS NOT NULL AND char_length(btrim(cancellation_reason)) >= 3)),
|
|
||||||
ADD CONSTRAINT campaign_state_fields CHECK (
|
|
||||||
(state = 'DRAFT' AND published_at IS NULL)
|
|
||||||
OR (state = 'PUBLISHED' AND published_at IS NOT NULL)
|
|
||||||
OR state = 'CANCELLED');
|
|
||||||
|
|
||||||
CREATE FUNCTION guard_seasonal_campaign() RETURNS trigger LANGUAGE plpgsql AS $$
|
|
||||||
BEGIN
|
|
||||||
IF TG_OP = 'DELETE' THEN RAISE EXCEPTION 'Campaigns cannot be deleted'; END IF;
|
|
||||||
IF TG_OP = 'INSERT' THEN
|
|
||||||
IF NEW.state <> 'DRAFT' OR NEW.version <> 0 THEN RAISE EXCEPTION 'Campaigns must start as drafts'; END IF;
|
|
||||||
RETURN NEW;
|
|
||||||
END IF;
|
|
||||||
IF (NEW.id, NEW.organization_id, NEW.created_by_id, NEW.slug, NEW.idempotency_key, NEW.request_hash, NEW.created_at)
|
|
||||||
IS DISTINCT FROM (OLD.id, OLD.organization_id, OLD.created_by_id, OLD.slug, OLD.idempotency_key, OLD.request_hash, OLD.created_at)
|
|
||||||
THEN RAISE EXCEPTION 'Campaign identity is immutable'; END IF;
|
|
||||||
IF OLD.state = 'CANCELLED' THEN RAISE EXCEPTION 'Cancelled campaigns are immutable'; END IF;
|
|
||||||
IF NEW.version <> OLD.version + 1 THEN RAISE EXCEPTION 'Campaign update requires next version'; END IF;
|
|
||||||
IF OLD.state <> 'DRAFT' OR NEW.state <> 'DRAFT' THEN
|
|
||||||
IF (NEW.title, NEW.summary, NEW.collection_id, NEW.starts_at, NEW.ends_at)
|
|
||||||
IS DISTINCT FROM (OLD.title, OLD.summary, OLD.collection_id, OLD.starts_at, OLD.ends_at)
|
|
||||||
THEN RAISE EXCEPTION 'Published campaign terms are immutable'; END IF;
|
|
||||||
END IF;
|
|
||||||
IF OLD.state = 'DRAFT' AND NEW.state = 'DRAFT' THEN RETURN NEW; END IF;
|
|
||||||
IF OLD.state = 'DRAFT' AND NEW.state = 'PUBLISHED' THEN
|
|
||||||
IF NEW.published_at IS NULL OR NEW.published_by_id IS NULL OR NEW.ends_at <= NEW.published_at
|
|
||||||
THEN RAISE EXCEPTION 'Publication requires unexpired terms and staff metadata'; END IF;
|
|
||||||
RETURN NEW;
|
|
||||||
END IF;
|
|
||||||
IF NEW.state = 'CANCELLED' THEN
|
|
||||||
IF (NEW.published_at, NEW.published_by_id) IS DISTINCT FROM (OLD.published_at, OLD.published_by_id)
|
|
||||||
THEN RAISE EXCEPTION 'Publication metadata is immutable'; END IF;
|
|
||||||
RETURN NEW;
|
|
||||||
END IF;
|
|
||||||
RAISE EXCEPTION 'Invalid campaign transition';
|
|
||||||
END;
|
|
||||||
$$;
|
|
||||||
CREATE TRIGGER seasonal_campaigns_guard BEFORE INSERT OR UPDATE OR DELETE ON seasonal_campaigns
|
|
||||||
FOR EACH ROW EXECUTE FUNCTION guard_seasonal_campaign();
|
|
||||||
|
|
||||||
UPDATE roles SET permissions = ARRAY(SELECT DISTINCT unnest(permissions || ARRAY['campaigns.read', 'campaigns.manage']))
|
|
||||||
WHERE is_system = true AND name = 'Owner';
|
|
||||||
|
|
@ -94,9 +94,6 @@ model User {
|
||||||
reviewVerifications ReviewPurchaseVerification[] @relation("ReviewVerifier")
|
reviewVerifications ReviewPurchaseVerification[] @relation("ReviewVerifier")
|
||||||
reviewRevocations ReviewPurchaseRevocation[]
|
reviewRevocations ReviewPurchaseRevocation[]
|
||||||
reviewModerations ProductReviewModeration[]
|
reviewModerations ProductReviewModeration[]
|
||||||
campaignsCreated SeasonalCampaign[] @relation("CampaignCreator")
|
|
||||||
campaignsPublished SeasonalCampaign[] @relation("CampaignPublisher")
|
|
||||||
campaignsCancelled SeasonalCampaign[] @relation("CampaignCanceller")
|
|
||||||
purchaseOrders PurchaseOrder[]
|
purchaseOrders PurchaseOrder[]
|
||||||
goodsReceipts GoodsReceipt[]
|
goodsReceipts GoodsReceipt[]
|
||||||
receiptInspections ReceiptInspection[]
|
receiptInspections ReceiptInspection[]
|
||||||
|
|
|
||||||
|
|
@ -13,11 +13,9 @@ import { HealthModule } from './health/health.module';
|
||||||
import { B2bModule } from './b2b/b2b.module';
|
import { B2bModule } from './b2b/b2b.module';
|
||||||
import { WishlistModule } from './wishlist/wishlist.module';
|
import { WishlistModule } from './wishlist/wishlist.module';
|
||||||
import { ReviewsModule } from './reviews/reviews.module';
|
import { ReviewsModule } from './reviews/reviews.module';
|
||||||
import { CampaignsModule } from './campaigns/campaigns.module';
|
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [
|
imports: [
|
||||||
CampaignsModule,
|
|
||||||
ReviewsModule,
|
ReviewsModule,
|
||||||
WishlistModule,
|
WishlistModule,
|
||||||
EnvironmentModule,
|
EnvironmentModule,
|
||||||
|
|
|
||||||
|
|
@ -1,127 +0,0 @@
|
||||||
import { Injectable } from '@nestjs/common';
|
|
||||||
import { AccessStore } from '../identity/access.store';
|
|
||||||
import { AppError } from '../common/errors/app-error';
|
|
||||||
import { commandHash } from '../common/idempotency';
|
|
||||||
import { recordAudit } from '../identity/audit';
|
|
||||||
import type { Principal } from '../identity/identity.types';
|
|
||||||
import {
|
|
||||||
campaignInclude,
|
|
||||||
nextCampaignVersion,
|
|
||||||
requireCampaign,
|
|
||||||
requireCampaignCollection,
|
|
||||||
} from './campaign-lookup';
|
|
||||||
import { campaignStatus } from './campaign-policy';
|
|
||||||
import type {
|
|
||||||
CampaignCreateInput,
|
|
||||||
CampaignPatchInput,
|
|
||||||
} from './campaign.schemas';
|
|
||||||
|
|
||||||
@Injectable()
|
|
||||||
export class CampaignDraftStore {
|
|
||||||
constructor(private readonly access: AccessStore) {}
|
|
||||||
|
|
||||||
create(actor: Principal, input: CampaignCreateInput) {
|
|
||||||
const hash = commandHash(
|
|
||||||
input.slug,
|
|
||||||
input.title,
|
|
||||||
input.summary,
|
|
||||||
input.collectionId,
|
|
||||||
input.startsAt.toISOString(),
|
|
||||||
input.endsAt.toISOString(),
|
|
||||||
);
|
|
||||||
return this.access.mutate(actor, 'campaigns.manage', async (tx) => {
|
|
||||||
const replay = await tx.seasonalCampaign.findUnique({
|
|
||||||
where: {
|
|
||||||
organizationId_idempotencyKey: {
|
|
||||||
organizationId: actor.organizationId,
|
|
||||||
idempotencyKey: input.idempotencyKey,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
include: campaignInclude,
|
|
||||||
});
|
|
||||||
if (replay) {
|
|
||||||
if (replay.requestHash !== hash)
|
|
||||||
throw new AppError('CAMPAIGN_REPLAY_CONFLICT');
|
|
||||||
return { ...replay, status: campaignStatus(replay) };
|
|
||||||
}
|
|
||||||
await requireCampaignCollection(
|
|
||||||
tx,
|
|
||||||
actor.organizationId,
|
|
||||||
input.collectionId,
|
|
||||||
);
|
|
||||||
if (
|
|
||||||
await tx.seasonalCampaign.findUnique({
|
|
||||||
where: {
|
|
||||||
organizationId_slug: {
|
|
||||||
organizationId: actor.organizationId,
|
|
||||||
slug: input.slug,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
})
|
|
||||||
)
|
|
||||||
throw new AppError('CAMPAIGN_SLUG_EXISTS');
|
|
||||||
const campaign = await tx.seasonalCampaign.create({
|
|
||||||
data: {
|
|
||||||
...input,
|
|
||||||
organizationId: actor.organizationId,
|
|
||||||
createdById: actor.userId,
|
|
||||||
requestHash: hash,
|
|
||||||
},
|
|
||||||
include: campaignInclude,
|
|
||||||
});
|
|
||||||
await recordAudit(
|
|
||||||
tx,
|
|
||||||
actor.organizationId,
|
|
||||||
actor.userId,
|
|
||||||
'campaign.created',
|
|
||||||
campaign.id,
|
|
||||||
);
|
|
||||||
return { ...campaign, status: campaignStatus(campaign) };
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
edit(actor: Principal, id: string, input: CampaignPatchInput) {
|
|
||||||
return this.access.mutate(actor, 'campaigns.manage', async (tx) => {
|
|
||||||
const campaign = await requireCampaign(tx, actor.organizationId, id);
|
|
||||||
if (campaign.state !== 'DRAFT')
|
|
||||||
throw new AppError('CAMPAIGN_STATE_CONFLICT');
|
|
||||||
if (campaign.version !== input.version)
|
|
||||||
throw new AppError('CAMPAIGN_CHANGED');
|
|
||||||
const values = {
|
|
||||||
title: input.title ?? campaign.title,
|
|
||||||
summary: input.summary ?? campaign.summary,
|
|
||||||
collectionId: input.collectionId ?? campaign.collectionId,
|
|
||||||
startsAt: input.startsAt ?? campaign.startsAt,
|
|
||||||
endsAt: input.endsAt ?? campaign.endsAt,
|
|
||||||
};
|
|
||||||
if (values.endsAt <= values.startsAt)
|
|
||||||
throw new AppError('CAMPAIGN_INVALID_WINDOW');
|
|
||||||
await requireCampaignCollection(
|
|
||||||
tx,
|
|
||||||
actor.organizationId,
|
|
||||||
values.collectionId,
|
|
||||||
);
|
|
||||||
if (
|
|
||||||
values.title === campaign.title &&
|
|
||||||
values.summary === campaign.summary &&
|
|
||||||
values.collectionId === campaign.collectionId &&
|
|
||||||
values.startsAt.getTime() === campaign.startsAt.getTime() &&
|
|
||||||
values.endsAt.getTime() === campaign.endsAt.getTime()
|
|
||||||
)
|
|
||||||
return { ...campaign, status: campaignStatus(campaign) };
|
|
||||||
const updated = await tx.seasonalCampaign.update({
|
|
||||||
where: { id },
|
|
||||||
data: { ...values, version: nextCampaignVersion(campaign.version) },
|
|
||||||
include: campaignInclude,
|
|
||||||
});
|
|
||||||
await recordAudit(
|
|
||||||
tx,
|
|
||||||
actor.organizationId,
|
|
||||||
actor.userId,
|
|
||||||
'campaign.updated',
|
|
||||||
id,
|
|
||||||
);
|
|
||||||
return { ...updated, status: campaignStatus(updated) };
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,92 +0,0 @@
|
||||||
import { Injectable } from '@nestjs/common';
|
|
||||||
import { AccessStore } from '../identity/access.store';
|
|
||||||
import { AppError } from '../common/errors/app-error';
|
|
||||||
import { recordAudit } from '../identity/audit';
|
|
||||||
import type { Principal } from '../identity/identity.types';
|
|
||||||
import {
|
|
||||||
campaignInclude,
|
|
||||||
eligibleCampaignCollection,
|
|
||||||
nextCampaignVersion,
|
|
||||||
requireCampaign,
|
|
||||||
} from './campaign-lookup';
|
|
||||||
import { campaignStatus } from './campaign-policy';
|
|
||||||
|
|
||||||
@Injectable()
|
|
||||||
export class CampaignLifecycleStore {
|
|
||||||
constructor(private readonly access: AccessStore) {}
|
|
||||||
|
|
||||||
publish(actor: Principal, id: string, version: number) {
|
|
||||||
return this.access.mutate(actor, 'campaigns.manage', async (tx) => {
|
|
||||||
const campaign = await requireCampaign(tx, actor.organizationId, id);
|
|
||||||
if (campaign.state === 'PUBLISHED') {
|
|
||||||
if (campaign.version !== version + 1)
|
|
||||||
throw new AppError('CAMPAIGN_CHANGED');
|
|
||||||
return { ...campaign, status: campaignStatus(campaign) };
|
|
||||||
}
|
|
||||||
if (campaign.state !== 'DRAFT')
|
|
||||||
throw new AppError('CAMPAIGN_STATE_CONFLICT');
|
|
||||||
if (campaign.version !== version) throw new AppError('CAMPAIGN_CHANGED');
|
|
||||||
if (
|
|
||||||
!(await tx.catalogGroup.findFirst({
|
|
||||||
where: {
|
|
||||||
...eligibleCampaignCollection,
|
|
||||||
id: campaign.collectionId,
|
|
||||||
organizationId: actor.organizationId,
|
|
||||||
},
|
|
||||||
select: { id: true },
|
|
||||||
}))
|
|
||||||
)
|
|
||||||
throw new AppError('CAMPAIGN_COLLECTION_EMPTY');
|
|
||||||
const now = new Date();
|
|
||||||
if (campaign.endsAt <= now) throw new AppError('CAMPAIGN_EXPIRED');
|
|
||||||
const published = await tx.seasonalCampaign.update({
|
|
||||||
where: { id },
|
|
||||||
data: {
|
|
||||||
state: 'PUBLISHED',
|
|
||||||
publishedAt: now,
|
|
||||||
publishedById: actor.userId,
|
|
||||||
version: nextCampaignVersion(campaign.version),
|
|
||||||
},
|
|
||||||
include: campaignInclude,
|
|
||||||
});
|
|
||||||
await recordAudit(
|
|
||||||
tx,
|
|
||||||
actor.organizationId,
|
|
||||||
actor.userId,
|
|
||||||
'campaign.published',
|
|
||||||
id,
|
|
||||||
);
|
|
||||||
return { ...published, status: campaignStatus(published) };
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
cancel(actor: Principal, id: string, reason: string) {
|
|
||||||
return this.access.mutate(actor, 'campaigns.manage', async (tx) => {
|
|
||||||
const campaign = await requireCampaign(tx, actor.organizationId, id);
|
|
||||||
if (campaign.state === 'CANCELLED') {
|
|
||||||
if (campaign.cancellationReason !== reason)
|
|
||||||
throw new AppError('CAMPAIGN_CANCELLATION_CONFLICT');
|
|
||||||
return { ...campaign, status: campaignStatus(campaign) };
|
|
||||||
}
|
|
||||||
const cancelled = await tx.seasonalCampaign.update({
|
|
||||||
where: { id },
|
|
||||||
data: {
|
|
||||||
state: 'CANCELLED',
|
|
||||||
cancelledAt: new Date(),
|
|
||||||
cancelledById: actor.userId,
|
|
||||||
cancellationReason: reason,
|
|
||||||
version: nextCampaignVersion(campaign.version),
|
|
||||||
},
|
|
||||||
include: campaignInclude,
|
|
||||||
});
|
|
||||||
await recordAudit(
|
|
||||||
tx,
|
|
||||||
actor.organizationId,
|
|
||||||
actor.userId,
|
|
||||||
'campaign.cancelled',
|
|
||||||
id,
|
|
||||||
);
|
|
||||||
return { ...cancelled, status: campaignStatus(cancelled) };
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,43 +0,0 @@
|
||||||
import { AppError } from '../common/errors/app-error';
|
|
||||||
import type { DatabaseService } from '../database/database.service';
|
|
||||||
import type { Prisma } from '../generated/prisma/client';
|
|
||||||
|
|
||||||
type Db = DatabaseService | Prisma.TransactionClient;
|
|
||||||
export const campaignInclude = {
|
|
||||||
collection: { select: { id: true, name: true, slug: true } },
|
|
||||||
} as const;
|
|
||||||
export const eligibleCampaignCollection: Prisma.CatalogGroupWhereInput = {
|
|
||||||
kind: 'COLLECTION',
|
|
||||||
products: {
|
|
||||||
some: {
|
|
||||||
product: { status: 'PUBLISHED', variants: { some: { active: true } } },
|
|
||||||
},
|
|
||||||
},
|
|
||||||
};
|
|
||||||
export async function requireCampaign(
|
|
||||||
db: Db,
|
|
||||||
organizationId: string,
|
|
||||||
id: string,
|
|
||||||
) {
|
|
||||||
const campaign = await db.seasonalCampaign.findFirst({
|
|
||||||
where: { id, organizationId },
|
|
||||||
include: campaignInclude,
|
|
||||||
});
|
|
||||||
if (!campaign) throw new AppError('CAMPAIGN_NOT_FOUND');
|
|
||||||
return campaign;
|
|
||||||
}
|
|
||||||
export async function requireCampaignCollection(
|
|
||||||
db: Db,
|
|
||||||
organizationId: string,
|
|
||||||
id: string,
|
|
||||||
) {
|
|
||||||
const collection = await db.catalogGroup.findFirst({
|
|
||||||
where: { id, organizationId, kind: 'COLLECTION' },
|
|
||||||
select: { id: true },
|
|
||||||
});
|
|
||||||
if (!collection) throw new AppError('CAMPAIGN_COLLECTION_NOT_FOUND');
|
|
||||||
}
|
|
||||||
export function nextCampaignVersion(version: number) {
|
|
||||||
if (version >= 2147483647) throw new AppError('CAMPAIGN_VERSION_LIMIT');
|
|
||||||
return version + 1;
|
|
||||||
}
|
|
||||||
|
|
@ -1,35 +0,0 @@
|
||||||
type CampaignTime = {
|
|
||||||
state: 'DRAFT' | 'PUBLISHED' | 'CANCELLED';
|
|
||||||
startsAt: Date;
|
|
||||||
endsAt: Date;
|
|
||||||
};
|
|
||||||
|
|
||||||
export function campaignStatus(campaign: CampaignTime, now = new Date()) {
|
|
||||||
if (campaign.state !== 'PUBLISHED') return campaign.state;
|
|
||||||
if (now < campaign.startsAt) return 'SCHEDULED';
|
|
||||||
return now >= campaign.endsAt ? 'ENDED' : 'ACTIVE';
|
|
||||||
}
|
|
||||||
|
|
||||||
export function publicCampaignView(
|
|
||||||
campaign: CampaignTime & {
|
|
||||||
id: string;
|
|
||||||
slug: string;
|
|
||||||
title: string;
|
|
||||||
summary: string;
|
|
||||||
collection: { id: string; name: string; slug: string };
|
|
||||||
},
|
|
||||||
) {
|
|
||||||
return {
|
|
||||||
id: campaign.id,
|
|
||||||
slug: campaign.slug,
|
|
||||||
title: campaign.title,
|
|
||||||
summary: campaign.summary,
|
|
||||||
startsAt: campaign.startsAt,
|
|
||||||
endsAt: campaign.endsAt,
|
|
||||||
collection: {
|
|
||||||
id: campaign.collection.id,
|
|
||||||
name: campaign.collection.name,
|
|
||||||
slug: campaign.collection.slug,
|
|
||||||
},
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
@ -1,69 +0,0 @@
|
||||||
import { Injectable } from '@nestjs/common';
|
|
||||||
import { DatabaseService } from '../database/database.service';
|
|
||||||
import type { Principal } from '../identity/identity.types';
|
|
||||||
import { campaignStatus, publicCampaignView } from './campaign-policy';
|
|
||||||
import {
|
|
||||||
campaignInclude,
|
|
||||||
eligibleCampaignCollection,
|
|
||||||
requireCampaign,
|
|
||||||
} from './campaign-lookup';
|
|
||||||
import { AppError } from '../common/errors/app-error';
|
|
||||||
import type { PageInput } from '../identity/identity.schemas';
|
|
||||||
import type { Prisma } from '../generated/prisma/client';
|
|
||||||
import type { CampaignQuery } from './campaign.schemas';
|
|
||||||
|
|
||||||
@Injectable()
|
|
||||||
export class CampaignReadStore {
|
|
||||||
constructor(private readonly db: DatabaseService) {}
|
|
||||||
private publicWhere(
|
|
||||||
organizationId: string,
|
|
||||||
now: Date,
|
|
||||||
): Prisma.SeasonalCampaignWhereInput {
|
|
||||||
return {
|
|
||||||
organizationId,
|
|
||||||
state: 'PUBLISHED',
|
|
||||||
startsAt: { lte: now },
|
|
||||||
endsAt: { gt: now },
|
|
||||||
collection: eligibleCampaignCollection,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
async publicList(organizationId: string, page: PageInput, now = new Date()) {
|
|
||||||
const campaigns = await this.db.seasonalCampaign.findMany({
|
|
||||||
where: this.publicWhere(organizationId, now),
|
|
||||||
include: campaignInclude,
|
|
||||||
orderBy: [{ startsAt: 'desc' }, { id: 'asc' }],
|
|
||||||
take: page.limit,
|
|
||||||
skip: page.offset,
|
|
||||||
});
|
|
||||||
return campaigns.map(publicCampaignView);
|
|
||||||
}
|
|
||||||
async publicGet(organizationId: string, slug: string) {
|
|
||||||
const campaign = await this.db.seasonalCampaign.findFirst({
|
|
||||||
where: { ...this.publicWhere(organizationId, new Date()), slug },
|
|
||||||
include: campaignInclude,
|
|
||||||
});
|
|
||||||
if (!campaign) throw new AppError('CAMPAIGN_NOT_FOUND');
|
|
||||||
return publicCampaignView(campaign);
|
|
||||||
}
|
|
||||||
async list(actor: Principal, query: CampaignQuery) {
|
|
||||||
const campaigns = await this.db.seasonalCampaign.findMany({
|
|
||||||
where: {
|
|
||||||
organizationId: actor.organizationId,
|
|
||||||
...(query.state ? { state: query.state } : {}),
|
|
||||||
},
|
|
||||||
include: campaignInclude,
|
|
||||||
orderBy: [{ createdAt: 'desc' }, { id: 'desc' }],
|
|
||||||
take: query.limit,
|
|
||||||
skip: query.offset,
|
|
||||||
});
|
|
||||||
const now = new Date();
|
|
||||||
return campaigns.map((campaign) => ({
|
|
||||||
...campaign,
|
|
||||||
status: campaignStatus(campaign, now),
|
|
||||||
}));
|
|
||||||
}
|
|
||||||
async get(actor: Principal, id: string) {
|
|
||||||
const campaign = await requireCampaign(this.db, actor.organizationId, id);
|
|
||||||
return { ...campaign, status: campaignStatus(campaign) };
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,50 +0,0 @@
|
||||||
import { z } from 'zod';
|
|
||||||
import { text } from '../common/input';
|
|
||||||
import { groupSchema } from '../catalog/catalog.schemas';
|
|
||||||
import { pageSchema } from '../identity/identity.schemas';
|
|
||||||
|
|
||||||
const timestamp = z.iso
|
|
||||||
.datetime({ offset: true })
|
|
||||||
.transform((value) => new Date(value));
|
|
||||||
const fields = {
|
|
||||||
title: text(160),
|
|
||||||
summary: text(500, 0),
|
|
||||||
collectionId: z.uuid(),
|
|
||||||
startsAt: timestamp,
|
|
||||||
endsAt: timestamp,
|
|
||||||
};
|
|
||||||
const version = z.number().int().min(0).max(2147483647);
|
|
||||||
export const campaignCreateSchema = z
|
|
||||||
.object({
|
|
||||||
...fields,
|
|
||||||
summary: fields.summary.default(''),
|
|
||||||
slug: groupSchema.shape.slug,
|
|
||||||
idempotencyKey: z.uuid(),
|
|
||||||
})
|
|
||||||
.strict()
|
|
||||||
.refine((value) => value.endsAt > value.startsAt, {
|
|
||||||
message: 'End must follow start',
|
|
||||||
path: ['endsAt'],
|
|
||||||
});
|
|
||||||
export const campaignPatchSchema = z
|
|
||||||
.object(fields)
|
|
||||||
.partial()
|
|
||||||
.extend({
|
|
||||||
version,
|
|
||||||
})
|
|
||||||
.strict()
|
|
||||||
.refine(
|
|
||||||
(value) => Object.keys(value).some((key) => key !== 'version'),
|
|
||||||
'Provide at least one field',
|
|
||||||
);
|
|
||||||
export const campaignPublicationSchema = z.object({ version }).strict();
|
|
||||||
export const campaignCancellationSchema = z
|
|
||||||
.object({ reason: text(500, 3) })
|
|
||||||
.strict();
|
|
||||||
export const campaignQuerySchema = pageSchema
|
|
||||||
.extend({ state: z.enum(['DRAFT', 'PUBLISHED', 'CANCELLED']).optional() })
|
|
||||||
.strict();
|
|
||||||
export const campaignSlugSchema = groupSchema.shape.slug;
|
|
||||||
export type CampaignCreateInput = z.infer<typeof campaignCreateSchema>;
|
|
||||||
export type CampaignPatchInput = z.infer<typeof campaignPatchSchema>;
|
|
||||||
export type CampaignQuery = z.infer<typeof campaignQuerySchema>;
|
|
||||||
|
|
@ -1,92 +0,0 @@
|
||||||
import {
|
|
||||||
Body,
|
|
||||||
Controller,
|
|
||||||
Get,
|
|
||||||
Param,
|
|
||||||
ParseUUIDPipe,
|
|
||||||
Patch,
|
|
||||||
Post,
|
|
||||||
Query,
|
|
||||||
} from '@nestjs/common';
|
|
||||||
import {
|
|
||||||
CurrentPrincipal,
|
|
||||||
RequirePermission,
|
|
||||||
} from '../identity/access.decorator';
|
|
||||||
import type { Principal } from '../identity/identity.types';
|
|
||||||
import { SchemaPipe } from '../common/validation.pipe';
|
|
||||||
import { CampaignDraftStore } from './campaign-draft.store';
|
|
||||||
import { CampaignReadStore } from './campaign-read.store';
|
|
||||||
import { CampaignLifecycleStore } from './campaign-lifecycle.store';
|
|
||||||
import {
|
|
||||||
campaignPublicationSchema,
|
|
||||||
campaignCancellationSchema,
|
|
||||||
} from './campaign.schemas';
|
|
||||||
import {
|
|
||||||
campaignCreateSchema,
|
|
||||||
campaignPatchSchema,
|
|
||||||
campaignQuerySchema,
|
|
||||||
type CampaignCreateInput,
|
|
||||||
type CampaignPatchInput,
|
|
||||||
type CampaignQuery,
|
|
||||||
} from './campaign.schemas';
|
|
||||||
|
|
||||||
@Controller('campaigns')
|
|
||||||
export class CampaignsController {
|
|
||||||
constructor(
|
|
||||||
private readonly drafts: CampaignDraftStore,
|
|
||||||
private readonly campaigns: CampaignReadStore,
|
|
||||||
private readonly lifecycle: CampaignLifecycleStore,
|
|
||||||
) {}
|
|
||||||
@Get()
|
|
||||||
@RequirePermission('campaigns.read')
|
|
||||||
list(
|
|
||||||
@CurrentPrincipal() actor: Principal,
|
|
||||||
@Query(new SchemaPipe(campaignQuerySchema)) query: CampaignQuery,
|
|
||||||
) {
|
|
||||||
return this.campaigns.list(actor, query);
|
|
||||||
}
|
|
||||||
@Post(':id/publication')
|
|
||||||
@RequirePermission('campaigns.manage')
|
|
||||||
publish(
|
|
||||||
@CurrentPrincipal() actor: Principal,
|
|
||||||
@Param('id', ParseUUIDPipe) id: string,
|
|
||||||
@Body(new SchemaPipe(campaignPublicationSchema))
|
|
||||||
input: { version: number },
|
|
||||||
) {
|
|
||||||
return this.lifecycle.publish(actor, id, input.version);
|
|
||||||
}
|
|
||||||
@Post(':id/cancellation')
|
|
||||||
@RequirePermission('campaigns.manage')
|
|
||||||
cancel(
|
|
||||||
@CurrentPrincipal() actor: Principal,
|
|
||||||
@Param('id', ParseUUIDPipe) id: string,
|
|
||||||
@Body(new SchemaPipe(campaignCancellationSchema)) input: { reason: string },
|
|
||||||
) {
|
|
||||||
return this.lifecycle.cancel(actor, id, input.reason);
|
|
||||||
}
|
|
||||||
@Get(':id')
|
|
||||||
@RequirePermission('campaigns.read')
|
|
||||||
get(
|
|
||||||
@CurrentPrincipal() actor: Principal,
|
|
||||||
@Param('id', ParseUUIDPipe) id: string,
|
|
||||||
) {
|
|
||||||
return this.campaigns.get(actor, id);
|
|
||||||
}
|
|
||||||
@Post()
|
|
||||||
@RequirePermission('campaigns.manage')
|
|
||||||
create(
|
|
||||||
@CurrentPrincipal() actor: Principal,
|
|
||||||
@Body(new SchemaPipe(campaignCreateSchema)) input: CampaignCreateInput,
|
|
||||||
) {
|
|
||||||
return this.drafts.create(actor, input);
|
|
||||||
}
|
|
||||||
@Patch(':id')
|
|
||||||
@RequirePermission('campaigns.manage')
|
|
||||||
edit(
|
|
||||||
@CurrentPrincipal() actor: Principal,
|
|
||||||
@Param('id', ParseUUIDPipe) id: string,
|
|
||||||
@Body(new SchemaPipe(campaignPatchSchema)) input: CampaignPatchInput,
|
|
||||||
) {
|
|
||||||
return this.drafts.edit(actor, id, input);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,21 +0,0 @@
|
||||||
import { Module } from '@nestjs/common';
|
|
||||||
import { DatabaseModule } from '../database/database.module';
|
|
||||||
import { IdentityModule } from '../identity/identity.module';
|
|
||||||
import { CampaignsController } from './campaigns.controller';
|
|
||||||
import { CampaignDraftStore } from './campaign-draft.store';
|
|
||||||
import { CampaignReadStore } from './campaign-read.store';
|
|
||||||
import { CampaignLifecycleStore } from './campaign-lifecycle.store';
|
|
||||||
import { PublicCampaignsController } from './public-campaigns.controller';
|
|
||||||
import { StorefrontGuard } from '../catalog/storefront.guard';
|
|
||||||
|
|
||||||
@Module({
|
|
||||||
imports: [DatabaseModule, IdentityModule],
|
|
||||||
controllers: [CampaignsController, PublicCampaignsController],
|
|
||||||
providers: [
|
|
||||||
CampaignDraftStore,
|
|
||||||
CampaignReadStore,
|
|
||||||
CampaignLifecycleStore,
|
|
||||||
StorefrontGuard,
|
|
||||||
],
|
|
||||||
})
|
|
||||||
export class CampaignsModule {}
|
|
||||||
|
|
@ -1,35 +0,0 @@
|
||||||
import {
|
|
||||||
Controller,
|
|
||||||
Get,
|
|
||||||
Param,
|
|
||||||
ParseUUIDPipe,
|
|
||||||
Query,
|
|
||||||
UseGuards,
|
|
||||||
} from '@nestjs/common';
|
|
||||||
import { Public } from '../identity/access.decorator';
|
|
||||||
import { StorefrontGuard } from '../catalog/storefront.guard';
|
|
||||||
import { pageSchema, type PageInput } from '../identity/identity.schemas';
|
|
||||||
import { SchemaPipe } from '../common/validation.pipe';
|
|
||||||
import { CampaignReadStore } from './campaign-read.store';
|
|
||||||
import { campaignSlugSchema } from './campaign.schemas';
|
|
||||||
|
|
||||||
@Public()
|
|
||||||
@UseGuards(StorefrontGuard)
|
|
||||||
@Controller('storefront/:organizationId/campaigns')
|
|
||||||
export class PublicCampaignsController {
|
|
||||||
constructor(private readonly campaigns: CampaignReadStore) {}
|
|
||||||
@Get()
|
|
||||||
list(
|
|
||||||
@Param('organizationId', ParseUUIDPipe) organizationId: string,
|
|
||||||
@Query(new SchemaPipe(pageSchema)) page: PageInput,
|
|
||||||
) {
|
|
||||||
return this.campaigns.publicList(organizationId, page);
|
|
||||||
}
|
|
||||||
@Get(':slug')
|
|
||||||
get(
|
|
||||||
@Param('organizationId', ParseUUIDPipe) organizationId: string,
|
|
||||||
@Param('slug', new SchemaPipe(campaignSlugSchema)) slug: string,
|
|
||||||
) {
|
|
||||||
return this.campaigns.publicGet(organizationId, slug);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,57 +0,0 @@
|
||||||
export const CAMPAIGN_ERRORS = {
|
|
||||||
CAMPAIGN_COLLECTION_EMPTY: [
|
|
||||||
409,
|
|
||||||
'Collection needs a published product with an active variant',
|
|
||||||
'Campaign collection publication eligibility failed',
|
|
||||||
],
|
|
||||||
CAMPAIGN_EXPIRED: [
|
|
||||||
409,
|
|
||||||
'Campaign end time has passed',
|
|
||||||
'Expired campaign publication rejected',
|
|
||||||
],
|
|
||||||
CAMPAIGN_CANCELLATION_CONFLICT: [
|
|
||||||
409,
|
|
||||||
'Campaign was cancelled with a different reason',
|
|
||||||
'Cancellation replay mismatch',
|
|
||||||
],
|
|
||||||
CAMPAIGN_NOT_FOUND: [
|
|
||||||
404,
|
|
||||||
'Campaign not found',
|
|
||||||
'Scoped campaign lookup failed',
|
|
||||||
],
|
|
||||||
CAMPAIGN_COLLECTION_NOT_FOUND: [
|
|
||||||
404,
|
|
||||||
'Collection not found',
|
|
||||||
'Scoped campaign collection lookup failed',
|
|
||||||
],
|
|
||||||
CAMPAIGN_REPLAY_CONFLICT: [
|
|
||||||
409,
|
|
||||||
'Idempotency key was used for a different campaign',
|
|
||||||
'Campaign create replay mismatch',
|
|
||||||
],
|
|
||||||
CAMPAIGN_SLUG_EXISTS: [
|
|
||||||
409,
|
|
||||||
'Campaign slug already exists',
|
|
||||||
'Organization campaign slug collision',
|
|
||||||
],
|
|
||||||
CAMPAIGN_STATE_CONFLICT: [
|
|
||||||
409,
|
|
||||||
'Campaign is not eligible for this action',
|
|
||||||
'Campaign lifecycle conflict',
|
|
||||||
],
|
|
||||||
CAMPAIGN_CHANGED: [
|
|
||||||
409,
|
|
||||||
'Campaign changed; fetch its current version',
|
|
||||||
'Campaign version mismatch',
|
|
||||||
],
|
|
||||||
CAMPAIGN_INVALID_WINDOW: [
|
|
||||||
400,
|
|
||||||
'End must be after start',
|
|
||||||
'Campaign time window invalid',
|
|
||||||
],
|
|
||||||
CAMPAIGN_VERSION_LIMIT: [
|
|
||||||
409,
|
|
||||||
'Campaign version limit reached',
|
|
||||||
'Campaign integer version capacity reached',
|
|
||||||
],
|
|
||||||
} as const;
|
|
||||||
|
|
@ -1,7 +1,6 @@
|
||||||
import { B2B_CUSTOM_CANDLE_ERRORS } from './b2b-custom-candle-errors';
|
import { B2B_CUSTOM_CANDLE_ERRORS } from './b2b-custom-candle-errors';
|
||||||
import { WISHLIST_ERRORS } from './wishlist-errors';
|
import { WISHLIST_ERRORS } from './wishlist-errors';
|
||||||
import { REVIEW_ERRORS } from './review-errors';
|
import { REVIEW_ERRORS } from './review-errors';
|
||||||
import { CAMPAIGN_ERRORS } from './campaign-errors';
|
|
||||||
import { CHECKOUT_ERRORS } from './checkout-errors';
|
import { CHECKOUT_ERRORS } from './checkout-errors';
|
||||||
import { OPERATIONS_ERRORS } from './operations-errors';
|
import { OPERATIONS_ERRORS } from './operations-errors';
|
||||||
import { PLATFORM_ERRORS } from './platform-errors';
|
import { PLATFORM_ERRORS } from './platform-errors';
|
||||||
|
|
@ -15,7 +14,6 @@ import { B2B_ARTWORK_ERRORS } from './b2b-artwork-errors';
|
||||||
import { B2B_ORDER_ERRORS } from './b2b-order-errors';
|
import { B2B_ORDER_ERRORS } from './b2b-order-errors';
|
||||||
import { B2B_PAYMENT_ERRORS } from './b2b-payment-errors';
|
import { B2B_PAYMENT_ERRORS } from './b2b-payment-errors';
|
||||||
export const ERRORS = {
|
export const ERRORS = {
|
||||||
...CAMPAIGN_ERRORS,
|
|
||||||
...REVIEW_ERRORS,
|
...REVIEW_ERRORS,
|
||||||
...WISHLIST_ERRORS,
|
...WISHLIST_ERRORS,
|
||||||
...B2B_CUSTOM_CANDLE_ERRORS,
|
...B2B_CUSTOM_CANDLE_ERRORS,
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,4 @@
|
||||||
export const PERMISSIONS = [
|
export const PERMISSIONS = [
|
||||||
'campaigns.read',
|
|
||||||
'campaigns.manage',
|
|
||||||
'reviews.verify',
|
'reviews.verify',
|
||||||
'reviews.read',
|
'reviews.read',
|
||||||
'reviews.moderate',
|
'reviews.moderate',
|
||||||
|
|
|
||||||
|
|
@ -1,189 +0,0 @@
|
||||||
import { randomUUID } from 'node:crypto';
|
|
||||||
import { identityApp, type IdentityApp } from './helpers/identity-app';
|
|
||||||
import { secondActor } from './helpers/commerce';
|
|
||||||
|
|
||||||
describe('seasonal campaign drafts', () => {
|
|
||||||
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 input(kind: 'COLLECTION' | 'CATEGORY' = 'COLLECTION') {
|
|
||||||
const collection = await ctx
|
|
||||||
.api()
|
|
||||||
.post('/api/v1/catalog-groups')
|
|
||||||
.auth(ctx.token, auth)
|
|
||||||
.send({
|
|
||||||
name: 'Seasonal candles',
|
|
||||||
slug: 'collection-' + randomUUID(),
|
|
||||||
kind,
|
|
||||||
})
|
|
||||||
.expect(201);
|
|
||||||
return {
|
|
||||||
slug: 'campaign-' + randomUUID(),
|
|
||||||
title: 'Seasonal candles',
|
|
||||||
summary: 'Explore the collection',
|
|
||||||
collectionId: collection.body.id as string,
|
|
||||||
startsAt: '2030-10-01T00:00:00Z',
|
|
||||||
endsAt: '2030-10-02T00:00:00Z',
|
|
||||||
idempotencyKey: randomUUID(),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
const create = (body: Awaited<ReturnType<typeof input>>, token = ctx.token) =>
|
|
||||||
ctx.api().post(url).auth(token, auth).send(body);
|
|
||||||
|
|
||||||
it('creates private drafts, replays a single intent, and rejects conflicting keys and slugs', async () => {
|
|
||||||
const body = await input();
|
|
||||||
const [first, retry] = await Promise.all([
|
|
||||||
create(body).expect(201),
|
|
||||||
create(body).expect(201),
|
|
||||||
]);
|
|
||||||
expect(first.body).toMatchObject({
|
|
||||||
state: 'DRAFT',
|
|
||||||
status: 'DRAFT',
|
|
||||||
version: 0,
|
|
||||||
slug: body.slug,
|
|
||||||
});
|
|
||||||
expect(retry.body.id).toBe(first.body.id);
|
|
||||||
expect(
|
|
||||||
(await create({ ...body, title: 'Different title' }).expect(409)).body
|
|
||||||
.code,
|
|
||||||
).toBe('CAMPAIGN_REPLAY_CONFLICT');
|
|
||||||
expect(
|
|
||||||
(await create({ ...body, idempotencyKey: randomUUID() }).expect(409)).body
|
|
||||||
.code,
|
|
||||||
).toBe('CAMPAIGN_SLUG_EXISTS');
|
|
||||||
expect(
|
|
||||||
(
|
|
||||||
await ctx
|
|
||||||
.api()
|
|
||||||
.get(`${url}/${first.body.id}`)
|
|
||||||
.auth(ctx.token, auth)
|
|
||||||
.expect(200)
|
|
||||||
).body.id,
|
|
||||||
).toBe(first.body.id);
|
|
||||||
const list = await ctx
|
|
||||||
.api()
|
|
||||||
.get(`${url}?state=DRAFT&limit=1`)
|
|
||||||
.auth(ctx.token, auth)
|
|
||||||
.expect(200);
|
|
||||||
expect(list.body).toHaveLength(1);
|
|
||||||
expect(
|
|
||||||
await ctx.db.auditEvent.count({
|
|
||||||
where: { targetId: first.body.id, action: 'campaign.created' },
|
|
||||||
}),
|
|
||||||
).toBe(1);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('edits only draft terms with optimistic concurrency and no-op audit suppression', async () => {
|
|
||||||
const body = await input();
|
|
||||||
const created = await create(body).expect(201);
|
|
||||||
const path = `${url}/${created.body.id}`;
|
|
||||||
await ctx
|
|
||||||
.api()
|
|
||||||
.patch(path)
|
|
||||||
.auth(ctx.token, auth)
|
|
||||||
.send({ version: 0, title: body.title })
|
|
||||||
.expect(200);
|
|
||||||
const changes = await Promise.all([
|
|
||||||
ctx
|
|
||||||
.api()
|
|
||||||
.patch(path)
|
|
||||||
.auth(ctx.token, auth)
|
|
||||||
.send({ version: 0, title: 'New title' }),
|
|
||||||
ctx
|
|
||||||
.api()
|
|
||||||
.patch(path)
|
|
||||||
.auth(ctx.token, auth)
|
|
||||||
.send({ version: 0, title: 'Other title' }),
|
|
||||||
]);
|
|
||||||
expect(changes.map((response) => response.status).sort()).toEqual([
|
|
||||||
200, 409,
|
|
||||||
]);
|
|
||||||
const current = (
|
|
||||||
await ctx.api().get(path).auth(ctx.token, auth).expect(200)
|
|
||||||
).body;
|
|
||||||
expect(current.version).toBe(1);
|
|
||||||
await ctx
|
|
||||||
.api()
|
|
||||||
.patch(path)
|
|
||||||
.auth(ctx.token, auth)
|
|
||||||
.send({ version: 1, endsAt: '2030-09-01T00:00:00Z' })
|
|
||||||
.expect(400);
|
|
||||||
expect((await create(body).expect(201)).body.title).toBe(current.title);
|
|
||||||
expect(
|
|
||||||
await ctx.db.auditEvent.count({
|
|
||||||
where: { targetId: created.body.id, action: 'campaign.updated' },
|
|
||||||
}),
|
|
||||||
).toBe(1);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('enforces permissions, organization scope, collection type and ownership validation', async () => {
|
|
||||||
const body = await input();
|
|
||||||
const created = await create(body).expect(201);
|
|
||||||
await ctx.api().get(url).expect(401);
|
|
||||||
const noPermission = await secondActor(ctx);
|
|
||||||
await create(body, noPermission.token).expect(403);
|
|
||||||
await ctx.api().get(url).auth(noPermission.token, auth).expect(403);
|
|
||||||
const reader = await secondActor(ctx, true, ['campaigns.read']);
|
|
||||||
await ctx.api().get(url).auth(reader.token, auth).expect(200);
|
|
||||||
await create(body, reader.token).expect(403);
|
|
||||||
const outsider = await secondActor(ctx, false, [
|
|
||||||
'campaigns.read',
|
|
||||||
'campaigns.manage',
|
|
||||||
]);
|
|
||||||
await ctx
|
|
||||||
.api()
|
|
||||||
.get(`${url}/${created.body.id}`)
|
|
||||||
.auth(outsider.token, auth)
|
|
||||||
.expect(404);
|
|
||||||
await create(
|
|
||||||
{ ...body, idempotencyKey: randomUUID() },
|
|
||||||
outsider.token,
|
|
||||||
).expect(404);
|
|
||||||
await create(await input('CATEGORY')).expect(404);
|
|
||||||
await ctx
|
|
||||||
.api()
|
|
||||||
.post(url)
|
|
||||||
.auth(ctx.token, auth)
|
|
||||||
.send({ ...body, organizationId: outsider.organizationId })
|
|
||||||
.expect(400);
|
|
||||||
await ctx
|
|
||||||
.api()
|
|
||||||
.patch(`${url}/${created.body.id}`)
|
|
||||||
.auth(ctx.token, auth)
|
|
||||||
.send({ version: 0, slug: 'changed-slug' })
|
|
||||||
.expect(400);
|
|
||||||
const docs = await ctx.api().get('/api/docs-json').expect(200);
|
|
||||||
expect(docs.body.paths[url]).toBeDefined();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('enforces immutable identity, valid windows and collection organization scope in the database', async () => {
|
|
||||||
const body = await input();
|
|
||||||
const created = await create(body).expect(201);
|
|
||||||
await expect(
|
|
||||||
ctx.executeSql(
|
|
||||||
`UPDATE seasonal_campaigns SET slug = 'rewritten-slug', version = version + 1 WHERE id = '${created.body.id}'`,
|
|
||||||
),
|
|
||||||
).rejects.toThrow('identity');
|
|
||||||
await expect(
|
|
||||||
ctx.executeSql(
|
|
||||||
`UPDATE seasonal_campaigns SET ends_at = starts_at, version = version + 1 WHERE id = '${created.body.id}'`,
|
|
||||||
),
|
|
||||||
).rejects.toThrow();
|
|
||||||
const outsider = await secondActor(ctx, false);
|
|
||||||
await expect(
|
|
||||||
ctx.executeSql(`INSERT INTO seasonal_campaigns
|
|
||||||
(id, organization_id, collection_id, created_by_id, slug, title, summary, starts_at, ends_at, idempotency_key, request_hash, updated_at)
|
|
||||||
SELECT '${randomUUID()}', '${outsider.organizationId}', collection_id, '${outsider.userId}', 'cross-${randomUUID()}', title, summary, starts_at, ends_at, '${randomUUID()}', request_hash, NOW()
|
|
||||||
FROM seasonal_campaigns WHERE id = '${created.body.id}'`),
|
|
||||||
).rejects.toThrow();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
@ -1,105 +0,0 @@
|
||||||
import { randomUUID } from 'node:crypto';
|
|
||||||
import {
|
|
||||||
campaignStatus,
|
|
||||||
publicCampaignView,
|
|
||||||
} from '../src/campaigns/campaign-policy';
|
|
||||||
import {
|
|
||||||
campaignCreateSchema,
|
|
||||||
campaignPatchSchema,
|
|
||||||
} from '../src/campaigns/campaign.schemas';
|
|
||||||
|
|
||||||
const startsAt = new Date('2030-10-01T00:00:00.000Z');
|
|
||||||
const endsAt = new Date('2030-10-02T00:00:00.000Z');
|
|
||||||
const campaign = { state: 'PUBLISHED' as const, startsAt, endsAt };
|
|
||||||
const input = {
|
|
||||||
slug: 'seasonal-gifts',
|
|
||||||
title: 'Seasonal gifts',
|
|
||||||
summary: '',
|
|
||||||
collectionId: randomUUID(),
|
|
||||||
startsAt: startsAt.toISOString(),
|
|
||||||
endsAt: endsAt.toISOString(),
|
|
||||||
idempotencyKey: randomUUID(),
|
|
||||||
};
|
|
||||||
|
|
||||||
describe('seasonal campaign contract', () => {
|
|
||||||
it('includes the start and excludes the end of the live window', () => {
|
|
||||||
expect(campaignStatus(campaign, new Date(startsAt.getTime() - 1))).toBe(
|
|
||||||
'SCHEDULED',
|
|
||||||
);
|
|
||||||
expect(campaignStatus(campaign, startsAt)).toBe('ACTIVE');
|
|
||||||
expect(campaignStatus(campaign, new Date(endsAt.getTime() - 1))).toBe(
|
|
||||||
'ACTIVE',
|
|
||||||
);
|
|
||||||
expect(campaignStatus(campaign, endsAt)).toBe('ENDED');
|
|
||||||
});
|
|
||||||
it('keeps drafts and cancelled campaigns private regardless of the clock', () => {
|
|
||||||
expect(campaignStatus({ ...campaign, state: 'DRAFT' }, startsAt)).toBe(
|
|
||||||
'DRAFT',
|
|
||||||
);
|
|
||||||
expect(campaignStatus({ ...campaign, state: 'CANCELLED' }, startsAt)).toBe(
|
|
||||||
'CANCELLED',
|
|
||||||
);
|
|
||||||
});
|
|
||||||
it('normalizes timezone offsets and rejects collapsed or invalid windows', () => {
|
|
||||||
const parsed = campaignCreateSchema.parse({
|
|
||||||
...input,
|
|
||||||
startsAt: '2030-10-01T05:30:00+05:30',
|
|
||||||
});
|
|
||||||
expect(parsed.startsAt.toISOString()).toBe(startsAt.toISOString());
|
|
||||||
for (const endsAt of [
|
|
||||||
input.startsAt,
|
|
||||||
'2030-09-30T00:00:00Z',
|
|
||||||
'2030-10-01T00:00:00.000001Z',
|
|
||||||
]) {
|
|
||||||
expect(campaignCreateSchema.safeParse({ ...input, endsAt }).success).toBe(
|
|
||||||
false,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
expect(
|
|
||||||
campaignCreateSchema.safeParse({
|
|
||||||
...input,
|
|
||||||
startsAt: '2030-10-01T00:00:00',
|
|
||||||
}).success,
|
|
||||||
).toBe(false);
|
|
||||||
});
|
|
||||||
it('rejects forged lifecycle/ownership fields and empty edits', () => {
|
|
||||||
for (const fields of [
|
|
||||||
{ state: 'PUBLISHED' },
|
|
||||||
{ organizationId: randomUUID() },
|
|
||||||
{ title: '<b>Offer</b>' },
|
|
||||||
{ slug: '../unsafe' },
|
|
||||||
])
|
|
||||||
expect(
|
|
||||||
campaignCreateSchema.safeParse({ ...input, ...fields }).success,
|
|
||||||
).toBe(false);
|
|
||||||
expect(campaignPatchSchema.safeParse({ version: 0 }).success).toBe(false);
|
|
||||||
expect(
|
|
||||||
campaignPatchSchema.safeParse({ version: -1, title: 'Offer' }).success,
|
|
||||||
).toBe(false);
|
|
||||||
expect(
|
|
||||||
campaignPatchSchema.safeParse({ version: 0, title: 'Offer' }).success,
|
|
||||||
).toBe(true);
|
|
||||||
});
|
|
||||||
it('allowlists public content without staff identifiers or replay metadata', () => {
|
|
||||||
const record = {
|
|
||||||
...campaign,
|
|
||||||
id: 'campaign',
|
|
||||||
slug: 'seasonal-gifts',
|
|
||||||
title: 'Seasonal gifts',
|
|
||||||
summary: '',
|
|
||||||
organizationId: 'private-org',
|
|
||||||
createdById: 'private-staff',
|
|
||||||
requestHash: 'private-hash',
|
|
||||||
collection: { id: 'collection', name: 'Gifts', slug: 'gifts' },
|
|
||||||
};
|
|
||||||
const result = publicCampaignView(record);
|
|
||||||
expect(result.collection.id).toBe('collection');
|
|
||||||
for (const field of [
|
|
||||||
'state',
|
|
||||||
'organizationId',
|
|
||||||
'createdById',
|
|
||||||
'requestHash',
|
|
||||||
])
|
|
||||||
expect(result).not.toHaveProperty(field);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
@ -1,252 +0,0 @@
|
||||||
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);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
});
|
|
||||||
Loading…
Reference in New Issue