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.

23.6 KB
Raw Blame
use chrono::{TimeZone, Utc};
use models_databases::views::{
    Conjunction, FilterCondition, FilterGroup, FilterNode, FilterTest, SetOperator,
};
use models_databases::{CellValue, ColumnId, ColumnKind, DatabaseId, OptionId, RowId, TableId};
use serde_json::json;
use uuid::Uuid;

use super::*;

#[test]
fn booking_step_round_trips_an_existing_native_booking_target() {
    let wire = serde_json::json!({
        "sections": [
            {
                "kind": "questions", "id": "019ce700-0000-7000-8000-000000000001",
                "title": "About you", "description": "", "questions": []
            },
            {
                "kind": "booking", "id": "019ce700-0000-7000-8000-000000000002",
                "title": "Book a time", "description": "Meet with our team.",
                "target": {
                    "profileId": "019ce700-0000-7000-8000-000000000003",
                    "eventTypeId": "019ce700-0000-7000-8000-000000000004"
                }
            }
        ]
    });
    let layout: FormLayout = serde_json::from_value(wire.clone()).unwrap();
    assert_eq!(serde_json::to_value(layout).unwrap(), wire);
}

const FORM: FormId = FormId::from_uuid(Uuid::from_u128(0xf0));
const DATABASE: DatabaseId = DatabaseId::from_uuid(Uuid::from_u128(0xdb));
const TABLE: TableId = TableId::from_uuid(Uuid::from_u128(0x7a));
const SUBMITTED: ColumnId = ColumnId::from_uuid(Uuid::from_u128(0x5b));
const TEAM: ColumnId = ColumnId::from_uuid(Uuid::from_u128(0x7e));
const CONTRACTOR: OptionId = OptionId::from_uuid(Uuid::from_u128(0xc0));
const ABOUT_YOU: FormSectionId = FormSectionId::from_uuid(Uuid::from_u128(0x51));
const ELIGIBILITY: FormSectionId = FormSectionId::from_uuid(Uuid::from_u128(0x52));
const TEAM_QUESTION: FormQuestionId = FormQuestionId::from_uuid(Uuid::from_u128(0x91));

#[test]
fn a_form_detail_reads_as_the_web_client_expects() {
    let detail = FormDetail {
        form: Form {
            id: FORM,
            name: "Q4 offsite RSVP".into(),
            description: "Tell us if you can make it.".into(),
            owner_id: "macro|[email protected]".into(),
            database_id: DATABASE,
            table_id: TABLE,
            submitted_column_id: Some(SUBMITTED),
            respondent_column_id: None,
            audience: Audience::Members,
            tally_visible: false,
            status: FormStatus::Open,
            closes_at: Some(Utc.with_ymd_and_hms(2026, 10, 3, 17, 0, 0).unwrap()),
            confirmation_message: "".into(),
            branding: FormBranding::default(),
            created_at: Utc.with_ymd_and_hms(2026, 9, 1, 9, 0, 0).unwrap(),
            updated_at: Utc.with_ymd_and_hms(2026, 9, 2, 9, 0, 0).unwrap(),
            project_id: None,
            is_hidden_in_drive: false,
            responses_visible: false,
            anonymous: false,
        },
        access: FormAccess::Edit,
        table_gone: false,
        sections: vec![
            FormSectionDetail::Questions {
                id: ABOUT_YOU,
                title: "About you".into(),
                description: "".into(),
                questions: vec![FormQuestionDetail {
                    id: TEAM_QUESTION,
                    column: TEAM,
                    title: "Team".into(),
                    kind: ColumnKind::Select { multi: false },
                    options: vec![QuestionOption {
                        id: CONTRACTOR,
                        label: "Contractor".into(),
                        color: Some("#F5A623".into()),
                    }],
                    help_text: "Where you sit".into(),
                    required: true,
                    widget: Some(Widget::Choice),
                }],
                show_when: None,
            },
            FormSectionDetail::Gate {
                id: ELIGIBILITY,
                title: "Eligibility".into(),
                description: "".into(),
                rules: FilterGroup {
                    conjunction: Conjunction::And,
                    conditions: vec![FilterNode::Condition(FilterCondition {
                        column: TEAM,
                        test: FilterTest::Options {
                            operator: SetOperator::IsNoneOf,
                            options: vec![CONTRACTOR],
                        },
                    })],
                },
                message: "The offsite is for employees.".into(),
            },
        ],
    };

    assert_eq!(
        serde_json::to_value(&detail).unwrap(),
        json!({
            "form": {
                "id": "00000000-0000-0000-0000-0000000000f0",
                "name": "Q4 offsite RSVP",
                "description": "Tell us if you can make it.",
                "ownerId": "macro|[email protected]",
                "databaseId": "00000000-0000-0000-0000-0000000000db",
                "tableId": "00000000-0000-0000-0000-00000000007a",
                "submittedColumnId": "00000000-0000-0000-0000-00000000005b",
                "respondentColumnId": null,
                "audience": "members",
                "tallyVisible": false,
                "responsesVisible": false,
                "anonymous": false,
                "status": "open",
                "closesAt": "2026-10-03T17:00:00Z",
                "confirmationMessage": "",
                "branding": { "logoFileId": null, "coverFileId": null, "accentColor": null },
                "createdAt": "2026-09-01T09:00:00Z",
                "updatedAt": "2026-09-02T09:00:00Z",
                "projectId": null,
                "isHiddenInDrive": false,
            },
            "access": "edit",
            "tableGone": false,
            "sections": [
                {
                    "kind": "questions",
                    "id": "00000000-0000-0000-0000-000000000051",
                    "title": "About you",
                    "description": "",
                    "questions": [{
                        "id": "00000000-0000-0000-0000-000000000091",
                        "column": "00000000-0000-0000-0000-00000000007e",
                        "title": "Team",
                        "kind": {"type": "select", "multi": false},
                        "options": [{
                            "id": "00000000-0000-0000-0000-0000000000c0",
                            "label": "Contractor",
                            "color": "#F5A623",
                        }],
                        "helpText": "Where you sit",
                        "required": true,
                        "widget": "choice",
                    }],
                },
                {
                    "kind": "gate",
                    "id": "00000000-0000-0000-0000-000000000052",
                    "title": "Eligibility",
                    "description": "",
                    "rules": {
                        "conjunction": "and",
                        "conditions": [{
                            "kind": "condition",
                            "column": "00000000-0000-0000-0000-00000000007e",
                            "test": {
                                "kind": "options",
                                "operator": "isNoneOf",
                                "options": ["00000000-0000-0000-0000-0000000000c0"],
                            },
                        }],
                    },
                    "message": "The offsite is for employees.",
                },
            ],
        })
    );
    let read_back: FormDetail =
        serde_json::from_value(serde_json::to_value(&detail).unwrap()).unwrap();
    assert_eq!(read_back, detail);
}

