Skip to main content

adk_website/ui/
editor.rs

1//! The web editor (spec 3.5 §7.8.2 "Entry points", §13 Q13, N4, A-I23, A-I24): a structured
2//! form per content kind, Markdown-backed rich text, media through the media pipeline, a
3//! preview with page diffs, scheduling, corrections and withdrawals — and no page builder.
4//!
5//! Every change enters the publishing pipeline as `EntryPoint::WebEditor` with the person as
6//! its proposer, so only people holding an editing role author content here (A-I24). A
7//! release under an approval chain waits for each role, each a distinct person who did not
8//! propose it (A-I23); the release is complete only when the last one approves.
9
10use std::collections::BTreeMap;
11
12use adk_core::Result;
13use adk_core::principal::SubjectRef;
14use adk_site::content::kind_directory;
15use adk_site::gate::{CheckStatus, GateReport};
16use adk_site::media::MediaUpload;
17use adk_site::pipeline::{
18    ApprovalDecision, Change, Draft, EntryPoint, PipelineOutcome, Preview, Withdrawal,
19};
20use awp_types::{
21    ContentId, ContentItem, ContentKind, ContentState, LanguageTag, Markdown, Role, Schedule,
22};
23use chrono::{DateTime, Utc};
24use schemars::JsonSchema;
25use serde::{Deserialize, Serialize};
26use serde_json::Value;
27
28use super::charter::SignerLine;
29use super::onboarding::{CheckView, PageView};
30use super::words;
31use super::{
32    FieldKind, FieldOption, FieldSpec, FormValues, Pill, Tone, WebsiteDesk, forbidden, invalid,
33    kernel, not_found, optional, site,
34};
35
36/// The roles that author content in the web editor (A-I24).
37const EDITING: [Role; 3] = [Role::Owner, Role::Editor, Role::Publisher];
38
39/// The kinds the editor offers, in order.
40const KINDS: [ContentKind; 9] = [
41    ContentKind::Page,
42    ContentKind::Post,
43    ContentKind::Article,
44    ContentKind::Product,
45    ContentKind::Event,
46    ContentKind::Notice,
47    ContentKind::Service,
48    ContentKind::Person,
49    ContentKind::Collection,
50];
51
52/// A release waiting for its approval chain (spec 3.5 §7.8.2 step 4, A-I23): its request in
53/// the site's approval service holds the votes, so the desk keeps none of its own. A release
54/// restored after a restart has no preview until a person acts on it.
55#[derive(Clone)]
56pub(crate) struct PendingRelease {
57    pub(crate) draft: Draft,
58    pub(crate) preview: Option<Preview>,
59    pub(crate) request: String,
60}
61
62/// How a release step ended.
63pub(crate) enum ReleaseStep {
64    Live {
65        seq: u64,
66    },
67    Scheduled {
68        at: String,
69    },
70    Pending(Box<PendingRelease>),
71    Held(String),
72    /// Approved while the site is frozen: it publishes when published again after the freeze.
73    Frozen,
74    Rejected {
75        by: String,
76        reason: String,
77    },
78}
79
80/// Who has approved a release waiting for its chain, and who still must (A-I23).
81#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
82#[serde(rename_all = "camelCase")]
83pub struct ApprovalView {
84    /// One line.
85    pub text: String,
86    /// The chain's roles, in order, with who approved in each.
87    pub lines: Vec<SignerLine>,
88    /// The roles the viewer may approve in now.
89    pub can_approve: Vec<String>,
90    /// Who proposed it; they cannot approve it.
91    pub proposer: String,
92}
93
94/// A content kind's form (spec 3.5 §7.8.2, Q13): structured fields, then the Markdown body.
95#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
96#[serde(rename_all = "camelCase")]
97pub struct KindForm {
98    /// The kind, as sent back.
99    pub kind: String,
100    /// Its name.
101    pub title: String,
102    /// What it is for.
103    pub description: String,
104    /// Its fields, before the body.
105    pub fields: Vec<FieldSpec>,
106}
107
108/// One item of the site's content.
109#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
110#[serde(rename_all = "camelCase")]
111pub struct ItemLine {
112    /// The item.
113    pub id: String,
114    /// Its kind's name.
115    pub kind: String,
116    /// Its title.
117    pub title: String,
118    /// Its address part.
119    pub slug: String,
120    /// Its language.
121    pub language: String,
122    /// Where it stands.
123    pub state: Pill,
124    /// When it publishes, for a scheduled item.
125    #[serde(default, skip_serializing_if = "Option::is_none")]
126    pub scheduled: Option<DateTime<Utc>>,
127    /// Whether it can be corrected or withdrawn: it is live.
128    pub live: bool,
129}
130
131/// A draft in progress.
132#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
133#[serde(rename_all = "camelCase")]
134pub struct DraftLine {
135    /// The draft.
136    pub id: String,
137    /// Its title.
138    pub title: String,
139    /// Its kind's name.
140    pub kind: String,
141    /// Where it stands.
142    pub status: Pill,
143    /// Who wrote it.
144    pub author: String,
145}
146
147/// The editor's home: the forms, the content and the drafts (spec 3.5 §7.8.2).
148#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
149#[serde(rename_all = "camelCase")]
150pub struct EditorHome {
151    /// One form per content kind.
152    pub kinds: Vec<KindForm>,
153    /// The site's content, newest kinds first.
154    pub items: Vec<ItemLine>,
155    /// Drafts in progress.
156    pub drafts: Vec<DraftLine>,
157    /// The site's languages.
158    pub languages: Vec<FieldOption>,
159    /// Whether the viewer may write.
160    pub can_edit: bool,
161    /// Who approves a publication, when the charter names a chain.
162    #[serde(default, skip_serializing_if = "Option::is_none")]
163    pub chain: Option<String>,
164}
165
166/// A media file beside a draft (spec 3.5 §7.8.2 "Media").
167#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
168#[serde(rename_all = "camelCase")]
169pub struct MediaView {
170    /// Its path.
171    pub path: String,
172    /// Its file name.
173    pub name: String,
174    /// Its media type.
175    pub content_type: String,
176    /// Its alt text.
177    #[serde(default, skip_serializing_if = "Option::is_none")]
178    pub alt: Option<String>,
179    /// Whether a person confirmed the alt text; the accessibility check needs it.
180    pub alt_confirmed: bool,
181    /// Whether it is a generated illustration.
182    pub generated: bool,
183}
184
185/// A schedule as the form shows it.
186#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
187#[serde(rename_all = "camelCase")]
188pub struct ScheduleInput {
189    /// When to publish.
190    #[serde(default, skip_serializing_if = "Option::is_none")]
191    pub publish_at: Option<DateTime<Utc>>,
192    /// Not before.
193    #[serde(default, skip_serializing_if = "Option::is_none")]
194    pub embargo_until: Option<DateTime<Utc>>,
195    /// When to withdraw it.
196    #[serde(default, skip_serializing_if = "Option::is_none")]
197    pub expires_at: Option<DateTime<Utc>>,
198    /// When to go back to the previous version.
199    #[serde(default, skip_serializing_if = "Option::is_none")]
200    pub revert_at: Option<DateTime<Utc>>,
201}
202
203impl ScheduleInput {
204    fn into_schedule(self) -> Option<Schedule> {
205        let schedule = Schedule {
206            publish_at: self.publish_at,
207            embargo_until: self.embargo_until,
208            expires_at: self.expires_at,
209            revert_at: self.revert_at,
210        };
211        (schedule != Schedule::default()).then_some(schedule)
212    }
213
214    fn of(schedule: Option<&Schedule>) -> Self {
215        schedule.map_or_else(Self::default, |s| Self {
216            publish_at: s.publish_at,
217            embargo_until: s.embargo_until,
218            expires_at: s.expires_at,
219            revert_at: s.revert_at,
220        })
221    }
222}
223
224/// One draft in the editor.
225#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
226#[serde(rename_all = "camelCase")]
227pub struct DraftView {
228    /// The draft.
229    pub id: String,
230    /// The kind, as sent back.
231    pub kind: String,
232    /// The kind's name.
233    pub kind_title: String,
234    /// The address part.
235    pub slug: String,
236    /// The language.
237    pub language: String,
238    /// The kind's fields with their values.
239    pub fields: Vec<FieldSpec>,
240    /// The body, in Markdown.
241    pub body: String,
242    /// The schedule.
243    pub schedule: ScheduleInput,
244    /// Its media.
245    pub media: Vec<MediaView>,
246    /// The per-change checks, once saved.
247    pub checks: Vec<CheckView>,
248    /// One line on the checks.
249    #[serde(default, skip_serializing_if = "Option::is_none")]
250    pub check_text: Option<String>,
251    /// The preview's pages and how they change.
252    pub preview: Vec<PageView>,
253    /// The approval chain it waits for.
254    #[serde(default, skip_serializing_if = "Option::is_none")]
255    pub approval: Option<ApprovalView>,
256    /// How publishing ended.
257    #[serde(default, skip_serializing_if = "Option::is_none")]
258    pub outcome: Option<String>,
259    /// Where it stands.
260    pub status: Pill,
261    /// The live item it changes, if any.
262    #[serde(default, skip_serializing_if = "Option::is_none")]
263    pub changes: Option<String>,
264    /// Who wrote it.
265    pub author: String,
266}
267
268/// An editor action (spec 3.5 §7.8.2). Uploads have their own call, with the file's bytes.
269#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
270#[serde(tag = "type", rename_all = "camelCase", rename_all_fields = "camelCase")]
271pub enum EditorCommand {
272    /// A new draft of `kind`.
273    New {
274        /// The kind, such as `product`.
275        kind: String,
276        /// Its language; the site's first unless set.
277        #[serde(default)]
278        language: Option<String>,
279    },
280    /// A draft that changes the item `id`.
281    Open {
282        /// The item.
283        id: String,
284    },
285    /// Saves the draft's form and runs the per-change checks.
286    Save {
287        /// The draft.
288        draft: String,
289        /// The address part.
290        slug: String,
291        /// The language.
292        language: String,
293        /// The kind's fields, by id.
294        fields: FormValues,
295        /// The body, in Markdown.
296        #[serde(default)]
297        body: Option<String>,
298        /// The schedule.
299        #[serde(default)]
300        schedule: ScheduleInput,
301    },
302    /// Confirms an image's alt text; the accessibility check needs it.
303    ConfirmAlt {
304        /// The draft.
305        draft: String,
306        /// The media file.
307        path: String,
308        /// The text.
309        alt: String,
310    },
311    /// Builds the preview with its page diffs (spec 3.3 §7.5).
312    Preview {
313        /// The draft.
314        draft: String,
315    },
316    /// Publishes, or schedules when the draft has a future time.
317    Publish {
318        /// The draft.
319        draft: String,
320    },
321    /// Approves a draft waiting for its chain, in `role` (A-I23).
322    Approve {
323        /// The draft.
324        draft: String,
325        /// The role.
326        role: String,
327    },
328    /// Refuses a draft waiting for its chain.
329    Reject {
330        /// The draft.
331        draft: String,
332        /// Why.
333        reason: String,
334    },
335    /// Corrects a live item: a new release with a visible correction note.
336    Correct {
337        /// The item.
338        id: String,
339        /// The correction note readers see.
340        note: String,
341        /// Fields to change.
342        #[serde(default)]
343        fields: FormValues,
344        /// A new body.
345        #[serde(default)]
346        body: Option<String>,
347    },
348    /// Withdraws a live item: a notice in its place, or 410 Gone without one.
349    Withdraw {
350        /// The item.
351        id: String,
352        /// The notice; 410 Gone when absent.
353        #[serde(default)]
354        notice: Option<String>,
355    },
356    /// Throws a draft away.
357    Discard {
358        /// The draft.
359        draft: String,
360    },
361}
362
363/// What an editor action did.
364#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
365#[serde(rename_all = "camelCase")]
366pub struct EditorOutcome {
367    /// The editor after it.
368    pub home: EditorHome,
369    /// The draft it acted on.
370    #[serde(default, skip_serializing_if = "Option::is_none")]
371    pub draft: Option<DraftView>,
372    /// One line on what happened.
373    #[serde(default, skip_serializing_if = "Option::is_none")]
374    pub note: Option<String>,
375}
376
377struct EditorDraft {
378    change: Change,
379    changes: Option<ContentId>,
380    checks: Option<GateReport>,
381    preview: Option<(Preview, Vec<PageView>)>,
382    pending: Option<PendingRelease>,
383    outcome: Option<String>,
384    done: bool,
385    scheduled: bool,
386}
387
388impl EditorDraft {
389    fn item(&self) -> &ContentItem {
390        &self.change.items[0]
391    }
392}
393
394#[derive(Default)]
395pub(crate) struct State {
396    drafts: BTreeMap<String, EditorDraft>,
397}
398
399impl WebsiteDesk {
400    pub(crate) async fn save_drafts(&self) -> Vec<super::saved::SavedDraft> {
401        let state = self.inner.editor.lock().await;
402        state
403            .drafts
404            .iter()
405            .map(|(id, draft)| super::saved::SavedDraft {
406                id: id.clone(),
407                items: draft.change.items.clone(),
408                media: super::saved::SavedDraft::encode(&draft.change.media),
409                entry: draft.change.entry.clone(),
410                proposer: draft.change.proposer.clone(),
411                job: draft.change.job.clone(),
412                action_class: draft.change.action_class.clone(),
413                changes: draft.changes.clone(),
414                outcome: draft.outcome.clone(),
415                done: draft.done,
416                scheduled: draft.scheduled,
417                request: draft.pending.as_ref().map(|pending| pending.request.clone()),
418            })
419            .collect()
420    }
421
422    pub(crate) async fn restore_drafts(&self, saved: Vec<super::saved::SavedDraft>) -> Result<()> {
423        let mut drafts = BTreeMap::new();
424        for draft in saved {
425            let media = draft.decode()?;
426            let change = Change {
427                items: draft.items,
428                media,
429                entry: draft.entry,
430                proposer: draft.proposer,
431                job: draft.job,
432                action_class: draft.action_class,
433            };
434            // A release that waited for its chain waits on the same request after a restart.
435            let pending = draft.request.map(|request| PendingRelease {
436                draft: Draft {
437                    ids: change.items.iter().map(|item| item.id.clone()).collect(),
438                    change: change.clone(),
439                },
440                preview: None,
441                request,
442            });
443            drafts.insert(
444                draft.id.clone(),
445                EditorDraft {
446                    change,
447                    changes: draft.changes,
448                    checks: None,
449                    preview: None,
450                    pending,
451                    outcome: draft.outcome,
452                    done: draft.done,
453                    scheduled: draft.scheduled,
454                },
455            );
456        }
457        let mut state = self.inner.editor.lock().await;
458        // Ids the desk hands out next must not collide with the restored ones.
459        for id in drafts.keys() {
460            if let Some(n) = id.rsplit('-').next().and_then(|n| n.parse::<u64>().ok()) {
461                self.bump_next(n + 1);
462            }
463        }
464        state.drafts = drafts;
465        Ok(())
466    }
467}
468
469fn kind_id(kind: ContentKind) -> String {
470    serde_json::to_value(kind).ok().and_then(|v| v.as_str().map(str::to_string)).unwrap_or_default()
471}
472
473fn kind_from(id: &str) -> Result<ContentKind> {
474    KINDS
475        .into_iter()
476        .find(|kind| kind_id(*kind) == id)
477        .ok_or_else(|| invalid("website.editor.kind", format!("no content kind '{id}'")))
478}
479
480fn description(kind: ContentKind) -> &'static str {
481    match kind {
482        ContentKind::Page => "A standing page, such as About or Opening hours",
483        ContentKind::Post => "A blog post",
484        ContentKind::Article => "A news article, with its byline",
485        ContentKind::Product => "Something you sell, with its price",
486        ContentKind::Event => "Something that happens at a time and place",
487        ContentKind::Notice => "A notice, with the date it ends",
488        ContentKind::Service => "A service you offer",
489        ContentKind::Person => "A person on your team",
490        ContentKind::Collection => "A list of other items",
491        _ => "Content",
492    }
493}
494
495/// The structured fields of `kind` (spec 3.5 §7.8.2): those the built-in renderer shows and
496/// marks up for search engines and agents.
497fn kind_fields(kind: ContentKind, currency: &str) -> Vec<FieldSpec> {
498    let mut fields = vec![
499        FieldSpec::new("title", "Title", FieldKind::Text).required(),
500        FieldSpec::new("summary", "Summary", FieldKind::LongText)
501            .hint("One or two sentences for lists, search results and agents"),
502    ];
503    match kind {
504        ContentKind::Post | ContentKind::Article => {
505            fields.push(FieldSpec::new("byline", "Byline", FieldKind::Text));
506        }
507        ContentKind::Product => {
508            fields.push(FieldSpec::new("price", "Price", FieldKind::Number).required());
509            fields.push(
510                FieldSpec::new("currency", "Currency", FieldKind::Text).required().value(currency),
511            );
512            fields.push(FieldSpec::new("sku", "Stock code (SKU)", FieldKind::Text));
513            fields.push(
514                FieldSpec::new("validUntil", "Price valid until", FieldKind::DateTime)
515                    .hint("Quotes keep their price until this time"),
516            );
517        }
518        ContentKind::Event => {
519            fields.push(FieldSpec::new("startsAt", "Starts", FieldKind::DateTime).required());
520            fields.push(FieldSpec::new("endsAt", "Ends", FieldKind::DateTime));
521            fields.push(FieldSpec::new("location", "Where", FieldKind::Text));
522        }
523        ContentKind::Person => fields.push(FieldSpec::new("role", "Role", FieldKind::Text)),
524        _ => {}
525    }
526    fields
527}
528
529fn field_text(value: &Value) -> String {
530    match value {
531        Value::String(text) => text.clone(),
532        Value::Null => String::new(),
533        other => other.to_string(),
534    }
535}
536
537fn valid_slug(slug: &str) -> bool {
538    !slug.is_empty()
539        && slug.len() <= 80
540        && slug.chars().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-')
541        && !slug.starts_with('-')
542        && !slug.ends_with('-')
543}
544
545fn outcome_words(step: &ReleaseStep) -> String {
546    match step {
547        ReleaseStep::Live { seq } => format!("Live in release {seq}, signed."),
548        ReleaseStep::Scheduled { at } => format!("Scheduled for {at}."),
549        ReleaseStep::Pending(_) => "Waiting for the approval chain.".into(),
550        ReleaseStep::Held(summary) => format!("Held by the checks: {summary}"),
551        ReleaseStep::Frozen => {
552            "Approved, but the site is frozen: publish it again once the freeze lifts.".into()
553        }
554        ReleaseStep::Rejected { by, reason } => format!("{by} refused it: {reason}"),
555    }
556}
557
558pub(crate) fn check_views(report: &GateReport) -> Vec<CheckView> {
559    report
560        .checks
561        .iter()
562        .filter(|check| check.status != CheckStatus::Skipped)
563        .map(|check| CheckView {
564            name: words::check(check.check).into(),
565            status: words::check_status(check.status),
566            findings: check
567                .findings
568                .iter()
569                .filter(|f| f.blocking)
570                .take(5)
571                .map(|f| f.message.clone())
572                .collect(),
573            note: check.note.clone(),
574        })
575        .collect()
576}
577
578impl WebsiteDesk {
579    /// Releases `draft` (spec 3.5 §7.8.2 steps 3–8): its preview, its approval, then the
580    /// signed release, or the chain it waits for.
581    pub(crate) async fn release(
582        &self,
583        draft: Draft,
584        preview: Option<Preview>,
585    ) -> Result<ReleaseStep> {
586        let runtime = self.runtime().await;
587        let preview = match preview {
588            Some(preview) => preview,
589            None => runtime.pipeline().preview(&draft).await.map_err(site)?,
590        };
591        if preview.gate.refuses_release() {
592            let _ = tokio::fs::remove_dir_all(&preview.staged.root).await;
593            return Err(site(adk_site::SiteError::GateFailed(preview.gate.summary())));
594        }
595        if !preview.gate.passed() {
596            let _ = tokio::fs::remove_dir_all(&preview.staged.root).await;
597            return Ok(ReleaseStep::Held(preview.gate.summary()));
598        }
599        match runtime.pipeline().approve(&draft, &preview).await.map_err(site)? {
600            ApprovalDecision::Approved { decision, .. } => {
601                self.finish(&draft, &preview, decision).await
602            }
603            ApprovalDecision::Pending { ticket } => {
604                Ok(ReleaseStep::Pending(Box::new(PendingRelease {
605                    draft,
606                    preview: Some(preview),
607                    request: ticket,
608                })))
609            }
610            ApprovalDecision::Rejected { by, reason } => {
611                let _ = tokio::fs::remove_dir_all(&preview.staged.root).await;
612                Ok(ReleaseStep::Rejected { by, reason })
613            }
614        }
615    }
616
617    async fn finish(
618        &self,
619        draft: &Draft,
620        preview: &Preview,
621        decision: Option<String>,
622    ) -> Result<ReleaseStep> {
623        let runtime = self.runtime().await;
624        // A freeze holds publishing, a person's release included (#1280, D5).
625        if runtime.is_frozen() {
626            let _ = tokio::fs::remove_dir_all(&preview.staged.root).await;
627            return Ok(ReleaseStep::Frozen);
628        }
629        let outcome = runtime.pipeline().complete(draft, decision).await.map_err(site);
630        let _ = tokio::fs::remove_dir_all(&preview.staged.root).await;
631        Ok(match outcome? {
632            PipelineOutcome::Published(published) => {
633                ReleaseStep::Live { seq: published.staged.manifest.seq }
634            }
635            PipelineOutcome::Scheduled { at } => ReleaseStep::Scheduled {
636                at: at.map_or_else(
637                    || "its time".to_string(),
638                    |at| at.format("%-d %b %Y %H:%M UTC").to_string(),
639                ),
640            },
641            PipelineOutcome::Held(report) => ReleaseStep::Held(report.summary()),
642            PipelineOutcome::Rejected { by, reason } => ReleaseStep::Rejected { by, reason },
643            PipelineOutcome::Pending { .. } => ReleaseStep::Held("it waits for approval".into()),
644        })
645    }
646
647    /// The chain the publication `action_class` needs, from the charter in force.
648    async fn chain(
649        &self,
650        action_class: &str,
651    ) -> Result<Option<(awp_types::Governance, Vec<Role>)>> {
652        let Some(charters) = &self.inner.charters else { return Ok(None) };
653        let Some(current) = charters.current(self.inner.site.id).await.map_err(kernel)? else {
654            return Ok(None);
655        };
656        let roles = current
657            .charter
658            .governance
659            .approval_chains
660            .iter()
661            .find(|chain| chain.action.as_str() == action_class)
662            .map(|chain| chain.roles.clone());
663        Ok(roles.map(|roles| (current.charter.governance, roles)))
664    }
665
666    /// Records `person`'s approval in `role` of a release waiting for its chain (A-I23) on
667    /// the release's request, which the kernel's inbox and chat cards decide too; `Some` once
668    /// the release completes or is refused.
669    pub(crate) async fn approve_release(
670        &self,
671        pending: &mut PendingRelease,
672        person: &str,
673        role: &str,
674    ) -> Result<Option<ReleaseStep>> {
675        let role = words::role_from(role)
676            .ok_or_else(|| invalid("website.editor.role", format!("no role '{role}'")))?;
677        let (governance, _) =
678            self.chain(&pending.draft.change.action_class).await?.ok_or_else(|| {
679                invalid("website.editor.no_chain", "this release needs no approval chain")
680            })?;
681        if adk_kernel::charter::is_agent_principal(person) || !governance.holds(person, role) {
682            return Err(forbidden(
683                "website.editor.not_an_approver",
684                format!("{person} does not hold the {} role", words::role(role).to_lowercase()),
685            ));
686        }
687        if pending.draft.change.proposer == person {
688            return Err(forbidden(
689                "website.editor.own_change",
690                "the person who proposed a change cannot approve it (spec 3.5 A-I23)",
691            ));
692        }
693        let runtime = self.runtime().await;
694        // A release restored after a restart is previewed again; the same change on the same
695        // base reaches the same request, a new base a new one.
696        let preview = match pending.preview.take() {
697            Some(preview) => preview,
698            None => runtime.pipeline().preview(&pending.draft).await.map_err(site)?,
699        };
700        pending.preview = Some(preview.clone());
701        match runtime.pipeline().approve(&pending.draft, &preview).await.map_err(site)? {
702            ApprovalDecision::Approved { decision, .. } => {
703                return Ok(Some(self.finish(&pending.draft, &preview, decision).await?));
704            }
705            ApprovalDecision::Rejected { by, reason } => {
706                return Ok(Some(ReleaseStep::Rejected { by, reason }));
707            }
708            ApprovalDecision::Pending { ticket } => pending.request = ticket,
709        }
710        let approvals = runtime.approvals();
711        let request = approvals.get(&pending.request).await?.ok_or_else(|| {
712            not_found("website.editor.request", "the release's approval request is gone")
713        })?;
714        if request.quorum_progress().0.iter().any(|approver| approver.id == person) {
715            return Err(invalid("website.editor.approved", "you have approved this already"));
716        }
717        approvals.approve(&pending.request, request.version, &SubjectRef::human(person)).await?;
718        match runtime.pipeline().approve(&pending.draft, &preview).await.map_err(site)? {
719            ApprovalDecision::Approved { decision, .. } => {
720                Ok(Some(self.finish(&pending.draft, &preview, decision).await?))
721            }
722            ApprovalDecision::Pending { .. } => Ok(None),
723            ApprovalDecision::Rejected { by, reason } => {
724                Ok(Some(ReleaseStep::Rejected { by, reason }))
725            }
726        }
727    }
728
729    /// Who approved `pending` and who still must, as `person` sees it, from the release's
730    /// request: whoever approved it, on whichever surface.
731    pub(crate) async fn approval_view(
732        &self,
733        pending: &PendingRelease,
734        person: &str,
735    ) -> Result<ApprovalView> {
736        let (governance, roles) =
737            self.chain(&pending.draft.change.action_class).await?.unwrap_or_else(|| {
738                (
739                    awp_types::Governance { roles: Vec::new(), approval_chains: Vec::new() },
740                    Vec::new(),
741                )
742            });
743        let runtime = self.runtime().await;
744        let request = runtime.approvals().get(&pending.request).await?;
745        let holders: Vec<Option<&adk_core::ApprovalDecision>> = match &request {
746            Some(request) => request.slot_holders().into_iter().map(|(_, held)| held).collect(),
747            None => Vec::new(),
748        };
749        let lines: Vec<SignerLine> = roles
750            .iter()
751            .enumerate()
752            .map(|(slot, role)| {
753                let held = holders.get(slot).copied().flatten();
754                SignerLine {
755                    role: words::role_id(*role).into(),
756                    label: words::role(*role).into(),
757                    holders: governance.holders(*role).map(str::to_string).collect(),
758                    signed_by: held.map(|decision| decision.authority().id.clone()),
759                    signed_at: held.map(|decision| decision.decided_at),
760                }
761            })
762            .collect();
763        let proposer = pending.draft.change.proposer.clone();
764        let approved = request.as_ref().is_some_and(|request| {
765            request.quorum_progress().0.iter().any(|approver| approver.id == person)
766        });
767        let can_approve: Vec<String> = if person != proposer && !approved {
768            let mut roles: Vec<String> = lines
769                .iter()
770                .filter(|line| line.signed_by.is_none() && line.holders.iter().any(|h| h == person))
771                .map(|line| line.role.clone())
772                .collect();
773            roles.dedup();
774            roles
775        } else {
776            Vec::new()
777        };
778        let waiting: Vec<String> = lines
779            .iter()
780            .filter(|l| l.signed_by.is_none())
781            .map(|l| l.label.to_lowercase())
782            .collect();
783        Ok(ApprovalView {
784            text: if waiting.is_empty() {
785                "Every role has approved.".into()
786            } else {
787                format!("Waiting for the {}", waiting.join(" and the "))
788            },
789            lines,
790            can_approve,
791            proposer,
792        })
793    }
794
795    /// The editor's home for `person` (spec 3.5 §7.8.2).
796    ///
797    /// # Errors
798    ///
799    /// The stores' errors.
800    pub async fn editor_home(&self, person: &str) -> Result<EditorHome> {
801        let roles = self.roles(person).await?;
802        let can_edit = EDITING.iter().any(|role| roles.contains(role));
803        let runtime = self.runtime().await;
804        let mut items: Vec<ContentItem> = runtime.store().list().await.map_err(site)?;
805        // What people write comes first; standing pages, the legal ones among them, after.
806        items.sort_by(|a, b| {
807            (a.kind == ContentKind::Page, a.kind, &a.slug, a.language.as_str()).cmp(&(
808                b.kind == ContentKind::Page,
809                b.kind,
810                &b.slug,
811                b.language.as_str(),
812            ))
813        });
814        let items = items
815            .into_iter()
816            .map(|item| ItemLine {
817                id: item.id.0.clone(),
818                kind: words::content_kind(item.kind).into(),
819                title: item
820                    .fields
821                    .get("title")
822                    .map(field_text)
823                    .unwrap_or_else(|| item.slug.clone()),
824                slug: item.slug.clone(),
825                language: item.language.to_string(),
826                state: words::content_state(item.state),
827                scheduled: item
828                    .schedule
829                    .as_ref()
830                    .and_then(|s| s.publish_at)
831                    .filter(|_| item.state == ContentState::Scheduled),
832                live: matches!(item.state, ContentState::Published | ContentState::Corrected),
833            })
834            .collect();
835        let state = self.inner.editor.lock().await;
836        let drafts = state
837            .drafts
838            .iter()
839            .filter(|(_, draft)| !draft.done)
840            .map(|(id, draft)| DraftLine {
841                id: id.clone(),
842                title: draft
843                    .item()
844                    .fields
845                    .get("title")
846                    .map(field_text)
847                    .filter(|t| !t.is_empty())
848                    .unwrap_or_else(|| "Untitled".into()),
849                kind: words::content_kind(draft.item().kind).into(),
850                status: draft_status(draft),
851                author: draft.change.proposer.clone(),
852            })
853            .collect();
854        drop(state);
855        let chain = self.chain("publish").await?.map(|(_, roles)| {
856            let names: Vec<String> = roles.iter().map(|r| words::role(*r).to_lowercase()).collect();
857            format!(
858                "Publishing needs the approval of the {}, each a different person.",
859                names.join(", then the ")
860            )
861        });
862        Ok(EditorHome {
863            kinds: KINDS
864                .into_iter()
865                .map(|kind| KindForm {
866                    kind: kind_id(kind),
867                    title: words::content_kind(kind).into(),
868                    description: description(kind).into(),
869                    fields: kind_fields(kind, &self.inner.currency),
870                })
871                .collect(),
872            items,
873            drafts,
874            languages: self
875                .inner
876                .languages
877                .iter()
878                .map(|l| FieldOption { value: l.to_string(), label: l.to_string() })
879                .collect(),
880            can_edit,
881            chain,
882        })
883    }
884
885    /// One draft as `person` sees it.
886    ///
887    /// # Errors
888    ///
889    /// `NotFound` for an unknown draft; the stores' errors.
890    pub async fn draft_view(&self, person: &str, id: &str) -> Result<DraftView> {
891        let state = self.inner.editor.lock().await;
892        let draft = state
893            .drafts
894            .get(id)
895            .ok_or_else(|| not_found("website.editor.draft", format!("no draft '{id}'")))?;
896        let item = draft.item().clone();
897        let fields = kind_fields(item.kind, &self.inner.currency)
898            .into_iter()
899            .map(|field| {
900                let value = item.fields.get(&field.id).map(field_text).unwrap_or_default();
901                if value.is_empty() { field } else { field.value(value) }
902            })
903            .collect();
904        let checks = draft.checks.as_ref().map(check_views).unwrap_or_default();
905        let check_text = draft.checks.as_ref().map(|report| {
906            if report.passed() {
907                "Every check passed.".to_string()
908            } else {
909                format!("Fix before publishing: {}", report.summary())
910            }
911        });
912        let preview = draft.preview.as_ref().map(|(_, pages)| pages.clone()).unwrap_or_default();
913        let pending = draft.pending.clone();
914        let view = DraftView {
915            id: id.to_string(),
916            kind: kind_id(item.kind),
917            kind_title: words::content_kind(item.kind).into(),
918            slug: item.slug.clone(),
919            language: item.language.to_string(),
920            fields,
921            body: item.body.as_ref().map(|b| b.0.clone()).unwrap_or_default(),
922            schedule: ScheduleInput::of(item.schedule.as_ref()),
923            media: item
924                .media
925                .iter()
926                .map(|m| MediaView {
927                    name: m.path.rsplit('/').next().unwrap_or(&m.path).to_string(),
928                    path: m.path.clone(),
929                    content_type: m.content_type.clone(),
930                    alt: m.alt.clone(),
931                    alt_confirmed: m.alt_confirmed,
932                    generated: m.generated,
933                })
934                .collect(),
935            checks,
936            check_text,
937            preview,
938            approval: None,
939            outcome: draft.outcome.clone(),
940            status: draft_status(draft),
941            changes: draft.changes.as_ref().map(|id| id.0.clone()),
942            author: draft.change.proposer.clone(),
943        };
944        drop(state);
945        Ok(match pending {
946            Some(pending) => {
947                DraftView { approval: Some(self.approval_view(&pending, person).await?), ..view }
948            }
949            None => view,
950        })
951    }
952
953    /// Runs one media upload through the media pipeline into the draft `id` (spec 3.5 §7.8.2
954    /// "Media"): sniffed, executables and polyglots refused, location stripped, resized; the
955    /// alt text is a draft until a person confirms it.
956    ///
957    /// # Errors
958    ///
959    /// `Forbidden` without an editing role; the media pipeline's refusal.
960    pub async fn upload(
961        &self,
962        person: &str,
963        id: &str,
964        name: &str,
965        bytes: &[u8],
966        alt: Option<String>,
967        generated: bool,
968    ) -> Result<DraftView> {
969        self.require(person, &EDITING, "Adding media").await?;
970        {
971            let mut state = self.inner.editor.lock().await;
972            let draft = state
973                .drafts
974                .get_mut(id)
975                .ok_or_else(|| not_found("website.editor.draft", format!("no draft '{id}'")))?;
976            let processed = self
977                .inner
978                .media
979                .process(&MediaUpload {
980                    name,
981                    bytes,
982                    alt: alt.filter(|a| !a.trim().is_empty()),
983                    generated,
984                })
985                .map_err(site)?;
986            let item = &mut draft.change.items[0];
987            let dir = format!("content/{}/{}", kind_directory(item.kind), item.slug);
988            let media = processed.media_ref(&dir);
989            item.media.retain(|held| held.path != media.path);
990            item.media.push(media.clone());
991            draft.change.media.retain(|(path, _)| path != &media.path);
992            draft.change.media.push((media.path.clone(), processed.bytes.clone()));
993            for variant in &processed.variants {
994                draft.change.media.push((format!("{dir}/{}", variant.name), variant.bytes.clone()));
995            }
996            draft.checks = None;
997            draft.preview = None;
998        }
999        self.persist().await;
1000        self.draft_view(person, id).await
1001    }
1002
1003    /// Carries out an editor `command` for `person` (spec 3.5 §7.8.2, A-I23, A-I24).
1004    ///
1005    /// # Errors
1006    ///
1007    /// `Forbidden` without an editing role or for an approval the person may not give;
1008    /// `InvalidInput` for a bad value; the pipeline's errors.
1009    pub async fn editor_command(
1010        &self,
1011        person: &str,
1012        command: EditorCommand,
1013    ) -> Result<EditorOutcome> {
1014        let result = self.editor_command_unsaved(person, command).await;
1015        if result.is_ok() {
1016            self.persist().await;
1017        }
1018        result
1019    }
1020
1021    async fn editor_command_unsaved(
1022        &self,
1023        person: &str,
1024        command: EditorCommand,
1025    ) -> Result<EditorOutcome> {
1026        let mut note = None;
1027        let mut current: Option<String> = None;
1028        match command {
1029            EditorCommand::New { kind, language } => {
1030                self.require(person, &EDITING, "Writing").await?;
1031                let kind = kind_from(&kind)?;
1032                let language = match language {
1033                    Some(tag) => LanguageTag::parse(&tag)
1034                        .map_err(|e| invalid("website.editor.language", e.to_string()))?,
1035                    None => self
1036                        .inner
1037                        .languages
1038                        .first()
1039                        .cloned()
1040                        .unwrap_or_else(|| LanguageTag::parse("en").expect("a valid tag")),
1041                };
1042                let id = self.next_id("draft");
1043                let mut fields = BTreeMap::new();
1044                if kind == ContentKind::Product {
1045                    fields
1046                        .insert("currency".to_string(), Value::String(self.inner.currency.clone()));
1047                }
1048                let item = ContentItem {
1049                    id: ContentId(String::new()),
1050                    kind,
1051                    slug: String::new(),
1052                    language,
1053                    fields,
1054                    volatile: Vec::new(),
1055                    body: None,
1056                    media: Vec::new(),
1057                    sources: Vec::new(),
1058                    schedule: None,
1059                    state: ContentState::Draft,
1060                };
1061                self.inner
1062                    .editor
1063                    .lock()
1064                    .await
1065                    .drafts
1066                    .insert(id.clone(), self.editor_draft(item, person, None));
1067                current = Some(id);
1068            }
1069            EditorCommand::Open { id } => {
1070                self.require(person, &EDITING, "Changing content").await?;
1071                let item = self
1072                    .runtime()
1073                    .await
1074                    .store()
1075                    .get(&ContentId(id.clone()))
1076                    .await
1077                    .map_err(site)?
1078                    .ok_or_else(|| not_found("website.editor.item", format!("no item '{id}'")))?;
1079                let draft_id = self.next_id("draft");
1080                let origin = item.id.clone();
1081                let mut item = item;
1082                item.state = ContentState::Draft;
1083                self.inner
1084                    .editor
1085                    .lock()
1086                    .await
1087                    .drafts
1088                    .insert(draft_id.clone(), self.editor_draft(item, person, Some(origin)));
1089                current = Some(draft_id);
1090            }
1091            EditorCommand::Save { draft, slug, language, fields, body, schedule } => {
1092                self.require(person, &EDITING, "Writing").await?;
1093                note = Some(
1094                    self.save(person, &draft, &slug, &language, &fields, body, schedule).await?,
1095                );
1096                current = Some(draft);
1097            }
1098            EditorCommand::ConfirmAlt { draft, path, alt } => {
1099                self.require(person, &EDITING, "Confirming alt text").await?;
1100                let alt = alt.trim().to_string();
1101                let mut state = self.inner.editor.lock().await;
1102                let held = state.drafts.get_mut(&draft).ok_or_else(|| {
1103                    not_found("website.editor.draft", format!("no draft '{draft}'"))
1104                })?;
1105                let media =
1106                    held.change.items[0].media.iter_mut().find(|m| m.path == path).ok_or_else(
1107                        || not_found("website.editor.media", format!("no media '{path}'")),
1108                    )?;
1109                media.alt = Some(alt);
1110                media.alt_confirmed = true;
1111                held.checks = None;
1112                held.preview = None;
1113                current = Some(draft);
1114            }
1115            EditorCommand::Preview { draft } => {
1116                self.require(person, &EDITING, "Previewing").await?;
1117                self.preview(&draft).await?;
1118                current = Some(draft);
1119            }
1120            EditorCommand::Publish { draft } => {
1121                self.require(person, &EDITING, "Publishing").await?;
1122                note = Some(self.publish(person, &draft).await?);
1123                current = Some(draft);
1124            }
1125            EditorCommand::Approve { draft, role } => {
1126                let mut state = self.inner.editor.lock().await;
1127                let held = state.drafts.get_mut(&draft).ok_or_else(|| {
1128                    not_found("website.editor.draft", format!("no draft '{draft}'"))
1129                })?;
1130                let mut pending = held.pending.take().ok_or_else(|| {
1131                    invalid("website.editor.not_waiting", "this draft waits for no approval")
1132                })?;
1133                match self.approve_release(&mut pending, person, &role).await {
1134                    Ok(Some(step)) => {
1135                        note = Some(outcome_words(&step));
1136                        held.outcome = note.clone();
1137                        held.done = !matches!(step, ReleaseStep::Held(_) | ReleaseStep::Frozen);
1138                    }
1139                    Ok(None) => {
1140                        held.pending = Some(pending);
1141                        note =
1142                            Some("Your approval is recorded; it waits for the other roles.".into());
1143                    }
1144                    Err(error) => {
1145                        held.pending = Some(pending);
1146                        return Err(error);
1147                    }
1148                }
1149                current = Some(draft);
1150            }
1151            EditorCommand::Reject { draft, reason } => {
1152                let reason = reason.trim().to_string();
1153                if reason.is_empty() {
1154                    return Err(invalid("website.editor.reason", "say why"));
1155                }
1156                let mut state = self.inner.editor.lock().await;
1157                let held = state.drafts.get_mut(&draft).ok_or_else(|| {
1158                    not_found("website.editor.draft", format!("no draft '{draft}'"))
1159                })?;
1160                let pending = held.pending.as_ref().ok_or_else(|| {
1161                    invalid("website.editor.not_waiting", "this draft waits for no approval")
1162                })?;
1163                let (governance, roles) =
1164                    self.chain(&pending.draft.change.action_class).await?.ok_or_else(|| {
1165                        invalid("website.editor.no_chain", "this release needs no approval chain")
1166                    })?;
1167                if !roles.iter().any(|role| governance.holds(person, *role)) {
1168                    return Err(forbidden(
1169                        "website.editor.not_an_approver",
1170                        "only an approver in the chain can refuse it",
1171                    ));
1172                }
1173                let runtime = self.runtime().await;
1174                let approvals = runtime.approvals();
1175                let request = approvals.get(&pending.request).await?.ok_or_else(|| {
1176                    not_found("website.editor.request", "the release's approval request is gone")
1177                })?;
1178                approvals
1179                    .reject(&pending.request, request.version, &SubjectRef::human(person), &reason)
1180                    .await?;
1181                if let Some(preview) = &pending.preview {
1182                    let _ = tokio::fs::remove_dir_all(&preview.staged.root).await;
1183                }
1184                held.pending = None;
1185                held.outcome = Some(format!("{person} refused it: {reason}"));
1186                note = held.outcome.clone();
1187                current = Some(draft);
1188            }
1189            EditorCommand::Correct { id, note: text, fields, body } => {
1190                self.require(person, &EDITING, "Correcting").await?;
1191                let text = text.trim().to_string();
1192                if text.is_empty() {
1193                    return Err(invalid(
1194                        "website.editor.note",
1195                        "a correction needs a note readers see",
1196                    ));
1197                }
1198                let runtime = self.runtime().await;
1199                let currency = self.inner.currency.clone();
1200                let item =
1201                    runtime.store().get(&ContentId(id.clone())).await.map_err(site)?.ok_or_else(
1202                        || not_found("website.editor.item", format!("no item '{id}'")),
1203                    )?;
1204                let mut changed = BTreeMap::new();
1205                for spec in kind_fields(item.kind, &currency) {
1206                    if let Some(value) = optional(&fields, &spec.id) {
1207                        changed.insert(spec.id.clone(), typed(&spec, value)?);
1208                    }
1209                }
1210                let body = body.filter(|b| !b.trim().is_empty());
1211                let outcome = runtime
1212                    .pipeline()
1213                    .correct(
1214                        &ContentId(id),
1215                        move |item| {
1216                            item.fields.extend(changed);
1217                            if let Some(body) = body {
1218                                item.body = Some(Markdown(body));
1219                            }
1220                        },
1221                        &text,
1222                        person,
1223                        EntryPoint::WebEditor,
1224                    )
1225                    .await
1226                    .map_err(site)?;
1227                let (line, draft) = self.adopt(outcome, person).await;
1228                note = Some(line);
1229                current = draft;
1230            }
1231            EditorCommand::Withdraw { id, notice } => {
1232                self.require(person, &EDITING, "Withdrawing").await?;
1233                let how = match notice.map(|n| n.trim().to_string()).filter(|n| !n.is_empty()) {
1234                    Some(text) => Withdrawal::Notice(text),
1235                    None => Withdrawal::Gone,
1236                };
1237                let outcome = self
1238                    .runtime()
1239                    .await
1240                    .pipeline()
1241                    .withdraw(&ContentId(id), how, person, EntryPoint::WebEditor)
1242                    .await
1243                    .map_err(site)?;
1244                let (line, draft) = self.adopt(outcome, person).await;
1245                note = Some(line);
1246                current = draft;
1247            }
1248            EditorCommand::Discard { draft } => {
1249                self.require(person, &EDITING, "Discarding a draft").await?;
1250                let removed = self.inner.editor.lock().await.drafts.remove(&draft);
1251                if let Some(removed) = removed {
1252                    if let Some((preview, _)) = removed.preview {
1253                        let _ = tokio::fs::remove_dir_all(&preview.staged.root).await;
1254                    }
1255                    if let Some(preview) = removed.pending.and_then(|pending| pending.preview) {
1256                        let _ = tokio::fs::remove_dir_all(&preview.staged.root).await;
1257                    }
1258                }
1259                note = Some("The draft is gone; nothing was published.".into());
1260            }
1261        }
1262        let draft = match current {
1263            Some(id) => Some(self.draft_view(person, &id).await?),
1264            None => None,
1265        };
1266        Ok(EditorOutcome { home: self.editor_home(person).await?, draft, note })
1267    }
1268
1269    fn editor_draft(
1270        &self,
1271        item: ContentItem,
1272        person: &str,
1273        changes: Option<ContentId>,
1274    ) -> EditorDraft {
1275        EditorDraft {
1276            change: Change {
1277                items: vec![item],
1278                media: Vec::new(),
1279                entry: EntryPoint::WebEditor,
1280                proposer: person.to_string(),
1281                job: "web-editor".into(),
1282                action_class: "publish".into(),
1283            },
1284            changes,
1285            checks: None,
1286            preview: None,
1287            pending: None,
1288            outcome: None,
1289            done: false,
1290            scheduled: false,
1291        }
1292    }
1293
1294    /// Keeps a correction or withdrawal that waits for its chain as a draft; returns the line
1295    /// for the person and the draft's id.
1296    async fn adopt(&self, outcome: PipelineOutcome, person: &str) -> (String, Option<String>) {
1297        match outcome {
1298            PipelineOutcome::Pending { ticket, draft, preview } => {
1299                let id = self.next_id("draft");
1300                let changes = draft.change.items.first().map(|item| item.id.clone());
1301                let mut held = self.editor_draft(draft.change.items[0].clone(), person, changes);
1302                held.change = draft.change.clone();
1303                held.pending =
1304                    Some(PendingRelease { draft, preview: Some(preview), request: ticket });
1305                self.inner.editor.lock().await.drafts.insert(id.clone(), held);
1306                ("It waits for the approval chain.".into(), Some(id))
1307            }
1308            PipelineOutcome::Published(published) => {
1309                (format!("Live in release {}, signed.", published.staged.manifest.seq), None)
1310            }
1311            PipelineOutcome::Held(report) => {
1312                (format!("Held by the checks: {}", report.summary()), None)
1313            }
1314            PipelineOutcome::Rejected { by, reason } => {
1315                (format!("{by} refused it: {reason}"), None)
1316            }
1317            PipelineOutcome::Scheduled { .. } => ("Scheduled.".into(), None),
1318        }
1319    }
1320
1321    #[allow(clippy::too_many_arguments)]
1322    async fn save(
1323        &self,
1324        person: &str,
1325        id: &str,
1326        slug: &str,
1327        language: &str,
1328        fields: &FormValues,
1329        body: Option<String>,
1330        schedule: ScheduleInput,
1331    ) -> Result<String> {
1332        let slug = slug.trim();
1333        if !valid_slug(slug) {
1334            return Err(invalid(
1335                "website.editor.slug",
1336                "the address part uses lowercase letters, digits and hyphens, such as `spring-menu`",
1337            ));
1338        }
1339        let language = LanguageTag::parse(language.trim())
1340            .map_err(|e| invalid("website.editor.language", e.to_string()))?;
1341        if !self.inner.languages.iter().any(|l| l.as_str().eq_ignore_ascii_case(language.as_str()))
1342        {
1343            return Err(invalid(
1344                "website.editor.language",
1345                format!("the site is not in '{language}'"),
1346            ));
1347        }
1348        let mut state = self.inner.editor.lock().await;
1349        let draft = state
1350            .drafts
1351            .get_mut(id)
1352            .ok_or_else(|| not_found("website.editor.draft", format!("no draft '{id}'")))?;
1353        if draft.pending.is_some() || draft.done {
1354            return Err(invalid(
1355                "website.editor.locked",
1356                "this draft is waiting for approval or published",
1357            ));
1358        }
1359        if draft.change.proposer != person {
1360            return Err(forbidden(
1361                "website.editor.not_yours",
1362                "someone else is writing this draft",
1363            ));
1364        }
1365        let item = &mut draft.change.items[0];
1366        if draft.changes.as_ref().is_some_and(|_| item.slug != slug || item.language != language) {
1367            return Err(invalid(
1368                "website.editor.address",
1369                "a live item keeps its address; withdraw it and write a new one to move it",
1370            ));
1371        }
1372        for spec in kind_fields(item.kind, &self.inner.currency) {
1373            match optional(fields, &spec.id) {
1374                Some(value) => {
1375                    item.fields.insert(spec.id.clone(), typed(&spec, value)?);
1376                }
1377                None if spec.required => {
1378                    return Err(invalid("website.ui.missing", format!("{} is needed", spec.label)));
1379                }
1380                None => {
1381                    item.fields.remove(&spec.id);
1382                }
1383            }
1384        }
1385        item.slug = slug.to_string();
1386        item.id = ContentId(format!("{}/{slug}/{language}", kind_directory(item.kind)));
1387        item.language = language;
1388        item.body = body.filter(|b| !b.trim().is_empty()).map(Markdown);
1389        item.schedule = schedule.into_schedule();
1390        if let Some(schedule) = &item.schedule
1391            && let (Some(publish), Some(expires)) = (schedule.publish_at, schedule.expires_at)
1392            && expires <= publish
1393        {
1394            return Err(invalid("website.editor.schedule", "it has to end after it starts"));
1395        }
1396        item.state = ContentState::Draft;
1397        let change = draft.change.clone();
1398        let runtime = self.runtime().await;
1399        let checked = runtime.pipeline().draft(change).await.map_err(site)?;
1400        let report = runtime.pipeline().check(&checked).await.map_err(site)?;
1401        let line = if report.passed() {
1402            "Saved. Every check passed.".to_string()
1403        } else {
1404            format!("Saved. Fix before publishing: {}", report.summary())
1405        };
1406        draft.checks = Some(report);
1407        if let Some((preview, _)) = draft.preview.take() {
1408            let _ = tokio::fs::remove_dir_all(&preview.staged.root).await;
1409        }
1410        draft.outcome = None;
1411        Ok(line)
1412    }
1413
1414    async fn preview(&self, id: &str) -> Result<()> {
1415        let mut state = self.inner.editor.lock().await;
1416        let draft = state
1417            .drafts
1418            .get_mut(id)
1419            .ok_or_else(|| not_found("website.editor.draft", format!("no draft '{id}'")))?;
1420        if draft.item().slug.is_empty() {
1421            return Err(invalid("website.editor.unsaved", "save the draft first"));
1422        }
1423        let runtime = self.runtime().await;
1424        let checked = runtime.pipeline().draft(draft.change.clone()).await.map_err(site)?;
1425        let preview = runtime.pipeline().preview(&checked).await.map_err(site)?;
1426        let mut pages = Vec::new();
1427        let slug = draft.item().slug.clone();
1428        let mut diffs = preview.diff.clone();
1429        diffs.sort_by_key(|d| (!d.path.contains(&slug), d.path.clone()));
1430        for diff in diffs.iter().take(20) {
1431            let twin =
1432                diff.path.trim_start_matches('/').trim_end_matches(".html").to_string() + ".md";
1433            let markdown = tokio::fs::read_to_string(preview.staged.root.join(&twin))
1434                .await
1435                .ok()
1436                .map(|text| text.chars().take(6_000).collect());
1437            pages.push(PageView {
1438                path: diff.path.clone(),
1439                title: if diff.path.contains(&slug) {
1440                    draft.item().fields.get("title").map(field_text).unwrap_or_else(|| slug.clone())
1441                } else {
1442                    diff.path.clone()
1443                },
1444                change: words::page_change(diff.change),
1445                markdown,
1446            });
1447        }
1448        draft.checks = Some(preview.gate.clone());
1449        if let Some((old, _)) = draft.preview.replace((preview, pages)) {
1450            let _ = tokio::fs::remove_dir_all(&old.staged.root).await;
1451        }
1452        Ok(())
1453    }
1454
1455    async fn publish(&self, person: &str, id: &str) -> Result<String> {
1456        let mut state = self.inner.editor.lock().await;
1457        let draft = state
1458            .drafts
1459            .get_mut(id)
1460            .ok_or_else(|| not_found("website.editor.draft", format!("no draft '{id}'")))?;
1461        if draft.item().slug.is_empty() {
1462            return Err(invalid("website.editor.unsaved", "save the draft first"));
1463        }
1464        if draft.done {
1465            return Err(invalid("website.editor.locked", "this draft is published"));
1466        }
1467        if draft.change.proposer != person {
1468            return Err(forbidden(
1469                "website.editor.not_yours",
1470                "someone else is writing this draft",
1471            ));
1472        }
1473        // A release waiting for its chain publishes once its request is approved, on this
1474        // desk or another surface — the kernel's inbox, a chat card (#1280).
1475        let step = match draft.pending.take() {
1476            Some(pending) => self.release(pending.draft, pending.preview).await?,
1477            None => {
1478                let runtime = self.runtime().await;
1479                let checked = runtime.pipeline().draft(draft.change.clone()).await.map_err(site)?;
1480                let preview = draft.preview.take().map(|(preview, _)| preview);
1481                self.release(checked, preview).await?
1482            }
1483        };
1484        let line = outcome_words(&step);
1485        match step {
1486            ReleaseStep::Pending(pending) => draft.pending = Some(*pending),
1487            ReleaseStep::Held(_) | ReleaseStep::Frozen => {}
1488            ReleaseStep::Scheduled { .. } => {
1489                draft.done = true;
1490                draft.scheduled = true;
1491            }
1492            _ => draft.done = true,
1493        }
1494        draft.outcome = Some(line.clone());
1495        Ok(line)
1496    }
1497}
1498
1499fn draft_status(draft: &EditorDraft) -> Pill {
1500    if draft.done && draft.scheduled {
1501        Pill::new("Scheduled", Tone::Info)
1502    } else if draft.done {
1503        Pill::new("Published", Tone::Good)
1504    } else if draft.pending.is_some() {
1505        Pill::new("Waiting for approval", Tone::Waiting)
1506    } else if draft.checks.as_ref().is_some_and(|r| !r.passed()) {
1507        Pill::new("Needs a fix", Tone::Bad)
1508    } else {
1509        Pill::new("Draft", Tone::Neutral)
1510    }
1511}
1512
1513/// A form value as the field's type (spec 3.5 §7.8.2): numbers as numbers, times as RFC 3339.
1514fn typed(spec: &FieldSpec, value: &str) -> Result<Value> {
1515    Ok(match spec.kind {
1516        FieldKind::Number => {
1517            let number: f64 = value.replace(',', "").parse().map_err(|_| {
1518                invalid("website.editor.number", format!("{} is a number", spec.label))
1519            })?;
1520            if !number.is_finite() || number < 0.0 {
1521                return Err(invalid(
1522                    "website.editor.number",
1523                    format!("{} is zero or more", spec.label),
1524                ));
1525            }
1526            serde_json::Number::from_f64(number).map_or(Value::Null, Value::Number)
1527        }
1528        FieldKind::DateTime => {
1529            let at = DateTime::parse_from_rfc3339(value).map_err(|_| {
1530                invalid("website.editor.time", format!("{} is a date and time", spec.label))
1531            })?;
1532            Value::String(at.with_timezone(&Utc).to_rfc3339_opts(chrono::SecondsFormat::Secs, true))
1533        }
1534        _ => Value::String(value.to_string()),
1535    })
1536}
1537
1538#[cfg(test)]
1539mod tests {
1540    use super::*;
1541
1542    #[test]
1543    fn every_kind_has_a_form_with_its_claims() {
1544        let product = kind_fields(ContentKind::Product, "KES");
1545        let ids: Vec<&str> = product.iter().map(|f| f.id.as_str()).collect();
1546        assert_eq!(ids, ["title", "summary", "price", "currency", "sku", "validUntil"]);
1547        assert!(product.iter().all(|f| f.id != "stock"), "stock is live, never a released claim");
1548        for kind in KINDS {
1549            assert_eq!(kind_from(&kind_id(kind)).unwrap(), kind);
1550        }
1551    }
1552
1553    #[test]
1554    fn values_take_their_fields_types() {
1555        let price = FieldSpec::new("price", "Price", FieldKind::Number);
1556        assert_eq!(typed(&price, "1,250.50").unwrap(), serde_json::json!(1250.5));
1557        assert!(typed(&price, "-1").is_err());
1558        let starts = FieldSpec::new("startsAt", "Starts", FieldKind::DateTime);
1559        assert_eq!(typed(&starts, "2026-11-02T09:00:00+03:00").unwrap(), "2026-11-02T06:00:00Z");
1560        assert!(typed(&starts, "tomorrow").is_err());
1561    }
1562
1563    #[test]
1564    fn slugs_are_address_parts() {
1565        assert!(valid_slug("spring-menu-2"));
1566        assert!(!valid_slug("Spring menu"));
1567        assert!(!valid_slug("../etc"));
1568        assert!(!valid_slug("-x"));
1569    }
1570}