feat(blog): add reviewed publication snapshots and SEO metadata

This commit is contained in:
mihir 2026-10-07 12:45:10 +05:30
parent 779496cc15
commit fa0073e109
21 changed files with 819 additions and 1 deletions

View File

@ -82,3 +82,5 @@ Campaign-linked collection discounts: see [Phase 4D API guide](docs/campaign-dis
Private idle cart recovery: see [Phase 4E API guide](docs/cart-recovery-api.md).
Explicit messaging consent and eligibility: see [Phase 4F API guide](docs/messaging-consent-api.md).
Blog drafts, publication and SEO metadata: see [Phase 4G API guide](docs/blog-publishing-api.md).

View File

@ -0,0 +1,28 @@
# Blog publishing and SEO metadata (Phase 4G)
Staff create and edit organization-scoped blog articles, explicitly publish reviewed draft versions, and withdraw content with a reason. Revisions to a published article remain private working text until publication replaces the public snapshot at its existing slug. This is the next provider-independent growth milestone while Instagram, Etsy and WhatsApp integrations remain deferred.
| Method | Route | Access |
| ------ | ----------------------------------------------- | ----------------------------------------------------------------------------------- |
| GET | `/api/v1/blog-articles` | `blog.read`; paginated staff records, optional `state` filter. |
| GET | `/api/v1/blog-articles/:id` | `blog.read`; working text and latest publication metadata/snapshot. |
| POST | `/api/v1/blog-articles` | `blog.manage`; create a draft. |
| PATCH | `/api/v1/blog-articles/:id` | `blog.manage`; edit working text at its current version. |
| POST | `/api/v1/blog-articles/:id/publication` | `blog.publish`; publish `{ "version": 0 }`. |
| POST | `/api/v1/blog-articles/:id/withdrawal` | `blog.publish`; withdraw with `{ "reason": "Editorial correction needed" }`. |
| GET | `/api/v1/storefront/:organizationId/blog` | Public, shared storefront rate limit; published article summaries and SEO metadata. |
| GET | `/api/v1/storefront/:organizationId/blog/:slug` | Public, shared storefront rate limit; latest published text and SEO metadata. |
Create with `slug`, `title`, `summary`, `body`, and a UUID `idempotencyKey`. Slugs use the existing lowercase, hyphen-separated catalog convention and are permanent within an organization. Title is single-line plain text up to 160 characters, summary up to 500, and body multiline plain text up to 20,000. All are required and trimmed. HTML, angle brackets, and unsafe control characters are rejected; body line breaks and tabs are supported. PATCH accepts the current `version` and at least one of title/summary/body. Identity, slug, scope, lifecycle metadata, and public snapshot are never client-editable.
Creation retries with the same key and normalized input return the same article; changed input returns `IDEMPOTENCY_CONFLICT` (409). Duplicate organization/slug returns `RECORD_CONFLICT` (409). Successful edits increment version and record `blog.updated`. Publishing checks the reviewed version, copies title/summary/body into the public snapshot, records publication version/time/staff, increments the working version, and audits `blog.published`. Repeating the **latest** successful publication version makes no new changes or audit record. Older publication commands after republishing return `BLOG_CHANGED` (409). An exact latest-publication retry after further draft edits leaves those edits unpublished. Editors do not require publication permission to save private changes.
Public responses expose only slug, published title/summary, publication date, and `seo: { title, description }` derived from that snapshot. Detail adds published `body`; list omits body and uses existing limit/offset pagination. Draft content, staff identities, internal scope, keys, hashes, and version counters are absent. Draft, withdrawn, and foreign-organization detail requests return `BLOG_NOT_FOUND` (404). Staff reads are separately permission-gated, and all writes recheck live session and permission inside the existing organization lock.
Withdrawal is terminal, immediate, and reasoned; it does not erase the last public snapshot or audit evidence. Repeating the same reason is safe; a different reason, edit, or publication after withdrawal returns `BLOG_STATE_CONFLICT` (409). The slug remains reserved. Public routing no longer exposes withdrawn records. Replace an irreversibly withdrawn article with a new slug when needed.
The frontend must render body as text, preserving paragraphs, and escape all text used in HTML metadata. This API supplies content and metadata; it does not render pages, generate HTML/Markdown, invent a canonical domain, submit a sitemap, or guarantee search indexing/ranking. Frontend canonical links, sitemap/robots integration, rich text, media and structured data are separate delivery work.
Deploy the additive table/type migration before the application. Existing system Owners gain `blog.read`, `blog.manage`, and `blog.publish`; custom roles require explicit grants. Scoped staff foreign keys, unique slugs/creation keys, native revision/transition guards, and exact snapshot checks protect persistence. Deletes and withdrawn-record rewrites are rejected. Prior migrations remain unchanged. Older code ignores this table; preserve article rows and audit events on rollback.
The latest public snapshot is retained, while the audit trail records editorial actions without storing old article bodies. Full revision history and restoration can be added when editorial rollback is required. Verification covers unpublished/draft privacy, live text separation, republication, metadata projection, independent permissions, scoped access, plain-text/size validation, stale and concurrent commands, creation retries, reasoned withdrawal, native snapshot/delete guards, and migration drift. Native multi-connection concurrency verification remains dependent on the existing PostgreSQL CI setup.

View File

@ -60,6 +60,7 @@ Wishlist, verified reviews/moderation, seasonal campaigns, discounts, cart recov
- 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.
- 4E (implemented): private discovery and versioned resumption of carts idle for 24 hours, current catalog previews, unavailable-item redaction/removal, and audited activity tracking. Outbound recovery reminders remain dependent on consent-aware messaging and provider enablement.
- 4F (consent and eligibility implemented; live delivery deferred): explicit, independent email/WhatsApp opt-in and withdrawal for promotions/cart reminders, immutable versioned evidence, private history, and scoped live eligibility checks. Provider delivery, verified channel destinations, suppression-aware dispatch and unsubscribe links remain separate milestones.
- 4G (backend implemented): versioned blog drafts, separate publication permission, stable-slug public snapshots, private revisions, reasoned withdrawal, and public SEO metadata. Frontend pages, sitemap/canonical integration, rich text/media and historical revision restoration remain separate milestones; live channel integrations remain deferred.
## Phase 5: Community and optimization

35
prisma/blog.prisma Normal file
View File

@ -0,0 +1,35 @@
enum BlogState {
DRAFT
PUBLISHED
WITHDRAWN
}
model BlogArticle {
id String @id @default(uuid()) @db.Uuid
organizationId String @map("organization_id") @db.Uuid
createdById String @map("created_by_id") @db.Uuid
slug String @db.VarChar(100)
title String @db.VarChar(160)
summary String @db.VarChar(500)
body String
state BlogState @default(DRAFT)
version Int @default(0)
publishedContent Json? @map("published_content")
publicationVersion Int? @map("publication_version")
publishedAt DateTime? @map("published_at") @db.Timestamptz(3)
publishedById String? @map("published_by_id") @db.Uuid
withdrawnAt DateTime? @map("withdrawn_at") @db.Timestamptz(3)
withdrawnById String? @map("withdrawn_by_id") @db.Uuid
withdrawalReason String? @map("withdrawal_reason") @db.VarChar(500)
idempotencyKey String @map("idempotency_key") @db.Uuid
requestHash String @map("request_hash") @db.Char(64)
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3)
updatedAt DateTime @updatedAt @map("updated_at") @db.Timestamptz(3)
createdBy User @relation("BlogCreator", fields: [createdById, organizationId], references: [id, organizationId], onDelete: Restrict)
publishedBy User? @relation("BlogPublisher", fields: [publishedById, organizationId], references: [id, organizationId], onDelete: Restrict)
withdrawnBy User? @relation("BlogWithdrawer", fields: [withdrawnById, organizationId], references: [id, organizationId], onDelete: Restrict)
@@unique([organizationId, slug])
@@unique([organizationId, idempotencyKey])
@@index([organizationId, state, publishedAt, id])
@@index([organizationId, createdAt, id])
@@map("blog_articles")
}