#[test]
fn a_layout_put_reads_sections_by_kind_and_a_missing_widget_as_default() {
    let layout: FormLayout = serde_json::from_value(json!({
        "sections": [
            {
                "kind": "questions",
                "id": "00000000-0000-0000-0000-000000000051",
                "title": "About you",
                "description": "",
                "questions": [{
                    "id": "00000000-0000-0000-0000-000000000091",
                    "column": "00000000-0000-0000-0000-00000000007e",
                    "helpText": "",
                    "required": false,
                    "widget": null,
                }],
            },
            {
                "kind": "gate",
                "id": "00000000-0000-0000-0000-000000000052",
                "title": "",
                "description": "",
                "rules": {"conjunction": "or", "conditions": []},
                "message": "Sorry",
            },
        ],
    }))
    .unwrap();

    assert_eq!(
        layout,
        FormLayout {
            sections: vec![
                FormSection::Questions {
                    id: ABOUT_YOU,
                    title: "About you".into(),
                    description: "".into(),
                    questions: vec![QuestionLayout {
                        id: TEAM_QUESTION,
                        column: TEAM,
                        help_text: "".into(),
                        required: false,
                        widget: None,
                    }],
                    show_when: None,
                },
                FormSection::Gate {
                    id: ELIGIBILITY,
                    title: "".into(),
                    description: "".into(),
                    rules: FilterGroup {
                        conjunction: Conjunction::Or,
                        conditions: vec![],
                    },
                    message: "Sorry".into(),
                },
            ],
        }
    );
    assert_eq!(layout.sections[1].id(), ELIGIBILITY);
}

#[test]
fn a_create_request_names_its_source_by_kind() {
    let new: CreateForm =
        serde_json::from_value(json!({"name": "RSVP", "source": {"kind": "new"}})).unwrap();
    assert_eq!(
        new.source,
        FormSource::New {
            is_hidden_in_drive: false,
            anonymous: false,
        }
    );

    let hidden: CreateForm = serde_json::from_value(
        json!({"name": "Lunch?", "source": {"kind": "new", "isHiddenInDrive": true}}),
    )
    .unwrap();
    assert_eq!(
        hidden.source,
        FormSource::New {
            is_hidden_in_drive: true,
            anonymous: false,
        }
    );

    let table: CreateForm = serde_json::from_value(json!({
        "name": "RSVP",
        "source": {
            "kind": "table",
            "databaseId": "00000000-0000-0000-0000-0000000000db",
            "tableId": "00000000-0000-0000-0000-00000000007a",
        },
    }))
    .unwrap();
    assert_eq!(
        table.source,
        FormSource::Table {
            database_id: DATABASE,
            table_id: TABLE,
        }
    );
}

