1pub mod charter;
34pub mod editor;
35pub mod onboarding;
36pub mod review;
37mod saved;
38pub mod setup;
39pub mod site;
40mod words;
41
42use std::collections::BTreeMap;
43use std::sync::Arc;
44use std::sync::atomic::{AtomicU64, Ordering};
45
46use adk_core::audit_log::AuditTrail;
47use adk_core::{AdkError, Clock, ErrorCategory, ErrorComponent, Result, SystemClock};
48use adk_harness::website::{SiteRef, SiteRuntime};
49use adk_harness::{FactScope, FactStore, StandingRuleStore};
50use adk_kernel::PartitionId;
51use adk_kernel::channels::ChannelSink;
52use adk_kernel::charter::{AutonomyLadder, CharterStore, KpiTracker, SignalStore};
53use adk_payments::wallet::{Wallet, WalletStore};
54use adk_site::media::MediaPipeline;
55use adk_site::migrate::{SiteSource, SourceContext};
56use adk_site::updates::UpdateEngine;
57use async_trait::async_trait;
58use awp_types::{LanguageTag, Role};
59use schemars::JsonSchema;
60use serde::{Deserialize, Serialize};
61use tokio::sync::{Mutex, RwLock};
62
63use crate::alarms::AlarmRouter;
64use crate::incident::{IncidentPath, StatusSink};
65use crate::onboarding::cost::CostInputs;
66use crate::review::{ReviewComposer, ReviewInputs};
67use crate::themes::ThemeId;
68use crate::wallet::WalletKpi;
69
70pub use charter::{CharterReview, SectionCard, SignerLine};
71pub use editor::{DraftView, EditorCommand, EditorHome, EditorOutcome, KindForm};
72pub use onboarding::{OnboardingCommand, OnboardingOutcome, OnboardingView};
73pub use review::{ReviewCommand, ReviewPage, ReviewView};
74pub use saved::{DeskStore, FileDeskStore, InMemoryDeskStore, SavedDesk};
75pub use setup::{ClaimedView, SetupView};
76pub use site::{SiteCommand, SiteOutcome, SiteViewModel};
77
78#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
81#[serde(rename_all = "camelCase")]
82pub enum Tone {
83 Good,
85 Waiting,
87 Bad,
89 Info,
91 Neutral,
93}
94
95#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
97#[serde(rename_all = "camelCase")]
98pub struct Pill {
99 pub text: String,
101 pub tone: Tone,
103}
104
105impl Pill {
106 pub fn new(text: impl Into<String>, tone: Tone) -> Self {
108 Self { text: text.into(), tone }
109 }
110}
111
112#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
114#[serde(rename_all = "camelCase")]
115pub struct Line {
116 pub label: String,
118 pub value: String,
120}
121
122impl Line {
123 pub(crate) fn new(label: impl Into<String>, value: impl Into<String>) -> Self {
124 Self { label: label.into(), value: value.into() }
125 }
126}
127
128#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
130#[serde(rename_all = "camelCase")]
131pub enum FieldKind {
132 Text,
134 LongText,
136 Markdown,
138 Email,
140 Tel,
142 Url,
144 Number,
146 DateTime,
148 Time,
150 Choice,
152}
153
154#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
156#[serde(rename_all = "camelCase")]
157pub struct FieldOption {
158 pub value: String,
160 pub label: String,
162}
163
164#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
166#[serde(rename_all = "camelCase")]
167pub struct FieldSpec {
168 pub id: String,
170 pub label: String,
172 pub kind: FieldKind,
174 pub required: bool,
176 #[serde(default, skip_serializing_if = "Option::is_none")]
178 pub hint: Option<String>,
179 #[serde(default, skip_serializing_if = "Vec::is_empty")]
181 pub options: Vec<FieldOption>,
182 #[serde(default, skip_serializing_if = "Option::is_none")]
184 pub value: Option<String>,
185}
186
187impl FieldSpec {
188 pub(crate) fn new(id: &str, label: &str, kind: FieldKind) -> Self {
189 Self {
190 id: id.into(),
191 label: label.into(),
192 kind,
193 required: false,
194 hint: None,
195 options: Vec::new(),
196 value: None,
197 }
198 }
199
200 pub(crate) fn required(mut self) -> Self {
201 self.required = true;
202 self
203 }
204
205 pub(crate) fn hint(mut self, hint: impl Into<String>) -> Self {
206 self.hint = Some(hint.into());
207 self
208 }
209
210 pub(crate) fn value(mut self, value: impl Into<String>) -> Self {
211 let value = value.into();
212 self.value = (!value.is_empty()).then_some(value);
213 self
214 }
215
216 pub(crate) fn options(mut self, options: impl IntoIterator<Item = (String, String)>) -> Self {
217 self.options =
218 options.into_iter().map(|(value, label)| FieldOption { value, label }).collect();
219 self
220 }
221}
222
223pub trait SiteAssembly: Send + Sync {
235 fn runtime(&self, theme: Option<ThemeId>) -> Arc<SiteRuntime>;
237}
238
239#[derive(
241 Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, JsonSchema,
242)]
243#[serde(rename_all = "camelCase")]
244pub enum ConnectionKind {
245 Domain,
247 Email,
249 OwnerChannel,
251 Analytics,
253 Payment,
255}
256
257#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
259#[serde(rename_all = "camelCase")]
260pub enum ConnectMethod {
261 OAuth,
263 Broker,
265 Pairing,
267}
268
269#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
271#[serde(tag = "type", rename_all = "camelCase", rename_all_fields = "camelCase")]
272pub enum ConnectStep {
273 Open {
275 url: String,
277 },
278 Code {
280 code: String,
282 how: String,
284 },
285 Done,
287}
288
289#[async_trait]
293pub trait Connector: Send + Sync {
294 fn id(&self) -> &str;
296 fn kind(&self) -> ConnectionKind;
298 fn service(&self) -> &str;
300 fn method(&self) -> ConnectMethod;
302 async fn start(&self, person: &str) -> Result<ConnectStep>;
308 async fn connected(&self) -> Result<Option<String>>;
314}
315
316#[async_trait]
319pub trait ReviewNotes: Send + Sync {
320 async fn notes(&self, week_start: chrono::NaiveDate) -> Result<ReviewInputs>;
326}
327
328#[derive(Clone)]
330pub struct WalletParts {
331 pub wallet: Wallet,
333 pub store: Arc<dyn WalletStore>,
335 pub kpi: Arc<WalletKpi>,
337}
338
339pub(crate) struct Desk {
340 pub(crate) site: SiteRef,
341 pub(crate) name: String,
342 pub(crate) owner: String,
343 pub(crate) languages: Vec<LanguageTag>,
344 pub(crate) currency: String,
345 pub(crate) clock: Arc<dyn Clock>,
346 pub(crate) audit: Option<AuditTrail>,
347 pub(crate) runtime: RwLock<Arc<SiteRuntime>>,
348 pub(crate) assembly: Option<Arc<dyn SiteAssembly>>,
349 pub(crate) setup: Option<Arc<crate::onboarding::SetupGate>>,
350 pub(crate) facts: Option<(Arc<dyn FactStore>, FactScope)>,
351 pub(crate) charters: Option<Arc<dyn CharterStore>>,
352 pub(crate) ladder: Option<AutonomyLadder>,
353 pub(crate) rules: Option<Arc<dyn StandingRuleStore>>,
354 pub(crate) status: Option<Arc<dyn StatusSink>>,
355 pub(crate) tracker: Option<KpiTracker>,
356 pub(crate) signals: Option<(Arc<dyn SignalStore>, PartitionId)>,
357 pub(crate) wallet: Option<WalletParts>,
358 pub(crate) updates: Option<Arc<UpdateEngine>>,
359 pub(crate) alarms: Option<Arc<AlarmRouter>>,
360 pub(crate) incidents: Option<Arc<IncidentPath>>,
361 pub(crate) composer: Option<ReviewComposer>,
362 pub(crate) notes: Option<Arc<dyn ReviewNotes>>,
363 pub(crate) store: Option<saved::SharedDeskStore>,
364 pub(crate) quotes: Option<Arc<crate::quotes::ReviewQuotes>>,
365 pub(crate) channel: Option<(Arc<dyn ChannelSink>, String)>,
366 pub(crate) discovery: Option<(SourceContext, Option<Arc<dyn SiteSource>>)>,
367 pub(crate) connectors: Vec<Arc<dyn Connector>>,
368 pub(crate) cost: Option<CostInputs>,
369 pub(crate) shape: String,
370 pub(crate) jurisdictions: Vec<String>,
371 pub(crate) media: MediaPipeline,
372 pub(crate) paired: Mutex<Option<String>>,
373 pub(crate) onboarding: Mutex<onboarding::State>,
374 pub(crate) charter: Mutex<charter::State>,
375 pub(crate) reviews: Mutex<review::State>,
376 pub(crate) editor: Mutex<editor::State>,
377 next: AtomicU64,
378}
379
380#[derive(Clone)]
397pub struct WebsiteDesk {
398 pub(crate) inner: Arc<Desk>,
399}
400
401impl std::fmt::Debug for WebsiteDesk {
402 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
403 f.debug_struct("WebsiteDesk").field("site", &self.inner.site).finish_non_exhaustive()
404 }
405}
406
407pub struct WebsiteDeskBuilder {
409 desk: Desk,
410}
411
412macro_rules! setter {
413 ($(#[$doc:meta])* $name:ident, $field:ident: $ty:ty) => {
414 $(#[$doc])*
415 #[must_use]
416 pub fn $name(mut self, value: $ty) -> Self {
417 self.desk.$field = Some(value);
418 self
419 }
420 };
421}
422
423impl WebsiteDeskBuilder {
424 #[must_use]
426 pub fn languages(mut self, languages: Vec<LanguageTag>) -> Self {
427 if !languages.is_empty() {
428 self.desk.languages = languages;
429 }
430 self
431 }
432
433 #[must_use]
435 pub fn currency(mut self, currency: impl Into<String>) -> Self {
436 self.desk.currency = currency.into().to_ascii_uppercase();
437 self
438 }
439
440 #[must_use]
442 pub fn clock(mut self, clock: Arc<dyn Clock>) -> Self {
443 self.desk.clock = clock;
444 self
445 }
446
447 #[must_use]
449 pub fn audit(mut self, trail: AuditTrail) -> Self {
450 self.desk.audit = Some(trail);
451 self
452 }
453
454 #[must_use]
456 pub fn assembly(mut self, assembly: Arc<dyn SiteAssembly>) -> Self {
457 self.desk.assembly = Some(assembly);
458 self
459 }
460
461 #[must_use]
463 pub fn setup(mut self, gate: Arc<crate::onboarding::SetupGate>) -> Self {
464 self.desk.setup = Some(gate);
465 self
466 }
467
468 #[must_use]
470 pub fn facts(mut self, facts: Arc<dyn FactStore>, scope: FactScope) -> Self {
471 self.desk.facts = Some((facts, scope));
472 self
473 }
474
475 setter!(
476 charters, charters: Arc<dyn CharterStore>
478 );
479
480 #[must_use]
483 pub fn ladder(mut self, ladder: AutonomyLadder, rules: Arc<dyn StandingRuleStore>) -> Self {
484 self.desk.ladder = Some(ladder);
485 self.desk.rules = Some(rules);
486 self
487 }
488
489 setter!(
490 status, status: Arc<dyn StatusSink>
492 );
493 setter!(
494 tracker, tracker: KpiTracker
496 );
497
498 #[must_use]
500 pub fn signals(mut self, store: Arc<dyn SignalStore>, partition: PartitionId) -> Self {
501 self.desk.signals = Some((store, partition));
502 self
503 }
504
505 setter!(
506 wallet, wallet: WalletParts
508 );
509 setter!(
510 updates, updates: Arc<UpdateEngine>
512 );
513 setter!(
514 alarms, alarms: Arc<AlarmRouter>
516 );
517 setter!(
518 incidents, incidents: Arc<IncidentPath>
520 );
521 setter!(
522 composer, composer: ReviewComposer
524 );
525 setter!(
526 notes, notes: Arc<dyn ReviewNotes>
528 );
529
530 #[must_use]
533 pub fn store(mut self, store: Arc<dyn DeskStore>) -> Self {
534 self.desk.store = Some(store);
535 self
536 }
537
538 #[must_use]
541 pub fn quotes(mut self, quotes: Arc<crate::quotes::ReviewQuotes>) -> Self {
542 self.desk.quotes = Some(quotes);
543 self
544 }
545
546 #[must_use]
548 pub fn channel(mut self, sink: Arc<dyn ChannelSink>, thread: impl Into<String>) -> Self {
549 self.desk.channel = Some((sink, thread.into()));
550 self
551 }
552
553 #[must_use]
557 pub fn discovery(
558 mut self,
559 context: SourceContext,
560 source: Option<Arc<dyn SiteSource>>,
561 ) -> Self {
562 self.desk.discovery = Some((context, source));
563 self
564 }
565
566 #[must_use]
568 pub fn connector(mut self, connector: Arc<dyn Connector>) -> Self {
569 self.desk.connectors.push(connector);
570 self
571 }
572
573 #[must_use]
575 pub fn cost(mut self, inputs: CostInputs) -> Self {
576 self.desk.cost = Some(inputs);
577 self
578 }
579
580 #[must_use]
582 pub fn shape(mut self, shape: impl Into<String>) -> Self {
583 self.desk.shape = shape.into();
584 self
585 }
586
587 #[must_use]
590 pub fn jurisdictions(mut self, jurisdictions: Vec<String>) -> Self {
591 self.desk.jurisdictions = jurisdictions;
592 self
593 }
594
595 #[must_use]
597 pub fn media(mut self, media: MediaPipeline) -> Self {
598 self.desk.media = media;
599 self
600 }
601
602 pub fn build(self) -> WebsiteDesk {
604 WebsiteDesk { inner: Arc::new(self.desk) }
605 }
606}
607
608impl WebsiteDesk {
609 pub fn builder(
612 site: SiteRef,
613 name: impl Into<String>,
614 owner: impl Into<String>,
615 runtime: Arc<SiteRuntime>,
616 ) -> WebsiteDeskBuilder {
617 WebsiteDeskBuilder {
618 desk: Desk {
619 site,
620 name: name.into(),
621 owner: owner.into(),
622 languages: vec![LanguageTag::parse("en").expect("a valid tag")],
623 currency: "USD".into(),
624 clock: Arc::new(SystemClock),
625 audit: None,
626 runtime: RwLock::new(runtime),
627 assembly: None,
628 setup: None,
629 facts: None,
630 charters: None,
631 ladder: None,
632 rules: None,
633 status: None,
634 tracker: None,
635 signals: None,
636 wallet: None,
637 updates: None,
638 alarms: None,
639 incidents: None,
640 composer: None,
641 notes: None,
642 store: None,
643 quotes: None,
644 channel: None,
645 discovery: None,
646 connectors: Vec::new(),
647 cost: None,
648 shape: "Single server or container".into(),
649 jurisdictions: Vec::new(),
650 media: MediaPipeline::default(),
651 paired: Mutex::new(None),
652 onboarding: Mutex::new(onboarding::State::default()),
653 charter: Mutex::new(charter::State::default()),
654 reviews: Mutex::new(review::State::default()),
655 editor: Mutex::new(editor::State::default()),
656 next: AtomicU64::new(1),
657 },
658 }
659 }
660
661 pub fn site(&self) -> &SiteRef {
663 &self.inner.site
664 }
665
666 pub fn name(&self) -> &str {
668 &self.inner.name
669 }
670
671 pub async fn runtime(&self) -> Arc<SiteRuntime> {
673 self.inner.runtime.read().await.clone()
674 }
675
676 pub(crate) fn bump_next(&self, at_least: u64) {
677 self.inner.next.fetch_max(at_least, Ordering::Relaxed);
678 }
679
680 pub(crate) fn next_id(&self, prefix: &str) -> String {
681 let n = self.inner.next.fetch_add(1, Ordering::Relaxed);
682 format!("{prefix}-{n}")
683 }
684
685 pub(crate) fn now(&self) -> chrono::DateTime<chrono::Utc> {
686 self.inner.clock.now()
687 }
688
689 pub async fn roles(&self, person: &str) -> Result<Vec<Role>> {
697 if adk_kernel::charter::is_agent_principal(person) {
698 return Ok(Vec::new());
699 }
700 if let Some(charters) = &self.inner.charters
701 && let Some(current) = charters.current(self.inner.site.id).await.map_err(kernel)?
702 {
703 return Ok(current
704 .charter
705 .governance
706 .roles
707 .iter()
708 .filter(|held| held.principal == person)
709 .flat_map(|held| held.roles.iter().copied())
710 .collect());
711 }
712 Ok(if person == self.inner.owner {
713 vec![Role::Owner, Role::Editor, Role::Publisher]
714 } else {
715 Vec::new()
716 })
717 }
718
719 pub(crate) async fn require(&self, person: &str, any: &[Role], what: &str) -> Result<()> {
721 let held = self.roles(person).await?;
722 if any.iter().any(|role| held.contains(role)) {
723 return Ok(());
724 }
725 let names: Vec<&str> = any.iter().map(|role| words::role(*role)).collect();
726 Err(forbidden(
727 "website.ui.not_allowed",
728 format!(
729 "{what} needs the {} role in the site's charter; {person} does not hold it",
730 names.join(" or ").to_lowercase()
731 ),
732 ))
733 }
734}
735
736pub(crate) fn forbidden(code: &'static str, message: impl Into<String>) -> AdkError {
737 AdkError::new(ErrorComponent::Server, ErrorCategory::Forbidden, code, message)
738}
739
740pub(crate) fn invalid(code: &'static str, message: impl Into<String>) -> AdkError {
741 AdkError::new(ErrorComponent::Server, ErrorCategory::InvalidInput, code, message)
742}
743
744pub(crate) fn not_found(code: &'static str, message: impl Into<String>) -> AdkError {
745 AdkError::new(ErrorComponent::Server, ErrorCategory::NotFound, code, message)
746}
747
748pub(crate) fn unavailable(what: &str) -> AdkError {
749 AdkError::new(
750 ErrorComponent::Server,
751 ErrorCategory::Unsupported,
752 "website.ui.not_configured",
753 format!(
754 "{what} is not set up on this site's desk; the host adds it to WebsiteDesk::builder"
755 ),
756 )
757}
758
759pub(crate) fn kernel(error: adk_kernel::KernelError) -> AdkError {
760 let category = match &error {
761 adk_kernel::KernelError::Unauthorized { .. } => ErrorCategory::Forbidden,
762 adk_kernel::KernelError::Config { .. } => ErrorCategory::InvalidInput,
763 _ => ErrorCategory::Internal,
764 };
765 AdkError::new(ErrorComponent::Server, category, "website.ui.kernel", error.to_string())
766}
767
768pub(crate) fn site(error: adk_site::SiteError) -> AdkError {
769 let category = match &error {
770 adk_site::SiteError::NotFound(_) | adk_site::SiteError::ReleaseNotFound { .. } => {
771 ErrorCategory::NotFound
772 }
773 adk_site::SiteError::InvalidContent { .. }
774 | adk_site::SiteError::GateFailed(_)
775 | adk_site::SiteError::MediaRefused { .. } => ErrorCategory::InvalidInput,
776 adk_site::SiteError::ServerCode { .. } => ErrorCategory::Forbidden,
777 _ => ErrorCategory::Internal,
778 };
779 AdkError::new(ErrorComponent::Server, category, "website.ui.site", error.to_string())
780}
781
782pub type FormValues = BTreeMap<String, String>;
784
785pub(crate) fn required<'a>(values: &'a FormValues, field: &str, label: &str) -> Result<&'a str> {
787 values
788 .get(field)
789 .map(|value| value.trim())
790 .filter(|value| !value.is_empty())
791 .ok_or_else(|| invalid("website.ui.missing", format!("{label} is needed")))
792}
793
794pub(crate) fn optional<'a>(values: &'a FormValues, field: &str) -> Option<&'a str> {
796 values.get(field).map(|value| value.trim()).filter(|value| !value.is_empty())
797}