feat(task-005): complete article intake dashboard detail flow

This commit is contained in:
2026-05-21 18:54:11 +03:00
parent 7972e9a95f
commit cf84400118
28 changed files with 1714 additions and 61 deletions
+1
View File
@@ -6,6 +6,7 @@
"build": "next build",
"start": "next start",
"test:roles": "node tests/role-navigation.test.mjs",
"test:ui": "node tests/role-navigation.test.mjs && node tests/article_dashboard.test.mjs && node tests/article_form_validation.test.mjs",
"typecheck": "tsc --noEmit"
},
"dependencies": {
@@ -0,0 +1,14 @@
import ArticleDetailPage from "@/pages/article-detail";
type DynamicArticleDetailPageProps = {
params: {
articleId: string;
};
};
export default async function DynamicArticleDetailPage({
params,
}: DynamicArticleDetailPageProps) {
const { articleId } = params;
return <ArticleDetailPage articleId={articleId} />;
}
@@ -0,0 +1,3 @@
import NewArticlePage from "@/pages/article-new";
export { NewArticlePage as default };
+135
View File
@@ -76,6 +76,141 @@ main {
text-decoration: none;
}
.panel {
max-width: 980px;
}
.table {
width: 100%;
border-collapse: collapse;
margin-top: 16px;
background: #ffffff;
border: 1px solid #d0d5dd;
border-radius: 8px;
overflow: hidden;
}
.table th,
.table td {
border-bottom: 1px solid #d0d5dd;
padding: 10px;
text-align: left;
vertical-align: top;
}
.table th {
background: #eef2f6;
}
.table a {
font-weight: 600;
color: #1f4b99;
text-decoration: none;
}
.table a:hover {
text-decoration: underline;
}
.emptyState {
margin-top: 8px;
padding: 16px;
border: 1px dashed #b7c0cc;
border-radius: 8px;
background: #ffffff;
}
.articleForm {
max-width: 620px;
display: grid;
gap: 8px;
padding: 16px;
border: 1px solid #d0d5dd;
border-radius: 8px;
background: #ffffff;
}
.articleForm label {
font-size: 13px;
font-weight: 600;
}
.articleForm input,
.articleForm select,
.articleForm textarea {
width: 100%;
border-radius: 6px;
border: 1px solid #d0d5dd;
padding: 10px;
font: inherit;
}
.articleForm textarea {
min-height: 120px;
}
.fieldError {
margin: 0;
color: #b42318;
font-size: 12px;
}
.formError {
margin: 4px 0 0;
color: #b42318;
font-weight: 600;
}
.formActions {
margin-top: 8px;
}
.formActions button {
border-radius: 6px;
border: 1px solid #1d2733;
background: #1d2733;
color: #ffffff;
min-height: 40px;
padding: 0 14px;
}
.detailGrid {
display: grid;
grid-template-columns: repeat(2, minmax(220px, 1fr));
gap: 10px;
}
.detailGrid div {
border: 1px solid #d0d5dd;
border-radius: 8px;
padding: 10px;
background: #ffffff;
}
.detailGrid dt {
font-size: 12px;
text-transform: uppercase;
color: #667085;
margin-bottom: 6px;
}
.detailGrid dd {
margin: 0;
font-weight: 600;
}
.timeline {
margin: 0;
list-style: none;
padding: 0;
max-width: 980px;
}
.timeline li {
border-bottom: 1px solid #d0d5dd;
padding: 10px 0;
}
@media (max-width: 640px) {
main {
padding: 28px;
+2 -21
View File
@@ -1,22 +1,3 @@
import type { ArticleListResponse } from "@pipeline/shared";
import DashboardPage from "@/pages/dashboard";
import { RoleNavigation } from "@/widgets/role-navigation";
const initialArticles: ArticleListResponse = {
articles: [],
};
export default function HomePage() {
return (
<main>
<header className="pageHeader">
<div>
<h1>AI Content Pipeline</h1>
<p>{initialArticles.articles.length} active article workflows</p>
</div>
<span className="roleBadge">Editor demo</span>
</header>
<RoleNavigation role="EDITOR" />
</main>
);
}
export { DashboardPage as default };
@@ -0,0 +1,59 @@
import type { ArticleSummary, TargetSiteConfig } from "@pipeline/shared";
export type DashboardRow = {
id: string;
targetSiteName: string;
workingTitle: string | null;
briefDescription: string;
status: string;
publishingStatus: string;
assignedEditor: string;
updatedAt: string;
nextAction: string;
};
const EMPTY_ASSIGNED_EDITOR_LABEL = "Unassigned";
export function getNextActionForStatus(status: string): string {
if (status === "ARTICLE_BRIEF_CREATED") {
return "Create plan";
}
if (status === "PLAN_DRAFTED") {
return "Run boundary questions";
}
if (status === "PLAN_REVIEWED") {
return "Gather evidence";
}
return "Continue workflow";
}
function getAssignedEditorLabel(article: ArticleSummary): string {
return article.assigned_editor_id ?? EMPTY_ASSIGNED_EDITOR_LABEL;
}
function getTargetSiteName(
article: ArticleSummary,
siteById: Map<string, TargetSiteConfig>,
): string {
const site = siteById.get(article.target_site_id);
return site?.name ?? "Unknown site";
}
export function buildDashboardRows(
articles: readonly ArticleSummary[],
sites: readonly TargetSiteConfig[],
): DashboardRow[] {
const siteById = new Map(sites.map((site) => [site.id, site]));
return articles.map((article) => ({
id: article.id,
targetSiteName: getTargetSiteName(article, siteById),
workingTitle: article.working_title ?? null,
briefDescription: article.brief_description,
status: article.status,
publishingStatus: article.publishing_status,
assignedEditor: getAssignedEditorLabel(article),
updatedAt: article.updated_at,
nextAction: getNextActionForStatus(article.status),
}));
}
@@ -0,0 +1,44 @@
import Link from "next/link";
import type { DashboardRow } from "./model";
type DashboardTableProps = {
rows: readonly DashboardRow[];
};
export function DashboardTable({ rows }: DashboardTableProps) {
if (rows.length === 0) {
return <p className="emptyState">No article workflows yet.</p>;
}
return (
<table className="table">
<thead>
<tr>
<th>Article title</th>
<th>Target website</th>
<th>Status</th>
<th>Assigned editor</th>
<th>Last updated</th>
<th>Next action</th>
<th>Publishing status</th>
</tr>
</thead>
<tbody>
{rows.map((row) => (
<tr key={row.id}>
<td>
<Link href={`/articles/${row.id}`}>{row.workingTitle || row.briefDescription}</Link>
</td>
<td>{row.targetSiteName}</td>
<td>{row.status}</td>
<td>{row.assignedEditor}</td>
<td>{new Date(row.updatedAt).toLocaleString()}</td>
<td>{row.nextAction}</td>
<td>{row.publishingStatus}</td>
</tr>
))}
</tbody>
</table>
);
}
@@ -0,0 +1,42 @@
import type { ArticleDetailResponse, WorkflowEventSummary } from "@pipeline/shared";
export type ArticleTimelineItem = Pick<
WorkflowEventSummary,
"id" | "event_type" | "to_status" | "from_status" | "actor_user_id" | "created_at"
> & {
articleId: string;
};
export type DetailSummary = {
articleId: string;
status: string;
publishingStatus: string;
briefDescription: string;
targetSite: string;
updatedAt: string;
timeline: ArticleTimelineItem[];
};
export function buildArticleTimeline(detail: ArticleDetailResponse): ArticleTimelineItem[] {
return (detail.workflow_events ?? []).map((event) => ({
id: event.id,
event_type: event.event_type,
to_status: event.to_status,
from_status: event.from_status,
actor_user_id: event.actor_user_id,
created_at: event.created_at,
articleId: event.article_id,
}));
}
export function buildDetailSummary(detail: ArticleDetailResponse): DetailSummary {
return {
articleId: detail.article.id,
status: detail.article.status,
publishingStatus: detail.article.publishing_status,
briefDescription: detail.article.brief_description,
targetSite: detail.target_site?.name ?? "Unknown",
updatedAt: detail.article.updated_at,
timeline: buildArticleTimeline(detail),
};
}
@@ -0,0 +1,52 @@
import type { DetailSummary } from "./model";
type DetailShellProps = {
summary: DetailSummary;
};
export function ArticleDetailShell({ summary }: DetailShellProps) {
const timeline = summary.timeline;
return (
<section>
<h2>Article detail</h2>
<dl className="detailGrid">
<div>
<dt>Article ID</dt>
<dd>{summary.articleId}</dd>
</div>
<div>
<dt>Status</dt>
<dd>{summary.status}</dd>
</div>
<div>
<dt>Publishing status</dt>
<dd>{summary.publishingStatus}</dd>
</div>
<div>
<dt>Target site</dt>
<dd>{summary.targetSite}</dd>
</div>
<div>
<dt>Last updated</dt>
<dd>{new Date(summary.updatedAt).toLocaleString()}</dd>
</div>
</dl>
<h3>Brief</h3>
<p>{summary.briefDescription}</p>
<h3>Workflow timeline</h3>
<ul className="timeline">
{timeline.map((event) => (
<li key={event.id}>
<strong>{event.event_type}</strong> from {event.from_status ?? "—"} to{" "}
{event.to_status ?? "—"} at {new Date(event.created_at).toLocaleString()}
{event.actor_user_id ? <span> • actor {event.actor_user_id}</span> : null}
</li>
))}
{timeline.length === 0 ? <li>No workflow events yet.</li> : null}
</ul>
</section>
);
}
@@ -0,0 +1,43 @@
import type { TargetSiteConfig } from "@pipeline/shared";
export type NewArticleDraft = {
targetSiteId: string;
briefDescription: string;
workingTitle: string;
contentType: string;
primaryKeyword: string;
};
export type FieldErrors = Record<string, string>;
export type NewArticleFormState = {
values: NewArticleDraft;
errors: FieldErrors;
formError?: string;
};
export function initialDraft(sites: readonly TargetSiteConfig[]): NewArticleDraft {
return {
targetSiteId: sites.length > 0 ? sites[0].id : "",
briefDescription: "",
workingTitle: "",
contentType: "longform_guide",
primaryKeyword: "",
};
}
export function validateArticleDraft(values: NewArticleDraft): FieldErrors {
const errors: FieldErrors = {};
if (!values.targetSiteId) {
errors.targetSiteId = "Select a target site";
}
if (!values.briefDescription.trim()) {
errors.briefDescription = "Brief description is required";
}
if (!values.contentType.trim()) {
errors.contentType = "Content type is required";
}
return errors;
}
@@ -0,0 +1,131 @@
"use client";
import { useMemo, useState, type FormEvent } from "react";
import { useRouter } from "next/navigation";
import type { TargetSiteConfig } from "@pipeline/shared";
import { ApiError, createArticle } from "@/shared/pipeline-api";
import {
initialDraft,
validateArticleDraft,
type FieldErrors,
type NewArticleDraft,
} from "./model";
type NewArticleFormProps = {
sites: readonly TargetSiteConfig[];
};
export function NewArticleForm({ sites }: NewArticleFormProps) {
const router = useRouter();
const [values, setValues] = useState<NewArticleDraft>(() => initialDraft(sites));
const [errors, setErrors] = useState<FieldErrors>({});
const [formError, setFormError] = useState("");
const [isSubmitting, setSubmitting] = useState(false);
const canSubmit = useMemo(
() => !isSubmitting && sites.length > 0,
[isSubmitting, sites.length],
);
async function handleSubmit(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
const nextErrors = validateArticleDraft(values);
if (Object.keys(nextErrors).length > 0) {
setErrors(nextErrors);
return;
}
setErrors({});
setFormError("");
setSubmitting(true);
try {
const response = await createArticle({
target_site_id: values.targetSiteId,
brief_description: values.briefDescription,
working_title: values.workingTitle || null,
language: "en",
content_type: values.contentType,
primary_keyword: values.primaryKeyword || null,
});
router.push(`/articles/${response.article.id}`);
} catch (error) {
if (error instanceof ApiError) {
setFormError(error.message || "Request failed");
} else {
setFormError("Unable to create article");
}
} finally {
setSubmitting(false);
}
}
function updateField<K extends keyof NewArticleDraft>(field: K, value: NewArticleDraft[K]) {
setValues((current) => ({ ...current, [field]: value }));
}
return (
<form className="articleForm" onSubmit={handleSubmit}>
<h2>Create article brief</h2>
{formError ? <p className="formError">Error: {formError}</p> : null}
<label htmlFor="targetSiteId">Target site</label>
<select
id="targetSiteId"
value={values.targetSiteId}
onChange={(event) => updateField("targetSiteId", event.target.value)}
>
<option value="">Select a site</option>
{sites.map((site) => (
<option key={site.id} value={site.id}>
{site.name}
</option>
))}
</select>
{errors.targetSiteId ? <p className="fieldError">{errors.targetSiteId}</p> : null}
<label htmlFor="briefDescription">Brief description</label>
<textarea
id="briefDescription"
value={values.briefDescription}
onChange={(event) => updateField("briefDescription", event.target.value)}
placeholder="Paste editor brief..."
/>
{errors.briefDescription ? (
<p className="fieldError">{errors.briefDescription}</p>
) : null}
<label htmlFor="workingTitle">Working title (optional)</label>
<input
id="workingTitle"
type="text"
value={values.workingTitle}
onChange={(event) => updateField("workingTitle", event.target.value)}
placeholder="Optional working title"
/>
<label htmlFor="contentType">Content type</label>
<input
id="contentType"
type="text"
value={values.contentType}
onChange={(event) => updateField("contentType", event.target.value)}
/>
{errors.contentType ? <p className="fieldError">{errors.contentType}</p> : null}
<label htmlFor="primaryKeyword">Primary keyword (optional)</label>
<input
id="primaryKeyword"
type="text"
value={values.primaryKeyword}
onChange={(event) => updateField("primaryKeyword", event.target.value)}
/>
<div className="formActions">
<button type="submit" disabled={!canSubmit}>
{isSubmitting ? "Creating..." : "Create article"}
</button>
</div>
</form>
);
}
@@ -0,0 +1,55 @@
import Link from "next/link";
import { RoleNavigation } from "@/widgets/role-navigation";
import {
buildDetailSummary,
} from "@/features/article-detail/model";
import { ArticleDetailShell } from "@/features/article-detail/ui";
import { fetchArticleDetail } from "@/shared/pipeline-api";
import { ApiError } from "@/shared/pipeline-api";
type ArticleDetailPageProps = {
articleId: string;
};
export default async function ArticleDetailPage({
articleId,
}: ArticleDetailPageProps) {
try {
const detail = await fetchArticleDetail(articleId);
const summary = buildDetailSummary(detail);
return (
<main>
<header className="pageHeader">
<div>
<h1>Article detail</h1>
<p>{summary.status}</p>
</div>
<Link href="/">Back to dashboard</Link>
</header>
<RoleNavigation role="EDITOR" />
<section className="panel">
<ArticleDetailShell summary={summary} />
</section>
</main>
);
} catch (error) {
if (error instanceof ApiError && error.status === 404) {
return (
<main>
<header className="pageHeader">
<h1>Article not found</h1>
<Link href="/">Back to dashboard</Link>
</header>
<RoleNavigation role="EDITOR" />
<section className="panel">
<p>The requested article does not exist.</p>
</section>
</main>
);
}
throw error;
}
}
@@ -0,0 +1,27 @@
import type { TargetSiteConfigResponse } from "@pipeline/shared";
import Link from "next/link";
import { RoleNavigation } from "@/widgets/role-navigation";
import { NewArticleForm } from "@/features/article-intake/ui";
import { fetchTargetSites } from "@/shared/pipeline-api";
export default async function NewArticlePage() {
const sites: TargetSiteConfigResponse[] = await fetchTargetSites();
const targetSites = sites.map((site) => site.site);
return (
<main>
<header className="pageHeader">
<div>
<h1>New Article</h1>
<p>Draft a new editorial brief for an existing site.</p>
</div>
<Link href="/">Back to dashboard</Link>
</header>
<RoleNavigation role="EDITOR" />
<section className="panel">
<NewArticleForm sites={targetSites} />
</section>
</main>
);
}
@@ -0,0 +1,37 @@
import Link from "next/link";
import type { ArticleListResponse, TargetSiteConfigResponse } from "@pipeline/shared";
import { RoleNavigation } from "@/widgets/role-navigation";
import { buildDashboardRows } from "@/features/article-dashboard/model";
import { DashboardTable } from "@/features/article-dashboard/ui";
import { fetchArticles, fetchTargetSites } from "@/shared/pipeline-api";
export default async function DashboardPage() {
const [articlesResponse, sitesResponse]: [
ArticleListResponse,
TargetSiteConfigResponse[],
] = await Promise.all([fetchArticles(), fetchTargetSites()]);
const rows = buildDashboardRows(
articlesResponse.articles,
sitesResponse.map((site) => site.site),
);
return (
<main>
<header className="pageHeader">
<div>
<h1>AI Content Pipeline</h1>
<p>{rows.length} active article workflows</p>
</div>
<Link href="/articles/new">New article</Link>
<span className="roleBadge">Editor demo</span>
</header>
<RoleNavigation role="EDITOR" />
<section className="panel">
<DashboardTable rows={rows} />
</section>
</main>
);
}
+148
View File
@@ -0,0 +1,148 @@
import type {
ArticleCreateRequest,
ArticleCreateResponse,
ArticleDetailResponse,
ArticleListResponse,
CurrentUserResponse,
TargetSiteConfigResponse,
} from "@pipeline/shared";
export const DEMO_EDITOR_EMAIL = "editor@example.com";
const DEFAULT_LOCAL_BACKEND_URL = "http://localhost:8000";
export type ApiErrorPayload = {
status: number;
message: string;
detail?: unknown;
};
export class ApiError extends Error {
status: number;
detail?: unknown;
constructor(payload: ApiErrorPayload) {
super(payload.message);
this.name = "ApiError";
this.status = payload.status;
this.detail = payload.detail;
}
}
function resolveBackendBaseUrl(): string {
if (typeof window === "undefined") {
return process.env.BACKEND_URL ?? process.env.NEXT_PUBLIC_BACKEND_URL ?? DEFAULT_LOCAL_BACKEND_URL;
}
return (
process.env.NEXT_PUBLIC_BACKEND_URL ??
process.env.BACKEND_URL ??
""
);
}
function buildApiUrl(path: string): string {
const normalizedPath = path.startsWith("/") ? path : `/${path}`;
const base = resolveBackendBaseUrl();
if (!base || base === "/") {
return normalizedPath;
}
return `${base.replace(/\/$/, "")}${normalizedPath}`;
}
async function parseBody(response: Response): Promise<unknown> {
const text = await response.text();
if (!text) {
return null;
}
try {
return JSON.parse(text);
} catch {
return text;
}
}
async function requestJson<T>(
path: string,
options: RequestInit = {},
): Promise<T> {
const isFormData = options.body instanceof FormData;
const response = await fetch(buildApiUrl(path), {
...options,
headers: {
...(!isFormData
? { "Content-Type": "application/json" }
: {}),
"X-Demo-User-Email": DEMO_EDITOR_EMAIL,
...(options.headers ?? {}),
},
cache: options.cache ?? "no-store",
});
const body = await parseBody(response);
if (!response.ok) {
const message =
typeof body === "object" && body !== null && "detail" in body
? String((body as { detail?: unknown }).detail)
: response.statusText;
throw new ApiError({
status: response.status,
message,
detail: body,
});
}
return body as T;
}
export function apiGet<T>(path: string): Promise<T> {
return requestJson<T>(path, { method: "GET" });
}
export function apiPost<TRequest, TResponse>(
path: string,
body: TRequest,
): Promise<TResponse> {
return requestJson<TResponse>(path, {
method: "POST",
body: JSON.stringify(body),
});
}
export function apiPatch<TRequest, TResponse>(
path: string,
body: TRequest,
): Promise<TResponse> {
return requestJson<TResponse>(path, {
method: "PATCH",
body: JSON.stringify(body),
});
}
export function fetchCurrentUser(): Promise<CurrentUserResponse> {
return apiGet("/api/me");
}
export function fetchTargetSites(): Promise<TargetSiteConfigResponse[]> {
return apiGet<TargetSiteConfigResponse[]>("/api/sites");
}
export function fetchArticles(): Promise<ArticleListResponse> {
return apiGet<ArticleListResponse>("/api/articles");
}
export function fetchArticleDetail(
articleId: string,
): Promise<ArticleDetailResponse> {
return apiGet<ArticleDetailResponse>(`/api/articles/${articleId}`);
}
export function createArticle(
request: ArticleCreateRequest,
): Promise<ArticleCreateResponse> {
return apiPost<ArticleCreateRequest, ArticleCreateResponse>(
"/api/articles",
request,
);
}
@@ -0,0 +1,63 @@
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import ts from "typescript";
const testDir = path.dirname(fileURLToPath(import.meta.url));
const sourcePath = path.resolve(
testDir,
"../src/features/article-dashboard/model.ts",
);
const source = readFileSync(sourcePath, "utf8");
const compiled = ts.transpileModule(source, {
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 },
});
const moduleExports = {};
new Function("exports", compiled.outputText)(moduleExports);
const { buildDashboardRows } = moduleExports;
const rows = buildDashboardRows(
[
{
id: "11111111-1111-1111-1111-111111111111",
target_site_id: "22222222-2222-2222-2222-222222222222",
status: "ARTICLE_BRIEF_CREATED",
publishing_status: "PUBLISH_NOT_STARTED",
brief_description: "Build AI article intake shell",
working_title: "AI Intake Shell",
language: "en",
content_type: "longform_guide",
primary_keyword: "AI workflow",
assigned_editor_id: null,
created_at: "2025-01-01T00:00:00Z",
updated_at: "2025-01-01T00:00:00Z",
},
],
[
{
id: "22222222-2222-2222-2222-222222222222",
name: "Editorial site",
slug: "editorial-site",
publishing_type: "git_next",
default_language: "en",
brand_voice: "Balanced",
audience: "Editor teams",
seo_rules: {},
visual_rules: {},
source_rules: {},
publishing_rules: {},
active_script_config_version_id: null,
created_at: "2025-01-01T00:00:00Z",
updated_at: "2025-01-01T00:00:00Z",
},
],
);
assert.equal(rows.length, 1, "one row should be built");
assert.equal(rows[0].targetSiteName, "Editorial site", "target site name should map");
assert.equal(rows[0].nextAction, "Create plan", "next action should match status mapping");
assert.equal(rows[0].assignedEditor, "Unassigned", "missing editor id should render Unassigned");
@@ -0,0 +1,45 @@
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import ts from "typescript";
const testDir = path.dirname(fileURLToPath(import.meta.url));
const sourcePath = path.resolve(
testDir,
"../src/features/article-intake/model.ts",
);
const source = readFileSync(sourcePath, "utf8");
const compiled = ts.transpileModule(source, {
compilerOptions: {
module: ts.ModuleKind.CommonJS,
target: ts.ScriptTarget.ES2022,
},
});
const moduleExports = {};
new Function("exports", compiled.outputText)(moduleExports);
const validateArticleDraft = moduleExports.validateArticleDraft;
const initialDraft = moduleExports.initialDraft;
const draft = {
targetSiteId: "",
briefDescription: "Keep this text intact",
workingTitle: "",
contentType: "longform_guide",
primaryKeyword: "",
};
const errors = validateArticleDraft(draft);
assert.ok(errors.targetSiteId, "validation should require target site");
assert.equal(
draft.briefDescription,
"Keep this text intact",
"brief description value should remain in form state when validation fails",
);
const fallbackDraft = initialDraft([]);
assert.equal(fallbackDraft.contentType, "longform_guide", "default content type preserved");