#[test]
fn an_update_tells_a_cleared_closing_time_from_an_untouched_one() {
    let cleared: UpdateForm = serde_json::from_value(json!({"closesAt": null})).unwrap();
    assert_eq!(cleared.closes_at, Some(None));
    assert!(cleared.needs_owner());

    let untouched: UpdateForm =
        serde_json::from_value(json!({"description": "New words"})).unwrap();
    assert_eq!(untouched.closes_at, None);
    assert_eq!(untouched.description.as_deref(), Some("New words"));
    assert!(!untouched.needs_owner());

    let audience: UpdateForm = serde_json::from_value(json!({"audience": "public"})).unwrap();
    assert_eq!(audience.audience, Some(Audience::Public));
    assert!(audience.needs_owner());
}

#[test]
fn a_submission_and_its_outcomes_read_as_tagged_objects() {
    let submission: Submission = serde_json::from_value(json!({
        "answers": [{
            "question": "00000000-0000-0000-0000-000000000091",
            "value": {"type": "options", "value": [{"id": "00000000-0000-0000-0000-0000000000c0"}]},
        }],
    }))
    .unwrap();
    assert_eq!(
        submission.answers,
        vec![Answer {
            question: TEAM_QUESTION,
            value: CellValue::Options(vec![models_databases::OptionRef::Id(CONTRACTOR)]),
        }]
    );

    let response = FormResponseId::from_uuid(Uuid::from_u128(0xe1));
    let row = RowId::from_uuid(Uuid::from_u128(0x40));
    assert_eq!(
        serde_json::to_value(SubmissionOutcome::Submitted {
            response,
            row,
            booking: None,
        })
        .unwrap(),
        json!({
            "outcome": "submitted",
            "response": "00000000-0000-0000-0000-0000000000e1",
            "row": "00000000-0000-0000-0000-000000000040",
        })
    );
    assert_eq!(
        serde_json::to_value(SubmissionOutcome::Stopped {
            section: ELIGIBILITY,
            message: "The offsite is for employees.".into(),
        })
        .unwrap(),
        json!({
            "outcome": "stopped",
            "section": "00000000-0000-0000-0000-000000000052",
            "message": "The offsite is for employees.",
        })
    );
}

#[test]
fn a_tally_names_options_and_checkbox_states() {
    let tally = FormTally {
        questions: vec![QuestionTally {
            question: TEAM_QUESTION,
            responses: 3,
            buckets: vec![
                TallyBucket {
                    value: TallyValue::Option { option: CONTRACTOR },
                    count: 2,
                    voters: Some(vec!["macro|[email protected]".to_string()]),
                },
                TallyBucket {
                    value: TallyValue::Checkbox { checked: true },
                    count: 1,
                    voters: None,
                },
            ],
        }],
    };
    assert_eq!(
        serde_json::to_value(tally).unwrap(),
        json!({
            "questions": [{
                "question": "00000000-0000-0000-0000-000000000091",
                "responses": 3,
                "buckets": [
                    {"value": {"kind": "option", "option": "00000000-0000-0000-0000-0000000000c0"}, "count": 2, "voters": ["macro|[email protected]"]},
                    {"value": {"kind": "checkbox", "checked": true}, "count": 1},
                ],
            }],
        })
    );
}

#[test]
fn an_error_names_its_code_question_and_layout_problem() {
    let error = FormErrorResponse {
        code: FormErrorCode::InvalidLayout,
        message: "a gate can only test questions of earlier sections".into(),
        question: None,
        problem: Some(LayoutProblem::GateNamesLaterColumn { column: TEAM }),
    };
    assert_eq!(
        serde_json::to_value(error).unwrap(),
        json!({
            "code": "invalidLayout",
            "message": "a gate can only test questions of earlier sections",
            "question": null,
            "problem": {
                "kind": "gateNamesLaterColumn",
                "column": "00000000-0000-0000-0000-00000000007e",
            },
        })
    );
}

