stage2-2 and docs

This commit is contained in:
alorig
2025-11-19 21:19:53 +05:00
parent 72e1f25bc7
commit 52c9c9f3d5
14 changed files with 1259 additions and 347 deletions

View File

@@ -93,6 +93,7 @@ const SiteSettings = lazy(() => import("./pages/Sites/Settings"));
// Site Builder - Lazy loaded (will be moved from separate container)
const SiteBuilderWizard = lazy(() => import("./pages/Sites/Builder/Wizard"));
const WorkflowWizard = lazy(() => import("./pages/Sites/Builder/WorkflowWizard"));
const SiteBuilderPreview = lazy(() => import("./pages/Sites/Builder/Preview"));
const SiteBuilderBlueprints = lazy(() => import("./pages/Sites/Builder/Blueprints"));
@@ -520,6 +521,11 @@ export default function App() {
<SiteBuilderWizard />
</Suspense>
} />
<Route path="/sites/builder/workflow/:blueprintId" element={
<Suspense fallback={null}>
<WorkflowWizard />
</Suspense>
} />
<Route path="/sites/builder/preview" element={
<Suspense fallback={null}>
<SiteBuilderPreview />

View File

@@ -0,0 +1,111 @@
/**
* Site Builder Workflow Wizard (Stage 2)
* Self-guided wizard with state-aware gating and progress tracking
*/
import { useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { useBuilderWorkflowStore, WizardStep } from '../../../store/builderWorkflowStore';
import WizardProgress from './components/WizardProgress';
import BusinessDetailsStep from './steps/BusinessDetailsStep';
import ClusterAssignmentStep from './steps/ClusterAssignmentStep';
import TaxonomyBuilderStep from './steps/TaxonomyBuilderStep';
import SitemapReviewStep from './steps/SitemapReviewStep';
import CoverageValidationStep from './steps/CoverageValidationStep';
import IdeasHandoffStep from './steps/IdeasHandoffStep';
import Alert from '../../../components/ui/alert/Alert';
import PageMeta from '../../../components/common/PageMeta';
import { Loader2 } from 'lucide-react';
const STEP_COMPONENTS: Record<WizardStep, React.ComponentType> = {
business_details: BusinessDetailsStep,
clusters: ClusterAssignmentStep,
taxonomies: TaxonomyBuilderStep,
sitemap: SitemapReviewStep,
coverage: CoverageValidationStep,
ideas: IdeasHandoffStep,
};
const STEP_LABELS: Record<WizardStep, string> = {
business_details: 'Business Details',
clusters: 'Cluster Assignment',
taxonomies: 'Taxonomy Builder',
sitemap: 'AI Sitemap Review',
coverage: 'Coverage Validation',
ideas: 'Ideas Hand-off',
};
export default function WorkflowWizard() {
const { blueprintId } = useParams<{ blueprintId: string }>();
const navigate = useNavigate();
const {
blueprintId: storeBlueprintId,
currentStep,
loading,
error,
context,
initialize,
refreshState,
} = useBuilderWorkflowStore();
const id = blueprintId ? parseInt(blueprintId, 10) : null;
useEffect(() => {
if (id && id !== storeBlueprintId) {
initialize(id);
}
}, [id, storeBlueprintId, initialize]);
useEffect(() => {
// Refresh state periodically to keep it in sync
if (id && storeBlueprintId === id) {
const interval = setInterval(() => {
refreshState();
}, 10000); // Refresh every 10 seconds
return () => clearInterval(interval);
}
}, [id, storeBlueprintId, refreshState]);
if (!id) {
return (
<div className="p-6">
<Alert variant="error">Invalid blueprint ID</Alert>
</div>
);
}
if (loading && !context) {
return (
<div className="flex items-center justify-center min-h-screen">
<Loader2 className="h-8 w-8 animate-spin text-primary" />
</div>
);
}
if (error) {
return (
<div className="p-6">
<Alert variant="error">{error}</Alert>
</div>
);
}
const StepComponent = STEP_COMPONENTS[currentStep];
return (
<div className="min-h-screen bg-gray-50 dark:bg-gray-900">
<PageMeta title={`Site Builder - ${STEP_LABELS[currentStep]}`} />
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
{/* Progress Indicator */}
<WizardProgress currentStep={currentStep} />
{/* Main Content */}
<div className="mt-8">
{StepComponent && <StepComponent blueprintId={id} />}
</div>
</div>
</div>
);
}

View File

@@ -0,0 +1,102 @@
/**
* Wizard Progress Indicator
* Shows breadcrumb with step completion status
*/
import { useBuilderWorkflowStore, WizardStep } from '../../../../store/builderWorkflowStore';
import { CheckCircle2, Circle } from 'lucide-react';
const STEPS: Array<{ key: WizardStep; label: string }> = [
{ key: 'business_details', label: 'Business Details' },
{ key: 'clusters', label: 'Clusters' },
{ key: 'taxonomies', label: 'Taxonomies' },
{ key: 'sitemap', label: 'Sitemap' },
{ key: 'coverage', label: 'Coverage' },
{ key: 'ideas', label: 'Ideas' },
];
interface WizardProgressProps {
currentStep: WizardStep;
}
export default function WizardProgress({ currentStep }: WizardProgressProps) {
const { completedSteps, blockingIssues } = useBuilderWorkflowStore();
const currentIndex = STEPS.findIndex(s => s.key === currentStep);
return (
<div className="bg-white dark:bg-gray-800 rounded-lg shadow-sm p-6">
<nav aria-label="Progress">
<ol className="flex items-center justify-between">
{STEPS.map((step, index) => {
const isCompleted = completedSteps.has(step.key);
const isCurrent = step.key === currentStep;
const isBlocked = blockingIssues.some(issue => issue.step === step.key);
const isAccessible = index <= currentIndex || isCompleted;
return (
<li key={step.key} className="flex-1 flex items-center">
<div className="flex items-center w-full">
{/* Step Circle */}
<div className="flex flex-col items-center flex-1">
<div
className={`
flex items-center justify-center w-10 h-10 rounded-full border-2
${
isCompleted
? 'bg-green-500 border-green-500 text-white'
: isCurrent
? 'bg-primary border-primary text-white'
: isBlocked
? 'bg-red-100 border-red-500 text-red-500'
: isAccessible
? 'bg-gray-100 border-gray-300 text-gray-600'
: 'bg-gray-50 border-gray-200 text-gray-400'
}
`}
>
{isCompleted ? (
<CheckCircle2 className="w-6 h-6" />
) : (
<span className="text-sm font-semibold">{index + 1}</span>
)}
</div>
<span
className={`
mt-2 text-xs font-medium text-center
${
isCurrent
? 'text-primary'
: isBlocked
? 'text-red-600'
: isAccessible
? 'text-gray-600'
: 'text-gray-400'
}
`}
>
{step.label}
</span>
</div>
{/* Connector Line */}
{index < STEPS.length - 1 && (
<div
className={`
flex-1 h-0.5 mx-2
${
isCompleted || (index < currentIndex)
? 'bg-green-500'
: 'bg-gray-200'
}
`}
/>
)}
</div>
</li>
);
})}
</ol>
</nav>
</div>
);
}

View File

@@ -1,363 +1,151 @@
import { useMemo, useRef, useState } from "react";
import type {
BuilderFormData,
SiteBuilderMetadata,
} from "../../../../types/siteBuilder";
import { Card } from "../../../../components/ui/card";
import { useSiteStore } from "../../../../store/siteStore";
import { Dropdown } from "../../../../components/ui/dropdown/Dropdown";
import { Check } from "lucide-react";
/**
* Step 1: Business Details
* Site type selection, hosting detection, brand inputs
*/
import { useState, useEffect } from 'react';
import { useBuilderWorkflowStore } from '../../../../store/builderWorkflowStore';
import { fetchSiteBlueprintById, updateSiteBlueprint, SiteBlueprint } from '../../../../services/api';
import { Card, CardDescription, CardTitle } from '../../../../components/ui/card';
import Button from '../../../../components/ui/button/Button';
import Input from '../../../../components/ui/input/Input';
import Alert from '../../../../components/ui/alert/Alert';
import { Loader2 } from 'lucide-react';
const inputClass =
"h-11 w-full rounded-xl border border-gray-200 bg-white px-4 text-sm font-medium text-gray-900 placeholder:text-gray-400 focus:border-brand-300 focus:outline-hidden focus:ring-3 focus:ring-brand-500/10 dark:border-white/10 dark:bg-white/[0.03] dark:text-white/90 dark:placeholder:text-white/30 dark:focus:border-brand-800";
const labelClass =
"text-sm font-semibold text-gray-700 dark:text-white/80 mb-2 inline-block";
interface Props {
data: BuilderFormData;
metadata?: SiteBuilderMetadata;
selectedSectors: Array<{ id: number; name: string }>;
onChange: <K extends keyof BuilderFormData>(
key: K,
value: BuilderFormData[K],
) => void;
interface BusinessDetailsStepProps {
blueprintId: number;
}
export function BusinessDetailsStep({
data,
metadata,
selectedSectors,
onChange,
}: Props) {
const { activeSite } = useSiteStore();
const [businessDropdownOpen, setBusinessDropdownOpen] = useState(false);
const businessButtonRef = useRef<HTMLButtonElement>(null);
const [audienceDropdownOpen, setAudienceDropdownOpen] = useState(false);
const audienceButtonRef = useRef<HTMLButtonElement>(null);
export default function BusinessDetailsStep({ blueprintId }: BusinessDetailsStepProps) {
const { context, completeStep, loading } = useBuilderWorkflowStore();
const [blueprint, setBlueprint] = useState<SiteBlueprint | null>(null);
const [formData, setFormData] = useState({
name: '',
description: '',
hosting_type: 'igny8_sites' as const,
business_type: '',
});
const [saving, setSaving] = useState(false);
const [error, setError] = useState<string | null>(null);
const businessOptions = metadata?.business_types ?? [];
const audienceOptions = metadata?.audience_profiles ?? [];
useEffect(() => {
// Load blueprint data
fetchSiteBlueprintById(blueprintId)
.then(setBlueprint)
.catch(err => setError(err.message));
}, [blueprintId]);
const selectedBusinessType = businessOptions.find(
(option) => option.id === data.businessTypeId,
);
const selectedAudienceOptions = useMemo(
() =>
audienceOptions.filter((option) =>
data.targetAudienceIds.includes(option.id),
),
[audienceOptions, data.targetAudienceIds],
);
const computeAudienceSummary = (
ids: number[],
custom?: string,
): string => {
const names = audienceOptions
.filter((option) => ids.includes(option.id))
.map((option) => option.name);
if (custom?.trim()) {
names.push(custom.trim());
useEffect(() => {
if (blueprint) {
setFormData({
name: blueprint.name || '',
description: blueprint.description || '',
hosting_type: (blueprint.hosting_type as any) || 'igny8_sites',
business_type: blueprint.config_json?.business_type || '',
});
}
}, [blueprint]);
const handleSave = async () => {
setSaving(true);
setError(null);
try {
const updated = await updateSiteBlueprint(blueprintId, {
name: formData.name,
description: formData.description,
hosting_type: formData.hosting_type,
config_json: {
...blueprint?.config_json,
business_type: formData.business_type,
},
});
setBlueprint(updated);
// Mark step as complete
await completeStep('business_details', {
blueprint_name: formData.name,
hosting_type: formData.hosting_type,
});
} catch (err: any) {
setError(err.message || 'Failed to save business details');
} finally {
setSaving(false);
}
return names.join(", ");
};
const toggleAudience = (audienceId: number) => {
const isSelected = data.targetAudienceIds.includes(audienceId);
const next = isSelected
? data.targetAudienceIds.filter((id) => id !== audienceId)
: [...data.targetAudienceIds, audienceId];
onChange("targetAudienceIds", next);
onChange("targetAudience", computeAudienceSummary(next, data.customTargetAudience));
};
const handleCustomAudienceChange = (value: string) => {
onChange("customTargetAudience", value);
onChange("targetAudience", computeAudienceSummary(data.targetAudienceIds, value));
};
const handleCustomBusinessTypeChange = (value: string) => {
onChange("customBusinessType", value);
onChange("businessTypeId", null);
onChange("businessType", value);
};
const canProceed = formData.name.trim().length > 0;
return (
<div className="space-y-6">
<Card variant="panel" padding="lg">
<div className="flex flex-col gap-2">
<p className="text-xs font-semibold uppercase tracking-wider text-gray-500 dark:text-white/50">
Context
</p>
<h3 className="text-lg font-semibold text-gray-900 dark:text-white">
Site &amp; sectors
</h3>
<p className="text-sm text-gray-500 dark:text-gray-400">
IGNY8 will generate a blueprint for every sector configured on this site.
</p>
</div>
<div className="mt-4 grid grid-cols-1 gap-4 md:grid-cols-2">
<div className="rounded-2xl border border-brand-100 bg-brand-50/60 p-4 dark:border-brand-500/40 dark:bg-brand-500/10">
<p className="text-xs uppercase tracking-wide text-brand-600 dark:text-brand-300">
Active site
</p>
<p className="text-base font-semibold text-brand-700 dark:text-brand-200">
{activeSite?.name ?? "No site selected"}
</p>
</div>
<div className="rounded-2xl border border-indigo-100 bg-indigo-50/60 p-4 dark:border-indigo-500/40 dark:bg-indigo-500/10">
<p className="text-xs uppercase tracking-wide text-indigo-600 dark:text-indigo-300">
Included sectors
</p>
{selectedSectors.length > 0 ? (
<div className="flex flex-wrap gap-2 pt-2">
{selectedSectors.map((sector) => (
<span
key={sector.id}
className="inline-flex items-center rounded-full bg-white px-3 py-1 text-xs font-semibold text-indigo-700 dark:bg-indigo-500/20 dark:text-indigo-100"
>
{sector.name}
</span>
))}
</div>
) : (
<p className="text-sm font-semibold text-indigo-700 dark:text-indigo-200">
No sectors configured for this site
</p>
)}
</div>
</div>
</Card>
<Card className="p-6">
<CardTitle>Business Details</CardTitle>
<CardDescription>
Tell us about your business and site type to get started.
</CardDescription>
<Card variant="surface" padding="lg">
<div className="grid grid-cols-1 gap-6 md:grid-cols-2">
<div>
<label className={labelClass}>Site name</label>
<input
className={inputClass}
type="text"
value={data.siteName}
placeholder="Acme Robotics"
onChange={(event) => onChange("siteName", event.target.value)}
/>
</div>
<div>
<label className={labelClass}>Hosting preference</label>
<select
className={inputClass}
value={data.hostingType}
onChange={(event) =>
onChange(
"hostingType",
event.target.value as BuilderFormData["hostingType"],
)
}
>
<option value="igny8_sites">IGNY8 Sites</option>
<option value="wordpress">WordPress</option>
<option value="shopify">Shopify</option>
<option value="multi">Multiple destinations</option>
</select>
</div>
</div>
{error && (
<Alert variant="error" className="mt-4">
{error}
</Alert>
)}
<div className="mt-6 grid grid-cols-1 gap-6 md:grid-cols-2">
<div>
<label className={labelClass}>Business type</label>
<button
ref={businessButtonRef}
type="button"
onClick={() => setBusinessDropdownOpen((open) => !open)}
className="dropdown-toggle flex w-full items-center justify-between rounded-xl border border-gray-200 bg-white px-4 py-3 text-sm font-medium text-gray-900 transition hover:border-brand-200 dark:border-white/10 dark:bg-white/[0.02] dark:text-white/90"
>
<span>
{selectedBusinessType?.name ||
"Select a business type from the library"}
</span>
<svg
className="h-4 w-4 text-gray-500 dark:text-gray-400"
viewBox="0 0 20 20"
fill="currentColor"
>
<path
fillRule="evenodd"
d="M5.23 7.21a.75.75 0 011.06.02L10 10.94l3.71-3.71a.75.75 0 111.08 1.04l-4.25 4.25a.75.75 0 01-1.08 0L5.21 8.27a.75.75 0 01.02-1.06z"
clipRule="evenodd"
/>
</svg>
</button>
<Dropdown
isOpen={businessDropdownOpen}
onClose={() => setBusinessDropdownOpen(false)}
anchorRef={businessButtonRef}
placement="bottom-left"
className="w-72 max-h-72 overflow-y-auto p-2"
>
{businessOptions.length === 0 ? (
<div className="px-3 py-2 text-sm text-gray-500">
No business types defined yet.
</div>
) : (
businessOptions.map((option) => {
const isSelected = option.id === data.businessTypeId;
return (
<button
key={option.id}
type="button"
onClick={() => {
onChange("businessTypeId", option.id);
onChange("businessType", option.name);
onChange("customBusinessType", "");
setBusinessDropdownOpen(false);
}}
className={`flex w-full items-start gap-3 rounded-xl px-3 py-2 text-left text-sm ${
isSelected
? "bg-brand-50 text-brand-700 dark:bg-brand-500/10 dark:text-brand-100"
: "text-gray-700 hover:bg-gray-100 dark:text-white/80 dark:hover:bg-white/10"
}`}
>
<span className="flex-1">
<span className="font-semibold">{option.name}</span>
{option.description && (
<span className="block text-xs text-gray-500 dark:text-gray-400">
{option.description}
</span>
)}
</span>
{isSelected && <Check className="h-4 w-4" />}
</button>
);
})
)}
</Dropdown>
<input
className={`${inputClass} mt-3`}
type="text"
value={data.customBusinessType ?? ""}
placeholder="Or describe a custom business model"
onChange={(event) =>
handleCustomBusinessTypeChange(event.target.value)
}
/>
</div>
<div>
<label className={labelClass}>Industry (from site settings)</label>
<div className="flex h-11 items-center rounded-xl border border-gray-100 bg-gray-50 px-4 text-sm font-semibold text-gray-700 dark:border-white/10 dark:bg-white/[0.05] dark:text-white/80">
{data.industry || "No industry selected"}
</div>
</div>
</div>
</Card>
<Card variant="surface" padding="lg">
<div className="space-y-4">
<div>
<label className={labelClass}>Target audience</label>
<p className="text-xs text-gray-500 dark:text-gray-400">
Choose one or more audience profiles from the IGNY8 library. Add your own if needed.
</p>
</div>
<div>
<button
ref={audienceButtonRef}
type="button"
onClick={() => setAudienceDropdownOpen((open) => !open)}
className="dropdown-toggle flex w-full items-center justify-between rounded-xl border border-gray-200 bg-white px-4 py-3 text-sm font-medium text-gray-900 transition hover:border-brand-200 dark:border-white/10 dark:bg-white/[0.02] dark:text-white/90"
>
<span>
{selectedAudienceOptions.length > 0
? `${selectedAudienceOptions.length} audience${
selectedAudienceOptions.length > 1 ? "s" : ""
} selected`
: "Select audiences to focus the messaging"}
</span>
<svg
className="h-4 w-4 text-gray-500 dark:text-gray-400"
viewBox="0 0 20 20"
fill="currentColor"
>
<path
fillRule="evenodd"
d="M5.23 7.21a.75.75 0 011.06.02L10 10.94l3.71-3.71a.75.75 0 111.08 1.04l-4.25 4.25a.75.75 0 01-1.08 0L5.21 8.27a.75.75 0 01.02-1.06z"
clipRule="evenodd"
/>
</svg>
</button>
<Dropdown
isOpen={audienceDropdownOpen}
onClose={() => setAudienceDropdownOpen(false)}
anchorRef={audienceButtonRef}
placement="bottom-left"
className="w-80 max-h-80 overflow-y-auto p-2"
>
{audienceOptions.length === 0 ? (
<div className="px-3 py-2 text-sm text-gray-500">
No audience profiles defined yet.
</div>
) : (
audienceOptions.map((option) => {
const isSelected = data.targetAudienceIds.includes(option.id);
return (
<button
key={option.id}
type="button"
onClick={() => toggleAudience(option.id)}
className={`flex w-full items-start gap-3 rounded-xl px-3 py-2 text-left text-sm ${
isSelected
? "bg-brand-50 text-brand-700 dark:bg-brand-500/10 dark:text-brand-100"
: "text-gray-700 hover:bg-gray-100 dark:text-white/80 dark:hover:bg-white/10"
}`}
>
<span className="flex-1">
<span className="font-semibold">{option.name}</span>
{option.description && (
<span className="block text-xs text-gray-500 dark:text-gray-400">
{option.description}
</span>
)}
</span>
{isSelected && <Check className="h-4 w-4" />}
</button>
);
})
)}
</Dropdown>
</div>
<div className="flex flex-wrap gap-2">
{selectedAudienceOptions.map((option) => (
<span
key={option.id}
className="inline-flex items-center gap-2 rounded-full bg-brand-50 px-3 py-1 text-xs font-semibold text-brand-700 dark:bg-brand-500/10 dark:text-brand-100"
>
{option.name}
<button
type="button"
className="text-brand-600 hover:text-brand-800 dark:text-brand-200 dark:hover:text-brand-50"
onClick={() => toggleAudience(option.id)}
aria-label={`Remove ${option.name}`}
>
×
</button>
</span>
))}
{data.customTargetAudience?.trim() && (
<span className="inline-flex items-center rounded-full bg-gray-100 px-3 py-1 text-xs font-semibold text-gray-700 dark:bg-white/10 dark:text-white/80">
{data.customTargetAudience.trim()}
</span>
)}
</div>
<input
className={inputClass}
type="text"
value={data.customTargetAudience ?? ""}
placeholder="Add custom audience (e.g., Healthcare innovators)"
onChange={(event) => handleCustomAudienceChange(event.target.value)}
<div className="mt-6 space-y-4">
<div>
<label className="block text-sm font-medium mb-2">Site Name *</label>
<Input
value={formData.name}
onChange={(e) => setFormData({ ...formData, name: e.target.value })}
placeholder="My Awesome Site"
required
/>
</div>
</Card>
</div>
<div>
<label className="block text-sm font-medium mb-2">Description</label>
<textarea
value={formData.description}
onChange={(e) => setFormData({ ...formData, description: e.target.value })}
className="w-full px-3 py-2 border rounded-md"
rows={3}
placeholder="Brief description of your site..."
/>
</div>
<div>
<label className="block text-sm font-medium mb-2">Hosting Type</label>
<select
value={formData.hosting_type}
onChange={(e) => setFormData({ ...formData, hosting_type: e.target.value as any })}
className="w-full px-3 py-2 border rounded-md"
>
<option value="igny8_sites">IGNY8 Sites</option>
<option value="wordpress">WordPress</option>
<option value="shopify">Shopify</option>
<option value="multi">Multiple Destinations</option>
</select>
</div>
</div>
<div className="mt-6 flex justify-end">
<Button
onClick={handleSave}
disabled={!canProceed || saving || loading}
variant="primary"
>
{saving ? (
<>
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
Saving...
</>
) : (
'Save & Continue'
)}
</Button>
</div>
{!canProceed && (
<Alert variant="warning" className="mt-4">
Please provide a site name to continue.
</Alert>
)}
</Card>
);
}

View File

@@ -0,0 +1,70 @@
/**
* Step 2: Cluster Assignment
* Select/attach planner clusters with coverage metrics
*/
import { useBuilderWorkflowStore } from '../../../../store/builderWorkflowStore';
import { Card, CardDescription, CardTitle } from '../../../../components/ui/card';
import Button from '../../../../components/ui/button/Button';
import Alert from '../../../../components/ui/alert/Alert';
interface ClusterAssignmentStepProps {
blueprintId: number;
}
export default function ClusterAssignmentStep({ blueprintId }: ClusterAssignmentStepProps) {
const { context, completeStep, blockingIssues } = useBuilderWorkflowStore();
const clusterBlocking = blockingIssues.find(issue => issue.step === 'clusters');
return (
<Card className="p-6">
<CardTitle>Cluster Assignment</CardTitle>
<CardDescription>
Attach keyword clusters from Planner to drive your sitemap structure.
</CardDescription>
{clusterBlocking && (
<Alert variant="error" className="mt-4">
{clusterBlocking.message}
</Alert>
)}
{context?.cluster_summary && (
<div className="mt-6">
<div className="grid grid-cols-3 gap-4 mb-6">
<div className="bg-gray-50 dark:bg-gray-800 p-4 rounded-lg">
<div className="text-sm text-gray-600 dark:text-gray-400">Total Clusters</div>
<div className="text-2xl font-bold">{context.cluster_summary.total}</div>
</div>
<div className="bg-gray-50 dark:bg-gray-800 p-4 rounded-lg">
<div className="text-sm text-gray-600 dark:text-gray-400">Attached</div>
<div className="text-2xl font-bold">{context.cluster_summary.attached}</div>
</div>
<div className="bg-gray-50 dark:bg-gray-800 p-4 rounded-lg">
<div className="text-sm text-gray-600 dark:text-gray-400">Coverage</div>
<div className="text-2xl font-bold">
{context.cluster_summary.coverage_stats.complete} / {context.cluster_summary.total}
</div>
</div>
</div>
{/* TODO: Add cluster selection table/list UI */}
<Alert variant="info" className="mt-4">
Cluster selection UI coming in next iteration. Use Planner Clusters to manage clusters first.
</Alert>
</div>
)}
<div className="mt-6 flex justify-end">
<Button
onClick={() => completeStep('clusters')}
disabled={!!clusterBlocking}
variant="primary"
>
Continue
</Button>
</div>
</Card>
);
}

View File

@@ -0,0 +1,52 @@
/**
* Step 5: Coverage Validation
* Validate cluster/taxonomy coverage before proceeding
*/
import { useBuilderWorkflowStore } from '../../../../store/builderWorkflowStore';
import { Card, CardDescription, CardTitle } from '../../../../components/ui/card';
import Button from '../../../../components/ui/button/Button';
import Alert from '../../../../components/ui/alert/Alert';
interface CoverageValidationStepProps {
blueprintId: number;
}
export default function CoverageValidationStep({ blueprintId }: CoverageValidationStepProps) {
const { context, completeStep, blockingIssues } = useBuilderWorkflowStore();
const coverageBlocking = blockingIssues.find(issue => issue.step === 'coverage');
return (
<Card className="p-6">
<CardTitle>Coverage Validation</CardTitle>
<CardDescription>
Ensure all clusters and taxonomies have proper coverage.
</CardDescription>
{coverageBlocking && (
<Alert variant="error" className="mt-4">
{coverageBlocking.message}
</Alert>
)}
{context && (
<div className="mt-6 space-y-4">
{/* TODO: Add coverage summary cards */}
<Alert variant="info">
Coverage validation UI coming in next iteration.
</Alert>
</div>
)}
<div className="mt-6 flex justify-end">
<Button
onClick={() => completeStep('coverage')}
disabled={!!coverageBlocking}
variant="primary"
>
Continue
</Button>
</div>
</Card>
);
}

View File

@@ -0,0 +1,52 @@
/**
* Step 6: Ideas Hand-off
* Select pages to push to Planner Ideas
*/
import { useBuilderWorkflowStore } from '../../../../store/builderWorkflowStore';
import { Card, CardDescription, CardTitle } from '../../../../components/ui/card';
import Button from '../../../../components/ui/button/Button';
import Alert from '../../../../components/ui/alert/Alert';
interface IdeasHandoffStepProps {
blueprintId: number;
}
export default function IdeasHandoffStep({ blueprintId }: IdeasHandoffStepProps) {
const { context, completeStep, blockingIssues } = useBuilderWorkflowStore();
const ideasBlocking = blockingIssues.find(issue => issue.step === 'ideas');
return (
<Card className="p-6">
<CardTitle>Ideas Hand-off</CardTitle>
<CardDescription>
Select pages to send to Planner Ideas for content generation.
</CardDescription>
{ideasBlocking && (
<Alert variant="error" className="mt-4">
{ideasBlocking.message}
</Alert>
)}
{context && (
<div className="mt-6">
{/* TODO: Add page selection UI */}
<Alert variant="info">
Ideas hand-off UI coming in next iteration.
</Alert>
</div>
)}
<div className="mt-6 flex justify-end">
<Button
onClick={() => completeStep('ideas')}
disabled={!!ideasBlocking}
variant="primary"
>
Complete Wizard
</Button>
</div>
</Card>
);
}

View File

@@ -0,0 +1,55 @@
/**
* Step 4: AI Sitemap Review
* Review and edit AI-generated sitemap
*/
import { useBuilderWorkflowStore } from '../../../../store/builderWorkflowStore';
import { Card, CardDescription, CardTitle } from '../../../../components/ui/card';
import Button from '../../../../components/ui/button/Button';
import Alert from '../../../../components/ui/alert/Alert';
interface SitemapReviewStepProps {
blueprintId: number;
}
export default function SitemapReviewStep({ blueprintId }: SitemapReviewStepProps) {
const { context, completeStep, blockingIssues } = useBuilderWorkflowStore();
const sitemapBlocking = blockingIssues.find(issue => issue.step === 'sitemap');
return (
<Card className="p-6">
<CardTitle>AI Sitemap Review</CardTitle>
<CardDescription>
Review and adjust the AI-generated site structure.
</CardDescription>
{sitemapBlocking && (
<Alert variant="error" className="mt-4">
{sitemapBlocking.message}
</Alert>
)}
{context?.sitemap_summary && (
<div className="mt-6">
<div className="text-sm text-gray-600 dark:text-gray-400 mb-2">
Total Pages: {context.sitemap_summary.total_pages}
</div>
{/* TODO: Add sitemap grid/table UI */}
<Alert variant="info" className="mt-4">
Sitemap review UI coming in next iteration.
</Alert>
</div>
)}
<div className="mt-6 flex justify-end">
<Button
onClick={() => completeStep('sitemap')}
disabled={!!sitemapBlocking}
variant="primary"
>
Continue
</Button>
</div>
</Card>
);
}

View File

@@ -0,0 +1,55 @@
/**
* Step 3: Taxonomy Builder
* Define/import taxonomies and link to clusters
*/
import { useBuilderWorkflowStore } from '../../../../store/builderWorkflowStore';
import { Card, CardDescription, CardTitle } from '../../../../components/ui/card';
import Button from '../../../../components/ui/button/Button';
import Alert from '../../../../components/ui/alert/Alert';
interface TaxonomyBuilderStepProps {
blueprintId: number;
}
export default function TaxonomyBuilderStep({ blueprintId }: TaxonomyBuilderStepProps) {
const { context, completeStep, blockingIssues } = useBuilderWorkflowStore();
const taxonomyBlocking = blockingIssues.find(issue => issue.step === 'taxonomies');
return (
<Card className="p-6">
<CardTitle>Taxonomy Builder</CardTitle>
<CardDescription>
Define categories, tags, and attributes for your site structure.
</CardDescription>
{taxonomyBlocking && (
<Alert variant="error" className="mt-4">
{taxonomyBlocking.message}
</Alert>
)}
{context?.taxonomy_summary && (
<div className="mt-6">
<div className="text-sm text-gray-600 dark:text-gray-400 mb-2">
Total Taxonomies: {context.taxonomy_summary.total}
</div>
{/* TODO: Add taxonomy tree/table UI */}
<Alert variant="info" className="mt-4">
Taxonomy builder UI coming in next iteration.
</Alert>
</div>
)}
<div className="mt-6 flex justify-end">
<Button
onClick={() => completeStep('taxonomies')}
disabled={!!taxonomyBlocking}
variant="primary"
>
Continue
</Button>
</div>
</Card>
);
}

View File

@@ -1914,3 +1914,141 @@ export async function fetchContentById(id: number): Promise<Content> {
return fetchAPI(`/v1/writer/content/${id}/`);
}
// Site Builder API
export interface SiteBlueprint {
id: number;
name: string;
description?: string;
config_json: Record<string, any>;
structure_json: Record<string, any>;
status: string;
hosting_type: string;
version: number;
deployed_version?: number;
site_id: number;
sector_id: number;
created_at: string;
updated_at: string;
pages?: PageBlueprint[];
workflow_state?: WorkflowState;
gating_messages?: string[];
}
export interface PageBlueprint {
id: number;
site_blueprint_id: number;
site_blueprint?: number;
slug: string;
title: string;
type: string;
blocks_json: any[];
status: string;
order: number;
created_at: string;
updated_at: string;
}
export interface WorkflowState {
current_step: string;
step_status: Record<string, { status: string; code?: string; message?: string; updated_at?: string }>;
blocking_reason?: string;
completed: boolean;
updated_at: string;
}
export interface WizardContext {
workflow: WorkflowState;
cluster_summary: {
total: number;
attached: number;
coverage_stats: {
complete: number;
in_progress: number;
pending: number;
};
clusters: Array<{
id: number;
name: string;
keywords_count: number;
volume: number;
context_type?: string;
dimension_meta?: Record<string, any>;
coverage_status: string;
role: string;
}>;
};
taxonomy_summary: {
total: number;
by_type: Record<string, number>;
taxonomies: Array<{
id: number;
name: string;
slug: string;
taxonomy_type: string;
cluster_count: number;
}>;
};
sitemap_summary: {
total_pages: number;
by_type: Record<string, number>;
coverage_percentage: number;
};
next_actions: Array<{
step: string;
action: string;
message: string;
}>;
}
export async function fetchSiteBlueprints(filters?: {
site_id?: number;
sector_id?: number;
status?: string;
page?: number;
page_size?: number;
}): Promise<{ count: number; next: string | null; previous: string | null; results: SiteBlueprint[] }> {
const params = new URLSearchParams();
if (filters?.site_id) params.append('site_id', filters.site_id.toString());
if (filters?.sector_id) params.append('sector_id', filters.sector_id.toString());
if (filters?.status) params.append('status', filters.status);
if (filters?.page) params.append('page', filters.page.toString());
if (filters?.page_size) params.append('page_size', filters.page_size.toString());
const queryString = params.toString();
return fetchAPI(`/v1/site-builder/siteblueprint/${queryString ? `?${queryString}` : ''}`);
}
export async function fetchSiteBlueprintById(id: number): Promise<SiteBlueprint> {
return fetchAPI(`/v1/site-builder/siteblueprint/${id}/`);
}
export async function createSiteBlueprint(data: Partial<SiteBlueprint>): Promise<SiteBlueprint> {
return fetchAPI('/v1/site-builder/siteblueprint/', {
method: 'POST',
body: JSON.stringify(data),
});
}
export async function updateSiteBlueprint(id: number, data: Partial<SiteBlueprint>): Promise<SiteBlueprint> {
return fetchAPI(`/v1/site-builder/siteblueprint/${id}/`, {
method: 'PATCH',
body: JSON.stringify(data),
});
}
export async function fetchWizardContext(blueprintId: number): Promise<WizardContext> {
return fetchAPI(`/v1/site-builder/siteblueprint/${blueprintId}/workflow/context/`);
}
export async function updateWorkflowStep(
blueprintId: number,
step: string,
status: string,
metadata?: Record<string, any>
): Promise<WorkflowState> {
return fetchAPI(`/v1/site-builder/siteblueprint/${blueprintId}/workflow/step/`, {
method: 'POST',
body: JSON.stringify({ step, status, metadata }),
});
}

View File

@@ -0,0 +1,220 @@
/**
* Builder Workflow Store (Zustand)
* Manages wizard progress + gating state for site blueprints
*/
import { create } from 'zustand';
import { persist } from 'zustand/middleware';
import {
fetchWizardContext,
updateWorkflowStep,
WizardContext,
WorkflowState,
} from '../services/api';
export type WizardStep =
| 'business_details'
| 'clusters'
| 'taxonomies'
| 'sitemap'
| 'coverage'
| 'ideas';
interface BuilderWorkflowState {
// Current blueprint being worked on
blueprintId: number | null;
// Workflow state
currentStep: WizardStep;
completedSteps: Set<WizardStep>;
blockingIssues: Array<{ step: WizardStep; message: string }>;
workflowState: WorkflowState | null;
// Wizard context (cluster/taxonomy summaries)
context: WizardContext | null;
// Loading/error states
loading: boolean;
error: string | null;
// Telemetry queue (for future event tracking)
telemetryQueue: Array<{ event: string; data: Record<string, any>; timestamp: string }>;
// Actions
initialize: (blueprintId: number) => Promise<void>;
refreshState: () => Promise<void>;
goToStep: (step: WizardStep) => void;
completeStep: (step: WizardStep, metadata?: Record<string, any>) => Promise<void>;
setBlockingIssue: (step: WizardStep, message: string) => void;
clearBlockingIssue: (step: WizardStep) => void;
flushTelemetry: () => void;
reset: () => void;
}
const DEFAULT_STEP: WizardStep = 'business_details';
export const useBuilderWorkflowStore = create<BuilderWorkflowState>()(
persist<BuilderWorkflowState>(
(set, get) => ({
blueprintId: null,
currentStep: DEFAULT_STEP,
completedSteps: new Set(),
blockingIssues: [],
workflowState: null,
context: null,
loading: false,
error: null,
telemetryQueue: [],
initialize: async (blueprintId: number) => {
set({ blueprintId, loading: true, error: null });
try {
const context = await fetchWizardContext(blueprintId);
const workflow = context.workflow;
// Determine completed steps from workflow state
const completedSteps = new Set<WizardStep>();
Object.entries(workflow.step_status || {}).forEach(([step, status]) => {
if (status.status === 'ready' || status.status === 'complete') {
completedSteps.add(step as WizardStep);
}
});
// Extract blocking issues
const blockingIssues: Array<{ step: WizardStep; message: string }> = [];
Object.entries(workflow.step_status || {}).forEach(([step, status]) => {
if (status.status === 'blocked' && status.message) {
blockingIssues.push({ step: step as WizardStep, message: status.message });
}
});
set({
blueprintId,
currentStep: (workflow.current_step as WizardStep) || DEFAULT_STEP,
completedSteps,
blockingIssues,
workflowState: workflow,
context,
loading: false,
error: null,
});
// Emit telemetry event
get().flushTelemetry();
} catch (error: any) {
set({
error: error.message || 'Failed to initialize workflow',
loading: false,
});
}
},
refreshState: async () => {
const { blueprintId } = get();
if (!blueprintId) {
return;
}
await get().initialize(blueprintId);
},
goToStep: (step: WizardStep) => {
set({ currentStep: step });
// Emit telemetry
const { blueprintId } = get();
if (blueprintId) {
get().flushTelemetry();
}
},
completeStep: async (step: WizardStep, metadata?: Record<string, any>) => {
const { blueprintId } = get();
if (!blueprintId) {
throw new Error('No blueprint initialized');
}
set({ loading: true, error: null });
try {
const updatedState = await updateWorkflowStep(blueprintId, step, 'ready', metadata);
// Update local state
const completedSteps = new Set(get().completedSteps);
completedSteps.add(step);
const blockingIssues = get().blockingIssues.filter(issue => issue.step !== step);
set({
workflowState: updatedState,
completedSteps,
blockingIssues,
loading: false,
});
// Refresh full context to get updated summaries
await get().refreshState();
// Emit telemetry
get().flushTelemetry();
} catch (error: any) {
set({
error: error.message || `Failed to complete step: ${step}`,
loading: false,
});
throw error;
}
},
setBlockingIssue: (step: WizardStep, message: string) => {
const blockingIssues = [...get().blockingIssues];
const existingIndex = blockingIssues.findIndex(issue => issue.step === step);
if (existingIndex >= 0) {
blockingIssues[existingIndex] = { step, message };
} else {
blockingIssues.push({ step, message });
}
set({ blockingIssues });
},
clearBlockingIssue: (step: WizardStep) => {
const blockingIssues = get().blockingIssues.filter(issue => issue.step !== step);
set({ blockingIssues });
},
flushTelemetry: () => {
// TODO: In Stage 2, implement actual telemetry dispatch
// For now, just clear the queue
const queue = get().telemetryQueue;
if (queue.length > 0) {
// Future: dispatch to analytics service
console.debug('Telemetry events (to be dispatched):', queue);
set({ telemetryQueue: [] });
}
},
reset: () => {
set({
blueprintId: null,
currentStep: DEFAULT_STEP,
completedSteps: new Set(),
blockingIssues: [],
workflowState: null,
context: null,
loading: false,
error: null,
telemetryQueue: [],
});
},
}),
{
name: 'builder-workflow-storage',
partialize: (state) => ({
blueprintId: state.blueprintId,
currentStep: state.currentStep,
// Note: completedSteps, blockingIssues, workflowState, context are not persisted
// They should be refreshed from API on mount
}),
}
)
);

View File

@@ -0,0 +1,89 @@
# Stage 2 Planner & Wizard UX
## Overview
- Feature flag: `USE_SITE_BUILDER_REFACTOR` (must be `true`)
- Goal: ship state-aware, guided Site Builder experience and expose cluster/taxonomy readiness to Planner UI
- Dependencies: Stage 1 migrations/services already deployed
- Entry point: `/sites/builder/workflow/:blueprintId` (protected route)
---
## Backend Enhancements
### New services / endpoints
| Component | Description | File |
| --- | --- | --- |
| `WizardContextService` | Aggregates workflow state, cluster stats, taxonomy summaries, coverage counts | `backend/igny8_core/business/site_building/services/wizard_context_service.py` |
| Workflow context API | `GET /api/v1/site-builder/siteblueprint/{id}/workflow/context/` returns `workflow`, `cluster_summary`, `taxonomy_summary`, `coverage`, `next_actions` | `modules/site_builder/views.py` |
| Workflow serializer helpers | `SiteBlueprintSerializer` now returns `workflow_state` + `gating_messages` via `WorkflowStateService.serialize_state()` | `modules/site_builder/serializers.py` |
### Workflow telemetry & logging
- `WorkflowStateService` normalizes step metadata (`status`, `code`, `message`, `updated_at`)
- Emits structured log events (`wizard_step_updated`, `wizard_blocking_issue`) for future analytics
- `serialize_state()` provides consistent payload for API, wizard store, and planner warnings
---
## Frontend Implementation
### API layer
- Added interfaces + calls (`fetchSiteBlueprints`, `fetchSiteBlueprintById`, `updateSiteBlueprint`, `fetchWizardContext`, `updateWorkflowStep`)
- Located in `frontend/src/services/api.ts`
### Zustand store
| Store | Purpose |
| --- | --- |
| `useBuilderWorkflowStore` | Tracks `blueprintId`, `currentStep`, `completedSteps`, `blockingIssues`, `workflowState`, `context`, telemetry queue |
- Actions: `initialize`, `refreshState`, `goToStep`, `completeStep`, `setBlockingIssue`, `clearBlockingIssue`, `flushTelemetry`, `reset`
- Persists last blueprint + step in `builder-workflow-storage` (sessionStorage)
### Wizard shell & routing
- New page: `WorkflowWizard` at `/sites/builder/workflow/:blueprintId`
- Lazy-loaded via `App.tsx`
- Refreshes context every 10s to keep telemetry/current state accurate
- Progress indicator (`WizardProgress`) shows completed/current/blocked steps
### Step components
| Step | Component | Status |
| --- | --- | --- |
| 1 Business Details | `steps/BusinessDetailsStep.tsx` | **Functional** (saves blueprint + completes step) |
| 2 Cluster Assignment | `steps/ClusterAssignmentStep.tsx` | Placeholder UI (shows stats, next iteration: attach/detach clusters) |
| 3 Taxonomy Builder | `steps/TaxonomyBuilderStep.tsx` | Placeholder UI (future: taxonomy tree/table + imports) |
| 4 AI Sitemap Review | `steps/SitemapReviewStep.tsx` | Placeholder UI (future: grid w/ grouping + regenerate) |
| 5 Coverage Validation | `steps/CoverageValidationStep.tsx` | Placeholder UI (future: coverage cards + gating logic) |
| 6 Ideas Hand-off | `steps/IdeasHandoffStep.tsx` | Placeholder UI (future: page selection + prompt override) |
### Planner UX TODOs (next iteration)
- Cluster matrix view linking back into wizard
- Taxonomy management table with inline edits & imports
- Planner dashboard banner if blueprint missing requirements
---
## Testing & Verification
1. Set `USE_SITE_BUILDER_REFACTOR=true`
2. Create or reuse a `SiteBlueprint` and open `/sites/builder/workflow/{id}`
3. Confirm payload from `GET /workflow/context/` includes:
- `workflow.steps` array with `status`, `code`, `message`
- `cluster_summary` (counts + list)
- `taxonomy_summary`
- `coverage` (pages, statuses)
- `next_actions`
4. Step 1 (Business Details) should allow update/save → triggers workflow state update
5. Steps 26 currently show placeholders + gating alerts (will be wired to new UIs)
Automated tests pending: once UI solidified, add Cypress flows for each step + Zustand store unit tests.
---
## Open Items / Future Work
- Build full step experiences (tables, drag/drop mapping, AI sitemap review UI)
- Planner cluster matrix & taxonomy management views
- Telemetry dispatcher (currently logs to console)
- Accessibility polish: keyboard navigation, helper tooltips, context drawer
- QA automation + e2e coverage
---
*Last updated: 2025-11-19*

View File

@@ -0,0 +1,85 @@
# Stage 3 Writer / Linker / Optimizer Enhancements
## Objective
Propagate the new metadata (clusters, taxonomies, entity types, attributes) through the planner → writer pipeline, enforce validation before publish, and unlock linker/optimizer capabilities. Stage 3 builds directly on Stage 2s wizard outputs; all changes stay behind `USE_SITE_BUILDER_REFACTOR` until pilot-ready.
---
## Backend Plan
### 1. Metadata Audit & Backfill
| Task | Description | Owner |
| --- | --- | --- |
| Backfill tables | Implement data migration using the stub added in `writer/migrations/0012_metadata_mapping_tables.py` to populate `ContentClusterMap`, `ContentTaxonomyMap`, `ContentAttributeMap` for legacy content/tasks. | Backend lead |
| Entity defaults | Ensure existing Tasks/Content have sensible defaults for `entity_type`, `taxonomy_id`, `cluster_role` (e.g., `blog_post` + `supporting`). | Backend lead |
| Audit script | Management command `python manage.py audit_site_metadata --site {id}` summarizing gaps per site. | Backend lead |
### 2. Pipeline Updates
| Stage | Changes |
| --- | --- |
| Ideas → Tasks | Update Task creation so every task inherits cluster/taxonomy/attribute metadata. Enforce “no cluster, no idea/task” rule. |
| Tasks → Content | Adjust `PageGenerationService` / writer Celery tasks to persist mappings into `ContentClusterMap`, `ContentTaxonomyMap`, `ContentAttributeMap`. |
| AI Prompts | Update prompts to include cluster role, taxonomy context, product attributes. Leverage Stage 1 metadata fields like `dimension_meta`, `attribute_values`. |
| Validation services | Add reusable validators (e.g., `ensure_required_attributes(task)`), returning structured errors for UI. |
### 3. Linker & Optimizer
| Component | Requirements |
| --- | --- |
| LinkerService | Use mapping tables to suggest hub ↔ supporting ↔ attribute links; include priority score + context snippet. |
| OptimizerService | Scorecards factoring cluster coverage, taxonomy alignment, attribute completeness. Provide `/sites/{id}/progress` and `/writer/content/{id}/validation` endpoints. |
| Caching/Indexes | Add DB indexes for frequent join patterns (content ↔ cluster_map, taxonomy_map). |
### 4. API Additions
- `GET /api/v1/sites/{id}/progress/` → cluster-level completion + validation flags.
- `GET /api/v1/writer/content/{id}/validation/` → aggregated checklist for Writer UI.
- `POST /api/v1/writer/content/{id}/validate/` → re-run validators and return actionable errors.
---
## Frontend Plan
### 1. Planner / Ideas / Writer Enhancements
| Area | UX Changes |
| --- | --- |
| Planner Ideas & Writer Tasks lists | Show chips/columns for cluster, taxonomy, entity type, validation status; add filters. |
| Writer Editor | Sidebar module summarizing cluster, taxonomy tree, attribute form; validation panel blocking publish until cleared. |
| Linker UI | Group internal link suggestions by cluster role; show context snippet + CTA to insert link. |
| Optimizer Dashboard | Scorecards per cluster dimension with color coding + “next action” cards. |
| Site Progress Widgets | On site overview, show completion bars (hub/supporting/attribute); deep link to problematic clusters/pages. |
### 2. Validation & Notifications
- Inline toasts + optional email when validation fails.
- Publish button disabled until validators pass; display error list linking to relevant fields.
- Credit reminder banner when user regenerates content/optimization tasks.
---
## Testing Strategy
| Area | Automated | Manual |
| --- | --- | --- |
| Pipeline | Unit tests for Task → Content metadata persistence, Prompt builders. | End-to-end: blueprint → ideas → tasks → content. |
| Validation | Tests ensuring validators trigger correct errors. | Attempt publish without taxonomy/attributes; confirm UX flow. |
| Linker/Optimizer | Service tests for scoring & suggestions. | Performance profiling on large datasets; UX review. |
| Progress Widgets | Component tests verifying counts. | Compare UI vs. database for pilot site. |
---
## Rollout Checklist
1. Deploy Stage 3 backend with feature flag ON in staging.
2. Run metadata backfill; verify progress dashboards and validators.
3. QA regression: planner → writer flow, linker, optimizer.
4. Pilot with internal content team; gather feedback on validation friction.
5. Optimize slow queries (indexes/caching) before production rollout.
6. Update training docs/videos for writers; enable flag gradually across accounts.
---
## Open Questions / Risks
- Volume impact when backfilling large content sets? (Plan: chunked migrations + progress logs)
- Telemetry volume for validator events? (Plan: aggregate counts; sample per site)
- WordPress deploy parity: ensure metadata travels through sync (handled in Stage 4).
---
*Last updated: 2025-11-19*

View File

@@ -0,0 +1,89 @@
# Stage 4 Publishing & Sync Integration
## Objective
Achieve feature parity between IGNY8-hosted deployments and WordPress sites using the shared metadata model introduced in Stages 13. This includes two-way sync for taxonomies/products, deployment readiness checks, and operational tooling.
---
## Backend Plan
### 1. Sync Architecture
| Task | Description |
| --- | --- |
| Audit adapters | Review current WordPress adapter + sync service; confirm endpoints for categories, tags, WooCommerce attributes/products. |
| Data mapping | Document mapping between WordPress taxonomies and IGNY8 `SiteBlueprintTaxonomy`, `ContentTaxonomyMap`, `external_reference` fields. |
| Sync configs | Extend integration settings to store WordPress/Woo credentials, sync frequency, and site archetype. |
### 2. Enhancements
| Area | Implementation |
| --- | --- |
| Import | `ContentSyncService` fetches WP taxonomies/products/custom post types -> maps to IGNY8 schema via `TaxonomyService`. Auto-create missing clusters/taxonomies with an `imported` flag. |
| Export | `WordPressAdapter` ensures taxonomies exist before publishing posts/products. Pushes product attributes/tags ahead of content. |
| Sync Health APIs | `/sites/{id}/sync/status`, `/sites/{id}/sync/run`, returning last sync time, mismatch counts, error logs. |
| Deployment | `SitesRendererAdapter` consumes cluster/taxonomy metadata for navigation, breadcrumbs, internal links. Deployment readiness check ensures cluster coverage, content status, validation flags. |
| Logging & Monitoring | Structured logs per sync run (duration, items processed, failures). Alerts for repeated sync failures or deployment errors. |
---
## Frontend Plan
### 1. Sync Dashboard
| Component | Features |
| --- | --- |
| Parity indicators | Status icons for taxonomies, products, posts. |
| Controls | Manual sync, retry failed items, view logs (with pagination/filtering). |
| Detail drawer | Shows mismatched items, suggested fixes, quick links into Planner/Writer. |
### 2. Deployment Panel
| Component | Features |
| --- | --- |
| Readiness checklist | Displays cluster coverage, content validation, sync status. |
| Actions | Deploy and rollback buttons with confirmation modals and logging. |
| Notifications | Toasts for success/failure; optional email/webhook integration. |
### 3. WordPress Connection UI
| Task | Description |
| --- | --- |
| Integration status | Show credential health, last sync time, active site type. |
| Troubleshooting | Inline helper text + links to docs/runbook. |
---
## Operational Runbooks
- Sync troubleshooting steps (auth errors, taxonomy mismatches, WooCommerce throttling).
- Rollback procedures for failed deployments.
- Escalation path + scripts to force sync, clear queue, or recover failed deploy.
---
## Testing Strategy
| Area | Automated | Manual |
| --- | --- | --- |
| Sync logic | Integration tests hitting mocked WP APIs, verifying mapping + retries. | Staging sync from live WP instance; verify taxonomy parity. |
| Deployment | Renderer tests using fixture metadata to ensure navigation/internal links. | Deploy IGNY8 site; inspect front-end output, breadcrumbs, menus. |
| Dashboards | Component/unit tests for Sync/Deployment panels. | Pilot user testing + UX review. |
| Runbooks | N/A | Tabletop exercises for failure scenarios (sync fails, deploy rollback). |
---
## Rollout Checklist
1. Enable Stage 4 flag in staging; run full import/export tests.
2. Pilot with one IGNY8-hosted and one WordPress-hosted site.
3. Train support on dashboards/runbooks; ensure alerting configured.
4. Announce availability; roll out gradually to accounts with WordPress integrations.
5. Monitor logs/alerts during first production syncs; iterate on tooling as needed.
---
## Risks & Mitigations
| Risk | Mitigation |
| --- | --- |
| API rate limits (WordPress/WooCommerce) | Backoff + batching, highlight in dashboard. |
| Data mismatches (taxonomies/products) | Detailed diff view + retry actions + runbook. |
| Deployment failures | Preflight checks + rollback buttons + structured logs. |
| Operational overhead | Alerting dashboards + documented on-call runbook. |
---
*Last updated: 2025-11-19*