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.

feat: add personal and team calendar scheduling (#6608)

Jacob Beckerman01b8e79c8fde
diff --git a/.github/workspace-dep-closures.json b/.github/workspace-dep-closures.json
index d42c47f8cc..cc86dba845 100644
--- a/.github/workspace-dep-closures.json
+++ b/.github/workspace-dep-closures.json
@@ -2143,30 +2143,148 @@
"crates/remote_env_var",
"crates/workspace-hack"
],
+ "calendar_scheduling": [
+ "crates/activity",
+ "crates/agent",
+ "crates/agent_fold",
+ "crates/agent_runtime_protocol",
+ "crates/ai_toolset",
+ "crates/ai_usage",
+ "crates/analytics_client",
+ "crates/attachment",
+ "crates/authentication_service_client",
+ "crates/bot_id",
+ "crates/bot_token",
+ "crates/broadcast",
+ "crates/calendar_events",
+ "crates/calendar_scheduling",
+ "crates/call",
+ "crates/channel_sender",
+ "crates/channels",
+ "crates/connection",
+ "crates/connection_gateway_client",
+ "crates/connection_gateway_models",
+ "crates/contacts",
+ "crates/cowlike",
+ "crates/crm",
+ "crates/database_env_vars",
+ "crates/document_sub_type",
+ "crates/email",
+ "crates/email_utils",
+ "crates/email_validator",
+ "crates/entity_access",
+ "crates/entity_access_db_utils",
+ "crates/entity_access_management",
+ "crates/entity_mutation",
+ "crates/filter_ast",
+ "crates/frecency",
+ "crates/genai_telemetry",
+ "crates/generic_email_domains",
+ "crates/google_token",
+ "crates/harness_id",
+ "crates/harness_token",
+ "crates/initiative",
+ "crates/invite_email",
+ "crates/ip_extractor",
+ "crates/item_filters",
+ "crates/kafka_util",
+ "crates/last_online_tracker",
+ "crates/lexical_client",
+ "crates/macro_auth",
+ "crates/macro_authorization",
+ "crates/macro_aws_config",
+ "crates/macro_entrypoint",
+ "crates/macro_env",
+ "crates/macro_env_var",
+ "crates/macro_event_broker",
+ "crates/macro_event_topics",
+ "crates/macro_service_urls",
+ "crates/macro_tower_layers",
+ "crates/macro_user_id",
+ "crates/macro_uuid",
+ "crates/mention_utils",
+ "crates/messages",
+ "crates/model",
+ "crates/model-entity",
+ "crates/model-error-response",
+ "crates/model_file_type",
+ "crates/model_notifications",
+ "crates/model_owner",
+ "crates/model_user",
+ "crates/models_ai_projection",
+ "crates/models_bulk_upload",
+ "crates/models_email",
+ "crates/models_entity_access_management",
+ "crates/models_pagination",
+ "crates/models_permissions",
+ "crates/models_properties",
+ "crates/models_sfs",
+ "crates/non_empty",
+ "crates/notification",
+ "crates/notification_state",
+ "crates/prompt",
+ "crates/properties",
+ "crates/rate_limit",
+ "crates/remote_env_var",
+ "crates/roles_and_permissions",
+ "crates/s3_key",
+ "crates/share_permission_db_utils",
+ "crates/sqs_client",
+ "crates/sqs_worker",
+ "crates/static_file_service_client",
+ "crates/system_properties",
+ "crates/teams",
+ "crates/unfurl",
+ "crates/workspace-hack"
+ ],
"calendar_service": [
+ "crates/activity",
"crates/agent",
+ "crates/agent_fold",
+ "crates/agent_runtime_protocol",
"crates/ai_toolset",
"crates/ai_usage",
+ "crates/analytics_client",
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
"crates/bot_token",
"crates/broadcast",
"crates/calendar_events",
+ "crates/calendar_scheduling",
+ "crates/call",
"crates/channel_sender",
+ "crates/channels",
+ "crates/connection",
"crates/connection_gateway_client",
"crates/connection_gateway_models",
+ "crates/contacts",
"crates/cowlike",
+ "crates/crm",
+ "crates/database_env_vars",
"crates/document_sub_type",
+ "crates/email",
"crates/email_db_client",
"crates/email_utils",
+ "crates/email_validator",
+ "crates/entity_access",
+ "crates/entity_access_db_utils",
+ "crates/entity_access_management",
+ "crates/entity_mutation",
+ "crates/filter_ast",
+ "crates/frecency",
"crates/genai_telemetry",
+ "crates/generic_email_domains",
"crates/google_token",
"crates/harness_id",
"crates/harness_token",
+ "crates/initiative",
"crates/invite_email",
+ "crates/ip_extractor",
+ "crates/item_filters",
"crates/kafka_util",
"crates/last_online_tracker",
+ "crates/lexical_client",
"crates/macro_auth",
"crates/macro_authorization",
"crates/macro_aws_config",
@@ -2184,6 +2302,7 @@
"crates/macro_user_id",
"crates/macro_uuid",
"crates/mention_utils",
+ "crates/messages",
"crates/model",
"crates/model-entity",
"crates/model-error-response",
@@ -2191,18 +2310,31 @@
"crates/model_notifications",
"crates/model_owner",
"crates/model_user",
+ "crates/models_ai_projection",
"crates/models_bulk_upload",
"crates/models_email",
+ "crates/models_entity_access_management",
"crates/models_pagination",
"crates/models_permissions",
+ "crates/models_properties",
+ "crates/models_sfs",
"crates/non_empty",
"crates/notification",
"crates/notification_state",
"crates/prompt",
+ "crates/properties",
"crates/rate_limit",
"crates/remote_env_var",
+ "crates/roles_and_permissions",
+ "crates/s3_key",
"crates/secretsmanager_client",
+ "crates/share_permission_db_utils",
+ "crates/sqs_client",
"crates/sqs_worker",
+ "crates/static_file_service_client",
+ "crates/system_properties",
+ "crates/teams",
+ "crates/unfurl",
"crates/workspace-hack",
"services/calendar_service"
],
diff --git a/.sqlx/query-077b2342186da97624278feba11f24217c1052749cd5112993b5a6b281fe25ea.json b/.sqlx/query-077b2342186da97624278feba11f24217c1052749cd5112993b5a6b281fe25ea.json
new file mode 100644
index 0000000000..c35d20f78d
--- /dev/null
+++ b/.sqlx/query-077b2342186da97624278feba11f24217c1052749cd5112993b5a6b281fe25ea.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT record FROM scheduling_booking WHERE id = $1",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "record",
+ "type_info": "Jsonb"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "077b2342186da97624278feba11f24217c1052749cd5112993b5a6b281fe25ea"
+}
diff --git a/.sqlx/query-0a6865a4f9a071baf88abf99f5a195bc34e24111a768b2a913ba5bcdebc801e5.json b/.sqlx/query-0a6865a4f9a071baf88abf99f5a195bc34e24111a768b2a913ba5bcdebc801e5.json
new file mode 100644
index 0000000000..1589645cbe
--- /dev/null
+++ b/.sqlx/query-0a6865a4f9a071baf88abf99f5a195bc34e24111a768b2a913ba5bcdebc801e5.json
@@ -0,0 +1,14 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "UPDATE scheduling_public_budget SET window_start = now() - interval '2 hours' WHERE profile_id = $1",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "0a6865a4f9a071baf88abf99f5a195bc34e24111a768b2a913ba5bcdebc801e5"
+}
diff --git a/.sqlx/query-146ef8de35934203c8317557127898a07b5ddb19e165f41770635f6dd7441497.json b/.sqlx/query-146ef8de35934203c8317557127898a07b5ddb19e165f41770635f6dd7441497.json
new file mode 100644
index 0000000000..9e27ba0914
--- /dev/null
+++ b/.sqlx/query-146ef8de35934203c8317557127898a07b5ddb19e165f41770635f6dd7441497.json
@@ -0,0 +1,26 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT count(*) FROM scheduling_booking WHERE profile_id = $1 AND event_type_id = $2 AND starts_at >= $3 AND starts_at < $4 AND status <> 'cancelled' AND id <> $5",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "count",
+ "type_info": "Int8"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Uuid",
+ "Timestamptz",
+ "Timestamptz",
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "146ef8de35934203c8317557127898a07b5ddb19e165f41770635f6dd7441497"
+}
diff --git a/.sqlx/query-156bb9931f9a60bcd5844ac278d2ab4e3982b99faa3f55f36dc25d5250f5473b.json b/.sqlx/query-156bb9931f9a60bcd5844ac278d2ab4e3982b99faa3f55f36dc25d5250f5473b.json
new file mode 100644
index 0000000000..4fd5430fef
--- /dev/null
+++ b/.sqlx/query-156bb9931f9a60bcd5844ac278d2ab4e3982b99faa3f55f36dc25d5250f5473b.json
@@ -0,0 +1,40 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT user_id, team_id, revision, configuration FROM scheduling_profile WHERE id = $1",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "user_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 1,
+ "name": "team_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 2,
+ "name": "revision",
+ "type_info": "Int8"
+ },
+ {
+ "ordinal": 3,
+ "name": "configuration",
+ "type_info": "Jsonb"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ true,
+ true,
+ false,
+ false
+ ]
+ },
+ "hash": "156bb9931f9a60bcd5844ac278d2ab4e3982b99faa3f55f36dc25d5250f5473b"
+}
diff --git a/.sqlx/query-284aad80ccc3909ff55fc54cb3af69e07a9d4fff44c94f5f4ac8bff17db3040b.json b/.sqlx/query-284aad80ccc3909ff55fc54cb3af69e07a9d4fff44c94f5f4ac8bff17db3040b.json
new file mode 100644
index 0000000000..acc05aa665
--- /dev/null
+++ b/.sqlx/query-284aad80ccc3909ff55fc54cb3af69e07a9d4fff44c94f5f4ac8bff17db3040b.json
@@ -0,0 +1,24 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT record FROM scheduling_booking WHERE profile_id = $1 AND starts_at >= $2 AND starts_at < $3 ORDER BY starts_at, id LIMIT 5001",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "record",
+ "type_info": "Jsonb"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Timestamptz",
+ "Timestamptz"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "284aad80ccc3909ff55fc54cb3af69e07a9d4fff44c94f5f4ac8bff17db3040b"
+}
diff --git a/.sqlx/query-2c5dd040ab7cb0467b2d6a7fcd325cdb1fc2f4505df46d059ca6f53d6d137351.json b/.sqlx/query-2c5dd040ab7cb0467b2d6a7fcd325cdb1fc2f4505df46d059ca6f53d6d137351.json
new file mode 100644
index 0000000000..a5f085dd01
--- /dev/null
+++ b/.sqlx/query-2c5dd040ab7cb0467b2d6a7fcd325cdb1fc2f4505df46d059ca6f53d6d137351.json
@@ -0,0 +1,25 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO scheduling_public_budget (profile_id, kind, window_start, used)\n VALUES ($1, $2, now(), 1)\n ON CONFLICT (profile_id, kind) DO UPDATE SET\n window_start = CASE WHEN scheduling_public_budget.window_start <= now() - make_interval(secs => $3) THEN now() ELSE scheduling_public_budget.window_start END,\n used = CASE WHEN scheduling_public_budget.window_start <= now() - make_interval(secs => $3) THEN 1 ELSE scheduling_public_budget.used + 1 END\n WHERE scheduling_public_budget.window_start <= now() - make_interval(secs => $3) OR scheduling_public_budget.used < $4\n RETURNING used\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "used",
+ "type_info": "Int4"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text",
+ "Float8",
+ "Int4"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "2c5dd040ab7cb0467b2d6a7fcd325cdb1fc2f4505df46d059ca6f53d6d137351"
+}
diff --git a/.sqlx/query-35c21e7b1e3a8236f3a603593f46955c895141190498a91651c1a49b386136cc.json b/.sqlx/query-35c21e7b1e3a8236f3a603593f46955c895141190498a91651c1a49b386136cc.json
new file mode 100644
index 0000000000..5be53ae544
--- /dev/null
+++ b/.sqlx/query-35c21e7b1e3a8236f3a603593f46955c895141190498a91651c1a49b386136cc.json
@@ -0,0 +1,16 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "UPDATE scheduling_host_claim SET occupied = tstzmultirange(tstzrange($2,$3,'[)')) WHERE booking_id = $1",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Timestamptz",
+ "Timestamptz"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "35c21e7b1e3a8236f3a603593f46955c895141190498a91651c1a49b386136cc"
+}
diff --git a/.sqlx/query-47ed313afdb94ab2f8f66e7a2c1fbe51feeefa5c7722ac92f6e799a3c4d5902b.json b/.sqlx/query-47ed313afdb94ab2f8f66e7a2c1fbe51feeefa5c7722ac92f6e799a3c4d5902b.json
new file mode 100644
index 0000000000..b80b54b9c7
--- /dev/null
+++ b/.sqlx/query-47ed313afdb94ab2f8f66e7a2c1fbe51feeefa5c7722ac92f6e799a3c4d5902b.json
@@ -0,0 +1,14 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "DELETE FROM scheduling_host_claim WHERE booking_id = $1",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "47ed313afdb94ab2f8f66e7a2c1fbe51feeefa5c7722ac92f6e799a3c4d5902b"
+}
diff --git a/.sqlx/query-51191335f5cbcd7a8f2b8373848812f4e9aefd75a4f71ef8bdd8ebe7adec8d88.json b/.sqlx/query-51191335f5cbcd7a8f2b8373848812f4e9aefd75a4f71ef8bdd8ebe7adec8d88.json
new file mode 100644
index 0000000000..27dad40142
--- /dev/null
+++ b/.sqlx/query-51191335f5cbcd7a8f2b8373848812f4e9aefd75a4f71ef8bdd8ebe7adec8d88.json
@@ -0,0 +1,20 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "UPDATE scheduling_booking SET starts_at = $2, ends_at = $3, status = 'processing', record = $4, recovery_at = $6 WHERE id = $1 AND status = $5 AND COALESCE(record->>'revision', '0') = $7",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Timestamptz",
+ "Timestamptz",
+ "Jsonb",
+ "Text",
+ "Timestamptz",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "51191335f5cbcd7a8f2b8373848812f4e9aefd75a4f71ef8bdd8ebe7adec8d88"
+}
diff --git a/.sqlx/query-51460044bcd559f7bd4f736786de74681260ed36429b886cdfb14215cf2a28ed.json b/.sqlx/query-51460044bcd559f7bd4f736786de74681260ed36429b886cdfb14215cf2a28ed.json
new file mode 100644
index 0000000000..a2bc219afc
--- /dev/null
+++ b/.sqlx/query-51460044bcd559f7bd4f736786de74681260ed36429b886cdfb14215cf2a28ed.json
@@ -0,0 +1,21 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "UPDATE scheduling_booking SET status = $2, record = $3, recovery_at = $5 WHERE id = $1 AND status = $4 AND COALESCE(record->>'revision', '0') = $8 AND ($4 <> 'processing' OR (record->'operation'->>'id' IS NOT DISTINCT FROM $6 AND record->'operation'->>'attempt' IS NOT DISTINCT FROM $7))",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text",
+ "Jsonb",
+ "Text",
+ "Timestamptz",
+ "Text",
+ "Text",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "51460044bcd559f7bd4f736786de74681260ed36429b886cdfb14215cf2a28ed"
+}
diff --git a/.sqlx/query-58c402543075bfc006f9b1b87d8d3939c94a7273f4e0e4378a4bfc34474ce65d.json b/.sqlx/query-58c402543075bfc006f9b1b87d8d3939c94a7273f4e0e4378a4bfc34474ce65d.json
new file mode 100644
index 0000000000..fa018a44bb
--- /dev/null
+++ b/.sqlx/query-58c402543075bfc006f9b1b87d8d3939c94a7273f4e0e4378a4bfc34474ce65d.json
@@ -0,0 +1,19 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "INSERT INTO scheduling_booking (id, profile_id, request_id, event_type_id, starts_at, ends_at, status, record) SELECT id, $1, id, $2, $3, $4, 'confirmed', $5 FROM unnest($6::uuid[]) AS id",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Uuid",
+ "Timestamptz",
+ "Timestamptz",
+ "Jsonb",
+ "UuidArray"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "58c402543075bfc006f9b1b87d8d3939c94a7273f4e0e4378a4bfc34474ce65d"
+}
diff --git a/.sqlx/query-62013877159959e52fc0560b55c8dd38f227485d2225eb650b00a92744066c0f.json b/.sqlx/query-62013877159959e52fc0560b55c8dd38f227485d2225eb650b00a92744066c0f.json
new file mode 100644
index 0000000000..2873edd9f7
--- /dev/null
+++ b/.sqlx/query-62013877159959e52fc0560b55c8dd38f227485d2225eb650b00a92744066c0f.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT record FROM scheduling_booking WHERE request_id = $1",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "record",
+ "type_info": "Jsonb"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "62013877159959e52fc0560b55c8dd38f227485d2225eb650b00a92744066c0f"
+}
diff --git a/.sqlx/query-6dbba2c9a4027b48de6e8bb6d3e7e37fa7638e8c303791123f1766966c4fe4b2.json b/.sqlx/query-6dbba2c9a4027b48de6e8bb6d3e7e37fa7638e8c303791123f1766966c4fe4b2.json
new file mode 100644
index 0000000000..e16be0baa1
--- /dev/null
+++ b/.sqlx/query-6dbba2c9a4027b48de6e8bb6d3e7e37fa7638e8c303791123f1766966c4fe4b2.json
@@ -0,0 +1,20 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT record FROM scheduling_booking WHERE status IN ('processing', 'failed') AND recovery_at <= now() ORDER BY recovery_at, id FOR UPDATE SKIP LOCKED LIMIT 1",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "record",
+ "type_info": "Jsonb"
+ }
+ ],
+ "parameters": {
+ "Left": []
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "6dbba2c9a4027b48de6e8bb6d3e7e37fa7638e8c303791123f1766966c4fe4b2"
+}
diff --git a/.sqlx/query-7a7367fddcf0c9549099d20ebbe7d1d2841a6f16bb100c017ca8be59a0abc2c5.json b/.sqlx/query-7a7367fddcf0c9549099d20ebbe7d1d2841a6f16bb100c017ca8be59a0abc2c5.json
new file mode 100644
index 0000000000..46ab4d7d96
--- /dev/null
+++ b/.sqlx/query-7a7367fddcf0c9549099d20ebbe7d1d2841a6f16bb100c017ca8be59a0abc2c5.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "INSERT INTO scheduling_booking (id, profile_id, request_id, event_type_id, starts_at, ends_at, status, record, recovery_at) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9)",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Uuid",
+ "Uuid",
+ "Uuid",
+ "Timestamptz",
+ "Timestamptz",
+ "Text",
+ "Jsonb",
+ "Timestamptz"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "7a7367fddcf0c9549099d20ebbe7d1d2841a6f16bb100c017ca8be59a0abc2c5"
+}
diff --git a/.sqlx/query-7b4c2fbb0736aea43f2351d6c154404bbec20eb285a95fb8a346977b5ab3d52b.json b/.sqlx/query-7b4c2fbb0736aea43f2351d6c154404bbec20eb285a95fb8a346977b5ab3d52b.json
new file mode 100644
index 0000000000..4f583adfb3
--- /dev/null
+++ b/.sqlx/query-7b4c2fbb0736aea43f2351d6c154404bbec20eb285a95fb8a346977b5ab3d52b.json
@@ -0,0 +1,24 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "UPDATE scheduling_profile SET configuration = $2, revision = revision + 1 WHERE id = $1 AND revision = $3 RETURNING revision",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "revision",
+ "type_info": "Int8"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Jsonb",
+ "Int8"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "7b4c2fbb0736aea43f2351d6c154404bbec20eb285a95fb8a346977b5ab3d52b"
+}
diff --git a/.sqlx/query-7f79ce9e1dbcb284bda1ccb12decd61ad0cdd61553ecf04b03d8753b4c49d8db.json b/.sqlx/query-7f79ce9e1dbcb284bda1ccb12decd61ad0cdd61553ecf04b03d8753b4c49d8db.json
new file mode 100644
index 0000000000..bff33d0b75
--- /dev/null
+++ b/.sqlx/query-7f79ce9e1dbcb284bda1ccb12decd61ad0cdd61553ecf04b03d8753b4c49d8db.json
@@ -0,0 +1,25 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT count(*) FROM scheduling_booking WHERE profile_id = $1 AND event_type_id = $2 AND starts_at >= $3 AND starts_at < $4 AND status <> 'cancelled'",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "count",
+ "type_info": "Int8"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Uuid",
+ "Timestamptz",
+ "Timestamptz"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "7f79ce9e1dbcb284bda1ccb12decd61ad0cdd61553ecf04b03d8753b4c49d8db"
+}
diff --git a/.sqlx/query-82562dd27302110221e02759e0d9d5dcf9a6c3476855f4ac07cf21a28f38ad04.json b/.sqlx/query-82562dd27302110221e02759e0d9d5dcf9a6c3476855f4ac07cf21a28f38ad04.json
new file mode 100644
index 0000000000..543886d65d
--- /dev/null
+++ b/.sqlx/query-82562dd27302110221e02759e0d9d5dcf9a6c3476855f4ac07cf21a28f38ad04.json
@@ -0,0 +1,16 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "UPDATE scheduling_host_claim SET occupied = occupied + tstzmultirange(tstzrange($2,$3,'[)')) WHERE booking_id = $1",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Timestamptz",
+ "Timestamptz"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "82562dd27302110221e02759e0d9d5dcf9a6c3476855f4ac07cf21a28f38ad04"
+}
diff --git a/.sqlx/query-8b18b1bed8bb8f3561f1eb663cd00a6ab884ad392ae9f90e8745e34dddd7cb20.json b/.sqlx/query-8b18b1bed8bb8f3561f1eb663cd00a6ab884ad392ae9f90e8745e34dddd7cb20.json
new file mode 100644
index 0000000000..992cdcc4d1
--- /dev/null
+++ b/.sqlx/query-8b18b1bed8bb8f3561f1eb663cd00a6ab884ad392ae9f90e8745e34dddd7cb20.json
@@ -0,0 +1,25 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "INSERT INTO scheduling_profile (id, user_id, team_id, configuration) VALUES ($1, $2, $3, $4) RETURNING revision",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "revision",
+ "type_info": "Int8"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text",
+ "Uuid",
+ "Jsonb"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "8b18b1bed8bb8f3561f1eb663cd00a6ab884ad392ae9f90e8745e34dddd7cb20"
+}
diff --git a/.sqlx/query-8b3fe0fa438a269e5bd2292ee3738ed9de35d2b98ab2474f04fdfb9f6339bfcb.json b/.sqlx/query-8b3fe0fa438a269e5bd2292ee3738ed9de35d2b98ab2474f04fdfb9f6339bfcb.json
new file mode 100644
index 0000000000..f23ae3d55e
--- /dev/null
+++ b/.sqlx/query-8b3fe0fa438a269e5bd2292ee3738ed9de35d2b98ab2474f04fdfb9f6339bfcb.json
@@ -0,0 +1,17 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "INSERT INTO scheduling_host_claim (booking_id, user_id, occupied) VALUES ($1,$2,tstzmultirange(tstzrange($3,$4,'[)')))",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text",
+ "Timestamptz",
+ "Timestamptz"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "8b3fe0fa438a269e5bd2292ee3738ed9de35d2b98ab2474f04fdfb9f6339bfcb"
+}
diff --git a/.sqlx/query-8bb74dd8c24be38056a194cd87f1a95830648539b32cfd8116be11e0cac171a3.json b/.sqlx/query-8bb74dd8c24be38056a194cd87f1a95830648539b32cfd8116be11e0cac171a3.json
new file mode 100644
index 0000000000..6ad7643744
--- /dev/null
+++ b/.sqlx/query-8bb74dd8c24be38056a194cd87f1a95830648539b32cfd8116be11e0cac171a3.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT id FROM scheduling_profile WHERE id = $1 FOR UPDATE",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "8bb74dd8c24be38056a194cd87f1a95830648539b32cfd8116be11e0cac171a3"
+}
diff --git a/.sqlx/query-a0c3aed794f2bb8b37562e850f0b8136632c335a0134b85b8ca9b9992db5916c.json b/.sqlx/query-a0c3aed794f2bb8b37562e850f0b8136632c335a0134b85b8ca9b9992db5916c.json
new file mode 100644
index 0000000000..08d579f776
--- /dev/null
+++ b/.sqlx/query-a0c3aed794f2bb8b37562e850f0b8136632c335a0134b85b8ca9b9992db5916c.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT count(*) FROM scheduling_public_budget WHERE profile_id = $1",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "count",
+ "type_info": "Int8"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "a0c3aed794f2bb8b37562e850f0b8136632c335a0134b85b8ca9b9992db5916c"
+}
diff --git a/.sqlx/query-a33d4ed123089542b9ecef6578de50673e4d55bb25760285917116ffceeec7b9.json b/.sqlx/query-a33d4ed123089542b9ecef6578de50673e4d55bb25760285917116ffceeec7b9.json
new file mode 100644
index 0000000000..81ec451424
--- /dev/null
+++ b/.sqlx/query-a33d4ed123089542b9ecef6578de50673e4d55bb25760285917116ffceeec7b9.json
@@ -0,0 +1,31 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT host AS \"host!\", count(*) AS \"count!\"\n FROM scheduling_booking\n CROSS JOIN LATERAL jsonb_array_elements_text(record->'booking'->'hosts') AS host\n WHERE profile_id = $1 AND starts_at >= $2 AND starts_at < $3\n AND status <> 'cancelled' AND host = ANY($4)\n GROUP BY host",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "host!",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 1,
+ "name": "count!",
+ "type_info": "Int8"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Timestamptz",
+ "Timestamptz",
+ "TextArray"
+ ]
+ },
+ "nullable": [
+ null,
+ null
+ ]
+ },
+ "hash": "a33d4ed123089542b9ecef6578de50673e4d55bb25760285917116ffceeec7b9"
+}
diff --git a/.sqlx/query-add7da0319cea71451fc509584591ba15a6973e42321c4261c186918635903a6.json b/.sqlx/query-add7da0319cea71451fc509584591ba15a6973e42321c4261c186918635903a6.json
new file mode 100644
index 0000000000..47d84f4dee
--- /dev/null
+++ b/.sqlx/query-add7da0319cea71451fc509584591ba15a6973e42321c4261c186918635903a6.json
@@ -0,0 +1,14 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "UPDATE scheduling_booking SET recovery_at = now() - interval '1 second' WHERE id = $1",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "add7da0319cea71451fc509584591ba15a6973e42321c4261c186918635903a6"
+}
diff --git a/.sqlx/query-dd4161b288754823091dc885e109b2f1713c0d4272746ded9ed159328b61de0d.json b/.sqlx/query-dd4161b288754823091dc885e109b2f1713c0d4272746ded9ed159328b61de0d.json
new file mode 100644
index 0000000000..1ce103ad05
--- /dev/null
+++ b/.sqlx/query-dd4161b288754823091dc885e109b2f1713c0d4272746ded9ed159328b61de0d.json
@@ -0,0 +1,16 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "UPDATE scheduling_booking SET status = 'processing', record = $2, recovery_at = $3 WHERE id = $1",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Jsonb",
+ "Timestamptz"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "dd4161b288754823091dc885e109b2f1713c0d4272746ded9ed159328b61de0d"
+}
diff --git a/.sqlx/query-f01ac4a2d86bb2ac055beca13b1b5c87a8d4e57ce7d893c5eec9493f438a861c.json b/.sqlx/query-f01ac4a2d86bb2ac055beca13b1b5c87a8d4e57ce7d893c5eec9493f438a861c.json
new file mode 100644
index 0000000000..c24dc2c82d
--- /dev/null
+++ b/.sqlx/query-f01ac4a2d86bb2ac055beca13b1b5c87a8d4e57ce7d893c5eec9493f438a861c.json
@@ -0,0 +1,37 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT user_id, lower(piece) AS \"start!\", upper(piece) AS \"end!\" FROM scheduling_host_claim CROSS JOIN LATERAL unnest(occupied) AS piece WHERE user_id = ANY($1) AND piece && tstzrange($2, $3, '[)') AND ($4::uuid IS NULL OR booking_id <> $4)",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "user_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 1,
+ "name": "start!",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 2,
+ "name": "end!",
+ "type_info": "Timestamptz"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "TextArray",
+ "Timestamptz",
+ "Timestamptz",
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false,
+ null,
+ null
+ ]
+ },
+ "hash": "f01ac4a2d86bb2ac055beca13b1b5c87a8d4e57ce7d893c5eec9493f438a861c"
+}
diff --git a/Cargo.lock b/Cargo.lock
index 6700d86682..d719c21fa0 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -3454,6 +3454,31 @@ dependencies = [
"workspace-hack",
]
+[[package]]
+name = "calendar_scheduling"
+version = "0.1.0"
+dependencies = [
+ "axum",
+ "calendar_events",
+ "chrono",
+ "chrono-tz",
+ "email_validator",
+ "macro_authorization",
+ "macro_user_id",
+ "model_user",
+ "reqwest 0.13.4",
+ "rootcause",
+ "serde",
+ "serde_json",
+ "sqlx",
+ "teams",
+ "thiserror 2.0.18",
+ "tokio",
+ "tracing",
+ "uuid",
+ "workspace-hack",
+]
+
[[package]]
name = "calendar_service"
version = "0.1.0"
@@ -3464,6 +3489,7 @@ dependencies = [
"aws-sdk-sqs",
"axum",
"calendar_events",
+ "calendar_scheduling",
"chrono",
"connection_gateway_client",
"email_db_client",
@@ -3491,6 +3517,7 @@ dependencies = [
"sqlx",
"sqs_worker",
"subtle",
+ "teams",
"tokio",
"tokio-util",
"tower 0.5.3",
diff --git a/Cargo.toml b/Cargo.toml
index 6278faa146..41db948cf1 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -17,6 +17,7 @@ members = [
"crates/bots",
"crates/broadcast",
"crates/calendar_events",
+ "crates/calendar_scheduling",
"crates/channel_bots",
"crates/channel_labels",
"crates/client/cache-core",
diff --git a/apps/web/src/features/calendar-view/components/Header.tsx b/apps/web/src/features/calendar-view/components/Header.tsx
index 8613459f00..8187b47941 100644
--- a/apps/web/src/features/calendar-view/components/Header.tsx
+++ b/apps/web/src/features/calendar-view/components/Header.tsx
@@ -7,6 +7,7 @@ import { MonthDrawer } from '@app/features/calendar/components/MonthDrawer';
import { PeriodSelector } from '@app/features/calendar/components/PeriodSelector';
import { useCalendarHotkeys } from '@app/features/calendar/hooks/use-calendar-hotkeys';
import { calendarPeriodLabel } from '@app/features/calendar/utils/calendar-label';
+import { CalendarSchedulingActions } from '@app/features/scheduling/calendar-actions';
import { createSizeBreakpoints } from '@app/util/create-size-breakpoints';
import { HeaderIsland } from '@components/app/split-layout/components/HeaderIsland';
import {
@@ -289,6 +290,7 @@ export function Header(props: { presentation: 'workspace' | 'preview' }) {
<Show when={!isMobile()}>
<CalendarSearch />
</Show>
+ <CalendarSchedulingActions />
<Show when={props.presentation === 'preview' || isMobile()}>
<CalendarSettingsDropdown isNarrow={isNarrow()} />
</Show>
@@ -368,6 +370,7 @@ export function Header(props: { presentation: 'workspace' | 'preview' }) {
{headerCreateMenu()}
</div>
</Show>
+ <CalendarSchedulingActions />
{todayButton(!breakpoints.labeledToday())}
<PeriodSelector isNarrow={isNarrow()} />
{previous()}
diff --git a/apps/web/src/features/scheduling/browser-test/fixture.tsx b/apps/web/src/features/scheduling/browser-test/fixture.tsx
new file mode 100644
index 0000000000..901aa5e3e2
--- /dev/null
+++ b/apps/web/src/features/scheduling/browser-test/fixture.tsx
@@ -0,0 +1,421 @@
+import { macroDarkTheme } from '../../theme/themes/macro-dark';
+import { macroLightTheme } from '../../theme/themes/macro-light';
+import { themeCssVars } from '../../theme/utils/themeColorTokens';
+import { BookingReceiptView } from '../views/booking-receipt-view';
+import '@fontsource-variable/inter';
+import '../../../index.css';
+import { createSignal, onCleanup, onMount, Show } from 'solid-js';
+import { createStore } from 'solid-js/store';
+import { render } from 'solid-js/web';
+import {
+ type SchedulingCapabilities,
+ SchedulingProvider,
+} from '../context/scheduling-context';
+import {
+ type Booking,
+ type BookingReceipt,
+ newEventType,
+ newSchedule,
+ type PublicProfile,
+ type SchedulingProfile,
+} from '../core/types';
+import { PublicBookingView } from '../views/public-booking-view';
+import { SchedulingSettingsView } from '../views/settings-view';
+
+function Fixture() {
+ const [loseNextResponse, setLoseNextResponse] = createSignal(false);
+ const receipts = new Map<string, BookingReceipt>();
+ const [narrow, setNarrow] = createSignal(false);
+ const [dark, setDark] = createSignal(false);
+ const applyTheme = (isDark: boolean) => {
+ setDark(isDark);
+ const base = isDark ? macroDarkTheme : macroLightTheme;
+ const vars = themeCssVars({
+ ...base,
+ colorTokens: {
+ ...base.colorTokens,
+ 'surface-0': isDark ? '#111111' : '#fafafa',
+ 'surface-1': isDark ? '#202020' : '#f7f7f8',
+ 'surface-2': isDark ? '#202020' : '#ffffff',
+ 'surface-3': isDark ? '#292929' : '#ffffff',
+ 'surface-4': isDark ? '#333333' : '#ffffff',
+ panel: isDark ? '#181818' : '#ffffff',
+ accent: isDark ? '#eeeeee' : '#171717',
+ edge: isDark ? '#3a3a3a' : '#dedede',
+ 'edge-muted': isDark ? '#2e2e2e' : '#e5e5e5',
+ },
+ });
+ for (const [key, value] of Object.entries(vars))
+ document.documentElement.style.setProperty(key, value);
+ document.documentElement.style.colorScheme = isDark ? 'dark' : 'light';
+ };
+ onMount(() => applyTheme(false));
+ const [screen, setScreen] = createSignal<'settings' | 'public' | 'receipt'>(
+ 'settings'
+ );
+ const [slug, setSlug] = createSignal<string>();
+ const schedule = newSchedule('America/New_York');
+ const event = {
+ ...newEventType(schedule.id, ['macro|[email protected]'], false),
+ title: '30 minute meeting',
+ slug: '30-minute-meeting',
+ enabled: true,
+ description:
+ 'A little time to connect, share ideas, and talk through what’s next.',
+ };
+ const [profileStore, setProfiles] = createStore<
+ Record<string, SchedulingProfile>
+ >({
+ me: {
+ id: '00000000-0000-4000-8000-000000000001',
+ name: 'Alex Morgan',
+ description: 'Find a time that works for you.',
+ schedules: [schedule],
+ defaultScheduleId: schedule.id,
+ eventTypes: [event],
+ revision: 1,
+ },
+ team: {
+ id: '00000000-0000-4000-8000-000000000002',
+ name: 'Design team',
+ description: 'Meet the team.',
+ schedules: [schedule],
+ defaultScheduleId: schedule.id,
+ eventTypes: [
+ {
+ ...event,
+ id: crypto.randomUUID(),
+ title: 'Team introduction',
+ slug: 'team-introduction',
+ mode: 'collective',
+ hosts: ['macro|[email protected]', 'macro|[email protected]'],
+ },
+ ],
+ revision: 1,
+ },
+ });
+ // Match the reactive store data returned by Solid Query in the real app.
+ const profiles = () => profileStore;
+ const [active, setActive] = createSignal('me');
+ type PreviewBooking = Booking & { profileId: string };
+ const sampleBookings = Object.values(profiles()).flatMap((profile, owner) =>
+ Array.from({ length: 34 }, (_, i): PreviewBooking => {
+ const date = new Date();
+ date.setUTCHours(14 + (i % 5), 0, 0, 0);
+ date.setUTCDate(date.getUTCDate() - 12 + Math.floor(i / 2));
+ const cancelled = i % 9 === 0;
+ return {
+ id: `sample-${owner}-${i}`,
+ profileId: profile.id,
+ eventTypeId: profile.eventTypes[0].id,
+ title: profile.eventTypes[0].title,
+ name: ['Jordan Lee', 'Taylor Chen', 'Casey Williams', 'Morgan Patel'][
+ i % 4
+ ],
+ email: `guest${i}@example.com`,
+ startsAt: date.toISOString(),
+ endsAt: new Date(date.getTime() + 1800000).toISOString(),
+ timeZone: 'America/New_York',
+ hosts: profile.eventTypes[0].hosts,
+ status: cancelled
+ ? 'cancelled'
+ : i > 28 && i % 2 === 0
+ ? 'pending'
+ : 'confirmed',
+ location: 'Google Meet',
+ answers: {},
+ rescheduleCount: i % 7 === 0 ? 1 : 0,
+ rescheduledAt:
+ i % 7 === 0
+ ? new Date(date.getTime() - 86400000).toISOString()
+ : null,
+ attendance:
+ date < new Date() && !cancelled
+ ? i % 11 === 0
+ ? 'guestNoShow'
+ : i % 13 === 0
+ ? 'hostNoShow'
+ : 'attended'
+ : 'unknown',
+ };
+ })
+ );
+ const [bookings, setBookings] =
+ createSignal<PreviewBooking[]>(sampleBookings);
+ const [notice, setNotice] = createSignal('');
+ const [receipt, setReceipt] = createSignal<BookingReceipt>();
+ const updateReceipt = (booking: Booking) => {
+ setBookings(
+ bookings().map((b) => (b.id === booking.id ? { ...b, ...booking } : b))
+ );
+ setReceipt((r) => (r ? { ...r, booking } : r));
+ };
+ const sampleSlots = (date: string) =>
+ [14, 15, 16].map((hour) => ({
+ startsAt: `${date}T${hour}:00:00Z`,
+ endsAt: `${date}T${hour}:30:00Z`,
+ }));
+ const current = () => profiles()[active()];
+ const publicProfile = (): PublicProfile => ({
+ ...current(),
+ eventTypes: current().eventTypes.filter((e) => e.enabled),
+ });
+ onMount(() => {
+ const followPreview = () => {
+ const parts = location.hash.slice(1).split('/');
+ if (parts[0] !== 'preview') return;
+ const entry = Object.entries(profiles()).find(
+ ([, p]) => p.id === parts[1]
+ );
+ if (!entry) return;
+ setActive(entry[0]);
+ setSlug(parts[2] || undefined);
+ setScreen('public');
+ };
+ followPreview();
+ window.addEventListener('hashchange', followPreview);
+ onCleanup(() => window.removeEventListener('hashchange', followPreview));
+ });
+ let selectedScope = () => 'me';
+ const capabilities: SchedulingCapabilities = {
+ userId: () => 'macro|[email protected]',
+ scopes: () => [
+ { id: 'me', name: 'Personal', canEdit: true },
+ { id: 'team', teamId: 'team', name: 'Design team', canEdit: true },
+ {
+ id: 'readonly',
+ teamId: 'team',
+ name: 'Team member (read only)',
+ canEdit: false,
+ },
+ ],
+ members: () => [
+ {
+ id: 'macro|[email protected]',
+ name: 'Alex Morgan',
+ email: '[email protected]',
+ },
+ {
+ id: 'macro|[email protected]',
+ name: 'Sam Rivera',
+ email: '[email protected]',
+ },
+ ],
+ link: (p, s) => `#preview/${p.id}/${s ?? ''}`,
+ copyLink: async () => {
+ setNotice('Booking link copied (isolated preview)');
+ },
+ manageBooking: async (id) => {
+ const booking = bookings().find((b) => b.id === id);
+ if (booking) {
+ setReceipt({
+ booking,
+ token: 'sample',
+ scheduleTimeZone: 'America/New_York',
+ });
+ setScreen('receipt');
+ }
+ },
+ openConnections: () => setNotice('Calendar connection shortcut selected'),
+ openTeamSettings: () => setNotice('Macro team settings shortcut selected'),
+ createSource: (scope, range) => {
+ selectedScope = () => (scope().id === 'readonly' ? 'team' : scope().id);
+ return {
+ profile: () =>
+ profiles()[scope().id === 'readonly' ? 'team' : scope().id],
+ bookings: () =>
+ bookings().filter(
+ (b) =>
+ b.profileId ===
+ profiles()[scope().id === 'readonly' ? 'team' : scope().id]
+ .id &&
+ b.startsAt >= range().from &&
+ b.startsAt < range().to
+ ),
+ loadInsights: async (from, to) =>
+ bookings().filter(
+ (b) =>
+ b.profileId ===
+ profiles()[scope().id === 'readonly' ? 'team' : scope().id]
+ .id &&
+ b.startsAt >= from &&
+ b.startsAt < to
+ ),
+ setAttendance: async (id, attendance) => {
+ const booking = bookings().find((b) => b.id === id);
+ if (
+ !booking ||
+ (!scope().canEdit &&
+ !booking.hosts.includes('macro|[email protected]'))
+ )
+ throw new Error('Forbidden');
+ if (
+ booking.status !== 'confirmed' ||
+ new Date(booking.endsAt) > new Date()
+ )
+ throw new Error('Attendance is available after the meeting ends.');
+ setBookings(
+ bookings().map((b) => (b.id === id ? { ...b, attendance } : b))
+ );
+ },
+ loading: () => false,
+ error: () => undefined,
+ saving: () => false,
+ reload: () => {},
+ save: async (p) => {
+ if (!scope().canEdit) throw new Error('Forbidden');
+ setProfiles({
+ ...profiles(),
+ [scope().id]: { ...p, revision: p.revision + 1 },
+ });
+ setActive(scope().id);
+ },
+ approve: async (id) => {
+ setBookings(
+ bookings().map((b) =>
+ b.id === id ? { ...b, status: 'confirmed' } : b
+ )
+ );
+ },
+ cancel: async (id) => {
+ setBookings(
+ bookings().map((b) =>
+ b.id === id ? { ...b, status: 'cancelled' } : b
+ )
+ );
+ },
+ };
+ },
+ };
+ return (
+ <div class="flex h-screen flex-col bg-panel text-ink">
+ <div class="flex flex-wrap items-center gap-3 shrink-0 border-b border-edge-muted bg-panel px-5 py-3 text-xs">
+ <strong>Isolated scheduling preview</strong>
+ <span class="text-ink-muted">
+ Sample data only · no invitations sent
+ </span>
+ <button type="button" onClick={() => setScreen('settings')}>
+ Settings
+ </button>
+ <button
+ type="button"
+ onClick={() => {
+ setActive(selectedScope());
+ setSlug(undefined);
+ setScreen('public');
+ }}
+ >
+ Public booking page
+ </button>
+ <button type="button" onClick={() => applyTheme(!dark())}>
+ {dark() ? 'Light preview' : 'Dark preview'}
+ </button>
+ <button type="button" onClick={() => setNarrow(!narrow())}>
+ {narrow() ? 'Full width' : 'Mobile width'}
+ </button>
+ <button type="button" onClick={() => setLoseNextResponse(true)}>
+ {loseNextResponse()
+ ? 'Lost response armed'
+ : 'Simulate lost booking response'}
+ </button>
+ <span role="status">{notice()}</span>
+ </div>
+ <div
+ class="min-h-0 flex-1 mx-auto w-full"
+ style={{ 'max-width': narrow() ? '390px' : undefined }}
+ >
+ <Show when={screen() === 'settings'}>
+ <SchedulingProvider value={capabilities}>
+ <SchedulingSettingsView />
+ </SchedulingProvider>
+ </Show>
+ <Show when={screen() === 'public'}>
+ <PublicBookingView
+ profile={publicProfile()}
+ event={publicProfile().eventTypes.find((e) => e.slug === slug())}
+ onEvent={setSlug}
+ onReceipt={(r) => {
+ setReceipt(r);
+ setScreen('receipt');
+ }}
+ source={{
+ slots: async (_p, _e, date) =>
+ [14, 15, 16].map((hour) => ({
+ startsAt: `${date}T${hour}:00:00Z`,
+ endsAt: `${date}T${hour}:30:00Z`,
+ })),
+ book: async (_p, eventId, r) => {
+ const existing = receipts.get(r.requestId);
+ if (existing) return existing;
+ const e = current().eventTypes.find((e) => e.id === eventId)!;
+ const booking: PreviewBooking = {
+ profileId: current().id,
+ attendance: 'unknown',
+ rescheduleCount: 0,
+ rescheduledAt: null,
+ id: crypto.randomUUID(),
+ eventTypeId: eventId,
+ title: e.title,
+ name: r.name,
+ email: r.email,
+ startsAt: r.startsAt,
+ endsAt: new Date(
+ new Date(r.startsAt).getTime() + e.durationMinutes * 60000
+ ).toISOString(),
+ timeZone: r.timeZone,
+ hosts: e.hosts,
+ status: e.requiresConfirmation ? 'pending' : 'confirmed',
+ location: 'Google Meet',
+ answers: r.answers,
+ };
+ setBookings([...bookings(), booking]);
+ const receipt = {
+ booking,
+ token: crypto.randomUUID(),
+ scheduleTimeZone: 'America/New_York',
+ };
+ receipts.set(r.requestId, receipt);
+ if (loseNextResponse()) {
+ setLoseNextResponse(false);
+ throw new Error('Injected lost response after reservation');
+ }
+ return receipt;
+ },
+ }}
+ />
+ </Show>
+ <Show when={screen() === 'receipt'}>
+ <BookingReceiptView
+ receipt={receipt()}
+ unavailable={false}
+ cancel={async () => {
+ const r = receipt();
+ if (r) updateReceipt({ ...r.booking, status: 'cancelled' });
+ }}
+ loadSlots={async (date) => sampleSlots(date)}
+ reschedule={async (start) => {
+ const r = receipt();
+ if (r) {
+ const duration =
+ new Date(r.booking.endsAt).getTime() -
+ new Date(r.booking.startsAt).getTime();
+ updateReceipt({
+ ...r.booking,
+ startsAt: start,
+ rescheduleCount: (r.booking.rescheduleCount ?? 0) + 1,
+ rescheduledAt: new Date().toISOString(),
+ attendance: 'unknown',
+ endsAt: new Date(
+ new Date(start).getTime() + duration
+ ).toISOString(),
+ });
+ }
+ }}
+ />
+ </Show>
+ </div>
+ </div>
+ );
+}
+const root = document.getElementById('root');
+if (root) render(() => <Fixture />, root);
diff --git a/apps/web/src/features/scheduling/browser-test/index.html b/apps/web/src/features/scheduling/browser-test/index.html
new file mode 100644
index 0000000000..3c79fa0a8d
--- /dev/null
+++ b/apps/web/src/features/scheduling/browser-test/index.html
@@ -0,0 +1,2 @@
+<!doctype html>
+<html lang="en" data-modality="keyboard"><head><meta charset="UTF-8"/><meta name="viewport" content="width=device-width,initial-scale=1.0"/><title>Macro scheduling preview · isolated fixtures</title></head><body><div id="root"></div><script type="module" src="./fixture.tsx"></script></body></html>
diff --git a/apps/web/src/features/scheduling/calendar-actions.tsx b/apps/web/src/features/scheduling/calendar-actions.tsx
new file mode 100644
index 0000000000..5cbd40c014
--- /dev/null
+++ b/apps/web/src/features/scheduling/calendar-actions.tsx
@@ -0,0 +1,67 @@
+import { ShowFeatureFlag } from '@app/lib/analytics/posthog';
+import { toast } from '@core/component/Toast/Toast';
+import { enableCalendarScheduling } from '@core/constant/featureFlags';
+import { useSettingsState } from '@core/constant/SettingsState';
+import { useUserId } from '@core/context/user';
+import { writeClipboardData } from '@core/util/dataTransfer';
+import { getWebOrigin } from '@core/util/webOrigin';
+import GearIcon from '@phosphor/gear.svg';
+import LinkIcon from '@phosphor/link.svg';
+import { Button } from '@ui';
+import { Suspense } from 'solid-js';
+import { useSchedulingProfileQuery } from './queries/source';
+
+function Actions() {
+ const user = useUserId();
+ const settings = useSettingsState();
+ const source = useSchedulingProfileQuery(() => ({
+ id: user() ?? 'me',
+ name: 'Personal',
+ canEdit: true,
+ }));
+ const copy = async () => {
+ const profile = source.isSuccess ? source.data : undefined;
+ if (!profile?.revision || !profile.eventTypes.some((e) => e.enabled)) {
+ settings.openSettings('Calendar');
+ return;
+ }
+ if (
+ await writeClipboardData({
+ 'text/plain': `${getWebOrigin()}/app/book/${encodeURIComponent(profile.id)}`,
+ })
+ )
+ toast.success('Booking link copied');
+ else toast.failure('Could not copy booking link');
+ };
+ return (
+ <div class="flex shrink-0 items-center gap-1">
+ <Button
+ variant="ghost"
+ size="sm"
+ label="Copy booking link"
+ disabled={source.isPending}
+ onClick={() => void copy()}
+ >
+ <LinkIcon class="size-3.5" />
+ <span class="hidden lg:inline">Booking link</span>
+ </Button>
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ label="Open calendar scheduling settings"
+ onClick={() => settings.openSettings('Calendar')}
+ >
+ <GearIcon class="size-3.5" />
+ </Button>
+ </div>
+ );
+}
+export function CalendarSchedulingActions() {
+ return (
+ <ShowFeatureFlag flag={enableCalendarScheduling}>
+ <Suspense>
+ <Actions />
+ </Suspense>
+ </ShowFeatureFlag>
+ );
+}
diff --git a/apps/web/src/features/scheduling/components/availability-panel.tsx b/apps/web/src/features/scheduling/components/availability-panel.tsx
new file mode 100644
index 0000000000..df00e893d1
--- /dev/null
+++ b/apps/web/src/features/scheduling/components/availability-panel.tsx
@@ -0,0 +1,126 @@
+import Clock from '@phosphor/clock.svg';
+import Globe from '@phosphor/globe.svg';
+import { Button } from '@ui';
+import { createSignal, For, Show } from 'solid-js';
+import type { AvailabilitySchedule, SchedulingProfile } from '../core/types';
+import { WEEKDAYS } from '../core/types';
+
+export function AvailabilityPanel(props: {
+ profile: SchedulingProfile;
+ canEdit: boolean;
+ saving: boolean;
+ onEdit: (schedule: AvailabilitySchedule) => void;
+ onDefault: (schedule: AvailabilitySchedule) => void;
+ onDelete: (schedule: AvailabilitySchedule) => void;
+}) {
+ const [remove, setRemove] = createSignal<string>();
+ const defaultId = () =>
+ props.profile.defaultScheduleId ?? props.profile.schedules[0]?.id;
+ const usedBy = (id: string) =>
+ props.profile.eventTypes.filter((e) => e.scheduleId === id);
+ return (
+ <div class="overflow-hidden rounded-xl border border-edge-muted bg-panel">
+ <For
+ each={props.profile.schedules}
+ fallback={
+ <div class="flex flex-col items-center gap-3 px-6 py-16 text-center">
+ <Clock class="size-7 text-ink-muted" />
+ <h2 class="font-semibold">Set your working hours</h2>
+ <p class="text-sm text-ink-muted">
+ Create a schedule to start accepting bookings.
+ </p>
+ </div>
+ }
+ >
+ {(schedule) => (
+ <article class="border-b border-edge-muted px-6 py-5 last:border-b-0">
+ <div class="flex flex-wrap items-start justify-between gap-5">
+ <button
+ type="button"
+ class="min-w-0 flex-1 text-left"
+ disabled={!props.canEdit}
+ onClick={() => props.onEdit(schedule)}
+ >
+ <div class="flex items-center gap-3">
+ <h2 class="font-semibold">{schedule.name}</h2>
+ <Show when={defaultId() === schedule.id}>
+ <span class="rounded-md bg-active px-2 py-0.5 text-xs text-ink-muted">
+ Default
+ </span>
+ </Show>
+ </div>
+ <div class="mt-3 flex flex-wrap gap-x-5 gap-y-2 text-sm text-ink-muted">
+ <span class="inline-flex items-center gap-1.5">
+ <Clock class="size-4" />
+ {schedule.weekly
+ .filter((d) => d.windows.length)
+ .map((d) => WEEKDAYS[d.day].slice(0, 3))
+ .join(', ') || 'No available days'}
+ </span>
+ <span class="inline-flex items-center gap-1.5">
+ <Globe class="size-4" />
+ {schedule.timeZone.replaceAll('_', ' ')}
+ </span>
+ </div>
+ <p class="mt-2 text-xs text-ink-muted">
+ {usedBy(schedule.id).length} event types ·{' '}
+ {schedule.overrides.length} date overrides
+ </p>
+ </button>
+ <Show when={props.canEdit}>
+ <div class="flex gap-2">
+ <Button
+ variant="outline"
+ onClick={() => props.onEdit(schedule)}
+ >
+ Edit
+ </Button>
+ <Show when={defaultId() !== schedule.id}>
+ <Button
+ variant="ghost"
+ disabled={props.saving}
+ onClick={() => props.onDefault(schedule)}
+ >
+ Set as default
+ </Button>
+ </Show>
+ <Button
+ variant="ghost"
+ onClick={() => setRemove(schedule.id)}
+ >
+ Delete
+ </Button>
+ </div>
+ </Show>
+ </div>
+ <Show when={props.canEdit && remove() === schedule.id}>
+ <div class="mt-4 flex flex-wrap items-center gap-3 border-t border-edge-muted pt-4">
+ <p class="flex-1 text-sm">
+ {usedBy(schedule.id).length
+ ? `Move ${usedBy(schedule.id)
+ .map((e) => e.title)
+ .join(
+ ', '
+ )} to another schedule before deleting this one.`
+ : `Delete “${schedule.name}”?`}
+ </p>
+ <Button variant="ghost" onClick={() => setRemove(undefined)}>
+ Keep schedule
+ </Button>
+ <Show when={!usedBy(schedule.id).length}>
+ <Button
+ variant="outline"
+ disabled={props.saving}
+ onClick={() => props.onDelete(schedule)}
+ >
+ Delete schedule
+ </Button>
+ </Show>
+ </div>
+ </Show>
+ </article>
+ )}
+ </For>
+ </div>
+ );
+}
diff --git a/apps/web/src/features/scheduling/components/bookings-panel.tsx b/apps/web/src/features/scheduling/components/bookings-panel.tsx
new file mode 100644
index 0000000000..13b03736ce
--- /dev/null
+++ b/apps/web/src/features/scheduling/components/bookings-panel.tsx
@@ -0,0 +1,480 @@
+import { TabsInset } from '@core/component/TabsInset';
+import CalendarIcon from '@phosphor/calendar-blank.svg';
+import CaretUp from '@phosphor/caret-up.svg';
+import ClockIcon from '@phosphor/clock.svg';
+import MagnifyingGlass from '@phosphor/magnifying-glass.svg';
+import UsersIcon from '@phosphor/users.svg';
+import { Button } from '@ui';
+import { createSignal, For, Show } from 'solid-js';
+import {
+ type BookingTab,
+ bookingTab,
+ bookingTimeRange,
+ filterBookings,
+} from '../core/booking-list';
+import type { Booking, EventType, SchedulingMember } from '../core/types';
+import { SelectInput, TextInput, TimeZoneInput } from './fields';
+
+export type BookingsPanelProps = {
+ bookings: Booking[];
+ events: EventType[];
+ members: SchedulingMember[];
+ canEdit: boolean;
+ busyId: string;
+ currentUserId: string;
+ onApprove: (id: string) => void;
+ onCancel: (id: string) => void;
+ onManage: (id: string) => void;
+ onAttendance: (
+ id: string,
+ attendance: NonNullable<Booking['attendance']>
+ ) => void;
+};
+
+function BookingStatus(props: { booking: Booking }) {
+ const label = () => {
+ if (props.booking.status === 'pending') return 'Unconfirmed';
+ if (props.booking.status === 'failed') return 'Calendar sync failed';
+ if (props.booking.status === 'processing') return 'Syncing calendar';
+ if (props.booking.status === 'cancelled') return 'Cancelled';
+ if (props.booking.attendance === 'guestNoShow') return 'Guest no-show';
+ if (props.booking.attendance === 'hostNoShow') return 'Host no-show';
+ if (props.booking.attendance === 'attended') return 'Attended';
+ return new Date(props.booking.endsAt).getTime() <= Date.now()
+ ? 'Ended'
+ : 'Confirmed';
+ };
+ return (
+ <span
+ class="inline-flex items-center gap-1.5 whitespace-nowrap rounded-md border border-edge-muted px-2 py-1 text-xs text-ink-muted"
+ classList={{
+ 'bg-success-bg text-success border-transparent':
+ props.booking.status === 'confirmed' &&
+ (props.booking.attendance === 'attended' ||
+ new Date(props.booking.endsAt).getTime() > Date.now()),
+ 'bg-warning-bg text-warning border-transparent':
+ props.booking.status === 'pending' ||
+ props.booking.status === 'processing',
+ 'bg-failure-bg text-failure border-transparent':
+ props.booking.status === 'failed' ||
+ props.booking.attendance === 'guestNoShow' ||
+ props.booking.attendance === 'hostNoShow',
+ }}
+ >
+ <span class="size-1.5 rounded-full bg-current" />
+ {label()}
+ </span>
+ );
+}
+
+function BookingRow(
+ props: Omit<BookingsPanelProps, 'bookings' | 'events'> & {
+ booking: Booking;
+ event?: EventType;
+ timeZone: string;
+ }
+) {
+ const [expanded, setExpanded] = createSignal(false);
+ const [confirmCancel, setConfirmCancel] = createSignal(false);
+ const isPast = () => new Date(props.booking.endsAt).getTime() <= Date.now();
+ const hosts = () =>
+ props.booking.hosts.map((id) => {
+ const member = props.members.find((m) => m.id === id);
+ return member?.name || member?.email || 'Calendar host';
+ });
+ const canManage = () =>
+ props.canEdit &&
+ (props.booking.status === 'pending' ||
+ (props.booking.status === 'confirmed' && !isPast()));
+ const meetingUrl = () => {
+ try {
+ const url = new URL(props.booking.location);
+ return url.protocol === 'https:' || url.protocol === 'http:'
+ ? url.href
+ : undefined;
+ } catch {
+ return undefined;
+ }
+ };
+ const date = (options: Intl.DateTimeFormatOptions) =>
+ new Intl.DateTimeFormat(undefined, {
+ timeZone: props.timeZone,
+ ...options,
+ }).format(new Date(props.booking.startsAt));
+ const answerLabel = (id: string) =>
+ props.booking.questionLabels?.[id] ??
+ props.event?.questions.find((question) => question.id === id)?.label ??
+ 'Additional response';
+ return (
+ <article class="bg-panel px-5 py-5 @min-[720px]:px-6">
+ <div class="grid min-w-0 grid-cols-[72px_1fr] gap-x-5 gap-y-4 @min-[880px]:grid-cols-[100px_1fr_auto]">
+ <div class="pt-0.5">
+ <p class="text-xs font-medium text-ink-muted">
+ {date({ weekday: 'long' })}
+ </p>
+ <p class="mt-1 text-lg font-semibold tabular-nums">
+ {date({ month: 'short', day: 'numeric' })}
+ </p>
+ <p class="mt-1 text-xs text-ink-muted">{date({ year: 'numeric' })}</p>
+ </div>
+ <div class="min-w-0">
+ <div class="flex flex-wrap items-center gap-2">
+ <h3 class="break-words font-semibold">{props.booking.title}</h3>
+ <BookingStatus booking={props.booking} />
+ <Show when={(props.booking.rescheduleCount ?? 0) > 0}>
+ <span class="text-xs text-ink-muted">Rescheduled</span>
+ </Show>
+ </div>
+ <p class="mt-1 text-sm">
+ {props.booking.name}
+ <span class="mx-1.5 text-ink-muted">·</span>
+ <span class="break-all text-ink-muted">{props.booking.email}</span>
+ </p>
+ <div class="mt-3 flex flex-wrap gap-x-5 gap-y-2 text-xs text-ink-muted">
+ <span class="flex items-center gap-1.5">
+ <ClockIcon class="size-3.5" />
+ {bookingTimeRange(props.booking, props.timeZone)}
+ </span>
+ <Show when={hosts().length}>
+ <span class="flex items-center gap-1.5">
+ <UsersIcon class="size-3.5 shrink-0" />
+ {hosts().join(', ')}
+ </span>
+ </Show>
+ </div>
+ <Show when={props.booking.location}>
+ <p class="mt-2 break-words text-xs text-ink-muted">
+ {props.booking.location}
+ </p>
+ </Show>
+ </div>
+ <div class="col-start-2 flex flex-wrap items-start gap-2 @min-[880px]:col-start-3">
+ <Show
+ when={
+ props.booking.status === 'confirmed' && !isPast() && meetingUrl()
+ }
+ >
+ <a
+ href={meetingUrl()}
+ target="_blank"
+ rel="noopener noreferrer"
+ class="inline-flex h-8 items-center rounded-md border border-edge-muted px-3 text-sm font-medium hover:bg-hover"
+ >
+ Join meeting ↗
+ </a>
+ </Show>
+ <Show when={canManage() && !isPast()}>
+ <Show when={props.booking.status === 'pending'}>
+ <Button
+ variant="strong"
+ size="sm"
+ disabled={!!props.busyId}
+ onClick={() => props.onApprove(props.booking.id)}
+ >
+ Confirm
+ </Button>
+ </Show>
+ <Button
+ variant="outline"
+ size="sm"
+ disabled={!!props.busyId}
+ onClick={() => props.onManage(props.booking.id)}
+ >
+ Reschedule
+ </Button>
+ </Show>
+ <Show when={canManage()}>
+ <Button
+ variant="outline"
+ size="sm"
+ disabled={!!props.busyId}
+ onClick={() => setConfirmCancel(true)}
+ >
+ {props.booking.status === 'pending' ? 'Decline' : 'Cancel'}
+ </Button>
+ </Show>
+ <Button
+ variant="ghost"
+ size="sm"
+ aria-expanded={expanded()}
+ aria-controls={`booking-details-${props.booking.id}`}
+ onClick={() => setExpanded(!expanded())}
+ >
+ Details
+ <CaretUp
+ class="size-3.5 transition-transform"
+ classList={{ 'rotate-180': expanded() }}
+ />
+ </Button>
+ </div>
+ </div>
+ <Show when={props.busyId === props.booking.id}>
+ <p role="status" class="mt-4 text-xs text-ink-muted">
+ Updating booking…
+ </p>
+ </Show>
+ <Show when={confirmCancel() && canManage()}>
+ <div class="mt-5 flex flex-wrap items-center gap-3 rounded-lg border border-edge-muted bg-surface-1 p-4">
+ <div class="min-w-48 flex-1 text-sm">
+ <p class="font-medium">
+ {props.booking.status === 'pending'
+ ? 'Decline this booking request?'
+ : 'Cancel this booking?'}
+ </p>
+ <p class="mt-1 text-ink-muted">
+ This releases the reserved time and cannot be undone.
+ </p>
+ </div>
+ <Button
+ variant="outline"
+ size="sm"
+ disabled={!!props.busyId}
+ onClick={() => setConfirmCancel(false)}
+ >
+ Keep booking
+ </Button>
+ <Button
+ variant="danger"
+ size="sm"
+ disabled={!!props.busyId}
+ onClick={() => props.onCancel(props.booking.id)}
+ >
+ {props.booking.status === 'pending'
+ ? 'Decline booking'
+ : 'Cancel booking'}
+ </Button>
+ </div>
+ </Show>
+ <Show when={expanded()}>
+ <div
+ id={`booking-details-${props.booking.id}`}
+ class="mt-5 grid gap-5 rounded-lg border border-edge-muted bg-surface-1 p-4 @min-[600px]:grid-cols-2"
+ >
+ <div class="text-sm">
+ <h4 class="font-medium">Guest’s time zone</h4>
+ <p class="mt-1 text-ink-muted">
+ {props.booking.timeZone.replaceAll('_', ' ')}
+ </p>
+ <p class="mt-1 text-xs text-ink-muted">
+ {new Date(props.booking.startsAt).toLocaleDateString(undefined, {
+ timeZone: props.booking.timeZone,
+ month: 'short',
+ day: 'numeric',
+ })}
+ {' · '}
+ {bookingTimeRange(props.booking, props.booking.timeZone)}
+ </p>
+ </div>
+ <Show when={props.booking.status === 'confirmed' && isPast()}>
+ <div class="max-w-56 text-sm">
+ <h4 class="mb-2 font-medium">Attendance</h4>
+ <SelectInput
+ label={`Attendance for ${props.booking.name}`}
+ value={props.booking.attendance ?? 'unknown'}
+ options={[
+ { value: 'unknown', label: 'Not recorded' },
+ { value: 'attended', label: 'Attended' },
+ { value: 'guestNoShow', label: 'Guest no-show' },
+ { value: 'hostNoShow', label: 'Host no-show' },
+ ]}
+ disabled={
+ (!props.canEdit &&
+ !props.booking.hosts.includes(props.currentUserId)) ||
+ !!props.busyId
+ }
+ onChange={(value) => {
+ if (
+ value === 'unknown' ||
+ value === 'attended' ||
+ value === 'guestNoShow' ||
+ value === 'hostNoShow'
+ )
+ props.onAttendance(props.booking.id, value);
+ }}
+ />
+ </div>
+ </Show>
+ <Show when={Object.keys(props.booking.answers).length}>
+ <dl class="space-y-4 @min-[600px]:col-span-2">
+ <For each={Object.entries(props.booking.answers)}>
+ {([id, answer]) => (
+ <div class="text-sm">
+ <dt class="font-medium">{answerLabel(id)}</dt>
+ <dd class="mt-1 whitespace-pre-wrap break-words text-ink-muted">
+ {answer || 'No response'}
+ </dd>
+ </div>
+ )}
+ </For>
+ </dl>
+ </Show>
+ <Show
+ when={
+ props.booking.status === 'failed' ||
+ props.booking.status === 'processing'
+ }
+ >
+ <p class="text-sm text-ink-muted @min-[600px]:col-span-2">
+ {props.booking.status === 'failed'
+ ? 'Calendar synchronization failed. This booking is not confirmed. Contact support before creating a replacement to avoid duplicate calendar events.'
+ : 'This booking is still being synchronized with the calendar. It will appear in Upcoming once it is confirmed.'}
+ </p>
+ </Show>
+ </div>
+ </Show>
+ </article>
+ );
+}
+
+export function BookingsPanel(props: BookingsPanelProps) {
+ const [tab, setTab] = createSignal<BookingTab>('Upcoming');
+ const [search, setSearch] = createSignal('');
+ const [eventId, setEventId] = createSignal('all');
+ const eventFilter = () => (eventId() === 'all' ? '' : eventId());
+ const [timeZone, setTimeZone] = createSignal(
+ Intl.DateTimeFormat().resolvedOptions().timeZone
+ );
+ const visible = () =>
+ filterBookings(
+ props.bookings,
+ { tab: tab(), search: search(), eventId: eventFilter() },
+ Date.now()
+ );
+ const tabs = (): BookingTab[] => [
+ 'Upcoming',
+ 'Unconfirmed',
+ 'Past',
+ 'Cancelled',
+ ...(props.bookings.some((booking) =>
+ ['failed', 'processing'].includes(booking.status)
+ ) || tab() === 'Needs attention'
+ ? (['Needs attention'] as const)
+ : []),
+ ];
+ const eventOptions = () => [
+ { value: 'all', label: 'All event types' },
+ ...Array.from(
+ new Map([
+ ...props.bookings.map((b) => [b.eventTypeId, b.title] as const),
+ ...props.events.map((e) => [e.id, e.title] as const),
+ ])
+ ).map(([value, label]) => ({ value, label })),
+ ];
+ return (
+ <div class="flex min-w-0 flex-col gap-5">
+ <div class="overflow-x-auto pb-1">
+ <TabsInset
+ aria-label="Booking status"
+ class="h-auto w-fit"
+ depth={1}
+ labelClass="h-9 gap-2 px-3 text-sm whitespace-nowrap"
+ list={tabs().map((value) => ({
+ value,
+ label: (
+ <>
+ {value}
+ <span class="rounded bg-ink/5 px-1.5 text-xs tabular-nums">
+ {
+ props.bookings.filter(
+ (booking) => bookingTab(booking, Date.now()) === value
+ ).length
+ }
+ </span>
+ </>
+ ),
+ }))}
+ value={tab()}
+ onChange={(value) => {
+ const selected = tabs().find((item) => item === value);
+ if (selected) setTab(selected);
+ }}
+ />
+ </div>
+ <div class="flex flex-wrap items-center gap-3">
+ <div class="relative min-w-48 flex-1">
+ <MagnifyingGlass class="pointer-events-none absolute top-3 left-3 size-4 text-ink-muted" />
+ <TextInput
+ aria-label="Search bookings"
+ placeholder="Search by name, email, or event…"
+ class="pl-9"
+ value={search()}
+ onInput={(e) => setSearch(e.currentTarget.value)}
+ />
+ </div>
+ <div class="w-48">
+ <SelectInput
+ label="Filter bookings by event type"
+ options={eventOptions()}
+ value={eventId()}
+ onChange={setEventId}
+ />
+ </div>
+ <div class="w-56">
+ <TimeZoneInput value={timeZone()} onChange={setTimeZone} />
+ </div>
+ </div>
+ <Show when={tab() === 'Needs attention'}>
+ <p class="rounded-lg border border-edge-muted bg-surface-1 p-4 text-sm text-ink-muted">
+ These bookings are awaiting calendar synchronization or need help.
+ They are kept separate from confirmed meetings.
+ </p>
+ </Show>
+ <div class="overflow-hidden rounded-xl border border-edge-muted divide-y divide-edge-muted">
+ <For
+ each={visible()}
+ fallback={
+ <div class="flex flex-col items-center gap-3 bg-panel px-6 py-16 text-center">
+ <div class="rounded-xl border border-edge-muted bg-surface-1 p-3">
+ <CalendarIcon class="size-6 text-ink-muted" />
+ </div>
+ <h3 class="font-semibold">
+ {search() || eventFilter()
+ ? 'No matching bookings'
+ : tab() === 'Needs attention'
+ ? 'No bookings need attention'
+ : `No ${tab().toLowerCase()} bookings`}
+ </h3>
+ <p class="max-w-sm text-sm text-ink-muted">
+ {search() || eventFilter()
+ ? 'Try another name, email, or event type.'
+ : tab() === 'Upcoming'
+ ? 'When someone books your event, you’ll see their details here.'
+ : tab() === 'Unconfirmed'
+ ? 'Booking requests that need your approval will appear here.'
+ : tab() === 'Past'
+ ? 'Your previous meetings will appear here after they end.'
+ : tab() === 'Cancelled'
+ ? 'Cancelled and declined bookings will appear here.'
+ : 'Your bookings are up to date.'}
+ </p>
+ <Show when={search() || eventFilter()}>
+ <Button
+ variant="outline"
+ onClick={() => {
+ setSearch('');
+ setEventId('all');
+ }}
+ >
+ Clear filters
+ </Button>
+ </Show>
+ </div>
+ }
+ >
+ {(booking) => (
+ <BookingRow
+ {...props}
+ booking={booking}
+ event={props.events.find((e) => e.id === booking.eventTypeId)}
+ timeZone={timeZone()}
+ />
+ )}
+ </For>
+ </div>
+ <p class="text-xs text-ink-muted">
+ {visible().length} {visible().length === 1 ? 'booking' : 'bookings'}
+ {' · '}Times shown in {timeZone().replaceAll('_', ' ')}
+ </p>
+ </div>
+ );
+}
diff --git a/apps/web/src/features/scheduling/components/event-editor.tsx b/apps/web/src/features/scheduling/components/event-editor.tsx
new file mode 100644
index 0000000000..e592771882
--- /dev/null
+++ b/apps/web/src/features/scheduling/components/event-editor.tsx
@@ -0,0 +1,606 @@
+import ArrowLeft from '@phosphor/arrow-left.svg';
+import CalendarIcon from '@phosphor/calendar-blank.svg';
+import CheckCircle from '@phosphor/check-circle.svg';
+import ClockIcon from '@phosphor/clock.svg';
+import GearIcon from '@phosphor/gear.svg';
+import Sliders from '@phosphor/sliders-horizontal.svg';
+import TextAlignLeft from '@phosphor/text-align-left.svg';
+import UsersIcon from '@phosphor/users.svg';
+import VideoCamera from '@phosphor/video-camera.svg';
+import { Button } from '@ui';
+import { createSignal, For, Index, Show } from 'solid-js';
+import { unwrap } from 'solid-js/store';
+import {
+ type AvailabilitySchedule,
+ type EventType,
+ type SchedulingMember,
+ slugify,
+ validateEvent,
+ WEEKDAYS,
+} from '../core/types';
+import { CheckField, Field, SelectInput, TextArea, TextInput } from './fields';
+
+export function EventEditor(props: {
+ event: EventType;
+ events: EventType[];
+ schedules: AvailabilitySchedule[];
+ members: SchedulingMember[];
+ team: boolean;
+ saving: boolean;
+ onSave: (event: EventType) => Promise<void>;
+ onCancel: () => void;
+}) {
+ const [draft, setDraft] = createSignal(structuredClone(unwrap(props.event)));
+ const [section, setSection] = createSignal('Basics');
+ const [error, setError] = createSignal('');
+ const update = <K extends keyof EventType>(key: K, value: EventType[K]) =>
+ setDraft((d) => ({ ...d, [key]: value }));
+ const save = async (e: SubmitEvent) => {
+ e.preventDefault();
+ const message = validateEvent(draft(), props.events);
+ if (message) {
+ setError(message);
+ return;
+ }
+ if (props.team && missingHosts().length) {
+ setSection('Hosts');
+ setError(
+ 'Remove former team members from the selected hosts before saving.'
+ );
+ return;
+ }
+ setError('');
+ try {
+ await props.onSave(draft());
+ } catch (e) {
+ setError(e instanceof Error ? e.message : 'Could not save this event.');
+ }
+ };
+ const missingHosts = () =>
+ draft().hosts.filter(
+ (id) => !props.members.some((member) => member.id === id)
+ );
+ const sections = () => [
+ {
+ label: 'Setup',
+ items: [
+ {
+ name: 'Basics',
+ icon: GearIcon,
+ description: 'Set the details people see on your booking page.',
+ },
+ {
+ name: 'Availability',
+ icon: CalendarIcon,
+ description: 'Choose when people can book this event.',
+ },
+ ...(props.team
+ ? [
+ {
+ name: 'Hosts',
+ icon: UsersIcon,
+ description: 'Choose the people who will host this event.',
+ },
+ ]
+ : []),
+ ],
+ },
+ {
+ label: 'Booking experience',
+ items: [
+ {
+ name: 'Booking form',
+ icon: TextAlignLeft,
+ description: 'Collect the information you need before a meeting.',
+ },
+ {
+ name: 'Confirmation',
+ icon: CheckCircle,
+ description: 'Choose how new bookings are accepted.',
+ },
+ ],
+ },
+ {
+ label: 'Policies',
+ items: [
+ {
+ name: 'Limits & buffers',
+ icon: Sliders,
+ description: 'Protect your time with notice, limits, and breaks.',
+ },
+ ],
+ },
+ ];
+ const currentSection = () =>
+ sections()
+ .flatMap((group) => group.items)
+ .find((item) => item.name === section());
+ return (
+ <form onSubmit={(e) => void save(e)} class="@container min-w-0">
+ <div class="grid min-w-0 gap-6 @min-[760px]:grid-cols-[180px_minmax(0,1fr)] @min-[1100px]:gap-10">
+ <aside class="min-w-0">
+ <Button variant="ghost" class="mb-5 -ml-2" onClick={props.onCancel}>
+ <ArrowLeft class="size-4" />
+ Event types
+ </Button>
+ <nav
+ aria-label="Event settings"
+ class="flex gap-5 overflow-x-auto pb-2 @min-[760px]:flex-col @min-[760px]:gap-6"
+ >
+ <For each={sections()}>
+ {(group) => (
+ <div class="shrink-0">
+ <h2 class="mb-2 px-3 text-xs font-medium text-ink-muted">
+ {group.label}
+ </h2>
+ <div class="flex gap-1 @min-[760px]:flex-col">
+ <For each={group.items}>
+ {(item) => (
+ <button
+ type="button"
+ aria-current={
+ section() === item.name ? 'page' : undefined
+ }
+ onClick={() => setSection(item.name)}
+ class="flex w-full items-center gap-2 rounded-lg px-3 py-2 text-left text-sm whitespace-nowrap text-ink-muted hover:bg-hover aria-[current=page]:bg-surface-2 aria-[current=page]:text-ink aria-[current=page]:font-medium focus-visible:outline-2 focus-visible:outline-ink"
+ >
+ <item.icon class="size-4" />
+ {item.name}
+ </button>
+ )}
+ </For>
+ </div>
+ </div>
+ )}
+ </For>
+ </nav>
+ </aside>
+ <div class="min-w-0">
+ <header class="mb-7 flex items-start justify-between gap-4">
+ <div class="min-w-0">
+ <h1 class="break-words text-2xl font-semibold tracking-tight">
+ {draft().title || 'New event type'}
+ </h1>
+ <p class="mt-1 text-sm text-ink-muted">
+ {draft().slug
+ ? `/${draft().slug}`
+ : 'Create a reusable booking link.'}
+ </p>
+ </div>
+ <Button type="submit" variant="strong" disabled={props.saving}>
+ {props.saving ? 'Saving…' : 'Save changes'}
+ </Button>
+ </header>
+ <div class="grid min-w-0 items-start gap-6 @min-[1100px]:grid-cols-[minmax(0,1fr)_240px]">
+ <section class="min-w-0 overflow-hidden rounded-xl border border-edge-muted bg-panel">
+ <div class="border-b border-edge-muted bg-surface-1 px-6 py-5">
+ <h2 class="font-semibold">{section()}</h2>
+ <p class="mt-1 text-sm text-ink-muted">
+ {currentSection()?.description}
+ </p>
+ </div>
+ <div class="flex flex-col gap-5 p-6">
+ <Show when={error()}>
+ <p role="alert" class="text-sm text-failure">
+ {error()}
+ </p>
+ </Show>
+ <Show when={section() === 'Basics'}>
+ <Field label="Title">
+ <TextInput
+ required
+ value={draft().title}
+ placeholder="30 minute meeting"
+ onInput={(e) => {
+ const title = e.currentTarget.value;
+ setDraft((d) => ({
+ ...d,
+ title,
+ slug:
+ d.slug === slugify(d.title)
+ ? slugify(title)
+ : d.slug,
+ }));
+ }}
+ />
+ </Field>
+ <Field
+ label="Link"
+ hint="A short, memorable name for your booking link."
+ >
+ <TextInput
+ required
+ value={draft().slug}
+ onInput={(e) => update('slug', e.currentTarget.value)}
+ />
+ </Field>
+ <Field label="Description">
+ <TextArea
+ value={draft().description}
+ placeholder="What should people know before booking?"
+ onInput={(e) =>
+ update('description', e.currentTarget.value)
+ }
+ />
+ </Field>
+ <Field label="Duration (minutes)" class="max-w-56">
+ <TextInput
+ type="number"
+ min="5"
+ max="480"
+ required
+ value={draft().durationMinutes}
+ onInput={(e) =>
+ update('durationMinutes', e.currentTarget.valueAsNumber)
+ }
+ />
+ </Field>
+ <CheckField
+ checked={draft().googleMeet}
+ onChange={(v) => update('googleMeet', v)}
+ label="Create a Google Meet link"
+ />
+ <Field
+ label={
+ draft().googleMeet
+ ? 'Additional location details'
+ : 'Location or meeting URL'
+ }
+ >
+ <TextInput
+ value={draft().location}
+ placeholder="Office address, phone number, or meeting URL"
+ onInput={(e) => update('location', e.currentTarget.value)}
+ />
+ </Field>
+ <CheckField
+ checked={draft().enabled}
+ onChange={(v) => update('enabled', v)}
+ label="Accept bookings"
+ />
+ </Show>
+ <Show when={section() === 'Availability'}>
+ <Field label="Availability schedule">
+ <SelectInput
+ label="Availability schedule"
+ value={draft().scheduleId}
+ options={props.schedules.map((s) => ({
+ value: s.id,
+ label: s.name,
+ }))}
+ onChange={(value) => update('scheduleId', value)}
+ />
+ </Field>
+ <Show
+ when={props.schedules.find(
+ (s) => s.id === draft().scheduleId
+ )}
+ >
+ {(schedule) => (
+ <div class="overflow-hidden rounded-lg border border-edge-muted">
+ <div class="border-b border-edge-muted bg-surface-2 px-4 py-3 text-sm font-medium">
+ Weekly hours{' '}
+ <span class="ml-2 font-normal text-ink-muted">
+ {schedule().timeZone.replaceAll('_', ' ')}
+ </span>
+ </div>
+ <dl class="divide-y divide-edge-muted">
+ <For each={schedule().weekly}>
+ {(day) => (
+ <div class="flex flex-wrap justify-between gap-2 px-4 py-3 text-sm">
+ <dt>{WEEKDAYS[day.day]}</dt>
+ <dd class="text-ink-muted">
+ {day.windows.length
+ ? day.windows
+ .map((w) => `${w.start} – ${w.end}`)
+ .join(', ')
+ : 'Unavailable'}
+ </dd>
+ </div>
+ )}
+ </For>
+ </dl>
+ </div>
+ )}
+ </Show>
+ <p class="text-sm text-ink-muted">
+ Busy events on each host’s connected calendar are excluded
+ automatically. Manage weekly hours and date overrides in
+ Availability.
+ </p>
+ </Show>
+ <Show when={section() === 'Hosts' && props.team}>
+ <Field label="Scheduling type">
+ <SelectInput
+ label="Scheduling type"
+ value={draft().mode}
+ options={[
+ {
+ value: 'collective',
+ label: 'Collective · all hosts attend',
+ },
+ {
+ value: 'roundRobin',
+ label: 'Round robin · one available host',
+ },
+ ]}
+ onChange={(value) =>
+ update(
+ 'mode',
+ value === 'roundRobin' ? 'roundRobin' : 'collective'
+ )
+ }
+ />
+ </Field>
+ <div class="flex flex-col gap-3">
+ <h3 class="text-sm font-semibold">Team hosts</h3>
+ <For each={props.members}>
+ {(member) => (
+ <div class="rounded-lg border border-edge-muted p-4">
+ <CheckField
+ checked={draft().hosts.includes(member.id)}
+ onChange={(checked) =>
+ update(
+ 'hosts',
+ checked
+ ? [...draft().hosts, member.id]
+ : draft().hosts.filter((h) => h !== member.id)
+ )
+ }
+ label={member.name || member.email}
+ />
+ <Show when={member.name}>
+ <p class="mt-1 ml-7 truncate text-xs text-ink-muted">
+ {member.email}
+ </p>
+ </Show>
+ </div>
+ )}
+ </For>
+ <For each={missingHosts()}>
+ {(id) => (
+ <div class="rounded-lg border border-warning/30 bg-warning-bg p-4">
+ <CheckField
+ checked={draft().hosts.includes(id)}
+ onChange={(checked) => {
+ if (!checked)
+ update(
+ 'hosts',
+ draft().hosts.filter((host) => host !== id)
+ );
+ }}
+ label="Former team member"
+ />
+ <p class="mt-2 text-xs text-ink-muted">
+ This selected host is no longer in the team. Uncheck
+ them before saving.
+ </p>
+ </div>
+ )}
+ </For>
+ </div>
+ <p class="text-xs text-ink-muted">
+ Hosts must be current members of this Macro team with a
+ connected calendar. Round robin assigns the available host
+ with the fewest bookings.
+ </p>
+ </Show>
+ <Show when={section() === 'Limits & buffers'}>
+ <div class="grid grid-cols-1 gap-5 @min-[900px]:grid-cols-2">
+ <For
+ each={[
+ {
+ key: 'beforeMinutes' as const,
+ label: 'Buffer before (minutes)',
+ max: 10080,
+ min: 0,
+ },
+ {
+ key: 'afterMinutes' as const,
+ label: 'Buffer after (minutes)',
+ max: 10080,
+ min: 0,
+ },
+ {
+ key: 'noticeMinutes' as const,
+ label: 'Minimum notice (minutes)',
+ max: 10080,
+ min: 0,
+ },
+ {
+ key: 'horizonDays' as const,
+ label: 'Booking window (days)',
+ max: 365,
+ min: 1,
+ },
+ {
+ key: 'intervalMinutes' as const,
+ label: 'Time-slot interval (minutes)',
+ max: 480,
+ min: 5,
+ },
+ ]}
+ >
+ {(field) => (
+ <Field label={field.label}>
+ <TextInput
+ type="number"
+ min={field.min}
+ max={field.max}
+ required
+ value={draft()[field.key]}
+ onInput={(e) =>
+ update(field.key, e.currentTarget.valueAsNumber)
+ }
+ />
+ </Field>
+ )}
+ </For>
+ <Field
+ label="Maximum bookings per day"
+ hint="Leave blank for no limit."
+ >
+ <TextInput
+ type="number"
+ min="1"
+ max="100"
+ value={draft().dailyLimit ?? ''}
+ onInput={(e) =>
+ update(
+ 'dailyLimit',
+ e.currentTarget.value === ''
+ ? null
+ : e.currentTarget.valueAsNumber
+ )
+ }
+ />
+ </Field>
+ </div>
+ </Show>
+ <Show when={section() === 'Booking form'}>
+ <p class="text-sm text-ink-muted">
+ Name and email are always required. Add questions to prepare
+ for the meeting.
+ </p>
+ <Index each={draft().questions}>
+ {(q) => (
+ <div class="flex flex-col gap-3 rounded-lg border border-edge-muted p-4">
+ <Field label="Question">
+ <TextInput
+ value={q().label}
+ onInput={(e) =>
+ update(
+ 'questions',
+ draft().questions.map((item) =>
+ item.id === q().id
+ ? { ...item, label: e.currentTarget.value }
+ : item
+ )
+ )
+ }
+ />
+ </Field>
+ <div class="flex items-center justify-between">
+ <CheckField
+ checked={q().required}
+ label="Required"
+ onChange={(required) =>
+ update(
+ 'questions',
+ draft().questions.map((item) =>
+ item.id === q().id
+ ? { ...item, required }
+ : item
+ )
+ )
+ }
+ />
+ <Button
+ variant="ghost"
+ onClick={() =>
+ update(
+ 'questions',
+ draft().questions.filter(
+ (item) => item.id !== q().id
+ )
+ )
+ }
+ >
+ Remove
+ </Button>
+ </div>
+ </div>
+ )}
+ </Index>
+ <Button
+ variant="outline"
+ onClick={() =>
+ update('questions', [
+ ...draft().questions,
+ { id: crypto.randomUUID(), label: '', required: false },
+ ])
+ }
+ >
+ Add a question
+ </Button>
+ </Show>
+ <Show when={section() === 'Confirmation'}>
+ <div class="rounded-lg border border-edge-muted p-4">
+ <p class="font-medium">Automatic confirmation</p>
+ <p class="mt-2 text-sm text-ink-muted">
+ Guests receive a calendar invitation as soon as they book
+ an available time.
+ </p>
+ <Show when={draft().requiresConfirmation}>
+ <Button
+ variant="outline"
+ onClick={() => update('requiresConfirmation', false)}
+ >
+ Enable automatic confirmation
+ </Button>
+ <p class="mt-2 text-sm text-ink-muted">
+ This link is paused until automatic confirmation is
+ enabled.
+ </p>
+ </Show>
+ </div>
+ </Show>
+ </div>
+ </section>
+ <aside class="hidden min-w-0 @min-[1100px]:block">
+ <p class="mb-3 text-xs font-medium text-ink-muted">
+ Booking preview
+ </p>
+ <div class="space-y-5 rounded-xl border border-edge-muted bg-panel p-5">
+ <div>
+ <h3 class="break-words text-lg font-semibold">
+ {draft().title || 'New event type'}
+ </h3>
+ <Show when={draft().description}>
+ <p class="mt-3 whitespace-pre-wrap break-words text-sm text-ink-muted">
+ {draft().description}
+ </p>
+ </Show>
+ </div>
+ <div class="space-y-3 text-sm text-ink-muted">
+ <p class="flex items-center gap-2">
+ <ClockIcon class="size-4" />
+ {draft().durationMinutes || 0} minutes
+ </p>
+ <Show when={draft().googleMeet}>
+ <p class="flex items-center gap-2">
+ <VideoCamera class="size-4" />
+ Google Meet
+ </p>
+ </Show>
+ <Show when={draft().location}>
+ <p class="break-words">{draft().location}</p>
+ </Show>
+ <Show when={props.team}>
+ <p class="flex items-center gap-2">
+ <UsersIcon class="size-4" />
+ {draft().mode === 'roundRobin'
+ ? 'Round robin'
+ : 'Collective'}
+ </p>
+ </Show>
+ <Show when={draft().requiresConfirmation}>
+ <p class="flex items-center gap-2">
+ <CheckCircle class="size-4" />
+ Confirmation required
+ </p>
+ </Show>
+ </div>
+ <div class="border-t border-edge-muted pt-4 text-xs text-ink-muted">
+ {draft().enabled
+ ? 'Accepting bookings'
+ : 'Booking link is paused'}
+ </div>
+ </div>
+ </aside>
+ </div>
+ </div>
+ </div>
+ </form>
+ );
+}
diff --git a/apps/web/src/features/scheduling/components/event-types-panel.tsx b/apps/web/src/features/scheduling/components/event-types-panel.tsx
new file mode 100644
index 0000000000..d510ae93ff
--- /dev/null
+++ b/apps/web/src/features/scheduling/components/event-types-panel.tsx
@@ -0,0 +1,193 @@
+import { DropdownMenu } from '@kobalte/core/dropdown-menu';
+import External from '@phosphor/arrow-square-out.svg';
+import Clock from '@phosphor/clock.svg';
+import Copy from '@phosphor/copy.svg';
+import Dots from '@phosphor/dots-three.svg';
+import Link from '@phosphor/link.svg';
+import { Button, ToggleSwitch } from '@ui';
+import { createSignal, For, Show } from 'solid-js';
+import type { EventType } from '../core/types';
+import { TextInput } from './fields';
+
+export function EventTypesPanel(props: {
+ events: EventType[];
+ canEdit: boolean;
+ saving: boolean;
+ onEdit: (event: EventType) => void;
+ onToggle: (event: EventType, enabled: boolean) => void;
+ onDuplicate: (event: EventType) => void;
+ onDelete: (event: EventType) => void;
+ onCopy: (event: EventType) => void;
+ link: (event: EventType) => string;
+}) {
+ const [search, setSearch] = createSignal('');
+ const [removing, setRemoving] = createSignal<string>();
+ const filtered = () =>
+ props.events.filter((e) =>
+ `${e.title} ${e.slug}`.toLowerCase().includes(search().toLowerCase())
+ );
+ return (
+ <div class="flex flex-col gap-5">
+ <div class="max-w-sm">
+ <TextInput
+ type="search"
+ aria-label="Search event types"
+ placeholder="Search event types…"
+ value={search()}
+ onInput={(e) => setSearch(e.currentTarget.value)}
+ />
+ </div>
+ <div class="overflow-hidden rounded-xl border border-edge-muted bg-panel">
+ <For
+ each={filtered()}
+ fallback={
+ <div class="flex flex-col items-center gap-3 px-6 py-16 text-center">
+ <Link class="size-7 text-ink-muted" />
+ <h2 class="font-semibold">
+ {search()
+ ? 'No matching event types'
+ : 'Create your first booking link'}
+ </h2>
+ <p class="max-w-sm text-sm text-ink-muted">
+ {search()
+ ? 'Try a different title or link.'
+ : 'Choose a duration and availability, then share your link.'}
+ </p>
+ </div>
+ }
+ >
+ {(event) => (
+ <article class="border-b border-edge-muted px-5 py-5 last:border-b-0">
+ <div class="flex flex-wrap items-center gap-x-6 gap-y-4">
+ <div class="min-w-48 flex-1">
+ <button
+ type="button"
+ disabled={!props.canEdit}
+ onClick={() => props.onEdit(event)}
+ class="max-w-full text-left"
+ >
+ <h2 class="truncate text-base font-semibold">
+ {event.title}
+ </h2>
+ </button>
+ <p class="mt-1 truncate text-xs text-ink-muted">
+ /{event.slug}
+ </p>
+ <Show when={event.description}>
+ <p class="mt-2 line-clamp-1 text-sm text-ink-muted">
+ {event.description}
+ </p>
+ </Show>
+ <div class="mt-3 flex flex-wrap items-center gap-2 text-xs text-ink-muted">
+ <span class="inline-flex items-center gap-1 rounded-md border border-edge-muted px-2 py-1">
+ <Clock class="size-3" />
+ {event.durationMinutes}m
+ </span>
+ <span class="rounded-md border border-edge-muted px-2 py-1">
+ {event.mode === 'roundRobin'
+ ? 'Round robin'
+ : event.mode === 'collective'
+ ? 'Collective'
+ : 'One-on-one'}
+ </span>
+ <Show when={!event.enabled}>
+ <span>Paused</span>
+ </Show>
+ <Show when={event.requiresConfirmation}>
+ <span>Requires confirmation</span>
+ </Show>
+ </div>
+ </div>
+ <div class="flex items-center gap-2">
+ <ToggleSwitch
+ checked={event.enabled}
+ disabled={!props.canEdit || props.saving}
+ label={
+ <span class="sr-only">
+ Accept bookings for {event.title}
+ </span>
+ }
+ controlClass="data-checked:bg-ink"
+ onChange={(v) => props.onToggle(event, v)}
+ />
+ <a
+ aria-label={`Preview ${event.title}`}
+ class="rounded-lg border border-edge-muted p-2 text-ink-muted hover:bg-hover"
+ href={props.link(event)}
+ target="_blank"
+ rel="noopener noreferrer"
+ >
+ <External class="size-4" />
+ </a>
+ <Button
+ variant="outline"
+ size="icon-md"
+ label={`Copy link for ${event.title}`}
+ onClick={() => props.onCopy(event)}
+ disabled={!event.enabled}
+ >
+ <Copy class="size-4" />
+ </Button>
+ <Show when={props.canEdit}>
+ <DropdownMenu>
+ <DropdownMenu.Trigger
+ as={Button}
+ variant="outline"
+ size="icon-md"
+ label={`Options for ${event.title}`}
+ >
+ <Dots class="size-5" />
+ </DropdownMenu.Trigger>
+ <DropdownMenu.Portal>
+ <DropdownMenu.Content class="z-action-menu min-w-40 rounded-lg border border-edge-muted bg-menu p-1 text-sm shadow-lg">
+ <DropdownMenu.Item
+ class="rounded px-3 py-2 outline-none data-highlighted:bg-hover"
+ onSelect={() => props.onEdit(event)}
+ >
+ Edit
+ </DropdownMenu.Item>
+ <DropdownMenu.Item
+ class="rounded px-3 py-2 outline-none data-highlighted:bg-hover"
+ onSelect={() => props.onDuplicate(event)}
+ >
+ Duplicate
+ </DropdownMenu.Item>
+ <DropdownMenu.Item
+ class="rounded px-3 py-2 text-failure outline-none data-highlighted:bg-hover"
+ onSelect={() => setRemoving(event.id)}
+ >
+ Delete
+ </DropdownMenu.Item>
+ </DropdownMenu.Content>
+ </DropdownMenu.Portal>
+ </DropdownMenu>
+ </Show>
+ </div>
+ </div>
+ <Show when={props.canEdit && removing() === event.id}>
+ <div class="mt-4 flex flex-wrap items-center gap-3 border-t border-edge-muted pt-4">
+ <p class="flex-1 text-sm">
+ Delete this event type? Existing bookings are kept.
+ </p>
+ <Button
+ variant="ghost"
+ onClick={() => setRemoving(undefined)}
+ >
+ Keep
+ </Button>
+ <Button
+ variant="outline"
+ disabled={props.saving}
+ onClick={() => props.onDelete(event)}
+ >
+ Delete event type
+ </Button>
+ </div>
+ </Show>
+ </article>
+ )}
+ </For>
+ </div>
+ </div>
+ );
+}
diff --git a/apps/web/src/features/scheduling/components/fields.tsx b/apps/web/src/features/scheduling/components/fields.tsx
new file mode 100644
index 0000000000..3d266d6058
--- /dev/null
+++ b/apps/web/src/features/scheduling/components/fields.tsx
@@ -0,0 +1,118 @@
+import { TimezoneSelect } from '@app/features/reminders/TimezoneSelect';
+import { Checkbox, cn, Select } from '@ui';
+import { type JSX, Show, splitProps } from 'solid-js';
+
+export function Field(props: {
+ label: string;
+ hint?: string;
+ children: JSX.Element;
+ class?: string;
+}) {
+ return (
+ <label
+ class={cn('flex min-w-0 flex-col gap-2 text-sm text-ink', props.class)}
+ >
+ <span class="font-medium">{props.label}</span>
+ {props.children}
+ <Show when={props.hint}>
+ <span class="text-xs leading-relaxed text-ink-muted">{props.hint}</span>
+ </Show>
+ </label>
+ );
+}
+export function TextInput(props: JSX.InputHTMLAttributes<HTMLInputElement>) {
+ const [local, rest] = splitProps(props, ['class']);
+ return (
+ <input
+ {...rest}
+ class={cn(
+ 'h-10 w-full min-w-0 rounded-lg border border-edge bg-surface-2 px-3 text-sm text-ink outline-none placeholder:text-ink-placeholder focus-visible:ring-2 focus-visible:ring-ink/20 disabled:opacity-50',
+ local.class
+ )}
+ />
+ );
+}
+export function TextArea(
+ props: JSX.TextareaHTMLAttributes<HTMLTextAreaElement>
+) {
+ const [local, rest] = splitProps(props, ['class']);
+ return (
+ <textarea
+ {...rest}
+ class={cn(
+ 'h-10 w-full min-w-0 rounded-lg border border-edge bg-surface-2 px-3 text-sm text-ink outline-none placeholder:text-ink-placeholder focus-visible:ring-2 focus-visible:ring-ink/20 disabled:opacity-50',
+ 'h-auto min-h-24 resize-y py-3',
+ local.class
+ )}
+ />
+ );
+}
+export function SelectInput(props: {
+ label: string;
+ value: string;
+ options: { value: string; label: string }[];
+ onChange: (value: string) => void;
+ disabled?: boolean;
+}) {
+ return (
+ <Select<{ value: string; label: string }>
+ options={props.options}
+ optionValue="value"
+ optionTextValue="label"
+ value={props.options.find((o) => o.value === props.value)}
+ onChange={(option) => option && props.onChange(option.value)}
+ disabled={props.disabled}
+ modal={false}
+ >
+ <Select.Trigger
+ aria-label={props.label}
+ class={
+ 'h-10 w-full min-w-0 rounded-lg border border-edge bg-surface-2 px-3 text-sm text-ink outline-none placeholder:text-ink-placeholder focus-visible:ring-2 focus-visible:ring-ink/20 disabled:opacity-50'
+ }
+ >
+ <Select.Value<{ value: string; label: string }>>
+ {(state) => state.selectedOption()?.label}
+ </Select.Value>
+ <Select.Icon />
+ </Select.Trigger>
+ <Select.Content>
+ <Select.Listbox />
+ </Select.Content>
+ </Select>
+ );
+}
+export function TimeZoneInput(props: {
+ value: string;
+ onChange: (zone: string) => void;
+ disabled?: boolean;
+}) {
+ return (
+ <fieldset disabled={props.disabled} class="min-w-0">
+ <TimezoneSelect
+ value={props.value}
+ onChange={props.onChange}
+ options={Intl.supportedValuesOf('timeZone').map((value) => ({
+ value,
+ label: value.replaceAll('_', ' '),
+ }))}
+ class="h-10 w-full rounded-lg border-edge bg-surface-2 px-3"
+ />
+ </fieldset>
+ );
+}
+export function CheckField(props: {
+ checked: boolean;
+ onChange: (checked: boolean) => void;
+ label: string;
+}) {
+ return (
+ <Checkbox
+ checked={props.checked}
+ onChange={props.onChange}
+ class="gap-3 text-sm"
+ >
+ <Checkbox.Control class="data-checked:bg-ink data-checked:border-ink text-panel" />
+ <Checkbox.Label>{props.label}</Checkbox.Label>
+ </Checkbox>
+ );
+}
diff --git a/apps/web/src/features/scheduling/components/insights-panel.tsx b/apps/web/src/features/scheduling/components/insights-panel.tsx
new file mode 100644
index 0000000000..4bab8d58fd
--- /dev/null
+++ b/apps/web/src/features/scheduling/components/insights-panel.tsx
@@ -0,0 +1,822 @@
+import DownloadIcon from '@phosphor/download-simple.svg';
+import InfoIcon from '@phosphor/info.svg';
+import { Button, Tooltip } from '@ui';
+import { createMemo, createSignal, For, type JSX, Show } from 'solid-js';
+import {
+ buildInsightPeriod,
+ type InsightDay,
+ type InsightMetric,
+ insightComparison,
+ insightPresetRange,
+ insightRangeError,
+ insightsCsv,
+ previousInsightRange,
+} from '../core/insights';
+import type { Booking, EventType, SchedulingMember } from '../core/types';
+import { Field, SelectInput, TextInput } from './fields';
+
+const SERIES: { key: InsightMetric; label: string; color: string }[] = [
+ { key: 'total', label: 'Scheduled', color: 'var(--color-purple)' },
+ { key: 'completed', label: 'Completed', color: 'var(--color-success)' },
+ { key: 'rescheduled', label: 'Rescheduled', color: 'var(--color-blue)' },
+ { key: 'cancelled', label: 'Cancelled', color: 'var(--color-failure)' },
+ {
+ key: 'hostNoShow',
+ label: 'No-show (host)',
+ color: 'var(--color-ink-muted)',
+ },
+ {
+ key: 'guestNoShow',
+ label: 'No-show (guest)',
+ color: 'var(--color-warning)',
+ },
+];
+
+function formatDate(date: string, long = false): string {
+ return new Intl.DateTimeFormat(undefined, {
+ timeZone: 'UTC',
+ month: 'short',
+ day: 'numeric',
+ ...(long ? { weekday: 'short' } : {}),
+ }).format(new Date(`${date}T12:00:00Z`));
+}
+
+function InsightSection(props: {
+ title: string;
+ description?: string;
+ actions?: JSX.Element;
+ children: JSX.Element;
+}) {
+ return (
+ <section class="min-w-0 overflow-hidden rounded-xl border border-edge-muted bg-panel">
+ <header class="flex flex-wrap items-center justify-between gap-3 border-b border-edge-muted bg-surface-1 px-5 py-4">
+ <div>
+ <h2 class="text-sm font-semibold">{props.title}</h2>
+ <Show when={props.description}>
+ <p class="mt-1 text-xs text-ink-muted">{props.description}</p>
+ </Show>
+ </div>
+ {props.actions}
+ </header>
+ {props.children}
+ </section>
+ );
+}
+
+function Metric(props: {
+ label: string;
+ definition: string;
+ value: number;
+ previous: number;
+ unit?: string;
+ lowerIsBetter?: boolean;
+}) {
+ const improved = () =>
+ props.value !== props.previous &&
+ (props.lowerIsBetter
+ ? props.value < props.previous
+ : props.value > props.previous);
+ return (
+ <div class="flex min-w-0 flex-col gap-2 p-5">
+ <div class="flex items-center gap-1.5 text-sm text-ink-muted">
+ <span>{props.label}</span>
+ <Tooltip label={props.definition}>
+ <button
+ type="button"
+ aria-label={`${props.label}: ${props.definition}`}
+ class="shrink-0 rounded focus-visible:outline-2 focus-visible:outline-ink"
+ >
+ <InfoIcon class="size-3.5" />
+ </button>
+ </Tooltip>
+ </div>
+ <p class="text-3xl font-semibold tracking-tight tabular-nums">
+ {Number.isInteger(props.value)
+ ? props.value.toLocaleString()
+ : props.value.toLocaleString(undefined, { maximumFractionDigits: 1 })}
+ <Show when={props.unit}>
+ <span class="ml-1 text-base font-normal text-ink-muted">
+ {props.unit}
+ </span>
+ </Show>
+ </p>
+ <div class="mt-2 flex flex-wrap items-center gap-2 text-xs text-ink-muted">
+ <span
+ class="rounded px-1.5 py-0.5 font-medium tabular-nums"
+ classList={{
+ 'bg-success-bg text-success-ink': improved(),
+ 'bg-surface-2 text-ink-muted': !improved(),
+ }}
+ >
+ {insightComparison(props.value, props.previous)}
+ </span>
+ <span>from last period</span>
+ </div>
+ </div>
+ );
+}
+
+function TrendChart(props: { days: InsightDay[] }) {
+ const [visible, setVisible] = createSignal<InsightMetric[]>(
+ SERIES.map((s) => s.key)
+ );
+ const [hovered, setHovered] = createSignal<number>();
+ const plotted = () => SERIES.filter((s) => visible().includes(s.key));
+ const maxValue = () =>
+ Math.max(
+ 4,
+ Math.ceil(
+ Math.max(
+ 0,
+ ...props.days.flatMap((d) => plotted().map((s) => d[s.key]))
+ ) / 4
+ ) * 4
+ );
+ const x = (index: number) =>
+ 48 + (index / Math.max(1, props.days.length - 1)) * 812;
+ const y = (count: number) => 246 - (count / maxValue()) * 210;
+ const activeDay = () =>
+ hovered() === undefined
+ ? undefined
+ : props.days[Math.min(hovered()!, props.days.length - 1)];
+ const labelIndices = () => [
+ ...new Set(
+ Array.from({ length: Math.min(7, props.days.length) }, (_, i) =>
+ Math.round(
+ (i / Math.max(1, Math.min(6, props.days.length - 1))) *
+ (props.days.length - 1)
+ )
+ )
+ ),
+ ];
+ return (
+ <InsightSection
+ title="Event trends"
+ actions={
+ <div class="flex flex-wrap gap-1.5" aria-label="Visible chart series">
+ <For each={SERIES}>
+ {(series) => (
+ <button
+ type="button"
+ aria-pressed={visible().includes(series.key)}
+ onClick={() =>
+ setVisible((current) =>
+ current.includes(series.key)
+ ? current.filter((key) => key !== series.key)
+ : [...current, series.key]
+ )
+ }
+ class="inline-flex items-center gap-1.5 rounded-md border border-edge-muted bg-panel px-2 py-1 text-xs text-ink-muted hover:bg-hover focus-visible:outline-2 focus-visible:outline-ink"
+ classList={{ 'opacity-40': !visible().includes(series.key) }}
+ >
+ <span
+ class="size-2 rounded-full"
+ style={{ background: series.color }}
+ />
+ {series.label}
+ </button>
+ )}
+ </For>
+ </div>
+ }
+ >
+ <div class="px-4 pb-4 pt-3 sm:px-6">
+ <div
+ class="relative rounded-md outline-none focus-visible:ring-2 focus-visible:ring-ink/20"
+ tabIndex={0}
+ role="group"
+ aria-label="Event trends chart. Use left and right arrow keys to explore dates."
+ onFocus={() => setHovered((value) => value ?? props.days.length - 1)}
+ onBlur={() => setHovered(undefined)}
+ onKeyDown={(event) => {
+ if (event.key !== 'ArrowLeft' && event.key !== 'ArrowRight') return;
+ event.preventDefault();
+ setHovered((index) =>
+ Math.max(
+ 0,
+ Math.min(
+ props.days.length - 1,
+ (index ?? props.days.length - 1) +
+ (event.key === 'ArrowRight' ? 1 : -1)
+ )
+ )
+ );
+ }}
+ onPointerMove={(event) => {
+ const rect = event.currentTarget.getBoundingClientRect();
+ const plotX = ((event.clientX - rect.left) / rect.width) * 900;
+ setHovered(
+ Math.max(
+ 0,
+ Math.min(
+ props.days.length - 1,
+ Math.round(((plotX - 48) / 812) * (props.days.length - 1))
+ )
+ )
+ );
+ }}
+ onPointerLeave={() => setHovered(undefined)}
+ >
+ <svg
+ viewBox="0 0 900 290"
+ class="block w-full"
+ role="img"
+ aria-label="Daily booking totals and outcomes"
+ >
+ <For each={[0, 1, 2, 3, 4]}>
+ {(step) => (
+ <g>
+ <line
+ x1="48"
+ x2="860"
+ y1={y((maxValue() / 4) * step)}
+ y2={y((maxValue() / 4) * step)}
+ stroke="var(--color-edge-muted)"
+ stroke-dasharray="3 3"
+ />
+ <text
+ x="36"
+ y={y((maxValue() / 4) * step) + 4}
+ text-anchor="end"
+ fill="var(--color-ink-muted)"
+ font-size="11"
+ >
+ {(maxValue() / 4) * step}
+ </text>
+ </g>
+ )}
+ </For>
+ <For each={plotted()}>
+ {(series) => (
+ <>
+ <polyline
+ points={props.days
+ .map((day, index) => `${x(index)},${y(day[series.key])}`)
+ .join(' ')}
+ fill="none"
+ stroke={series.color}
+ stroke-width="2"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+ />
+ <Show when={props.days.length <= 10}>
+ <For each={props.days}>
+ {(day, index) => (
+ <circle
+ cx={x(index())}
+ cy={y(day[series.key])}
+ r="3"
+ fill="var(--color-panel)"
+ stroke={series.color}
+ stroke-width="1.5"
+ />
+ )}
+ </For>
+ </Show>
+ </>
+ )}
+ </For>
+ <For each={labelIndices()}>
+ {(index) => (
+ <text
+ x={x(index)}
+ y="270"
+ text-anchor="middle"
+ fill="var(--color-ink-muted)"
+ font-size="11"
+ >
+ {formatDate(props.days[index].date)}
+ </text>
+ )}
+ </For>
+ <Show when={activeDay()}>
+ {(day) => (
+ <>
+ <line
+ x1={x(Math.min(hovered()!, props.days.length - 1))}
+ x2={x(Math.min(hovered()!, props.days.length - 1))}
+ y1="26"
+ y2="246"
+ stroke="var(--color-edge)"
+ />
+ <For each={plotted()}>
+ {(series) => (
+ <circle
+ cx={x(Math.min(hovered()!, props.days.length - 1))}
+ cy={y(day()[series.key])}
+ r="4"
+ fill={series.color}
+ stroke="var(--color-panel)"
+ stroke-width="2"
+ />
+ )}
+ </For>
+ </>
+ )}
+ </Show>
+ </svg>
+ <Show when={activeDay()}>
+ {(day) => (
+ <div
+ class="pointer-events-none absolute right-3 top-3 z-10 w-48 rounded-lg border border-edge-muted bg-panel p-3 text-xs shadow-lg"
+ role="status"
+ aria-live="polite"
+ >
+ <p class="mb-2 border-b border-edge-muted pb-2 font-semibold">
+ {formatDate(day().date, true)}
+ </p>
+ <For each={plotted()}>
+ {(series) => (
+ <div class="flex items-center gap-2 py-1">
+ <span
+ class="size-2 rounded-full"
+ style={{ background: series.color }}
+ />
+ <span class="flex-1 text-ink-muted">{series.label}</span>
+ <span class="tabular-nums">{day()[series.key]}</span>
+ </div>
+ )}
+ </For>
+ </div>
+ )}
+ </Show>
+ </div>
+ <p class="text-center text-xs text-ink-muted">Booking start date</p>
+ <details class="mt-4 text-xs text-ink-muted">
+ <summary class="w-fit rounded py-1 focus-visible:outline-2 focus-visible:outline-ink">
+ View daily data
+ </summary>
+ <div class="mt-2 max-h-60 overflow-auto rounded-lg border border-edge-muted">
+ <table class="w-full text-left tabular-nums">
+ <caption class="sr-only">Daily bookings and outcomes</caption>
+ <thead class="bg-surface-2">
+ <tr>
+ <th class="p-3">Date</th>
+ <For each={SERIES}>
+ {(series) => (
+ <th class="p-3 font-medium">{series.label}</th>
+ )}
+ </For>
+ </tr>
+ </thead>
+ <tbody>
+ <For each={props.days}>
+ {(day) => (
+ <tr class="border-t border-edge-muted">
+ <th class="whitespace-nowrap p-3 font-normal">
+ {formatDate(day.date)}
+ </th>
+ <For each={SERIES}>
+ {(series) => <td class="p-3">{day[series.key]}</td>}
+ </For>
+ </tr>
+ )}
+ </For>
+ </tbody>
+ </table>
+ </div>
+ </details>
+ </div>
+ </InsightSection>
+ );
+}
+
+function HourChart(props: { hours: number[] }) {
+ const max = () => Math.max(1, ...props.hours);
+ const hourLabel = (hour: number) =>
+ `${hour % 12 || 12}${hour < 12 ? 'am' : 'pm'}`;
+ return (
+ <InsightSection
+ title="Popular booking times"
+ description="When your meetings start"
+ >
+ <div class="px-5 pb-5 pt-8">
+ <div class="flex h-36 items-end gap-1 border-b border-edge-muted">
+ <For each={props.hours}>
+ {(count, hour) => (
+ <Tooltip
+ class="h-full min-w-0 flex-1 items-end"
+ label={`${hourLabel(hour())}: ${count} ${count === 1 ? 'booking' : 'bookings'}`}
+ >
+ <div class="flex h-full min-w-0 flex-1 items-end">
+ <div
+ tabIndex={0}
+ role="img"
+ aria-label={`${hourLabel(hour())}: ${count} bookings`}
+ class="w-full rounded-t-sm bg-ink/70 outline-none hover:bg-ink focus-visible:ring-2 focus-visible:ring-ink/30"
+ style={{
+ height: `${Math.max(count ? 3 : 0, (count / max()) * 100)}%`,
+ 'min-height': '2px',
+ }}
+ />
+ </div>
+ </Tooltip>
+ )}
+ </For>
+ </div>
+ <div class="mt-3 flex justify-between text-xs text-ink-muted">
+ <span>12am</span>
+ <span>6am</span>
+ <span>12pm</span>
+ <span>6pm</span>
+ <span>11pm</span>
+ </div>
+ </div>
+ </InsightSection>
+ );
+}
+
+function RankedList(props: {
+ title: string;
+ description: string;
+ rows: { id: string; name: string; count: number }[];
+ empty: string;
+}) {
+ const max = () => Math.max(1, ...props.rows.map((row) => row.count));
+ return (
+ <InsightSection title={props.title} description={props.description}>
+ <div class="flex flex-col gap-5 p-5">
+ <For
+ each={props.rows}
+ fallback={
+ <p class="py-8 text-center text-sm text-ink-muted">{props.empty}</p>
+ }
+ >
+ {(row) => (
+ <div class="flex flex-col gap-2">
+ <div class="flex items-center justify-between gap-3 text-sm">
+ <span class="truncate" title={row.name}>
+ {row.name}
+ </span>
+ <span class="text-ink-muted tabular-nums">{row.count}</span>
+ </div>
+ <div class="h-1.5 overflow-hidden rounded-full bg-surface-2">
+ <div
+ class="h-full rounded-full bg-ink/70"
+ style={{ width: `${(row.count / max()) * 100}%` }}
+ />
+ </div>
+ </div>
+ )}
+ </For>
+ </div>
+ </InsightSection>
+ );
+}
+
+export function InsightsPanel(props: {
+ bookings: Booking[];
+ events: EventType[];
+ members: SchedulingMember[];
+ loading: boolean;
+ error?: string;
+ from: string;
+ to: string;
+ timeZone: string;
+ onRangeChange: (from: string, to: string) => void;
+ onRetry: () => void;
+ scopeSelector?: JSX.Element;
+}) {
+ const [eventId, setEventId] = createSignal('all');
+ const [hostId, setHostId] = createSignal('all');
+ const [customOpen, setCustomOpen] = createSignal(false);
+ const [customFrom, setCustomFrom] = createSignal(props.from);
+ const [customTo, setCustomTo] = createSignal(props.to);
+ const [rangeError, setRangeError] = createSignal('');
+ const now = new Date();
+ const filtered = createMemo(() =>
+ props.bookings.filter(
+ (booking) =>
+ (eventId() === 'all' || booking.eventTypeId === eventId()) &&
+ (hostId() === 'all' || booking.hosts.includes(hostId()))
+ )
+ );
+ const current = createMemo(() =>
+ buildInsightPeriod(
+ filtered(),
+ { from: props.from, to: props.to },
+ props.timeZone,
+ now
+ )
+ );
+ const previous = createMemo(() =>
+ buildInsightPeriod(
+ filtered(),
+ previousInsightRange({ from: props.from, to: props.to }),
+ props.timeZone,
+ now
+ )
+ );
+ const eventOptions = createMemo(() => {
+ const items = new Map(props.events.map((event) => [event.id, event.title]));
+ for (const booking of props.bookings)
+ if (!items.has(booking.eventTypeId))
+ items.set(booking.eventTypeId, booking.title);
+ return [
+ { value: 'all', label: 'All event types' },
+ ...[...items].map(([value, label]) => ({ value, label })),
+ ];
+ });
+ const hostOptions = createMemo(() => {
+ const items = new Map(
+ props.members.map((member) => [member.id, member.name || member.email])
+ );
+ for (const booking of props.bookings)
+ for (const id of booking.hosts)
+ if (!items.has(id)) items.set(id, 'Former member');
+ return [
+ { value: 'all', label: 'All hosts' },
+ ...[...items].map(([value, label]) => ({ value, label })),
+ ];
+ });
+ const selectedRange = () => {
+ if (customOpen()) return 'custom';
+ return (
+ [7, 30, 90]
+ .find((days) => {
+ const range = insightPresetRange(days, props.timeZone, now);
+ return range.from === props.from && range.to === props.to;
+ })
+ ?.toString() ?? 'custom'
+ );
+ };
+ const changePreset = (value: string) => {
+ setRangeError('');
+ if (value === 'custom') {
+ setCustomFrom(props.from);
+ setCustomTo(props.to);
+ setCustomOpen(true);
+ return;
+ }
+ setCustomOpen(false);
+ const range = insightPresetRange(Number(value), props.timeZone, now);
+ props.onRangeChange(range.from, range.to);
+ };
+ const download = () => {
+ const csv = insightsCsv(
+ current().bookings,
+ new Map(
+ props.members.map((member) => [member.id, member.name || member.email])
+ )
+ );
+ const url = URL.createObjectURL(
+ new Blob(['\uFEFF', csv], { type: 'text/csv;charset=utf-8' })
+ );
+ const link = document.createElement('a');
+ link.href = url;
+ link.download = `booking-insights-${props.from}-${props.to}.csv`;
+ link.click();
+ setTimeout(() => URL.revokeObjectURL(url), 1000);
+ };
+ return (
+ <div class="flex flex-col gap-5" aria-busy={props.loading}>
+ <div class="flex flex-wrap items-center gap-2">
+ {props.scopeSelector}
+ <div class="w-44">
+ <SelectInput
+ label="Filter event types"
+ value={eventId()}
+ options={eventOptions()}
+ onChange={setEventId}
+ />
+ </div>
+ <div class="w-40">
+ <SelectInput
+ label="Filter hosts"
+ value={hostId()}
+ options={hostOptions()}
+ onChange={setHostId}
+ />
+ </div>
+ <div class="hidden flex-1 sm:block" />
+ <Button
+ variant="outline"
+ onClick={download}
+ disabled={
+ props.loading || !!props.error || !current().bookings.length
+ }
+ class="h-10"
+ >
+ <DownloadIcon class="size-4" />
+ Download
+ </Button>
+ <div class="w-40">
+ <SelectInput
+ label="Insights date range"
+ value={selectedRange()}
+ onChange={changePreset}
+ options={[
+ { value: '7', label: 'Last 7 days' },
+ { value: '30', label: 'Last 30 days' },
+ { value: '90', label: 'Last 90 days' },
+ { value: 'custom', label: 'Custom range' },
+ ]}
+ />
+ </div>
+ </div>
+ <Show when={customOpen()}>
+ <form
+ class="flex flex-wrap items-end gap-3 rounded-xl border border-edge-muted bg-surface-2 p-4"
+ onSubmit={(event) => {
+ event.preventDefault();
+ const error = insightRangeError({
+ from: customFrom(),
+ to: customTo(),
+ });
+ setRangeError(error ?? '');
+ if (!error) {
+ setCustomOpen(false);
+ props.onRangeChange(customFrom(), customTo());
+ }
+ }}
+ >
+ <Field label="Start date">
+ <TextInput
+ required
+ type="date"
+ value={customFrom()}
+ onInput={(event) => setCustomFrom(event.currentTarget.value)}
+ />
+ </Field>
+ <Field label="End date">
+ <TextInput
+ required
+ type="date"
+ value={customTo()}
+ min={customFrom()}
+ onInput={(event) => setCustomTo(event.currentTarget.value)}
+ />
+ </Field>
+ <Button type="submit" variant="strong" class="h-10">
+ Apply dates
+ </Button>
+ <Button
+ type="button"
+ variant="ghost"
+ class="h-10"
+ onClick={() => {
+ setCustomOpen(false);
+ setRangeError('');
+ }}
+ >
+ Cancel
+ </Button>
+ <Show when={rangeError()}>
+ <p role="alert" class="w-full text-sm text-failure">
+ {rangeError()}
+ </p>
+ </Show>
+ </form>
+ </Show>
+ <div class="flex flex-wrap items-center justify-between gap-2 text-xs text-ink-muted">
+ <p>
+ {formatDate(props.from)} – {formatDate(props.to)} ·{' '}
+ {props.timeZone.replaceAll('_', ' ')}
+ </p>
+ <Show when={eventId() !== 'all' || hostId() !== 'all'}>
+ <button
+ type="button"
+ class="underline underline-offset-2"
+ onClick={() => {
+ setEventId('all');
+ setHostId('all');
+ }}
+ >
+ Clear filters
+ </button>
+ </Show>
+ </div>
+ <Show when={props.error}>
+ <div
+ role="alert"
+ class="flex flex-wrap items-center justify-between gap-4 rounded-xl border border-edge-muted p-5"
+ >
+ <p class="text-sm">{props.error}</p>
+ <Button variant="outline" onClick={props.onRetry}>
+ Try again
+ </Button>
+ </div>
+ </Show>
+ <Show when={props.loading}>
+ <p role="status" class="text-sm text-ink-muted">
+ Loading booking insights…
+ </p>
+ </Show>
+ <Show when={!props.error}>
+ <div
+ class="flex flex-col gap-5"
+ classList={{ 'opacity-50': props.loading }}
+ >
+ <InsightSection title="Events">
+ <div class="grid grid-cols-1 divide-y divide-edge-muted @sm:grid-cols-2 @3xl:grid-cols-4 @3xl:divide-x @3xl:divide-y-0">
+ <Metric
+ label="Total events"
+ definition="Bookings starting in this period, including pending and cancelled bookings. Failed and processing requests are excluded."
+ value={current().counts.total}
+ previous={previous().counts.total}
+ />
+ <Metric
+ label="Events completed"
+ definition="Confirmed bookings that have ended, excluding marked no-shows. This does not imply attendance was recorded."
+ value={current().counts.completed}
+ previous={previous().counts.completed}
+ />
+ <Metric
+ label="Events rescheduled"
+ definition="Bookings starting in this period with at least one recorded reschedule. Each booking is counted once."
+ value={current().counts.rescheduled}
+ previous={previous().counts.rescheduled}
+ />
+ <Metric
+ label="Events cancelled"
+ definition="Cancelled bookings with a scheduled start in this period."
+ value={current().counts.cancelled}
+ previous={previous().counts.cancelled}
+ lowerIsBetter
+ />
+ </div>
+ </InsightSection>
+ <InsightSection title="Performance">
+ <div class="grid grid-cols-1 divide-y divide-edge-muted @sm:grid-cols-2 @3xl:grid-cols-4 @3xl:divide-x @3xl:divide-y-0">
+ <Metric
+ label="Hours in meetings"
+ definition="Total scheduled duration of completed events. Actual call duration is not tracked."
+ value={current().meetingMinutes / 60}
+ previous={previous().meetingMinutes / 60}
+ unit="hrs"
+ />
+ <Metric
+ label="Average duration"
+ definition="Average scheduled duration of confirmed bookings starting in this period, in minutes."
+ value={current().averageMinutes}
+ previous={previous().averageMinutes}
+ unit="min"
+ />
+ <Metric
+ label="No-show (host)"
+ definition="Bookings explicitly marked as a host no-show. Unrecorded attendance is not treated as a no-show."
+ value={current().counts.hostNoShow}
+ previous={previous().counts.hostNoShow}
+ lowerIsBetter
+ />
+ <Metric
+ label="No-show (guest)"
+ definition="Bookings explicitly marked as a guest no-show. Unrecorded attendance is not treated as a no-show."
+ value={current().counts.guestNoShow}
+ previous={previous().counts.guestNoShow}
+ lowerIsBetter
+ />
+ </div>
+ </InsightSection>
+ <Show when={!props.loading && !current().bookings.length}>
+ <p class="rounded-lg border border-dashed border-edge-muted px-5 py-4 text-sm text-ink-muted">
+ No bookings match this period and these filters. Try another date
+ range or clear the filters.
+ </p>
+ </Show>
+ <TrendChart days={current().days} />
+ <div class="grid grid-cols-1 items-start gap-5 @3xl:grid-cols-2">
+ <RankedList
+ title="Popular event types"
+ description="Number of bookings by event type"
+ rows={current().eventCounts.map((row) => ({
+ ...row,
+ name:
+ props.events.find((event) => event.id === row.id)?.title ??
+ row.name,
+ }))}
+ empty="No event types booked in this period."
+ />
+ <HourChart hours={current().hours} />
+ </div>
+ <Show when={hostOptions().length > 2}>
+ <RankedList
+ title="Bookings by host"
+ description="Collective bookings count toward each participating host"
+ rows={current().hostCounts.map((row) => ({
+ ...row,
+ name:
+ props.members.find((member) => member.id === row.id)?.name ??
+ 'Former member',
+ }))}
+ empty="No hosts with bookings in this period."
+ />
+ </Show>
+ <p class="text-xs leading-relaxed text-ink-muted">
+ Compared with{' '}
+ {formatDate(
+ previousInsightRange({ from: props.from, to: props.to }).from
+ )}{' '}
+ –{' '}
+ {formatDate(
+ previousInsightRange({ from: props.from, to: props.to }).to
+ )}
+ . All charts use the booking’s current start date in{' '}
+ {props.timeZone.replaceAll('_', ' ')}. A booking can be both
+ rescheduled and completed or cancelled.
+ </p>
+ </div>
+ </Show>
+ </div>
+ );
+}
diff --git a/apps/web/src/features/scheduling/components/reschedule-form.tsx b/apps/web/src/features/scheduling/components/reschedule-form.tsx
new file mode 100644
index 0000000000..3118ae0488
--- /dev/null
+++ b/apps/web/src/features/scheduling/components/reschedule-form.tsx
@@ -0,0 +1,131 @@
+import { Button } from '@ui';
+import { createSignal, Show } from 'solid-js';
+import { Field, SelectInput, TextInput } from './fields';
+
+export function RescheduleForm(props: {
+ timeZone: string;
+ load: (date: string) => Promise<{ startsAt: string; endsAt: string }[]>;
+ submit: (startsAt: string) => Promise<void>;
+ onCancel: () => void;
+}) {
+ const [date, setDate] = createSignal('');
+ const [slots, setSlots] = createSignal<
+ { startsAt: string; endsAt: string }[]
+ >([]);
+ const [selected, setSelected] = createSignal('');
+ const [loading, setLoading] = createSignal(false);
+ const [saving, setSaving] = createSignal(false);
+ const [error, setError] = createSignal('');
+ let request = 0;
+ const load = async (value: string) => {
+ const current = ++request;
+ setDate(value);
+ setSlots([]);
+ setSelected('');
+ setError('');
+ if (!value) {
+ setLoading(false);
+ return;
+ }
+ setLoading(true);
+ try {
+ const times = await props.load(value);
+ if (current === request) {
+ setSlots(times);
+ setSelected(times[0]?.startsAt ?? '');
+ }
+ } catch {
+ if (current === request) setError('Could not load replacement times.');
+ } finally {
+ if (current === request) setLoading(false);
+ }
+ };
+ const save = async (e: SubmitEvent) => {
+ e.preventDefault();
+ if (!selected() || saving()) return;
+ setError('');
+ setSaving(true);
+ try {
+ await props.submit(selected());
+ } catch {
+ setError(
+ 'Could not reschedule this meeting. Refresh before trying again.'
+ );
+ } finally {
+ setSaving(false);
+ }
+ };
+ return (
+ <form
+ class="mt-6 flex flex-col gap-4 border-t border-edge-muted pt-5"
+ onSubmit={(e) => void save(e)}
+ >
+ <h2 class="font-semibold">Choose a new time</h2>
+ <Field
+ label="Date"
+ hint={`Dates and times in ${props.timeZone.replaceAll('_', ' ')}`}
+ >
+ <TextInput
+ type="date"
+ disabled={saving()}
+ required
+ value={date()}
+ onInput={(e) => void load(e.currentTarget.value)}
+ />
+ </Field>
+ <Show
+ when={!loading()}
+ fallback={
+ <p role="status" class="text-sm text-ink-muted">
+ Checking availability…
+ </p>
+ }
+ >
+ <Show
+ when={slots().length}
+ fallback={
+ <Show when={date()}>
+ <p class="text-sm text-ink-muted">
+ No available times on this date.
+ </p>
+ </Show>
+ }
+ >
+ <Field label="Time">
+ <SelectInput
+ label="Time"
+ disabled={saving()}
+ value={selected()}
+ onChange={setSelected}
+ options={slots().map((s) => ({
+ value: s.startsAt,
+ label: new Date(s.startsAt).toLocaleTimeString([], {
+ timeZone: props.timeZone,
+ hour: 'numeric',
+ minute: '2-digit',
+ }),
+ }))}
+ />
+ </Field>
+ </Show>
+ </Show>
+ <Show when={error()}>
+ <p role="alert" class="text-sm text-failure">
+ {error()}
+ </p>
+ </Show>
+ <div class="flex gap-2">
+ <Button
+ variant="strong"
+ type="submit"
+ disabled={!selected() || saving() || loading()}
+ >
+ {saving() ? 'Rescheduling…' : 'Confirm new time'}
+ </Button>
+ <Button variant="ghost" disabled={saving()} onClick={props.onCancel}>
+ Keep current time
+ </Button>
+ </div>
+ </form>
+ );
+}
diff --git a/apps/web/src/features/scheduling/components/schedule-editor.tsx b/apps/web/src/features/scheduling/components/schedule-editor.tsx
new file mode 100644
index 0000000000..6df3f3e544
--- /dev/null
+++ b/apps/web/src/features/scheduling/components/schedule-editor.tsx
@@ -0,0 +1,412 @@
+import { Popover } from '@kobalte/core/popover';
+import ArrowLeft from '@phosphor/arrow-left.svg';
+import Copy from '@phosphor/copy.svg';
+import Plus from '@phosphor/plus.svg';
+import X from '@phosphor/x.svg';
+import { Button, ToggleSwitch } from '@ui';
+import { createSignal, For, Index, Show } from 'solid-js';
+import { unwrap } from 'solid-js/store';
+import {
+ type AvailabilitySchedule,
+ type TimeWindow,
+ validateSchedule,
+ WEEKDAYS,
+} from '../core/types';
+import { CheckField, Field, TextInput, TimeZoneInput } from './fields';
+
+function nextWindow(windows: TimeWindow[]): TimeWindow {
+ const last = windows.at(-1);
+ if (!last) return { start: '09:00', end: '17:00' };
+ const [h, m] = last.end.split(':').map(Number);
+ const end = Math.min(h * 60 + m + 60, 1439);
+ return {
+ start: last.end,
+ end: `${String(Math.floor(end / 60)).padStart(2, '0')}:${String(end % 60).padStart(2, '0')}`,
+ };
+}
+function Windows(props: {
+ label: string;
+ windows: TimeWindow[];
+ onChange: (windows: TimeWindow[]) => void;
+}) {
+ return (
+ <div class="flex min-w-0 flex-col gap-2">
+ <Index each={props.windows}>
+ {(window, i) => (
+ <div class="flex min-w-0 items-center gap-2">
+ <TextInput
+ type="time"
+ class="w-28 shrink-0 px-2 @min-[560px]:w-32"
+ aria-label={`${props.label} start ${i + 1}`}
+ required
+ value={window().start}
+ onInput={(e) =>
+ props.onChange(
+ props.windows.map((w, j) =>
+ j === i ? { ...w, start: e.currentTarget.value } : w
+ )
+ )
+ }
+ />
+ <span class="text-ink-muted">–</span>
+ <TextInput
+ type="time"
+ class="w-28 shrink-0 px-2 @min-[560px]:w-32"
+ aria-label={`${props.label} end ${i + 1}`}
+ required
+ value={window().end}
+ onInput={(e) =>
+ props.onChange(
+ props.windows.map((w, j) =>
+ j === i ? { ...w, end: e.currentTarget.value } : w
+ )
+ )
+ }
+ />
+ <Button
+ variant="ghost"
+ size="icon-md"
+ label={`Remove ${props.label} range ${i + 1}`}
+ onClick={() =>
+ props.onChange(props.windows.filter((_, j) => j !== i))
+ }
+ >
+ <X class="size-4" />
+ </Button>
+ </div>
+ )}
+ </Index>
+ </div>
+ );
+}
+function CopyHours(props: {
+ day: number;
+ disabled: boolean;
+ onCopy: (days: number[]) => void;
+}) {
+ const [open, setOpen] = createSignal(false);
+ const [days, setDays] = createSignal<number[]>([]);
+ return (
+ <Popover
+ open={open()}
+ onOpenChange={(value) => {
+ setOpen(value);
+ if (value) setDays([]);
+ }}
+ placement="bottom-end"
+ gutter={8}
+ >
+ <Popover.Trigger
+ as={Button}
+ variant="outline"
+ depth={2}
+ size="icon-md"
+ disabled={props.disabled}
+ label={`Copy ${WEEKDAYS[props.day]} hours`}
+ >
+ <Copy class="size-4" />
+ </Popover.Trigger>
+ <Popover.Portal>
+ <Popover.Content class="z-action-menu w-56 rounded-xl border border-edge bg-menu p-4 text-ink shadow-xl">
+ <h4 class="mb-3 text-sm font-semibold">Copy times to</h4>
+ <div class="flex flex-col gap-3">
+ <For
+ each={WEEKDAYS.map((name, day) => ({ name, day })).filter(
+ (d) => d.day !== props.day
+ )}
+ >
+ {(d) => (
+ <CheckField
+ label={d.name}
+ checked={days().includes(d.day)}
+ onChange={(checked) =>
+ setDays(
+ checked
+ ? [...days(), d.day]
+ : days().filter((day) => day !== d.day)
+ )
+ }
+ />
+ )}
+ </For>
+ </div>
+ <Button
+ class="mt-4 w-full"
+ variant="strong"
+ disabled={!days().length}
+ onClick={() => {
+ props.onCopy(days());
+ setOpen(false);
+ }}
+ >
+ Apply
+ </Button>
+ </Popover.Content>
+ </Popover.Portal>
+ </Popover>
+ );
+}
+export function ScheduleEditor(props: {
+ schedule: AvailabilitySchedule;
+ saving: boolean;
+ onSave: (s: AvailabilitySchedule) => Promise<void>;
+ onCancel: () => void;
+}) {
+ const [draft, setDraft] = createSignal(
+ structuredClone(unwrap(props.schedule))
+ );
+ const [error, setError] = createSignal('');
+ const remembered = new Map<number, TimeWindow[]>();
+ const setDay = (day: number, windows: TimeWindow[]) =>
+ setDraft((d) => ({
+ ...d,
+ weekly: d.weekly.map((w) => (w.day === day ? { ...w, windows } : w)),
+ }));
+ const save = async (e: SubmitEvent) => {
+ e.preventDefault();
+ const message = validateSchedule(draft());
+ setError(message ?? '');
+ if (message) return;
+ try {
+ await props.onSave(draft());
+ } catch (e) {
+ setError(e instanceof Error ? e.message : 'Could not save schedule.');
+ }
+ };
+ return (
+ <form class="flex flex-col gap-6" onSubmit={(e) => void save(e)}>
+ <h1 class="sr-only">Edit availability schedule</h1>
+ <div class="sticky top-0 z-10 flex items-center gap-3 bg-panel py-3">
+ <Button
+ variant="ghost"
+ size="icon-md"
+ label="Back to availability"
+ onClick={props.onCancel}
+ >
+ <ArrowLeft class="size-5" />
+ </Button>
+ <TextInput
+ aria-label="Schedule name"
+ required
+ value={draft().name}
+ class="h-10 flex-1 border-transparent bg-transparent px-2 text-xl font-semibold focus-visible:border-edge"
+ onInput={(e) =>
+ setDraft((d) => ({ ...d, name: e.currentTarget.value }))
+ }
+ />
+ <Button type="submit" variant="strong" disabled={props.saving}>
+ {props.saving ? 'Saving…' : 'Save schedule'}
+ </Button>
+ </div>
+ <Show when={error()}>
+ <p role="alert" class="text-sm text-failure">
+ {error()}
+ </p>
+ </Show>
+ <section class="overflow-hidden rounded-xl border border-edge-muted bg-surface-1">
+ <div class="border-b border-edge-muted bg-surface-2 px-5 py-5">
+ <h3 class="font-semibold">Weekly hours</h3>
+ <p class="mt-1 text-sm text-ink-muted">
+ Set the times you are available each day.
+ </p>
+ </div>
+ <div class="divide-y divide-edge-muted">
+ <Index each={draft().weekly}>
+ {(day) => (
+ <div class="grid grid-cols-[1fr_auto] items-start gap-x-3 gap-y-3 px-5 py-4 @min-[720px]:grid-cols-[160px_1fr_auto]">
+ <ToggleSwitch
+ size="md"
+ class="min-h-10 gap-3"
+ labelClass="text-sm font-medium"
+ controlClass="data-checked:bg-ink"
+ label={WEEKDAYS[day().day]}
+ checked={!!day().windows.length}
+ onChange={(checked) => {
+ if (!checked) remembered.set(day().day, day().windows);
+ setDay(
+ day().day,
+ checked
+ ? (remembered.get(day().day) ?? [
+ { start: '09:00', end: '17:00' },
+ ])
+ : []
+ );
+ }}
+ />
+ <div class="col-span-2 row-start-2 @min-[720px]:col-span-1 @min-[720px]:col-start-2 @min-[720px]:row-start-1">
+ <Show
+ when={day().windows.length}
+ fallback={
+ <p class="flex h-10 items-center text-sm text-ink-muted">
+ Unavailable
+ </p>
+ }
+ >
+ <Windows
+ label={WEEKDAYS[day().day]}
+ windows={day().windows}
+ onChange={(windows) => setDay(day().day, windows)}
+ />
+ </Show>
+ </div>
+ <div class="col-start-2 row-start-1 flex h-10 items-center gap-2 @min-[720px]:col-start-3">
+ <Button
+ variant="outline"
+ depth={2}
+ size="icon-md"
+ label={`Add ${WEEKDAYS[day().day]} hours`}
+ disabled={
+ day().windows.length >= 8 ||
+ day().windows.at(-1)?.end === '23:59'
+ }
+ onClick={() =>
+ setDay(day().day, [
+ ...day().windows,
+ nextWindow(day().windows),
+ ])
+ }
+ >
+ <Plus class="size-4" />
+ </Button>
+ <CopyHours
+ day={day().day}
+ disabled={!day().windows.length}
+ onCopy={(days) =>
+ setDraft((d) => ({
+ ...d,
+ weekly: d.weekly.map((w) =>
+ days.includes(w.day)
+ ? {
+ ...w,
+ windows: structuredClone(unwrap(day().windows)),
+ }
+ : w
+ ),
+ }))
+ }
+ />
+ </div>
+ </div>
+ )}
+ </Index>
+ </div>
+ </section>
+ <section class="overflow-hidden rounded-xl border border-edge-muted bg-surface-1">
+ <div class="flex flex-wrap items-center justify-between gap-4 bg-surface-2 px-5 py-5">
+ <div>
+ <h3 class="font-semibold">Date overrides</h3>
+ <p class="mt-1 text-sm text-ink-muted">
+ Adjust your hours for a specific date or take a day off.
+ </p>
+ </div>
+ <Button
+ variant="outline"
+ depth={2}
+ onClick={() =>
+ setDraft((d) => ({
+ ...d,
+ overrides: [...d.overrides, { date: '', windows: [] }],
+ }))
+ }
+ >
+ <Plus class="size-4" />
+ Add date override
+ </Button>
+ </div>
+ <Index each={draft().overrides}>
+ {(override, index) => (
+ <div class="flex flex-col gap-4 border-t border-edge-muted px-5 py-4">
+ <div class="flex items-center justify-between gap-3">
+ <TextInput
+ class="max-w-48"
+ type="date"
+ required
+ aria-label="Override date"
+ value={override().date}
+ onInput={(e) =>
+ setDraft((d) => ({
+ ...d,
+ overrides: d.overrides.map((o, i) =>
+ i === index ? { ...o, date: e.currentTarget.value } : o
+ ),
+ }))
+ }
+ />
+ <Button
+ variant="ghost"
+ size="icon-md"
+ label="Remove date override"
+ onClick={() =>
+ setDraft((d) => ({
+ ...d,
+ overrides: d.overrides.filter((_, i) => i !== index),
+ }))
+ }
+ >
+ <X class="size-4" />
+ </Button>
+ </div>
+ <div class="flex flex-wrap items-start justify-between gap-3">
+ <Show
+ when={override().windows.length}
+ fallback={
+ <p class="py-2 text-sm text-ink-muted">
+ Unavailable all day
+ </p>
+ }
+ >
+ <Windows
+ label={override().date || 'Override'}
+ windows={override().windows}
+ onChange={(windows) =>
+ setDraft((d) => ({
+ ...d,
+ overrides: d.overrides.map((o, i) =>
+ i === index ? { ...o, windows } : o
+ ),
+ }))
+ }
+ />
+ </Show>
+ <Button
+ variant="outline"
+ depth={2}
+ disabled={
+ override().windows.length >= 8 ||
+ override().windows.at(-1)?.end === '23:59'
+ }
+ onClick={() =>
+ setDraft((d) => ({
+ ...d,
+ overrides: d.overrides.map((o, i) =>
+ i === index
+ ? {
+ ...o,
+ windows: [...o.windows, nextWindow(o.windows)],
+ }
+ : o
+ ),
+ }))
+ }
+ >
+ <Plus class="size-4" />
+ Set hours
+ </Button>
+ </div>
+ </div>
+ )}
+ </Index>
+ </section>
+ <Field
+ label="Time zone"
+ class="max-w-sm"
+ hint="Your weekly hours and date overrides use this time zone."
+ >
+ <TimeZoneInput
+ value={draft().timeZone}
+ onChange={(timeZone) => setDraft((d) => ({ ...d, timeZone }))}
+ />
+ </Field>
+ </form>
+ );
+}
diff --git a/apps/web/src/features/scheduling/components/scheduling-workspace.tsx b/apps/web/src/features/scheduling/components/scheduling-workspace.tsx
new file mode 100644
index 0000000000..e7a741929e
--- /dev/null
+++ b/apps/web/src/features/scheduling/components/scheduling-workspace.tsx
@@ -0,0 +1,160 @@
+import { SettingsSheetContext } from '@app/features/settings/primitives';
+import External from '@phosphor/arrow-square-out.svg';
+import Calendar from '@phosphor/calendar-blank.svg';
+import Chart from '@phosphor/chart-line.svg';
+import Clock from '@phosphor/clock.svg';
+import Copy from '@phosphor/copy.svg';
+import Gear from '@phosphor/gear-six.svg';
+import Link from '@phosphor/link.svg';
+import Plugs from '@phosphor/plugs-connected.svg';
+import Users from '@phosphor/users.svg';
+import { cn } from '@ui';
+import { createEffect, For, type JSX, on, Show, useContext } from 'solid-js';
+
+export const schedulingPages = [
+ {
+ name: 'Event types',
+ description:
+ 'Configure different events for people to book on your calendar.',
+ icon: Link,
+ },
+ {
+ name: 'Bookings',
+ description: 'See upcoming and past events booked through your links.',
+ icon: Calendar,
+ },
+ {
+ name: 'Availability',
+ description: 'Set the times you are available for meetings.',
+ icon: Clock,
+ },
+ {
+ name: 'Teams',
+ description: 'Schedule together with your Macro team.',
+ icon: Users,
+ },
+ {
+ name: 'Insights',
+ description: 'View booking insights across your events.',
+ icon: Chart,
+ },
+ {
+ name: 'Booking page',
+ description: 'Make your public booking page feel like you.',
+ icon: Gear,
+ },
+];
+
+export function SchedulingWorkspace(props: {
+ page: string;
+ onNavigate: (page: string) => void;
+ title?: string;
+ description?: string;
+ actions?: JSX.Element;
+ children: JSX.Element;
+ publicLink?: string;
+ onCopy: () => void;
+ onConnections: () => void;
+ editor?: boolean;
+}) {
+ const inSheet = useContext(SettingsSheetContext);
+ let scrollBody: HTMLElement | undefined;
+ createEffect(
+ on([() => props.page, () => props.editor, () => props.title], () =>
+ scrollBody?.scrollTo({ top: 0 })
+ )
+ );
+ return (
+ <div class="@container/workspace h-full min-h-0 bg-page text-ink select-children">
+ <div class="flex h-full min-h-0 flex-col @min-[900px]/workspace:flex-row">
+ <Show when={!props.editor}>
+ <aside class="flex shrink-0 flex-col gap-5 px-3 py-4 @min-[900px]/workspace:w-52 @min-[900px]/workspace:py-7">
+ <div class="hidden items-center gap-2 px-3 @min-[900px]/workspace:flex">
+ <Calendar class="size-5" />
+ <span class="text-lg font-semibold tracking-tight">
+ Scheduling
+ </span>
+ </div>
+ <nav
+ aria-label="Scheduling"
+ class="flex gap-1 overflow-x-auto @min-[900px]/workspace:flex-col"
+ >
+ <For each={schedulingPages}>
+ {(item) => (
+ <button
+ type="button"
+ aria-current={props.page === item.name ? 'page' : undefined}
+ onClick={() => props.onNavigate(item.name)}
+ class={cn(
+ 'flex shrink-0 items-center gap-3 rounded-lg px-3 py-2.5 text-left text-sm transition-colors hover:bg-hover',
+ props.page === item.name
+ ? 'bg-active font-medium text-ink'
+ : 'text-ink-muted'
+ )}
+ >
+ <item.icon class="size-[18px] shrink-0" />
+ {item.name}
+ </button>
+ )}
+ </For>
+ </nav>
+ <div class="mt-auto hidden flex-col gap-1 @min-[900px]/workspace:flex">
+ <Show when={props.publicLink}>
+ <a
+ class="flex items-center gap-3 rounded-lg px-3 py-2 text-sm text-ink-muted hover:bg-hover"
+ href={props.publicLink}
+ target="_blank"
+ rel="noopener noreferrer"
+ >
+ <External class="size-[18px]" />
+ View public page
+ </a>
+ </Show>
+ <button
+ type="button"
+ disabled={!props.publicLink}
+ onClick={props.onCopy}
+ class="flex items-center gap-3 rounded-lg px-3 py-2 text-left text-sm text-ink-muted hover:bg-hover disabled:opacity-40"
+ >
+ <Copy class="size-[18px]" />
+ Copy public page link
+ </button>
+ <button
+ type="button"
+ onClick={props.onConnections}
+ class="flex items-center gap-3 rounded-lg px-3 py-2 text-left text-sm text-ink-muted hover:bg-hover"
+ >
+ <Plugs class="size-[18px]" />
+ Connected calendars
+ </button>
+ </div>
+ </aside>
+ </Show>
+ <main
+ ref={scrollBody}
+ data-drawer-scroll-body={inSheet ? true : undefined}
+ class="min-h-0 min-w-0 flex-1 overflow-y-auto rounded-t-2xl border border-edge-muted bg-panel [scrollbar-gutter:stable] [overflow-anchor:none] @min-[900px]/workspace:my-2 @min-[900px]/workspace:mr-2 @min-[900px]/workspace:rounded-2xl"
+ >
+ <div class="@container mx-auto flex w-full max-w-[1600px] flex-col gap-7 px-5 py-7 @min-[700px]/workspace:px-8 @min-[1200px]/workspace:px-10 @min-[1200px]/workspace:py-9">
+ <Show when={props.title}>
+ <header class="flex flex-wrap items-start justify-between gap-4">
+ <div>
+ <h1 class="text-xl font-semibold tracking-tight">
+ {props.title}
+ </h1>
+ <Show when={props.description}>
+ <p class="mt-1 text-sm text-ink-muted">
+ {props.description}
+ </p>
+ </Show>
+ </div>
+ {props.actions}
+ </header>
+ </Show>
+ {props.children}
+ </div>
+ </main>
+ </div>
+ </div>
+ );
+}
diff --git a/apps/web/src/features/scheduling/context/scheduling-context.tsx b/apps/web/src/features/scheduling/context/scheduling-context.tsx
new file mode 100644
index 0000000000..c63005c789
--- /dev/null
+++ b/apps/web/src/features/scheduling/context/scheduling-context.tsx
@@ -0,0 +1,54 @@
+import {
+ type Accessor,
+ createContext,
+ type ParentProps,
+ useContext,
+} from 'solid-js';
+import type {
+ Booking,
+ BookingAttendance,
+ SchedulingMember,
+ SchedulingProfile,
+ SchedulingScope,
+} from '../core/types';
+
+export type SchedulingSource = {
+ profile: Accessor<SchedulingProfile | undefined>;
+ bookings: Accessor<Booking[]>;
+ loading: Accessor<boolean>;
+ error: Accessor<string | undefined>;
+ saving: Accessor<boolean>;
+ save: (profile: SchedulingProfile) => Promise<void>;
+ approve: (id: string) => Promise<void>;
+ cancel: (id: string) => Promise<void>;
+ loadInsights: (from: string, to: string) => Promise<Booking[]>;
+ setAttendance: (id: string, attendance: BookingAttendance) => Promise<void>;
+ reload: () => void;
+};
+export type SchedulingCapabilities = {
+ scopes: Accessor<SchedulingScope[]>;
+ members: Accessor<SchedulingMember[]>;
+ userId: Accessor<string>;
+ createSource: (
+ scope: Accessor<SchedulingScope>,
+ range: Accessor<{ from: string; to: string }>
+ ) => SchedulingSource;
+ copyLink: (profile: SchedulingProfile, slug?: string) => Promise<void>;
+ link: (profile: SchedulingProfile, slug?: string) => string;
+ openConnections: () => void;
+ openTeamSettings: () => void;
+ manageBooking: (id: string) => Promise<void>;
+};
+const Context = createContext<SchedulingCapabilities>();
+export function SchedulingProvider(
+ props: ParentProps<{ value: SchedulingCapabilities }>
+) {
+ return (
+ <Context.Provider value={props.value}>{props.children}</Context.Provider>
+ );
+}
+export function useScheduling() {
+ const value = useContext(Context);
+ if (!value) throw new Error('SchedulingProvider is required');
+ return value;
+}
diff --git a/apps/web/src/features/scheduling/core/booking-error.ts b/apps/web/src/features/scheduling/core/booking-error.ts
new file mode 100644
index 0000000000..ccd5228e5e
--- /dev/null
+++ b/apps/web/src/features/scheduling/core/booking-error.ts
@@ -0,0 +1,2 @@
+/** A request rejected before a reservation was accepted. */
+export class BookingRejectedError extends Error {}
diff --git a/apps/web/src/features/scheduling/core/booking-list.test.ts b/apps/web/src/features/scheduling/core/booking-list.test.ts
new file mode 100644
index 0000000000..eedc5b66c7
--- /dev/null
+++ b/apps/web/src/features/scheduling/core/booking-list.test.ts
@@ -0,0 +1,95 @@
+import { describe, expect, it } from 'vitest';
+import { bookingTab, bookingTimeRange, filterBookings } from './booking-list';
+import type { Booking } from './types';
+
+const now = Date.parse('2026-09-18T16:00:00Z');
+function booking(overrides: Partial<Booking> = {}): Booking {
+ return {
+ id: 'meeting',
+ eventTypeId: 'intro',
+ title: 'Introduction',
+ name: 'Alex Morgan',
+ email: '[email protected]',
+ startsAt: '2026-09-18T17:00:00Z',
+ endsAt: '2026-09-18T17:30:00Z',
+ timeZone: 'America/New_York',
+ hosts: ['host'],
+ status: 'confirmed',
+ location: '',
+ answers: {},
+ attendance: 'unknown',
+ rescheduleCount: 0,
+ rescheduledAt: null,
+ ...overrides,
+ };
+}
+
+describe('booking management', () => {
+ it('keeps unconfirmed, failed, and processing requests out of upcoming meetings', () => {
+ const rows = [
+ booking(),
+ booking({ id: 'pending', status: 'pending' }),
+ booking({ id: 'failed', status: 'failed' }),
+ booking({ id: 'processing', status: 'processing' }),
+ booking({ id: 'cancelled', status: 'cancelled' }),
+ ];
+ const filter = { search: '', eventId: '' };
+ expect(
+ filterBookings(rows, { ...filter, tab: 'Upcoming' }, now).map((b) => b.id)
+ ).toEqual(['meeting']);
+ expect(
+ filterBookings(rows, { ...filter, tab: 'Needs attention' }, now).map(
+ (b) => b.id
+ )
+ ).toEqual(['failed', 'processing']);
+ expect(bookingTab(rows[1], now)).toBe('Unconfirmed');
+ expect(bookingTab(rows[4], now)).toBe('Cancelled');
+ });
+
+ it('keeps ongoing meetings upcoming and sorts past meetings newest first', () => {
+ expect(bookingTab(booking({ startsAt: '2026-09-18T15:30:00Z' }), now)).toBe(
+ 'Upcoming'
+ );
+ const ended = booking({
+ id: 'ended',
+ endsAt: '2026-09-18T16:00:00Z',
+ startsAt: '2026-09-18T15:30:00Z',
+ });
+ const earlier = booking({
+ id: 'earlier',
+ startsAt: '2026-09-17T17:00:00Z',
+ endsAt: '2026-09-17T17:30:00Z',
+ });
+ expect(
+ filterBookings(
+ [earlier, ended],
+ { tab: 'Past', search: '', eventId: '' },
+ now
+ ).map((b) => b.id)
+ ).toEqual(['ended', 'earlier']);
+ });
+
+ it('combines event and case-insensitive guest filters without mutating data', () => {
+ const rows = [booking(), booking({ id: 'other', eventTypeId: 'review' })];
+ expect(
+ filterBookings(
+ rows,
+ { tab: 'Upcoming', search: ' [email protected] ', eventId: 'intro' },
+ now
+ ).map((b) => b.id)
+ ).toEqual(['meeting']);
+ expect(rows.map((b) => b.id)).toEqual(['meeting', 'other']);
+ });
+
+ it('distinguishes repeated clock times across a daylight-saving transition', () => {
+ const range = bookingTimeRange(
+ booking({
+ startsAt: '2026-11-01T05:30:00Z',
+ endsAt: '2026-11-01T06:30:00Z',
+ }),
+ 'America/New_York'
+ );
+ expect(range).toContain('EDT');
+ expect(range).toContain('EST');
+ });
+});
diff --git a/apps/web/src/features/scheduling/core/booking-list.ts b/apps/web/src/features/scheduling/core/booking-list.ts
new file mode 100644
index 0000000000..c5fc257bfe
--- /dev/null
+++ b/apps/web/src/features/scheduling/core/booking-list.ts
@@ -0,0 +1,62 @@
+import type { Booking } from './types';
+
+export type BookingTab =
+ | 'Upcoming'
+ | 'Unconfirmed'
+ | 'Past'
+ | 'Cancelled'
+ | 'Needs attention';
+
+export function bookingTab(booking: Booking, now: number): BookingTab {
+ if (booking.status === 'pending') return 'Unconfirmed';
+ if (booking.status === 'cancelled') return 'Cancelled';
+ if (booking.status === 'failed' || booking.status === 'processing')
+ return 'Needs attention';
+ return new Date(booking.endsAt).getTime() <= now ? 'Past' : 'Upcoming';
+}
+
+export function filterBookings(
+ bookings: Booking[],
+ filters: { tab: BookingTab; search: string; eventId: string },
+ now: number
+): Booking[] {
+ const search = filters.search.trim().toLocaleLowerCase();
+ return bookings
+ .filter(
+ (booking) =>
+ bookingTab(booking, now) === filters.tab &&
+ (!filters.eventId || booking.eventTypeId === filters.eventId) &&
+ (!search ||
+ [booking.title, booking.name, booking.email].some((value) =>
+ value.toLocaleLowerCase().includes(search)
+ ))
+ )
+ .sort((a, b) => {
+ const difference =
+ new Date(a.startsAt).getTime() - new Date(b.startsAt).getTime();
+ return filters.tab === 'Past' || filters.tab === 'Cancelled'
+ ? -difference
+ : difference;
+ });
+}
+
+export function bookingTimeRange(booking: Booking, timeZone: string): string {
+ const start = new Date(booking.startsAt);
+ const end = new Date(booking.endsAt);
+ const day = new Intl.DateTimeFormat(undefined, { timeZone });
+ const differentDays = day.format(start) !== day.format(end);
+ const time = new Intl.DateTimeFormat(undefined, {
+ timeZone,
+ hour: 'numeric',
+ minute: '2-digit',
+ timeZoneName: 'short',
+ });
+ const endTime = new Intl.DateTimeFormat(undefined, {
+ timeZone,
+ hour: 'numeric',
+ minute: '2-digit',
+ timeZoneName: 'short',
+ ...(differentDays ? { month: 'short', day: 'numeric' } : {}),
+ });
+ return `${time.format(start)} – ${endTime.format(end)}`;
+}
diff --git a/apps/web/src/features/scheduling/core/insights.test.ts b/apps/web/src/features/scheduling/core/insights.test.ts
new file mode 100644
index 0000000000..4ba67ab8da
--- /dev/null
+++ b/apps/web/src/features/scheduling/core/insights.test.ts
@@ -0,0 +1,176 @@
+import { describe, expect, it } from 'vitest';
+import {
+ buildInsightPeriod,
+ insightComparison,
+ insightPresetRange,
+ insightRangeError,
+ insightsCsv,
+ insightsQueryRange,
+ previousInsightRange,
+ reportDate,
+} from './insights';
+import type { Booking } from './types';
+
+function booking(overrides: Partial<Booking> = {}): Booking {
+ return {
+ id: 'booking-1',
+ eventTypeId: 'event-1',
+ title: 'Discovery call',
+ name: 'Alex',
+ email: '[email protected]',
+ startsAt: '2026-09-18T13:00:00Z',
+ endsAt: '2026-09-18T13:30:00Z',
+ timeZone: 'America/New_York',
+ hosts: ['host-1'],
+ status: 'confirmed',
+ attendance: 'unknown',
+ rescheduleCount: 0,
+ rescheduledAt: null,
+ location: '',
+ answers: {},
+ ...overrides,
+ };
+}
+
+const range = { from: '2026-09-18', to: '2026-09-18' };
+const zone = 'America/New_York';
+const now = new Date('2026-09-19T12:00:00Z');
+
+describe('scheduling insights', () => {
+ it('uses inclusive calendar dates in the report zone and filters failed requests', () => {
+ const report = buildInsightPeriod(
+ [
+ booking({ id: 'before', startsAt: '2026-09-18T03:59:00Z' }),
+ booking({ id: 'first', startsAt: '2026-09-18T04:00:00Z' }),
+ booking({
+ id: 'last',
+ startsAt: '2026-09-19T03:59:00Z',
+ endsAt: '2026-09-19T04:29:00Z',
+ }),
+ booking({ id: 'after', startsAt: '2026-09-19T04:00:00Z' }),
+ booking({ id: 'failed', status: 'failed' }),
+ booking({ id: 'processing', status: 'processing' }),
+ ],
+ range,
+ zone,
+ now
+ );
+ expect(report.bookings.map((b) => b.id)).toEqual(['first', 'last']);
+ expect(report.counts.total).toBe(2);
+ expect(report.days).toHaveLength(1);
+ expect(report.days[0].date).toBe('2026-09-18');
+ expect(report.hours[0]).toBe(1);
+ expect(report.hours[23]).toBe(1);
+ });
+
+ it('counts reschedules and no-shows only from stored metadata', () => {
+ const report = buildInsightPeriod(
+ [
+ booking(),
+ booking({ id: 'rescheduled', rescheduleCount: 3 }),
+ booking({ id: 'cancelled', status: 'cancelled', rescheduleCount: 1 }),
+ booking({ id: 'pending', status: 'pending' }),
+ booking({ id: 'guest-absent', attendance: 'guestNoShow' }),
+ booking({ id: 'host-absent', attendance: 'hostNoShow' }),
+ ],
+ range,
+ zone,
+ now
+ );
+ expect(report.counts).toEqual({
+ total: 6,
+ completed: 2,
+ rescheduled: 2,
+ cancelled: 1,
+ guestNoShow: 1,
+ hostNoShow: 1,
+ });
+ expect(report.meetingMinutes).toBe(60);
+ expect(report.averageMinutes).toBe(30);
+ expect(report.eventCounts[0].count).toBe(6);
+ expect(report.hostCounts).toEqual([{ id: 'host-1', count: 6 }]);
+ });
+
+ it('does not classify future or pending bookings as completed and deduplicates hosts', () => {
+ const report = buildInsightPeriod(
+ [
+ booking({ hosts: ['host-1', 'host-1', 'host-2'] }),
+ booking({ id: 'future', endsAt: '2026-09-20T13:30:00Z' }),
+ booking({ id: 'pending', status: 'pending' }),
+ ],
+ range,
+ zone,
+ now
+ );
+ expect(report.counts.completed).toBe(1);
+ expect(report.hostCounts).toEqual([
+ { id: 'host-1', count: 3 },
+ { id: 'host-2', count: 1 },
+ ]);
+ });
+
+ it('builds equal-length previous periods across months and leap years', () => {
+ expect(
+ previousInsightRange({ from: '2024-03-01', to: '2024-03-07' })
+ ).toEqual({ from: '2024-02-23', to: '2024-02-29' });
+ expect(
+ insightPresetRange(7, zone, new Date('2026-09-19T02:00:00Z'))
+ ).toEqual({ from: '2026-09-12', to: '2026-09-18' });
+ expect(reportDate(new Date('2026-09-19T02:00:00Z'), zone)).toBe(
+ '2026-09-18'
+ );
+ });
+
+ it('creates UTC query bounds at real local midnights through spring and fall DST', () => {
+ expect(insightsQueryRange('2026-03-08', '2026-03-08', zone)).toEqual({
+ from: '2026-03-07T05:00:00.000Z',
+ to: '2026-03-09T04:00:00.000Z',
+ });
+ expect(insightsQueryRange('2026-11-01', '2026-11-01', zone)).toEqual({
+ from: '2026-10-31T04:00:00.000Z',
+ to: '2026-11-02T05:00:00.000Z',
+ });
+ });
+
+ it('rejects invalid, reversed and excessive date ranges', () => {
+ expect(
+ insightRangeError({ from: '2026-02-30', to: '2026-03-01' })
+ ).toBeDefined();
+ expect(
+ insightRangeError({ from: '2026-09-19', to: '2026-09-18' })
+ ).toContain('End date');
+ expect(
+ insightRangeError({ from: '2025-01-01', to: '2026-12-31' })
+ ).toContain('366');
+ expect(
+ insightRangeError({ from: '2024-01-01', to: '2024-12-31' })
+ ).toBeUndefined();
+ });
+
+ it('does not claim an infinite growth rate from an empty preceding period', () => {
+ expect(insightComparison(5, 0)).toBe('New');
+ expect(insightComparison(0, 0)).toBe('0%');
+ expect(insightComparison(0, 5)).toBe('-100%');
+ expect(insightComparison(20, 5)).toBe('+300%');
+ });
+
+ it('exports actual records, escapes commas/quotes/newlines and neutralizes formulas', () => {
+ const csv = insightsCsv(
+ [
+ booking({
+ title: 'Intro, "hello"',
+ name: '=HYPERLINK("bad")',
+ location: 'private not included',
+ hosts: ['host-1'],
+ rescheduleCount: 2,
+ }),
+ ],
+ new Map([['host-1', 'A\nB']])
+ );
+ expect(csv).toContain('"Intro, ""hello"""');
+ expect(csv).toContain('"\'=HYPERLINK(""bad"")"');
+ expect(csv).toContain('"A\nB"');
+ expect(csv).toContain('"unknown","2"');
+ expect(csv).not.toContain('private not included');
+ });
+});
diff --git a/apps/web/src/features/scheduling/core/insights.ts b/apps/web/src/features/scheduling/core/insights.ts
new file mode 100644
index 0000000000..ce02f8bc42
--- /dev/null
+++ b/apps/web/src/features/scheduling/core/insights.ts
@@ -0,0 +1,270 @@
+import { TZDateMini } from '@date-fns/tz';
+import type { Booking } from './types';
+
+export type InsightRange = { from: string; to: string };
+export type InsightMetric =
+ | 'total'
+ | 'completed'
+ | 'rescheduled'
+ | 'cancelled'
+ | 'guestNoShow'
+ | 'hostNoShow';
+export type InsightCounts = Record<InsightMetric, number>;
+export type InsightDay = InsightCounts & { date: string };
+export type InsightPeriod = {
+ bookings: Booking[];
+ counts: InsightCounts;
+ days: InsightDay[];
+ hours: number[];
+ meetingMinutes: number;
+ averageMinutes: number;
+ eventCounts: { id: string; name: string; count: number }[];
+ hostCounts: { id: string; count: number }[];
+};
+
+const DAY_MS = 86_400_000;
+
+function reportDateFormatter(timeZone: string): Intl.DateTimeFormat {
+ return new Intl.DateTimeFormat('en', {
+ timeZone,
+ year: 'numeric',
+ month: '2-digit',
+ day: '2-digit',
+ });
+}
+
+function formattedDate(date: Date, formatter: Intl.DateTimeFormat): string {
+ const parts = formatter.formatToParts(date);
+ const part = (type: string) => parts.find((p) => p.type === type)?.value;
+ return `${part('year')}-${part('month')}-${part('day')}`;
+}
+
+export function reportDate(date: Date, timeZone: string): string {
+ return formattedDate(date, reportDateFormatter(timeZone));
+}
+
+export function shiftReportDate(date: string, days: number): string {
+ return new Date(Date.parse(`${date}T00:00:00Z`) + days * DAY_MS)
+ .toISOString()
+ .slice(0, 10);
+}
+
+function dateStamp(date: string): number {
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(date)) return Number.NaN;
+ const value = Date.parse(`${date}T00:00:00Z`);
+ return Number.isFinite(value) &&
+ new Date(value).toISOString().slice(0, 10) === date
+ ? value
+ : Number.NaN;
+}
+
+export function insightRangeError(range: InsightRange): string | undefined {
+ const from = dateStamp(range.from);
+ const to = dateStamp(range.to);
+ if (!Number.isFinite(from) || !Number.isFinite(to))
+ return 'Choose a start and end date.';
+ if (from > to) return 'End date must be on or after start date.';
+ if ((to - from) / DAY_MS >= 366)
+ return 'Choose a date range of up to 366 days.';
+}
+
+export function previousInsightRange(range: InsightRange): InsightRange {
+ const days = (dateStamp(range.to) - dateStamp(range.from)) / DAY_MS + 1;
+ return {
+ from: shiftReportDate(range.from, -days),
+ to: shiftReportDate(range.from, -1),
+ };
+}
+
+/** UTC half-open bounds covering the report and its equally long preceding period. */
+export function insightsQueryRange(
+ from: string,
+ to: string,
+ timeZone: string
+): InsightRange {
+ const range = { from, to };
+ const error = insightRangeError(range);
+ if (error) throw new Error(error);
+ const midnight = (date: string) => {
+ const [year, month, day] = date.split('-').map(Number);
+ return new TZDateMini(
+ year,
+ month - 1,
+ day,
+ 0,
+ 0,
+ 0,
+ timeZone
+ ).toISOString();
+ };
+ return {
+ from: midnight(previousInsightRange(range).from),
+ to: midnight(shiftReportDate(to, 1)),
+ };
+}
+
+export function insightPresetRange(
+ days: number,
+ timeZone: string,
+ now = new Date()
+): InsightRange {
+ const to = reportDate(now, timeZone);
+ return { from: shiftReportDate(to, 1 - days), to };
+}
+
+function emptyCounts(): InsightCounts {
+ return {
+ total: 0,
+ completed: 0,
+ rescheduled: 0,
+ cancelled: 0,
+ guestNoShow: 0,
+ hostNoShow: 0,
+ };
+}
+
+function bookingCounts(booking: Booking, now: number): InsightCounts {
+ const guestNoShow = booking.attendance === 'guestNoShow';
+ const hostNoShow = booking.attendance === 'hostNoShow';
+ return {
+ total: 1,
+ completed: Number(
+ booking.status === 'confirmed' &&
+ Date.parse(booking.endsAt) <= now &&
+ !guestNoShow &&
+ !hostNoShow
+ ),
+ rescheduled: Number((booking.rescheduleCount ?? 0) > 0),
+ cancelled: Number(booking.status === 'cancelled'),
+ guestNoShow: Number(guestNoShow),
+ hostNoShow: Number(hostNoShow),
+ };
+}
+
+function addCounts(to: InsightCounts, from: InsightCounts): void {
+ for (const key of Object.keys(from) as InsightMetric[]) to[key] += from[key];
+}
+
+/** Groups by booking start date in the report's time zone, including both end dates. */
+export function buildInsightPeriod(
+ bookings: Booking[],
+ range: InsightRange,
+ timeZone: string,
+ now = new Date()
+): InsightPeriod {
+ const counts = emptyCounts();
+ const days: InsightDay[] = [];
+ if (!insightRangeError(range)) {
+ for (
+ let date = range.from;
+ date <= range.to;
+ date = shiftReportDate(date, 1)
+ )
+ days.push({ date, ...emptyCounts() });
+ }
+ const byDate = new Map(days.map((day) => [day.date, day]));
+ const hours = Array.from({ length: 24 }, () => 0);
+ const dateFormat = reportDateFormatter(timeZone);
+ const hourFormat = new Intl.DateTimeFormat('en', {
+ timeZone,
+ hour: 'numeric',
+ hourCycle: 'h23',
+ });
+ const visible: Booking[] = [];
+ const events = new Map<string, { id: string; name: string; count: number }>();
+ const hosts = new Map<string, number>();
+ let meetingMinutes = 0;
+ let durationMinutes = 0;
+ let durationCount = 0;
+ for (const booking of bookings) {
+ if (booking.status === 'failed' || booking.status === 'processing')
+ continue;
+ const start = new Date(booking.startsAt);
+ const end = new Date(booking.endsAt);
+ if (!Number.isFinite(start.getTime()) || !Number.isFinite(end.getTime()))
+ continue;
+ const day = byDate.get(formattedDate(start, dateFormat));
+ if (!day) continue;
+ visible.push(booking);
+ const values = bookingCounts(booking, now.getTime());
+ addCounts(counts, values);
+ addCounts(day, values);
+ hours[Number(hourFormat.format(start))] += 1;
+ const event = events.get(booking.eventTypeId) ?? {
+ id: booking.eventTypeId,
+ name: booking.title,
+ count: 0,
+ };
+ event.count += 1;
+ events.set(booking.eventTypeId, event);
+ for (const host of new Set(booking.hosts))
+ hosts.set(host, (hosts.get(host) ?? 0) + 1);
+ const minutes = Math.max(0, (end.getTime() - start.getTime()) / 60_000);
+ if (booking.status === 'confirmed') {
+ durationCount += 1;
+ durationMinutes += minutes;
+ }
+ if (values.completed) meetingMinutes += minutes;
+ }
+ return {
+ bookings: visible.sort((a, b) => a.startsAt.localeCompare(b.startsAt)),
+ counts,
+ days,
+ hours,
+ meetingMinutes,
+ averageMinutes: durationCount ? durationMinutes / durationCount : 0,
+ eventCounts: [...events.values()].sort((a, b) => b.count - a.count),
+ hostCounts: [...hosts]
+ .map(([id, count]) => ({ id, count }))
+ .sort((a, b) => b.count - a.count),
+ };
+}
+
+export function insightComparison(current: number, previous: number): string {
+ if (current === previous) return '0%';
+ if (previous === 0) return 'New';
+ const delta = Math.round(((current - previous) / previous) * 100);
+ return `${delta > 0 ? '+' : ''}${delta}%`;
+}
+
+function csvCell(value: string | number): string {
+ let text = String(value);
+ // Guest-supplied values must stay text when opened in spreadsheet software.
+ if (/^[\s]*[=+@-]|^[\t\r\n]/.test(text)) text = `'${text}`;
+ return `"${text.replaceAll('"', '""')}"`;
+}
+
+export function insightsCsv(
+ bookings: Booking[],
+ hostNames: ReadonlyMap<string, string> = new Map()
+): string {
+ const rows = [
+ [
+ 'Booking ID',
+ 'Event',
+ 'Guest name',
+ 'Guest email',
+ 'Start',
+ 'End',
+ 'Guest time zone',
+ 'Status',
+ 'Attendance',
+ 'Times rescheduled',
+ 'Hosts',
+ ],
+ ...bookings.map((b) => [
+ b.id,
+ b.title,
+ b.name,
+ b.email,
+ b.startsAt,
+ b.endsAt,
+ b.timeZone,
+ b.status,
+ b.attendance ?? 'unknown',
+ b.rescheduleCount ?? 0,
+ b.hosts.map((id) => hostNames.get(id) ?? id).join('; '),
+ ]),
+ ];
+ return rows.map((row) => row.map(csvCell).join(',')).join('\r\n');
+}
diff --git a/apps/web/src/features/scheduling/core/types.test.ts b/apps/web/src/features/scheduling/core/types.test.ts
new file mode 100644
index 0000000000..c76068b119
--- /dev/null
+++ b/apps/web/src/features/scheduling/core/types.test.ts
@@ -0,0 +1,34 @@
+import { describe, expect, it } from 'vitest';
+import {
+ newEventType,
+ newSchedule,
+ validateEvent,
+ validateSchedule,
+} from './types';
+
+describe('scheduling form validation', () => {
+ it('rejects overlapping hours and allows adjacent windows', () => {
+ const schedule = newSchedule('America/New_York');
+ schedule.weekly[1].windows = [
+ { start: '09:00', end: '12:00' },
+ { start: '11:00', end: '17:00' },
+ ];
+ expect(validateSchedule(schedule)).toContain('overlap');
+ schedule.weekly[1].windows[1].start = '12:00';
+ expect(validateSchedule(schedule)).toBeUndefined();
+ });
+ it('rejects duplicate links and fractional booking durations', () => {
+ const event = {
+ ...newEventType('schedule', ['host'], false),
+ title: 'Meeting',
+ slug: 'meeting',
+ };
+ expect(validateEvent(event, [{ ...event, id: 'another' }])).toContain(
+ 'link'
+ );
+ expect(validateEvent({ ...event, durationMinutes: 30.5 }, [])).toContain(
+ 'Duration'
+ );
+ expect(validateEvent(event, [])).toBeUndefined();
+ });
+});
diff --git a/apps/web/src/features/scheduling/core/types.ts b/apps/web/src/features/scheduling/core/types.ts
new file mode 100644
index 0000000000..2fda6356a9
--- /dev/null
+++ b/apps/web/src/features/scheduling/core/types.ts
@@ -0,0 +1,240 @@
+export type SchedulingMode = 'individual' | 'collective' | 'roundRobin';
+export type TimeWindow = { start: string; end: string };
+export type WeeklyDay = { day: number; windows: TimeWindow[] };
+export type DateOverride = { date: string; windows: TimeWindow[] };
+export type AvailabilitySchedule = {
+ id: string;
+ name: string;
+ timeZone: string;
+ weekly: WeeklyDay[];
+ overrides: DateOverride[];
+};
+export type BookingQuestion = { id: string; label: string; required: boolean };
+export type EventType = {
+ id: string;
+ title: string;
+ slug: string;
+ description: string;
+ durationMinutes: number;
+ location: string;
+ googleMeet: boolean;
+ enabled: boolean;
+ scheduleId: string;
+ mode: SchedulingMode;
+ hosts: string[];
+ beforeMinutes: number;
+ afterMinutes: number;
+ noticeMinutes: number;
+ horizonDays: number;
+ intervalMinutes: number;
+ dailyLimit: number | null;
+ requiresConfirmation: boolean;
+ questions: BookingQuestion[];
+};
+export type SchedulingProfile = {
+ id: string;
+ name: string;
+ description: string;
+ schedules: AvailabilitySchedule[];
+ defaultScheduleId?: string | null;
+ eventTypes: EventType[];
+ revision: number;
+};
+export type SchedulingScope = {
+ id: string;
+ name: string;
+ teamId?: string;
+ canEdit: boolean;
+};
+export type SchedulingMember = { id: string; name: string; email: string };
+export type BookingAttendance =
+ | 'unknown'
+ | 'attended'
+ | 'guestNoShow'
+ | 'hostNoShow';
+export type Booking = {
+ id: string;
+ eventTypeId: string;
+ title: string;
+ name: string;
+ email: string;
+ startsAt: string;
+ endsAt: string;
+ timeZone: string;
+ hosts: string[];
+ status: 'pending' | 'confirmed' | 'cancelled' | 'processing' | 'failed';
+ attendance: BookingAttendance;
+ rescheduleCount: number;
+ rescheduledAt: string | null;
+ location: string;
+ answers: Record<string, string>;
+ questionLabels?: Record<string, string>;
+};
+export type PublicEvent = Pick<
+ EventType,
+ | 'id'
+ | 'title'
+ | 'slug'
+ | 'description'
+ | 'durationMinutes'
+ | 'location'
+ | 'googleMeet'
+ | 'questions'
+ | 'requiresConfirmation'
+ | 'mode'
+>;
+export type PublicProfile = {
+ id: string;
+ name: string;
+ description: string;
+ eventTypes: PublicEvent[];
+};
+export type BookingRequest = {
+ startsAt: string;
+ name: string;
+ email: string;
+ timeZone: string;
+ answers: Record<string, string>;
+ requestId: string;
+};
+export type BookingReceipt = {
+ booking: Booking;
+ token: string;
+ scheduleTimeZone: string;
+};
+export const WEEKDAYS = [
+ 'Sunday',
+ 'Monday',
+ 'Tuesday',
+ 'Wednesday',
+ 'Thursday',
+ 'Friday',
+ 'Saturday',
+];
+
+export function newSchedule(timeZone: string): AvailabilitySchedule {
+ return {
+ id: crypto.randomUUID(),
+ name: 'Working hours',
+ timeZone,
+ weekly: WEEKDAYS.map((_, day) => ({
+ day,
+ windows: day > 0 && day < 6 ? [{ start: '09:00', end: '17:00' }] : [],
+ })),
+ overrides: [],
+ };
+}
+
+export function newEventType(
+ scheduleId: string,
+ hosts: string[],
+ team: boolean
+): EventType {
+ return {
+ id: crypto.randomUUID(),
+ title: '',
+ slug: '',
+ description: '',
+ durationMinutes: 30,
+ location: '',
+ googleMeet: true,
+ enabled: false,
+ scheduleId,
+ mode: team ? 'collective' : 'individual',
+ hosts,
+ beforeMinutes: 0,
+ afterMinutes: 0,
+ noticeMinutes: 120,
+ horizonDays: 60,
+ intervalMinutes: 30,
+ dailyLimit: null,
+ requiresConfirmation: false,
+ questions: [],
+ };
+}
+
+export function slugify(value: string): string {
+ return value
+ .toLowerCase()
+ .normalize('NFKD')
+ .replace(/[^a-z0-9]+/g, '-')
+ .replace(/^-|-$/g, '')
+ .slice(0, 80);
+}
+
+export function validateSchedule(
+ schedule: AvailabilitySchedule
+): string | undefined {
+ if (!schedule.name.trim()) return 'Give this schedule a name.';
+ try {
+ new Intl.DateTimeFormat('en', { timeZone: schedule.timeZone });
+ } catch {
+ return 'Choose a valid time zone.';
+ }
+ for (const day of [...schedule.weekly, ...schedule.overrides]) {
+ const windows = [...day.windows].sort((a, b) =>
+ a.start.localeCompare(b.start)
+ );
+ for (let i = 0; i < windows.length; i++) {
+ const w = windows[i];
+ if (
+ !/^([01]\d|2[0-3]):[0-5]\d$/.test(w.start) ||
+ !/^([01]\d|2[0-3]):[0-5]\d$/.test(w.end) ||
+ w.start >= w.end
+ )
+ return 'Each time range must end after it starts.';
+ if (i > 0 && windows[i - 1].end > w.start)
+ return 'Time ranges cannot overlap.';
+ }
+ }
+ if (
+ new Set(schedule.overrides.map((o) => o.date)).size !==
+ schedule.overrides.length
+ )
+ return 'Use only one override per date.';
+}
+
+export function validateEvent(
+ event: EventType,
+ others: EventType[]
+): string | undefined {
+ if (!event.title.trim()) return 'Give this event a title.';
+ if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(event.slug))
+ return 'Use lowercase letters, numbers, and hyphens for the link.';
+ if (others.some((e) => e.id !== event.id && e.slug === event.slug))
+ return 'Another event uses this link.';
+ if (!event.hosts.length) return 'Choose at least one host.';
+ if (
+ !Number.isInteger(event.durationMinutes) ||
+ event.durationMinutes < 5 ||
+ event.durationMinutes > 480
+ )
+ return 'Duration must be 5–480 minutes.';
+ if (
+ !Number.isInteger(event.intervalMinutes) ||
+ event.intervalMinutes < 5 ||
+ event.intervalMinutes > 480
+ )
+ return 'Time-slot interval must be 5–480 minutes.';
+ if (
+ event.horizonDays < 1 ||
+ event.horizonDays > 365 ||
+ !Number.isInteger(event.horizonDays)
+ )
+ return 'Booking window must be 1–365 days.';
+ if (
+ [event.beforeMinutes, event.afterMinutes, event.noticeMinutes].some(
+ (v) => !Number.isInteger(v) || v < 0 || v > 10080
+ )
+ )
+ return 'Buffers and notice must be between 0 and 10,080 minutes.';
+ if (
+ event.dailyLimit !== null &&
+ (!Number.isInteger(event.dailyLimit) ||
+ event.dailyLimit < 1 ||
+ event.dailyLimit > 100)
+ )
+ return 'Daily limit must be 1–100 bookings.';
+ if (event.questions.some((q) => !q.label.trim()))
+ return 'Every booking question needs a label.';
+}
diff --git a/apps/web/src/features/scheduling/primitives/booking-flow.test.ts b/apps/web/src/features/scheduling/primitives/booking-flow.test.ts
new file mode 100644
index 0000000000..d598f9c693
--- /dev/null
+++ b/apps/web/src/features/scheduling/primitives/booking-flow.test.ts
@@ -0,0 +1,114 @@
+import { createRoot } from 'solid-js';
+import { describe, expect, it, vi } from 'vitest';
+import { BookingRejectedError } from '../core/booking-error';
+import type { BookingReceipt } from '../core/types';
+import { type BookingSource, createBookingFlow } from './booking-flow';
+
+function deferred<T>() {
+ let resolve!: (value: T) => void;
+ const promise = new Promise<T>((done) => {
+ resolve = done;
+ });
+ return { promise, resolve };
+}
+describe('booking flow', () => {
+ it('ignores availability that arrives after a newer date was selected', async () => {
+ const first = deferred<{ startsAt: string; endsAt: string }[]>();
+ const second = deferred<{ startsAt: string; endsAt: string }[]>();
+ const source: BookingSource = {
+ slots: vi
+ .fn()
+ .mockReturnValueOnce(first.promise)
+ .mockReturnValueOnce(second.promise),
+ book: vi.fn(),
+ };
+ const flow = createRoot(() => createBookingFlow(source, 'profile'));
+ const old = flow.chooseDate('event', '2026-10-01', 'UTC');
+ const current = flow.chooseDate('event', '2026-10-02', 'UTC');
+ const slot = {
+ startsAt: '2026-10-02T09:00:00Z',
+ endsAt: '2026-10-02T09:30:00Z',
+ };
+ second.resolve([slot]);
+ await current;
+ first.resolve([]);
+ await old;
+ expect(flow.slots()).toEqual([slot]);
+ expect(flow.loading()).toBe(false);
+ });
+ it('prevents a second submission while the first is pending', async () => {
+ const pending = deferred<BookingReceipt>();
+ const book = vi.fn().mockReturnValue(pending.promise);
+ const flow = createRoot(() =>
+ createBookingFlow({ slots: vi.fn(), book }, 'profile')
+ );
+ flow.select('2026-10-02T09:00:00Z');
+ const details = {
+ name: 'Guest',
+ email: '[email protected]',
+ timeZone: 'UTC',
+ answers: {},
+ };
+ const first = flow.submit('event', details);
+ await flow.submit('event', details);
+ expect(book).toHaveBeenCalledTimes(1);
+ pending.resolve({ token: 'token' } as BookingReceipt);
+ await first;
+ });
+});
+
+it('holds the original request across navigation and edited details after an uncertain response', async () => {
+ const book = vi
+ .fn()
+ .mockRejectedValueOnce(new Error('lost response'))
+ .mockResolvedValueOnce({ token: 't' } as BookingReceipt);
+ const flow = createRoot(() =>
+ createBookingFlow({ slots: vi.fn(), book }, 'profile')
+ );
+ const start = '2026-10-02T09:00:00Z';
+ flow.select(start);
+ const details = {
+ name: 'Guest',
+ email: '[email protected]',
+ timeZone: 'UTC',
+ answers: {},
+ };
+ await flow.submit('event', details);
+ expect(flow.uncertain()).toBe(true);
+ flow.back();
+ flow.reset();
+ flow.select('2026-10-03T10:00:00Z');
+ await flow.chooseDate('another-event', '2026-10-03', 'UTC');
+ expect(flow.selected()).toBe(start);
+ await flow.submit('another-event', {
+ ...details,
+ email: '[email protected]',
+ });
+ expect(book.mock.calls[1]).toEqual(book.mock.calls[0]);
+ expect(flow.uncertain()).toBe(false);
+ expect(flow.receipt()?.token).toBe('t');
+});
+
+it('allows a different time after a definite rejection', async () => {
+ const flow = createRoot(() =>
+ createBookingFlow(
+ {
+ slots: vi.fn(),
+ book: vi.fn().mockRejectedValue(new BookingRejectedError('Time taken')),
+ },
+ 'profile'
+ )
+ );
+ flow.select('2026-10-02T09:00:00Z');
+ await flow.submit('event', {
+ name: 'Guest',
+ email: '[email protected]',
+ timeZone: 'UTC',
+ answers: {},
+ });
+ expect(flow.uncertain()).toBe(false);
+ flow.back();
+ expect(flow.selected()).toBeUndefined();
+ flow.select('2026-10-02T10:00:00Z');
+ expect(flow.selected()).toBe('2026-10-02T10:00:00Z');
+});
diff --git a/apps/web/src/features/scheduling/primitives/booking-flow.ts b/apps/web/src/features/scheduling/primitives/booking-flow.ts
new file mode 100644
index 0000000000..5877eb27e6
--- /dev/null
+++ b/apps/web/src/features/scheduling/primitives/booking-flow.ts
@@ -0,0 +1,116 @@
+import { createSignal } from 'solid-js';
+import { BookingRejectedError } from '../core/booking-error';
+import type { BookingReceipt, BookingRequest } from '../core/types';
+
+export type BookingSource = {
+ slots: (
+ profile: string,
+ event: string,
+ date: string,
+ timeZone: string
+ ) => Promise<{ startsAt: string; endsAt: string }[]>;
+ book: (
+ profile: string,
+ event: string,
+ request: BookingRequest
+ ) => Promise<BookingReceipt>;
+};
+
+export function createBookingFlow(source: BookingSource, profileId: string) {
+ const [slots, setSlots] = createSignal<
+ { startsAt: string; endsAt: string }[]
+ >([]);
+ const [loading, setLoading] = createSignal(false);
+ const [submitting, setSubmitting] = createSignal(false);
+ const [uncertain, setUncertain] = createSignal(false);
+ let attempted: { eventId: string; request: BookingRequest } | undefined;
+ const [error, setError] = createSignal('');
+ const [selected, setSelected] = createSignal<string>();
+ const [receipt, setReceipt] = createSignal<BookingReceipt>();
+ let generation = 0;
+ let requestId = crypto.randomUUID();
+ const chooseDate = async (
+ eventId: string,
+ date: string,
+ timeZone: string
+ ) => {
+ if (submitting() || uncertain()) return;
+ const current = ++generation;
+ setSelected(undefined);
+ setSlots([]);
+ setError('');
+ setLoading(true);
+ requestId = crypto.randomUUID();
+ try {
+ const next = await source.slots(profileId, eventId, date, timeZone);
+ if (current === generation) setSlots(next);
+ } catch {
+ if (current === generation)
+ setError(
+ 'Availability could not be loaded. Please retry or contact the host.'
+ );
+ } finally {
+ if (current === generation) setLoading(false);
+ }
+ };
+ const submit = async (
+ eventId: string,
+ details: Omit<BookingRequest, 'startsAt' | 'requestId'>
+ ) => {
+ const startsAt = selected();
+ if (!startsAt || submitting()) return;
+ setSubmitting(true);
+ setError('');
+ try {
+ attempted ??= { eventId, request: { ...details, startsAt, requestId } };
+ setReceipt(
+ await source.book(profileId, attempted.eventId, attempted.request)
+ );
+ setUncertain(false);
+ attempted = undefined;
+ } catch (error) {
+ if (error instanceof BookingRejectedError) {
+ attempted = undefined;
+ setUncertain(false);
+ setError(error.message);
+ } else {
+ setUncertain(true);
+ setError(
+ 'We could not verify the response. Your time may already be reserved. Retry this same request to check it; do not make another booking.'
+ );
+ }
+ } finally {
+ setSubmitting(false);
+ }
+ };
+ return {
+ reset: () => {
+ if (submitting() || uncertain()) return;
+ attempted = undefined;
+ generation++;
+ setSlots([]);
+ setSelected(undefined);
+ setReceipt(undefined);
+ setLoading(false);
+ setError('');
+ requestId = crypto.randomUUID();
+ },
+ slots,
+ loading,
+ submitting,
+ uncertain,
+ error,
+ selected,
+ receipt,
+ chooseDate,
+ submit,
+ select: (start: string) => {
+ if (submitting() || uncertain()) return;
+ setSelected(start);
+ requestId = crypto.randomUUID();
+ },
+ back: () => {
+ if (!submitting() && !uncertain()) setSelected(undefined);
+ },
+ };
+}
diff --git a/apps/web/src/features/scheduling/primitives/insights-state.test.ts b/apps/web/src/features/scheduling/primitives/insights-state.test.ts
new file mode 100644
index 0000000000..d26fad1a8b
--- /dev/null
+++ b/apps/web/src/features/scheduling/primitives/insights-state.test.ts
@@ -0,0 +1,135 @@
+import { createRoot } from 'solid-js';
+import { describe, expect, it, vi } from 'vitest';
+import type { Booking } from '../core/types';
+import { createInsightsState } from './insights-state';
+
+function deferred<T>() {
+ let resolve!: (value: T) => void;
+ let reject!: (reason: Error) => void;
+ const promise = new Promise<T>((done, fail) => {
+ resolve = done;
+ reject = fail;
+ });
+ return { promise, resolve, reject };
+}
+
+function booking(id: string): Booking {
+ return {
+ id,
+ eventTypeId: 'event',
+ title: 'Discovery call',
+ name: 'Guest',
+ email: '[email protected]',
+ startsAt: '2026-03-08T14:00:00Z',
+ endsAt: '2026-03-08T14:30:00Z',
+ timeZone: 'America/New_York',
+ hosts: ['host'],
+ status: 'confirmed',
+ location: '',
+ answers: {},
+ attendance: 'unknown',
+ rescheduleCount: 0,
+ rescheduledAt: null,
+ };
+}
+
+describe('insights loading state', () => {
+ it('keeps the newest report when an older date-range request resolves later', async () => {
+ const first = deferred<Booking[]>();
+ const second = deferred<Booking[]>();
+ const loadInsights = vi
+ .fn()
+ .mockReturnValueOnce(first.promise)
+ .mockReturnValueOnce(second.promise);
+ const owned = createRoot((dispose) => ({
+ dispose,
+ state: createInsightsState({ loadInsights }, 'America/New_York'),
+ }));
+ const oldRequest = owned.state.load('2026-03-01', '2026-03-07');
+ const currentRequest = owned.state.load('2026-03-08', '2026-03-14');
+ second.resolve([booking('current')]);
+ await currentRequest;
+ first.resolve([booking('old')]);
+ await oldRequest;
+ expect(owned.state.range()).toEqual({
+ from: '2026-03-08',
+ to: '2026-03-14',
+ });
+ expect(owned.state.bookings().map((item) => item.id)).toEqual(['current']);
+ expect(owned.state.loading()).toBe(false);
+ expect(owned.state.error()).toBeUndefined();
+ owned.dispose();
+ });
+
+ it('ignores obsolete failures while a newer request remains in flight', async () => {
+ const first = deferred<Booking[]>();
+ const second = deferred<Booking[]>();
+ const loadInsights = vi
+ .fn()
+ .mockReturnValueOnce(first.promise)
+ .mockReturnValueOnce(second.promise);
+ const owned = createRoot((dispose) => ({
+ dispose,
+ state: createInsightsState({ loadInsights }, 'UTC'),
+ }));
+ const oldRequest = owned.state.load('2026-03-01', '2026-03-07');
+ const currentRequest = owned.state.load('2026-03-08', '2026-03-14');
+ first.reject(new Error('Old request failed'));
+ await oldRequest;
+ expect(owned.state.error()).toBeUndefined();
+ expect(owned.state.loading()).toBe(true);
+ second.resolve([booking('current')]);
+ await currentRequest;
+ expect(owned.state.bookings()[0].id).toBe('current');
+ expect(owned.state.loading()).toBe(false);
+ owned.dispose();
+ });
+
+ it('clears stale data on failure and retries the same current and comparison bounds', async () => {
+ const retry = deferred<Booking[]>();
+ const loadInsights = vi
+ .fn()
+ .mockResolvedValueOnce([booking('old')])
+ .mockRejectedValueOnce(new Error('Network unavailable'))
+ .mockReturnValueOnce(retry.promise);
+ const owned = createRoot((dispose) => ({
+ dispose,
+ state: createInsightsState({ loadInsights }, 'America/New_York'),
+ }));
+ await owned.state.load('2026-03-01', '2026-03-01');
+ await owned.state.load('2026-03-08', '2026-03-08');
+ expect(owned.state.bookings()).toEqual([]);
+ expect(owned.state.error()).toBe('Network unavailable');
+ expect(owned.state.loading()).toBe(false);
+ const retryRequest = owned.state.load();
+ expect(owned.state.error()).toBeUndefined();
+ expect(owned.state.loading()).toBe(true);
+ expect(loadInsights.mock.calls[1]).toEqual([
+ '2026-03-07T05:00:00.000Z',
+ '2026-03-09T04:00:00.000Z',
+ ]);
+ expect(loadInsights.mock.calls[2]).toEqual(loadInsights.mock.calls[1]);
+ retry.resolve([booking('fresh')]);
+ await retryRequest;
+ expect(owned.state.bookings()[0].id).toBe('fresh');
+ expect(owned.state.loading()).toBe(false);
+ owned.dispose();
+ });
+
+ it('ignores a report resolving after the owner scope is unmounted', async () => {
+ const pending = deferred<Booking[]>();
+ const owned = createRoot((dispose) => ({
+ dispose,
+ state: createInsightsState(
+ { loadInsights: () => pending.promise },
+ 'UTC'
+ ),
+ }));
+ const request = owned.state.load('2026-03-08', '2026-03-08');
+ owned.dispose();
+ pending.resolve([booking('previous-owner')]);
+ await request;
+ expect(owned.state.bookings()).toEqual([]);
+ expect(owned.state.error()).toBeUndefined();
+ });
+});
diff --git a/apps/web/src/features/scheduling/primitives/insights-state.ts b/apps/web/src/features/scheduling/primitives/insights-state.ts
new file mode 100644
index 0000000000..e3bfb61f91
--- /dev/null
+++ b/apps/web/src/features/scheduling/primitives/insights-state.ts
@@ -0,0 +1,37 @@
+import { createSignal, onCleanup } from 'solid-js';
+import type { SchedulingSource } from '../context/scheduling-context';
+import { insightPresetRange, insightsQueryRange } from '../core/insights';
+import type { Booking } from '../core/types';
+
+/** Keep one report range coherent while filters load, ignoring superseded requests. */
+export function createInsightsState(
+ source: Pick<SchedulingSource, 'loadInsights'>,
+ timeZone: string
+) {
+ const [range, setRange] = createSignal(insightPresetRange(7, timeZone));
+ const [bookings, setBookings] = createSignal<Booking[]>([]);
+ const [loading, setLoading] = createSignal(true);
+ const [error, setError] = createSignal<string>();
+ let request = 0;
+ onCleanup(() => request++);
+ const load = async (from = range().from, to = range().to) => {
+ const id = ++request;
+ setRange({ from, to });
+ setLoading(true);
+ setError(undefined);
+ setBookings([]);
+ try {
+ const bounds = insightsQueryRange(from, to, timeZone);
+ const data = await source.loadInsights(bounds.from, bounds.to);
+ if (request === id) setBookings(data);
+ } catch (e) {
+ if (request === id)
+ setError(
+ e instanceof Error ? e.message : 'Could not load insights. Try again.'
+ );
+ } finally {
+ if (request === id) setLoading(false);
+ }
+ };
+ return { range, bookings, loading, error, load };
+}
diff --git a/apps/web/src/features/scheduling/public-booking.tsx b/apps/web/src/features/scheduling/public-booking.tsx
new file mode 100644
index 0000000000..97dbb07349
--- /dev/null
+++ b/apps/web/src/features/scheduling/public-booking.tsx
@@ -0,0 +1,106 @@
+import { useFeatureFlag } from '@app/lib/analytics/posthog';
+import { enableCalendarScheduling } from '@core/constant/featureFlags';
+import { useLocation, useNavigate, useParams } from '@solidjs/router';
+import { Show, Suspense } from 'solid-js';
+import {
+ createBookingReceiptSource,
+ createPublicBookingSource,
+ usePublicProfileQuery,
+} from './queries/public';
+import { BookingReceiptView } from './views/booking-receipt-view';
+import { PublicBookingView } from './views/public-booking-view';
+
+function BookingPageContent() {
+ const params = useParams<{ profile: string; slug?: string }>();
+ const navigate = useNavigate();
+ const profile = usePublicProfileQuery(() => params.profile);
+ const source = createPublicBookingSource();
+ return (
+ <Show
+ when={profile.isSuccess ? profile.data : undefined}
+ fallback={
+ <div class="p-12 text-center text-ink-muted">
+ {profile.isError
+ ? 'This booking page is unavailable.'
+ : 'Loading booking page…'}
+ </div>
+ }
+ >
+ {(p) => (
+ <Show
+ when={
+ !params.slug || p().eventTypes.some((e) => e.slug === params.slug)
+ }
+ fallback={
+ <p class="p-12 text-center">
+ This event is no longer accepting bookings.
+ </p>
+ }
+ >
+ <PublicBookingView
+ profile={p()}
+ event={p().eventTypes.find((e) => e.slug === params.slug)}
+ source={source}
+ onEvent={(slug) => navigate(`/book/${params.profile}/${slug}`)}
+ onReceipt={(r) => navigate(`/booking/${r.booking.id}#${r.token}`)}
+ />
+ </Show>
+ )}
+ </Show>
+ );
+}
+export function PublicBookingPage() {
+ const scheduling = useFeatureFlag(enableCalendarScheduling);
+ return (
+ <Show
+ when={scheduling().enabled}
+ fallback={
+ <p class="p-12 text-center text-ink-muted">
+ {scheduling().loading
+ ? 'Loading…'
+ : 'This booking page is unavailable.'}
+ </p>
+ }
+ >
+ <Suspense fallback={<p class="p-12">Loading…</p>}>
+ <BookingPageContent />
+ </Suspense>
+ </Show>
+ );
+}
+
+function ReceiptContent() {
+ const params = useParams<{ id: string }>();
+ const location = useLocation();
+ const token = () => location.hash.slice(1);
+ const source = createBookingReceiptSource(() => params.id, token);
+ return (
+ <BookingReceiptView
+ receipt={source.receipt.isSuccess ? source.receipt.data : undefined}
+ unavailable={source.receipt.isError}
+ cancel={source.cancel}
+ loadSlots={source.replacementSlots}
+ reschedule={source.reschedule}
+ />
+ );
+}
+
+export function BookingReceiptPage() {
+ const scheduling = useFeatureFlag(enableCalendarScheduling);
+ return (
+ <Show
+ when={scheduling().enabled}
+ fallback={
+ <p class="p-12 text-center text-ink-muted">
+ {scheduling().loading
+ ? 'Loading…'
+ : 'This booking page is unavailable.'}
+ </p>
+ }
+ >
+ <Suspense fallback={<p class="p-12">Loading…</p>}>
+ <ReceiptContent />
+ </Suspense>
+ </Show>
+ );
+}
diff --git a/apps/web/src/features/scheduling/queries/keys.ts b/apps/web/src/features/scheduling/queries/keys.ts
new file mode 100644
index 0000000000..99510b8694
--- /dev/null
+++ b/apps/web/src/features/scheduling/queries/keys.ts
@@ -0,0 +1,18 @@
+import { createQueryKeys } from '@lukemorales/query-key-factory';
+export const schedulingKeys = createQueryKeys('scheduling', {
+ replacementSlots: (id: string, token: string, date: string) => [
+ id,
+ token,
+ date,
+ ],
+ receipt: (id: string, token: string) => [id, token],
+ settings: (scope: string) => [scope],
+ bookings: (scope: string, from: string, to: string) => [scope, from, to],
+ insights: (scope: string, from: string, to: string) => [scope, from, to],
+ publicProfile: (id: string) => [id],
+ slots: (profile: string, event: string, date: string) => [
+ profile,
+ event,
+ date,
+ ],
+});
diff --git a/apps/web/src/features/scheduling/queries/public.test.ts b/apps/web/src/features/scheduling/queries/public.test.ts
new file mode 100644
index 0000000000..be45f05da9
--- /dev/null
+++ b/apps/web/src/features/scheduling/queries/public.test.ts
@@ -0,0 +1,83 @@
+import { schedulingClient } from '@service-email/scheduling';
+import { QueryClient, QueryClientProvider } from '@tanstack/solid-query';
+import { err, ok } from 'neverthrow';
+import { createComponent, createRoot } from 'solid-js';
+import { expect, it, vi } from 'vitest';
+import type { BookingReceipt } from '../core/types';
+import { createBookingFlow } from '../primitives/booking-flow';
+import { createPublicBookingSource } from './public';
+
+vi.mock('@service-email/scheduling', () => ({
+ schedulingClient: { book: vi.fn() },
+}));
+vi.mock('@queries/client', () => ({ queryClient: {} }));
+
+it('preserves uncertain retries but unlocks rejected requests', async () => {
+ const client = new QueryClient();
+ let flow!: ReturnType<typeof createBookingFlow>;
+ const dispose = createRoot((dispose) => {
+ createComponent(QueryClientProvider, {
+ client,
+ get children() {
+ flow = createBookingFlow(createPublicBookingSource(), 'profile');
+ return null;
+ },
+ });
+ return dispose;
+ });
+ try {
+ const receipt: BookingReceipt = {
+ token: 'private-token',
+ scheduleTimeZone: 'UTC',
+ booking: {
+ id: 'booking',
+ eventTypeId: 'event',
+ title: 'Meeting',
+ name: 'Guest',
+ email: '[email protected]',
+ startsAt: '2026-10-03T09:00:00Z',
+ endsAt: '2026-10-03T09:30:00Z',
+ timeZone: 'UTC',
+ hosts: ['host'],
+ status: 'confirmed',
+ attendance: 'unknown',
+ rescheduleCount: 0,
+ rescheduledAt: null,
+ location: '',
+ answers: {},
+ },
+ };
+ const book = vi.mocked(schedulingClient.book);
+ book
+ .mockResolvedValueOnce(ok(JSON.parse('{}')))
+ .mockResolvedValueOnce(ok(receipt));
+ flow.select(receipt.booking.startsAt);
+ const details = {
+ name: 'Guest',
+ email: '[email protected]',
+ timeZone: 'UTC',
+ answers: {},
+ };
+ await flow.submit('event', details);
+ expect(flow.uncertain()).toBe(true);
+ expect(flow.receipt()).toBeUndefined();
+ await flow.submit('event', details);
+ expect(book.mock.calls[1]).toEqual(book.mock.calls[0]);
+ expect(flow.receipt()).toEqual(receipt);
+ expect(flow.uncertain()).toBe(false);
+ for (const status of [413, 422]) {
+ flow.reset();
+ flow.select(receipt.booking.startsAt);
+ book.mockResolvedValueOnce(
+ err([{ code: 'HTTP_ERROR', message: `HTTP error! status: ${status}` }])
+ );
+ await flow.submit('event', details);
+ expect(flow.uncertain()).toBe(false);
+ flow.back();
+ expect(flow.selected()).toBeUndefined();
+ }
+ } finally {
+ dispose();
+ client.clear();
+ }
+});
diff --git a/apps/web/src/features/scheduling/queries/public.ts b/apps/web/src/features/scheduling/queries/public.ts
new file mode 100644
index 0000000000..148ef60362
--- /dev/null
+++ b/apps/web/src/features/scheduling/queries/public.ts
@@ -0,0 +1,142 @@
+import { ThrownResultError, throwOnErr } from '@core/util/result';
+import { queryClient } from '@queries/client';
+import { schedulingClient } from '@service-email/scheduling';
+import { useMutation, useQuery } from '@tanstack/solid-query';
+import type { Accessor } from 'solid-js';
+import { BookingRejectedError } from '../core/booking-error';
+import type { BookingReceipt, BookingRequest } from '../core/types';
+import { schedulingKeys } from './keys';
+
+function validateReceipt(receipt: BookingReceipt): BookingReceipt {
+ if (
+ !receipt ||
+ typeof receipt.booking?.id !== 'string' ||
+ !receipt.booking.id ||
+ typeof receipt.token !== 'string' ||
+ !receipt.token ||
+ typeof receipt.scheduleTimeZone !== 'string' ||
+ !receipt.scheduleTimeZone
+ ) {
+ throw new Error(
+ 'The booking response is incomplete. Retry the original request.'
+ );
+ }
+ return receipt;
+}
+
+export function usePublicProfileQuery(id: Accessor<string>) {
+ return useQuery(() => ({
+ queryKey: schedulingKeys.publicProfile(id()).queryKey,
+ queryFn: async () =>
+ (await throwOnErr(() => schedulingClient.profile(id()))).profile,
+ retry: false,
+ }));
+}
+
+export function createPublicBookingSource() {
+ const book = useMutation(() => ({
+ retry: false,
+ mutationFn: async (args: {
+ profile: string;
+ event: string;
+ request: BookingRequest;
+ }) => {
+ try {
+ return validateReceipt(
+ await throwOnErr(() =>
+ schedulingClient.book(args.profile, args.event, args.request)
+ )
+ );
+ } catch (error) {
+ if (
+ error instanceof ThrownResultError &&
+ error.errors.length > 0 &&
+ error.errors.every(
+ (e) =>
+ ['CONFLICT', 'NOT_FOUND', 'UNAUTHORIZED', 'FORBIDDEN'].includes(
+ e.code
+ ) ||
+ (e.code === 'HTTP_ERROR' &&
+ /status: (400|413|422|429)$/.test(e.message ?? ''))
+ )
+ ) {
+ throw new BookingRejectedError(
+ 'The request was not accepted. Check your details and refresh availability before trying again.'
+ );
+ }
+ throw error;
+ }
+ },
+ }));
+ return {
+ slots: (profile: string, event: string, date: string, timeZone: string) =>
+ queryClient.fetchQuery({
+ queryKey: schedulingKeys.slots(profile, event, `${date}:${timeZone}`)
+ .queryKey,
+ staleTime: 0,
+ retry: false,
+ queryFn: async () =>
+ (
+ await throwOnErr(() =>
+ schedulingClient.slots(profile, event, date, timeZone)
+ )
+ ).slots,
+ }),
+ book: (profile: string, event: string, request: BookingRequest) =>
+ book.mutateAsync({ profile, event, request }),
+ };
+}
+
+export function createBookingReceiptSource(
+ id: Accessor<string>,
+ token: Accessor<string>
+) {
+ const receipt = useQuery(() => ({
+ queryKey: schedulingKeys.receipt(id(), token()).queryKey,
+ queryFn: async () =>
+ validateReceipt(
+ await throwOnErr(() => schedulingClient.receipt(id(), token()))
+ ),
+ retry: false,
+ gcTime: 0,
+ refetchInterval: (q) =>
+ q.state.data?.booking.status === 'processing' ||
+ q.state.data?.booking.status === 'failed'
+ ? 5000
+ : false,
+ }));
+ const cancel = useMutation(() => ({
+ mutationFn: () =>
+ throwOnErr(() => schedulingClient.cancelPublic(id(), token())),
+ retry: false,
+ }));
+ const reschedule = useMutation(() => ({
+ mutationFn: (startsAt: string) =>
+ throwOnErr(() => schedulingClient.reschedule(id(), token(), startsAt)),
+ retry: false,
+ }));
+ return {
+ receipt,
+ cancel: async () => {
+ await cancel.mutateAsync();
+ await receipt.refetch();
+ },
+ reschedule: async (startsAt: string) => {
+ await reschedule.mutateAsync(startsAt);
+ await receipt.refetch();
+ },
+ replacementSlots: (date: string) =>
+ queryClient.fetchQuery({
+ queryKey: schedulingKeys.replacementSlots(id(), token(), date).queryKey,
+ queryFn: async () =>
+ (
+ await throwOnErr(() =>
+ schedulingClient.replacementSlots(id(), token(), date)
+ )
+ ).slots,
+ staleTime: 0,
+ gcTime: 0,
+ retry: false,
+ }),
+ };
+}
diff --git a/apps/web/src/features/scheduling/queries/source.ts b/apps/web/src/features/scheduling/queries/source.ts
new file mode 100644
index 0000000000..62c94f1329
--- /dev/null
+++ b/apps/web/src/features/scheduling/queries/source.ts
@@ -0,0 +1,108 @@
+import { throwOnErr } from '@core/util/result';
+import { queryClient } from '@queries/client';
+import { schedulingClient } from '@service-email/scheduling';
+import { useMutation, useQuery } from '@tanstack/solid-query';
+import type { Accessor } from 'solid-js';
+import type { SchedulingSource } from '../context/scheduling-context';
+import type { SchedulingProfile, SchedulingScope } from '../core/types';
+import { schedulingKeys } from './keys';
+
+export function useSchedulingProfileQuery(scope: Accessor<SchedulingScope>) {
+ return useQuery(() => ({
+ queryKey: schedulingKeys.settings(scope().id).queryKey,
+ queryFn: async () =>
+ (await throwOnErr(() => schedulingClient.settings(scope().teamId)))
+ .profile,
+ retry: false,
+ }));
+}
+
+export function createSchedulingSource(
+ scope: Accessor<SchedulingScope>,
+ range: Accessor<{ from: string; to: string }>
+): SchedulingSource {
+ const profile = useSchedulingProfileQuery(scope);
+ const bookings = useQuery(() => ({
+ queryKey: schedulingKeys.bookings(scope().id, range().from, range().to)
+ .queryKey,
+ queryFn: async () =>
+ (
+ await throwOnErr(() =>
+ schedulingClient.bookings(scope().teamId, range())
+ )
+ ).bookings,
+ retry: false,
+ }));
+ const save = useMutation(() => ({
+ mutationFn: async ({
+ next,
+ owner,
+ }: {
+ next: SchedulingProfile;
+ owner: SchedulingScope;
+ }) =>
+ (await throwOnErr(() => schedulingClient.save(next, owner.teamId)))
+ .profile,
+ onSuccess: (data, { owner }) => {
+ queryClient.setQueryData(
+ schedulingKeys.settings(owner.id).queryKey,
+ data
+ );
+ },
+ }));
+ const reload = () => {
+ void profile.refetch();
+ void bookings.refetch();
+ };
+ return {
+ profile: () => (profile.isSuccess ? profile.data : undefined),
+ bookings: () => (bookings.isSuccess ? bookings.data : []),
+ loading: () => profile.isPending || bookings.isPending,
+ error: () =>
+ profile.isError || bookings.isError
+ ? profile.isError
+ ? 'Calendar scheduling could not be loaded. Check your connection and try again.'
+ : 'Bookings could not be loaded. Try a shorter date range or check your connection.'
+ : undefined,
+ saving: () => save.isPending,
+ save: async (next) => {
+ await save.mutateAsync({ next, owner: scope() });
+ },
+ approve: async (id) => {
+ await throwOnErr(() => schedulingClient.approve(id));
+ await bookings.refetch();
+ },
+ cancel: async (id) => {
+ await throwOnErr(() => schedulingClient.cancel(id));
+ await bookings.refetch();
+ },
+ loadInsights: (from, to) => {
+ const owner = scope();
+ return queryClient.fetchQuery({
+ queryKey: schedulingKeys.insights(owner.id, from, to).queryKey,
+ queryFn: async () =>
+ (
+ await throwOnErr(() =>
+ schedulingClient.bookings(owner.teamId, { from, to })
+ )
+ ).bookings,
+ staleTime: 0,
+ retry: false,
+ });
+ },
+ setAttendance: async (id, attendance) => {
+ await throwOnErr(() => schedulingClient.setAttendance(id, attendance));
+ await bookings.refetch();
+ await queryClient.invalidateQueries({
+ queryKey: schedulingKeys.insights._def,
+ });
+ },
+ reload,
+ };
+}
+
+export function useManageBookingMutation() {
+ return useMutation(() => ({
+ mutationFn: (id: string) => throwOnErr(() => schedulingClient.manage(id)),
+ }));
+}
diff --git a/apps/web/src/features/scheduling/scheduling.tsx b/apps/web/src/features/scheduling/scheduling.tsx
new file mode 100644
index 0000000000..7f4710f996
--- /dev/null
+++ b/apps/web/src/features/scheduling/scheduling.tsx
@@ -0,0 +1,95 @@
+import { toast } from '@core/component/Toast/Toast';
+import { useSettingsState } from '@core/constant/SettingsState';
+import { useUserContext } from '@core/context/user';
+import { getDisplayName, macroIdToEmail, tryMacroId } from '@core/user';
+import { writeClipboardData } from '@core/util/dataTransfer';
+import { getWebOrigin } from '@core/util/webOrigin';
+import { useCurrentTeamQuery } from '@queries/team/teams';
+import { useNavigate } from '@solidjs/router';
+import { Suspense } from 'solid-js';
+import { SchedulingProvider } from './context/scheduling-context';
+import type { SchedulingProfile, SchedulingScope } from './core/types';
+import {
+ createSchedulingSource,
+ useManageBookingMutation,
+} from './queries/source';
+import { SchedulingSettingsView } from './views/settings-view';
+
+export function schedulingLink(
+ profile: Pick<SchedulingProfile, 'id'>,
+ slug?: string
+) {
+ return `${getWebOrigin()}/app/book/${encodeURIComponent(profile.id)}${slug ? `/${encodeURIComponent(slug)}` : ''}`;
+}
+
+function SchedulingSettingsContent() {
+ const navigate = useNavigate();
+ const manageBooking = useManageBookingMutation();
+ const user = useUserContext();
+ const team = useCurrentTeamQuery();
+ const settings = useSettingsState();
+ const currentTeam = () => (team.isSuccess ? team.data : undefined);
+ const members = () =>
+ currentTeam()?.members.map((m) => {
+ const id = tryMacroId(m.user_id);
+ return {
+ id: m.user_id,
+ name: id ? getDisplayName(id) : m.user_id,
+ email: id ? macroIdToEmail(id) : m.user_id,
+ };
+ }) ?? [];
+ const scopes = (): SchedulingScope[] => {
+ const result: SchedulingScope[] = [
+ { id: user.userId() ?? 'me', name: 'Personal', canEdit: true },
+ ];
+ const data = currentTeam();
+ if (data) {
+ const role = data.members.find((m) => m.user_id === user.userId())?.role;
+ result.push({
+ id: data.team.id,
+ name: data.team.name,
+ teamId: data.team.id,
+ canEdit: role === 'admin' || role === 'owner',
+ });
+ }
+ return result;
+ };
+ return (
+ <SchedulingProvider
+ value={{
+ manageBooking: async (id) => {
+ const receipt = await manageBooking.mutateAsync(id);
+ settings.closeSettings();
+ navigate(`/booking/${id}#${receipt.token}`);
+ },
+ scopes,
+ members,
+ userId: () => user.userId() ?? '',
+ createSource: createSchedulingSource,
+ link: schedulingLink,
+ openConnections: () => settings.openSettings('Connected'),
+ openTeamSettings: () => settings.openSettings('Team'),
+ copyLink: async (profile, slug) => {
+ if (
+ await writeClipboardData({
+ 'text/plain': schedulingLink(profile, slug),
+ })
+ )
+ toast.success('Booking link copied');
+ else toast.failure('Could not copy booking link');
+ },
+ }}
+ >
+ <SchedulingSettingsView />
+ </SchedulingProvider>
+ );
+}
+export function SchedulingSettings() {
+ return (
+ <Suspense
+ fallback={<p class="p-8 text-ink-muted">Loading calendar settings…</p>}
+ >
+ <SchedulingSettingsContent />
+ </Suspense>
+ );
+}
diff --git a/apps/web/src/features/scheduling/views/booking-receipt-view.tsx b/apps/web/src/features/scheduling/views/booking-receipt-view.tsx
new file mode 100644
index 0000000000..99d8bc3038
--- /dev/null
+++ b/apps/web/src/features/scheduling/views/booking-receipt-view.tsx
@@ -0,0 +1,162 @@
+import { Button } from '@ui';
+import { createSignal, Show } from 'solid-js';
+import { RescheduleForm } from '../components/reschedule-form';
+import type { BookingReceipt } from '../core/types';
+
+export function BookingReceiptView(props: {
+ receipt?: BookingReceipt;
+ unavailable: boolean;
+ cancel: () => Promise<void>;
+ loadSlots: (date: string) => Promise<{ startsAt: string; endsAt: string }[]>;
+ reschedule: (start: string) => Promise<void>;
+}) {
+ const [confirm, setConfirm] = createSignal(false);
+ const [rescheduling, setRescheduling] = createSignal(false);
+ const [busy, setBusy] = createSignal(false);
+ const [error, setError] = createSignal('');
+ const cancel = async () => {
+ if (busy()) return;
+ setError('');
+ setBusy(true);
+ try {
+ await props.cancel();
+ setRescheduling(false);
+ setConfirm(false);
+ } catch {
+ setError(
+ 'Cancellation failed. Your booking has not been marked cancelled. Please try again.'
+ );
+ } finally {
+ setBusy(false);
+ }
+ };
+ return (
+ <main class="min-h-screen bg-panel px-4 py-20 text-ink">
+ <div class="mx-auto max-w-lg rounded-2xl border border-edge-muted bg-surface-1 p-8">
+ <Show
+ when={props.receipt}
+ fallback={
+ <p>
+ {props.unavailable
+ ? 'We could not load this booking. Keep this private link and try again before making another booking.'
+ : 'Loading booking…'}
+ </p>
+ }
+ >
+ {(r) => (
+ <>
+ <h1 class="text-2xl font-semibold">
+ {r().booking.status === 'cancelled'
+ ? 'Booking cancelled'
+ : r().booking.status === 'pending'
+ ? 'Booking requested'
+ : r().booking.status === 'confirmed'
+ ? 'You’re booked'
+ : r().booking.status === 'failed'
+ ? 'We’re updating your booking'
+ : 'Booking is processing'}
+ </h1>
+ <h2 class="mt-6 font-semibold">{r().booking.title}</h2>
+ <p class="mt-2 text-sm">
+ {new Date(r().booking.startsAt).toLocaleString([], {
+ dateStyle: 'full',
+ timeStyle: 'short',
+ timeZone: r().booking.timeZone,
+ })}
+ </p>
+ <p class="mt-1 text-sm text-ink-muted">
+ {r().booking.timeZone.replaceAll('_', ' ')}
+ </p>
+ <p class="mt-4 text-sm">{r().booking.location}</p>
+ <p class="mt-5 text-sm text-ink-muted">
+ {r().booking.status === 'pending'
+ ? 'Your host will confirm this meeting. The time is held while they review it.'
+ : r().booking.status === 'confirmed'
+ ? 'A calendar invitation has been sent to your email.'
+ : r().booking.status === 'failed'
+ ? 'Your time is reserved. We’re retrying the calendar update automatically; keep this page to check its status and avoid making another booking.'
+ : ''}
+ </p>
+ <p class="mt-3 text-xs text-ink-muted">
+ Keep this private link to manage your booking.
+ </p>
+ <Show
+ when={
+ r().booking.status === 'confirmed' ||
+ r().booking.status === 'pending'
+ }
+ >
+ <div class="mt-6 flex flex-wrap gap-2">
+ <Button
+ variant="outline"
+ disabled={busy()}
+ onClick={() => {
+ setConfirm(false);
+ setRescheduling(true);
+ }}
+ >
+ Reschedule
+ </Button>
+ <Button
+ variant="outline"
+ disabled={busy()}
+ onClick={() => {
+ setRescheduling(false);
+ setConfirm(true);
+ }}
+ >
+ Cancel booking
+ </Button>
+ <Show when={confirm()}>
+ <Button
+ variant="strong"
+ disabled={busy()}
+ onClick={() => void cancel()}
+ >
+ {busy() ? 'Cancelling…' : 'Confirm cancellation'}
+ </Button>
+ <Button
+ variant="ghost"
+ disabled={busy()}
+ onClick={() => setConfirm(false)}
+ >
+ Keep booking
+ </Button>
+ </Show>
+ </div>
+ </Show>
+ <Show
+ when={
+ rescheduling() &&
+ (r().booking.status === 'pending' ||
+ r().booking.status === 'confirmed')
+ }
+ >
+ <RescheduleForm
+ timeZone={r().scheduleTimeZone}
+ load={props.loadSlots}
+ submit={async (start) => {
+ setError('');
+ setBusy(true);
+ try {
+ await props.reschedule(start);
+ setRescheduling(false);
+ } finally {
+ setBusy(false);
+ }
+ }}
+ onCancel={() => setRescheduling(false)}
+ />
+ </Show>
+ <Show when={error()}>
+ <p role="alert" class="mt-4 text-sm text-failure">
+ {error()}
+ </p>
+ </Show>
+ </>
+ )}
+ </Show>
+ </div>
+ </main>
+ );
+}
diff --git a/apps/web/src/features/scheduling/views/insights-view.tsx b/apps/web/src/features/scheduling/views/insights-view.tsx
new file mode 100644
index 0000000000..e8d33ac08c
--- /dev/null
+++ b/apps/web/src/features/scheduling/views/insights-view.tsx
@@ -0,0 +1,31 @@
+import { type JSX, onMount } from 'solid-js';
+import { InsightsPanel } from '../components/insights-panel';
+import type { SchedulingSource } from '../context/scheduling-context';
+import type { EventType, SchedulingMember } from '../core/types';
+import { createInsightsState } from '../primitives/insights-state';
+
+export function InsightsView(props: {
+ source: SchedulingSource;
+ events: EventType[];
+ members: SchedulingMember[];
+ timeZone: string;
+ scopeSelector?: JSX.Element;
+}) {
+ const state = createInsightsState(props.source, props.timeZone);
+ onMount(() => void state.load());
+ return (
+ <InsightsPanel
+ scopeSelector={props.scopeSelector}
+ bookings={state.bookings()}
+ events={props.events}
+ members={props.members}
+ timeZone={props.timeZone}
+ loading={state.loading()}
+ error={state.error()}
+ from={state.range().from}
+ to={state.range().to}
+ onRangeChange={(from, to) => void state.load(from, to)}
+ onRetry={() => void state.load()}
+ />
+ );
+}
diff --git a/apps/web/src/features/scheduling/views/public-booking-view.tsx b/apps/web/src/features/scheduling/views/public-booking-view.tsx
new file mode 100644
index 0000000000..f5e1f65fd9
--- /dev/null
+++ b/apps/web/src/features/scheduling/views/public-booking-view.tsx
@@ -0,0 +1,396 @@
+import { Button } from '@ui';
+import { createEffect, createSignal, For, on, Show } from 'solid-js';
+import {
+ Field,
+ TextArea,
+ TextInput,
+ TimeZoneInput,
+} from '../components/fields';
+import type { BookingReceipt, PublicEvent, PublicProfile } from '../core/types';
+import {
+ type BookingSource,
+ createBookingFlow,
+} from '../primitives/booking-flow';
+
+function dateKey(date: Date) {
+ return date.toISOString().slice(0, 10);
+}
+
+export function PublicBookingView(props: {
+ profile: PublicProfile;
+ event?: PublicEvent;
+ source: BookingSource;
+ onEvent: (slug: string) => void;
+ onReceipt: (r: BookingReceipt) => void;
+}) {
+ const flow = createBookingFlow(props.source, props.profile.id);
+ const [date, setDate] = createSignal('');
+ const [zone, setZone] = createSignal(
+ Intl.DateTimeFormat().resolvedOptions().timeZone
+ );
+ const [name, setName] = createSignal('');
+ const [email, setEmail] = createSignal('');
+ const [answers, setAnswers] = createSignal<Record<string, string>>({});
+ createEffect(
+ on(
+ () => props.event?.id,
+ () => {
+ setDate('');
+ setAnswers({});
+ flow.reset();
+ },
+ { defer: true }
+ )
+ );
+ const today = () => {
+ const parts = new Intl.DateTimeFormat('en', {
+ timeZone: zone(),
+ year: 'numeric',
+ month: '2-digit',
+ day: '2-digit',
+ }).formatToParts(new Date());
+ return ['year', 'month', 'day']
+ .map((k) => parts.find((p) => p.type === k)?.value)
+ .join('-');
+ };
+ const currentMonth = () => new Date(`${today().slice(0, 7)}-01T00:00:00Z`);
+ const [month, setMonth] = createSignal(currentMonth());
+ const days = () =>
+ Array.from(
+ {
+ length: new Date(
+ Date.UTC(month().getUTCFullYear(), month().getUTCMonth() + 1, 0)
+ ).getUTCDate(),
+ },
+ (_, i) =>
+ new Date(
+ Date.UTC(month().getUTCFullYear(), month().getUTCMonth(), i + 1)
+ )
+ );
+ const choose = (value: string) => {
+ setDate(value);
+ if (props.event) void flow.chooseDate(props.event.id, value, zone());
+ };
+ const submit = async (e: SubmitEvent) => {
+ e.preventDefault();
+ if (!props.event) return;
+ await flow.submit(props.event.id, {
+ name: name(),
+ email: email(),
+ answers: answers(),
+ timeZone: zone(),
+ });
+ const r = flow.receipt();
+ if (r) props.onReceipt(r);
+ };
+ return (
+ <main class="min-h-screen overflow-y-auto bg-panel px-4 py-12 text-ink sm:py-20">
+ <div class="mx-auto max-w-4xl">
+ <a
+ href="https://macro.com"
+ class="mb-8 inline-block text-lg font-semibold tracking-tight"
+ >
+ Macro
+ <span class="ml-2 text-sm font-normal text-ink-muted">
+ Scheduling
+ </span>
+ </a>
+ <Show
+ when={props.event}
+ fallback={
+ <section class="mx-auto max-w-xl">
+ <h1 class="text-3xl font-semibold">{props.profile.name}</h1>
+ <p class="mt-3 whitespace-pre-wrap text-ink-muted">
+ {props.profile.description}
+ </p>
+ <div class="mt-8 flex flex-col gap-3">
+ <For
+ each={props.profile.eventTypes}
+ fallback={
+ <p class="rounded-xl border border-edge-muted p-8 text-sm text-ink-muted">
+ There are no bookable events right now.
+ </p>
+ }
+ >
+ {(event) => (
+ <button
+ type="button"
+ class="rounded-xl border border-edge-muted bg-surface-1 p-6 text-left hover:bg-hover"
+ onClick={() => props.onEvent(event.slug)}
+ >
+ <h2 class="font-semibold">
+ {event.title} <span class="float-right">→</span>
+ </h2>
+ <p class="mt-2 text-sm text-ink-muted">
+ {event.durationMinutes} minutes ·{' '}
+ {event.googleMeet
+ ? 'Google Meet'
+ : event.location || 'Meeting'}
+ </p>
+ <p class="mt-3 text-sm text-ink-muted">
+ {event.description}
+ </p>
+ </button>
+ )}
+ </For>
+ </div>
+ </section>
+ }
+ >
+ {(event) => (
+ <section class="grid overflow-hidden rounded-2xl border border-edge-muted bg-surface-1 md:grid-cols-[280px_1fr]">
+ <aside class="border-b border-edge-muted p-7 md:border-r md:border-b-0">
+ <p class="text-sm text-ink-muted">{props.profile.name}</p>
+ <h1 class="mt-3 text-2xl font-semibold">{event().title}</h1>
+ <p class="mt-5 text-sm">◷ {event().durationMinutes} minutes</p>
+ <p class="mt-3 text-sm">
+ {event().googleMeet
+ ? 'Google Meet'
+ : event().location || 'Meeting'}
+ </p>
+ <p class="mt-5 whitespace-pre-wrap text-sm leading-relaxed text-ink-muted">
+ {event().description}
+ </p>
+ <Show when={flow.selected()}>
+ <p class="mt-5 text-sm font-medium">
+ {new Date(flow.selected()!).toLocaleString([], {
+ timeZone: zone(),
+ dateStyle: 'full',
+ timeStyle: 'short',
+ })}
+ </p>
+ </Show>
+ <div class="mt-6">
+ <Field label="Your time zone">
+ <TimeZoneInput
+ value={zone()}
+ disabled={flow.submitting() || flow.uncertain()}
+ onChange={(value) => {
+ setZone(value);
+ setMonth(currentMonth());
+ setDate('');
+ flow.reset();
+ }}
+ />
+ </Field>
+ </div>
+ </aside>
+ <div class="p-7">
+ <Show when={flow.error()}>
+ <p
+ role="alert"
+ class="mb-4 rounded-lg border border-edge-muted p-3 text-sm text-failure"
+ >
+ {flow.error()}
+ </p>
+ </Show>
+ <Show
+ when={!flow.selected()}
+ fallback={
+ <form
+ class="flex flex-col gap-5"
+ onSubmit={(e) => void submit(e)}
+ >
+ <Button
+ variant="ghost"
+ class="self-start"
+ onClick={flow.back}
+ disabled={flow.submitting() || flow.uncertain()}
+ >
+ ← Choose another time
+ </Button>
+ <h2 class="text-lg font-semibold">Your details</h2>
+ <Field label="Name">
+ <TextInput
+ required
+ disabled={flow.submitting() || flow.uncertain()}
+ autocomplete="name"
+ value={name()}
+ onInput={(e) => setName(e.currentTarget.value)}
+ />
+ </Field>
+ <Field label="Email address">
+ <TextInput
+ type="email"
+ disabled={flow.submitting() || flow.uncertain()}
+ required
+ autocomplete="email"
+ value={email()}
+ onInput={(e) => setEmail(e.currentTarget.value)}
+ />
+ </Field>
+ <For each={event().questions}>
+ {(q) => (
+ <Field label={`${q.label}${q.required ? ' *' : ''}`}>
+ <TextArea
+ disabled={flow.submitting() || flow.uncertain()}
+ required={q.required}
+ value={answers()[q.id] ?? ''}
+ onInput={(e) =>
+ setAnswers({
+ ...answers(),
+ [q.id]: e.currentTarget.value,
+ })
+ }
+ />
+ </Field>
+ )}
+ </For>
+ <Button
+ type="submit"
+ variant="strong"
+ disabled={flow.submitting()}
+ >
+ {flow.submitting()
+ ? 'Booking…'
+ : flow.uncertain()
+ ? 'Check booking status'
+ : event().requiresConfirmation
+ ? 'Request booking'
+ : 'Confirm booking'}
+ </Button>
+ <p class="text-xs text-ink-muted">
+ Your details are shared with the meeting hosts.
+ </p>
+ </form>
+ }
+ >
+ <h2 class="text-lg font-semibold">Select a date & time</h2>
+ <div class="mt-5 flex items-center justify-between">
+ <span class="font-medium">
+ {month().toLocaleDateString([], {
+ timeZone: 'UTC',
+ month: 'long',
+ year: 'numeric',
+ })}
+ </span>
+ <div class="flex gap-1">
+ <Button
+ variant="ghost"
+ label="Previous month"
+ disabled={month() <= currentMonth()}
+ onClick={() =>
+ setMonth(
+ new Date(
+ Date.UTC(
+ month().getUTCFullYear(),
+ month().getUTCMonth() - 1,
+ 1
+ )
+ )
+ )
+ }
+ >
+ ‹
+ </Button>
+ <Button
+ variant="ghost"
+ label="Next month"
+ onClick={() =>
+ setMonth(
+ new Date(
+ Date.UTC(
+ month().getUTCFullYear(),
+ month().getUTCMonth() + 1,
+ 1
+ )
+ )
+ )
+ }
+ >
+ ›
+ </Button>
+ </div>
+ </div>
+ <div class="mt-3 grid grid-cols-7 gap-1">
+ <For each={['S', 'M', 'T', 'W', 'T', 'F', 'S']}>
+ {(day) => (
+ <span class="py-2 text-center text-xs text-ink-muted">
+ {day}
+ </span>
+ )}
+ </For>
+ <For each={Array.from({ length: month().getUTCDay() })}>
+ {() => <span />}
+ </For>
+ <For each={days()}>
+ {(d) => (
+ <Button
+ variant={date() === dateKey(d) ? 'strong' : 'ghost'}
+ class="h-auto w-full aspect-square"
+ disabled={dateKey(d) < today()}
+ aria-label={d.toLocaleDateString([], {
+ timeZone: 'UTC',
+ dateStyle: 'full',
+ })}
+ onClick={() => choose(dateKey(d))}
+ >
+ {d.getUTCDate()}
+ </Button>
+ )}
+ </For>
+ </div>
+ <Show when={date()}>
+ <div class="mt-6 border-t border-edge-muted pt-5">
+ <div class="mb-3 flex items-center justify-between">
+ <h3 class="text-sm font-semibold">Available times</h3>
+ <Button
+ size="sm"
+ variant="ghost"
+ onClick={() => choose(date())}
+ >
+ Refresh
+ </Button>
+ </div>
+ <Show
+ when={!flow.loading()}
+ fallback={
+ <p role="status" class="text-sm text-ink-muted">
+ Checking calendars…
+ </p>
+ }
+ >
+ <div class="grid grid-cols-2 gap-2">
+ <For
+ each={flow.slots()}
+ fallback={
+ <Show when={!flow.error()}>
+ <p class="col-span-2 text-sm text-ink-muted">
+ No times available. Please choose another
+ date.
+ </p>
+ </Show>
+ }
+ >
+ {(slot) => (
+ <Button
+ variant="outline"
+ onClick={() => flow.select(slot.startsAt)}
+ >
+ {new Date(slot.startsAt).toLocaleTimeString(
+ [],
+ {
+ timeZone: zone(),
+ hour: 'numeric',
+ minute: '2-digit',
+ }
+ )}
+ </Button>
+ )}
+ </For>
+ </div>
+ </Show>
+ </div>
+ </Show>
+ </Show>
+ </div>
+ </section>
+ )}
+ </Show>
+ <p class="mt-8 text-center text-xs text-ink-muted">
+ Scheduling by Macro
+ </p>
+ </div>
+ </main>
+ );
+}
diff --git a/apps/web/src/features/scheduling/views/settings-view.tsx b/apps/web/src/features/scheduling/views/settings-view.tsx
new file mode 100644
index 0000000000..4a44c66f0c
--- /dev/null
+++ b/apps/web/src/features/scheduling/views/settings-view.tsx
@@ -0,0 +1,581 @@
+import Copy from '@phosphor/copy.svg';
+import Plus from '@phosphor/plus.svg';
+import Users from '@phosphor/users.svg';
+import { Button } from '@ui';
+import { createSignal, For, Show } from 'solid-js';
+import { unwrap } from 'solid-js/store';
+import { AvailabilityPanel } from '../components/availability-panel';
+import { BookingsPanel } from '../components/bookings-panel';
+import { EventEditor } from '../components/event-editor';
+import { EventTypesPanel } from '../components/event-types-panel';
+import { Field, SelectInput, TextArea, TextInput } from '../components/fields';
+import { ScheduleEditor } from '../components/schedule-editor';
+import {
+ SchedulingWorkspace,
+ schedulingPages,
+} from '../components/scheduling-workspace';
+import { useScheduling } from '../context/scheduling-context';
+import { reportDate, shiftReportDate } from '../core/insights';
+import {
+ type AvailabilitySchedule,
+ type EventType,
+ newEventType,
+ newSchedule,
+ type SchedulingProfile,
+} from '../core/types';
+import { InsightsView } from './insights-view';
+
+export function SchedulingSettingsView() {
+ const capabilities = useScheduling();
+ const [scopeId, setScopeId] = createSignal(
+ capabilities.scopes()[0]?.id ?? 'me'
+ );
+ const scope = () =>
+ capabilities.scopes().find((s) => s.id === scopeId()) ??
+ capabilities.scopes()[0];
+ const browserZone = Intl.DateTimeFormat().resolvedOptions().timeZone;
+ const today = reportDate(new Date(), browserZone);
+ const [bookingFrom, setBookingFrom] = createSignal(
+ shiftReportDate(today, -30)
+ );
+ const [bookingTo, setBookingTo] = createSignal(shiftReportDate(today, 30));
+ const source = capabilities.createSource(scope, () => ({
+ from: new Date(`${bookingFrom()}T00:00:00`).toISOString(),
+ to: new Date(`${shiftReportDate(bookingTo(), 1)}T00:00:00`).toISOString(),
+ }));
+ const [page, setPage] = createSignal('Event types');
+ const [event, setEvent] = createSignal<EventType>();
+ const [schedule, setSchedule] = createSignal<AvailabilitySchedule>();
+ const [error, setError] = createSignal('');
+ const [busyBooking, setBusyBooking] = createSignal('');
+ const [profileDraft, setProfileDraft] = createSignal<{
+ name: string;
+ description: string;
+ }>();
+ const profile = source.profile;
+ const editing = () => !!event() || !!schedule();
+ const pageInfo = () => schedulingPages.find((p) => p.name === page());
+ const navigate = (name: string) => {
+ setPage(name);
+ setEvent(undefined);
+ setSchedule(undefined);
+ setError('');
+ };
+ const changeScope = (id: string) => {
+ setScopeId(id);
+ setEvent(undefined);
+ setSchedule(undefined);
+ setProfileDraft(undefined);
+ setError('');
+ };
+ const save = async (next: SchedulingProfile) => {
+ setError('');
+ await source.save(next);
+ };
+ const action = async (fn: () => Promise<void>) => {
+ setError('');
+ try {
+ await fn();
+ } catch (e) {
+ setError(e instanceof Error ? e.message : 'Could not save your changes.');
+ }
+ };
+ const bookingAction = async (id: string, fn: () => Promise<void>) => {
+ setBusyBooking(id);
+ await action(fn);
+ setBusyBooking('');
+ };
+ const createEvent = async () => {
+ let p = profile();
+ if (!p) return;
+ if (!p.schedules.length) {
+ const s = newSchedule(Intl.DateTimeFormat().resolvedOptions().timeZone);
+ await save({ ...p, schedules: [s], defaultScheduleId: s.id });
+ p = profile();
+ if (!p) return;
+ }
+ setEvent(
+ newEventType(
+ p.defaultScheduleId ?? p.schedules[0].id,
+ [capabilities.userId()],
+ !!scope().teamId
+ )
+ );
+ };
+ const duplicate = (item: EventType) => {
+ const existing = profile()?.eventTypes ?? [];
+ let slug = `${item.slug}-copy`;
+ let suffix = 2;
+ while (existing.some((e) => e.slug === slug))
+ slug = `${item.slug}-copy-${suffix++}`;
+ setEvent({
+ ...structuredClone(unwrap(item)),
+ id: crypto.randomUUID(),
+ title: `${item.title} (copy)`,
+ slug,
+ enabled: false,
+ });
+ };
+ return (
+ <SchedulingWorkspace
+ page={page()}
+ onNavigate={navigate}
+ editor={!!event()}
+ title={!editing() ? pageInfo()?.name : undefined}
+ description={pageInfo()?.description}
+ publicLink={
+ profile()?.revision ? capabilities.link(profile()!) : undefined
+ }
+ onCopy={() => {
+ const p = profile();
+ if (p) void action(() => capabilities.copyLink(p));
+ }}
+ onConnections={capabilities.openConnections}
+ actions={
+ <Show
+ when={
+ !editing() &&
+ (page() === 'Event types' || page() === 'Availability')
+ }
+ >
+ <Button
+ variant="strong"
+ disabled={!scope().canEdit || source.saving() || !profile()}
+ onClick={() =>
+ page() === 'Event types'
+ ? void action(createEvent)
+ : setSchedule(
+ newSchedule(
+ Intl.DateTimeFormat().resolvedOptions().timeZone
+ )
+ )
+ }
+ >
+ <Plus class="size-4" />
+ {page() === 'Event types' ? 'New event type' : 'New schedule'}
+ </Button>
+ </Show>
+ }
+ >
+ <Show when={!editing() && page() !== 'Insights'}>
+ <div class="flex flex-wrap items-center justify-between gap-3">
+ <div class="w-56">
+ <SelectInput
+ label="Calendar owner"
+ value={scope().id}
+ options={capabilities
+ .scopes()
+ .map((s) => ({ value: s.id, label: s.name }))}
+ disabled={source.saving() || !!busyBooking()}
+ onChange={changeScope}
+ />
+ </div>
+ <Show when={page() === 'Event types' || page() === 'Booking page'}>
+ <Button
+ variant="outline"
+ disabled={!profile()?.revision}
+ onClick={() => {
+ const p = profile();
+ if (p) void action(() => capabilities.copyLink(p));
+ }}
+ >
+ <Copy class="size-4" />
+ Copy public link
+ </Button>
+ </Show>
+ </div>
+ </Show>
+ <Show when={!scope().canEdit}>
+ <p class="rounded-lg border border-edge-muted px-4 py-3 text-sm text-ink-muted">
+ Team members can view scheduling. Owners and admins manage links and
+ availability.
+ </p>
+ </Show>
+ <Show when={page() === 'Bookings'}>
+ <div class="flex flex-wrap items-end gap-4">
+ <Field
+ label="From"
+ hint={`Dates in ${browserZone.replaceAll('_', ' ')}`}
+ >
+ <TextInput
+ type="date"
+ value={bookingFrom()}
+ max={bookingTo()}
+ onChange={(e) => {
+ if (
+ e.currentTarget.value &&
+ e.currentTarget.value <= bookingTo()
+ )
+ setBookingFrom(e.currentTarget.value);
+ }}
+ />
+ </Field>
+ <Field label="Through">
+ <TextInput
+ type="date"
+ value={bookingTo()}
+ min={bookingFrom()}
+ onChange={(e) => {
+ if (
+ e.currentTarget.value &&
+ e.currentTarget.value >= bookingFrom()
+ )
+ setBookingTo(e.currentTarget.value);
+ }}
+ />
+ </Field>
+ </div>
+ </Show>
+ <Show when={source.error()}>
+ <div
+ role="alert"
+ class="flex flex-wrap items-center justify-between gap-3 rounded-xl border border-edge-muted p-5"
+ >
+ <p class="text-sm">{source.error()}</p>
+ <Button variant="outline" onClick={source.reload}>
+ Try again
+ </Button>
+ </div>
+ </Show>
+ <Show when={source.loading()}>
+ <p role="status" class="text-sm text-ink-muted">
+ Loading scheduling…
+ </p>
+ </Show>
+ <Show when={error()}>
+ <p role="alert" class="text-sm text-failure">
+ {error()}
+ </p>
+ </Show>
+ <Show when={profile()}>
+ {(p) => (
+ <>
+ <Show when={!editing()}>
+ <Show when={page() === 'Event types'}>
+ <EventTypesPanel
+ events={p().eventTypes}
+ canEdit={scope().canEdit}
+ saving={source.saving()}
+ onEdit={setEvent}
+ onDuplicate={duplicate}
+ link={(item) => capabilities.link(p(), item.slug)}
+ onCopy={(item) =>
+ void action(() => capabilities.copyLink(p(), item.slug))
+ }
+ onToggle={(item, enabled) =>
+ void action(() =>
+ save({
+ ...p(),
+ eventTypes: p().eventTypes.map((e) =>
+ e.id === item.id ? { ...e, enabled } : e
+ ),
+ })
+ )
+ }
+ onDelete={(item) =>
+ void action(() =>
+ save({
+ ...p(),
+ eventTypes: p().eventTypes.filter(
+ (e) => e.id !== item.id
+ ),
+ })
+ )
+ }
+ />
+ </Show>
+ <Show when={page() === 'Availability'}>
+ <AvailabilityPanel
+ profile={p()}
+ canEdit={scope().canEdit}
+ saving={source.saving()}
+ onEdit={setSchedule}
+ onDefault={(s) =>
+ void action(() => save({ ...p(), defaultScheduleId: s.id }))
+ }
+ onDelete={(s) =>
+ void action(async () => {
+ if (p().eventTypes.some((e) => e.scheduleId === s.id))
+ throw new Error(
+ 'Move event types to another schedule first.'
+ );
+ const schedules = p().schedules.filter(
+ (x) => x.id !== s.id
+ );
+ await save({
+ ...p(),
+ schedules,
+ defaultScheduleId:
+ p().defaultScheduleId === s.id
+ ? (schedules[0]?.id ?? null)
+ : p().defaultScheduleId,
+ });
+ })
+ }
+ />
+ </Show>
+ <Show when={page() === 'Bookings'}>
+ <BookingsPanel
+ bookings={source.bookings()}
+ events={p().eventTypes}
+ members={capabilities.members()}
+ currentUserId={capabilities.userId()}
+ canEdit={scope().canEdit}
+ busyId={busyBooking()}
+ onApprove={(id) =>
+ void bookingAction(id, () => source.approve(id))
+ }
+ onCancel={(id) =>
+ void bookingAction(id, () => source.cancel(id))
+ }
+ onManage={(id) =>
+ void bookingAction(id, () => capabilities.manageBooking(id))
+ }
+ onAttendance={(id, attendance) =>
+ void bookingAction(id, () =>
+ source.setAttendance(id, attendance)
+ )
+ }
+ />
+ </Show>
+ <Show when={page() === 'Insights'}>
+ <Show when={scope().id} keyed>
+ {(_scopeId) => (
+ <InsightsView
+ scopeSelector={
+ <div class="w-48">
+ <SelectInput
+ label="Calendar owner"
+ value={scope().id}
+ options={capabilities
+ .scopes()
+ .map((s) => ({ value: s.id, label: s.name }))}
+ onChange={changeScope}
+ />
+ </div>
+ }
+ source={source}
+ events={p().eventTypes}
+ members={capabilities.members()}
+ timeZone={
+ p().schedules.find(
+ (s) => s.id === p().defaultScheduleId
+ )?.timeZone ??
+ p().schedules[0]?.timeZone ??
+ Intl.DateTimeFormat().resolvedOptions().timeZone
+ }
+ />
+ )}
+ </Show>
+ </Show>
+ <Show when={page() === 'Teams'}>
+ <div class="rounded-xl border border-edge-muted bg-panel">
+ <div class="flex items-center justify-between border-b border-edge-muted bg-surface-1 px-6 py-5">
+ <div>
+ <h2 class="font-semibold">Your teams</h2>
+ <p class="mt-1 text-sm text-ink-muted">
+ Team links use your existing Macro memberships.
+ </p>
+ </div>
+ <Button
+ variant="outline"
+ onClick={capabilities.openTeamSettings}
+ >
+ Manage teams
+ </Button>
+ </div>
+ <For
+ each={capabilities
+ .scopes()
+ .filter((s) => s.teamId && s.id === s.teamId)}
+ fallback={
+ <div class="flex flex-col items-center gap-3 p-12 text-center">
+ <Users class="size-8 text-ink-muted" />
+ <p class="font-medium">Bring your team together</p>
+ <p class="text-sm text-ink-muted">
+ Create or join a Macro team to offer collective and
+ round-robin meetings.
+ </p>
+ <Button
+ variant="strong"
+ onClick={capabilities.openTeamSettings}
+ >
+ Open team settings
+ </Button>
+ </div>
+ }
+ >
+ {(team) => (
+ <div class="flex flex-wrap items-center justify-between gap-4 px-6 py-5">
+ <div>
+ <h3 class="font-semibold">{team.name}</h3>
+ <p class="mt-1 text-sm text-ink-muted">
+ {team.canEdit ? 'Owner or admin' : 'Team member'} ·
+ Collective & round-robin scheduling
+ </p>
+ </div>
+ <Button
+ variant="outline"
+ onClick={() => {
+ changeScope(team.id);
+ navigate('Event types');
+ }}
+ >
+ View event types
+ </Button>
+ </div>
+ )}
+ </For>
+ </div>
+ <Show when={scope().teamId}>
+ <div class="overflow-hidden rounded-xl border border-edge-muted">
+ <div class="border-b border-edge-muted bg-surface-1 px-6 py-4">
+ <h2 class="font-semibold">Team members</h2>
+ <p class="mt-1 text-sm text-ink-muted">
+ Hosts need a connected calendar. Their personal working
+ hours are respected when configured.
+ </p>
+ </div>
+ <For each={capabilities.members()}>
+ {(member) => (
+ <div class="flex items-center gap-3 border-b border-edge-muted px-6 py-4 last:border-b-0">
+ <span class="flex size-9 items-center justify-center rounded-full bg-active text-sm font-medium">
+ {member.name.slice(0, 1).toUpperCase()}
+ </span>
+ <div>
+ <p class="text-sm font-medium">{member.name}</p>
+ <p class="text-xs text-ink-muted">{member.email}</p>
+ </div>
+ </div>
+ )}
+ </For>
+ </div>
+ </Show>
+ </Show>
+ <Show when={page() === 'Booking page'}>
+ <div class="grid gap-6 @min-[850px]:grid-cols-[1fr_320px]">
+ <div class="flex flex-col gap-6 rounded-xl border border-edge-muted p-6">
+ <Field label="Display name">
+ <TextInput
+ disabled={!scope().canEdit}
+ value={profileDraft()?.name ?? p().name}
+ onInput={(e) =>
+ setProfileDraft({
+ name: e.currentTarget.value,
+ description:
+ profileDraft()?.description ?? p().description,
+ })
+ }
+ />
+ </Field>
+ <Field label="Introduction">
+ <TextArea
+ disabled={!scope().canEdit}
+ value={profileDraft()?.description ?? p().description}
+ onInput={(e) =>
+ setProfileDraft({
+ name: profileDraft()?.name ?? p().name,
+ description: e.currentTarget.value,
+ })
+ }
+ />
+ </Field>
+ <Button
+ class="self-start"
+ variant="strong"
+ disabled={
+ !scope().canEdit || !profileDraft() || source.saving()
+ }
+ onClick={() =>
+ void action(async () => {
+ await save({ ...p(), ...profileDraft() });
+ setProfileDraft(undefined);
+ })
+ }
+ >
+ Save booking page
+ </Button>
+ </div>
+ <aside class="rounded-xl border border-edge-muted bg-surface-1 p-6">
+ <p class="text-xs font-medium uppercase tracking-wide text-ink-muted">
+ Preview
+ </p>
+ <span class="mt-6 flex size-12 items-center justify-center rounded-full bg-active text-lg font-semibold">
+ {(profileDraft()?.name ?? p().name).slice(0, 1)}
+ </span>
+ <h2 class="mt-4 font-semibold">
+ {profileDraft()?.name ?? p().name}
+ </h2>
+ <p class="mt-2 whitespace-pre-wrap text-sm text-ink-muted">
+ {profileDraft()?.description ?? p().description}
+ </p>
+ <Show when={p().revision > 0}>
+ <a
+ class="mt-6 inline-block text-sm underline underline-offset-4"
+ href={capabilities.link(p())}
+ target="_blank"
+ rel="noopener noreferrer"
+ >
+ View public page ↗
+ </a>
+ </Show>
+ </aside>
+ </div>
+ </Show>
+ </Show>
+ <Show when={event()} keyed>
+ {(value) => (
+ <EventEditor
+ event={value}
+ events={p().eventTypes}
+ schedules={p().schedules}
+ members={capabilities.members()}
+ team={!!scope().teamId}
+ saving={source.saving()}
+ onCancel={() => setEvent(undefined)}
+ onSave={async (next) => {
+ const exists = p().eventTypes.some((e) => e.id === next.id);
+ await save({
+ ...p(),
+ eventTypes: exists
+ ? p().eventTypes.map((e) =>
+ e.id === next.id ? next : e
+ )
+ : [...p().eventTypes, next],
+ });
+ if (event()?.id === next.id) setEvent(undefined);
+ }}
+ />
+ )}
+ </Show>
+ <Show when={schedule()} keyed>
+ {(value) => (
+ <ScheduleEditor
+ schedule={value}
+ saving={source.saving()}
+ onCancel={() => setSchedule(undefined)}
+ onSave={async (next) => {
+ const exists = p().schedules.some((s) => s.id === next.id);
+ await save({
+ ...p(),
+ defaultScheduleId:
+ p().defaultScheduleId ??
+ p().schedules[0]?.id ??
+ next.id,
+ schedules: exists
+ ? p().schedules.map((s) =>
+ s.id === next.id ? next : s
+ )
+ : [...p().schedules, next],
+ });
+ if (schedule()?.id === next.id) setSchedule(undefined);
+ }}
+ />
+ )}
+ </Show>
+ </>
+ )}
+ </Show>
+ </SchedulingWorkspace>
+ );
+}
diff --git a/apps/web/src/features/scheduling/vitest.config.ts b/apps/web/src/features/scheduling/vitest.config.ts
new file mode 100644
index 0000000000..f3646196dc
--- /dev/null
+++ b/apps/web/src/features/scheduling/vitest.config.ts
@@ -0,0 +1,15 @@
+import { fileURLToPath } from 'node:url';
+import solidPlugin from 'vite-plugin-solid';
+import tsconfigPaths from 'vite-tsconfig-paths';
+import { defineConfig } from 'vitest/config';
+
+export default defineConfig({
+ root: fileURLToPath(new URL('../../..', import.meta.url)),
+ plugins: [tsconfigPaths(), solidPlugin()],
+ ssr: { resolve: { conditions: ['browser', 'development'] } },
+ test: {
+ name: 'scheduling',
+ environment: 'jsdom',
+ include: ['src/features/scheduling/**/*.{test,spec}.{ts,tsx}'],
+ },
+});
diff --git a/apps/web/src/features/settings/SettingsTabContent.tsx b/apps/web/src/features/settings/SettingsTabContent.tsx
index f14604fe2b..8b02fc70ab 100644
--- a/apps/web/src/features/settings/SettingsTabContent.tsx
+++ b/apps/web/src/features/settings/SettingsTabContent.tsx
@@ -2,6 +2,7 @@ import type { SettingsTab } from '@core/constant/SettingsState';
import { useSettingsTabAvailable } from '@core/constant/settingsTabsConfig';
import { Show, Suspense } from 'solid-js';
import { CrmSettings as Crm } from '../crm/crm-settings';
+import { SchedulingSettings } from '../scheduling/scheduling';
import { Account } from './Account';
import { Admin } from './Admin';
import { Agent } from './Agent';
@@ -34,6 +35,9 @@ export function SettingsTabContent(props: { tab: SettingsTab }) {
<Show when={isCurrentTab('Account')}>
<Account />
</Show>
+ <Show when={isCurrentTab('Calendar')}>
+ <SchedulingSettings />
+ </Show>
<Show when={isCurrentTab('API Keys')}>
<ApiKeys />
</Show>
diff --git a/apps/web/src/lib/core/constant/SettingsState.tsx b/apps/web/src/lib/core/constant/SettingsState.tsx
index 0b0bef9477..cb58749e0c 100644
--- a/apps/web/src/lib/core/constant/SettingsState.tsx
+++ b/apps/web/src/lib/core/constant/SettingsState.tsx
@@ -16,6 +16,7 @@ import { createMemo, createSignal, onCleanup } from 'solid-js';
import { settingsTabToSlug } from './settingsTabsConfig';
export type SettingsTab =
+ | 'Calendar'
| 'Account'
| 'API Keys'
| 'Notifications'
diff --git a/apps/web/src/lib/core/constant/featureFlags.ts b/apps/web/src/lib/core/constant/featureFlags.ts
index 0c5cc1bc40..4e0fe9036f 100644
--- a/apps/web/src/lib/core/constant/featureFlags.ts
+++ b/apps/web/src/lib/core/constant/featureFlags.ts
@@ -596,6 +596,13 @@ export function isCalendarSearchUiEnabled(): boolean {
);
}
+// Scheduling settings, calendar shortcuts, and public booking/receipt pages.
+// Off until PostHog enables it, including in dev.
+export const enableCalendarScheduling = defineFlag({
+ key: 'enable-calendar-scheduling',
+ env: 'ENABLE_CALENDAR_SCHEDULING',
+});
+
// The "Enable calendar" prompt on phones. Off by default everywhere,
// including dev: the mobile toast layout drops the body and the close button,
// so the prompt lands as an undismissable one-line bar over the composer.
diff --git a/apps/web/src/lib/core/constant/settingsTabsConfig.test.ts b/apps/web/src/lib/core/constant/settingsTabsConfig.test.ts
index 33fb766b46..2b4ad31d8c 100644
--- a/apps/web/src/lib/core/constant/settingsTabsConfig.test.ts
+++ b/apps/web/src/lib/core/constant/settingsTabsConfig.test.ts
@@ -19,14 +19,11 @@ describe('settings Connections tab', () => {
const workspace = SETTINGS_TAB_GROUPS.find(
(group) => group.label === 'Workspace'
);
- expect(workspace?.items.map((item) => item.tab)).toEqual([
- 'Team',
- 'Tags',
- 'CRM',
+ const tabs = workspace?.items.map((item) => item.tab) ?? [];
+ const integrations = tabs.indexOf('Connected');
+ expect(tabs.slice(integrations, integrations + 2)).toEqual([
'Connected',
'Connections',
- 'Agent',
- 'Bots',
]);
});
});
diff --git a/apps/web/src/lib/core/constant/settingsTabsConfig.tsx b/apps/web/src/lib/core/constant/settingsTabsConfig.tsx
index fd758e651e..a7869b8c48 100644
--- a/apps/web/src/lib/core/constant/settingsTabsConfig.tsx
+++ b/apps/web/src/lib/core/constant/settingsTabsConfig.tsx
@@ -2,6 +2,7 @@ import { useFeatureFlag } from '@app/lib/analytics/posthog';
import BellIcon from '@phosphor/bell-simple.svg';
import BugIcon from '@phosphor/bug.svg';
import BuildingsIcon from '@phosphor/buildings.svg';
+import CalendarIcon from '@phosphor/calendar-blank.svg';
import CpuIcon from '@phosphor/cpu.svg';
import CreditCardIcon from '@phosphor/credit-card.svg';
import DeviceMobileIcon from '@phosphor/device-mobile-speaker.svg';
@@ -25,6 +26,7 @@ import {
botManagement,
DEV_MODE_ENV,
ENABLE_APP_STORE_QR_CODE,
+ enableCalendarScheduling,
enableChatV3Agents,
enableCrm,
enableNotificationSettings,
@@ -142,6 +144,12 @@ export const SETTINGS_TAB_GROUPS: SettingsTabGroup[] = [
icon: BuildingsIcon,
keywords: ['contacts', 'customers', 'deals'],
},
+ {
+ tab: 'Calendar',
+ label: 'Calendar',
+ icon: CalendarIcon,
+ keywords: ['scheduling', 'bookings', 'availability'],
+ },
{
tab: 'Connected',
label: 'Integrations',
@@ -198,6 +206,7 @@ const SETTINGS_TAB_SLUGS: Record<SettingsTab, string> = {
Harness: 'runtimes',
Bots: 'bots',
Team: 'team',
+ Calendar: 'calendar',
Tags: 'tags',
CRM: 'crm',
Connected: 'connections',
@@ -234,6 +243,7 @@ export const settingsSlugToTab = (
* surface a tab the panel won't render.
*/
export const useSettingsTabAvailable = () => {
+ const calendarSchedulingFlag = useFeatureFlag(enableCalendarScheduling);
const botManagementFlag = useFeatureFlag(botManagement);
const chatV3AgentsFlag = useFeatureFlag(enableChatV3Agents);
const crmFlag = useFeatureFlag(enableCrm);
@@ -246,6 +256,8 @@ export const useSettingsTabAvailable = () => {
case 'Account':
case 'Billing':
return true;
+ case 'Calendar':
+ return calendarSchedulingFlag().enabled;
// Issuing and copying a key is desk work, and the mobile sheet has no
// good place for a one-time secret.
case 'API Keys':
diff --git a/apps/web/src/lib/service-clients/service-calendar/generated/schemas/createCalendarEventRequest.ts b/apps/web/src/lib/service-clients/service-calendar/generated/schemas/createCalendarEventRequest.ts
index 30f43b2c3a..75c8cf19e3 100644
--- a/apps/web/src/lib/service-clients/service-calendar/generated/schemas/createCalendarEventRequest.ts
+++ b/apps/web/src/lib/service-clients/service-calendar/generated/schemas/createCalendarEventRequest.ts
@@ -9,6 +9,7 @@ import type { CreateCalendarEventRequestCalendarId } from './createCalendarEvent
import type { CreateCalendarEventRequestConference } from './createCalendarEventRequestConference';
import type { CreateCalendarEventRequestDescription } from './createCalendarEventRequestDescription';
import type { CreateCalendarEventRequestEmailLinkId } from './createCalendarEventRequestEmailLinkId';
+import type { CreateCalendarEventRequestIdempotencyKey } from './createCalendarEventRequestIdempotencyKey';
import type { CreateCalendarEventRequestLocation } from './createCalendarEventRequestLocation';
import type { CreateCalendarEventRequestOutOfOffice } from './createCalendarEventRequestOutOfOffice';
import type { CreateCalendarEventRequestReminders } from './createCalendarEventRequestReminders';
@@ -31,6 +32,8 @@ inbox default. */
/** Connected inbox whose primary calendar receives the event; defaults
to the requester's primary inbox. */
emailLinkId?: CreateCalendarEventRequestEmailLinkId;
+ /** Stable retry identity, scoped to the authenticated organizer. */
+ idempotencyKey?: CreateCalendarEventRequestIdempotencyKey;
/** Optional location label. */
location?: CreateCalendarEventRequestLocation;
outOfOffice?: CreateCalendarEventRequestOutOfOffice;
diff --git a/apps/web/src/lib/service-clients/service-calendar/generated/schemas/createCalendarEventRequestIdempotencyKey.ts b/apps/web/src/lib/service-clients/service-calendar/generated/schemas/createCalendarEventRequestIdempotencyKey.ts
new file mode 100644
index 0000000000..370e8c267b
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-calendar/generated/schemas/createCalendarEventRequestIdempotencyKey.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * calendar_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Stable retry identity, scoped to the authenticated organizer.
+ */
+export type CreateCalendarEventRequestIdempotencyKey = string | null;
diff --git a/apps/web/src/lib/service-clients/service-calendar/generated/schemas/index.ts b/apps/web/src/lib/service-clients/service-calendar/generated/schemas/index.ts
index d0f85cc680..50c757549f 100644
--- a/apps/web/src/lib/service-clients/service-calendar/generated/schemas/index.ts
+++ b/apps/web/src/lib/service-clients/service-calendar/generated/schemas/index.ts
@@ -37,6 +37,7 @@ export * from './createCalendarEventRequestCalendarId';
export * from './createCalendarEventRequestConference';
export * from './createCalendarEventRequestDescription';
export * from './createCalendarEventRequestEmailLinkId';
+export * from './createCalendarEventRequestIdempotencyKey';
export * from './createCalendarEventRequestLocation';
export * from './createCalendarEventRequestOutOfOffice';
export * from './createCalendarEventRequestReminders';
diff --git a/apps/web/src/lib/service-clients/service-calendar/openapi.json b/apps/web/src/lib/service-clients/service-calendar/openapi.json
index 364c977d19..6a807ef493 100644
--- a/apps/web/src/lib/service-clients/service-calendar/openapi.json
+++ b/apps/web/src/lib/service-clients/service-calendar/openapi.json
@@ -768,6 +768,11 @@
"format": "uuid",
"description": "Connected inbox whose primary calendar receives the event; defaults\nto the requester's primary inbox."
},
+ "idempotencyKey": {
+ "type": ["string", "null"],
+ "format": "uuid",
+ "description": "Stable retry identity, scoped to the authenticated organizer."
+ },
"location": {
"type": ["string", "null"],
"description": "Optional location label."
diff --git a/apps/web/src/lib/service-clients/service-email/scheduling.ts b/apps/web/src/lib/service-clients/service-email/scheduling.ts
new file mode 100644
index 0000000000..e32ff1d262
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-email/scheduling.ts
@@ -0,0 +1,92 @@
+import type {
+ Booking,
+ BookingAttendance,
+ BookingReceipt,
+ BookingRequest,
+ PublicProfile,
+ SchedulingProfile,
+} from '@app/features/scheduling/core/types';
+import { SERVER_HOSTS } from '@core/constant/servers';
+import { fetchWithToken } from '@core/util/fetchWithToken';
+import { safeFetch } from '@core/util/safeFetch';
+
+const host = `${SERVER_HOSTS['calendar-service']}/scheduling`;
+const scope = (teamId?: string) =>
+ teamId ? `?teamId=${encodeURIComponent(teamId)}` : '';
+const json = (body: unknown) => ({
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify(body),
+});
+
+export const schedulingClient = {
+ settings: (teamId?: string) =>
+ fetchWithToken<{ profile: SchedulingProfile }>(
+ `${host}/settings${scope(teamId)}`
+ ),
+ save: (profile: SchedulingProfile, teamId?: string) =>
+ fetchWithToken<{ profile: SchedulingProfile }>(
+ `${host}/settings${scope(teamId)}`,
+ { method: 'PUT', ...json(profile) }
+ ),
+ bookings: (teamId?: string, range?: { from: string; to: string }) => {
+ const query = new URLSearchParams();
+ if (teamId) query.set('teamId', teamId);
+ if (range) {
+ query.set('from', range.from);
+ query.set('to', range.to);
+ }
+ return fetchWithToken<{ bookings: Booking[] }>(`${host}/bookings?${query}`);
+ },
+ setAttendance: (id: string, attendance: BookingAttendance) =>
+ fetchWithToken<{ booking: Booking }>(
+ `${host}/bookings/${encodeURIComponent(id)}/attendance`,
+ { method: 'POST', ...json({ attendance }) }
+ ),
+ manage: (id: string) =>
+ fetchWithToken<BookingReceipt>(
+ `${host}/bookings/${encodeURIComponent(id)}/manage`
+ ),
+ approve: (id: string) =>
+ fetchWithToken<{ booking: Booking }>(
+ `${host}/bookings/${encodeURIComponent(id)}/approve`,
+ { method: 'POST' }
+ ),
+ cancel: (id: string) =>
+ fetchWithToken<{ booking: Booking }>(
+ `${host}/bookings/${encodeURIComponent(id)}/cancel`,
+ { method: 'POST' }
+ ),
+ profile: (id: string) =>
+ safeFetch<{ profile: PublicProfile }>(
+ `${host}/public/${encodeURIComponent(id)}`
+ ),
+ slots: (profileId: string, eventId: string, date: string, timeZone: string) =>
+ safeFetch<{ slots: { startsAt: string; endsAt: string }[] }>(
+ `${host}/public/${encodeURIComponent(profileId)}/${encodeURIComponent(eventId)}/slots?date=${encodeURIComponent(date)}&timeZone=${encodeURIComponent(timeZone)}`
+ ),
+ book: (profileId: string, eventId: string, request: BookingRequest) =>
+ safeFetch<BookingReceipt>(
+ `${host}/public/${encodeURIComponent(profileId)}/${encodeURIComponent(eventId)}/book`,
+ { method: 'POST', ...json(request) }
+ ),
+ receipt: (id: string, token: string) =>
+ safeFetch<BookingReceipt>(
+ `${host}/public/bookings/${encodeURIComponent(id)}`,
+ { headers: { Authorization: `Bearer ${token}` } }
+ ),
+ replacementSlots: (id: string, token: string, date: string) =>
+ safeFetch<{ slots: { startsAt: string; endsAt: string }[] }>(
+ `${host}/public/bookings/${encodeURIComponent(id)}/slots?date=${encodeURIComponent(date)}`,
+ { headers: { Authorization: `Bearer ${token}` } }
+ ),
+ reschedule: (id: string, token: string, startsAt: string) =>
+ safeFetch<BookingReceipt>(
+ `${host}/public/bookings/${encodeURIComponent(id)}/reschedule`,
+ { method: 'POST', ...json({ token, startsAt }) }
+ ),
+ cancelPublic: (id: string, token: string) =>
+ safeFetch<{ booking: Booking }>(
+ `${host}/public/bookings/${encodeURIComponent(id)}/cancel`,
+ { method: 'POST', ...json({ token }) }
+ ),
+};
diff --git a/apps/web/src/routes/Root.tsx b/apps/web/src/routes/Root.tsx
index 0467ca5af9..bfae54afd7 100644
--- a/apps/web/src/routes/Root.tsx
+++ b/apps/web/src/routes/Root.tsx
@@ -1,5 +1,5 @@
import { DEFAULT_ROUTE } from '@app/constants/defaultRoute';
-import { ROUTER_BASE } from '@app/constants/routerBase';
+import { ROUTER_BASE, ROUTER_BASE_CONCAT } from '@app/constants/routerBase';
import { makeEmailAuthComponents } from '@app/features/auth/EmailAuth';
import { Login } from '@app/features/auth/Login';
import { MobileAuthWelcome } from '@app/features/auth/mobile-onboarding/MobileAuthWelcome';
@@ -125,6 +125,10 @@ import {
Show,
} from 'solid-js';
import { useReminderAlerts } from '../features/reminders/reminder-alerts';
+import {
+ BookingReceiptPage,
+ PublicBookingPage,
+} from '../features/scheduling/public-booking';
import { BasePathComponent } from './BasePath';
import { TaskRoute } from './TaskRoute';
@@ -236,6 +240,8 @@ function OnboardingRoute() {
}
const ROUTES: RouteDefinition[] = [
+ { path: '/book/:profile/:slug?', component: PublicBookingPage },
+ { path: '/booking/:id', component: BookingReceiptPage },
{ path: '/meet/*path', component: MeetingRouter },
{
path: '/task-slug/:taskSlug',
@@ -530,16 +536,33 @@ function InitialInteractiveOnboardingModal() {
);
}
-/** Meeting links have a focused shell and never enter app onboarding. */
+/** Meeting and booking links have a focused shell and skip app onboarding. */
function AppRouteLayout(props: RouteSectionProps) {
const location = useLocation();
return (
- <IncomingMeetingInvitationsProvider>
- <Show when={!isMeetingPath(location.pathname)} fallback={props.children}>
- <Layout {...props} />
- <InitialInteractiveOnboardingModal />
- </Show>
- </IncomingMeetingInvitationsProvider>
+ <Show
+ when={
+ !(
+ location.pathname.startsWith(`${ROUTER_BASE_CONCAT}book/`) ||
+ location.pathname.startsWith(`${ROUTER_BASE_CONCAT}booking/`)
+ )
+ }
+ fallback={
+ <div class="h-dvh overflow-y-auto bg-page text-ink">
+ {props.children}
+ </div>
+ }
+ >
+ <IncomingMeetingInvitationsProvider>
+ <Show
+ when={!isMeetingPath(location.pathname)}
+ fallback={props.children}
+ >
+ <Layout {...props} />
+ <InitialInteractiveOnboardingModal />
+ </Show>
+ </IncomingMeetingInvitationsProvider>
+ </Show>
);
}
diff --git a/apps/web/vitest.config.ts b/apps/web/vitest.config.ts
index 777cc7c2cc..c9a93464c7 100644
--- a/apps/web/vitest.config.ts
+++ b/apps/web/vitest.config.ts
@@ -30,6 +30,13 @@ export default defineConfig({
test: {
exclude: [...configDefaults.exclude],
projects: [
+ {
+ extends: './src/features/scheduling/vitest.config.ts',
+ test: {
+ include: ['src/features/scheduling/**/*.{test,spec}.{ts,tsx}'],
+ name: 'scheduling',
+ },
+ },
'../../packages/email-renderer/vitest.config.ts',
'../../packages/collaboration/vitest.collab.config.ts',
'../../packages/collaboration/vitest.transport.config.ts',
@@ -206,6 +213,7 @@ export default defineConfig({
exclude: [
...configDefaults.exclude,
'src/components/view-shell/**/*',
+ 'src/features/scheduling/**/*',
'src/features/{theme,block-channel,block-call,block-pr,block-md,channel,notifications,block-email,email-message,email-thread,email-compose}/**/*',
],
include: [
diff --git a/crates/calendar_events/src/domain/models.rs b/crates/calendar_events/src/domain/models.rs
index 5a677e017f..e8cdbfbec0 100644
--- a/crates/calendar_events/src/domain/models.rs
+++ b/crates/calendar_events/src/domain/models.rs
@@ -1067,6 +1067,8 @@ pub struct CalendarAttendeeInput {
/// User-supplied fields for a new provider event.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CalendarEventDraft {
+ /// Optional stable creation identity for callers with durable retry state.
+ pub idempotency_key: Option<Uuid>,
/// Display title.
pub title: String,
/// Optional event body.
@@ -1656,3 +1658,9 @@ pub struct ProviderCalendar {
/// Default reminders applied to events that keep `useDefault`.
pub default_reminders: Vec<EventReminderOverride>,
}
+
+/// Stable organizer-scoped identifier for a retryable event creation.
+/// Hex UUIDs satisfy the Google Calendar base32hex event-ID alphabet.
+pub fn creation_provider_id(key: Uuid, owner: &str) -> String {
+ Uuid::new_v5(&key, owner.as_bytes()).simple().to_string()
+}
diff --git a/crates/calendar_events/src/domain/mutations.rs b/crates/calendar_events/src/domain/mutations.rs
index 4116f67500..2b7297ba8a 100644
--- a/crates/calendar_events/src/domain/mutations.rs
+++ b/crates/calendar_events/src/domain/mutations.rs
@@ -796,3 +796,50 @@ fn internal(error: rootcause::Report) -> CalendarMutationError {
#[cfg(test)]
mod test;
+
+impl<R, G, T, B, N> super::ports::CalendarCreationRecoveryService
+ for CalendarMutationServiceImpl<R, G, T, B, N>
+where
+ R: CalendarRepository,
+ G: GoogleCalendarMutationProvider,
+ T: CalendarAccessTokenProvider,
+ B: MacroEventBroker,
+ N: CalendarRefreshNotifier,
+{
+ #[tracing::instrument(skip(self, requester_id), err)]
+ async fn delete_created_event(
+ &self,
+ requester_id: &str,
+ calendar_id: Uuid,
+ creation_key: Uuid,
+ ) -> Result<(), CalendarMutationError> {
+ // Resolve current access rather than interpreting an inaccessible canonical event as gone.
+ let target = self
+ .repository
+ .get_creation_target(requester_id, None, Some(calendar_id))
+ .await
+ .map_err(internal)?
+ .ok_or(CalendarMutationError::NoWritableCalendar)?;
+ if target.is_read_only {
+ return Err(CalendarMutationError::ReadOnly);
+ }
+ let access_token = self.fetch_token(&target.token_identity).await?;
+ let provider_id = super::models::creation_provider_id(creation_key, &target.owner_id);
+ self.provider
+ .delete_event(
+ &access_token,
+ &target.google_target(OccurrenceRange::maintenance_horizon(Utc::now())),
+ &provider_id,
+ )
+ .await
+ .map_err(provider_error)?;
+ let retired = self
+ .repository
+ .remove_google_source(target.account_id, target.calendar_id, &provider_id)
+ .await
+ .map_err(|error| CalendarMutationError::PersistFailed(format!("{error:?}")))?;
+ self.announce_retirements(&target.owner_id, target.email_link_id, retired)
+ .await;
+ Ok(())
+ }
+}
diff --git a/crates/calendar_events/src/domain/mutations/test.rs b/crates/calendar_events/src/domain/mutations/test.rs
index 2212c59a69..216ce5760d 100644
--- a/crates/calendar_events/src/domain/mutations/test.rs
+++ b/crates/calendar_events/src/domain/mutations/test.rs
@@ -118,6 +118,7 @@ fn echo_upsert(target_owner: &str) -> CalendarEventUpsert {
fn draft() -> CalendarEventDraft {
CalendarEventDraft {
+ idempotency_key: None,
title: "New event".to_string(),
description: None,
location: None,
@@ -2454,6 +2455,55 @@ async fn disconnecting_an_inbox_the_requester_does_not_own_is_not_found() {
assert!(calls.lock().unwrap().is_empty());
}
+#[tokio::test]
+async fn keyed_deletion_replays_after_the_canonical_event_has_disappeared() {
+ use crate::domain::ports::CalendarCreationRecoveryService;
+ let target = creation_target(false);
+ let calendar_id = target.calendar_id;
+ let key = Uuid::now_v7();
+ let expected = crate::domain::models::creation_provider_id(key, &target.owner_id);
+ let repo = FakeRepo {
+ creation_target: Some(target),
+ mutation_target: None,
+ ..Default::default()
+ };
+ let removed = repo.removed_sources.clone();
+ let provider = FakeProvider::new(FakeProviderBehavior::Echo);
+ let calls = provider.calls.clone();
+ let svc = service(repo, provider, FakeTokens::ok());
+ svc.delete_created_event("macro|user", calendar_id, key)
+ .await
+ .unwrap();
+ svc.delete_created_event("macro|user", calendar_id, key)
+ .await
+ .unwrap();
+ assert_eq!(
+ calls.lock().unwrap().as_slice(),
+ [format!("delete:{expected}"), format!("delete:{expected}")]
+ );
+ assert_eq!(removed.lock().unwrap().len(), 2);
+}
+
+#[tokio::test]
+async fn keyed_deletion_requires_current_writable_calendar_access() {
+ use crate::domain::ports::CalendarCreationRecoveryService;
+ for target in [None, Some(creation_target(true))] {
+ let repo = FakeRepo {
+ creation_target: target,
+ ..Default::default()
+ };
+ let provider = FakeProvider::new(FakeProviderBehavior::Echo);
+ let calls = provider.calls.clone();
+ assert!(
+ service(repo, provider, FakeTokens::ok())
+ .delete_created_event("macro|user", Uuid::now_v7(), Uuid::now_v7())
+ .await
+ .is_err()
+ );
+ assert!(calls.lock().unwrap().is_empty());
+ }
+}
+
#[tokio::test]
async fn rsvp_uses_only_the_selected_owned_address_for_both_scopes() {
for scope in [
diff --git a/crates/calendar_events/src/domain/ports.rs b/crates/calendar_events/src/domain/ports.rs
index 24f873809e..553e9de2b8 100644
--- a/crates/calendar_events/src/domain/ports.rs
+++ b/crates/calendar_events/src/domain/ports.rs
@@ -945,3 +945,15 @@ pub trait CalendarReminderDispatchQueue: Send + Sync + 'static {
receipt_handle: &str,
) -> impl Future<Output = Result<(), Report>> + Send;
}
+
+/// Recovery capability for callers that persist a creation key and its target calendar.
+pub trait CalendarCreationRecoveryService: CalendarMutationService {
+ /// Delete a keyed event even if a previous deletion already retired its local projection.
+ /// The current requester must still own a writable grant to the pinned calendar.
+ fn delete_created_event(
+ &self,
+ requester_id: &str,
+ calendar_id: Uuid,
+ creation_key: Uuid,
+ ) -> impl Future<Output = Result<(), CalendarMutationError>> + Send;
+}
diff --git a/crates/calendar_events/src/inbound/mutation_router.rs b/crates/calendar_events/src/inbound/mutation_router.rs
index 94775859dc..fecc7bbb37 100644
--- a/crates/calendar_events/src/inbound/mutation_router.rs
+++ b/crates/calendar_events/src/inbound/mutation_router.rs
@@ -114,6 +114,8 @@ impl From<CalendarAttendeeInputBody> for CalendarAttendeeInput {
#[derive(Debug, Deserialize, utoipa::ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct CreateCalendarEventRequest {
+ /// Stable retry identity, scoped to the authenticated organizer.
+ pub idempotency_key: Option<Uuid>,
/// Exact calendar to create the event on; takes precedence over the
/// inbox default.
pub calendar_id: Option<Uuid>,
@@ -421,6 +423,7 @@ where
Auth: MacroAuthorizationService,
{
let draft = CalendarEventDraft {
+ idempotency_key: request.idempotency_key,
title: request.title,
description: request.description,
location: request.location,
diff --git a/crates/calendar_events/src/inbound/toolset/create_calendar_event.rs b/crates/calendar_events/src/inbound/toolset/create_calendar_event.rs
index e318114c1d..d9f7839a39 100644
--- a/crates/calendar_events/src/inbound/toolset/create_calendar_event.rs
+++ b/crates/calendar_events/src/inbound/toolset/create_calendar_event.rs
@@ -170,6 +170,7 @@ where
}
};
let draft = CalendarEventDraft {
+ idempotency_key: None,
title: self.title.clone(),
description: self.description.clone(),
location: self.location.clone(),
diff --git a/crates/calendar_events/src/outbound/calendar_service_mutations.rs b/crates/calendar_events/src/outbound/calendar_service_mutations.rs
index 3b681d721e..9421765df4 100644
--- a/crates/calendar_events/src/outbound/calendar_service_mutations.rs
+++ b/crates/calendar_events/src/outbound/calendar_service_mutations.rs
@@ -177,6 +177,7 @@ fn create_body(
"reminders": draft.reminders,
"conference": draft.conference,
"outOfOffice": draft.out_of_office,
+ "idempotencyKey": draft.idempotency_key,
})
}
diff --git a/crates/calendar_events/src/outbound/calendar_service_mutations/test.rs b/crates/calendar_events/src/outbound/calendar_service_mutations/test.rs
index 1e6d93bb8a..a36687f8e1 100644
--- a/crates/calendar_events/src/outbound/calendar_service_mutations/test.rs
+++ b/crates/calendar_events/src/outbound/calendar_service_mutations/test.rs
@@ -18,6 +18,7 @@ use crate::inbound::mutation_router::{
fn sample_draft() -> CalendarEventDraft {
CalendarEventDraft {
+ idempotency_key: None,
title: "Standup".to_string(),
description: Some("Daily".to_string()),
location: None,
diff --git a/crates/calendar_events/src/outbound/google.rs b/crates/calendar_events/src/outbound/google.rs
index be51d34b8f..4539921d11 100644
--- a/crates/calendar_events/src/outbound/google.rs
+++ b/crates/calendar_events/src/outbound/google.rs
@@ -53,6 +53,7 @@ impl GoogleRequestGate for UnmeteredGate {
pub struct GoogleCalendarClient<G = UnmeteredGate> {
client: Client,
gate: G,
+ api_base: String,
}
impl GoogleCalendarClient<UnmeteredGate> {
@@ -61,6 +62,7 @@ impl GoogleCalendarClient<UnmeteredGate> {
Self {
client,
gate: UnmeteredGate,
+ api_base: GOOGLE_CALENDAR_API.into(),
}
}
}
@@ -68,7 +70,11 @@ impl GoogleCalendarClient<UnmeteredGate> {
impl<G: GoogleRequestGate> GoogleCalendarClient<G> {
/// Construct a client whose requests must pass the supplied quota gate.
pub fn with_gate(client: Client, gate: G) -> Self {
- Self { client, gate }
+ Self {
+ client,
+ gate,
+ api_base: GOOGLE_CALENDAR_API.into(),
+ }
}
async fn calendars(
@@ -82,7 +88,7 @@ impl<G: GoogleRequestGate> GoogleCalendarClient<G> {
self.gate.acquire(email_link_id).await?;
let mut request = self
.client
- .get(format!("{GOOGLE_CALENDAR_API}/users/me/calendarList"))
+ .get(format!("{}/users/me/calendarList", self.api_base))
.bearer_auth(access_token)
.query(&[("maxResults", "250"), ("minAccessRole", "reader")]);
if let Some(token) = &page_token {
@@ -114,7 +120,7 @@ impl<G: GoogleRequestGate> GoogleCalendarClient<G> {
self.gate.acquire(email_link_id).await?;
let mut request = self
.client
- .get(format!("{GOOGLE_CALENDAR_API}/calendars/{calendar}/events"))
+ .get(format!("{}/calendars/{calendar}/events", self.api_base))
.bearer_auth(access_token)
.query(&[
("maxResults", "2500".to_string()),
@@ -156,7 +162,7 @@ impl<G: GoogleRequestGate> GoogleCalendarClient<G> {
self.gate.acquire(email_link_id).await?;
let mut request = self
.client
- .get(format!("{GOOGLE_CALENDAR_API}/calendars/{calendar}/events"))
+ .get(format!("{}/calendars/{calendar}/events", self.api_base))
.bearer_auth(access_token)
.query(&[
("maxResults", "2500"),
@@ -209,7 +215,8 @@ impl<G: GoogleRequestGate> GoogleCalendarClient<G> {
let response = self
.client
.get(format!(
- "{GOOGLE_CALENDAR_API}/calendars/{calendar}/events/{event}"
+ "{}/calendars/{calendar}/events/{event}",
+ self.api_base
))
.bearer_auth(access_token)
.send()
@@ -248,7 +255,7 @@ impl<G: GoogleRequestGate> GoogleCalendarClient<G> {
self.gate.acquire(email_link_id).await?;
let mut request = self
.client
- .get(format!("{GOOGLE_CALENDAR_API}/calendars/{calendar}/events"))
+ .get(format!("{}/calendars/{calendar}/events", self.api_base))
.bearer_auth(access_token)
.query(&[
("maxResults", "2500"),
@@ -287,7 +294,8 @@ impl<G: GoogleRequestGate> GoogleCalendarClient<G> {
let mut request = self
.client
.get(format!(
- "{GOOGLE_CALENDAR_API}/calendars/{calendar}/events/{event}/instances"
+ "{}/calendars/{calendar}/events/{event}/instances",
+ self.api_base
))
.bearer_auth(access_token)
.query(&[
@@ -577,7 +585,8 @@ impl<G: GoogleRequestGate> GoogleCalendarProvider for GoogleCalendarClient<G> {
GoogleRequestKind::Mutation,
self.client
.post(format!(
- "{GOOGLE_CALENDAR_API}/calendars/{calendar}/events/watch"
+ "{}/calendars/{calendar}/events/watch",
+ self.api_base
))
.bearer_auth(access_token)
.json(&serde_json::json!({
@@ -924,7 +933,8 @@ impl<G: GoogleRequestGate> GoogleCalendarClient<G> {
let response = self
.client
.delete(format!(
- "{GOOGLE_CALENDAR_API}/calendars/{calendar}/events/{event}"
+ "{}/calendars/{calendar}/events/{event}",
+ self.api_base
))
.bearer_auth(access_token)
.query(&[SEND_UPDATES])
@@ -991,7 +1001,8 @@ impl<G: GoogleRequestGate> GoogleCalendarClient<G> {
let request = self
.client
.patch(format!(
- "{GOOGLE_CALENDAR_API}/calendars/{calendar}/events/{event}"
+ "{}/calendars/{calendar}/events/{event}",
+ self.api_base
))
.bearer_auth(access_token)
.query(&[SEND_UPDATES]);
@@ -1033,21 +1044,69 @@ impl<G: GoogleRequestGate> GoogleCalendarMutationProvider for GoogleCalendarClie
draft: &CalendarEventDraft,
) -> Result<CalendarEventUpsert, GoogleProviderError> {
let calendar = urlencoding::encode(&target.provider_calendar_id);
- let body = draft_body(draft);
+ let mut body = draft_body(draft);
+ // Scope caller keys to the organizer. Hex UUIDs are valid Google base32hex IDs.
+ let provider_id = draft
+ .idempotency_key
+ .map(|key| crate::domain::models::creation_provider_id(key, &target.owner_id));
+ if let Some(id) = &provider_id {
+ body["id"] = serde_json::json!(id);
+ if let Some(existing) = self
+ .event(
+ access_token,
+ target.email_link_id,
+ &target.provider_calendar_id,
+ id,
+ )
+ .await?
+ {
+ return self
+ .mutation_readback(access_token, target, existing)
+ .await?
+ .ok_or_else(|| {
+ GoogleProviderError::new(
+ GoogleProviderErrorKind::Permanent,
+ "The reserved calendar event was removed",
+ )
+ });
+ }
+ }
self.gate.acquire(target.email_link_id).await?;
let request = self
.client
- .post(format!("{GOOGLE_CALENDAR_API}/calendars/{calendar}/events"))
+ .post(format!("{}/calendars/{calendar}/events", self.api_base))
.bearer_auth(access_token)
.query(&[SEND_UPDATES]);
- let created: GoogleEvent = send_google(
- GoogleRequestKind::Mutation,
- with_conference_query(request, &body).json(&body),
- )
- .await?;
- // The insert already happened and carries no idempotency key, so a
- // readback miss must not surface as retryable: a client retry would
- // POST a duplicate event.
+ let response = with_conference_query(request, &body)
+ .json(&body)
+ .send()
+ .await
+ .map_err(provider_transport_error)?;
+ let status = response.status();
+ let created: GoogleEvent = if status == StatusCode::CONFLICT && provider_id.is_some() {
+ self.event(
+ access_token,
+ target.email_link_id,
+ &target.provider_calendar_id,
+ provider_id.as_deref().unwrap_or_default(),
+ )
+ .await?
+ .ok_or_else(|| {
+ GoogleProviderError::new(
+ GoogleProviderErrorKind::Transient,
+ "Calendar creation is still converging",
+ )
+ })?
+ } else if status.is_success() {
+ response.json().await.map_err(provider_transport_error)?
+ } else {
+ let body = response.text().await.map_err(provider_transport_error)?;
+ return Err(provider_response_error(
+ GoogleRequestKind::Mutation,
+ status,
+ &body,
+ ));
+ };
self.mutation_readback(access_token, target, created)
.await?
.ok_or_else(|| {
@@ -1336,7 +1395,7 @@ impl<G: GoogleRequestGate> GoogleCalendarMutationProvider for GoogleCalendarClie
self.gate.acquire(email_link_id).await?;
let response = self
.client
- .post(format!("{GOOGLE_CALENDAR_API}/channels/stop"))
+ .post(format!("{}/channels/stop", self.api_base))
.bearer_auth(access_token)
.json(&serde_json::json!({
"id": channel_id,
diff --git a/crates/calendar_events/src/outbound/google/test.rs b/crates/calendar_events/src/outbound/google/test.rs
index 7e4bd09038..760badef5c 100644
--- a/crates/calendar_events/src/outbound/google/test.rs
+++ b/crates/calendar_events/src/outbound/google/test.rs
@@ -1008,6 +1008,7 @@ fn mutation_bodies_serialize_reminders_in_google_shape() {
});
let draft = CalendarEventDraft {
+ idempotency_key: None,
title: "New".to_string(),
description: None,
location: None,
@@ -1144,6 +1145,7 @@ fn conference_writes_declare_conference_support() {
#[test]
fn drafts_carry_conference_requests_and_their_parameter() {
let draft = CalendarEventDraft {
+ idempotency_key: None,
title: "Kickoff".to_string(),
description: None,
location: None,
@@ -1176,6 +1178,7 @@ fn drafts_carry_conference_requests_and_their_parameter() {
fn timed_draft(out_of_office: Option<OutOfOfficeProperties>) -> CalendarEventDraft {
CalendarEventDraft {
+ idempotency_key: None,
title: "Away".to_string(),
description: None,
location: None,
@@ -1366,3 +1369,98 @@ fn conference_data_survives_the_raw_payload_round_trip() {
Some("https://meet.google.com/abc-defg-hij")
);
}
+
+#[cfg(feature = "inbound")]
+#[tokio::test]
+async fn keyed_create_recovers_lost_response_and_duplicate_conflict_without_second_insert() {
+ use axum::{
+ Json, Router,
+ extract::State,
+ http::StatusCode,
+ response::IntoResponse,
+ routing::{get, post},
+ };
+ use std::sync::{
+ Arc, Mutex,
+ atomic::{AtomicUsize, Ordering},
+ };
+ #[derive(Clone)]
+ struct Remote {
+ event: Arc<Mutex<Option<serde_json::Value>>>,
+ posts: Arc<AtomicUsize>,
+ insert_status: StatusCode,
+ }
+ async fn read(State(s): State<Remote>) -> axum::response::Response {
+ match s.event.lock().unwrap().clone() {
+ Some(event) => Json(event).into_response(),
+ None => StatusCode::NOT_FOUND.into_response(),
+ }
+ }
+ async fn insert(
+ State(s): State<Remote>,
+ Json(body): Json<serde_json::Value>,
+ ) -> axum::response::Response {
+ s.posts.fetch_add(1, Ordering::SeqCst);
+ let mut event = body;
+ event["iCalUID"] = serde_json::json!("[email protected]");
+ event["created"] = serde_json::json!("2026-07-20T14:00:00Z");
+ event["updated"] = serde_json::json!("2026-07-20T14:00:00Z");
+ *s.event.lock().unwrap() = Some(event);
+ (
+ s.insert_status,
+ Json(serde_json::json!({"error":{"message":"injected uncertain result"}})),
+ )
+ .into_response()
+ }
+ for insert_status in [StatusCode::SERVICE_UNAVAILABLE, StatusCode::CONFLICT] {
+ let remote = Remote {
+ event: Default::default(),
+ posts: Default::default(),
+ insert_status,
+ };
+ let app = Router::new()
+ .route("/calendars/primary/events", post(insert))
+ .route("/calendars/primary/events/{id}", get(read))
+ .with_state(remote.clone());
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let endpoint = format!("http://{}", listener.local_addr().unwrap());
+ let task = tokio::spawn(async move {
+ axum::serve(listener, app).await.unwrap();
+ });
+ let client = GoogleCalendarClient {
+ client: Client::new(),
+ gate: UnmeteredGate,
+ api_base: endpoint,
+ };
+ let target = GoogleCalendarTarget {
+ owner_id: "macro|[email protected]".into(),
+ email_link_id: Uuid::now_v7(),
+ account_id: Uuid::now_v7(),
+ calendar_id: Uuid::now_v7(),
+ provider_calendar_id: "primary".into(),
+ is_read_only: false,
+ range: OccurrenceRange::maintenance_horizon(Utc::now()),
+ };
+ let mut draft = timed_draft(None);
+ draft.idempotency_key = Some(Uuid::now_v7());
+ let first = client.create_event("test-token", &target, &draft).await;
+ assert_eq!(first.is_ok(), insert_status == StatusCode::CONFLICT);
+ client
+ .create_event("test-token", &target, &draft)
+ .await
+ .unwrap();
+ assert_eq!(remote.posts.load(Ordering::SeqCst), 1);
+ let provider_id = remote.event.lock().unwrap().as_ref().unwrap()["id"]
+ .as_str()
+ .unwrap()
+ .to_owned();
+ assert_eq!(
+ provider_id,
+ crate::domain::models::creation_provider_id(
+ draft.idempotency_key.unwrap(),
+ &target.owner_id
+ )
+ );
+ task.abort();
+ }
+}
diff --git a/crates/calendar_scheduling/Cargo.toml b/crates/calendar_scheduling/Cargo.toml
new file mode 100644
index 0000000000..e703069f76
--- /dev/null
+++ b/crates/calendar_scheduling/Cargo.toml
@@ -0,0 +1,34 @@
+[package]
+name = "calendar_scheduling"
+version = "0.1.0"
+edition = "2024"
+publish = false
+
+[features]
+default = []
+postgres = ["dep:sqlx"]
+inbound = ["dep:axum", "dep:macro_authorization"]
+calendar = ["dep:calendar_events", "dep:teams", "dep:macro_user_id"]
+
+[dependencies]
+email_validator = { path = "../email_validator" }
+workspace-hack = { version = "0.1", path = "../workspace-hack" }
+chrono = { workspace = true }
+chrono-tz = { workspace = true }
+serde = { workspace = true }
+serde_json = { workspace = true }
+uuid = { workspace = true }
+thiserror = { workspace = true }
+rootcause = { workspace = true }
+tracing = { workspace = true }
+axum = { workspace = true, optional = true }
+sqlx = { workspace = true, optional = true }
+macro_authorization = { path = "../macro_authorization", default-features = false, features = ["axum"], optional = true }
+calendar_events = { path = "../calendar_events", optional = true }
+teams = { path = "../teams", default-features = false, features = ["ports"], optional = true }
+macro_user_id = { path = "../macro_user_id", optional = true }
+
+[dev-dependencies]
+model_user = { path = "../model_user" }
+reqwest = { workspace = true }
+tokio = { workspace = true }
diff --git a/crates/calendar_scheduling/README.md b/crates/calendar_scheduling/README.md
new file mode 100644
index 0000000000..bd2f0b98ed
--- /dev/null
+++ b/crates/calendar_scheduling/README.md
@@ -0,0 +1,76 @@
+# Calendar scheduling
+
+Personal and Macro-team booking pages, event types, weekly schedules/date overrides,
+collective and round-robin hosts, booking limits/buffers, custom questions, host
+legacy approval management, cancellation, rescheduling, and recorded attendance. `domain::Service` owns
+authorization and booking policy. HTTP adapters expose public presentation types and authenticate
+management requests; PostgreSQL and the existing calendar/team domain ports supply
+storage and provider operations.
+
+## Integration
+
+Apply MacroDB migrations `20260918164303_calendar_scheduling.sql` and
+`20260918175703_scheduling_recovery.sql`, then deploy the
+updated calendar service with its existing `CALENDAR_SYNC_ENABLED` setting enabled.
+The migration uses PostgreSQL multiranges (PostgreSQL 14+) and `btree_gist` for
+atomic host conflict exclusion. Each host needs a connected, writable primary
+calendar with calendar sync ready. All connected calendars are checked for busy
+time. Invitations and Google Meet links use the existing calendar mutation service.
+Deployed invitations include the private cancellation/rescheduling URL.
+
+The web entry points are Settings → Calendar, the calendar header shortcuts,
+`/app/book/:profile/:slug?`, and `/app/booking/:id#token`. Existing Macro team
+owners/admins can manage team scheduling; members have read access. Current
+membership is checked again when booking or approving. Booking capabilities travel
+in request headers/bodies, and scheduling responses disable caching.
+
+Event types start paused. Public pages show enabled types only. Team availability
+uses the selected shared weekly schedule plus every selected host's busy calendar
+and personal default availability (including that host's time zone and date overrides).
+Personal profiles without an explicit default use their first schedule; hosts who have
+not configured personal availability use the team schedule.
+Round robin assigns one available host, favoring the least assigned host. Public
+slots are displayed on the visitor's local date. Existing bookings retain their
+original event/schedule snapshots for management after a link is edited or removed.
+
+Booking queries accept a half-open `from`/`to` range of start times, up to 733 days
+(room for two full comparison years across daylight-saving changes). They return the
+complete range or a clear error when more than 5,000 records match. The management UI starts with a 61-day range and exposes date controls so large profiles can narrow it; round-robin balancing uses aggregate host counts and is independent of this list limit. Insights must not
+interpret failures as an empty dataset. Reschedule counts increase only after a
+successful move; old records default to zero, without reconstructing unknown history.
+Attendance defaults to unknown and may be recorded only after a confirmed meeting has
+ended, by a current assigned host or profile administrator. Elapsed confirmed meetings
+can be counted as completed, but this alone is not evidence of attendance.
+
+## Verification
+
+- `cargo test -p calendar_scheduling --features postgres,inbound` with `DATABASE_URL` pointing
+ to a disposable PostgreSQL server and `SQLX_OFFLINE` unset. The SQLx integration
+ tests create isolated test databases and apply the actual scheduling migration.
+- `SQLX_OFFLINE=true cargo check -p calendar_service` checks production composition.
+- In `apps/web`, `bun --bun x vitest run --config src/features/scheduling/vitest.config.ts`
+ checks client validation and request races/retries.
+- `/src/features/scheduling/browser-test/index.html` on the Vite dev server mounts
+ the real scheduling components with injected sample data. It never sends invitations
+ or writes hosted data; it is separate from production routes.
+
+## Operational behavior
+
+A booking holds its host reservations before calling the provider. An uncertain
+provider write leaves the booking `failed` (or `processing` after a process crash),
+with reservations retained to avoid duplicate meetings. Durable operation intents, stable
+provider creation IDs, pinned calendars, and version-fenced retries recover these states after
+five minutes. The calendar-service worker runs every 15 seconds; repeated failures back off and
+emit operator-attention errors. Keyed deletion works even after local calendar projection
+retirement. Completion-persistence failures still return the durable private receipt. Rescheduling reserves the old and new intervals until the provider
+accepts the update, then releases the old interval. Calendar projections without a
+source time zone for all-day events conservatively block all possible UTC offsets.
+
+This change does not include payments, workflow automation, routing forms, advanced
+analytics, or webhooks. Core booking insights are derived from authorized booking records.
+New approval-only configurations and bookings are disabled until standalone host/guest
+notifications exist. Existing pending records remain manageable. Confirmed meetings receive
+provider calendar invitations. Shared PostgreSQL budgets cap public availability and booking
+requests per profile; all booking changes use a monotonic revision to prevent stale edits.
+See `docs/CALENDAR_SCHEDULING_V1.md` for rollout, rollback and monitoring queries.
+It does not deploy the backend or apply migrations to shared databases.
diff --git a/crates/calendar_scheduling/src/domain.rs b/crates/calendar_scheduling/src/domain.rs
new file mode 100644
index 0000000000..8a5c37bfc8
--- /dev/null
+++ b/crates/calendar_scheduling/src/domain.rs
@@ -0,0 +1,7 @@
+//! Scheduling policy and capability contracts.
+pub mod availability;
+pub mod models;
+pub mod ports;
+pub mod service;
+
+mod recovery;
diff --git a/crates/calendar_scheduling/src/domain/availability.rs b/crates/calendar_scheduling/src/domain/availability.rs
new file mode 100644
index 0000000000..f6cf8a1260
--- /dev/null
+++ b/crates/calendar_scheduling/src/domain/availability.rs
@@ -0,0 +1,252 @@
+//! Deterministic, timezone-aware slot generation and configuration validation.
+use super::models::*;
+use chrono::{DateTime, Datelike, Duration, NaiveDate, NaiveTime, Offset, TimeZone, Utc};
+use std::collections::HashSet;
+
+/// Validate all persisted scheduling rules before accepting configuration.
+pub fn validate_profile(profile: &Profile, team: bool) -> Result<(), Error> {
+ if profile.name.trim().is_empty()
+ || profile.name.len() > 200
+ || profile.description.len() > 4000
+ || profile.schedules.len() > 30
+ || profile.event_types.len() > 100
+ {
+ return invalid("Profile fields exceed their limits");
+ }
+ let mut schedule_ids = HashSet::new();
+ for schedule in &profile.schedules {
+ if !schedule_ids.insert(schedule.id)
+ || schedule.name.trim().is_empty()
+ || schedule.name.len() > 100
+ || schedule.weekly.len() != 7
+ || schedule.overrides.len() > 366
+ {
+ return invalid("Invalid availability schedule");
+ }
+ let mut days = HashSet::new();
+ for day in &schedule.weekly {
+ if day.day > 6 || !days.insert(day.day) {
+ return invalid("Each weekday must appear exactly once");
+ }
+ validate_windows(&day.windows)?;
+ }
+ let mut dates = HashSet::new();
+ for date in &schedule.overrides {
+ if !dates.insert(date.date) {
+ return invalid("Only one override is allowed per date");
+ }
+ validate_windows(&date.windows)?;
+ }
+ }
+ if profile
+ .default_schedule_id
+ .is_some_and(|id| !schedule_ids.contains(&id))
+ {
+ return invalid("Choose an existing default availability schedule");
+ }
+ let mut ids = HashSet::new();
+ let mut slugs = HashSet::new();
+ for event in &profile.event_types {
+ if !ids.insert(event.id)
+ || !slugs.insert(&event.slug)
+ || event.slug.is_empty()
+ || event.slug.len() > 80
+ || event.slug.starts_with('-')
+ || event.slug.ends_with('-')
+ || event.slug.contains("--")
+ || !event
+ .slug
+ .bytes()
+ .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
+ {
+ return invalid("Booking links must have unique lowercase slugs");
+ }
+ if event.title.trim().is_empty()
+ || event.title.len() > 200
+ || event.description.len() > 4000
+ || event.location.len() > 2000
+ || !(5..=480).contains(&event.duration_minutes)
+ || !(5..=480).contains(&event.interval_minutes)
+ || !(1..=365).contains(&event.horizon_days)
+ || event.before_minutes > 10080
+ || event.after_minutes > 10080
+ || event.notice_minutes > 10080
+ || event.daily_limit.is_some_and(|n| !(1..=100).contains(&n))
+ {
+ return invalid("Invalid event duration, booking limits, or text fields");
+ }
+ if !schedule_ids.contains(&event.schedule_id)
+ || event.hosts.is_empty()
+ || event.hosts.len() > 30
+ || event.hosts.iter().collect::<HashSet<_>>().len() != event.hosts.len()
+ {
+ return invalid("Choose an availability schedule and distinct hosts");
+ }
+ if (!team && (event.mode != SchedulingMode::Individual || event.hosts.len() != 1))
+ || (team && event.mode == SchedulingMode::Individual)
+ {
+ return invalid("Scheduling type does not match the profile");
+ }
+ if event.questions.len() > 20
+ || event
+ .questions
+ .iter()
+ .any(|q| q.label.trim().is_empty() || q.label.len() > 500)
+ || event
+ .questions
+ .iter()
+ .map(|q| q.id)
+ .collect::<HashSet<_>>()
+ .len()
+ != event.questions.len()
+ {
+ return invalid("Invalid booking questions");
+ }
+ }
+ Ok(())
+}
+fn invalid<T>(message: &str) -> Result<T, Error> {
+ Err(Error::Invalid(message.into()))
+}
+fn parse_time(value: &str) -> Result<NaiveTime, Error> {
+ if value.len() != 5 {
+ return invalid("Times must use HH:MM");
+ }
+ NaiveTime::parse_from_str(value, "%H:%M").map_err(|_| Error::Invalid("Invalid time".into()))
+}
+fn validate_windows(windows: &[TimeWindow]) -> Result<(), Error> {
+ if windows.len() > 8 {
+ return invalid("At most eight time ranges are allowed per day");
+ }
+ let mut intervals = windows
+ .iter()
+ .map(|w| Ok((parse_time(&w.start)?, parse_time(&w.end)?)))
+ .collect::<Result<Vec<_>, Error>>()?;
+ intervals.sort();
+ for (index, (start, end)) in intervals.iter().enumerate() {
+ if start >= end || (index > 0 && intervals[index - 1].1 > *start) {
+ return invalid("Time ranges must be positive and cannot overlap");
+ }
+ }
+ Ok(())
+}
+
+fn windows_for_date(schedule: &Schedule, date: NaiveDate) -> Option<&[TimeWindow]> {
+ schedule
+ .overrides
+ .iter()
+ .find(|o| o.date == date)
+ .map(|o| o.windows.as_slice())
+ .or_else(|| {
+ schedule
+ .weekly
+ .iter()
+ .find(|d| u32::from(d.day) == date.weekday().num_days_from_sunday())
+ .map(|d| d.windows.as_slice())
+ })
+}
+
+/// Check a team slot against a host's own hours and date overrides in their local zone.
+pub fn schedule_contains(
+ schedule: &Schedule,
+ starts_at: DateTime<Utc>,
+ ends_at: DateTime<Utc>,
+) -> Result<bool, Error> {
+ let start = starts_at.with_timezone(&schedule.time_zone);
+ let end = ends_at.with_timezone(&schedule.time_zone);
+ if start.date_naive() != end.date_naive() {
+ return Ok(false);
+ }
+ for window in windows_for_date(schedule, start.date_naive()).unwrap_or_default() {
+ let window_start = parse_time(&window.start)?;
+ let window_end = parse_time(&window.end)?;
+ if start.time() < window_start || end.time() > window_end {
+ continue;
+ }
+ if start.offset().fix() == end.offset().fix() {
+ return Ok(true);
+ }
+ // A repeated DST hour can leave a window between two apparently valid endpoints.
+ // Scheduling starts and durations have minute precision, so inspect the transition.
+ let mut instant = starts_at;
+ let mut contained = true;
+ while instant < ends_at {
+ let local = instant.with_timezone(&schedule.time_zone).time();
+ if local < window_start || local >= window_end {
+ contained = false;
+ break;
+ }
+ instant += Duration::minutes(1);
+ }
+ if contained {
+ return Ok(true);
+ }
+ }
+ Ok(false)
+}
+
+/// Offer starts for one date; ambiguous/nonexistent DST wall-clock starts are skipped.
+pub fn slots_for_date(
+ event: &EventType,
+ schedule: &Schedule,
+ date: NaiveDate,
+ now: DateTime<Utc>,
+ busy: &[BusyRange],
+) -> Result<Vec<Slot>, Error> {
+ if !event.enabled {
+ return Ok(vec![]);
+ }
+ let windows = windows_for_date(schedule, date);
+ let Some(windows) = windows else {
+ return Ok(vec![]);
+ };
+ let mut slots = vec![];
+ for window in windows {
+ let mut local = date.and_time(parse_time(&window.start)?);
+ let local_end = date.and_time(parse_time(&window.end)?);
+ while local < local_end {
+ let instant = schedule.time_zone.from_local_datetime(&local).single();
+ local += Duration::minutes(i64::from(event.interval_minutes));
+ let Some(start) = instant.map(|t| t.with_timezone(&Utc)) else {
+ continue;
+ };
+ let end = start + Duration::minutes(i64::from(event.duration_minutes));
+ if !schedule_contains(schedule, start, end)?
+ || start < now + Duration::minutes(i64::from(event.notice_minutes))
+ || start > now + Duration::days(i64::from(event.horizon_days))
+ {
+ continue;
+ }
+ let occupied_start = start - Duration::minutes(i64::from(event.before_minutes));
+ let occupied_end = end + Duration::minutes(i64::from(event.after_minutes));
+ let hosts: Vec<_> = event
+ .hosts
+ .iter()
+ .filter(|host| {
+ !busy.iter().any(|b| {
+ &b.host == *host && b.start < occupied_end && b.end > occupied_start
+ })
+ })
+ .cloned()
+ .collect();
+ let available = match event.mode {
+ SchedulingMode::Individual | SchedulingMode::Collective => {
+ hosts.len() == event.hosts.len()
+ }
+ SchedulingMode::RoundRobin => !hosts.is_empty(),
+ };
+ if available {
+ slots.push(Slot {
+ starts_at: start,
+ ends_at: end,
+ hosts,
+ });
+ }
+ }
+ }
+ slots.sort_by_key(|s| s.starts_at);
+ Ok(slots)
+}
+
+#[cfg(test)]
+mod test;
diff --git a/crates/calendar_scheduling/src/domain/availability/test.rs b/crates/calendar_scheduling/src/domain/availability/test.rs
new file mode 100644
index 0000000000..734404822c
--- /dev/null
+++ b/crates/calendar_scheduling/src/domain/availability/test.rs
@@ -0,0 +1,216 @@
+use super::*;
+use chrono::TimeZone;
+
+fn schedule() -> Schedule {
+ Schedule {
+ id: Uuid::nil(),
+ name: "Work".into(),
+ time_zone: chrono_tz::America::New_York,
+ weekly: (0..7)
+ .map(|day| WeeklyDay {
+ day,
+ windows: vec![TimeWindow {
+ start: "09:00".into(),
+ end: "12:00".into(),
+ }],
+ })
+ .collect(),
+ overrides: vec![],
+ }
+}
+fn event() -> EventType {
+ EventType {
+ id: Uuid::new_v4(),
+ title: "Meeting".into(),
+ slug: "meeting".into(),
+ description: String::new(),
+ duration_minutes: 30,
+ location: String::new(),
+ google_meet: false,
+ enabled: true,
+ schedule_id: Uuid::nil(),
+ mode: SchedulingMode::Collective,
+ hosts: vec!["a".into(), "b".into()],
+ before_minutes: 0,
+ after_minutes: 0,
+ notice_minutes: 0,
+ horizon_days: 365,
+ interval_minutes: 30,
+ daily_limit: None,
+ requires_confirmation: false,
+ questions: vec![],
+ }
+}
+use uuid::Uuid;
+#[test]
+fn collective_intersects_and_round_robin_unions_host_availability() {
+ let day = NaiveDate::from_ymd_opt(2026, 9, 21).unwrap();
+ let now = Utc.with_ymd_and_hms(2026, 9, 20, 0, 0, 0).unwrap();
+ let busy = vec![BusyRange {
+ host: "a".into(),
+ start: Utc.with_ymd_and_hms(2026, 9, 21, 13, 0, 0).unwrap(),
+ end: Utc.with_ymd_and_hms(2026, 9, 21, 14, 0, 0).unwrap(),
+ }];
+ let mut e = event();
+ let collective = slots_for_date(&e, &schedule(), day, now, &busy).unwrap();
+ assert_eq!(collective.len(), 4);
+ e.mode = SchedulingMode::RoundRobin;
+ let rr = slots_for_date(&e, &schedule(), day, now, &busy).unwrap();
+ assert_eq!(rr.len(), 6);
+ assert_eq!(rr[0].hosts, vec!["b"]);
+}
+#[test]
+fn buffers_notice_and_horizon_are_enforced() {
+ let day = NaiveDate::from_ymd_opt(2026, 9, 21).unwrap();
+ let now = Utc.with_ymd_and_hms(2026, 9, 21, 13, 0, 0).unwrap();
+ let mut e = event();
+ e.notice_minutes = 60;
+ e.before_minutes = 15;
+ e.after_minutes = 15;
+ let busy = vec![BusyRange {
+ host: "a".into(),
+ start: Utc.with_ymd_and_hms(2026, 9, 21, 14, 30, 0).unwrap(),
+ end: Utc.with_ymd_and_hms(2026, 9, 21, 15, 0, 0).unwrap(),
+ }];
+ let slots = slots_for_date(&e, &schedule(), day, now, &busy).unwrap();
+ assert_eq!(slots.len(), 1);
+ assert_eq!(
+ slots[0].starts_at,
+ Utc.with_ymd_and_hms(2026, 9, 21, 15, 30, 0).unwrap()
+ );
+ e.horizon_days = 1;
+ assert!(
+ slots_for_date(&e, &schedule(), day + Duration::days(3), now, &[])
+ .unwrap()
+ .is_empty()
+ );
+}
+#[test]
+fn empty_override_blocks_an_otherwise_available_day() {
+ let day = NaiveDate::from_ymd_opt(2026, 9, 21).unwrap();
+ let mut s = schedule();
+ s.overrides.push(DateOverride {
+ date: day,
+ windows: vec![],
+ });
+ assert!(
+ slots_for_date(
+ &event(),
+ &s,
+ day,
+ Utc.with_ymd_and_hms(2026, 9, 20, 0, 0, 0).unwrap(),
+ &[]
+ )
+ .unwrap()
+ .is_empty()
+ );
+}
+#[test]
+fn daylight_saving_keeps_local_hours_and_skips_nonexistent_starts() {
+ let mut s = schedule();
+ s.weekly[0].windows = vec![TimeWindow {
+ start: "01:00".into(),
+ end: "04:00".into(),
+ }];
+ let day = NaiveDate::from_ymd_opt(2026, 3, 8).unwrap();
+ let slots = slots_for_date(
+ &event(),
+ &s,
+ day,
+ Utc.with_ymd_and_hms(2026, 3, 7, 0, 0, 0).unwrap(),
+ &[],
+ )
+ .unwrap();
+ assert_eq!(slots.len(), 4);
+ assert!(
+ slots
+ .iter()
+ .all(|s| s.ends_at - s.starts_at == Duration::minutes(30))
+ );
+ let day = NaiveDate::from_ymd_opt(2026, 11, 1).unwrap();
+ let slots = slots_for_date(
+ &event(),
+ &s,
+ day,
+ Utc.with_ymd_and_hms(2026, 10, 31, 0, 0, 0).unwrap(),
+ &[],
+ )
+ .unwrap();
+ assert_eq!(slots.len(), 4); // ambiguous 1:00/1:30 are never silently assigned an offset
+}
+#[test]
+fn rejects_overlapping_windows_duplicate_days_and_invalid_links() {
+ let mut p = Profile {
+ id: Uuid::new_v4(),
+ name: "Calendar".into(),
+ description: String::new(),
+ schedules: vec![schedule()],
+ default_schedule_id: None,
+ event_types: vec![event()],
+ revision: 0,
+ };
+ assert!(validate_profile(&p, true).is_ok());
+ p.schedules[0].weekly[0].windows.push(TimeWindow {
+ start: "10:00".into(),
+ end: "11:00".into(),
+ });
+ assert!(validate_profile(&p, true).is_err());
+ p.schedules[0] = schedule();
+ p.schedules[0].weekly[0].day = 1;
+ assert!(validate_profile(&p, true).is_err());
+ p.schedules[0] = schedule();
+ p.event_types[0].slug = "../private".into();
+ assert!(validate_profile(&p, true).is_err());
+}
+
+#[test]
+fn personal_hours_respect_overrides_and_repeated_dst_hour() {
+ let mut s = schedule();
+ s.time_zone = chrono_tz::America::New_York;
+ for day in &mut s.weekly {
+ day.windows = vec![TimeWindow {
+ start: "01:30".into(),
+ end: "02:00".into(),
+ }];
+ }
+ let start = Utc.with_ymd_and_hms(2026, 11, 1, 5, 45, 0).unwrap();
+ assert!(schedule_contains(&s, start, start + Duration::minutes(10)).unwrap());
+ assert!(!schedule_contains(&s, start, start + Duration::hours(1)).unwrap());
+ s.overrides.push(DateOverride {
+ date: start.with_timezone(&s.time_zone).date_naive(),
+ windows: vec![],
+ });
+ assert!(!schedule_contains(&s, start, start + Duration::minutes(10)).unwrap());
+}
+
+#[test]
+fn primary_schedule_rejects_slots_that_leave_hours_during_fall_back() {
+ let mut schedule = schedule();
+ schedule.weekly[0].windows = vec![TimeWindow {
+ start: "00:30".into(),
+ end: "01:30".into(),
+ }];
+ let mut event = event();
+ event.duration_minutes = 120;
+ let slots = slots_for_date(
+ &event,
+ &schedule,
+ NaiveDate::from_ymd_opt(2026, 11, 1).unwrap(),
+ Utc.with_ymd_and_hms(2026, 10, 31, 0, 0, 0).unwrap(),
+ &[],
+ )
+ .unwrap();
+ assert!(slots.is_empty());
+ event.duration_minutes = 30;
+ assert!(
+ !slots_for_date(
+ &event,
+ &schedule,
+ NaiveDate::from_ymd_opt(2026, 11, 1).unwrap(),
+ Utc.with_ymd_and_hms(2026, 10, 31, 0, 0, 0).unwrap(),
+ &[],
+ )
+ .unwrap()
+ .is_empty()
+ );
+}
diff --git a/crates/calendar_scheduling/src/domain/models.rs b/crates/calendar_scheduling/src/domain/models.rs
new file mode 100644
index 0000000000..255380bb03
--- /dev/null
+++ b/crates/calendar_scheduling/src/domain/models.rs
@@ -0,0 +1,392 @@
+//! Scheduling value objects and persisted booking records.
+use chrono::{DateTime, NaiveDate, Utc};
+use serde::{Deserialize, Serialize};
+use std::collections::BTreeMap;
+use uuid::Uuid;
+
+/// A wall-clock window in an availability schedule.
+#[derive(Clone, Debug, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct TimeWindow {
+ /// Inclusive HH:MM start.
+ pub start: String,
+ /// Exclusive HH:MM end.
+ pub end: String,
+}
+/// Availability for one weekday.
+#[derive(Clone, Debug, Serialize, Deserialize)]
+pub struct WeeklyDay {
+ /// Sunday is zero.
+ pub day: u8,
+ /// Non-overlapping local windows.
+ pub windows: Vec<TimeWindow>,
+}
+/// Replacement availability for one date.
+#[derive(Clone, Debug, Serialize, Deserialize)]
+pub struct DateOverride {
+ /// Local date in the schedule zone.
+ pub date: NaiveDate,
+ /// Empty means unavailable all day.
+ pub windows: Vec<TimeWindow>,
+}
+/// Reusable hours, with DST interpreted in an IANA zone.
+#[derive(Clone, Debug, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct Schedule {
+ /// Stable schedule identity.
+ pub id: Uuid,
+ /// Display name.
+ pub name: String,
+ /// IANA time zone.
+ pub time_zone: chrono_tz::Tz,
+ /// Weekly windows.
+ pub weekly: Vec<WeeklyDay>,
+ /// Date-specific replacements.
+ pub overrides: Vec<DateOverride>,
+}
+/// Team host assignment policy.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub enum SchedulingMode {
+ /// One personal host.
+ Individual,
+ /// Every selected host must be available.
+ Collective,
+ /// Assign one available host, balancing booking counts.
+ RoundRobin,
+}
+/// A question on the booking form.
+#[derive(Clone, Debug, Serialize, Deserialize)]
+pub struct Question {
+ /// Stable identity.
+ pub id: Uuid,
+ /// Public question label.
+ pub label: String,
+ /// Whether an answer is mandatory.
+ pub required: bool,
+}
+/// A reusable booking link.
+#[derive(Clone, Debug, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct EventType {
+ /// Stable identity.
+ pub id: Uuid,
+ /// Public title.
+ pub title: String,
+ /// Unique link segment within a profile.
+ pub slug: String,
+ /// Public description.
+ pub description: String,
+ /// Meeting duration.
+ pub duration_minutes: u16,
+ /// Meeting location.
+ pub location: String,
+ /// Generate a Google Meet conference.
+ pub google_meet: bool,
+ /// Whether new bookings are accepted.
+ pub enabled: bool,
+ /// Referenced availability schedule.
+ pub schedule_id: Uuid,
+ /// Host assignment policy.
+ pub mode: SchedulingMode,
+ /// Current Macro user identities selected as hosts.
+ pub hosts: Vec<String>,
+ /// Protected time before a meeting.
+ pub before_minutes: u16,
+ /// Protected time after a meeting.
+ pub after_minutes: u16,
+ /// Minimum notice in minutes.
+ pub notice_minutes: u16,
+ /// Maximum days ahead.
+ pub horizon_days: u16,
+ /// Spacing of offered start times.
+ pub interval_minutes: u16,
+ /// Maximum bookings for this event on one schedule-local day.
+ pub daily_limit: Option<u16>,
+ /// Hold bookings for host approval.
+ pub requires_confirmation: bool,
+ /// Additional form fields.
+ pub questions: Vec<Question>,
+}
+/// Editable configuration for a person or team.
+#[derive(Clone, Debug, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct Profile {
+ /// Public, opaque profile identity.
+ pub id: Uuid,
+ /// Display name on the public page.
+ pub name: String,
+ /// Public introduction.
+ pub description: String,
+ /// Reusable schedules.
+ pub schedules: Vec<Schedule>,
+ /// Personal hours used by team events; absent legacy profiles use their first schedule.
+ #[serde(default)]
+ pub default_schedule_id: Option<Uuid>,
+ /// Booking links.
+ pub event_types: Vec<EventType>,
+ /// Optimistic concurrency version.
+ pub revision: i64,
+}
+/// A profile's private ownership boundary.
+#[derive(Clone, Debug)]
+pub struct OwnedProfile {
+ /// Owning Macro user, absent for team profiles.
+ pub user_id: Option<String>,
+ /// Owning Macro team, absent for personal profiles.
+ pub team_id: Option<Uuid>,
+ /// Editable/public configuration.
+ pub profile: Profile,
+}
+/// Booking lifecycle state.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub enum BookingStatus {
+ /// Reserved, awaiting host confirmation.
+ Pending,
+ /// Provider calendar has accepted the event.
+ Confirmed,
+ /// Cancellation completed.
+ Cancelled,
+ /// Reserved while a calendar operation is in flight.
+ Processing,
+ /// Calendar write failed; reservation retained for safe reconciliation.
+ Failed,
+}
+/// Attendance recorded by an assigned host or profile administrator after a meeting.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub enum BookingAttendance {
+ /// Attendance has not been recorded; elapsed time does not imply attendance.
+ #[default]
+ Unknown,
+ /// The meeting took place with the expected participants.
+ Attended,
+ /// The guest did not attend.
+ GuestNoShow,
+ /// A required host did not attend.
+ HostNoShow,
+}
+/// Public booking details, also visible to authorized profile members.
+#[derive(Clone, Debug, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct Booking {
+ /// Booking identity.
+ pub id: Uuid,
+ /// Booking link identity.
+ pub event_type_id: Uuid,
+ /// Snapshot of the meeting title.
+ pub title: String,
+ /// Booker's name.
+ pub name: String,
+ /// Booker's email.
+ pub email: String,
+ /// Absolute meeting start.
+ pub starts_at: DateTime<Utc>,
+ /// Absolute meeting end.
+ pub ends_at: DateTime<Utc>,
+ /// Booker's display time zone.
+ pub time_zone: chrono_tz::Tz,
+ /// Assigned hosts.
+ pub hosts: Vec<String>,
+ /// Current lifecycle state.
+ pub status: BookingStatus,
+ /// Explicit attendance outcome; existing booking records default to unknown.
+ #[serde(default)]
+ pub attendance: BookingAttendance,
+ /// Number of successfully completed moves to a different start time.
+ #[serde(default)]
+ pub reschedule_count: u16,
+ /// When the most recent successful reschedule completed.
+ #[serde(default)]
+ pub rescheduled_at: Option<DateTime<Utc>>,
+ /// Final location or conference URL.
+ pub location: String,
+ /// Answers keyed by question identity.
+ pub answers: BTreeMap<Uuid, String>,
+ /// Original labels for answers, independent of later event-type edits.
+ #[serde(default)]
+ pub question_labels: BTreeMap<Uuid, String>,
+}
+/// Private persisted state, never returned from a public profile endpoint.
+#[derive(Clone, Debug, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct BookingRecord {
+ /// Monotonic version fencing every mutation, including same-status edits.
+ #[serde(default)]
+ pub revision: u32,
+ /// Event rules captured at booking time, so deleting a link cannot orphan bookings.
+ pub event: EventType,
+ /// Availability schedule captured when the booking was made.
+ pub schedule: Schedule,
+ /// Booking details.
+ pub booking: Booking,
+ /// Owning profile.
+ pub profile_id: Uuid,
+ /// Unguessable booker management capability.
+ pub token: Uuid,
+ /// Client-generated idempotency identity.
+ pub request_id: Uuid,
+ /// Creation calendar pinned before the first provider attempt.
+ #[serde(default)]
+ pub calendar_id: Option<Uuid>,
+ /// Durable intent and retry fence for an in-flight provider operation.
+ #[serde(default)]
+ pub operation: Option<CalendarOperation>,
+ /// Calendar event produced by the provider.
+ pub calendar_event_id: Option<Uuid>,
+ /// Earliest occupied instant including buffer.
+ pub busy_start: DateTime<Utc>,
+ /// Latest occupied instant including buffer.
+ pub busy_end: DateTime<Utc>,
+}
+/// A request to reserve an offered slot.
+#[derive(Clone, Debug, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct BookingRequest {
+ /// Selected absolute start.
+ pub starts_at: DateTime<Utc>,
+ /// Booker name.
+ pub name: String,
+ /// Booker email.
+ pub email: String,
+ /// Booker display zone.
+ pub time_zone: chrono_tz::Tz,
+ /// Question answers.
+ pub answers: BTreeMap<Uuid, String>,
+ /// Unique retry-safe operation identity.
+ pub request_id: Uuid,
+}
+/// A host's occupied range.
+#[derive(Clone, Debug)]
+pub struct BusyRange {
+ /// Host identity.
+ pub host: String,
+ /// Inclusive instant.
+ pub start: DateTime<Utc>,
+ /// Exclusive instant.
+ pub end: DateTime<Utc>,
+}
+/// Available slot and the hosts who can satisfy it.
+#[derive(Clone, Debug, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct Slot {
+ /// Absolute start.
+ pub starts_at: DateTime<Utc>,
+ /// Absolute end.
+ pub ends_at: DateTime<Utc>,
+ /// Host candidates, retained only on the server.
+ #[serde(skip)]
+ pub hosts: Vec<String>,
+}
+/// Membership facts from the owning teams domain.
+#[derive(Clone, Debug)]
+pub struct TeamMember {
+ /// Macro user identity.
+ pub user_id: String,
+ /// Whether this member administers scheduling.
+ pub admin: bool,
+}
+/// Use-case failures mapped by transport adapters.
+#[derive(Debug, thiserror::Error)]
+pub enum Error {
+ /// Invalid configuration or request.
+ #[error("{0}")]
+ Invalid(String),
+ /// Missing profile, link, or booking.
+ #[error("Scheduling resource not found")]
+ NotFound,
+ /// Caller lacks membership or editing rights.
+ #[error("You do not have permission to manage this calendar")]
+ Forbidden,
+ /// Stale revision or slot no longer available.
+ #[error("This time or configuration has changed. Refresh and try again.")]
+ Conflict,
+ /// A host's calendar is not available for reliable conflict checking.
+ #[error("A host's calendar is unavailable or still syncing. Please try again later.")]
+ CalendarUnavailable,
+ /// Public scheduling budget is exhausted for this profile.
+ #[error("Too many scheduling requests. Please try again later.")]
+ RateLimited,
+ /// Persistence or provider operation failed.
+ #[error("Scheduling is temporarily unavailable")]
+ Unavailable,
+}
+
+/// Published booking-page fields, excluding internal hosts and scheduling configuration.
+#[derive(Clone, Debug, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct PublicProfile {
+ /// Opaque page identity.
+ pub id: Uuid,
+ /// Public owner name.
+ pub name: String,
+ /// Public introduction.
+ pub description: String,
+ /// Only currently enabled booking links.
+ pub event_types: Vec<PublicEvent>,
+}
+/// Public presentation of a bookable event.
+#[derive(Clone, Debug, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct PublicEvent {
+ /// Event identity.
+ pub id: Uuid,
+ /// Public title.
+ pub title: String,
+ /// Link path segment.
+ pub slug: String,
+ /// Public description.
+ pub description: String,
+ /// Meeting length.
+ pub duration_minutes: u16,
+ /// Location shared by the host.
+ pub location: String,
+ /// Whether a Google Meet will be created.
+ pub google_meet: bool,
+ /// Information requested from the booker.
+ pub questions: Vec<Question>,
+ /// Whether the host must approve.
+ pub requires_confirmation: bool,
+ /// Individual or team scheduling behavior.
+ pub mode: SchedulingMode,
+}
+
+/// Durable provider intent. A recovery worker resumes the same operation after a crash.
+#[derive(Clone, Debug, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct CalendarOperation {
+ /// Stable identity fencing completion against newer operations.
+ pub id: Uuid,
+ /// Number of recovery claims; also fences an expired worker.
+ pub attempt: u32,
+ /// Earliest time another worker may claim this operation.
+ pub retry_at: DateTime<Utc>,
+ /// Intended provider change, retained through failures.
+ pub kind: CalendarOperationKind,
+}
+/// Provider changes that can be retried without creating a second event.
+#[derive(Clone, Debug, Serialize, Deserialize)]
+#[serde(tag = "kind", rename_all = "camelCase")]
+pub enum CalendarOperationKind {
+ /// Create one event using the booking identity as the idempotency key.
+ Create,
+ /// Move the existing event and restore this terminal booking status.
+ Move {
+ /// Status before the move.
+ status: BookingStatus,
+ /// Original start, used to count successful changes exactly once.
+ original_start: DateTime<Utc>,
+ },
+ /// Cancel the provider event before releasing its host reservations.
+ Cancel,
+}
+
+/// Shared public API budgets, independent of application replica count.
+#[derive(Clone, Copy)]
+pub enum PublicBudget {
+ /// Availability calculations: 120 per minute per profile.
+ Availability,
+ /// New reservations: 30 per hour per profile.
+ Booking,
+}
diff --git a/crates/calendar_scheduling/src/domain/ports.rs b/crates/calendar_scheduling/src/domain/ports.rs
new file mode 100644
index 0000000000..bc2a13fd3b
--- /dev/null
+++ b/crates/calendar_scheduling/src/domain/ports.rs
@@ -0,0 +1,108 @@
+//! Persistence and calendar capabilities required by scheduling policy.
+use super::models::*;
+use chrono::{DateTime, Utc};
+use std::future::Future;
+use uuid::Uuid;
+
+/// Scheduling's durable store. Reservations are atomic across all profiles and hosts.
+pub trait Repository: Send + Sync + 'static {
+ /// Consume a shared per-profile public API budget, failing closed on storage errors.
+ fn consume_budget(
+ &self,
+ profile: Uuid,
+ budget: PublicBudget,
+ ) -> impl Future<Output = Result<(), Error>> + Send;
+ /// Atomically claim one overdue operation and increment its completion fence.
+ fn claim_recovery(&self) -> impl Future<Output = Result<Option<BookingRecord>, Error>> + Send;
+ /// Read a profile, including its ownership boundary.
+ fn profile(&self, id: Uuid)
+ -> impl Future<Output = Result<Option<OwnedProfile>, Error>> + Send;
+ /// Create or compare-and-swap a profile at its supplied revision.
+ fn save_profile(
+ &self,
+ profile: OwnedProfile,
+ ) -> impl Future<Output = Result<Profile, Error>> + Send;
+ /// List every profile booking in a half-open range, or fail explicitly on overflow.
+ fn bookings(
+ &self,
+ profile: Uuid,
+ start: DateTime<Utc>,
+ end: DateTime<Utc>,
+ ) -> impl Future<Output = Result<Vec<BookingRecord>, Error>> + Send;
+ /// Count active assignments per candidate host without loading booking records.
+ fn host_booking_counts(
+ &self,
+ profile: Uuid,
+ hosts: &[String],
+ start: DateTime<Utc>,
+ end: DateTime<Utc>,
+ ) -> impl Future<Output = Result<std::collections::BTreeMap<String, i64>, Error>> + Send;
+ /// Read all active host claims, including those owned by other profiles.
+ fn busy(
+ &self,
+ hosts: &[String],
+ start: DateTime<Utc>,
+ end: DateTime<Utc>,
+ exclude: Option<Uuid>,
+ ) -> impl Future<Output = Result<Vec<BusyRange>, Error>> + Send;
+ /// Reserve host ranges atomically; enforce the daily limit and idempotency.
+ fn reserve(
+ &self,
+ record: BookingRecord,
+ limit: Option<u16>,
+ day_start: DateTime<Utc>,
+ day_end: DateTime<Utc>,
+ ) -> impl Future<Output = Result<BookingRecord, Error>> + Send;
+ /// Load a booking by identity.
+ fn booking(
+ &self,
+ id: Uuid,
+ ) -> impl Future<Output = Result<Option<BookingRecord>, Error>> + Send;
+ /// Resolve a retry before rechecking the now-occupied slot.
+ fn booking_request(
+ &self,
+ request: Uuid,
+ ) -> impl Future<Output = Result<Option<BookingRecord>, Error>> + Send;
+ /// Atomically protect both old and new ranges while a reschedule is processed.
+ fn move_booking(
+ &self,
+ record: BookingRecord,
+ expected: BookingStatus,
+ day_start: DateTime<Utc>,
+ day_end: DateTime<Utc>,
+ ) -> impl Future<Output = Result<BookingRecord, Error>> + Send;
+ /// Compare-and-swap a booking and release cancelled claims in the same transaction.
+ fn update_booking(
+ &self,
+ record: BookingRecord,
+ expected: BookingStatus,
+ ) -> impl Future<Output = Result<BookingRecord, Error>> + Send;
+}
+/// Calendar adapter, implemented with the existing calendar domain services.
+pub trait Calendars: Send + Sync + 'static {
+ /// Select and pin the organizer's writable primary calendar before reserving.
+ fn creation_calendar(&self, host: &str) -> impl Future<Output = Result<Uuid, Error>> + Send;
+ /// Load authoritative busy time, failing closed for disconnected or syncing hosts.
+ fn busy(
+ &self,
+ hosts: &[String],
+ start: DateTime<Utc>,
+ end: DateTime<Utc>,
+ exclude_event: Option<Uuid>,
+ ) -> impl Future<Output = Result<Vec<BusyRange>, Error>> + Send;
+ /// Create the organizer's provider event and invite all assigned hosts and the booker.
+ fn create(
+ &self,
+ record: &BookingRecord,
+ event: &EventType,
+ ) -> impl Future<Output = Result<(Uuid, String), Error>> + Send;
+ /// Cancel the provider event, notifying attendees through the calendar integration.
+ fn cancel(&self, record: &BookingRecord) -> impl Future<Output = Result<(), Error>> + Send;
+ /// Move an existing provider event without creating a second invitation.
+ fn reschedule(&self, record: &BookingRecord) -> impl Future<Output = Result<(), Error>> + Send;
+}
+/// Membership facts supplied by Macro's teams domain.
+pub trait Directory: Send + Sync + 'static {
+ /// All current members, including the owner.
+ fn members(&self, team: Uuid) -> impl Future<Output = Result<Vec<TeamMember>, Error>> + Send;
+}
diff --git a/crates/calendar_scheduling/src/domain/recovery.rs b/crates/calendar_scheduling/src/domain/recovery.rs
new file mode 100644
index 0000000000..8d99bef87b
--- /dev/null
+++ b/crates/calendar_scheduling/src/domain/recovery.rs
@@ -0,0 +1,112 @@
+//! Durable provider-operation recovery and completion fencing.
+use super::{models::*, ports::*, service::Service};
+use chrono::{Duration, Utc};
+use uuid::Uuid;
+
+impl CalendarOperation {
+ /// Start a recoverable operation; the grace period exceeds provider request timeouts.
+ pub fn new(kind: CalendarOperationKind) -> Self {
+ Self {
+ id: Uuid::now_v7(),
+ attempt: 0,
+ retry_at: Utc::now() + Duration::minutes(5),
+ kind,
+ }
+ }
+}
+impl<R: Repository, C: Calendars, D: Directory> Service<R, C, D> {
+ /// Resume one overdue operation. Multiple replicas claim separate rows atomically.
+ #[tracing::instrument(skip(self), err)]
+ pub async fn recover_once(&self) -> Result<bool, Error> {
+ let Some(record) = self.repository.claim_recovery().await? else {
+ return Ok(false);
+ };
+ let id = record.booking.id;
+ let attempt = record.operation.as_ref().map_or(0, |op| op.attempt);
+ if attempt >= 3 {
+ tracing::error!(booking_id = %id, attempt, "scheduling recovery requires operator attention");
+ }
+ let result = self.finish_operation(record).await?;
+ if matches!(
+ result.booking.status,
+ BookingStatus::Failed | BookingStatus::Processing
+ ) {
+ return Ok(true);
+ }
+ tracing::info!(booking_id = %id, attempt, "scheduling operation recovered");
+ Ok(true)
+ }
+
+ pub(super) async fn finish_operation(
+ &self,
+ mut record: BookingRecord,
+ ) -> Result<BookingRecord, Error> {
+ let operation = record.operation.clone().ok_or(Error::Conflict)?;
+ let result = match operation.kind {
+ CalendarOperationKind::Create => self
+ .calendars
+ .create(&record, &record.event)
+ .await
+ .map(|(id, location)| {
+ record.calendar_event_id = Some(id);
+ record.booking.location = location;
+ record.booking.status = BookingStatus::Confirmed;
+ }),
+ CalendarOperationKind::Move {
+ status,
+ original_start,
+ } => self.calendars.reschedule(&record).await.map(|()| {
+ record.booking.status = status;
+ if record.booking.starts_at != original_start {
+ record.booking.reschedule_count =
+ record.booking.reschedule_count.saturating_add(1);
+ record.booking.rescheduled_at = Some(Utc::now());
+ record.booking.attendance = BookingAttendance::Unknown;
+ }
+ }),
+ CalendarOperationKind::Cancel => self.calendars.cancel(&record).await.map(|()| {
+ record.booking.status = BookingStatus::Cancelled;
+ }),
+ };
+ if let Err(error) = result {
+ record.booking.status = BookingStatus::Failed;
+ // Keep both reservations after an uncertain move. Never expose an occupied slot.
+ let minutes = 5_i64 * 2_i64.pow(operation.attempt.min(4));
+ if let Some(op) = &mut record.operation {
+ op.retry_at = Utc::now() + Duration::minutes(minutes.min(60));
+ }
+ tracing::warn!(booking_id = %record.booking.id, attempt = operation.attempt, error = ?error, "scheduling operation queued for recovery");
+ // Reservation is durable: return its receipt even when the provider is uncertain.
+ // A guest must not be encouraged to create a second booking.
+ return self.persist_completion(record).await;
+ }
+ self.persist_completion(record).await
+ }
+
+ async fn persist_completion(&self, mut record: BookingRecord) -> Result<BookingRecord, Error> {
+ match self
+ .repository
+ .update_booking(record.clone(), BookingStatus::Processing)
+ .await
+ {
+ Ok(saved) => Ok(saved),
+ Err(Error::Conflict) => {
+ // A recovery worker or later edit owns the revision now. The original
+ // reservation still exists, so this is not a rejected booking attempt.
+ if let Ok(Some(current)) = self.repository.booking(record.booking.id).await {
+ return Ok(current);
+ }
+ record.booking.status = BookingStatus::Processing;
+ Ok(record)
+ }
+ Err(Error::Unavailable) => {
+ // The reservation and intent predate the provider call. Keep its private receipt
+ // available even when the completion write is uncertain; recovery owns convergence.
+ tracing::error!(booking_id = %record.booking.id, "scheduling completion persistence unavailable; intent retained");
+ record.booking.status = BookingStatus::Processing;
+ Ok(record)
+ }
+ Err(error) => Err(error),
+ }
+ }
+}
diff --git a/crates/calendar_scheduling/src/domain/service.rs b/crates/calendar_scheduling/src/domain/service.rs
new file mode 100644
index 0000000000..85c00d95e7
--- /dev/null
+++ b/crates/calendar_scheduling/src/domain/service.rs
@@ -0,0 +1,799 @@
+//! Scheduling use cases, authorization, and booking state transitions.
+use super::{
+ availability::{schedule_contains, slots_for_date, validate_profile},
+ models::*,
+ ports::*,
+};
+use chrono::{DateTime, Duration, NaiveDate, TimeZone, Utc};
+use uuid::Uuid;
+
+/// Scheduling domain service with replaceable persistence, directory, and calendars.
+pub struct Service<R, C, D> {
+ pub(super) repository: R,
+ pub(super) calendars: C,
+ directory: D,
+}
+impl<R: Repository, C: Calendars, D: Directory> Service<R, C, D> {
+ /// Construct the scheduling use-case service.
+ pub fn new(repository: R, calendars: C, directory: D) -> Self {
+ Self {
+ repository,
+ calendars,
+ directory,
+ }
+ }
+ /// Deterministic opaque identity for a personal or team scheduling profile.
+ pub fn profile_id(user: &str, team: Option<Uuid>) -> Uuid {
+ let scope = team.map_or_else(
+ || format!("macro:scheduling:user:{user}"),
+ |t| format!("macro:scheduling:team:{t}"),
+ );
+ Uuid::new_v5(&Uuid::NAMESPACE_URL, scope.as_bytes())
+ }
+ async fn authorize(&self, user: &str, owner: &OwnedProfile, write: bool) -> Result<(), Error> {
+ if let Some(team) = owner.team_id {
+ if self
+ .directory
+ .members(team)
+ .await?
+ .iter()
+ .any(|m| m.user_id == user && (!write || m.admin))
+ {
+ return Ok(());
+ }
+ } else if owner.user_id.as_deref() == Some(user) {
+ return Ok(());
+ }
+ Err(Error::Forbidden)
+ }
+ /// Read configuration, returning an unsaved default for a new profile.
+ pub async fn settings(&self, user: &str, team: Option<Uuid>) -> Result<Profile, Error> {
+ let id = Self::profile_id(user, team);
+ let owner = self
+ .repository
+ .profile(id)
+ .await?
+ .unwrap_or_else(|| OwnedProfile {
+ user_id: team.is_none().then(|| user.to_owned()),
+ team_id: team,
+ profile: Profile {
+ id,
+ name: "My calendar".into(),
+ description: String::new(),
+ schedules: vec![],
+ default_schedule_id: None,
+ event_types: vec![],
+ revision: 0,
+ },
+ });
+ self.authorize(user, &owner, false).await?;
+ Ok(owner.profile)
+ }
+ /// Save a validated, revision-protected profile. Only team admins may edit team links.
+ pub async fn save(
+ &self,
+ user: &str,
+ team: Option<Uuid>,
+ profile: Profile,
+ ) -> Result<Profile, Error> {
+ if profile.id != Self::profile_id(user, team) {
+ return Err(Error::Forbidden);
+ }
+ validate_profile(&profile, team.is_some())?;
+ let owner = OwnedProfile {
+ user_id: team.is_none().then(|| user.to_owned()),
+ team_id: team,
+ profile,
+ };
+ self.authorize(user, &owner, true).await?;
+ let previous = self.repository.profile(owner.profile.id).await?;
+ self.validate_hosts(&owner, previous.as_ref()).await?;
+ self.repository.save_profile(owner).await
+ }
+ async fn validate_hosts(
+ &self,
+ owner: &OwnedProfile,
+ previous: Option<&OwnedProfile>,
+ ) -> Result<(), Error> {
+ let members = if let Some(team) = owner.team_id {
+ self.directory
+ .members(team)
+ .await?
+ .into_iter()
+ .map(|m| m.user_id)
+ .collect::<Vec<_>>()
+ } else {
+ vec![owner.user_id.clone().ok_or(Error::Forbidden)?]
+ };
+ for event in &owner.profile.event_types {
+ let old =
+ previous.and_then(|p| p.profile.event_types.iter().find(|e| e.id == event.id));
+ // Permit repairing one legacy event at a time; booking still validates current hosts.
+ if event.requires_confirmation && !old.is_some_and(|e| e.requires_confirmation) {
+ return Err(Error::Invalid(
+ "Manual approval is not available yet. Use automatic confirmation.".into(),
+ ));
+ }
+ if event.hosts.iter().any(|host| !members.contains(host))
+ && !old.is_some_and(|e| e.hosts == event.hosts && (!event.enabled || e.enabled))
+ {
+ return Err(Error::Invalid(
+ "Every host must be a current member of this calendar's owner".into(),
+ ));
+ }
+ }
+ Ok(())
+ }
+ async fn validate_booking_hosts(
+ &self,
+ owner: &OwnedProfile,
+ hosts: &[String],
+ ) -> Result<(), Error> {
+ let members = if let Some(team) = owner.team_id {
+ self.directory
+ .members(team)
+ .await?
+ .into_iter()
+ .map(|m| m.user_id)
+ .collect::<Vec<_>>()
+ } else {
+ vec![owner.user_id.clone().ok_or(Error::Forbidden)?]
+ };
+ if hosts.iter().any(|h| !members.contains(h)) {
+ return Err(Error::Forbidden);
+ }
+ Ok(())
+ }
+ /// Publish only enabled event types and public presentation fields.
+ pub async fn public_profile(&self, id: Uuid) -> Result<PublicProfile, Error> {
+ let owner = self.repository.profile(id).await?.ok_or(Error::NotFound)?;
+ let p = owner.profile;
+ Ok(PublicProfile {
+ id: p.id,
+ name: p.name,
+ description: p.description,
+ event_types: p
+ .event_types
+ .into_iter()
+ .filter(|e| e.enabled)
+ .map(|e| PublicEvent {
+ id: e.id,
+ title: e.title,
+ slug: e.slug,
+ description: e.description,
+ duration_minutes: e.duration_minutes,
+ location: e.location,
+ google_meet: e.google_meet,
+ questions: e.questions,
+ requires_confirmation: e.requires_confirmation,
+ mode: e.mode,
+ })
+ .collect(),
+ })
+ }
+ /// Compute slots without exposing host identities or private event details.
+ pub async fn slots(
+ &self,
+ profile_id: Uuid,
+ event_id: Uuid,
+ date: NaiveDate,
+ ) -> Result<Vec<Slot>, Error> {
+ let owner = self
+ .repository
+ .profile(profile_id)
+ .await?
+ .ok_or(Error::NotFound)?;
+ self.slots_for_owner(&owner, event_id, date).await
+ }
+ async fn slots_for_owner(
+ &self,
+ owner: &OwnedProfile,
+ event_id: Uuid,
+ date: NaiveDate,
+ ) -> Result<Vec<Slot>, Error> {
+ let profile_id = owner.profile.id;
+ let event = owner
+ .profile
+ .event_types
+ .iter()
+ .find(|e| e.id == event_id && e.enabled)
+ .ok_or(Error::NotFound)?;
+ self.validate_booking_hosts(owner, &event.hosts).await?;
+ if event.requires_confirmation {
+ return Err(Error::Invalid(
+ "This booking link is paused until its host enables automatic confirmation.".into(),
+ ));
+ }
+ let schedule = owner
+ .profile
+ .schedules
+ .iter()
+ .find(|s| s.id == event.schedule_id)
+ .ok_or(Error::NotFound)?;
+ let (start, end) = day_bounds(schedule, date)?;
+ let now = Utc::now();
+ if end < now || start > now + Duration::days(i64::from(event.horizon_days) + 1) {
+ return Ok(vec![]);
+ }
+ let records = self.repository.bookings(profile_id, start, end).await?;
+ let count = records
+ .iter()
+ .filter(|r| {
+ r.booking.event_type_id == event_id && r.booking.status != BookingStatus::Cancelled
+ })
+ .count();
+ if event.daily_limit.is_some_and(|n| count >= usize::from(n)) {
+ return Ok(vec![]);
+ }
+ let busy_start = start - Duration::minutes(i64::from(event.before_minutes));
+ let busy_end = end + Duration::minutes(i64::from(event.after_minutes));
+ let mut busy = self
+ .calendars
+ .busy(&event.hosts, busy_start, busy_end, None)
+ .await?;
+ busy.extend(
+ self.repository
+ .busy(&event.hosts, busy_start, busy_end, None)
+ .await?,
+ );
+ self.respect_host_hours(
+ owner,
+ event,
+ slots_for_date(event, schedule, date, now, &busy)?,
+ )
+ .await
+ }
+ async fn respect_host_hours(
+ &self,
+ owner: &OwnedProfile,
+ event: &EventType,
+ slots: Vec<Slot>,
+ ) -> Result<Vec<Slot>, Error> {
+ if owner.team_id.is_none() {
+ return Ok(slots);
+ }
+ let mut schedules = vec![];
+ for host in &event.hosts {
+ if let Some(personal) = self
+ .repository
+ .profile(Self::profile_id(host, None))
+ .await?
+ {
+ let schedule = personal
+ .profile
+ .default_schedule_id
+ .and_then(|id| personal.profile.schedules.iter().find(|s| s.id == id))
+ .or_else(|| personal.profile.schedules.first());
+ if let Some(schedule) = schedule {
+ schedules.push((host, schedule.clone()));
+ }
+ }
+ }
+ let mut available = vec![];
+ for mut slot in slots {
+ let mut hosts = vec![];
+ for host in &slot.hosts {
+ let personal = schedules.iter().find(|(id, _)| *id == host);
+ if let Some((_, schedule)) = personal
+ && !schedule_contains(schedule, slot.starts_at, slot.ends_at)?
+ {
+ continue;
+ }
+ // Hosts who have not configured personal hours use the shared team schedule.
+ hosts.push(host.clone());
+ }
+ let bookable = match event.mode {
+ SchedulingMode::Individual | SchedulingMode::Collective => {
+ hosts.len() == event.hosts.len()
+ }
+ SchedulingMode::RoundRobin => !hosts.is_empty(),
+ };
+ if bookable {
+ slot.hosts = hosts;
+ available.push(slot);
+ }
+ }
+ Ok(available)
+ }
+ /// Offer times on a booker's local date, across host time-zone boundaries.
+ pub async fn slots_in_zone(
+ &self,
+ profile_id: Uuid,
+ event_id: Uuid,
+ date: NaiveDate,
+ zone: chrono_tz::Tz,
+ ) -> Result<Vec<Slot>, Error> {
+ let owner = self
+ .repository
+ .profile(profile_id)
+ .await?
+ .ok_or(Error::NotFound)?;
+ self.repository
+ .consume_budget(profile_id, PublicBudget::Availability)
+ .await?;
+ let event = owner
+ .profile
+ .event_types
+ .iter()
+ .find(|e| e.id == event_id)
+ .ok_or(Error::NotFound)?;
+ let schedule = owner
+ .profile
+ .schedules
+ .iter()
+ .find(|s| s.id == event.schedule_id)
+ .ok_or(Error::NotFound)?;
+ let viewer_schedule = Schedule {
+ time_zone: zone,
+ ..schedule.clone()
+ };
+ let (start, end) = day_bounds(&viewer_schedule, date)?;
+ let mut host_date = start.with_timezone(&schedule.time_zone).date_naive();
+ let last = (end - Duration::seconds(1))
+ .with_timezone(&schedule.time_zone)
+ .date_naive();
+ let mut slots = vec![];
+ while host_date <= last {
+ slots.extend(
+ self.slots_for_owner(&owner, event_id, host_date)
+ .await?
+ .into_iter()
+ .filter(|s| s.starts_at >= start && s.starts_at < end),
+ );
+ host_date = host_date.succ_opt().ok_or(Error::Conflict)?;
+ }
+ slots.sort_by_key(|s| s.starts_at);
+ Ok(slots)
+ }
+ /// Reserve a slot and create the provider event, or hold it for confirmation.
+ pub async fn book(
+ &self,
+ profile_id: Uuid,
+ event_id: Uuid,
+ request: BookingRequest,
+ ) -> Result<BookingRecord, Error> {
+ if let Some(existing) = self.repository.booking_request(request.request_id).await? {
+ if existing.profile_id == profile_id
+ && existing.booking.event_type_id == event_id
+ && existing.booking.email == request.email.trim().to_lowercase()
+ && existing.booking.starts_at == request.starts_at
+ {
+ return Ok(existing);
+ }
+ return Err(Error::Conflict);
+ }
+ let owner = self
+ .repository
+ .profile(profile_id)
+ .await?
+ .ok_or(Error::NotFound)?;
+ let event = owner
+ .profile
+ .event_types
+ .iter()
+ .find(|e| e.id == event_id && e.enabled)
+ .ok_or(Error::NotFound)?;
+ self.validate_booking_hosts(&owner, &event.hosts).await?;
+ if event.requires_confirmation {
+ return Err(Error::Invalid(
+ "This booking link is paused until its host enables automatic confirmation.".into(),
+ ));
+ }
+ if request.name.trim().is_empty()
+ || request.name.len() > 200
+ || request.email.len() > 254
+ || !email_validator::is_valid_email(&request.email)
+ || request.answers.len() > 20
+ || request.answers.values().any(|a| a.len() > 4000)
+ {
+ return Err(Error::Invalid(
+ "Provide a valid name, email, and booking answers".into(),
+ ));
+ }
+ if event.questions.iter().any(|q| {
+ q.required
+ && request
+ .answers
+ .get(&q.id)
+ .is_none_or(|a| a.trim().is_empty())
+ }) || request
+ .answers
+ .keys()
+ .any(|id| !event.questions.iter().any(|q| q.id == *id))
+ {
+ return Err(Error::Invalid(
+ "Complete the required booking questions".into(),
+ ));
+ }
+ self.repository
+ .consume_budget(profile_id, PublicBudget::Booking)
+ .await?;
+ let schedule = owner
+ .profile
+ .schedules
+ .iter()
+ .find(|s| s.id == event.schedule_id)
+ .ok_or(Error::NotFound)?;
+ let date = request
+ .starts_at
+ .with_timezone(&schedule.time_zone)
+ .date_naive();
+ let mut slot = self
+ .slots_for_owner(&owner, event_id, date)
+ .await?
+ .into_iter()
+ .find(|s| s.starts_at == request.starts_at)
+ .ok_or(Error::Conflict)?;
+ if event.mode == SchedulingMode::RoundRobin {
+ let counts = self
+ .repository
+ .host_booking_counts(
+ profile_id,
+ &slot.hosts,
+ Utc::now() - Duration::days(30),
+ Utc::now() + Duration::days(366),
+ )
+ .await?;
+ slot.hosts
+ .sort_by_key(|host| (counts.get(host).copied().unwrap_or(0), host.clone()));
+ }
+ let mut backup_hosts =
+ if event.mode == SchedulingMode::RoundRobin && slot.hosts.len() > 1 {
+ slot.hosts.split_off(1)
+ } else {
+ Vec::new()
+ }
+ .into_iter();
+ let (day_start, day_end) = day_bounds(schedule, date)?;
+ let mut record = BookingRecord {
+ revision: 0,
+ event: event.clone(),
+ schedule: schedule.clone(),
+ profile_id,
+ token: Uuid::new_v4(),
+ request_id: request.request_id,
+ calendar_event_id: None,
+ calendar_id: Some(
+ self.calendars
+ .creation_calendar(slot.hosts.first().ok_or(Error::CalendarUnavailable)?)
+ .await?,
+ ),
+ operation: Some(CalendarOperation::new(CalendarOperationKind::Create)),
+ busy_start: slot.starts_at - Duration::minutes(i64::from(event.before_minutes)),
+ busy_end: slot.ends_at + Duration::minutes(i64::from(event.after_minutes)),
+ booking: Booking {
+ id: Uuid::now_v7(),
+ event_type_id: event_id,
+ title: event.title.clone(),
+ name: request.name.trim().into(),
+ email: request.email.trim().to_lowercase(),
+ starts_at: slot.starts_at,
+ ends_at: slot.ends_at,
+ time_zone: request.time_zone,
+ hosts: slot.hosts,
+ status: BookingStatus::Processing,
+ attendance: BookingAttendance::Unknown,
+ reschedule_count: 0,
+ rescheduled_at: None,
+ location: event.location.clone(),
+ answers: request.answers,
+ question_labels: event
+ .questions
+ .iter()
+ .map(|q| (q.id, q.label.clone()))
+ .collect(),
+ },
+ };
+ let reservation_id = record.booking.id;
+ loop {
+ match self
+ .repository
+ .reserve(record.clone(), event.daily_limit, day_start, day_end)
+ .await
+ {
+ Ok(reserved) if reserved.booking.id != reservation_id => return Ok(reserved),
+ Ok(reserved) => return self.finish_operation(reserved).await,
+ Err(Error::Conflict) => {
+ let host = backup_hosts.next().ok_or(Error::Conflict)?;
+ record.calendar_id = Some(self.calendars.creation_calendar(&host).await?);
+ record.booking.hosts = vec![host];
+ }
+ Err(error) => return Err(error),
+ }
+ }
+ }
+ /// Read bookings for a profile, with authorization and a bounded range.
+ pub async fn bookings(&self, user: &str, team: Option<Uuid>) -> Result<Vec<Booking>, Error> {
+ let now = Utc::now();
+ self.bookings_in_range(
+ user,
+ team,
+ now - Duration::days(30),
+ now + Duration::days(31),
+ )
+ .await
+ }
+ /// Read a complete, authorized half-open range of booking start times.
+ /// Oversized ranges or result sets fail explicitly rather than returning partial insights.
+ pub async fn bookings_in_range(
+ &self,
+ user: &str,
+ team: Option<Uuid>,
+ start: DateTime<Utc>,
+ end: DateTime<Utc>,
+ ) -> Result<Vec<Booking>, Error> {
+ if end <= start || end - start > Duration::days(733) {
+ return Err(Error::Invalid(
+ "Choose a booking date range of no more than 733 days".into(),
+ ));
+ }
+ let id = Self::profile_id(user, team);
+ let Some(owner) = self.repository.profile(id).await? else {
+ self.settings(user, team).await?;
+ return Ok(vec![]);
+ };
+ self.authorize(user, &owner, false).await?;
+ Ok(self
+ .repository
+ .bookings(id, start, end)
+ .await?
+ .into_iter()
+ .map(|mut r| {
+ r.booking.question_labels = r
+ .event
+ .questions
+ .into_iter()
+ .map(|q| (q.id, q.label))
+ .collect();
+ r.booking
+ })
+ .collect())
+ }
+ /// Record attendance after a confirmed meeting, as its current host or an administrator.
+ pub async fn set_attendance(
+ &self,
+ user: &str,
+ id: Uuid,
+ attendance: BookingAttendance,
+ ) -> Result<Booking, Error> {
+ let mut record = self.repository.booking(id).await?.ok_or(Error::NotFound)?;
+ let owner = self
+ .repository
+ .profile(record.profile_id)
+ .await?
+ .ok_or(Error::NotFound)?;
+ if record.booking.hosts.iter().any(|host| host == user) {
+ self.authorize(user, &owner, false).await?;
+ } else {
+ self.authorize(user, &owner, true).await?;
+ }
+ if record.booking.status != BookingStatus::Confirmed || record.booking.ends_at > Utc::now()
+ {
+ return Err(Error::Invalid(
+ "Attendance can be recorded after a confirmed meeting has ended".into(),
+ ));
+ }
+ record.booking.attendance = attendance;
+ self.repository
+ .update_booking(record.clone(), BookingStatus::Confirmed)
+ .await?;
+ Ok(record.booking)
+ }
+ /// Approve a held booking, revalidating membership and calendar conflicts.
+ pub async fn approve(&self, user: &str, id: Uuid) -> Result<Booking, Error> {
+ let mut record = self.repository.booking(id).await?.ok_or(Error::NotFound)?;
+ let owner = self
+ .repository
+ .profile(record.profile_id)
+ .await?
+ .ok_or(Error::NotFound)?;
+ self.authorize(user, &owner, true).await?;
+ self.validate_booking_hosts(&owner, &record.booking.hosts)
+ .await?;
+ if record.booking.status != BookingStatus::Pending || record.booking.starts_at <= Utc::now()
+ {
+ return Err(Error::Conflict);
+ }
+ if self
+ .calendars
+ .busy(
+ &record.booking.hosts,
+ record.busy_start,
+ record.busy_end,
+ None,
+ )
+ .await?
+ .iter()
+ .any(|b| b.start < record.busy_end && b.end > record.busy_start)
+ {
+ return Err(Error::Conflict);
+ }
+ record.booking.status = BookingStatus::Processing;
+ record.calendar_id = Some(
+ self.calendars
+ .creation_calendar(
+ record
+ .booking
+ .hosts
+ .first()
+ .ok_or(Error::CalendarUnavailable)?,
+ )
+ .await?,
+ );
+ record.operation = Some(CalendarOperation::new(CalendarOperationKind::Create));
+ record = self
+ .repository
+ .update_booking(record, BookingStatus::Pending)
+ .await?;
+ Ok(self.finish_operation(record).await?.booking)
+ }
+ /// Let a profile administrator open the booking's management page.
+ pub async fn manage(&self, user: &str, id: Uuid) -> Result<BookingRecord, Error> {
+ let record = self.repository.booking(id).await?.ok_or(Error::NotFound)?;
+ let owner = self
+ .repository
+ .profile(record.profile_id)
+ .await?
+ .ok_or(Error::NotFound)?;
+ self.authorize(user, &owner, true).await?;
+ Ok(record)
+ }
+ /// Read a booking using its unguessable booker capability.
+ pub async fn receipt(&self, id: Uuid, token: Uuid) -> Result<BookingRecord, Error> {
+ let record = self.repository.booking(id).await?.ok_or(Error::NotFound)?;
+ if record.token != token {
+ return Err(Error::NotFound);
+ }
+ Ok(record)
+ }
+ /// Return replacement slots while excluding this booking's own reservation and calendar event.
+ pub async fn replacement_slots(
+ &self,
+ id: Uuid,
+ token: Uuid,
+ date: NaiveDate,
+ ) -> Result<Vec<Slot>, Error> {
+ let record = self.receipt(id, token).await?;
+ self.repository
+ .consume_budget(record.profile_id, PublicBudget::Availability)
+ .await?;
+ if !matches!(
+ record.booking.status,
+ BookingStatus::Pending | BookingStatus::Confirmed
+ ) {
+ return Err(Error::Conflict);
+ }
+ let owner = self
+ .repository
+ .profile(record.profile_id)
+ .await?
+ .ok_or(Error::NotFound)?;
+ let mut event = record.event.clone();
+ event.hosts = record.booking.hosts.clone();
+ event.mode = if event.hosts.len() == 1 {
+ SchedulingMode::Individual
+ } else {
+ SchedulingMode::Collective
+ };
+ // Current membership is authoritative even when the original link was removed.
+ self.validate_booking_hosts(&owner, &event.hosts).await?;
+ let (start, end) = day_bounds(&record.schedule, date)?;
+ if start > Utc::now() + Duration::days(i64::from(event.horizon_days) + 1)
+ || end < Utc::now()
+ {
+ return Ok(vec![]);
+ }
+ let occupied_start = start - Duration::minutes(i64::from(event.before_minutes));
+ let occupied_end = end + Duration::minutes(i64::from(event.after_minutes));
+ let mut busy = self
+ .calendars
+ .busy(
+ &event.hosts,
+ occupied_start,
+ occupied_end,
+ record.calendar_event_id,
+ )
+ .await?;
+ busy.extend(
+ self.repository
+ .busy(&event.hosts, occupied_start, occupied_end, Some(id))
+ .await?,
+ );
+ self.respect_host_hours(
+ &owner,
+ &event,
+ slots_for_date(&event, &record.schedule, date, Utc::now(), &busy)?,
+ )
+ .await
+ }
+ /// Move a booking while retaining both reservations until the calendar accepts the change.
+ pub async fn reschedule(
+ &self,
+ id: Uuid,
+ token: Uuid,
+ starts_at: DateTime<Utc>,
+ ) -> Result<BookingRecord, Error> {
+ let mut record = self.receipt(id, token).await?;
+ let original_start = record.booking.starts_at;
+ let date = starts_at
+ .with_timezone(&record.schedule.time_zone)
+ .date_naive();
+ let slot = self
+ .replacement_slots(id, token, date)
+ .await?
+ .into_iter()
+ .find(|s| s.starts_at == starts_at)
+ .ok_or(Error::Conflict)?;
+ let original_status = record.booking.status;
+ record.booking.starts_at = slot.starts_at;
+ record.booking.ends_at = slot.ends_at;
+ record.busy_start =
+ slot.starts_at - Duration::minutes(i64::from(record.event.before_minutes));
+ record.busy_end = slot.ends_at + Duration::minutes(i64::from(record.event.after_minutes));
+ record.booking.status = BookingStatus::Processing;
+ record.operation = Some(CalendarOperation::new(CalendarOperationKind::Move {
+ status: original_status,
+ original_start,
+ }));
+ let (start, end) = day_bounds(&record.schedule, date)?;
+ record = self
+ .repository
+ .move_booking(record, original_status, start, end)
+ .await?;
+ self.finish_operation(record).await
+ }
+ /// Cancel through a booker capability or an authorized profile administrator.
+ pub async fn cancel(
+ &self,
+ id: Uuid,
+ token: Option<Uuid>,
+ user: Option<&str>,
+ ) -> Result<Booking, Error> {
+ let mut record = self.repository.booking(id).await?.ok_or(Error::NotFound)?;
+ if token != Some(record.token) {
+ let owner = self
+ .repository
+ .profile(record.profile_id)
+ .await?
+ .ok_or(Error::NotFound)?;
+ self.authorize(user.ok_or(Error::Forbidden)?, &owner, true)
+ .await?;
+ }
+ if record.booking.status == BookingStatus::Cancelled {
+ return Ok(record.booking);
+ }
+ let expected = record.booking.status;
+ if expected == BookingStatus::Processing || expected == BookingStatus::Failed {
+ return Err(Error::Conflict);
+ }
+ record.booking.status = BookingStatus::Processing;
+ record.operation = Some(CalendarOperation::new(CalendarOperationKind::Cancel));
+ record = self.repository.update_booking(record, expected).await?;
+ Ok(self.finish_operation(record).await?.booking)
+ }
+}
+fn day_bounds(
+ schedule: &Schedule,
+ date: NaiveDate,
+) -> Result<(DateTime<Utc>, DateTime<Utc>), Error> {
+ let start = schedule
+ .time_zone
+ .from_local_datetime(&date.and_hms_opt(0, 0, 0).ok_or(Error::Conflict)?)
+ .earliest()
+ .ok_or(Error::Conflict)?;
+ let end = schedule
+ .time_zone
+ .from_local_datetime(
+ &date
+ .succ_opt()
+ .ok_or(Error::Conflict)?
+ .and_hms_opt(0, 0, 0)
+ .ok_or(Error::Conflict)?,
+ )
+ .earliest()
+ .ok_or(Error::Conflict)?;
+ Ok((start.with_timezone(&Utc), end.with_timezone(&Utc)))
+}
+
+#[cfg(test)]
+mod test;
diff --git a/crates/calendar_scheduling/src/domain/service/test.rs b/crates/calendar_scheduling/src/domain/service/test.rs
new file mode 100644
index 0000000000..fd3dfaaba5
--- /dev/null
+++ b/crates/calendar_scheduling/src/domain/service/test.rs
@@ -0,0 +1,1137 @@
+use super::*;
+use std::{
+ collections::HashMap,
+ sync::{
+ Arc, Mutex,
+ atomic::{AtomicBool, AtomicUsize, Ordering},
+ },
+};
+#[derive(Default)]
+struct Memory {
+ fail_completion: AtomicBool,
+ reserve_barrier: Option<tokio::sync::Barrier>,
+ reserve_calls: AtomicUsize,
+ profiles: Mutex<HashMap<Uuid, OwnedProfile>>,
+ bookings: Mutex<HashMap<Uuid, BookingRecord>>,
+}
+impl Repository for Arc<Memory> {
+ async fn consume_budget(&self, _: Uuid, _: PublicBudget) -> Result<(), Error> {
+ Ok(())
+ }
+ async fn claim_recovery(&self) -> Result<Option<BookingRecord>, Error> {
+ let mut data = self.bookings.lock().unwrap();
+ let Some(record) = data.values_mut().find(|r| {
+ matches!(
+ r.booking.status,
+ BookingStatus::Processing | BookingStatus::Failed
+ ) && r
+ .operation
+ .as_ref()
+ .is_some_and(|o| o.retry_at <= Utc::now())
+ }) else {
+ return Ok(None);
+ };
+ let operation = record.operation.as_mut().unwrap();
+ operation.attempt += 1;
+ record.revision += 1;
+ operation.retry_at = Utc::now() + Duration::minutes(5);
+ record.booking.status = BookingStatus::Processing;
+ Ok(Some(record.clone()))
+ }
+ async fn profile(&self, id: Uuid) -> Result<Option<OwnedProfile>, Error> {
+ Ok(self.profiles.lock().unwrap().get(&id).cloned())
+ }
+ async fn save_profile(&self, mut p: OwnedProfile) -> Result<Profile, Error> {
+ let mut data = self.profiles.lock().unwrap();
+ if data
+ .get(&p.profile.id)
+ .is_some_and(|old| old.profile.revision != p.profile.revision)
+ {
+ return Err(Error::Conflict);
+ }
+ p.profile.revision += 1;
+ let out = p.profile.clone();
+ data.insert(p.profile.id, p);
+ Ok(out)
+ }
+ async fn bookings(
+ &self,
+ p: Uuid,
+ start: DateTime<Utc>,
+ end: DateTime<Utc>,
+ ) -> Result<Vec<BookingRecord>, Error> {
+ Ok(self
+ .bookings
+ .lock()
+ .unwrap()
+ .values()
+ .filter(|r| {
+ r.profile_id == p && r.booking.starts_at >= start && r.booking.starts_at < end
+ })
+ .cloned()
+ .collect())
+ }
+ async fn host_booking_counts(
+ &self,
+ profile: Uuid,
+ hosts: &[String],
+ start: DateTime<Utc>,
+ end: DateTime<Utc>,
+ ) -> Result<std::collections::BTreeMap<String, i64>, Error> {
+ let bookings = self.bookings(profile, start, end).await?;
+ Ok(hosts
+ .iter()
+ .map(|host| {
+ (
+ host.clone(),
+ bookings
+ .iter()
+ .filter(|r| {
+ r.booking.status != BookingStatus::Cancelled
+ && r.booking.hosts.contains(host)
+ })
+ .count() as i64,
+ )
+ })
+ .collect())
+ }
+ async fn busy(
+ &self,
+ hosts: &[String],
+ start: DateTime<Utc>,
+ end: DateTime<Utc>,
+ exclude: Option<Uuid>,
+ ) -> Result<Vec<BusyRange>, Error> {
+ Ok(self
+ .bookings
+ .lock()
+ .unwrap()
+ .values()
+ .filter(|r| {
+ Some(r.booking.id) != exclude
+ && r.booking.status != BookingStatus::Cancelled
+ && r.busy_start < end
+ && r.busy_end > start
+ })
+ .flat_map(|r| {
+ r.booking
+ .hosts
+ .iter()
+ .filter(|h| hosts.contains(h))
+ .map(|h| BusyRange {
+ host: h.clone(),
+ start: r.busy_start,
+ end: r.busy_end,
+ })
+ })
+ .collect())
+ }
+ async fn reserve(
+ &self,
+ r: BookingRecord,
+ _: Option<u16>,
+ _: DateTime<Utc>,
+ _: DateTime<Utc>,
+ ) -> Result<BookingRecord, Error> {
+ if let Some(barrier) = &self.reserve_barrier
+ && self.reserve_calls.fetch_add(1, Ordering::SeqCst) < 2
+ {
+ barrier.wait().await;
+ }
+ let mut data = self.bookings.lock().unwrap();
+ if data.values().any(|b| {
+ b.booking.status != BookingStatus::Cancelled
+ && b.busy_start < r.busy_end
+ && b.busy_end > r.busy_start
+ && b.booking.hosts.iter().any(|h| r.booking.hosts.contains(h))
+ }) {
+ return Err(Error::Conflict);
+ }
+ data.insert(r.booking.id, r.clone());
+ Ok(r)
+ }
+ async fn booking(&self, id: Uuid) -> Result<Option<BookingRecord>, Error> {
+ Ok(self.bookings.lock().unwrap().get(&id).cloned())
+ }
+ async fn booking_request(&self, id: Uuid) -> Result<Option<BookingRecord>, Error> {
+ Ok(self
+ .bookings
+ .lock()
+ .unwrap()
+ .values()
+ .find(|r| r.request_id == id)
+ .cloned())
+ }
+ async fn update_booking(
+ &self,
+ mut r: BookingRecord,
+ expected: BookingStatus,
+ ) -> Result<BookingRecord, Error> {
+ if expected == BookingStatus::Processing
+ && self.fail_completion.swap(false, Ordering::SeqCst)
+ {
+ return Err(Error::Unavailable);
+ }
+ let mut data = self.bookings.lock().unwrap();
+ if data.get(&r.booking.id).is_none_or(|old| {
+ old.revision != r.revision
+ || old.booking.status != expected
+ || (expected == BookingStatus::Processing
+ && old.operation.as_ref().map(|o| (o.id, o.attempt))
+ != r.operation.as_ref().map(|o| (o.id, o.attempt)))
+ }) {
+ return Err(Error::Conflict);
+ }
+ r.revision += 1;
+ data.insert(r.booking.id, r.clone());
+ Ok(r)
+ }
+ async fn move_booking(
+ &self,
+ r: BookingRecord,
+ expected: BookingStatus,
+ _: DateTime<Utc>,
+ _: DateTime<Utc>,
+ ) -> Result<BookingRecord, Error> {
+ self.update_booking(r, expected).await
+ }
+}
+#[derive(Default)]
+struct Calendar {
+ creates: AtomicUsize,
+ lose_create_response: AtomicBool,
+ lose_move_response: AtomicBool,
+ lose_cancel_response: AtomicBool,
+ events: Mutex<HashMap<Uuid, Uuid>>,
+}
+impl Calendars for Arc<Calendar> {
+ async fn creation_calendar(&self, host: &str) -> Result<Uuid, Error> {
+ Ok(Uuid::new_v5(&Uuid::NAMESPACE_OID, host.as_bytes()))
+ }
+ async fn busy(
+ &self,
+ _: &[String],
+ _: DateTime<Utc>,
+ _: DateTime<Utc>,
+ _: Option<Uuid>,
+ ) -> Result<Vec<BusyRange>, Error> {
+ Ok(vec![])
+ }
+ async fn create(&self, record: &BookingRecord, _: &EventType) -> Result<(Uuid, String), Error> {
+ let id = *self
+ .events
+ .lock()
+ .unwrap()
+ .entry(record.booking.id)
+ .or_insert_with(|| {
+ self.creates.fetch_add(1, Ordering::SeqCst);
+ Uuid::now_v7()
+ });
+ if self.lose_create_response.swap(false, Ordering::SeqCst) {
+ return Err(Error::CalendarUnavailable);
+ }
+ Ok((id, "https://meet.google.com/test".into()))
+ }
+ async fn cancel(&self, _: &BookingRecord) -> Result<(), Error> {
+ if self.lose_cancel_response.swap(false, Ordering::SeqCst) {
+ return Err(Error::CalendarUnavailable);
+ }
+ Ok(())
+ }
+ async fn reschedule(&self, _: &BookingRecord) -> Result<(), Error> {
+ if self.lose_move_response.swap(false, Ordering::SeqCst) {
+ return Err(Error::CalendarUnavailable);
+ }
+ Ok(())
+ }
+}
+struct Members;
+impl Directory for Members {
+ async fn members(&self, _: Uuid) -> Result<Vec<TeamMember>, Error> {
+ Ok(vec![
+ TeamMember {
+ user_id: "admin".into(),
+ admin: true,
+ },
+ TeamMember {
+ user_id: "member".into(),
+ admin: false,
+ },
+ ])
+ }
+}
+type TestService = Service<Arc<Memory>, Arc<Calendar>, Members>;
+fn profile(team: Option<Uuid>) -> Profile {
+ let schedule = Schedule {
+ id: Uuid::new_v4(),
+ name: "Work".into(),
+ time_zone: chrono_tz::UTC,
+ weekly: (0..7)
+ .map(|day| WeeklyDay {
+ day,
+ windows: vec![TimeWindow {
+ start: "09:00".into(),
+ end: "17:00".into(),
+ }],
+ })
+ .collect(),
+ overrides: vec![],
+ };
+ let event = EventType {
+ id: Uuid::new_v4(),
+ title: "Meeting".into(),
+ slug: "meeting".into(),
+ description: String::new(),
+ duration_minutes: 30,
+ location: String::new(),
+ google_meet: false,
+ enabled: true,
+ schedule_id: schedule.id,
+ mode: if team.is_some() {
+ SchedulingMode::RoundRobin
+ } else {
+ SchedulingMode::Individual
+ },
+ hosts: if team.is_some() {
+ vec!["admin".into(), "member".into()]
+ } else {
+ vec!["admin".into()]
+ },
+ before_minutes: 0,
+ after_minutes: 0,
+ notice_minutes: 0,
+ horizon_days: 30,
+ interval_minutes: 30,
+ daily_limit: None,
+ requires_confirmation: false,
+ questions: vec![],
+ };
+ Profile {
+ id: TestService::profile_id("admin", team),
+ name: "Calendar".into(),
+ description: String::new(),
+ default_schedule_id: Some(schedule.id),
+ schedules: vec![schedule],
+ event_types: vec![event],
+ revision: 0,
+ }
+}
+fn request() -> BookingRequest {
+ BookingRequest {
+ starts_at: (Utc::now().date_naive() + Duration::days(2))
+ .and_hms_opt(10, 0, 0)
+ .unwrap()
+ .and_utc(),
+ name: "Booker".into(),
+ email: "[email protected]".into(),
+ time_zone: chrono_tz::UTC,
+ answers: Default::default(),
+ request_id: Uuid::new_v4(),
+ }
+}
+#[tokio::test]
+async fn team_permissions_and_host_membership_are_server_enforced() {
+ let service = TestService::new(
+ Arc::new(Memory::default()),
+ Arc::new(Calendar::default()),
+ Members,
+ );
+ let team = Some(Uuid::new_v4());
+ let p = profile(team);
+ assert!(matches!(
+ service.save("member", team, p.clone()).await,
+ Err(Error::Forbidden)
+ ));
+ assert!(matches!(
+ service.settings("stranger", team).await,
+ Err(Error::Forbidden)
+ ));
+ let mut bad = p.clone();
+ bad.event_types[0].hosts.push("stranger".into());
+ assert!(matches!(
+ service.save("admin", team, bad).await,
+ Err(Error::Invalid(_))
+ ));
+ assert!(service.save("admin", team, p).await.is_ok());
+ assert!(service.settings("member", team).await.is_ok());
+}
+#[tokio::test]
+async fn personal_calendar_cannot_impersonate_another_host() {
+ let service = TestService::new(
+ Arc::new(Memory::default()),
+ Arc::new(Calendar::default()),
+ Members,
+ );
+ let mut p = profile(None);
+ p.event_types[0].hosts = vec!["member".into()];
+ assert!(matches!(
+ service.save("admin", None, p).await,
+ Err(Error::Invalid(_))
+ ));
+}
+#[tokio::test]
+async fn booking_retry_is_idempotent_and_another_request_conflicts() {
+ let cal = Arc::new(Calendar::default());
+ let service = TestService::new(Arc::new(Memory::default()), cal.clone(), Members);
+ let p = service.save("admin", None, profile(None)).await.unwrap();
+ let r = request();
+ let a = service
+ .book(p.id, p.event_types[0].id, r.clone())
+ .await
+ .unwrap();
+ let b = service.book(p.id, p.event_types[0].id, r).await.unwrap();
+ assert_eq!(a.booking.id, b.booking.id);
+ assert_eq!(cal.creates.load(Ordering::SeqCst), 1);
+ assert!(matches!(
+ service.book(p.id, p.event_types[0].id, request()).await,
+ Err(Error::Conflict)
+ ));
+ assert!(matches!(
+ service.receipt(a.booking.id, Uuid::new_v4()).await,
+ Err(Error::NotFound)
+ ));
+ service
+ .cancel(a.booking.id, Some(a.token), None)
+ .await
+ .unwrap();
+ assert!(
+ service
+ .book(p.id, p.event_types[0].id, request())
+ .await
+ .is_ok()
+ );
+}
+#[tokio::test]
+async fn concurrent_round_robin_bookings_use_distinct_hosts_and_calendars() {
+ let repo = Arc::new(Memory {
+ reserve_barrier: Some(tokio::sync::Barrier::new(2)),
+ ..Default::default()
+ });
+ let cal = Arc::new(Calendar::default());
+ let service = TestService::new(repo.clone(), cal.clone(), Members);
+ let team = Some(Uuid::new_v4());
+ let p = service.save("admin", team, profile(team)).await.unwrap();
+ let retry = request();
+ let (a, b) = tokio::join!(
+ service.book(p.id, p.event_types[0].id, retry.clone()),
+ service.book(p.id, p.event_types[0].id, request()),
+ );
+ let (a, b) = (a.unwrap(), b.unwrap());
+ assert_ne!(a.booking.hosts, b.booking.hosts);
+ assert_eq!(a.booking.hosts.len(), 1);
+ assert_eq!(b.booking.hosts.len(), 1);
+ for record in [&a, &b] {
+ assert_eq!(
+ record.calendar_id,
+ Some(
+ cal.creation_calendar(&record.booking.hosts[0])
+ .await
+ .unwrap()
+ )
+ );
+ }
+ assert_eq!(cal.creates.load(Ordering::SeqCst), 2);
+ assert_eq!(
+ service
+ .book(p.id, p.event_types[0].id, retry)
+ .await
+ .unwrap()
+ .booking
+ .id,
+ a.booking.id
+ );
+ assert!(matches!(
+ service.book(p.id, p.event_types[0].id, request()).await,
+ Err(Error::Conflict)
+ ));
+ assert_eq!(cal.creates.load(Ordering::SeqCst), 2);
+}
+#[tokio::test]
+async fn pending_booking_can_be_approved_after_link_is_removed() {
+ let service = TestService::new(
+ Arc::new(Memory::default()),
+ Arc::new(Calendar::default()),
+ Members,
+ );
+ let p = profile(None);
+ let mut p = service.save("admin", None, p).await.unwrap();
+ let booking = service
+ .book(p.id, p.event_types[0].id, request())
+ .await
+ .unwrap();
+ let mut legacy = booking.clone();
+ legacy.booking.status = BookingStatus::Pending;
+ legacy.event.requires_confirmation = true;
+ legacy.calendar_event_id = None;
+ service
+ .repository
+ .bookings
+ .lock()
+ .unwrap()
+ .insert(legacy.booking.id, legacy);
+ p.event_types.clear();
+ service.save("admin", None, p).await.unwrap();
+ assert_eq!(
+ service
+ .approve("admin", booking.booking.id)
+ .await
+ .unwrap()
+ .status,
+ BookingStatus::Confirmed
+ );
+ let moved = service
+ .reschedule(
+ booking.booking.id,
+ booking.token,
+ booking.booking.starts_at + Duration::hours(1),
+ )
+ .await
+ .unwrap();
+ assert_eq!(moved.booking.status, BookingStatus::Confirmed);
+ assert_eq!(moved.booking.reschedule_count, 1);
+}
+#[tokio::test]
+async fn reschedule_keeps_identity_and_releases_the_old_slot() {
+ let cal = Arc::new(Calendar::default());
+ let service = TestService::new(Arc::new(Memory::default()), cal.clone(), Members);
+ let p = service.save("admin", None, profile(None)).await.unwrap();
+ let a = service
+ .book(p.id, p.event_types[0].id, request())
+ .await
+ .unwrap();
+ let next = a.booking.starts_at + Duration::hours(1);
+ assert!(matches!(
+ service.manage("stranger", a.booking.id).await,
+ Err(Error::Forbidden)
+ ));
+ let b = service
+ .reschedule(a.booking.id, a.token, next)
+ .await
+ .unwrap();
+ assert_eq!(b.booking.id, a.booking.id);
+ assert_eq!(b.calendar_event_id, a.calendar_event_id);
+ assert_eq!(b.booking.starts_at, next);
+ assert_eq!(b.booking.status, BookingStatus::Confirmed);
+ assert_eq!(b.booking.reschedule_count, 1);
+ assert!(b.booking.rescheduled_at.is_some());
+ let unchanged = service
+ .reschedule(b.booking.id, b.token, next)
+ .await
+ .unwrap();
+ assert_eq!(unchanged.booking.reschedule_count, 1);
+ assert_eq!(unchanged.booking.rescheduled_at, b.booking.rescheduled_at);
+ assert_eq!(cal.creates.load(Ordering::SeqCst), 1);
+ assert!(
+ service
+ .book(p.id, p.event_types[0].id, request())
+ .await
+ .is_ok()
+ );
+}
+
+#[tokio::test]
+async fn visitor_time_zone_uses_the_visitors_local_date() {
+ let service = TestService::new(
+ Arc::new(Memory::default()),
+ Arc::new(Calendar::default()),
+ Members,
+ );
+ let p = service.save("admin", None, profile(None)).await.unwrap();
+ let date = request().starts_at.date_naive();
+ let zone = chrono_tz::Pacific::Auckland;
+ let slots = service
+ .slots_in_zone(p.id, p.event_types[0].id, date, zone)
+ .await
+ .unwrap();
+ assert!(!slots.is_empty());
+ assert!(
+ slots
+ .iter()
+ .all(|s| s.starts_at.with_timezone(&zone).date_naive() == date)
+ );
+}
+
+#[tokio::test]
+async fn approval_rechecks_assigned_hosts_even_after_link_removal() {
+ struct ChangingMembers(Arc<Mutex<Vec<TeamMember>>>);
+ impl Directory for ChangingMembers {
+ async fn members(&self, _: Uuid) -> Result<Vec<TeamMember>, Error> {
+ Ok(self.0.lock().unwrap().clone())
+ }
+ }
+ let members = Arc::new(Mutex::new(vec![
+ TeamMember {
+ user_id: "admin".into(),
+ admin: true,
+ },
+ TeamMember {
+ user_id: "member".into(),
+ admin: false,
+ },
+ ]));
+ let service = Service::new(
+ Arc::new(Memory::default()),
+ Arc::new(Calendar::default()),
+ ChangingMembers(members.clone()),
+ );
+ let team = Some(Uuid::new_v4());
+ let mut p = profile(team);
+ p.event_types[0].hosts = vec!["member".into()];
+ let mut p = service.save("admin", team, p).await.unwrap();
+ let b = service
+ .book(p.id, p.event_types[0].id, request())
+ .await
+ .unwrap();
+ let mut legacy = b.clone();
+ legacy.booking.status = BookingStatus::Pending;
+ legacy.calendar_event_id = None;
+ service
+ .repository
+ .bookings
+ .lock()
+ .unwrap()
+ .insert(legacy.booking.id, legacy);
+ p.event_types.clear();
+ service.save("admin", team, p).await.unwrap();
+ members.lock().unwrap().retain(|m| m.admin);
+ assert!(matches!(
+ service.approve("admin", b.booking.id).await,
+ Err(Error::Forbidden)
+ ));
+}
+
+#[tokio::test]
+async fn attendance_requires_finished_confirmed_booking_and_current_host_or_admin() {
+ let store = Arc::new(Memory::default());
+ let service = TestService::new(store.clone(), Arc::new(Calendar::default()), Members);
+ let team = Some(Uuid::new_v4());
+ let mut p = profile(team);
+ p.event_types[0].hosts = vec!["member".into()];
+ let p = service.save("admin", team, p).await.unwrap();
+ let r = service
+ .book(p.id, p.event_types[0].id, request())
+ .await
+ .unwrap();
+ assert!(matches!(
+ service
+ .set_attendance("member", r.booking.id, BookingAttendance::Attended)
+ .await,
+ Err(Error::Invalid(_))
+ ));
+ {
+ let mut data = store.bookings.lock().unwrap();
+ let r = data.get_mut(&r.booking.id).unwrap();
+ r.booking.starts_at = Utc::now() - Duration::hours(2);
+ r.booking.ends_at = Utc::now() - Duration::hours(1);
+ }
+ assert!(matches!(
+ service
+ .set_attendance("stranger", r.booking.id, BookingAttendance::GuestNoShow)
+ .await,
+ Err(Error::Forbidden)
+ ));
+ assert_eq!(
+ service
+ .set_attendance("member", r.booking.id, BookingAttendance::Attended)
+ .await
+ .unwrap()
+ .attendance,
+ BookingAttendance::Attended
+ );
+ assert_eq!(
+ service
+ .set_attendance("admin", r.booking.id, BookingAttendance::GuestNoShow)
+ .await
+ .unwrap()
+ .attendance,
+ BookingAttendance::GuestNoShow
+ );
+ assert_eq!(
+ service
+ .set_attendance("admin", r.booking.id, BookingAttendance::Unknown)
+ .await
+ .unwrap()
+ .attendance,
+ BookingAttendance::Unknown
+ );
+ store
+ .bookings
+ .lock()
+ .unwrap()
+ .get_mut(&r.booking.id)
+ .unwrap()
+ .booking
+ .status = BookingStatus::Pending;
+ assert!(matches!(
+ service
+ .set_attendance("admin", r.booking.id, BookingAttendance::Attended)
+ .await,
+ Err(Error::Invalid(_))
+ ));
+}
+
+#[tokio::test]
+async fn unrelated_team_member_cannot_record_attendance() {
+ let store = Arc::new(Memory::default());
+ let service = TestService::new(store.clone(), Arc::new(Calendar::default()), Members);
+ let team = Some(Uuid::new_v4());
+ let mut p = profile(team);
+ p.event_types[0].hosts = vec!["admin".into()];
+ let p = service.save("admin", team, p).await.unwrap();
+ let r = service
+ .book(p.id, p.event_types[0].id, request())
+ .await
+ .unwrap();
+ store
+ .bookings
+ .lock()
+ .unwrap()
+ .get_mut(&r.booking.id)
+ .unwrap()
+ .booking
+ .ends_at = Utc::now() - Duration::hours(1);
+ assert!(matches!(
+ service
+ .set_attendance("member", r.booking.id, BookingAttendance::HostNoShow)
+ .await,
+ Err(Error::Forbidden)
+ ));
+}
+
+#[tokio::test]
+async fn booking_ranges_are_half_open_bounded_and_authorized() {
+ let service = TestService::new(
+ Arc::new(Memory::default()),
+ Arc::new(Calendar::default()),
+ Members,
+ );
+ let team = Some(Uuid::new_v4());
+ let p = service.save("admin", team, profile(team)).await.unwrap();
+ let r = service
+ .book(p.id, p.event_types[0].id, request())
+ .await
+ .unwrap();
+ let start = r.booking.starts_at;
+ assert_eq!(
+ service
+ .bookings_in_range("member", team, start, start + Duration::hours(1))
+ .await
+ .unwrap()
+ .len(),
+ 1
+ );
+ assert!(
+ service
+ .bookings_in_range("member", team, start - Duration::hours(1), start)
+ .await
+ .unwrap()
+ .is_empty()
+ );
+ assert!(matches!(
+ service
+ .bookings_in_range("stranger", team, start, start + Duration::hours(1))
+ .await,
+ Err(Error::Forbidden)
+ ));
+ assert!(matches!(
+ service.bookings_in_range("admin", team, start, start).await,
+ Err(Error::Invalid(_))
+ ));
+ assert!(matches!(
+ service
+ .bookings_in_range("admin", team, start, start + Duration::days(734))
+ .await,
+ Err(Error::Invalid(_))
+ ));
+}
+
+#[tokio::test]
+async fn legacy_booking_metadata_defaults_without_inventing_attendance_or_history() {
+ let service = TestService::new(
+ Arc::new(Memory::default()),
+ Arc::new(Calendar::default()),
+ Members,
+ );
+ let p = service.save("admin", None, profile(None)).await.unwrap();
+ let r = service
+ .book(p.id, p.event_types[0].id, request())
+ .await
+ .unwrap();
+ let mut json = serde_json::to_value(r).unwrap();
+ let booking = json["booking"].as_object_mut().unwrap();
+ booking.remove("attendance");
+ booking.remove("rescheduleCount");
+ booking.remove("rescheduledAt");
+ let decoded: BookingRecord = serde_json::from_value(json).unwrap();
+ assert_eq!(decoded.booking.attendance, BookingAttendance::Unknown);
+ assert_eq!(decoded.booking.reschedule_count, 0);
+ assert_eq!(decoded.booking.rescheduled_at, None);
+}
+
+#[tokio::test]
+async fn removed_host_in_another_link_does_not_break_current_team_booking() {
+ let store = Arc::new(Memory::default());
+ let service = TestService::new(store.clone(), Arc::new(Calendar::default()), Members);
+ let team = Some(Uuid::new_v4());
+ let p = service.save("admin", team, profile(team)).await.unwrap();
+ let mut unrelated = p.event_types[0].clone();
+ unrelated.id = Uuid::new_v4();
+ unrelated.slug = "old-link".into();
+ unrelated.hosts = vec!["former-member".into()];
+ store
+ .profiles
+ .lock()
+ .unwrap()
+ .get_mut(&p.id)
+ .unwrap()
+ .profile
+ .event_types
+ .push(unrelated.clone());
+ assert!(
+ !service
+ .slots(p.id, p.event_types[0].id, request().starts_at.date_naive())
+ .await
+ .unwrap()
+ .is_empty()
+ );
+ assert!(matches!(
+ service
+ .slots(p.id, unrelated.id, request().starts_at.date_naive())
+ .await,
+ Err(Error::Forbidden)
+ ));
+ assert!(
+ service
+ .book(p.id, p.event_types[0].id, request())
+ .await
+ .is_ok()
+ );
+}
+
+#[tokio::test]
+async fn team_slots_intersect_each_hosts_personal_default_hours_in_their_zone() {
+ let service = TestService::new(
+ Arc::new(Memory::default()),
+ Arc::new(Calendar::default()),
+ Members,
+ );
+ let mut personal = profile(None);
+ let mut defaults = personal.schedules[0].clone();
+ defaults.id = Uuid::new_v4();
+ defaults.time_zone = chrono_tz::America::New_York;
+ for day in &mut defaults.weekly {
+ day.windows = vec![TimeWindow {
+ start: "09:00".into(),
+ end: "10:00".into(),
+ }];
+ }
+ personal.default_schedule_id = Some(defaults.id);
+ personal.schedules.push(defaults);
+ service.save("admin", None, personal).await.unwrap();
+ let team = Some(Uuid::new_v4());
+ let mut p = profile(team);
+ p.event_types[0].mode = SchedulingMode::Collective;
+ let p = service.save("admin", team, p).await.unwrap();
+ let date = request().starts_at.date_naive();
+ let slots = service
+ .slots(p.id, p.event_types[0].id, date)
+ .await
+ .unwrap();
+ assert_eq!(slots.len(), 2);
+ assert!(slots.iter().all(|s| {
+ s.starts_at
+ .with_timezone(&chrono_tz::America::New_York)
+ .time()
+ >= chrono::NaiveTime::from_hms_opt(9, 0, 0).unwrap()
+ }));
+ assert!(slots.iter().all(|s| {
+ s.ends_at
+ .with_timezone(&chrono_tz::America::New_York)
+ .time()
+ <= chrono::NaiveTime::from_hms_opt(10, 0, 0).unwrap()
+ }));
+ let mut p = p;
+ p.event_types[0].mode = SchedulingMode::RoundRobin;
+ let p = service.save("admin", team, p).await.unwrap();
+ let slots = service
+ .slots(p.id, p.event_types[0].id, date)
+ .await
+ .unwrap();
+ let outside = slots
+ .iter()
+ .find(|s| s.starts_at == request().starts_at)
+ .unwrap();
+ assert_eq!(outside.hosts, vec!["member"]);
+ let b = service
+ .book(p.id, p.event_types[0].id, request())
+ .await
+ .unwrap();
+ assert_eq!(b.booking.hosts, vec!["member"]);
+}
+
+fn make_due(store: &Memory, id: Uuid) {
+ store
+ .bookings
+ .lock()
+ .unwrap()
+ .get_mut(&id)
+ .unwrap()
+ .operation
+ .as_mut()
+ .unwrap()
+ .retry_at = Utc::now() - Duration::seconds(1);
+}
+
+#[tokio::test]
+async fn recovery_after_lost_create_response_creates_only_one_invitation() {
+ let store = Arc::new(Memory::default());
+ let calendars = Arc::new(Calendar {
+ lose_create_response: AtomicBool::new(true),
+ ..Default::default()
+ });
+ let service = TestService::new(store.clone(), calendars.clone(), Members);
+ let p = service.save("admin", None, profile(None)).await.unwrap();
+ assert_eq!(
+ service
+ .book(p.id, p.event_types[0].id, request())
+ .await
+ .unwrap()
+ .booking
+ .status,
+ BookingStatus::Failed
+ );
+ assert!(matches!(
+ service.book(p.id, p.event_types[0].id, request()).await,
+ Err(Error::Conflict)
+ ));
+ let record = store
+ .bookings
+ .lock()
+ .unwrap()
+ .values()
+ .next()
+ .unwrap()
+ .clone();
+ assert_eq!(record.booking.status, BookingStatus::Failed);
+ assert!(!service.recover_once().await.unwrap());
+ make_due(&store, record.booking.id);
+ assert!(service.recover_once().await.unwrap());
+ assert_eq!(
+ service
+ .receipt(record.booking.id, record.token)
+ .await
+ .unwrap()
+ .booking
+ .status,
+ BookingStatus::Confirmed
+ );
+ assert_eq!(calendars.creates.load(Ordering::SeqCst), 1);
+ assert!(!service.recover_once().await.unwrap());
+}
+
+#[tokio::test]
+async fn recovery_finishes_move_once_and_cancel_releases_the_slot() {
+ let store = Arc::new(Memory::default());
+ let calendars = Arc::new(Calendar::default());
+ let service = TestService::new(store.clone(), calendars.clone(), Members);
+ let p = service.save("admin", None, profile(None)).await.unwrap();
+ let r = service
+ .book(p.id, p.event_types[0].id, request())
+ .await
+ .unwrap();
+ calendars.lose_move_response.store(true, Ordering::SeqCst);
+ let next = r.booking.starts_at + Duration::hours(1);
+ assert_eq!(
+ service
+ .reschedule(r.booking.id, r.token, next)
+ .await
+ .unwrap()
+ .booking
+ .status,
+ BookingStatus::Failed
+ );
+ let stored = store.booking(r.booking.id).await.unwrap().unwrap();
+ assert_eq!(stored.booking.status, BookingStatus::Failed);
+ assert_eq!(stored.booking.reschedule_count, 0);
+ assert_eq!(stored.booking.rescheduled_at, None);
+ make_due(&store, r.booking.id);
+ assert!(service.recover_once().await.unwrap());
+ let moved = service.receipt(r.booking.id, r.token).await.unwrap();
+ assert_eq!(moved.booking.starts_at, next);
+ assert_eq!(moved.booking.reschedule_count, 1);
+ assert!(!service.recover_once().await.unwrap());
+ calendars.lose_cancel_response.store(true, Ordering::SeqCst);
+ assert_eq!(
+ service
+ .cancel(r.booking.id, Some(r.token), None)
+ .await
+ .unwrap()
+ .status,
+ BookingStatus::Failed
+ );
+ make_due(&store, r.booking.id);
+ assert!(service.recover_once().await.unwrap());
+ assert_eq!(
+ service
+ .receipt(r.booking.id, r.token)
+ .await
+ .unwrap()
+ .booking
+ .status,
+ BookingStatus::Cancelled
+ );
+}
+
+#[tokio::test]
+async fn restart_recovers_processing_and_old_worker_cannot_complete_new_claim() {
+ let store = Arc::new(Memory::default());
+ let calendars = Arc::new(Calendar::default());
+ let service = TestService::new(store.clone(), calendars.clone(), Members);
+ let p = service.save("admin", None, profile(None)).await.unwrap();
+ let mut r = service
+ .book(p.id, p.event_types[0].id, request())
+ .await
+ .unwrap();
+ r.booking.status = BookingStatus::Processing;
+ store
+ .bookings
+ .lock()
+ .unwrap()
+ .insert(r.booking.id, r.clone());
+ make_due(&store, r.booking.id);
+ let claimed = store.claim_recovery().await.unwrap().unwrap();
+ let receipt = service.finish_operation(r).await.unwrap();
+ assert_eq!(receipt.booking.id, claimed.booking.id);
+ assert_eq!(receipt.token, claimed.token);
+ assert_eq!(receipt.revision, claimed.revision);
+ assert_eq!(receipt.booking.status, BookingStatus::Processing);
+ assert_eq!(
+ store
+ .booking(claimed.booking.id)
+ .await
+ .unwrap()
+ .unwrap()
+ .revision,
+ claimed.revision
+ );
+ service.finish_operation(claimed).await.unwrap();
+ assert_eq!(calendars.creates.load(Ordering::SeqCst), 1);
+}
+
+#[tokio::test]
+async fn new_manual_approval_configuration_and_legacy_links_are_blocked() {
+ let store = Arc::new(Memory::default());
+ let service = TestService::new(store.clone(), Arc::new(Calendar::default()), Members);
+ let mut p = profile(None);
+ p.event_types[0].requires_confirmation = true;
+ assert!(matches!(
+ service.save("admin", None, p.clone()).await,
+ Err(Error::Invalid(_))
+ ));
+ store
+ .save_profile(OwnedProfile {
+ user_id: Some("admin".into()),
+ team_id: None,
+ profile: p.clone(),
+ })
+ .await
+ .unwrap();
+ assert!(matches!(
+ service.book(p.id, p.event_types[0].id, request()).await,
+ Err(Error::Invalid(_))
+ ));
+ assert!(store.bookings.lock().unwrap().is_empty());
+}
+
+#[tokio::test]
+async fn completion_database_failure_still_returns_private_receipt_and_recovers() {
+ let store = Arc::new(Memory::default());
+ let calendars = Arc::new(Calendar::default());
+ let service = TestService::new(store.clone(), calendars.clone(), Members);
+ let p = service.save("admin", None, profile(None)).await.unwrap();
+ store.fail_completion.store(true, Ordering::SeqCst);
+ let receipt = service
+ .book(p.id, p.event_types[0].id, request())
+ .await
+ .unwrap();
+ assert_eq!(receipt.booking.status, BookingStatus::Processing);
+ assert_eq!(
+ service
+ .receipt(receipt.booking.id, receipt.token)
+ .await
+ .unwrap()
+ .booking
+ .status,
+ BookingStatus::Processing
+ );
+ make_due(&store, receipt.booking.id);
+ assert!(service.recover_once().await.unwrap());
+ assert_eq!(
+ service
+ .receipt(receipt.booking.id, receipt.token)
+ .await
+ .unwrap()
+ .booking
+ .status,
+ BookingStatus::Confirmed
+ );
+ assert_eq!(calendars.creates.load(Ordering::SeqCst), 1);
+}
+
+#[tokio::test]
+async fn invalid_email_never_reserves_a_slot_or_calls_the_provider() {
+ let store = Arc::new(Memory::default());
+ let calendars = Arc::new(Calendar::default());
+ let service = TestService::new(store.clone(), calendars.clone(), Members);
+ let profile = service.save("admin", None, profile(None)).await.unwrap();
+ for email in ["@", "a@@b", "[email protected]\n", "guest example.com"] {
+ let mut request = request();
+ request.email = email.into();
+ assert!(matches!(
+ service
+ .book(profile.id, profile.event_types[0].id, request)
+ .await,
+ Err(Error::Invalid(_))
+ ));
+ }
+ assert!(store.bookings.lock().unwrap().is_empty());
+ assert_eq!(calendars.creates.load(Ordering::SeqCst), 0);
+}
+
+#[tokio::test]
+async fn stale_team_events_can_be_repaired_one_at_a_time() {
+ let store = Arc::new(Memory::default());
+ let service = TestService::new(store.clone(), Arc::new(Calendar::default()), Members);
+ let team = Uuid::now_v7();
+ let mut profile = service
+ .save("admin", Some(team), profile(Some(team)))
+ .await
+ .unwrap();
+ let mut second = profile.event_types[0].clone();
+ second.id = Uuid::now_v7();
+ second.slug = "second".into();
+ profile.event_types.push(second);
+ for event in &mut profile.event_types {
+ event.hosts.push("departed".into());
+ event.requires_confirmation = true;
+ }
+ store
+ .profiles
+ .lock()
+ .unwrap()
+ .get_mut(&profile.id)
+ .unwrap()
+ .profile = profile.clone();
+ for index in 0..2 {
+ profile.event_types[index]
+ .hosts
+ .retain(|host| host != "departed");
+ profile.event_types[index].requires_confirmation = false;
+ profile = service.save("admin", Some(team), profile).await.unwrap();
+ }
+ profile.event_types[0].hosts.push("new-outsider".into());
+ assert!(matches!(
+ service.save("admin", Some(team), profile).await,
+ Err(Error::Invalid(_))
+ ));
+}
diff --git a/crates/calendar_scheduling/src/inbound.rs b/crates/calendar_scheduling/src/inbound.rs
new file mode 100644
index 0000000000..f1de119bd9
--- /dev/null
+++ b/crates/calendar_scheduling/src/inbound.rs
@@ -0,0 +1,2 @@
+//! HTTP adapters for scheduling use cases.
+pub mod router;
diff --git a/crates/calendar_scheduling/src/inbound/router.rs b/crates/calendar_scheduling/src/inbound/router.rs
new file mode 100644
index 0000000000..eb38042a05
--- /dev/null
+++ b/crates/calendar_scheduling/src/inbound/router.rs
@@ -0,0 +1,390 @@
+//! Thin HTTP routes; membership, availability, and write policy live in the service.
+use crate::domain::{models::*, ports::*, service::Service};
+use axum::{
+ Json, Router,
+ extract::{DefaultBodyLimit, FromRef, Path, Query, State},
+ http::{HeaderMap, StatusCode},
+ response::{IntoResponse, Response},
+ routing::{get, post},
+};
+use macro_authorization::{
+ MacroAuthorizationExtractor, MacroAuthorizationService, MacroAuthorizationState, UserOrInternal,
+};
+use serde::{Deserialize, Serialize};
+use std::sync::Arc;
+use uuid::Uuid;
+
+/// Scheduling service and authentication state.
+pub struct RouterState<R, C, D, A> {
+ service: Arc<Service<R, C, D>>,
+ auth: MacroAuthorizationState<A>,
+}
+impl<R, C, D, A> Clone for RouterState<R, C, D, A> {
+ fn clone(&self) -> Self {
+ Self {
+ service: self.service.clone(),
+ auth: self.auth.clone(),
+ }
+ }
+}
+impl<R, C, D, A> FromRef<RouterState<R, C, D, A>> for MacroAuthorizationState<A> {
+ fn from_ref(s: &RouterState<R, C, D, A>) -> Self {
+ s.auth.clone()
+ }
+}
+impl<R, C, D, A> RouterState<R, C, D, A> {
+ /// Bind the domain service to the host's authentication.
+ pub fn new(service: Arc<Service<R, C, D>>, auth: MacroAuthorizationState<A>) -> Self {
+ Self { service, auth }
+ }
+}
+/// Scheduling API mounted beneath `/calendar/scheduling`.
+pub fn router<
+ R: Repository,
+ C: Calendars,
+ D: Directory,
+ A: MacroAuthorizationService,
+ T: Send + Sync + 'static,
+>(
+ state: RouterState<R, C, D, A>,
+) -> Router<T> {
+ Router::new()
+ .route(
+ "/settings",
+ get(settings::<R, C, D, A>).put(save::<R, C, D, A>),
+ )
+ .route("/bookings", get(bookings::<R, C, D, A>))
+ .route("/bookings/{id}/manage", get(manage::<R, C, D, A>))
+ .route("/bookings/{id}/approve", post(approve::<R, C, D, A>))
+ .route("/bookings/{id}/attendance", post(attendance::<R, C, D, A>))
+ .route("/bookings/{id}/cancel", post(cancel::<R, C, D, A>))
+ .route("/public/{profile}", get(public_profile::<R, C, D, A>))
+ .route("/public/{profile}/{event}/slots", get(slots::<R, C, D, A>))
+ .route("/public/{profile}/{event}/book", post(book::<R, C, D, A>))
+ .route("/public/bookings/{id}", get(receipt::<R, C, D, A>))
+ .route(
+ "/public/bookings/{id}/cancel",
+ post(cancel_public::<R, C, D, A>),
+ )
+ .route(
+ "/public/bookings/{id}/slots",
+ get(replacement_slots::<R, C, D, A>),
+ )
+ .route(
+ "/public/bookings/{id}/reschedule",
+ post(reschedule::<R, C, D, A>),
+ )
+ .layer(DefaultBodyLimit::max(128 * 1024))
+ .layer(axum::middleware::from_fn(no_store))
+ .with_state(state)
+}
+#[derive(Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct Scope {
+ team_id: Option<Uuid>,
+}
+#[derive(Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct BookingRange {
+ team_id: Option<Uuid>,
+ from: Option<chrono::DateTime<chrono::Utc>>,
+ to: Option<chrono::DateTime<chrono::Utc>>,
+}
+#[derive(Deserialize)]
+struct AttendanceRequest {
+ attendance: BookingAttendance,
+}
+#[derive(Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct SlotQuery {
+ date: chrono::NaiveDate,
+ time_zone: Option<chrono_tz::Tz>,
+}
+#[derive(Deserialize)]
+struct ReplacementQuery {
+ date: chrono::NaiveDate,
+}
+#[derive(Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct RescheduleRequest {
+ starts_at: chrono::DateTime<chrono::Utc>,
+ token: Uuid,
+}
+#[derive(Deserialize)]
+struct Token {
+ token: Uuid,
+}
+#[derive(Serialize)]
+struct ProfileResponse {
+ profile: Profile,
+}
+#[derive(Serialize)]
+struct BookingsResponse {
+ bookings: Vec<Booking>,
+}
+#[derive(Serialize)]
+struct BookingResponse {
+ booking: Booking,
+}
+#[derive(Serialize)]
+#[serde(rename_all = "camelCase")]
+struct ReceiptResponse {
+ booking: Booking,
+ token: Uuid,
+ schedule_time_zone: chrono_tz::Tz,
+}
+#[derive(Serialize)]
+struct SlotsResponse {
+ slots: Vec<Slot>,
+}
+#[derive(Serialize)]
+struct PublicResponse {
+ profile: PublicProfile,
+}
+struct ApiError(Error);
+impl From<Error> for ApiError {
+ fn from(e: Error) -> Self {
+ Self(e)
+ }
+}
+impl IntoResponse for ApiError {
+ fn into_response(self) -> Response {
+ let status = match self.0 {
+ Error::RateLimited => StatusCode::TOO_MANY_REQUESTS,
+ Error::NotFound => StatusCode::NOT_FOUND,
+ Error::Forbidden => StatusCode::FORBIDDEN,
+ Error::Conflict => StatusCode::CONFLICT,
+ Error::Invalid(_) => StatusCode::BAD_REQUEST,
+ Error::CalendarUnavailable | Error::Unavailable => StatusCode::SERVICE_UNAVAILABLE,
+ };
+ let mut response = (
+ status,
+ Json(serde_json::json!({"message": self.0.to_string()})),
+ )
+ .into_response();
+ if status == StatusCode::TOO_MANY_REQUESTS {
+ response.headers_mut().insert(
+ axum::http::header::RETRY_AFTER,
+ axum::http::HeaderValue::from_static("60"),
+ );
+ }
+ response
+ }
+}
+async fn settings<R: Repository, C: Calendars, D: Directory, A: MacroAuthorizationService>(
+ State(s): State<RouterState<R, C, D, A>>,
+ user: MacroAuthorizationExtractor<A, UserOrInternal>,
+ Query(q): Query<Scope>,
+) -> Result<Json<ProfileResponse>, ApiError> {
+ Ok(Json(ProfileResponse {
+ profile: s
+ .service
+ .settings(user.authorization.user.macro_user_id.as_ref(), q.team_id)
+ .await?,
+ }))
+}
+async fn save<R: Repository, C: Calendars, D: Directory, A: MacroAuthorizationService>(
+ State(s): State<RouterState<R, C, D, A>>,
+ user: MacroAuthorizationExtractor<A, UserOrInternal>,
+ Query(q): Query<Scope>,
+ Json(profile): Json<Profile>,
+) -> Result<Json<ProfileResponse>, ApiError> {
+ Ok(Json(ProfileResponse {
+ profile: s
+ .service
+ .save(
+ user.authorization.user.macro_user_id.as_ref(),
+ q.team_id,
+ profile,
+ )
+ .await?,
+ }))
+}
+async fn bookings<R: Repository, C: Calendars, D: Directory, A: MacroAuthorizationService>(
+ State(s): State<RouterState<R, C, D, A>>,
+ user: MacroAuthorizationExtractor<A, UserOrInternal>,
+ Query(q): Query<BookingRange>,
+) -> Result<Json<BookingsResponse>, ApiError> {
+ let user = user.authorization.user.macro_user_id.as_ref();
+ let bookings = match (q.from, q.to) {
+ (Some(start), Some(end)) => {
+ s.service
+ .bookings_in_range(user, q.team_id, start, end)
+ .await?
+ }
+ (None, None) => s.service.bookings(user, q.team_id).await?,
+ _ => return Err(Error::Invalid("Provide both booking range endpoints".into()).into()),
+ };
+ Ok(Json(BookingsResponse { bookings }))
+}
+async fn attendance<R: Repository, C: Calendars, D: Directory, A: MacroAuthorizationService>(
+ State(s): State<RouterState<R, C, D, A>>,
+ user: MacroAuthorizationExtractor<A, UserOrInternal>,
+ Path(id): Path<Uuid>,
+ Json(request): Json<AttendanceRequest>,
+) -> Result<Json<BookingResponse>, ApiError> {
+ Ok(Json(BookingResponse {
+ booking: s
+ .service
+ .set_attendance(
+ user.authorization.user.macro_user_id.as_ref(),
+ id,
+ request.attendance,
+ )
+ .await?,
+ }))
+}
+async fn approve<R: Repository, C: Calendars, D: Directory, A: MacroAuthorizationService>(
+ State(s): State<RouterState<R, C, D, A>>,
+ user: MacroAuthorizationExtractor<A, UserOrInternal>,
+ Path(id): Path<Uuid>,
+) -> Result<Json<BookingResponse>, ApiError> {
+ Ok(Json(BookingResponse {
+ booking: s
+ .service
+ .approve(user.authorization.user.macro_user_id.as_ref(), id)
+ .await?,
+ }))
+}
+async fn cancel<R: Repository, C: Calendars, D: Directory, A: MacroAuthorizationService>(
+ State(s): State<RouterState<R, C, D, A>>,
+ user: MacroAuthorizationExtractor<A, UserOrInternal>,
+ Path(id): Path<Uuid>,
+) -> Result<Json<BookingResponse>, ApiError> {
+ Ok(Json(BookingResponse {
+ booking: s
+ .service
+ .cancel(
+ id,
+ None,
+ Some(user.authorization.user.macro_user_id.as_ref()),
+ )
+ .await?,
+ }))
+}
+async fn public_profile<R: Repository, C: Calendars, D: Directory, A: MacroAuthorizationService>(
+ State(s): State<RouterState<R, C, D, A>>,
+ Path(id): Path<Uuid>,
+) -> Result<Json<PublicResponse>, ApiError> {
+ Ok(Json(PublicResponse {
+ profile: s.service.public_profile(id).await?,
+ }))
+}
+async fn slots<R: Repository, C: Calendars, D: Directory, A: MacroAuthorizationService>(
+ State(s): State<RouterState<R, C, D, A>>,
+ Path((profile, event)): Path<(Uuid, Uuid)>,
+ Query(q): Query<SlotQuery>,
+) -> Result<Json<SlotsResponse>, ApiError> {
+ Ok(Json(SlotsResponse {
+ slots: s
+ .service
+ .slots_in_zone(
+ profile,
+ event,
+ q.date,
+ q.time_zone.unwrap_or(chrono_tz::UTC),
+ )
+ .await?,
+ }))
+}
+async fn book<R: Repository, C: Calendars, D: Directory, A: MacroAuthorizationService>(
+ State(s): State<RouterState<R, C, D, A>>,
+ Path((profile, event)): Path<(Uuid, Uuid)>,
+ Json(request): Json<BookingRequest>,
+) -> Result<Json<ReceiptResponse>, ApiError> {
+ let r = s.service.book(profile, event, request).await?;
+ Ok(Json(ReceiptResponse {
+ booking: r.booking,
+ token: r.token,
+ schedule_time_zone: r.schedule.time_zone,
+ }))
+}
+async fn receipt<R: Repository, C: Calendars, D: Directory, A: MacroAuthorizationService>(
+ State(s): State<RouterState<R, C, D, A>>,
+ Path(id): Path<Uuid>,
+ headers: HeaderMap,
+) -> Result<Json<ReceiptResponse>, ApiError> {
+ let r = s.service.receipt(id, booking_token(&headers)?).await?;
+ Ok(Json(ReceiptResponse {
+ booking: r.booking,
+ token: r.token,
+ schedule_time_zone: r.schedule.time_zone,
+ }))
+}
+async fn cancel_public<R: Repository, C: Calendars, D: Directory, A: MacroAuthorizationService>(
+ State(s): State<RouterState<R, C, D, A>>,
+ Path(id): Path<Uuid>,
+ Json(q): Json<Token>,
+) -> Result<Json<BookingResponse>, ApiError> {
+ Ok(Json(BookingResponse {
+ booking: s.service.cancel(id, Some(q.token), None).await?,
+ }))
+}
+
+async fn replacement_slots<
+ R: Repository,
+ C: Calendars,
+ D: Directory,
+ A: MacroAuthorizationService,
+>(
+ State(s): State<RouterState<R, C, D, A>>,
+ Path(id): Path<Uuid>,
+ Query(q): Query<ReplacementQuery>,
+ headers: HeaderMap,
+) -> Result<Json<SlotsResponse>, ApiError> {
+ Ok(Json(SlotsResponse {
+ slots: s
+ .service
+ .replacement_slots(id, booking_token(&headers)?, q.date)
+ .await?,
+ }))
+}
+async fn reschedule<R: Repository, C: Calendars, D: Directory, A: MacroAuthorizationService>(
+ State(s): State<RouterState<R, C, D, A>>,
+ Path(id): Path<Uuid>,
+ Json(q): Json<RescheduleRequest>,
+) -> Result<Json<ReceiptResponse>, ApiError> {
+ let r = s.service.reschedule(id, q.token, q.starts_at).await?;
+ Ok(Json(ReceiptResponse {
+ booking: r.booking,
+ token: r.token,
+ schedule_time_zone: r.schedule.time_zone,
+ }))
+}
+
+async fn manage<R: Repository, C: Calendars, D: Directory, A: MacroAuthorizationService>(
+ State(s): State<RouterState<R, C, D, A>>,
+ user: MacroAuthorizationExtractor<A, UserOrInternal>,
+ Path(id): Path<Uuid>,
+) -> Result<Json<ReceiptResponse>, ApiError> {
+ let r = s
+ .service
+ .manage(user.authorization.user.macro_user_id.as_ref(), id)
+ .await?;
+ Ok(Json(ReceiptResponse {
+ booking: r.booking,
+ token: r.token,
+ schedule_time_zone: r.schedule.time_zone,
+ }))
+}
+
+fn booking_token(headers: &HeaderMap) -> Result<Uuid, ApiError> {
+ headers
+ .get(axum::http::header::AUTHORIZATION)
+ .and_then(|h| h.to_str().ok())
+ .and_then(|h| h.strip_prefix("Bearer "))
+ .and_then(|s| Uuid::parse_str(s).ok())
+ .ok_or(ApiError(Error::NotFound))
+}
+
+async fn no_store(request: axum::extract::Request, next: axum::middleware::Next) -> Response {
+ let mut response = next.run(request).await;
+ response.headers_mut().insert(
+ axum::http::header::CACHE_CONTROL,
+ axum::http::HeaderValue::from_static("private, no-store"),
+ );
+ response
+}
+
+#[cfg(all(test, feature = "postgres"))]
+mod test;
diff --git a/crates/calendar_scheduling/src/inbound/router/test.rs b/crates/calendar_scheduling/src/inbound/router/test.rs
new file mode 100644
index 0000000000..817b8a12a4
--- /dev/null
+++ b/crates/calendar_scheduling/src/inbound/router/test.rs
@@ -0,0 +1,259 @@
+//! HTTP + real PostgreSQL contract checks; only identity and external calendar are controlled.
+use super::*;
+use crate::outbound::postgres::PostgresRepository;
+use chrono::{DateTime, Duration, Utc};
+use macro_authorization::{InternalIdentityClaims, MacroAuthorizationError};
+use model_user::UserContext;
+use rootcause::Report;
+use std::sync::atomic::{AtomicBool, Ordering};
+
+#[derive(Clone)]
+struct Identity;
+impl MacroAuthorizationService for Identity {
+ async fn authorize(&self, jwt: &str) -> Result<UserContext, Report<MacroAuthorizationError>> {
+ if !matches!(jwt, "host" | "member" | "stranger") {
+ return Err(Report::new(MacroAuthorizationError::InvalidCredentials));
+ }
+ Ok(UserContext {
+ user_id: format!("macro|{jwt}@example.test"),
+ fusion_user_id: jwt.into(),
+ ..Default::default()
+ })
+ }
+ async fn authorize_internal(
+ &self,
+ _: &str,
+ _: InternalIdentityClaims,
+ ) -> Result<Option<UserContext>, Report<MacroAuthorizationError>> {
+ Err(Report::new(MacroAuthorizationError::InvalidCredentials))
+ }
+}
+struct People;
+impl Directory for People {
+ async fn members(&self, _: Uuid) -> Result<Vec<TeamMember>, Error> {
+ Ok(vec![
+ TeamMember {
+ user_id: "macro|[email protected]".into(),
+ admin: true,
+ },
+ TeamMember {
+ user_id: "macro|[email protected]".into(),
+ admin: false,
+ },
+ ])
+ }
+}
+struct Calendar(AtomicBool);
+impl Calendars for Calendar {
+ async fn creation_calendar(&self, _: &str) -> Result<Uuid, Error> {
+ Ok(Uuid::nil())
+ }
+ async fn busy(
+ &self,
+ _: &[String],
+ _: DateTime<Utc>,
+ _: DateTime<Utc>,
+ _: Option<Uuid>,
+ ) -> Result<Vec<BusyRange>, Error> {
+ Ok(vec![])
+ }
+ async fn create(&self, r: &BookingRecord, _: &EventType) -> Result<(Uuid, String), Error> {
+ if self.0.swap(false, Ordering::SeqCst) {
+ return Err(Error::CalendarUnavailable);
+ }
+ Ok((r.booking.id, "Test location".into()))
+ }
+ async fn cancel(&self, _: &BookingRecord) -> Result<(), Error> {
+ Ok(())
+ }
+ async fn reschedule(&self, _: &BookingRecord) -> Result<(), Error> {
+ Ok(())
+ }
+}
+
+#[sqlx::test(migrations = false)]
+async fn http_booking_receipt_recovery_reschedule_cancel_and_team_auth(pool: sqlx::PgPool) {
+ sqlx::raw_sql("CREATE TABLE \"User\" (id text PRIMARY KEY); CREATE TABLE team (id uuid PRIMARY KEY); INSERT INTO \"User\" VALUES ('macro|[email protected]');").execute(&pool).await.unwrap();
+ sqlx::raw_sql(include_str!(
+ "../../../../macro_db_client/migrations/20260918164303_calendar_scheduling.sql"
+ ))
+ .execute(&pool)
+ .await
+ .unwrap();
+ sqlx::raw_sql(include_str!(
+ "../../../../macro_db_client/migrations/20260918175703_scheduling_recovery.sql"
+ ))
+ .execute(&pool)
+ .await
+ .unwrap();
+ let service = Arc::new(Service::new(
+ PostgresRepository::new(pool.clone()),
+ Calendar(AtomicBool::new(true)),
+ People,
+ ));
+ let app: Router = router(RouterState::new(
+ service.clone(),
+ MacroAuthorizationState::new(Arc::new(Identity)),
+ ));
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let base = format!("http://{}", listener.local_addr().unwrap());
+ let task = tokio::spawn(async move {
+ axum::serve(listener, app).await.unwrap();
+ });
+ let client = reqwest::Client::new();
+ assert_eq!(
+ client
+ .get(format!("{base}/settings"))
+ .send()
+ .await
+ .unwrap()
+ .status(),
+ 401
+ );
+ let response: serde_json::Value = client
+ .get(format!("{base}/settings"))
+ .bearer_auth("host")
+ .send()
+ .await
+ .unwrap()
+ .json()
+ .await
+ .unwrap();
+ let id: Uuid = serde_json::from_value(response["profile"]["id"].clone()).unwrap();
+ let schedule = Uuid::now_v7();
+ let event = Uuid::now_v7();
+ let profile = serde_json::json!({
+ "id":id,"name":"Integration host","description":"","revision":0,"defaultScheduleId":schedule,
+ "schedules":[{"id":schedule,"name":"Work","timeZone":"UTC","overrides":[],"weekly":(0..7).map(|day| serde_json::json!({"day":day,"windows":[{"start":"09:00","end":"17:00"}]})).collect::<Vec<_>>() }],
+ "eventTypes":[{"id":event,"title":"Integration meeting","slug":"meeting","description":"","durationMinutes":30,"location":"","googleMeet":false,"enabled":true,"scheduleId":schedule,"mode":"individual","hosts":["macro|[email protected]"],"beforeMinutes":0,"afterMinutes":0,"noticeMinutes":0,"horizonDays":30,"intervalMinutes":30,"dailyLimit":null,"requiresConfirmation":false,"questions":[]}]
+ });
+ let saved = client
+ .put(format!("{base}/settings"))
+ .bearer_auth("host")
+ .json(&profile)
+ .send()
+ .await
+ .unwrap();
+ assert_eq!(saved.status(), 200);
+ assert_eq!(
+ client
+ .put(format!("{base}/settings"))
+ .bearer_auth("stranger")
+ .json(&profile)
+ .send()
+ .await
+ .unwrap()
+ .status(),
+ 403
+ );
+ let day = (Utc::now() + Duration::days(2)).date_naive();
+ let slots: serde_json::Value = client
+ .get(format!(
+ "{base}/public/{id}/{event}/slots?date={day}&time_zone=UTC"
+ ))
+ .send()
+ .await
+ .unwrap()
+ .json()
+ .await
+ .unwrap();
+ let start = slots["slots"][0]["startsAt"].as_str().unwrap();
+ let request = serde_json::json!({"startsAt":start,"name":"Test Guest","email":"[email protected]","timeZone":"UTC","answers":{},"requestId":Uuid::now_v7()});
+ let booked = client
+ .post(format!("{base}/public/{id}/{event}/book"))
+ .json(&request)
+ .send()
+ .await
+ .unwrap();
+ assert_eq!(
+ booked.status(),
+ 200,
+ "durable reservations return their receipt even on provider failure"
+ );
+ assert_eq!(booked.headers()["cache-control"], "private, no-store");
+ let receipt: serde_json::Value = booked.json().await.unwrap();
+ assert_eq!(receipt["booking"]["status"], "failed");
+ let booking = Uuid::parse_str(receipt["booking"]["id"].as_str().unwrap()).unwrap();
+ let token = receipt["token"].as_str().unwrap();
+ assert_eq!(
+ client
+ .get(format!("{base}/public/bookings/{booking}"))
+ .bearer_auth(Uuid::new_v4())
+ .send()
+ .await
+ .unwrap()
+ .status(),
+ 404
+ );
+ let retry: serde_json::Value = client
+ .post(format!("{base}/public/{id}/{event}/book"))
+ .json(&request)
+ .send()
+ .await
+ .unwrap()
+ .json()
+ .await
+ .unwrap();
+ assert_eq!(retry["booking"]["id"], receipt["booking"]["id"]);
+ sqlx::query!(
+ "UPDATE scheduling_booking SET recovery_at = now() - interval '1 second' WHERE id = $1",
+ booking
+ )
+ .execute(&pool)
+ .await
+ .unwrap();
+ assert!(service.recover_once().await.unwrap());
+ let confirmed: serde_json::Value = client
+ .get(format!("{base}/public/bookings/{booking}"))
+ .bearer_auth(token)
+ .send()
+ .await
+ .unwrap()
+ .json()
+ .await
+ .unwrap();
+ assert_eq!(confirmed["booking"]["status"], "confirmed");
+ let next = slots["slots"][2]["startsAt"].as_str().unwrap();
+ let moved: serde_json::Value = client
+ .post(format!("{base}/public/bookings/{booking}/reschedule"))
+ .json(&serde_json::json!({"token":token,"startsAt":next}))
+ .send()
+ .await
+ .unwrap()
+ .json()
+ .await
+ .unwrap();
+ assert_eq!(moved["booking"]["rescheduleCount"], 1);
+ let cancelled: serde_json::Value = client
+ .post(format!("{base}/public/bookings/{booking}/cancel"))
+ .json(&serde_json::json!({"token":token}))
+ .send()
+ .await
+ .unwrap()
+ .json()
+ .await
+ .unwrap();
+ assert_eq!(cancelled["booking"]["status"], "cancelled");
+ let team = Uuid::now_v7();
+ assert_eq!(
+ client
+ .get(format!("{base}/settings?teamId={team}"))
+ .bearer_auth("stranger")
+ .send()
+ .await
+ .unwrap()
+ .status(),
+ 403
+ );
+ assert_eq!(
+ client
+ .get(format!("{base}/settings?teamId={team}"))
+ .bearer_auth("member")
+ .send()
+ .await
+ .unwrap()
+ .status(),
+ 200
+ );
+ task.abort();
+}
diff --git a/crates/calendar_scheduling/src/lib.rs b/crates/calendar_scheduling/src/lib.rs
new file mode 100644
index 0000000000..40afb629e6
--- /dev/null
+++ b/crates/calendar_scheduling/src/lib.rs
@@ -0,0 +1,7 @@
+//! Personal and team booking links, availability, and booking lifecycle.
+#![deny(missing_docs)]
+pub mod domain;
+#[cfg(feature = "inbound")]
+pub mod inbound;
+#[cfg(any(feature = "postgres", feature = "calendar"))]
+pub mod outbound;
diff --git a/crates/calendar_scheduling/src/outbound.rs b/crates/calendar_scheduling/src/outbound.rs
new file mode 100644
index 0000000000..e631e87b04
--- /dev/null
+++ b/crates/calendar_scheduling/src/outbound.rs
@@ -0,0 +1,5 @@
+//! Persistence adapters for scheduling-owned data.
+#[cfg(feature = "calendar")]
+pub mod macro_services;
+#[cfg(feature = "postgres")]
+pub mod postgres;
diff --git a/crates/calendar_scheduling/src/outbound/macro_services.rs b/crates/calendar_scheduling/src/outbound/macro_services.rs
new file mode 100644
index 0000000000..34bbf85f2a
--- /dev/null
+++ b/crates/calendar_scheduling/src/outbound/macro_services.rs
@@ -0,0 +1,311 @@
+//! Reuses calendar writes, sync projections, and current team membership.
+use crate::domain::{
+ models::*,
+ ports::{Calendars, Directory},
+};
+use calendar_events::domain::{
+ models::{
+ CalendarAttendeeInput, CalendarEventDraft, CalendarSyncStatus, ConferenceChange, EventTime,
+ EventTransparency, OccurrenceRange,
+ },
+ ports::{CalendarCreationRecoveryService, CalendarDeletionScope, CalendarOccurrenceService},
+};
+use chrono::{DateTime, Duration, Utc};
+use std::sync::Arc;
+use teams::domain::{model::TeamRole, team_repo::TeamRepository};
+use uuid::Uuid;
+
+/// Adapter composed from existing domain services, never their outbound implementations.
+pub struct MacroCalendars<O, M> {
+ occurrences: Arc<O>,
+ mutations: Arc<M>,
+ management_origin: Option<String>,
+}
+impl<O, M> MacroCalendars<O, M> {
+ /// Wire the host's calendar domain capabilities.
+ pub fn new(occurrences: Arc<O>, mutations: Arc<M>, management_origin: Option<String>) -> Self {
+ Self {
+ occurrences,
+ mutations,
+ management_origin,
+ }
+ }
+}
+impl<O: CalendarOccurrenceService, M: CalendarCreationRecoveryService> Calendars
+ for MacroCalendars<O, M>
+{
+ async fn creation_calendar(&self, host: &str) -> Result<Uuid, Error> {
+ self.mutations
+ .list_visible_calendars(host)
+ .await
+ .map_err(|_| Error::CalendarUnavailable)?
+ .into_iter()
+ .find(|c| c.is_primary && c.is_writable && c.sync_error.is_none())
+ .map(|c| c.id)
+ .ok_or(Error::CalendarUnavailable)
+ }
+ async fn busy(
+ &self,
+ hosts: &[String],
+ start: DateTime<Utc>,
+ end: DateTime<Utc>,
+ exclude_event: Option<Uuid>,
+ ) -> Result<Vec<BusyRange>, Error> {
+ let mut events = vec![];
+ for host in hosts {
+ let calendars = self
+ .mutations
+ .list_visible_calendars(host)
+ .await
+ .map_err(|_| Error::CalendarUnavailable)?;
+ if calendars.iter().any(|c| c.sync_error.is_some())
+ || !calendars
+ .iter()
+ .any(|c| c.is_primary && c.is_writable && c.sync_error.is_none())
+ || self
+ .occurrences
+ .sync_status(host)
+ .await
+ .map_err(|_| Error::CalendarUnavailable)?
+ != CalendarSyncStatus::Ready
+ {
+ return Err(Error::CalendarUnavailable);
+ }
+ let range = OccurrenceRange {
+ starts_at: start,
+ ends_at: end,
+ start_date: (start - Duration::days(1)).date_naive(),
+ end_date: (end + Duration::days(1)).date_naive(),
+ };
+ let rows = self
+ .occurrences
+ .list_occurrences(host, range, None, 2001)
+ .await
+ .map_err(|_| Error::CalendarUnavailable)?;
+ // Never treat a truncated occurrence result as free time.
+ if rows.len() > 2000 {
+ return Err(Error::CalendarUnavailable);
+ }
+ events.extend(
+ rows.into_iter()
+ .map(|(event, occurrence)| (host.clone(), event, occurrence)),
+ );
+ }
+ let excluded_uid = events
+ .iter()
+ .find(|(_, event, _)| Some(event.id) == exclude_event)
+ .map(|(_, event, _)| event.ical_uid.clone());
+ let mut busy = vec![];
+ for (host, event, occurrence) in events {
+ let mut owned = event.attendees.iter().filter(|a| a.is_self).peekable();
+ let declined = owned.peek().is_some()
+ && owned.all(|a| {
+ a.response_status
+ == calendar_events::domain::models::AttendeeResponseStatus::Declined
+ });
+ if occurrence.is_cancelled
+ || Some(event.id) == exclude_event
+ || excluded_uid
+ .as_ref()
+ .is_some_and(|uid| !uid.is_empty() && *uid == event.ical_uid)
+ || event.transparency == EventTransparency::Transparent
+ || declined
+ {
+ continue;
+ }
+ let (start, end) = match occurrence.time {
+ EventTime::Timed {
+ starts_at, ends_at, ..
+ } => (starts_at, ends_at),
+ // All-day dates lack a source zone; conservatively cover every UTC offset.
+ EventTime::AllDay {
+ start_date,
+ end_date,
+ } => (
+ start_date
+ .and_hms_opt(0, 0, 0)
+ .ok_or(Error::CalendarUnavailable)?
+ .and_utc()
+ - Duration::hours(14),
+ end_date
+ .and_hms_opt(0, 0, 0)
+ .ok_or(Error::CalendarUnavailable)?
+ .and_utc()
+ + Duration::hours(12),
+ ),
+ };
+ busy.push(BusyRange { host, start, end });
+ }
+ Ok(busy)
+ }
+ async fn create(
+ &self,
+ record: &BookingRecord,
+ event: &EventType,
+ ) -> Result<(Uuid, String), Error> {
+ let organizer = record
+ .booking
+ .hosts
+ .first()
+ .ok_or(Error::CalendarUnavailable)?;
+ let mut emails = vec![record.booking.email.clone()];
+ for host in record.booking.hosts.iter().skip(1) {
+ let user: macro_user_id::user_id::MacroUserIdStr<'_> = host
+ .as_str()
+ .try_into()
+ .map_err(|_| Error::CalendarUnavailable)?;
+ emails.push(user.email_part().as_ref().to_owned());
+ }
+ let answers = event
+ .questions
+ .iter()
+ .filter_map(|q| {
+ record
+ .booking
+ .answers
+ .get(&q.id)
+ .map(|a| format!("{}: {}", q.label, a))
+ })
+ .collect::<Vec<_>>()
+ .join("\n");
+ let management = self
+ .management_origin
+ .as_ref()
+ .map(|origin| {
+ format!(
+ "\n\nManage this booking: {}/app/booking/{}#{}",
+ origin.trim_end_matches('/'),
+ record.booking.id,
+ record.token
+ )
+ })
+ .unwrap_or_default();
+ let draft = CalendarEventDraft {
+ idempotency_key: Some(record.booking.id),
+ title: format!("{} — {}", record.booking.title, record.booking.name),
+ description: Some(format!(
+ "{}\n\n{}{}",
+ event.description, answers, management
+ )),
+ location: (!event.location.is_empty()).then(|| event.location.clone()),
+ time: EventTime::Timed {
+ starts_at: record.booking.starts_at,
+ ends_at: record.booking.ends_at,
+ time_zone: Some(record.booking.time_zone.to_string()),
+ },
+ attendees: emails
+ .into_iter()
+ .map(|email| CalendarAttendeeInput {
+ email,
+ is_optional: false,
+ response_status: None,
+ })
+ .collect(),
+ recurrence_lines: vec![],
+ visibility: None,
+ transparency: None,
+ reminders: None,
+ conference: event.google_meet.then_some(ConferenceChange::GoogleMeet),
+ out_of_office: None,
+ };
+ let result = self
+ .mutations
+ .create_event(organizer, None, record.calendar_id, draft)
+ .await
+ .map_err(|error| {
+ tracing::error!(error=?error,"scheduling calendar creation failed");
+ Error::CalendarUnavailable
+ })?;
+ if event.google_meet
+ && result
+ .conference_url
+ .as_ref()
+ .is_none_or(|url| url.is_empty())
+ {
+ return Err(Error::CalendarUnavailable);
+ }
+ Ok((
+ result.id,
+ result
+ .conference_url
+ .or(result.location)
+ .unwrap_or_default(),
+ ))
+ }
+ async fn cancel(&self, record: &BookingRecord) -> Result<(), Error> {
+ if let Some(calendar_id) = record.calendar_id {
+ return self
+ .mutations
+ .delete_created_event(
+ record
+ .booking
+ .hosts
+ .first()
+ .ok_or(Error::CalendarUnavailable)?,
+ calendar_id,
+ record.booking.id,
+ )
+ .await
+ .map_err(|_| Error::CalendarUnavailable);
+ }
+ if let Some(id) = record.calendar_event_id {
+ self.mutations
+ .delete_event(
+ record
+ .booking
+ .hosts
+ .first()
+ .ok_or(Error::CalendarUnavailable)?,
+ id,
+ None,
+ CalendarDeletionScope::All,
+ )
+ .await
+ .map_err(|_| Error::CalendarUnavailable)?;
+ }
+ Ok(())
+ }
+ async fn reschedule(&self, record: &BookingRecord) -> Result<(), Error> {
+ if let Some(id) = record.calendar_event_id {
+ self.mutations
+ .update_event(
+ record
+ .booking
+ .hosts
+ .first()
+ .ok_or(Error::CalendarUnavailable)?,
+ id,
+ None,
+ calendar_events::domain::models::CalendarEventPatch {
+ time: Some(EventTime::Timed {
+ starts_at: record.booking.starts_at,
+ ends_at: record.booking.ends_at,
+ time_zone: Some(record.booking.time_zone.to_string()),
+ }),
+ ..Default::default()
+ },
+ calendar_events::domain::ports::CalendarUpdateScope::All,
+ )
+ .await
+ .map_err(|_| Error::CalendarUnavailable)?;
+ }
+ Ok(())
+ }
+}
+/// Membership adapter over the owning teams repository port.
+pub struct MacroDirectory<T>(pub T);
+impl<T: TeamRepository> Directory for MacroDirectory<T> {
+ async fn members(&self, team: Uuid) -> Result<Vec<TeamMember>, Error> {
+ Ok(self
+ .0
+ .get_all_team_members(&team)
+ .await
+ .map_err(|_| Error::Forbidden)?
+ .into_iter()
+ .map(|m| TeamMember {
+ user_id: m.user_id.to_string(),
+ admin: matches!(m.role, TeamRole::Owner | TeamRole::Admin),
+ })
+ .collect())
+ }
+}
diff --git a/crates/calendar_scheduling/src/outbound/postgres.rs b/crates/calendar_scheduling/src/outbound/postgres.rs
new file mode 100644
index 0000000000..28b9cd9ac3
--- /dev/null
+++ b/crates/calendar_scheduling/src/outbound/postgres.rs
@@ -0,0 +1,298 @@
+//! PostgreSQL store with optimistic profile revisions and atomic host reservations.
+use crate::domain::{models::*, ports::Repository};
+use chrono::{DateTime, Utc};
+use sqlx::PgPool;
+use uuid::Uuid;
+
+/// Scheduling-owned PostgreSQL repository.
+pub struct PostgresRepository {
+ pool: PgPool,
+}
+impl PostgresRepository {
+ /// Use the application's MacroDB pool.
+ pub fn new(pool: PgPool) -> Self {
+ Self { pool }
+ }
+}
+fn db_error(error: sqlx::Error) -> Error {
+ if error
+ .as_database_error()
+ .is_some_and(|e| e.is_unique_violation() || e.code().as_deref() == Some("23P01"))
+ {
+ return Error::Conflict;
+ }
+ tracing::error!(error = ?error, "scheduling persistence failed");
+ Error::Unavailable
+}
+fn decode<T: serde::de::DeserializeOwned>(value: serde_json::Value) -> Result<T, Error> {
+ serde_json::from_value(value).map_err(|_| Error::Unavailable)
+}
+fn encode<T: serde::Serialize>(value: &T) -> Result<serde_json::Value, Error> {
+ serde_json::to_value(value).map_err(|_| Error::Unavailable)
+}
+fn status(value: BookingStatus) -> &'static str {
+ match value {
+ BookingStatus::Pending => "pending",
+ BookingStatus::Processing => "processing",
+ BookingStatus::Confirmed => "confirmed",
+ BookingStatus::Cancelled => "cancelled",
+ BookingStatus::Failed => "failed",
+ }
+}
+impl Repository for PostgresRepository {
+ async fn consume_budget(&self, profile: Uuid, budget: PublicBudget) -> Result<(), Error> {
+ let (key, seconds, limit) = match budget {
+ PublicBudget::Availability => ("availability", 60.0_f64, 120_i32),
+ PublicBudget::Booking => ("booking", 3600.0_f64, 30_i32),
+ };
+ let allowed = sqlx::query_scalar!(r#"
+ INSERT INTO scheduling_public_budget (profile_id, kind, window_start, used)
+ VALUES ($1, $2, now(), 1)
+ ON CONFLICT (profile_id, kind) DO UPDATE SET
+ window_start = CASE WHEN scheduling_public_budget.window_start <= now() - make_interval(secs => $3) THEN now() ELSE scheduling_public_budget.window_start END,
+ used = CASE WHEN scheduling_public_budget.window_start <= now() - make_interval(secs => $3) THEN 1 ELSE scheduling_public_budget.used + 1 END
+ WHERE scheduling_public_budget.window_start <= now() - make_interval(secs => $3) OR scheduling_public_budget.used < $4
+ RETURNING used
+ "#, profile, key, seconds, limit).fetch_optional(&self.pool).await.map_err(db_error)?;
+ allowed.map(|_| ()).ok_or(Error::RateLimited)
+ }
+ async fn claim_recovery(&self) -> Result<Option<BookingRecord>, Error> {
+ let mut tx = self.pool.begin().await.map_err(db_error)?;
+ let row = sqlx::query_scalar!("SELECT record FROM scheduling_booking WHERE status IN ('processing', 'failed') AND recovery_at <= now() ORDER BY recovery_at, id FOR UPDATE SKIP LOCKED LIMIT 1")
+ .fetch_optional(&mut *tx).await.map_err(db_error)?;
+ let Some(row) = row else {
+ return Ok(None);
+ };
+ let mut record: BookingRecord = decode(row)?;
+ let operation = record.operation.as_mut().ok_or(Error::Unavailable)?;
+ operation.attempt = operation.attempt.saturating_add(1);
+ record.revision = record.revision.saturating_add(1);
+ operation.retry_at = Utc::now() + chrono::Duration::minutes(5);
+ let retry_at = operation.retry_at;
+ record.booking.status = BookingStatus::Processing;
+ let json = encode(&record)?;
+ sqlx::query!("UPDATE scheduling_booking SET status = 'processing', record = $2, recovery_at = $3 WHERE id = $1", record.booking.id, json, retry_at)
+ .execute(&mut *tx).await.map_err(db_error)?;
+ tx.commit().await.map_err(db_error)?;
+ Ok(Some(record))
+ }
+ async fn profile(&self, id: Uuid) -> Result<Option<OwnedProfile>, Error> {
+ let row = sqlx::query!("SELECT user_id, team_id, revision, configuration FROM scheduling_profile WHERE id = $1", id).fetch_optional(&self.pool).await.map_err(db_error)?;
+ row.map(|r| {
+ let mut profile: Profile = decode(r.configuration)?;
+ profile.revision = r.revision;
+ Ok(OwnedProfile {
+ user_id: r.user_id,
+ team_id: r.team_id,
+ profile,
+ })
+ })
+ .transpose()
+ }
+ async fn save_profile(&self, owner: OwnedProfile) -> Result<Profile, Error> {
+ let mut profile = owner.profile;
+ let json = encode(&profile)?;
+ let revision = if profile.revision == 0 {
+ sqlx::query_scalar!("INSERT INTO scheduling_profile (id, user_id, team_id, configuration) VALUES ($1, $2, $3, $4) RETURNING revision", profile.id, owner.user_id, owner.team_id, json).fetch_one(&self.pool).await.map_err(db_error)?
+ } else {
+ sqlx::query_scalar!("UPDATE scheduling_profile SET configuration = $2, revision = revision + 1 WHERE id = $1 AND revision = $3 RETURNING revision", profile.id, json, profile.revision).fetch_optional(&self.pool).await.map_err(db_error)?.ok_or(Error::Conflict)?
+ };
+ profile.revision = revision;
+ Ok(profile)
+ }
+ async fn bookings(
+ &self,
+ profile: Uuid,
+ start: DateTime<Utc>,
+ end: DateTime<Utc>,
+ ) -> Result<Vec<BookingRecord>, Error> {
+ let records = sqlx::query_scalar!("SELECT record FROM scheduling_booking WHERE profile_id = $1 AND starts_at >= $2 AND starts_at < $3 ORDER BY starts_at, id LIMIT 5001", profile, start, end).fetch_all(&self.pool).await.map_err(db_error)?;
+ if records.len() > 5000 {
+ return Err(Error::Invalid(
+ "Too many bookings in this date range. Choose a shorter date range.".into(),
+ ));
+ }
+ records.into_iter().map(decode).collect()
+ }
+ async fn host_booking_counts(
+ &self,
+ profile: Uuid,
+ hosts: &[String],
+ start: DateTime<Utc>,
+ end: DateTime<Utc>,
+ ) -> Result<std::collections::BTreeMap<String, i64>, Error> {
+ let rows = sqlx::query!(
+ r#"SELECT host AS "host!", count(*) AS "count!"
+ FROM scheduling_booking
+ CROSS JOIN LATERAL jsonb_array_elements_text(record->'booking'->'hosts') AS host
+ WHERE profile_id = $1 AND starts_at >= $2 AND starts_at < $3
+ AND status <> 'cancelled' AND host = ANY($4)
+ GROUP BY host"#,
+ profile,
+ start,
+ end,
+ hosts
+ )
+ .fetch_all(&self.pool)
+ .await
+ .map_err(db_error)?;
+ Ok(rows.into_iter().map(|row| (row.host, row.count)).collect())
+ }
+ async fn busy(
+ &self,
+ hosts: &[String],
+ start: DateTime<Utc>,
+ end: DateTime<Utc>,
+ exclude: Option<Uuid>,
+ ) -> Result<Vec<BusyRange>, Error> {
+ Ok(sqlx::query!(r#"SELECT user_id, lower(piece) AS "start!", upper(piece) AS "end!" FROM scheduling_host_claim CROSS JOIN LATERAL unnest(occupied) AS piece WHERE user_id = ANY($1) AND piece && tstzrange($2, $3, '[)') AND ($4::uuid IS NULL OR booking_id <> $4)"#, hosts, start, end, exclude).fetch_all(&self.pool).await.map_err(db_error)?.into_iter().map(|r| BusyRange { host: r.user_id, start: r.start, end: r.end }).collect())
+ }
+ async fn reserve(
+ &self,
+ record: BookingRecord,
+ limit: Option<u16>,
+ day_start: DateTime<Utc>,
+ day_end: DateTime<Utc>,
+ ) -> Result<BookingRecord, Error> {
+ let mut tx = self.pool.begin().await.map_err(db_error)?;
+ // Serialize per-profile limits; the exclusion constraint also protects hosts across profiles.
+ sqlx::query!(
+ "SELECT id FROM scheduling_profile WHERE id = $1 FOR UPDATE",
+ record.profile_id
+ )
+ .fetch_one(&mut *tx)
+ .await
+ .map_err(db_error)?;
+ if let Some(existing) = sqlx::query_scalar!(
+ "SELECT record FROM scheduling_booking WHERE request_id = $1",
+ record.request_id
+ )
+ .fetch_optional(&mut *tx)
+ .await
+ .map_err(db_error)?
+ {
+ let existing: BookingRecord = decode(existing)?;
+ if existing.profile_id == record.profile_id
+ && existing.booking.email == record.booking.email
+ && existing.booking.starts_at == record.booking.starts_at
+ && existing.booking.event_type_id == record.booking.event_type_id
+ {
+ return Ok(existing);
+ }
+ return Err(Error::Conflict);
+ }
+ if let Some(limit) = limit {
+ let count = sqlx::query_scalar!("SELECT count(*) FROM scheduling_booking WHERE profile_id = $1 AND event_type_id = $2 AND starts_at >= $3 AND starts_at < $4 AND status <> 'cancelled'", record.profile_id, record.booking.event_type_id, day_start, day_end).fetch_one(&mut *tx).await.map_err(db_error)?.unwrap_or(0);
+ if count >= i64::from(limit) {
+ return Err(Error::Conflict);
+ }
+ }
+ let json = encode(&record)?;
+ sqlx::query!("INSERT INTO scheduling_booking (id, profile_id, request_id, event_type_id, starts_at, ends_at, status, record, recovery_at) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9)", record.booking.id, record.profile_id, record.request_id, record.booking.event_type_id, record.booking.starts_at, record.booking.ends_at, status(record.booking.status), json, record.operation.as_ref().map(|o| o.retry_at)).execute(&mut *tx).await.map_err(db_error)?;
+ let mut hosts: Vec<_> = record.booking.hosts.iter().collect();
+ hosts.sort();
+ for host in hosts {
+ sqlx::query!("INSERT INTO scheduling_host_claim (booking_id, user_id, occupied) VALUES ($1,$2,tstzmultirange(tstzrange($3,$4,'[)')))", record.booking.id, host, record.busy_start, record.busy_end).execute(&mut *tx).await.map_err(db_error)?;
+ }
+ tx.commit().await.map_err(db_error)?;
+ Ok(record)
+ }
+ async fn booking(&self, id: Uuid) -> Result<Option<BookingRecord>, Error> {
+ sqlx::query_scalar!("SELECT record FROM scheduling_booking WHERE id = $1", id)
+ .fetch_optional(&self.pool)
+ .await
+ .map_err(db_error)?
+ .map(decode)
+ .transpose()
+ }
+ async fn booking_request(&self, request: Uuid) -> Result<Option<BookingRecord>, Error> {
+ sqlx::query_scalar!(
+ "SELECT record FROM scheduling_booking WHERE request_id = $1",
+ request
+ )
+ .fetch_optional(&self.pool)
+ .await
+ .map_err(db_error)?
+ .map(decode)
+ .transpose()
+ }
+ async fn move_booking(
+ &self,
+ mut record: BookingRecord,
+ expected: BookingStatus,
+ start: DateTime<Utc>,
+ end: DateTime<Utc>,
+ ) -> Result<BookingRecord, Error> {
+ let mut tx = self.pool.begin().await.map_err(db_error)?;
+ sqlx::query!(
+ "SELECT id FROM scheduling_profile WHERE id = $1 FOR UPDATE",
+ record.profile_id
+ )
+ .fetch_one(&mut *tx)
+ .await
+ .map_err(db_error)?;
+ if let Some(limit) = record.event.daily_limit {
+ let count = sqlx::query_scalar!("SELECT count(*) FROM scheduling_booking WHERE profile_id = $1 AND event_type_id = $2 AND starts_at >= $3 AND starts_at < $4 AND status <> 'cancelled' AND id <> $5", record.profile_id, record.booking.event_type_id, start, end, record.booking.id).fetch_one(&mut *tx).await.map_err(db_error)?.unwrap_or(0);
+ if count >= i64::from(limit) {
+ return Err(Error::Conflict);
+ }
+ }
+ let expected_revision = record.revision.to_string();
+ record.revision = record.revision.saturating_add(1);
+ let json = encode(&record)?;
+ let updated = sqlx::query!("UPDATE scheduling_booking SET starts_at = $2, ends_at = $3, status = 'processing', record = $4, recovery_at = $6 WHERE id = $1 AND status = $5 AND COALESCE(record->>'revision', '0') = $7", record.booking.id, record.booking.starts_at, record.booking.ends_at, json, status(expected), record.operation.as_ref().map(|o| o.retry_at), expected_revision).execute(&mut *tx).await.map_err(db_error)?;
+ if updated.rows_affected() != 1 {
+ return Err(Error::Conflict);
+ }
+ sqlx::query!("UPDATE scheduling_host_claim SET occupied = occupied + tstzmultirange(tstzrange($2,$3,'[)')) WHERE booking_id = $1", record.booking.id, record.busy_start, record.busy_end).execute(&mut *tx).await.map_err(db_error)?;
+ tx.commit().await.map_err(db_error)?;
+ Ok(record)
+ }
+ async fn update_booking(
+ &self,
+ mut record: BookingRecord,
+ expected: BookingStatus,
+ ) -> Result<BookingRecord, Error> {
+ let mut tx = self.pool.begin().await.map_err(db_error)?;
+ let expected_revision = record.revision.to_string();
+ record.revision = record.revision.saturating_add(1);
+ let json = encode(&record)?;
+ let updated = sqlx::query!(
+ "UPDATE scheduling_booking SET status = $2, record = $3, recovery_at = $5 WHERE id = $1 AND status = $4 AND COALESCE(record->>'revision', '0') = $8 AND ($4 <> 'processing' OR (record->'operation'->>'id' IS NOT DISTINCT FROM $6 AND record->'operation'->>'attempt' IS NOT DISTINCT FROM $7))",
+ record.booking.id,
+ status(record.booking.status),
+ json,
+ status(expected),
+ if matches!(record.booking.status, BookingStatus::Processing | BookingStatus::Failed) { record.operation.as_ref().map(|o| o.retry_at) } else { None },
+ record.operation.as_ref().map(|o| o.id.to_string()),
+ record.operation.as_ref().map(|o| o.attempt.to_string()),
+ expected_revision
+ )
+ .execute(&mut *tx)
+ .await
+ .map_err(db_error)?;
+ if updated.rows_affected() != 1 {
+ return Err(Error::Conflict);
+ }
+ if record.booking.status == BookingStatus::Cancelled {
+ sqlx::query!(
+ "DELETE FROM scheduling_host_claim WHERE booking_id = $1",
+ record.booking.id
+ )
+ .execute(&mut *tx)
+ .await
+ .map_err(db_error)?;
+ }
+ if matches!(
+ record.booking.status,
+ BookingStatus::Confirmed | BookingStatus::Pending
+ ) {
+ sqlx::query!("UPDATE scheduling_host_claim SET occupied = tstzmultirange(tstzrange($2,$3,'[)')) WHERE booking_id = $1", record.booking.id, record.busy_start, record.busy_end).execute(&mut *tx).await.map_err(db_error)?;
+ }
+ tx.commit().await.map_err(db_error)?;
+ Ok(record)
+ }
+}
+
+#[cfg(test)]
+mod test;
diff --git a/crates/calendar_scheduling/src/outbound/postgres/test.rs b/crates/calendar_scheduling/src/outbound/postgres/test.rs
new file mode 100644
index 0000000000..11993863c3
--- /dev/null
+++ b/crates/calendar_scheduling/src/outbound/postgres/test.rs
@@ -0,0 +1,356 @@
+use super::*;
+use chrono::Duration;
+
+async fn setup(pool: &PgPool) {
+ sqlx::raw_sql(
+ "CREATE TABLE \"User\" (id text PRIMARY KEY); CREATE TABLE team (id uuid PRIMARY KEY);",
+ )
+ .execute(pool)
+ .await
+ .unwrap();
+ sqlx::raw_sql(include_str!(
+ "../../../../macro_db_client/migrations/20260918164303_calendar_scheduling.sql"
+ ))
+ .execute(pool)
+ .await
+ .unwrap();
+ sqlx::raw_sql(include_str!(
+ "../../../../macro_db_client/migrations/20260918175703_scheduling_recovery.sql"
+ ))
+ .execute(pool)
+ .await
+ .unwrap();
+ sqlx::raw_sql("INSERT INTO \"User\" (id) VALUES ('host');")
+ .execute(pool)
+ .await
+ .unwrap();
+}
+fn owned() -> OwnedProfile {
+ OwnedProfile {
+ user_id: Some("host".into()),
+ team_id: None,
+ profile: Profile {
+ id: Uuid::new_v4(),
+ name: "Host".into(),
+ description: String::new(),
+ default_schedule_id: None,
+ schedules: vec![],
+ event_types: vec![],
+ revision: 0,
+ },
+ }
+}
+fn booking(profile: Uuid, start: DateTime<Utc>) -> BookingRecord {
+ let event:EventType=serde_json::from_value(serde_json::json!({"id":Uuid::new_v4(),"title":"Meeting","slug":"meeting","description":"","durationMinutes":30,"location":"","googleMeet":false,"enabled":true,"scheduleId":Uuid::nil(),"mode":"individual","hosts":["host"],"beforeMinutes":0,"afterMinutes":0,"noticeMinutes":0,"horizonDays":30,"intervalMinutes":30,"dailyLimit":null,"requiresConfirmation":false,"questions":[]})).unwrap();
+ BookingRecord {
+ revision: 0,
+ event: event.clone(),
+ schedule: Schedule {
+ id: Uuid::nil(),
+ name: "Work".into(),
+ time_zone: chrono_tz::UTC,
+ weekly: vec![],
+ overrides: vec![],
+ },
+ profile_id: profile,
+ token: Uuid::new_v4(),
+ request_id: Uuid::new_v4(),
+ calendar_event_id: None,
+ calendar_id: None,
+ operation: None,
+ busy_start: start,
+ busy_end: start + Duration::minutes(30),
+ booking: Booking {
+ id: Uuid::new_v4(),
+ event_type_id: event.id,
+ title: "Meeting".into(),
+ name: "Booker".into(),
+ email: "[email protected]".into(),
+ starts_at: start,
+ ends_at: start + Duration::minutes(30),
+ time_zone: chrono_tz::UTC,
+ hosts: vec!["host".into()],
+ status: BookingStatus::Pending,
+ attendance: BookingAttendance::Unknown,
+ reschedule_count: 0,
+ rescheduled_at: None,
+ location: String::new(),
+ answers: Default::default(),
+ question_labels: Default::default(),
+ },
+ }
+}
+#[sqlx::test(migrations = false)]
+async fn overlapping_host_reservations_are_atomic(pool: PgPool) {
+ setup(&pool).await;
+ let repo = PostgresRepository::new(pool);
+ let p = repo.save_profile(owned()).await.unwrap();
+ let start = Utc::now() + Duration::days(2);
+ let a = booking(p.id, start);
+ let b = booking(p.id, start);
+ let (a, b) = tokio::join!(
+ repo.reserve(a, None, start, start + Duration::days(1)),
+ repo.reserve(b, None, start, start + Duration::days(1))
+ );
+ assert_eq!(usize::from(a.is_ok()) + usize::from(b.is_ok()), 1);
+ let mut winner = a.or(b).unwrap();
+ winner.booking.status = BookingStatus::Cancelled;
+ repo.update_booking(winner, BookingStatus::Pending)
+ .await
+ .unwrap();
+ assert!(
+ repo.reserve(booking(p.id, start), None, start, start + Duration::days(1))
+ .await
+ .is_ok()
+ );
+}
+#[sqlx::test(migrations = false)]
+async fn profile_revision_rejects_lost_updates(pool: PgPool) {
+ setup(&pool).await;
+ let repo = PostgresRepository::new(pool);
+ let mut owner = owned();
+ owner.profile = repo.save_profile(owner.clone()).await.unwrap();
+ let stale = owner.clone();
+ repo.save_profile(owner).await.unwrap();
+ assert!(matches!(
+ repo.save_profile(stale).await,
+ Err(Error::Conflict)
+ ));
+}
+#[sqlx::test(migrations = false)]
+async fn daily_limit_is_atomic_for_non_overlapping_slots(pool: PgPool) {
+ setup(&pool).await;
+ let repo = PostgresRepository::new(pool);
+ let p = repo.save_profile(owned()).await.unwrap();
+ let start = Utc::now() + Duration::days(2);
+ let a = booking(p.id, start);
+ let mut b = booking(p.id, start + Duration::hours(1));
+ b.booking.event_type_id = a.booking.event_type_id;
+ let (a, b) = tokio::join!(
+ repo.reserve(a, Some(1), start, start + Duration::days(1)),
+ repo.reserve(b, Some(1), start, start + Duration::days(1))
+ );
+ assert_eq!(usize::from(a.is_ok()) + usize::from(b.is_ok()), 1);
+}
+
+#[sqlx::test(migrations = false)]
+async fn reschedule_holds_both_times_without_blocking_the_days_between(pool: PgPool) {
+ setup(&pool).await;
+ let repo = PostgresRepository::new(pool);
+ let p = repo.save_profile(owned()).await.unwrap();
+ let start = Utc::now() + Duration::days(2);
+ let mut moving = repo
+ .reserve(booking(p.id, start), None, start, start + Duration::days(1))
+ .await
+ .unwrap();
+ repo.reserve(
+ booking(p.id, start + Duration::days(1)),
+ None,
+ start,
+ start + Duration::days(3),
+ )
+ .await
+ .unwrap();
+ moving.booking.starts_at += Duration::days(2);
+ moving.booking.ends_at += Duration::days(2);
+ moving.busy_start += Duration::days(2);
+ moving.busy_end += Duration::days(2);
+ moving.booking.status = BookingStatus::Processing;
+ moving = repo
+ .move_booking(
+ moving.clone(),
+ BookingStatus::Pending,
+ start,
+ start + Duration::days(3),
+ )
+ .await
+ .unwrap();
+ for occupied in [start, start + Duration::days(2)] {
+ assert!(matches!(
+ repo.reserve(
+ booking(p.id, occupied),
+ None,
+ start,
+ start + Duration::days(3)
+ )
+ .await,
+ Err(Error::Conflict)
+ ));
+ }
+ moving.booking.status = BookingStatus::Pending;
+ repo.update_booking(moving, BookingStatus::Processing)
+ .await
+ .unwrap();
+ assert!(
+ repo.reserve(booking(p.id, start), None, start, start + Duration::days(1))
+ .await
+ .is_ok()
+ );
+}
+
+#[sqlx::test(migrations = false)]
+async fn booking_history_is_bounded_but_host_counts_are_not(pool: PgPool) {
+ setup(&pool).await;
+ let repo = PostgresRepository::new(pool.clone());
+ let p = repo.save_profile(owned()).await.unwrap();
+ let start = Utc::now() + Duration::days(2);
+ let r = booking(p.id, start);
+ let json = serde_json::to_value(&r).unwrap();
+ let ids: Vec<_> = (0..5001).map(|_| Uuid::now_v7()).collect();
+ sqlx::query!(
+ "INSERT INTO scheduling_booking (id, profile_id, request_id, event_type_id, starts_at, ends_at, status, record) SELECT id, $1, id, $2, $3, $4, 'confirmed', $5 FROM unnest($6::uuid[]) AS id",
+ p.id, r.booking.event_type_id, start, r.booking.ends_at, json, &ids
+ ).execute(&pool).await.unwrap();
+ let hosts = vec!["host".to_string(), "unused".to_string()];
+ let counts = repo
+ .host_booking_counts(p.id, &hosts, start, start + Duration::days(1))
+ .await
+ .unwrap();
+ assert_eq!(counts.get("host"), Some(&5001));
+ assert!(!counts.contains_key("unused"));
+ assert!(
+ repo.host_booking_counts(p.id, &hosts, start - Duration::days(1), start)
+ .await
+ .unwrap()
+ .is_empty()
+ );
+ assert!(
+ matches!(repo.bookings(p.id, start, start + Duration::days(1)).await, Err(Error::Invalid(message)) if message.contains("shorter date range"))
+ );
+ assert!(
+ repo.bookings(p.id, start - Duration::days(1), start)
+ .await
+ .unwrap()
+ .is_empty()
+ );
+}
+
+#[sqlx::test(migrations = false)]
+async fn recovery_claims_are_exclusive_and_completion_is_fenced(pool: PgPool) {
+ setup(&pool).await;
+ let repo = PostgresRepository::new(pool.clone());
+ let p = repo.save_profile(owned()).await.unwrap();
+ let start = Utc::now() + Duration::days(2);
+ let mut original = booking(p.id, start);
+ original.booking.status = BookingStatus::Processing;
+ let mut operation = CalendarOperation::new(CalendarOperationKind::Create);
+ operation.retry_at = Utc::now() - Duration::seconds(1);
+ original.operation = Some(operation);
+ repo.reserve(original.clone(), None, start, start + Duration::days(1))
+ .await
+ .unwrap();
+ let (a, b) = tokio::join!(repo.claim_recovery(), repo.claim_recovery());
+ let mut claimed = a.unwrap().or(b.unwrap()).unwrap();
+ assert_eq!(claimed.operation.as_ref().unwrap().attempt, 1);
+ assert!(repo.claim_recovery().await.unwrap().is_none());
+ original.booking.status = BookingStatus::Confirmed;
+ assert!(matches!(
+ repo.update_booking(original, BookingStatus::Processing)
+ .await,
+ Err(Error::Conflict)
+ ));
+ claimed.booking.status = BookingStatus::Confirmed;
+ repo.update_booking(claimed, BookingStatus::Processing)
+ .await
+ .unwrap();
+}
+
+#[sqlx::test(migrations = false)]
+async fn public_budget_is_atomic_shared_and_resets_without_growing_rows(pool: PgPool) {
+ setup(&pool).await;
+ let repo = std::sync::Arc::new(PostgresRepository::new(pool.clone()));
+ let p = repo.save_profile(owned()).await.unwrap();
+ let mut tasks = tokio::task::JoinSet::new();
+ for _ in 0..50 {
+ let repo = repo.clone();
+ tasks.spawn(async move { repo.consume_budget(p.id, PublicBudget::Booking).await });
+ }
+ let mut admitted = 0;
+ while let Some(result) = tasks.join_next().await {
+ match result.unwrap() {
+ Ok(()) => admitted += 1,
+ Err(Error::RateLimited) => {}
+ other => panic!("unexpected budget result: {other:?}"),
+ }
+ }
+ assert_eq!(admitted, 30);
+ sqlx::query!("UPDATE scheduling_public_budget SET window_start = now() - interval '2 hours' WHERE profile_id = $1", p.id).execute(&pool).await.unwrap();
+ repo.consume_budget(p.id, PublicBudget::Booking)
+ .await
+ .unwrap();
+ repo.consume_budget(p.id, PublicBudget::Availability)
+ .await
+ .unwrap();
+ assert_eq!(
+ sqlx::query_scalar!(
+ "SELECT count(*) FROM scheduling_public_budget WHERE profile_id = $1",
+ p.id
+ )
+ .fetch_one(&pool)
+ .await
+ .unwrap(),
+ Some(2)
+ );
+}
+
+#[sqlx::test(migrations = false)]
+async fn stale_confirmed_snapshot_cannot_release_a_rescheduled_reservation(pool: PgPool) {
+ setup(&pool).await;
+ let repo = PostgresRepository::new(pool);
+ let p = repo.save_profile(owned()).await.unwrap();
+ let start = Utc::now() + Duration::days(2);
+ let mut stale = booking(p.id, start);
+ stale.booking.status = BookingStatus::Confirmed;
+ repo.reserve(stale.clone(), None, start, start + Duration::days(1))
+ .await
+ .unwrap();
+ let mut moving = stale.clone();
+ moving.booking.starts_at += Duration::hours(2);
+ moving.booking.ends_at += Duration::hours(2);
+ moving.busy_start += Duration::hours(2);
+ moving.busy_end += Duration::hours(2);
+ moving.operation = Some(CalendarOperation::new(CalendarOperationKind::Move {
+ status: BookingStatus::Confirmed,
+ original_start: start,
+ }));
+ moving.booking.status = BookingStatus::Processing;
+ let mut moved = repo
+ .move_booking(
+ moving,
+ BookingStatus::Confirmed,
+ start,
+ start + Duration::days(1),
+ )
+ .await
+ .unwrap();
+ moved.booking.status = BookingStatus::Confirmed;
+ repo.update_booking(moved, BookingStatus::Processing)
+ .await
+ .unwrap();
+ stale.booking.attendance = BookingAttendance::Attended;
+ assert!(matches!(
+ repo.update_booking(stale.clone(), BookingStatus::Confirmed)
+ .await,
+ Err(Error::Conflict)
+ ));
+ assert!(matches!(
+ repo.move_booking(
+ stale,
+ BookingStatus::Confirmed,
+ start,
+ start + Duration::days(1)
+ )
+ .await,
+ Err(Error::Conflict)
+ ));
+ assert!(matches!(
+ repo.reserve(
+ booking(p.id, start + Duration::hours(2)),
+ None,
+ start,
+ start + Duration::days(1)
+ )
+ .await,
+ Err(Error::Conflict)
+ ));
+}
diff --git a/crates/macro_db_client/migrations/20260918164303_calendar_scheduling.sql b/crates/macro_db_client/migrations/20260918164303_calendar_scheduling.sql
new file mode 100644
index 0000000000..5d13451248
--- /dev/null
+++ b/crates/macro_db_client/migrations/20260918164303_calendar_scheduling.sql
@@ -0,0 +1,31 @@
+-- Scheduling owns its configuration, booking snapshots, and host reservations.
+CREATE EXTENSION IF NOT EXISTS btree_gist;
+CREATE TABLE scheduling_profile (
+ id uuid PRIMARY KEY,
+ user_id text REFERENCES "User"(id) ON DELETE CASCADE,
+ team_id uuid REFERENCES team(id) ON DELETE CASCADE,
+ revision bigint NOT NULL DEFAULT 1 CHECK (revision > 0),
+ configuration jsonb NOT NULL,
+ CHECK (num_nonnulls(user_id, team_id) = 1)
+);
+CREATE UNIQUE INDEX scheduling_profile_user ON scheduling_profile(user_id) WHERE user_id IS NOT NULL;
+CREATE UNIQUE INDEX scheduling_profile_team ON scheduling_profile(team_id) WHERE team_id IS NOT NULL;
+CREATE TABLE scheduling_booking (
+ id uuid PRIMARY KEY,
+ profile_id uuid NOT NULL REFERENCES scheduling_profile(id) ON DELETE CASCADE,
+ request_id uuid NOT NULL UNIQUE,
+ event_type_id uuid NOT NULL,
+ starts_at timestamptz NOT NULL,
+ ends_at timestamptz NOT NULL,
+ status text NOT NULL CHECK (status IN ('pending','processing','confirmed','cancelled','failed')),
+ record jsonb NOT NULL,
+ CHECK (ends_at > starts_at)
+);
+CREATE INDEX scheduling_booking_profile_time ON scheduling_booking(profile_id, starts_at);
+CREATE TABLE scheduling_host_claim (
+ booking_id uuid NOT NULL REFERENCES scheduling_booking(id) ON DELETE CASCADE,
+ user_id text NOT NULL REFERENCES "User"(id) ON DELETE CASCADE,
+ occupied tstzmultirange NOT NULL,
+ PRIMARY KEY (booking_id, user_id),
+ EXCLUDE USING gist (user_id WITH =, occupied WITH &&)
+);
diff --git a/crates/macro_db_client/migrations/20260918175703_scheduling_recovery.sql b/crates/macro_db_client/migrations/20260918175703_scheduling_recovery.sql
new file mode 100644
index 0000000000..4233e494f1
--- /dev/null
+++ b/crates/macro_db_client/migrations/20260918175703_scheduling_recovery.sql
@@ -0,0 +1,12 @@
+-- Additive: old service versions omit this nullable field safely.
+ALTER TABLE scheduling_booking ADD COLUMN recovery_at timestamptz;
+CREATE INDEX scheduling_booking_recovery ON scheduling_booking(recovery_at)
+ WHERE status IN ('processing', 'failed') AND recovery_at IS NOT NULL;
+-- Bounded to two rows per profile. Deleting a profile also removes its budgets.
+CREATE TABLE scheduling_public_budget (
+ profile_id uuid NOT NULL REFERENCES scheduling_profile(id) ON DELETE CASCADE,
+ kind text NOT NULL CHECK (kind IN ('availability', 'booking')),
+ window_start timestamptz NOT NULL,
+ used integer NOT NULL CHECK (used > 0),
+ PRIMARY KEY (profile_id, kind)
+);
diff --git a/docs/AGENT_GUIDE/surfaces.md b/docs/AGENT_GUIDE/surfaces.md
index 6a00934f23..3dc84a86bd 100644
--- a/docs/AGENT_GUIDE/surfaces.md
+++ b/docs/AGENT_GUIDE/surfaces.md
@@ -1120,6 +1120,62 @@ footer. Answering a recurring invitation opens a rounded glass sheet: choose
`This event` or `All events`, then `Save response`. Cancel or Close returns to
the event details without sending a response.
+Calendar scheduling requires the PostHog flag `enable-calendar-scheduling`, which
+is off unless enabled remotely (including in dev). For local browser checks,
+`VITE_ENABLE_CALENDAR_SCHEDULING=true` overrides it. While off, the Calendar settings
+tab and calendar booking shortcuts are hidden; public booking and receipt links
+show an unavailable page without fetching scheduling data. When enabling a hosted
+rollout, include anonymous visitors so invitees can open those links.
+
+When enabled, calendar scheduling lives in **Settings → Calendar** (`/app/settings/calendar`).
+The scheduling sidebar opens Event types, Bookings, Availability, Teams, Insights,
+and Booking page. Event editors have a grouped settings sidebar; booking status
+filters use the same segmented control as the CRM sidebar.
+In Availability, each weekday has an enable switch, time ranges, an add button,
+and a copy-hours menu; select target days and Apply before saving the schedule.
+Date overrides and the searchable timezone picker sit below the weekly hours.
+Choose Personal or your Macro team in `Calendar owner`. Team owners/admins can
+edit team links; ordinary members can view them. `Event types` creates, edits,
+pauses, duplicates, previews, and copies booking links. Event settings include
+weekly availability, collective/all-host or round-robin/one-host assignment,
+notice, buffers, booking horizon, daily limits, and custom questions. New event
+types stay paused until `Accept bookings` is selected and changes are saved.
+`Availability` manages named weekly schedules and date overrides in an IANA time
+zone. Set a default schedule for new event types; a schedule cannot be deleted
+until its event types use another one. Collective and round-robin team meetings
+respect each host’s personal default hours when configured, plus busy calendars.
+`Teams` uses existing Macro team membership and links to team settings.
+`Booking page` edits the public name and description. `Bookings` shows
+upcoming, unconfirmed, past, and cancelled meetings; admins can confirm requests,
+reschedule, or cancel them. Choose From/Through dates to load bookings (initially 30 days before and after today), then search by guest/title/email and filter by event type. Dates use your browser time zone; shorten the range if more than 5,000 bookings match.
+Cancellation asks for confirmation. After a confirmed meeting ends, an assigned
+host or team admin can mark attendance or a host/guest no-show. Pending requests
+from older configurations appear under Unconfirmed. New approval-only links are disabled;
+new links use automatic confirmation and provider calendar invitations. Existing approval
+links must switch to automatic confirmation before accepting new bookings.
+
+`Insights` reports the selected personal/team owner with 7/30/90-day or custom
+ranges, event/host filters, previous-period comparisons, event trends, meeting
+hours, no-shows, popular events, and host counts. Download exports the filtered
+bookings to CSV. Metrics use booking start dates in the default schedule’s time
+zone; failed/processing requests are excluded. Completed means ended confirmed
+bookings excluding recorded no-shows. Rescheduled counts bookings with recorded
+reschedule history. Ratings/CSAT are not shown because no survey data is collected.
+Oversized result sets return an error instead of silently truncating insights.
+
+The calendar header includes `Copy booking link` and `Open calendar scheduling
+settings`. Copy opens settings when no active personal link exists. Public
+`/app/book/:profile/:slug?` pages accept bookings without Macro sign-in. Uncertain
+calendar writes retain the booking and show its private receipt while automatic recovery runs.
+After a network response cannot be verified, `Check booking status` retries the original request;
+do not create a replacement booking. Receipt pages poll while the calendar update is pending. Visitors
+choose their time zone, date, time, and required details. The private
+`/app/booking/:id#token` receipt supports cancellation and rescheduling; preserve
+that private link. Rescheduling dates are labelled in the availability schedule's
+time zone. Calendar provider failures show an error; they never report a
+confirmed booking. Current integrations check hosts' connected calendars and
+write invitations/Google Meet through the existing calendar service.
+
The standalone Calendar view has a left navigation sidebar. The `New` menu
above the mini calendar offers `Event`, feature-gated `Call`, and feature-gated
`Reminder`. An icon-only shortcut in the `Upcoming events` header opens the
diff --git a/docs/CALENDAR_SCHEDULING_V1.md b/docs/CALENDAR_SCHEDULING_V1.md
new file mode 100644
index 0000000000..4a95a7ba7e
--- /dev/null
+++ b/docs/CALENDAR_SCHEDULING_V1.md
@@ -0,0 +1,134 @@
+# Scheduling v1 parity
+
+Reference: signed-in Cal.com Links, event editor, Bookings, Availability, Teams,
+and Insights, inspected September 18, 2026. Macro keeps its own identity and UI
+primitives while using the same sidebar/page hierarchy, settings sections,
+bordered lists, metric strips, and chart layout. Themes use Macro semantic tokens;
+the isolated browser fixture defaults to the light reference appearance.
+
+| Core workflow | Implemented |
+| --- | --- |
+| Personal booking links | Event CRUD, duration, description, URL slug, location/Google Meet, pause, duplicate, copy and preview |
+| Booking form | Required name/email and configurable questions |
+| Availability | Multiple named schedules, explicit default, weekly ranges, per-day enable/add/remove/copy, timezone, date overrides, deletion protected while in use |
+| Scheduling policies | Notice, horizon, buffers, slot interval, daily limits; DST-aware server slot calculation and atomic conflict reservations |
+| Team scheduling | Existing Macro membership and permissions, collective and round robin; team hours intersect configured personal default hours and busy calendars |
+| Guest booking | Public links, visitor timezone, slots, confirmation, private cancellation/reschedule receipt; provider invitations and Google Meet |
+| Booking management | Upcoming/unconfirmed/past/cancelled, search/event/timezone filters, guest/host/answer details, legacy-request approval, cancellation confirmation, reschedule, attendance/no-show recording |
+| Insights | Personal/team scope, 7/30/90/custom dates, event/host filters, prior-period comparisons, completed/rescheduled/cancelled/no-show counts, scheduled meeting hours, duration, trends, hourly totals, event/host rankings, CSV |
+| Calendar integration | Existing connected calendars and permission checks, busy conflict exclusion, provider event create/update/cancel |
+| Macro entry points | Calendar settings tab; copy booking link and scheduling settings in calendar header; standalone public and receipt routes |
+
+## Reporting semantics
+
+Reports group bookings by their current start date in the profile default
+schedule's timezone. Previous-period queries include equal calendar-day windows
+across DST. Completed means confirmed bookings whose end time has passed,
+excluding recorded no-shows; actual call duration is not tracked. Rescheduled
+counts bookings with at least one recorded successful reschedule, once per
+booking. No-shows require an explicit host/admin record. Categories may overlap.
+Failed and processing provider operations are excluded. Oversized queries return
+an actionable error instead of silently dropping records. CSV exports the filtered
+current-period bookings and escapes spreadsheet formulas.
+
+## Deliberate deferrals and remaining gaps
+
+- Payments, routing forms, workflows/webhooks, recurring group classes, ratings and
+ CSAT collection are outside this core scheduling release. Unsupported metrics
+ are not shown as invented zeroes.
+- New manual-approval links are disabled in the UI and rejected by the backend until
+ host/guest notifications are implemented. Existing pending records can still be managed.
+ Legacy approval links are paused for new bookings until automatic confirmation is enabled.
+- Provider writes have durable, version-fenced recovery. Create uses a stable organizer-scoped
+ provider ID; cancellation can replay after the canonical calendar record disappears.
+ Uncertain writes retain reservations, return a private receipt, and retry automatically.
+ Repeated failures require operator attention; see the release checklist below.
+- Hosted activation still requires both scheduling migrations and the updated calendar
+ service. The isolated browser fixture uses explicitly labelled sample data and
+ the real UI components; its mutations do not send invitations or change Cal.com.
+
+## Verification
+
+Unit/integration tests cover timezones/DST, comparisons, exports, async races,
+status filtering, authorization, attendance, host availability, and transactional
+reservations. Browser checks cover page navigation, filters, chart interactions,
+CSV trigger, no-show-to-insights updates, defaults, schedule deletion protection,
+read-only scopes, event creation, and both themes. See the crate README for backend
+setup and operational details; `docs/AGENT_GUIDE/surfaces.md` describes the UI.
+
+Pre-production checks also exercise lost provider responses and duplicate-provider
+conflicts, database completion failures, recovery lease takeover, repeated cancellation,
+and shared request budgets. The browser's lost-response fixture verifies that a guest
+retries the same booking request and receives its existing receipt. Narrow 390px
+layouts were checked for event types, availability, insights, and confirmation.
+These fixture checks do not replace the connected-account rollout checks below.
+
+An isolated full local stack also applied both migrations and verified actual sign-in,
+personal event creation/editing/duplication, persisted weekly-hour edits, collective team
+host selection, read-only team membership, and team Insights. This caught and fixed editor
+cloning of Solid Query store proxies; the preview now uses reactive store inputs too.
+A disconnected host correctly exposes no bookable slots and shows an availability error.
+Real Google OAuth, invitations, and Meet remain the connected-account rollout gate.
+
+## Pre-production release checklist
+
+Connected-account checks remain an outstanding rollout gate. Dedicated Google-connected
+test accounts were unavailable for the PR readiness pass; local fixtures and automated
+tests do not verify real invitations, OAuth, or Meet creation.
+
+- Apply `20260918164303_calendar_scheduling.sql`, then `20260918175703_scheduling_recovery.sql`
+ before deploying the calendar service. Both are additive; the second adds a nullable retry
+ timestamp, partial recovery index, and bounded per-profile request budgets.
+- Leave the frontend PostHog flag `enable-calendar-scheduling` disabled until the
+ connected-account checks below pass. An absent flag is also off, including in dev;
+ `VITE_ENABLE_CALENDAR_SCHEDULING=true` is available for local testing. The flag gates
+ the Calendar settings tab, calendar booking shortcuts, and public booking/receipt pages
+ before their queries mount. Hosted rollout targeting must include anonymous visitors
+ so invitees can book and manage bookings. Disabling it also hides existing receipt links.
+ This frontend flag does not disable backend routes, recovery, or migrations.
+- Keep the existing `CALENDAR_SYNC_ENABLED` switch enabled for scheduling routes and recovery.
+ New configuration cannot turn on manual approval. Automatic provider invitations remain active.
+- Database-backed HTTP checks cover authorization, configuration, public slots, idempotent booking,
+ private receipts, failed-write recovery, rescheduling and cancellation. External identity and
+ Google are controlled in these tests; they do not prove real OAuth, email delivery, or Meet creation.
+- Before rollout, complete one personal and one team booking with dedicated connected test accounts;
+ confirm busy-time exclusion, invitation delivery, Meet, reschedule and cancellation. Test revoked
+ access and restored access. Do not use a live customer's calendar as a fixture.
+- Roll back the service/frontend to the version before scheduling if necessary; retain both additive
+ migrations and every booking/claim. Do not delete reservations to clear a failure. Drain/reconcile
+ pending intents before re-enabling scheduling on any older implementation without recovery.
+- Shared profile budgets allow 120 availability requests/minute and 30 new booking attempts/hour.
+ They fail closed if storage fails and are independent of replica count. They are backpressure,
+ not human verification: gateway/IP abuse monitoring remains part of normal service operations.
+
+## Recovery and monitoring
+
+The calendar service polls every 15 seconds, at most 25 operations per pass. Each claim has a
+five-minute lease, an incremented operation attempt, and a booking revision. All edits use the
+revision, protecting against confirmed → processing → confirmed races. Provider errors back off
+from five minutes to one hour; the third recovery attempt emits an operator-attention error.
+Completed claims clear their due timestamp. Disconnected/inaccessible calendars keep reservations
+until access is restored; recovery never interprets lost permission as a successful deletion.
+
+Use the calendar-service logs for `scheduling operation queued for recovery`, `scheduling operation
+recovered`, `scheduling recovery requires operator attention`, and `scheduling completion persistence
+unavailable`. Alert on operator-attention/persistence errors and sustained scheduling 5xx. During
+rollout, also check overdue rows so a stopped worker cannot hide behind missing logs:
+
+```sql
+SELECT status, count(*) AS bookings, min(recovery_at) AS earliest_retry
+FROM scheduling_booking
+WHERE status IN ('processing', 'failed')
+GROUP BY status;
+
+SELECT id, status, recovery_at, record->'operation'->>'attempt' AS attempts
+FROM scheduling_booking
+WHERE status IN ('processing', 'failed')
+ORDER BY recovery_at NULLS FIRST
+LIMIT 100;
+```
+
+These queries omit guest details and private management tokens. Investigate any due timestamp
+more than ten minutes overdue; check worker health, calendar grant/sync state, then provider logs.
+Do not manually release claims or reset database volumes. Permanent provider rejection needs a
+reviewed resolution; retrying cannot repair a revoked grant or deleted target calendar.
diff --git a/packages/sdk/generated/calendar/types.gen.ts b/packages/sdk/generated/calendar/types.gen.ts
index c01a76f3d6..c54118573f 100644
--- a/packages/sdk/generated/calendar/types.gen.ts
+++ b/packages/sdk/generated/calendar/types.gen.ts
@@ -323,6 +323,10 @@ export type CreateCalendarEventRequest = {
* to the requester's primary inbox.
*/
emailLinkId?: string | null;
+ /**
+ * Stable retry identity, scoped to the authenticated organizer.
+ */
+ idempotencyKey?: string | null;
/**
* Optional location label.
*/
diff --git a/packages/sdk/specs/calendar.json b/packages/sdk/specs/calendar.json
index 364c977d19..6a807ef493 100644
--- a/packages/sdk/specs/calendar.json
+++ b/packages/sdk/specs/calendar.json
@@ -768,6 +768,11 @@
"format": "uuid",
"description": "Connected inbox whose primary calendar receives the event; defaults\nto the requester's primary inbox."
},
+ "idempotencyKey": {
+ "type": ["string", "null"],
+ "format": "uuid",
+ "description": "Stable retry identity, scoped to the authenticated organizer."
+ },
"location": {
"type": ["string", "null"],
"description": "Optional location label."
diff --git a/rules/ast-grep/ts-feature-components-presentational.yml b/rules/ast-grep/ts-feature-components-presentational.yml
index e7f4f56b29..d1e1bc8bbc 100644
--- a/rules/ast-grep/ts-feature-components-presentational.yml
+++ b/rules/ast-grep/ts-feature-components-presentational.yml
@@ -13,6 +13,7 @@ note: |-
untyped wire JSON for property-changed rows. In block-agent, `ui/` is
the presentation layer and `component/` is the composition layer.
files:
+ - apps/web/src/features/scheduling/components/**
- apps/web/src/features/crm/components/**
- apps/web/src/features/slack-import/components/**
- apps/web/src/features/channels-view/components/ChannelDetailView*
diff --git a/rules/ast-grep/ts-feature-core-pure.yml b/rules/ast-grep/ts-feature-core-pure.yml
index 813e205856..0801fef712 100644
--- a/rules/ast-grep/ts-feature-core-pure.yml
+++ b/rules/ast-grep/ts-feature-core-pure.yml
@@ -15,6 +15,7 @@ note: |-
The shared @core/util/base64 codec is also pure and may be reused by email.
Block-agent names its rendering layers `ui/` and `component/`.
files:
+ - apps/web/src/features/scheduling/core/**
- apps/web/src/features/crm/core/**
- apps/web/src/features/slack-import/core/**
- apps/web/src/features/channel/core/channel-invite*
diff --git a/rules/ast-grep/ts-feature-data-no-ui.yml b/rules/ast-grep/ts-feature-data-no-ui.yml
index e681252339..30372e2618 100644
--- a/rules/ast-grep/ts-feature-data-no-ui.yml
+++ b/rules/ast-grep/ts-feature-data-no-ui.yml
@@ -11,6 +11,10 @@ note: |-
with fake clients and controllers with fake capabilities; neither imports
rendering code, including block-agent’s `ui/` and `component/` layers.
files:
+ - apps/web/src/features/scheduling/core/**
+ - apps/web/src/features/scheduling/context/**
+ - apps/web/src/features/scheduling/queries/**
+ - apps/web/src/features/scheduling/primitives/**
- apps/web/src/features/crm/queries/**
- apps/web/src/features/crm/primitives/**
- apps/web/src/features/slack-import/queries/**
diff --git a/rules/ast-grep/ts-feature-layers-use-context.yml b/rules/ast-grep/ts-feature-layers-use-context.yml
index 92f3769faf..7fc66f7fe9 100644
--- a/rules/ast-grep/ts-feature-layers-use-context.yml
+++ b/rules/ast-grep/ts-feature-layers-use-context.yml
@@ -15,6 +15,11 @@ note: |-
`files` in each ts-/tsx-feature-* rule. Block-agent uses `ui/` for
presentation and `component/` for composition.
files:
+ - apps/web/src/features/scheduling/context/**
+ - apps/web/src/features/scheduling/queries/**
+ - apps/web/src/features/scheduling/primitives/**
+ - apps/web/src/features/scheduling/components/**
+ - apps/web/src/features/scheduling/views/**
- apps/web/src/features/crm/queries/**
- apps/web/src/features/crm/primitives/**
- apps/web/src/features/crm/components/**
diff --git a/rules/ast-grep/tsx-feature-components-presentational.yml b/rules/ast-grep/tsx-feature-components-presentational.yml
index baa0987caa..aab71e8c25 100644
--- a/rules/ast-grep/tsx-feature-components-presentational.yml
+++ b/rules/ast-grep/tsx-feature-components-presentational.yml
@@ -13,6 +13,7 @@ note: |-
untyped wire JSON for property-changed rows. In block-agent, `ui/` is
the presentation layer and `component/` is the composition layer.
files:
+ - apps/web/src/features/scheduling/components/**
- apps/web/src/features/crm/components/**
- apps/web/src/features/slack-import/components/**
- apps/web/src/features/channels-view/components/ChannelDetailView*
diff --git a/rules/ast-grep/tsx-feature-core-pure.yml b/rules/ast-grep/tsx-feature-core-pure.yml
index 67c9a87dfe..94a306bae2 100644
--- a/rules/ast-grep/tsx-feature-core-pure.yml
+++ b/rules/ast-grep/tsx-feature-core-pure.yml
@@ -15,6 +15,7 @@ note: |-
The shared @core/util/base64 codec is also pure and may be reused by email.
Block-agent names its rendering layers `ui/` and `component/`.
files:
+ - apps/web/src/features/scheduling/core/**
- apps/web/src/features/crm/core/**
- apps/web/src/features/slack-import/core/**
- apps/web/src/features/channel/core/channel-invite*
diff --git a/rules/ast-grep/tsx-feature-data-no-ui.yml b/rules/ast-grep/tsx-feature-data-no-ui.yml
index 38add60fee..3f84daad8a 100644
--- a/rules/ast-grep/tsx-feature-data-no-ui.yml
+++ b/rules/ast-grep/tsx-feature-data-no-ui.yml
@@ -11,6 +11,10 @@ note: |-
with fake clients and controllers with fake capabilities; neither imports
rendering code, including block-agent’s `ui/` and `component/` layers.
files:
+ - apps/web/src/features/scheduling/core/**
+ - apps/web/src/features/scheduling/context/**
+ - apps/web/src/features/scheduling/queries/**
+ - apps/web/src/features/scheduling/primitives/**
- apps/web/src/features/crm/queries/**
- apps/web/src/features/crm/primitives/**
- apps/web/src/features/slack-import/queries/**
diff --git a/rules/ast-grep/tsx-feature-layers-use-context.yml b/rules/ast-grep/tsx-feature-layers-use-context.yml
index 3f2d807b52..c7b2f1eb39 100644
--- a/rules/ast-grep/tsx-feature-layers-use-context.yml
+++ b/rules/ast-grep/tsx-feature-layers-use-context.yml
@@ -15,6 +15,11 @@ note: |-
`files` in each ts-/tsx-feature-* rule. Block-agent uses `ui/` for
presentation and `component/` for composition.
files:
+ - apps/web/src/features/scheduling/context/**
+ - apps/web/src/features/scheduling/queries/**
+ - apps/web/src/features/scheduling/primitives/**
+ - apps/web/src/features/scheduling/components/**
+ - apps/web/src/features/scheduling/views/**
- apps/web/src/features/crm/queries/**
- apps/web/src/features/crm/primitives/**
- apps/web/src/features/crm/components/**
diff --git a/services/calendar_service/Cargo.toml b/services/calendar_service/Cargo.toml
index b8319b0b1f..c003f1c0e4 100644
--- a/services/calendar_service/Cargo.toml
+++ b/services/calendar_service/Cargo.toml
@@ -28,6 +28,7 @@ calendar_events = { path = "../../crates/calendar_events", features = [
"inbound",
"postgres",
] }
+calendar_scheduling = { path = "../../crates/calendar_scheduling", features = ["calendar", "inbound", "postgres"] }
chrono = { workspace = true }
connection_gateway_client = { path = "../../crates/connection_gateway_client" }
email_db_client = { path = "../../crates/email_db_client" }
@@ -57,6 +58,7 @@ serde_json = { workspace = true }
sqlx = { workspace = true }
sqs_worker = { path = "../../crates/sqs_worker" }
subtle = { workspace = true }
+teams = { path = "../../crates/teams", default-features = false, features = ["outbound", "ports"] }
tokio = { workspace = true, features = ["signal"] }
tokio-util = { workspace = true, features = ["rt"] }
tower = { workspace = true }
diff --git a/services/calendar_service/src/api.rs b/services/calendar_service/src/api.rs
index 41e00f4ffe..f96da33981 100644
--- a/services/calendar_service/src/api.rs
+++ b/services/calendar_service/src/api.rs
@@ -64,10 +64,20 @@ fn api_router(state: ApiContext) -> Router<ApiContext> {
// Calendar mutations follow the calendar sync kill switch: without sync a
// provider write would never be reflected locally.
if state.config.calendar_sync_enabled {
- calendar_watch::router().merge(calendar_mutation_router(CalendarMutationRouterState::new(
- state.calendar_mutation_service.clone(),
- state.authorization_state.clone(),
- )))
+ calendar_watch::router()
+ .nest(
+ "/scheduling",
+ calendar_scheduling::inbound::router::router(
+ calendar_scheduling::inbound::router::RouterState::new(
+ state.scheduling_service.clone(),
+ state.authorization_state.clone(),
+ ),
+ ),
+ )
+ .merge(calendar_mutation_router(CalendarMutationRouterState::new(
+ state.calendar_mutation_service.clone(),
+ state.authorization_state.clone(),
+ )))
} else {
calendar_watch::router()
}
diff --git a/services/calendar_service/src/api/context.rs b/services/calendar_service/src/api/context.rs
index 4072864621..3e6a097448 100644
--- a/services/calendar_service/src/api/context.rs
+++ b/services/calendar_service/src/api/context.rs
@@ -18,6 +18,17 @@ use crate::config::Config;
pub type AuthorizationService = MacroAuthorizationServiceImpl<MacroAuthJwtValidator>;
/// Calendar grant/watch service backing the push webhook.
pub type CalendarGrantService = CalendarService<PgCalendarRepository>;
+/// Booking policy backed by calendar services and the team directory.
+pub type SchedulingService = calendar_scheduling::domain::service::Service<
+ calendar_scheduling::outbound::postgres::PostgresRepository,
+ calendar_scheduling::outbound::macro_services::MacroCalendars<
+ CalendarGrantService,
+ CalendarMutationSvc,
+ >,
+ calendar_scheduling::outbound::macro_services::MacroDirectory<
+ teams::outbound::team_repo::TeamRepositoryImpl,
+ >,
+>;
/// User-initiated calendar mutation service.
pub type CalendarMutationSvc = CalendarMutationServiceImpl<
PgCalendarRepository,
@@ -38,4 +49,6 @@ pub struct ApiContext {
pub calendar_service: Arc<CalendarGrantService>,
/// User-initiated calendar mutation service.
pub calendar_mutation_service: Arc<CalendarMutationSvc>,
+ /// Personal and team scheduling service.
+ pub scheduling_service: Arc<SchedulingService>,
}
diff --git a/services/calendar_service/src/main.rs b/services/calendar_service/src/main.rs
index ca30c1a3a9..31f41c4c7e 100644
--- a/services/calendar_service/src/main.rs
+++ b/services/calendar_service/src/main.rs
@@ -30,6 +30,8 @@ use tokio_util::{sync::CancellationToken, task::TaskTracker};
const EVENT_BROKER_DRAIN_TIMEOUT: Duration = Duration::from_secs(10);
+mod scheduling_recovery;
+
#[tokio::main]
#[tracing::instrument(err)]
async fn main() -> anyhow::Result<()> {
@@ -188,11 +190,33 @@ async fn main() -> anyhow::Result<()> {
ConnectionGatewayCalendarRefresh::new(connection_gateway_client, db.clone()),
));
+ let scheduling_service = Arc::new(calendar_scheduling::domain::service::Service::new(
+ calendar_scheduling::outbound::postgres::PostgresRepository::new(db.clone()),
+ calendar_scheduling::outbound::macro_services::MacroCalendars::new(
+ calendar_service.clone(),
+ calendar_mutation_service.clone(),
+ match config.environment {
+ Environment::Production => Some("https://macro.com".into()),
+ Environment::Develop => Some("https://dev.macro.com".into()),
+ Environment::Local => None,
+ },
+ ),
+ calendar_scheduling::outbound::macro_services::MacroDirectory(
+ teams::outbound::team_repo::TeamRepositoryImpl::new(db.clone()),
+ ),
+ ));
+ if config.calendar_sync_enabled {
+ worker_tracker.spawn(scheduling_recovery::run(
+ scheduling_service.clone(),
+ worker_cancellation_token.clone(),
+ ));
+ }
let api_result = calendar_service::api::setup_and_serve(ApiContext {
config: Arc::new(config),
authorization_state,
calendar_service,
calendar_mutation_service,
+ scheduling_service,
})
.await;
diff --git a/services/calendar_service/src/scheduling_recovery.rs b/services/calendar_service/src/scheduling_recovery.rs
new file mode 100644
index 0000000000..f5d44f1f50
--- /dev/null
+++ b/services/calendar_service/src/scheduling_recovery.rs
@@ -0,0 +1,26 @@
+//! Drives durable scheduling intents after provider failures or process restarts.
+use calendar_service::api::context::SchedulingService;
+use std::{sync::Arc, time::Duration};
+use tokio_util::sync::CancellationToken;
+
+pub async fn run(service: Arc<SchedulingService>, stop: CancellationToken) {
+ loop {
+ for _ in 0..25 {
+ tokio::select! {
+ _ = stop.cancelled() => return,
+ result = tokio::time::timeout(Duration::from_secs(120), service.recover_once()) => {
+ match result {
+ Ok(Ok(true)) => {},
+ Ok(Ok(false)) => break,
+ Ok(Err(error)) => tracing::warn!(error=?error, "scheduling recovery attempt failed"),
+ Err(error) => tracing::error!(error=?error, "scheduling recovery timed out; lease will expire"),
+ }
+ }
+ }
+ }
+ tokio::select! {
+ _ = stop.cancelled() => return,
+ _ = tokio::time::sleep(Duration::from_secs(15)) => {},
+ }
+ }
+}