#[test]
fn a_form_takes_responses_while_open_and_before_it_closes() {
    let now = Utc.with_ymd_and_hms(2026, 10, 1, 12, 0, 0).unwrap();
    let form = |status, closes_at| Form {
        id: FORM,
        name: "RSVP".into(),
        description: "".into(),
        owner_id: "macro|[email protected]".into(),
        database_id: DATABASE,
        table_id: TABLE,
        submitted_column_id: None,
        respondent_column_id: None,
        audience: Audience::Members,
        tally_visible: false,
        status,
        closes_at,
        confirmation_message: "".into(),
        branding: FormBranding::default(),
        created_at: now,
        updated_at: now,
        project_id: None,
        is_hidden_in_drive: false,
        responses_visible: false,
        anonymous: false,
    };
    assert!(form(FormStatus::Open, None).accepts_responses_at(now));
    assert!(
        form(FormStatus::Open, Some(now + chrono::Duration::hours(1))).accepts_responses_at(now)
    );
    assert!(!form(FormStatus::Open, Some(now)).accepts_responses_at(now));
    assert!(!form(FormStatus::Closed, None).accepts_responses_at(now));
}

#[test]
fn a_listed_form_names_the_callers_access_beside_the_form() {
    let now = Utc.with_ymd_and_hms(2026, 9, 1, 9, 0, 0).unwrap();
    let listed = ListedForm {
        form: Form {
            id: FORM,
            name: "RSVP".into(),
            description: "".into(),
            owner_id: "macro|[email protected]".into(),
            database_id: DATABASE,
            table_id: TABLE,
            submitted_column_id: None,
            respondent_column_id: None,
            audience: Audience::Public,
            tally_visible: true,
            status: FormStatus::Closed,
            closes_at: None,
            confirmation_message: "Thanks".into(),
            branding: FormBranding::default(),
            created_at: now,
            updated_at: now,
            project_id: None,
            is_hidden_in_drive: false,
            responses_visible: false,
            anonymous: false,
        },
        access: FormAccess::View,
    };
    assert_eq!(
        serde_json::to_value(&listed).unwrap(),
        json!({
            "form": {
                "id": "00000000-0000-0000-0000-0000000000f0",
                "name": "RSVP",
                "description": "",
                "ownerId": "macro|[email protected]",
                "databaseId": "00000000-0000-0000-0000-0000000000db",
                "tableId": "00000000-0000-0000-0000-00000000007a",
                "submittedColumnId": null,
                "respondentColumnId": null,
                "audience": "public",
                "tallyVisible": true,
                "responsesVisible": false,
                "anonymous": false,
                "status": "closed",
                "closesAt": null,
                "confirmationMessage": "Thanks",
                "branding": { "logoFileId": null, "coverFileId": null, "accentColor": null },
                "createdAt": "2026-09-01T09:00:00Z",
                "updatedAt": "2026-09-01T09:00:00Z",
                "projectId": null,
                "isHiddenInDrive": false,
            },
            "access": "view",
        })
    );
}

#[test]
fn table_source_openapi_uses_the_serialized_field_names() {
    use utoipa::PartialSchema;

    let schema = serde_json::to_value(FormSource::schema()).unwrap();
    let table = &schema["oneOf"][1];
    let properties = table["properties"].as_object().unwrap();
    assert!(properties.contains_key("databaseId"));
    assert!(properties.contains_key("tableId"));
    assert!(!properties.contains_key("database_id"));
    assert!(!properties.contains_key("table_id"));
    let required = table["required"].as_array().unwrap();
    assert!(required.contains(&json!("databaseId")));
    assert!(required.contains(&json!("tableId")));
}

#[test]
fn error_schema_requires_nullable_fields_that_are_always_serialized() {
    use utoipa::PartialSchema;

    let response = FormErrorResponse {
        code: FormErrorCode::Closed,
        message: "This form is closed.".into(),
        question: None,
        problem: None,
    };
    let wire = serde_json::to_value(response).unwrap();
    let schema = serde_json::to_value(FormErrorResponse::schema()).unwrap();
    let required = schema["required"].as_array().unwrap();
    for field in ["code", "message", "question", "problem"] {
        assert!(wire.get(field).is_some());
        assert!(
            required.contains(&json!(field)),
            "missing required field {field}"
        );
    }
}