View File

@ -48,5 +48,6 @@
"20261006120000_seasonal_campaigns": "4f81582f91a8d3cb30bf49051281ca05c862b794925c0643a7237d1a1efb6f40",
"20261006160000_campaign_discounts": "99485a5b252f01057dfa6300c567c79586555a76cec5c2dc0d9c3fef9fc61017",
"20261007120000_cart_recovery": "a415f3b458c55bf37a95f8d2f3b31dfc7ae4427f04aabc9f0910f1201caa6d31",
"20261007130000_messaging_consent": "b4fd5b1cf6a7cd17083a4b5fbef815ec1ebc25ba7538c6de18c05e16212155dd"
"20261007130000_messaging_consent": "b4fd5b1cf6a7cd17083a4b5fbef815ec1ebc25ba7538c6de18c05e16212155dd",
"20261007140000_blog_publishing": "92e8d98a8e89f3eda28b6cf5c3b45125a325e5d8e852f1e5a0a3cf5d7eff65a4"
}

View File

@ -0,0 +1,62 @@
CREATE TYPE "BlogState" AS ENUM ('DRAFT', 'PUBLISHED', 'WITHDRAWN');
CREATE TABLE "blog_articles" (
"id" UUID NOT NULL, "organization_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, "body" TEXT NOT NULL,
"state" "BlogState" NOT NULL DEFAULT 'DRAFT', "version" INTEGER NOT NULL DEFAULT 0,
"published_content" JSONB, "publication_version" INTEGER, "published_at" TIMESTAMPTZ(3), "published_by_id" UUID,
"withdrawn_at" TIMESTAMPTZ(3), "withdrawn_by_id" UUID, "withdrawal_reason" VARCHAR(500),
"idempotency_key" UUID NOT NULL, "request_hash" CHAR(64) NOT NULL,
"created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, "updated_at" TIMESTAMPTZ(3) NOT NULL,
CONSTRAINT "blog_articles_pkey" PRIMARY KEY ("id"),
CONSTRAINT "blog_articles_created_by_id_organization_id_fkey" FOREIGN KEY ("created_by_id", "organization_id") REFERENCES "users"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE,
CONSTRAINT "blog_articles_published_by_id_organization_id_fkey" FOREIGN KEY ("published_by_id", "organization_id") REFERENCES "users"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE,
CONSTRAINT "blog_articles_withdrawn_by_id_organization_id_fkey" FOREIGN KEY ("withdrawn_by_id", "organization_id") REFERENCES "users"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE,
CONSTRAINT "blog_article_terms" CHECK (version >= 0 AND char_length(title) >= 1 AND char_length(summary) >= 1 AND char_length(body) BETWEEN 1 AND 20000 AND slug ~ '^[a-z0-9]+(-[a-z0-9]+)*$' AND request_hash ~ '^[a-f0-9]{64}$'),
CONSTRAINT "blog_publication_metadata" CHECK (
(published_content IS NULL AND publication_version IS NULL AND published_at IS NULL AND published_by_id IS NULL)
OR (published_content IS NOT NULL AND jsonb_typeof(published_content) = 'object' AND publication_version IS NOT NULL AND publication_version >= 0 AND publication_version < version AND published_at IS NOT NULL AND published_by_id IS NOT NULL)
),
CONSTRAINT "blog_state_metadata" CHECK (
(state = 'DRAFT' AND published_content IS NULL OR state = 'PUBLISHED' AND published_content IS NOT NULL OR state = 'WITHDRAWN')
AND ((state = 'WITHDRAWN' AND withdrawn_at IS NOT NULL AND withdrawn_by_id IS NOT NULL AND withdrawal_reason IS NOT NULL AND char_length(withdrawal_reason) >= 3)
OR (state <> 'WITHDRAWN' AND withdrawn_at IS NULL AND withdrawn_by_id IS NULL AND withdrawal_reason IS NULL))
)
);
CREATE UNIQUE INDEX "blog_articles_organization_id_slug_key" ON "blog_articles"("organization_id", "slug");
CREATE UNIQUE INDEX "blog_articles_organization_id_idempotency_key_key" ON "blog_articles"("organization_id", "idempotency_key");
CREATE INDEX "blog_articles_organization_id_state_published_at_id_idx" ON "blog_articles"("organization_id", "state", "published_at", "id");
CREATE INDEX "blog_articles_organization_id_created_at_id_idx" ON "blog_articles"("organization_id", "created_at", "id");
CREATE FUNCTION guard_blog_article() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
IF TG_OP = 'DELETE' THEN RAISE EXCEPTION 'Blog articles cannot be deleted'; END IF;
IF TG_OP = 'INSERT' THEN
IF NEW.state <> 'DRAFT' OR NEW.version <> 0 THEN RAISE EXCEPTION 'Articles must begin as drafts'; END IF;
RETURN NEW;
END IF;
IF OLD.state = 'WITHDRAWN' THEN RAISE EXCEPTION 'Withdrawn articles are immutable'; 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 'Article identity is immutable'; END IF;
IF NEW.version::bigint <> OLD.version::bigint + 1 THEN RAISE EXCEPTION 'Article requires next version'; END IF;
IF NEW.state = 'WITHDRAWN' THEN
IF (NEW.title, NEW.summary, NEW.body, NEW.published_content, NEW.publication_version, NEW.published_at, NEW.published_by_id)
IS DISTINCT FROM (OLD.title, OLD.summary, OLD.body, OLD.published_content, OLD.publication_version, OLD.published_at, OLD.published_by_id)
THEN RAISE EXCEPTION 'Withdrawal cannot rewrite content'; END IF;
RETURN NEW;
END IF;
IF (NEW.published_content, NEW.publication_version, NEW.published_at, NEW.published_by_id)
IS DISTINCT FROM (OLD.published_content, OLD.publication_version, OLD.published_at, OLD.published_by_id) THEN
IF NEW.state <> 'PUBLISHED' OR NEW.publication_version IS DISTINCT FROM OLD.version
OR NEW.published_content IS DISTINCT FROM jsonb_build_object('title', OLD.title, 'summary', OLD.summary, 'body', OLD.body)
OR (NEW.title, NEW.summary, NEW.body) IS DISTINCT FROM (OLD.title, OLD.summary, OLD.body)
THEN RAISE EXCEPTION 'Publication requires the reviewed draft snapshot'; END IF;
RETURN NEW;
END IF;
IF NEW.state <> OLD.state THEN RAISE EXCEPTION 'Invalid article transition'; END IF;
RETURN NEW;
END;
$$;
CREATE TRIGGER blog_articles_guard BEFORE INSERT OR UPDATE OR DELETE ON blog_articles FOR EACH ROW EXECUTE FUNCTION guard_blog_article();
UPDATE roles SET permissions = ARRAY(SELECT DISTINCT unnest(permissions || ARRAY['blog.read', 'blog.manage', 'blog.publish']))
WHERE is_system = true AND name = 'Owner';

