Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

6.4 KB
Raw Blame
//! HTTP surface for the onboarding flow.

use crate::domain::models::{DismissedPrompts, OnboardingRow, OnboardingState, PromptId};
use crate::domain::ports::OnboardingError;
use crate::domain::service::OnboardingService;
use axum::{
    Json, Router,
    extract::{FromRef, Path, State},
    http::StatusCode,
    response::{IntoResponse, Response},
    routing::{get, post},
};
use macro_authorization::{
    MacroAuthorizationExtractor, MacroAuthorizationService, MacroAuthorizationState, UserOrInternal,
};
use serde::Deserialize;
use std::sync::Arc;
use utoipa::ToSchema;

/// Body for completing onboarding.
#[derive(Debug, Deserialize, ToSchema)]
pub struct CompleteOnboardingRequest {
    /// Whether the user skipped rather than finished.
    #[serde(default)]
    pub skipped: bool,
}

/// Router state: the onboarding service plus the authorization state the
/// request extractors authenticate against (auth happens in the extractor,
/// not in host-layered middleware).
pub struct OnboardingRouterState<T, Auth> {
    /// The onboarding service implementation.
    pub service: Arc<T>,
    /// The authorization state used by the request extractors.
    pub authorization_state: MacroAuthorizationState<Auth>,
}

// Manual Clone impl so T doesn't need to be Clone (it's behind Arc).
impl<T, Auth> Clone for OnboardingRouterState<T, Auth> {
    fn clone(&self) -> Self {
        Self {
            service: self.service.clone(),
            authorization_state: self.authorization_state.clone(),
        }
    }
}

impl<T, Auth> FromRef<OnboardingRouterState<T, Auth>> for Arc<T> {
    fn from_ref(state: &OnboardingRouterState<T, Auth>) -> Self {
        state.service.clone()
    }
}

impl<T, Auth> FromRef<OnboardingRouterState<T, Auth>> for MacroAuthorizationState<Auth> {
    fn from_ref(state: &OnboardingRouterState<T, Auth>) -> Self {
        state.authorization_state.clone()
    }
}

/// Build the onboarding router.
pub fn onboarding_router<T, Auth, S>(state: OnboardingRouterState<T, Auth>) -> Router<S>
where
    T: OnboardingService,
    Auth: MacroAuthorizationService,
    S: Send + Sync + Clone + 'static,
{
    Router::new()
        .route("/onboarding", get(get_state_handler::<T, Auth>))
        .route("/onboarding/complete", post(complete_handler::<T, Auth>))
        .route(
            "/onboarding/prompts",
            get(dismissed_prompts_handler::<T, Auth>),
        )
        .route(
            "/onboarding/prompts/{prompt_id}/dismiss",
            post(dismiss_prompt_handler::<T, Auth>),
        )
        .with_state(state)
}

fn error_response(e: OnboardingError) -> Response {
    tracing::error!(error = ?e, "onboarding request failed");
    StatusCode::INTERNAL_SERVER_ERROR.into_response()
}

/// Get the authenticated user's onboarding state.
#[utoipa::path(
    get,
    path = "/onboarding",
    responses(
        (status = 200, description = "Current onboarding state", body = OnboardingState),
        (status = 500, description = "Internal server error"),
    ),
    tag = "onboarding"
)]
#[tracing::instrument(skip(service, user), fields(user_id = %user.authorization.user.macro_user_id))]
pub async fn get_state_handler<T: OnboardingService, Auth: MacroAuthorizationService>(
    State(service): State<Arc<T>>,
    user: MacroAuthorizationExtractor<Auth, UserOrInternal>,
) -> Response {
    match service
        .get_state(user.authorization.user.macro_user_id)
        .await
    {
        Ok(state) => Json(state).into_response(),
        Err(e) => error_response(e),
    }
}

/// Complete (or skip) onboarding. Unreserved leftover onboarding-staged
/// import candidates are deleted.
#[utoipa::path(
    post,
    path = "/onboarding/complete",
    request_body = CompleteOnboardingRequest,
    responses(
        (status = 200, description = "Completed onboarding row", body = OnboardingRow),
        (status = 500, description = "Internal server error"),
    ),
    tag = "onboarding"
)]
#[tracing::instrument(skip(service, user, body), fields(user_id = %user.authorization.user.macro_user_id))]
pub async fn complete_handler<T: OnboardingService, Auth: MacroAuthorizationService>(
    State(service): State<Arc<T>>,
    user: MacroAuthorizationExtractor<Auth, UserOrInternal>,
    Json(body): Json<CompleteOnboardingRequest>,
) -> Response {
    match service
        .complete(user.authorization.user.macro_user_id, body.skipped)
        .await
    {
        Ok(row) => Json(row).into_response(),
        Err(e) => error_response(e),
    }
}

/// List the sidebar prompts the authenticated user dismissed on any device.
#[utoipa::path(
    get,
    path = "/onboarding/prompts",
    responses(
        (status = 200, description = "Dismissed prompt ids", body = DismissedPrompts),
        (status = 500, description = "Internal server error"),
    ),
    tag = "onboarding"
)]
#[tracing::instrument(skip(service, user), fields(user_id = %user.authorization.user.macro_user_id))]
pub async fn dismissed_prompts_handler<T: OnboardingService, Auth: MacroAuthorizationService>(
    State(service): State<Arc<T>>,
    user: MacroAuthorizationExtractor<Auth, UserOrInternal>,
) -> Response {
    match service
        .dismissed_prompts(user.authorization.user.macro_user_id)
        .await
    {
        Ok(prompts) => Json(prompts).into_response(),
        Err(e) => error_response(e),
    }
}

/// Dismiss one sidebar prompt for the authenticated user, on every device.
/// Idempotent.
#[utoipa::path(
    post,
    path = "/onboarding/prompts/{prompt_id}/dismiss",
    params(("prompt_id" = String, Path, description = "Prompt id, e.g. `import:files`")),
    responses(
        (status = 204, description = "Dismissed"),
        (status = 400, description = "Malformed prompt id"),
        (status = 500, description = "Internal server error"),
    ),
    tag = "onboarding"
)]
#[tracing::instrument(skip(service, user), fields(user_id = %user.authorization.user.macro_user_id))]
pub async fn dismiss_prompt_handler<T: OnboardingService, Auth: MacroAuthorizationService>(
    State(service): State<Arc<T>>,
    user: MacroAuthorizationExtractor<Auth, UserOrInternal>,
    Path(prompt_id): Path<String>,
) -> Response {
    let Some(prompt) = PromptId::parse(&prompt_id) else {
        return (StatusCode::BAD_REQUEST, "malformed prompt id").into_response();
    };
    match service
        .dismiss_prompt(user.authorization.user.macro_user_id, prompt)
        .await
    {
        Ok(()) => StatusCode::NO_CONTENT.into_response(),
        Err(e) => error_response(e),
    }
}