#[test]
fn form_and_response_schemas_require_every_field_they_always_serialize() {
    use utoipa::PartialSchema;

    let now = Utc.with_ymd_and_hms(2026, 9, 1, 9, 0, 0).unwrap();
    let form = Form {
        id: FORM,
        name: "RSVP".into(),
        description: "".into(),
        owner_id: "macro|[email protected]".into(),
        database_id: DATABASE,
        table_id: TABLE,
        submitted_column_id: None,
        respondent_column_id: None,
        audience: Audience::Members,
        tally_visible: false,
        status: FormStatus::Open,
        closes_at: None,
        confirmation_message: "".into(),
        branding: FormBranding::default(),
        created_at: now,
        updated_at: now,
        project_id: None,
        is_hidden_in_drive: false,
        responses_visible: false,
        anonymous: false,
    };
    let response = FormResponse {
        id: FormResponseId::from_uuid(Uuid::from_u128(0xe1)),
        form_id: FORM,
        status: ResponseStatus::Stopped,
        stopped_at_section: None,
        row: None,
        submitted_at: now,
        updated_at: now,
    };
    for (name, wire, schema) in [
        (
            "Form",
            serde_json::to_value(form).unwrap(),
            serde_json::to_value(Form::schema()).unwrap(),
        ),
        (
            "FormResponse",
            serde_json::to_value(response).unwrap(),
            serde_json::to_value(FormResponse::schema()).unwrap(),
        ),
    ] {
        let required = schema["required"].as_array().unwrap();
        for field in wire.as_object().unwrap().keys() {
            assert!(
                required.contains(&json!(field)),
                "{name}.{field} is always sent but not required"
            );
        }
    }
}

#[test]
fn a_form_sends_its_branding_with_its_facts() {
    let now = Utc.with_ymd_and_hms(2026, 9, 1, 9, 0, 0).unwrap();
    let form = Form {
        id: FORM,
        name: "Site intake".into(),
        description: "".into(),
        owner_id: "macro|[email protected]".into(),
        database_id: DATABASE,
        table_id: TABLE,
        submitted_column_id: None,
        respondent_column_id: None,
        audience: Audience::Public,
        tally_visible: false,
        status: FormStatus::Open,
        closes_at: None,
        confirmation_message: "".into(),
        branding: FormBranding {
            logo_file_id: Some(Uuid::from_u128(0x10)),
            cover_file_id: None,
            accent_color: Some(AccentColor::try_from("#1F6FEB".to_string()).unwrap()),
        },
        created_at: now,
        updated_at: now,
        project_id: None,
        is_hidden_in_drive: false,
        responses_visible: false,
        anonymous: false,
    };
    assert_eq!(
        serde_json::to_value(&form).unwrap()["branding"],
        json!({
            "logoFileId": "00000000-0000-0000-0000-000000000010",
            "coverFileId": null,
            "accentColor": "#1f6feb",
        })
    );
    let schema = serde_json::to_value(<FormBranding as utoipa::PartialSchema>::schema()).unwrap();
    let required = schema["required"].as_array().unwrap();
    for field in ["logoFileId", "coverFileId", "accentColor"] {
        assert!(
            required.contains(&json!(field)),
            "missing required field {field}"
        );
    }
}

#[test]
fn an_accent_color_is_six_hex_digits_after_a_hash() {
    for accepted in ["#000000", "#ffffff", "#1F6FEB"] {
        assert!(
            AccentColor::try_from(accepted.to_string()).is_ok(),
            "{accepted}"
        );
    }
    for refused in [
        "",
        "#fff",
        "1f6feb",
        "#1f6feb00",
        "#1g6feb",
        "red",
        " #1f6feb",
    ] {
        assert!(
            AccentColor::try_from(refused.to_string()).is_err(),
            "{refused}"
        );
    }
}

#[test]
fn a_branding_change_sets_clears_or_keeps_each_part() {
    let update: UpdateForm = serde_json::from_value(json!({
        "logoFileId": "00000000-0000-0000-0000-000000000010",
        "coverFileId": null,
        "accentColor": "#ABCDEF",
    }))
    .unwrap();
    assert_eq!(update.logo_file_id, Some(Some(Uuid::from_u128(0x10))));
    assert_eq!(update.cover_file_id, Some(None));
    assert_eq!(
        update.accent_color,
        Some(Some(AccentColor::try_from("#abcdef".to_string()).unwrap()))
    );
    assert!(update.changes_branding());
    assert!(!update.needs_owner());

    let untouched: UpdateForm = serde_json::from_value(json!({ "description": "Hi" })).unwrap();
    assert_eq!(untouched.logo_file_id, None);
    assert_eq!(untouched.accent_color, None);
    assert!(!untouched.changes_branding());

    assert!(serde_json::from_value::<UpdateForm>(json!({ "accentColor": "blue" })).is_err());
}