View File

@ -91,6 +91,9 @@ model User {
addresses Address[]
wishlistItems WishlistItem[]
messagingConsents MessagingConsentDecision[]
blogsCreated BlogArticle[] @relation("BlogCreator")
blogsPublished BlogArticle[] @relation("BlogPublisher")
blogsWithdrawn BlogArticle[] @relation("BlogWithdrawer")
reviewPurchases ReviewPurchaseVerification[] @relation("ReviewBuyer")
reviewVerifications ReviewPurchaseVerification[] @relation("ReviewVerifier")
reviewRevocations ReviewPurchaseRevocation[]

View File

@ -15,9 +15,11 @@ import { WishlistModule } from './wishlist/wishlist.module';
import { ReviewsModule } from './reviews/reviews.module';
import { CampaignsModule } from './campaigns/campaigns.module';
import { MessagingModule } from './messaging/messaging.module';
import { BlogModule } from './blog/blog.module';
@Module({
imports: [
BlogModule,
MessagingModule,
CampaignsModule,
ReviewsModule,

View File

@ -0,0 +1,72 @@
import { Injectable } from '@nestjs/common';
import { AccessStore } from '../identity/access.store';
import type { Principal } from '../identity/identity.types';
import { assertReplay, commandHash } from '../common/idempotency';
import { recordAudit } from '../identity/audit';
import { AppError } from '../common/errors/app-error';
import { requireArticle, nextBlogVersion } from './blog-lookup';
import type { BlogCreateInput, BlogPatchInput } from './blog.schemas';
@Injectable()
export class BlogDraftStore {
constructor(private readonly access: AccessStore) {}
create(actor: Principal, input: BlogCreateInput) {
const requestHash = commandHash(
input.slug,
input.title,
input.summary,
input.body,
);
return this.access.mutate(actor, 'blog.manage', async (tx) => {
const previous = await tx.blogArticle.findUnique({
where: {
organizationId_idempotencyKey: {
organizationId: actor.organizationId,
idempotencyKey: input.idempotencyKey,
},
},
});
if (previous) {
assertReplay(previous.requestHash, requestHash);
return previous;
}
const article = await tx.blogArticle.create({
data: {
...input,
organizationId: actor.organizationId,
createdById: actor.userId,
requestHash,
},
});
await recordAudit(
tx,
actor.organizationId,
actor.userId,
'blog.created',
article.id,
);
return article;
});
}
edit(actor: Principal, id: string, input: BlogPatchInput) {
return this.access.mutate(actor, 'blog.manage', async (tx) => {
const article = await requireArticle(tx, actor.organizationId, id);
if (article.state === 'WITHDRAWN')
throw new AppError('BLOG_STATE_CONFLICT');
if (article.version !== input.version) throw new AppError('BLOG_CHANGED');
const { version, ...fields } = input;
const updated = await tx.blogArticle.update({
where: { id },
data: { ...fields, version: nextBlogVersion(version) },
});
await recordAudit(
tx,
actor.organizationId,
actor.userId,
'blog.updated',
id,
);
return updated;
});
}
}

17
src/blog/blog-lookup.ts Normal file
View File

@ -0,0 +1,17 @@
import type { Prisma } from '../generated/prisma/client';
import { AppError } from '../common/errors/app-error';
export async function requireArticle(
tx: Prisma.TransactionClient,
organizationId: string,
id: string,
) {
const article = await tx.blogArticle.findFirst({
where: { id, organizationId },
});
if (!article) throw new AppError('BLOG_NOT_FOUND');
return article;
}
export function nextBlogVersion(version: number) {
if (version >= 2147483647) throw new AppError('BLOG_CHANGED');
return version + 1;
}

View File

@ -0,0 +1,72 @@
import { Injectable } from '@nestjs/common';
import { AccessStore } from '../identity/access.store';
import type { Principal } from '../identity/identity.types';
import { recordAudit } from '../identity/audit';
import { AppError } from '../common/errors/app-error';
import { requireArticle, nextBlogVersion } from './blog-lookup';
@Injectable()
export class BlogPublicationStore {
constructor(private readonly access: AccessStore) {}
publish(actor: Principal, id: string, version: number) {
return this.access.mutate(actor, 'blog.publish', async (tx) => {
const article = await requireArticle(tx, actor.organizationId, id);
if (article.state === 'WITHDRAWN')
throw new AppError('BLOG_STATE_CONFLICT');
if (article.publicationVersion === version) return article;
if (article.version !== version) throw new AppError('BLOG_CHANGED');
// ponytail: retain the latest public snapshot; add revision history when editorial rollback is needed.
const updated = await tx.blogArticle.update({
where: { id },
data: {
state: 'PUBLISHED',
publishedContent: {
title: article.title,
summary: article.summary,
body: article.body,
},
publicationVersion: version,
publishedAt: new Date(),
publishedById: actor.userId,
version: nextBlogVersion(version),
},
});
await recordAudit(
tx,
actor.organizationId,
actor.userId,
'blog.published',
id,
);
return updated;
});
}
withdraw(actor: Principal, id: string, reason: string) {
return this.access.mutate(actor, 'blog.publish', async (tx) => {
const article = await requireArticle(tx, actor.organizationId, id);
if (article.state === 'WITHDRAWN') {
if (article.withdrawalReason !== reason)
throw new AppError('BLOG_STATE_CONFLICT');
return article;
}
const updated = await tx.blogArticle.update({
where: { id },
data: {
state: 'WITHDRAWN',
withdrawalReason: reason,
withdrawnAt: new Date(),
withdrawnById: actor.userId,
version: nextBlogVersion(article.version),
},
});
await recordAudit(
tx,
actor.organizationId,
actor.userId,
'blog.withdrawn',
id,
);
return updated;
});
}
}

View File

@ -0,0 +1,68 @@
import { Injectable } from '@nestjs/common';
import { DatabaseService } from '../database/database.service';
import type { Principal } from '../identity/identity.types';
import type { PageInput } from '../identity/identity.schemas';
import type { Prisma } from '../generated/prisma/client';
import { AppError } from '../common/errors/app-error';
import { requireArticle } from './blog-lookup';
import type { BlogQuery } from './blog.schemas';
const publicSelect = { slug: true, publishedContent: true, publishedAt: true };
function publicView(
article: {
slug: string;
publishedContent: Prisma.JsonValue | null;
publishedAt: Date | null;
},
detail: boolean,
) {
const content = article.publishedContent as {
title: string;
summary: string;
body: string;
};
return {
slug: article.slug,
title: content.title,
summary: content.summary,
...(detail ? { body: content.body } : {}),
publishedAt: article.publishedAt,
seo: { title: content.title, description: content.summary },
};
}
@Injectable()
export class BlogReadStore {
constructor(private readonly db: DatabaseService) {}
list(actor: Principal, page: BlogQuery) {
return this.db.blogArticle.findMany({
where: {
organizationId: actor.organizationId,
...(page.state ? { state: page.state } : {}),
},
orderBy: [{ createdAt: 'desc' }, { id: 'desc' }],
skip: page.offset,
take: page.limit,
});
}
get(actor: Principal, id: string) {
return requireArticle(this.db, actor.organizationId, id);
}
async publicList(organizationId: string, page: PageInput) {
const articles = await this.db.blogArticle.findMany({
where: { organizationId, state: 'PUBLISHED' },
select: publicSelect,
orderBy: [{ publishedAt: 'desc' }, { id: 'asc' }],
skip: page.offset,
take: page.limit,
});
return articles.map((article) => publicView(article, false));
}
async publicGet(organizationId: string, slug: string) {
const article = await this.db.blogArticle.findFirst({
where: { organizationId, slug, state: 'PUBLISHED' },
select: publicSelect,
});
if (!article) throw new AppError('BLOG_NOT_FOUND');
return publicView(article, true);
}
}

View File

@ -0,0 +1,88 @@
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 { BlogDraftStore } from './blog-draft.store';
import { BlogReadStore } from './blog-read.store';
import { BlogPublicationStore } from './blog-publication.store';
import {
blogCreateSchema,
blogPatchSchema,
blogPublicationSchema,
blogWithdrawalSchema,
blogQuerySchema,
type BlogCreateInput,
type BlogPatchInput,
type BlogQuery,
} from './blog.schemas';
@Controller('blog-articles')
export class BlogController {
constructor(
private readonly drafts: BlogDraftStore,
private readonly articles: BlogReadStore,
private readonly publication: BlogPublicationStore,
) {}
@Get()
@RequirePermission('blog.read')
list(
@CurrentPrincipal() actor: Principal,
@Query(new SchemaPipe(blogQuerySchema)) query: BlogQuery,
) {
return this.articles.list(actor, query);
}
@Get(':id')
@RequirePermission('blog.read')
get(
@CurrentPrincipal() actor: Principal,
@Param('id', ParseUUIDPipe) id: string,
) {
return this.articles.get(actor, id);
}
@Post()
@RequirePermission('blog.manage')
create(
@CurrentPrincipal() actor: Principal,
@Body(new SchemaPipe(blogCreateSchema)) input: BlogCreateInput,
) {
return this.drafts.create(actor, input);
}
@Patch(':id')
@RequirePermission('blog.manage')
edit(
@CurrentPrincipal() actor: Principal,
@Param('id', ParseUUIDPipe) id: string,
@Body(new SchemaPipe(blogPatchSchema)) input: BlogPatchInput,
) {
return this.drafts.edit(actor, id, input);
}
@Post(':id/publication')
@RequirePermission('blog.publish')
publish(
@CurrentPrincipal() actor: Principal,
@Param('id', ParseUUIDPipe) id: string,
@Body(new SchemaPipe(blogPublicationSchema)) input: { version: number },
) {
return this.publication.publish(actor, id, input.version);
}
@Post(':id/withdrawal')
@RequirePermission('blog.publish')
withdraw(
@CurrentPrincipal() actor: Principal,
@Param('id', ParseUUIDPipe) id: string,
@Body(new SchemaPipe(blogWithdrawalSchema)) input: { reason: string },
) {
return this.publication.withdraw(actor, id, input.reason);
}
}

20
src/blog/blog.module.ts Normal file
View File

@ -0,0 +1,20 @@
import { Module } from '@nestjs/common';
import { DatabaseModule } from '../database/database.module';
import { IdentityModule } from '../identity/identity.module';
import { BlogController } from './blog.controller';
import { PublicBlogController } from './public-blog.controller';
import { BlogDraftStore } from './blog-draft.store';
import { BlogReadStore } from './blog-read.store';
import { BlogPublicationStore } from './blog-publication.store';
import { StorefrontGuard } from '../catalog/storefront.guard';
@Module({
imports: [DatabaseModule, IdentityModule],
controllers: [BlogController, PublicBlogController],
providers: [
BlogDraftStore,
BlogReadStore,
BlogPublicationStore,
StorefrontGuard,
],
})
export class BlogModule {}

39
src/blog/blog.schemas.ts Normal file
View File

@ -0,0 +1,39 @@
import { z } from 'zod';
import { text } from '../common/input';
import { groupSchema } from '../catalog/catalog.schemas';
import { pageSchema } from '../identity/identity.schemas';
export const blogSlugSchema = groupSchema.shape.slug;
const fields = {
title: text(160),
summary: text(500),
body: z
.string()
.trim()
.min(1)
.max(20000)
.regex(
/^[^<>\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F]*$/,
'Plain text only',
),
};
const version = z.number().int().min(0).max(2147483646);
export const blogCreateSchema = z
.object({ ...fields, slug: blogSlugSchema, idempotencyKey: z.uuid() })
.strict();
export const blogPatchSchema = z
.object(fields)
.partial()
.extend({ version })
.strict()
.refine(
(input) => Object.keys(input).some((key) => key !== 'version'),
'Provide a field to edit',
);
export const blogPublicationSchema = z.object({ version }).strict();
export const blogWithdrawalSchema = z.object({ reason: text(500, 3) }).strict();
export const blogQuerySchema = pageSchema
.extend({ state: z.enum(['DRAFT', 'PUBLISHED', 'WITHDRAWN']).optional() })
.strict();
export type BlogCreateInput = z.infer<typeof blogCreateSchema>;
export type BlogPatchInput = z.infer<typeof blogPatchSchema>;
export type BlogQuery = z.infer<typeof blogQuerySchema>;

View File

@ -0,0 +1,34 @@
import {
Controller,
Get,
Param,
ParseUUIDPipe,
Query,
UseGuards,
} from '@nestjs/common';
import { Public } from '../identity/access.decorator';
import { StorefrontGuard } from '../catalog/storefront.guard';
import { SchemaPipe } from '../common/validation.pipe';
import { pageSchema, type PageInput } from '../identity/identity.schemas';
import { blogSlugSchema } from './blog.schemas';
import { BlogReadStore } from './blog-read.store';
@Public()
@UseGuards(StorefrontGuard)
@Controller('storefront/:organizationId/blog')
export class PublicBlogController {
constructor(private readonly articles: BlogReadStore) {}
@Get()
list(
@Param('organizationId', ParseUUIDPipe) organizationId: string,
@Query(new SchemaPipe(pageSchema)) page: PageInput,
) {
return this.articles.publicList(organizationId, page);
}
@Get(':slug')
get(
@Param('organizationId', ParseUUIDPipe) organizationId: string,
@Param('slug', new SchemaPipe(blogSlugSchema)) slug: string,
) {
return this.articles.publicGet(organizationId, slug);
}
}

View File

@ -0,0 +1,17 @@
export const BLOG_ERRORS = {
BLOG_NOT_FOUND: [
404,
'Article not found',
'Scoped blog article lookup failed',
],
BLOG_CHANGED: [
409,
'Article version has changed',
'Stale blog command rejected',
],
BLOG_STATE_CONFLICT: [
409,
'Article state does not allow this action',
'Withdrawn article mutation rejected',
],
} as const;

View File

@ -3,6 +3,7 @@ import { WISHLIST_ERRORS } from './wishlist-errors';
import { REVIEW_ERRORS } from './review-errors';
import { CAMPAIGN_ERRORS } from './campaign-errors';
import { MESSAGING_ERRORS } from './messaging-errors';
import { BLOG_ERRORS } from './blog-errors';
import { CHECKOUT_ERRORS } from './checkout-errors';
import { OPERATIONS_ERRORS } from './operations-errors';
import { PLATFORM_ERRORS } from './platform-errors';
@ -16,6 +17,7 @@ import { B2B_ARTWORK_ERRORS } from './b2b-artwork-errors';
import { B2B_ORDER_ERRORS } from './b2b-order-errors';
import { B2B_PAYMENT_ERRORS } from './b2b-payment-errors';
export const ERRORS = {
...BLOG_ERRORS,
...MESSAGING_ERRORS,
...CAMPAIGN_ERRORS,
...REVIEW_ERRORS,

View File

@ -1,4 +1,7 @@
export const PERMISSIONS = [
'blog.read',
'blog.manage',
'blog.publish',
'messaging.read',
'campaigns.read',
'campaigns.manage',

34
test/blog-policy.spec.ts Normal file
View File

@ -0,0 +1,34 @@
import { randomUUID } from 'node:crypto';
import { blogCreateSchema, blogPatchSchema } from '../src/blog/blog.schemas';
import { nextBlogVersion } from '../src/blog/blog-lookup';
it('accepts multiline plain text, validates editorial commands and bounds revisions', () => {
const input = {
slug: 'candle-care',
title: 'Candle care',
summary: 'Simple care.',
body: 'First line.\nSecond line.',
idempotencyKey: randomUUID(),
};
expect(blogCreateSchema.safeParse(input).success).toBe(true);
for (const fields of [
{ body: '<img src=x>' },
{ body: '\u0000' },
{ body: ' ' },
{ title: ' ' },
{ summary: ' ' },
{ slug: '../private' },
{ body: 'x'.repeat(20001) },
{ state: 'PUBLISHED' },
])
expect(blogCreateSchema.safeParse({ ...input, ...fields }).success).toBe(
false,
);
expect(blogPatchSchema.safeParse({ version: 0 }).success).toBe(false);
expect(
blogPatchSchema.safeParse({ version: 0, body: input.body }).success,
).toBe(true);
expect(nextBlogVersion(0)).toBe(1);
expect(nextBlogVersion(2147483646)).toBe(2147483647);
expect(() => nextBlogVersion(2147483647)).toThrow();
});

View File

@ -0,0 +1,218 @@
import { randomUUID } from 'node:crypto';
import { identityApp, type IdentityApp } from './helpers/identity-app';
import { secondActor } from './helpers/commerce';
describe('versioned blog drafts and public publication snapshots', () => {
let ctx: IdentityApp;
beforeAll(async () => {
ctx = await identityApp();
});
afterAll(async () => {
await ctx.close();
});
beforeEach(async () => {
await ctx.clearLimits();
});
const input = () => ({
slug: 'candle-' + randomUUID(),
title: 'Candle care',
summary: 'How to care for a candle.',
body: 'Trim the wick.\nLet the wax cool.',
idempotencyKey: randomUUID(),
});
const create = (body = input(), token = ctx.token) =>
ctx
.api()
.post('/api/v1/blog-articles')
.auth(token, { type: 'bearer' })
.send(body);
const publish = (id: string, version: number, token = ctx.token) =>
ctx
.api()
.post('/api/v1/blog-articles/' + id + '/publication')
.auth(token, { type: 'bearer' })
.send({ version });
const publicGet = (slug: string) =>
ctx
.api()
.get('/api/v1/storefront/' + ctx.owner.organizationId + '/blog/' + slug);
it('keeps drafts private, freezes a reviewed snapshot and republishes changes at the same slug', async () => {
const values = input();
const draft = await create(values).expect(201);
await publicGet(values.slug).expect(404);
const first = await publish(draft.body.id, 0).expect(201);
expect(first.body).toMatchObject({
version: 1,
publicationVersion: 0,
state: 'PUBLISHED',
});
const live = await publicGet(values.slug).expect(200);
expect(live.body).toMatchObject({
slug: values.slug,
title: values.title,
summary: values.summary,
body: values.body,
seo: { title: values.title, description: values.summary },
});
expect(JSON.stringify(live.body)).not.toMatch(
/requestHash|idempotencyKey|createdById|publishedById|organizationId|version/,
);
const feed = await ctx
.api()
.get('/api/v1/storefront/' + ctx.owner.organizationId + '/blog')
.query({ limit: 1 })
.expect(200);
expect(feed.body[0]).toMatchObject({
slug: values.slug,
title: values.title,
});
expect(feed.body[0]).not.toHaveProperty('body');
await expect(
ctx.executeSql(
`UPDATE blog_articles SET version = version + 1, publication_version = version, published_content = '{"title":"Leaked"}'::jsonb WHERE id = '${draft.body.id}'`,
),
).rejects.toThrow(/reviewed draft/);
const editor = await secondActor(ctx, true, ['blog.manage']);
await ctx
.api()
.patch('/api/v1/blog-articles/' + draft.body.id)
.auth(editor.token, { type: 'bearer' })
.send({ version: 1, title: 'Updated care', body: 'Cool before moving.' })
.expect(200);
expect((await publicGet(values.slug).expect(200)).body).toEqual(live.body);
await publish(draft.body.id, 2, editor.token).expect(403);
expect((await publish(draft.body.id, 1).expect(409)).body.code).toBe(
'BLOG_CHANGED',
);
await publish(draft.body.id, 2).expect(201);
const updated = await publicGet(values.slug).expect(200);
expect(updated.body).toMatchObject({
title: 'Updated care',
body: 'Cool before moving.',
});
await publish(draft.body.id, 0).expect(409);
const repeat = await publish(draft.body.id, 2).expect(201);
expect(repeat.body.version).toBe(3);
expect(
await ctx.db.auditEvent.count({
where: { targetId: draft.body.id, action: 'blog.published' },
}),
).toBe(2);
});
it('makes creation retry-safe and protects versioned edits and reserved slugs', async () => {
const values = input();
const draft = await create(values).expect(201);
expect((await create(values).expect(201)).body.id).toBe(draft.body.id);
expect(
(await create({ ...values, title: 'Changed' }).expect(409)).body.code,
).toBe('IDEMPOTENCY_CONFLICT');
await create({ ...values, idempotencyKey: randomUUID() }).expect(409);
await ctx
.api()
.patch('/api/v1/blog-articles/' + draft.body.id)
.auth(ctx.token, { type: 'bearer' })
.send({ version: 1, title: 'Changed' })
.expect(409);
const results = await Promise.all([
publish(draft.body.id, 0),
ctx
.api()
.patch('/api/v1/blog-articles/' + draft.body.id)
.auth(ctx.token, { type: 'bearer' })
.send({ version: 0, title: 'Revised' }),
]);
expect(results.map((r) => r.status).filter((s) => s < 300)).toHaveLength(1);
expect(results.map((r) => r.status)).toContain(409);
});
it('withdraws immediately and cannot edit, republish or delete withdrawn evidence', async () => {
const values = input();
const draft = await create(values).expect(201);
await publish(draft.body.id, 0).expect(201);
const withdraw = (reason: string) =>
ctx
.api()
.post('/api/v1/blog-articles/' + draft.body.id + '/withdrawal')
.auth(ctx.token, { type: 'bearer' })
.send({ reason });
await withdraw('Editorial correction needed').expect(201);
await withdraw('Editorial correction needed').expect(201);
await withdraw('Another reason').expect(409);
await publicGet(values.slug).expect(404);
const list = await ctx
.api()
.get('/api/v1/storefront/' + ctx.owner.organizationId + '/blog')
.expect(200);
expect(list.body.some((article: any) => article.slug === values.slug)).toBe(
false,
);
await publish(draft.body.id, 1).expect(409);
await ctx
.api()
.patch('/api/v1/blog-articles/' + draft.body.id)
.auth(ctx.token, { type: 'bearer' })
.send({ version: 2, title: 'Changed' })
.expect(409);
await expect(
ctx.executeSql(`DELETE FROM blog_articles WHERE id = '${draft.body.id}'`),
).rejects.toThrow(/deleted/);
expect(
await ctx.db.auditEvent.count({
where: { targetId: draft.body.id, action: 'blog.withdrawn' },
}),
).toBe(1);
});
it('enforces scope, separate editorial permissions and plain text input', async () => {
const values = input();
const draft = await create(values).expect(201);
const customer = await secondActor(ctx);
await create(input(), customer.token).expect(403);
await ctx
.api()
.get('/api/v1/blog-articles')
.auth(customer.token, { type: 'bearer' })
.expect(403);
const foreign = await secondActor(ctx, false, [
'blog.read',
'blog.manage',
'blog.publish',
]);
await ctx
.api()
.get('/api/v1/blog-articles/' + draft.body.id)
.auth(foreign.token, { type: 'bearer' })
.expect(404);
await publish(draft.body.id, 0, foreign.token).expect(404);
await create({ ...input(), body: '<script>bad()</script>' }).expect(400);
await create({ ...input(), body: 'x'.repeat(20001) }).expect(400);
await ctx
.api()
.patch('/api/v1/blog-articles/' + draft.body.id)
.auth(ctx.token, { type: 'bearer' })
.send({ version: 0 })
.expect(400);
await ctx
.api()
.post('/api/v1/blog-articles/' + draft.body.id + '/publication')
.auth(ctx.token, { type: 'bearer' })
.send({ version: 0, publishedContent: {} })
.expect(400);
const staff = await ctx
.api()
.get('/api/v1/blog-articles/' + draft.body.id)
.auth(ctx.token, { type: 'bearer' })
.expect(200);
expect(staff.body).toMatchObject({
state: 'DRAFT',
version: 0,
publishedContent: null,
});
await ctx
.api()
.get('/api/v1/blog-articles')
.auth(ctx.token, { type: 'bearer' })
.query({ limit: 1 })
.expect(200);
await ctx.api().get('/api/v1/blog-articles').expect(401);
await ctx.api().get('/api/v1/storefront/not-a-uuid/blog').expect(400);
});
});