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.

5.7 KB
Raw Blame
use super::{
    ReturnUrlError, SettleRequest, SubscriptionPeriodQuery, UpdateAutoReloadRequest,
    get_plans_handler, scope_from_query, validate_return_url,
};
use crate::domain::{
    AUTO_RELOAD_DEFAULT_MINIMUM_CENTS, AUTO_RELOAD_DEFAULT_TARGET_CENTS,
    AUTO_RELOAD_TARGET_MAX_CENTS, AiPricing, AutoReloadThresholds, PlanTier, SubscriptionScope,
};
use axum::extract::{Query, State};
use macro_uuid::Uuid;

#[test]
fn return_urls_must_be_https_on_the_calling_origin() {
    let origin = Some("https://macro.com");
    assert_eq!(
        validate_return_url("https://macro.com/app/settings/billing?x=1", origin),
        Ok(())
    );
    // Without an Origin header any https URL without credentials passes.
    assert_eq!(
        validate_return_url("https://preview.macro.com/app", None),
        Ok(())
    );
    assert_eq!(
        validate_return_url("http://localhost:3000/app", Some("http://localhost:3000")),
        Ok(())
    );
    assert_eq!(
        validate_return_url("https://macro.com:443/app", origin),
        Ok(())
    );
    assert_eq!(
        validate_return_url("https://macro.com:8443/app", origin),
        Err(ReturnUrlError::Origin)
    );
    assert_eq!(
        validate_return_url("https://evil.example/app", origin),
        Err(ReturnUrlError::Origin)
    );
    assert_eq!(
        validate_return_url("http://macro.com/app", None),
        Err(ReturnUrlError::Scheme)
    );
    assert_eq!(
        validate_return_url("javascript:alert(1)", None),
        Err(ReturnUrlError::Unparseable)
    );
    assert_eq!(
        validate_return_url("/app/settings/billing", None),
        Err(ReturnUrlError::Unparseable)
    );
    assert_eq!(
        validate_return_url("https://user:[email protected]/app", None),
        Err(ReturnUrlError::Credentials)
    );
}

#[tokio::test]
async fn plan_catalog_lists_every_tier_and_marks_the_purchasable_ones() {
    let pricing = AiPricing::testing();
    let catalog = get_plans_handler(State(pricing)).await.0;
    let summary = catalog
        .plans
        .iter()
        .map(|plan| (plan.tier, plan.purchasable, plan.included_ai_cents_per_seat))
        .collect::<Vec<_>>();

    // The frontend reads allowances from here, so every tier it can display is
    // listed with its own configured allowance; Free's is its monthly hard cap.
    assert_eq!(
        summary,
        vec![
            (
                PlanTier::Free,
                false,
                pricing.included_allowance_cents_for(PlanTier::Free)
            ),
            (
                PlanTier::Premium,
                true,
                pricing.included_allowance_cents_for(PlanTier::Premium)
            ),
            (
                PlanTier::Max,
                true,
                pricing.included_allowance_cents_for(PlanTier::Max)
            ),
        ]
    );
    assert_eq!(summary[0].2, 500);
    assert_eq!(summary[1].2, 2_000);
    assert_eq!(summary[2].2, 10_000);

    // The Auto-Reload dialog reads its starting values and ceiling from here.
    assert_eq!(
        catalog.auto_reload_target_max_cents,
        AUTO_RELOAD_TARGET_MAX_CENTS
    );
    assert_eq!(
        catalog.auto_reload_defaults.minimum_balance_cents,
        AUTO_RELOAD_DEFAULT_MINIMUM_CENTS
    );
    assert_eq!(
        catalog.auto_reload_defaults.target_balance_cents,
        AUTO_RELOAD_DEFAULT_TARGET_CENTS
    );

    // Paid plans start Auto-Reload with a monthly limit sized to the plan.
    assert_eq!(
        catalog
            .plans
            .iter()
            .map(|plan| plan.auto_reload_default_monthly_limit_cents)
            .collect::<Vec<_>>(),
        vec![None, Some(20_000), Some(100_000)]
    );
}

#[test]
fn auto_reload_request_reads_camel_case_and_defaults_the_monthly_limit() {
    let with_limit: UpdateAutoReloadRequest = serde_json::from_str(
        r#"{"enabled":true,"minimumBalanceCents":500,"targetBalanceCents":2000,"monthlySpendLimitCents":5000}"#,
    )
    .unwrap();
    assert!(with_limit.enabled);
    assert_eq!(
        AutoReloadThresholds::from(&with_limit),
        AutoReloadThresholds {
            minimum_cents: 500,
            target_cents: 2_000,
            monthly_limit_cents: Some(5_000),
        }
    );

    let without_limit: UpdateAutoReloadRequest = serde_json::from_str(
        r#"{"enabled":false,"minimumBalanceCents":500,"targetBalanceCents":2000}"#,
    )
    .unwrap();
    assert!(!without_limit.enabled);
    assert_eq!(without_limit.monthly_spend_limit_cents, None);

    let null_limit: UpdateAutoReloadRequest = serde_json::from_str(
        r#"{"enabled":true,"minimumBalanceCents":500,"targetBalanceCents":2000,"monthlySpendLimitCents":null}"#,
    )
    .unwrap();
    assert_eq!(null_limit.monthly_spend_limit_cents, None);
}

#[test]
fn subscription_period_query_selects_the_scope() {
    let Query(team) = Query::<SubscriptionPeriodQuery>::try_from_uri(
        &"/internal/ai-billing/subscription-period?customerId=cus_123&teamId=00000000-0000-0000-0000-000000000007"
            .parse()
            .unwrap(),
    )
    .unwrap();
    assert_eq!(team.customer_id, "cus_123");
    assert_eq!(
        scope_from_query(team.team_id),
        SubscriptionScope::Team {
            team_id: Uuid::from_u128(7)
        }
    );

    let Query(personal) = Query::<SubscriptionPeriodQuery>::try_from_uri(
        &"/internal/ai-billing/subscription-period?customerId=cus_123"
            .parse()
            .unwrap(),
    )
    .unwrap();
    assert_eq!(personal.customer_id, "cus_123");
    assert_eq!(
        scope_from_query(personal.team_id),
        SubscriptionScope::Personal
    );
}

#[test]
fn settle_request_reads_the_camel_case_user_id() {
    let request: SettleRequest = serde_json::from_str(r#"{"userId":"macro|[email protected]"}"#).unwrap();
    assert_eq!(request.user_id, "macro|[email protected]");
}