pub mod charter;
pub mod editor;
pub mod onboarding;
pub mod review;
mod saved;
pub mod setup;
pub mod site;
mod words;
use std::collections::BTreeMap;
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
use adk_core::audit_log::AuditTrail;
use adk_core::{AdkError, Clock, ErrorCategory, ErrorComponent, Result, SystemClock};
use adk_harness::website::{SiteRef, SiteRuntime};
use adk_harness::{FactScope, FactStore, StandingRuleStore};
use adk_kernel::PartitionId;
use adk_kernel::channels::ChannelSink;
use adk_kernel::charter::{AutonomyLadder, CharterStore, KpiTracker, SignalStore};
use adk_payments::wallet::{Wallet, WalletStore};
use adk_site::media::MediaPipeline;
use adk_site::migrate::{SiteSource, SourceContext};
use adk_site::updates::UpdateEngine;
use async_trait::async_trait;
use awp_types::{LanguageTag, Role};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use tokio::sync::{Mutex, RwLock};
use crate::alarms::AlarmRouter;
use crate::incident::{IncidentPath, StatusSink};
use crate::onboarding::cost::CostInputs;
use crate::review::{ReviewComposer, ReviewInputs};
use crate::themes::ThemeId;
use crate::wallet::WalletKpi;
pub use charter::{CharterReview, SectionCard, SignerLine};
pub use editor::{DraftView, EditorCommand, EditorHome, EditorOutcome, KindForm};
pub use onboarding::{OnboardingCommand, OnboardingOutcome, OnboardingView};
pub use review::{ReviewCommand, ReviewPage, ReviewView};
pub use saved::{DeskStore, FileDeskStore, InMemoryDeskStore, SavedDesk};
pub use setup::{ClaimedView, SetupView};
pub use site::{SiteCommand, SiteOutcome, SiteViewModel};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub enum Tone {
Good,
Waiting,
Bad,
Info,
Neutral,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct Pill {
pub text: String,
pub tone: Tone,
}
impl Pill {
pub fn new(text: impl Into<String>, tone: Tone) -> Self {
Self { text: text.into(), tone }
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct Line {
pub label: String,
pub value: String,
}
impl Line {
pub(crate) fn new(label: impl Into<String>, value: impl Into<String>) -> Self {
Self { label: label.into(), value: value.into() }
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub enum FieldKind {
Text,
LongText,
Markdown,
Email,
Tel,
Url,
Number,
DateTime,
Time,
Choice,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct FieldOption {
pub value: String,
pub label: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct FieldSpec {
pub id: String,
pub label: String,
pub kind: FieldKind,
pub required: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub hint: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub options: Vec<FieldOption>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub value: Option<String>,
}
impl FieldSpec {
pub(crate) fn new(id: &str, label: &str, kind: FieldKind) -> Self {
Self {
id: id.into(),
label: label.into(),
kind,
required: false,
hint: None,
options: Vec::new(),
value: None,
}
}
pub(crate) fn required(mut self) -> Self {
self.required = true;
self
}
pub(crate) fn hint(mut self, hint: impl Into<String>) -> Self {
self.hint = Some(hint.into());
self
}
pub(crate) fn value(mut self, value: impl Into<String>) -> Self {
let value = value.into();
self.value = (!value.is_empty()).then_some(value);
self
}
pub(crate) fn options(mut self, options: impl IntoIterator<Item = (String, String)>) -> Self {
self.options =
options.into_iter().map(|(value, label)| FieldOption { value, label }).collect();
self
}
}
pub trait SiteAssembly: Send + Sync {
fn runtime(&self, theme: Option<ThemeId>) -> Arc<SiteRuntime>;
}
#[derive(
Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, JsonSchema,
)]
#[serde(rename_all = "camelCase")]
pub enum ConnectionKind {
Domain,
Email,
OwnerChannel,
Analytics,
Payment,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub enum ConnectMethod {
OAuth,
Broker,
Pairing,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(tag = "type", rename_all = "camelCase", rename_all_fields = "camelCase")]
pub enum ConnectStep {
Open {
url: String,
},
Code {
code: String,
how: String,
},
Done,
}
#[async_trait]
pub trait Connector: Send + Sync {
fn id(&self) -> &str;
fn kind(&self) -> ConnectionKind;
fn service(&self) -> &str;
fn method(&self) -> ConnectMethod;
async fn start(&self, person: &str) -> Result<ConnectStep>;
async fn connected(&self) -> Result<Option<String>>;
}
#[async_trait]
pub trait ReviewNotes: Send + Sync {
async fn notes(&self, week_start: chrono::NaiveDate) -> Result<ReviewInputs>;
}
#[derive(Clone)]
pub struct WalletParts {
pub wallet: Wallet,
pub store: Arc<dyn WalletStore>,
pub kpi: Arc<WalletKpi>,
}
pub(crate) struct Desk {
pub(crate) site: SiteRef,
pub(crate) name: String,
pub(crate) owner: String,
pub(crate) languages: Vec<LanguageTag>,
pub(crate) currency: String,
pub(crate) clock: Arc<dyn Clock>,
pub(crate) audit: Option<AuditTrail>,
pub(crate) runtime: RwLock<Arc<SiteRuntime>>,
pub(crate) assembly: Option<Arc<dyn SiteAssembly>>,
pub(crate) setup: Option<Arc<crate::onboarding::SetupGate>>,
pub(crate) facts: Option<(Arc<dyn FactStore>, FactScope)>,
pub(crate) charters: Option<Arc<dyn CharterStore>>,
pub(crate) ladder: Option<AutonomyLadder>,
pub(crate) rules: Option<Arc<dyn StandingRuleStore>>,
pub(crate) status: Option<Arc<dyn StatusSink>>,
pub(crate) tracker: Option<KpiTracker>,
pub(crate) signals: Option<(Arc<dyn SignalStore>, PartitionId)>,
pub(crate) wallet: Option<WalletParts>,
pub(crate) updates: Option<Arc<UpdateEngine>>,
pub(crate) alarms: Option<Arc<AlarmRouter>>,
pub(crate) incidents: Option<Arc<IncidentPath>>,
pub(crate) composer: Option<ReviewComposer>,
pub(crate) notes: Option<Arc<dyn ReviewNotes>>,
pub(crate) store: Option<saved::SharedDeskStore>,
pub(crate) quotes: Option<Arc<crate::quotes::ReviewQuotes>>,
pub(crate) channel: Option<(Arc<dyn ChannelSink>, String)>,
pub(crate) discovery: Option<(SourceContext, Option<Arc<dyn SiteSource>>)>,
pub(crate) connectors: Vec<Arc<dyn Connector>>,
pub(crate) cost: Option<CostInputs>,
pub(crate) shape: String,
pub(crate) jurisdictions: Vec<String>,
pub(crate) media: MediaPipeline,
pub(crate) paired: Mutex<Option<String>>,
pub(crate) onboarding: Mutex<onboarding::State>,
pub(crate) charter: Mutex<charter::State>,
pub(crate) reviews: Mutex<review::State>,
pub(crate) editor: Mutex<editor::State>,
next: AtomicU64,
}
#[derive(Clone)]
pub struct WebsiteDesk {
pub(crate) inner: Arc<Desk>,
}
impl std::fmt::Debug for WebsiteDesk {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("WebsiteDesk").field("site", &self.inner.site).finish_non_exhaustive()
}
}
pub struct WebsiteDeskBuilder {
desk: Desk,
}
macro_rules! setter {
($(#[$doc:meta])* $name:ident, $field:ident: $ty:ty) => {
$(#[$doc])*
#[must_use]
pub fn $name(mut self, value: $ty) -> Self {
self.desk.$field = Some(value);
self
}
};
}
impl WebsiteDeskBuilder {
#[must_use]
pub fn languages(mut self, languages: Vec<LanguageTag>) -> Self {
if !languages.is_empty() {
self.desk.languages = languages;
}
self
}
#[must_use]
pub fn currency(mut self, currency: impl Into<String>) -> Self {
self.desk.currency = currency.into().to_ascii_uppercase();
self
}
#[must_use]
pub fn clock(mut self, clock: Arc<dyn Clock>) -> Self {
self.desk.clock = clock;
self
}
#[must_use]
pub fn audit(mut self, trail: AuditTrail) -> Self {
self.desk.audit = Some(trail);
self
}
#[must_use]
pub fn assembly(mut self, assembly: Arc<dyn SiteAssembly>) -> Self {
self.desk.assembly = Some(assembly);
self
}
#[must_use]
pub fn setup(mut self, gate: Arc<crate::onboarding::SetupGate>) -> Self {
self.desk.setup = Some(gate);
self
}
#[must_use]
pub fn facts(mut self, facts: Arc<dyn FactStore>, scope: FactScope) -> Self {
self.desk.facts = Some((facts, scope));
self
}
setter!(
charters, charters: Arc<dyn CharterStore>
);
#[must_use]
pub fn ladder(mut self, ladder: AutonomyLadder, rules: Arc<dyn StandingRuleStore>) -> Self {
self.desk.ladder = Some(ladder);
self.desk.rules = Some(rules);
self
}
setter!(
status, status: Arc<dyn StatusSink>
);
setter!(
tracker, tracker: KpiTracker
);
#[must_use]
pub fn signals(mut self, store: Arc<dyn SignalStore>, partition: PartitionId) -> Self {
self.desk.signals = Some((store, partition));
self
}
setter!(
wallet, wallet: WalletParts
);
setter!(
updates, updates: Arc<UpdateEngine>
);
setter!(
alarms, alarms: Arc<AlarmRouter>
);
setter!(
incidents, incidents: Arc<IncidentPath>
);
setter!(
composer, composer: ReviewComposer
);
setter!(
notes, notes: Arc<dyn ReviewNotes>
);
#[must_use]
pub fn store(mut self, store: Arc<dyn DeskStore>) -> Self {
self.desk.store = Some(store);
self
}
#[must_use]
pub fn quotes(mut self, quotes: Arc<crate::quotes::ReviewQuotes>) -> Self {
self.desk.quotes = Some(quotes);
self
}
#[must_use]
pub fn channel(mut self, sink: Arc<dyn ChannelSink>, thread: impl Into<String>) -> Self {
self.desk.channel = Some((sink, thread.into()));
self
}
#[must_use]
pub fn discovery(
mut self,
context: SourceContext,
source: Option<Arc<dyn SiteSource>>,
) -> Self {
self.desk.discovery = Some((context, source));
self
}
#[must_use]
pub fn connector(mut self, connector: Arc<dyn Connector>) -> Self {
self.desk.connectors.push(connector);
self
}
#[must_use]
pub fn cost(mut self, inputs: CostInputs) -> Self {
self.desk.cost = Some(inputs);
self
}
#[must_use]
pub fn shape(mut self, shape: impl Into<String>) -> Self {
self.desk.shape = shape.into();
self
}
#[must_use]
pub fn jurisdictions(mut self, jurisdictions: Vec<String>) -> Self {
self.desk.jurisdictions = jurisdictions;
self
}
#[must_use]
pub fn media(mut self, media: MediaPipeline) -> Self {
self.desk.media = media;
self
}
pub fn build(self) -> WebsiteDesk {
WebsiteDesk { inner: Arc::new(self.desk) }
}
}
impl WebsiteDesk {
pub fn builder(
site: SiteRef,
name: impl Into<String>,
owner: impl Into<String>,
runtime: Arc<SiteRuntime>,
) -> WebsiteDeskBuilder {
WebsiteDeskBuilder {
desk: Desk {
site,
name: name.into(),
owner: owner.into(),
languages: vec![LanguageTag::parse("en").expect("a valid tag")],
currency: "USD".into(),
clock: Arc::new(SystemClock),
audit: None,
runtime: RwLock::new(runtime),
assembly: None,
setup: None,
facts: None,
charters: None,
ladder: None,
rules: None,
status: None,
tracker: None,
signals: None,
wallet: None,
updates: None,
alarms: None,
incidents: None,
composer: None,
notes: None,
store: None,
quotes: None,
channel: None,
discovery: None,
connectors: Vec::new(),
cost: None,
shape: "Single server or container".into(),
jurisdictions: Vec::new(),
media: MediaPipeline::default(),
paired: Mutex::new(None),
onboarding: Mutex::new(onboarding::State::default()),
charter: Mutex::new(charter::State::default()),
reviews: Mutex::new(review::State::default()),
editor: Mutex::new(editor::State::default()),
next: AtomicU64::new(1),
},
}
}
pub fn site(&self) -> &SiteRef {
&self.inner.site
}
pub fn name(&self) -> &str {
&self.inner.name
}
pub async fn runtime(&self) -> Arc<SiteRuntime> {
self.inner.runtime.read().await.clone()
}
pub(crate) fn bump_next(&self, at_least: u64) {
self.inner.next.fetch_max(at_least, Ordering::Relaxed);
}
pub(crate) fn next_id(&self, prefix: &str) -> String {
let n = self.inner.next.fetch_add(1, Ordering::Relaxed);
format!("{prefix}-{n}")
}
pub(crate) fn now(&self) -> chrono::DateTime<chrono::Utc> {
self.inner.clock.now()
}
pub async fn roles(&self, person: &str) -> Result<Vec<Role>> {
if adk_kernel::charter::is_agent_principal(person) {
return Ok(Vec::new());
}
if let Some(charters) = &self.inner.charters
&& let Some(current) = charters.current(self.inner.site.id).await.map_err(kernel)?
{
return Ok(current
.charter
.governance
.roles
.iter()
.filter(|held| held.principal == person)
.flat_map(|held| held.roles.iter().copied())
.collect());
}
Ok(if person == self.inner.owner {
vec![Role::Owner, Role::Editor, Role::Publisher]
} else {
Vec::new()
})
}
pub(crate) async fn require(&self, person: &str, any: &[Role], what: &str) -> Result<()> {
let held = self.roles(person).await?;
if any.iter().any(|role| held.contains(role)) {
return Ok(());
}
let names: Vec<&str> = any.iter().map(|role| words::role(*role)).collect();
Err(forbidden(
"website.ui.not_allowed",
format!(
"{what} needs the {} role in the site's charter; {person} does not hold it",
names.join(" or ").to_lowercase()
),
))
}
}
pub(crate) fn forbidden(code: &'static str, message: impl Into<String>) -> AdkError {
AdkError::new(ErrorComponent::Server, ErrorCategory::Forbidden, code, message)
}
pub(crate) fn invalid(code: &'static str, message: impl Into<String>) -> AdkError {
AdkError::new(ErrorComponent::Server, ErrorCategory::InvalidInput, code, message)
}
pub(crate) fn not_found(code: &'static str, message: impl Into<String>) -> AdkError {
AdkError::new(ErrorComponent::Server, ErrorCategory::NotFound, code, message)
}
pub(crate) fn unavailable(what: &str) -> AdkError {
AdkError::new(
ErrorComponent::Server,
ErrorCategory::Unsupported,
"website.ui.not_configured",
format!(
"{what} is not set up on this site's desk; the host adds it to WebsiteDesk::builder"
),
)
}
pub(crate) fn kernel(error: adk_kernel::KernelError) -> AdkError {
let category = match &error {
adk_kernel::KernelError::Unauthorized { .. } => ErrorCategory::Forbidden,
adk_kernel::KernelError::Config { .. } => ErrorCategory::InvalidInput,
_ => ErrorCategory::Internal,
};
AdkError::new(ErrorComponent::Server, category, "website.ui.kernel", error.to_string())
}
pub(crate) fn site(error: adk_site::SiteError) -> AdkError {
let category = match &error {
adk_site::SiteError::NotFound(_) | adk_site::SiteError::ReleaseNotFound { .. } => {
ErrorCategory::NotFound
}
adk_site::SiteError::InvalidContent { .. }
| adk_site::SiteError::GateFailed(_)
| adk_site::SiteError::MediaRefused { .. } => ErrorCategory::InvalidInput,
adk_site::SiteError::ServerCode { .. } => ErrorCategory::Forbidden,
_ => ErrorCategory::Internal,
};
AdkError::new(ErrorComponent::Server, category, "website.ui.site", error.to_string())
}
pub type FormValues = BTreeMap<String, String>;
pub(crate) fn required<'a>(values: &'a FormValues, field: &str, label: &str) -> Result<&'a str> {
values
.get(field)
.map(|value| value.trim())
.filter(|value| !value.is_empty())
.ok_or_else(|| invalid("website.ui.missing", format!("{label} is needed")))
}
pub(crate) fn optional<'a>(values: &'a FormValues, field: &str) -> Option<&'a str> {
values.get(field).map(|value| value.trim()).filter(|value| !value.is_empty())
}