Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(teams): hexify teams crate (#1911)
Will Hutchinsona62028576ffd
diff --git a/js/app/packages/service-clients/service-auth/generated/client.ts b/js/app/packages/service-clients/service-auth/generated/client.tsindex a447afd558..efbc6bb576 100644--- a/js/app/packages/service-clients/service-auth/generated/client.ts+++ b/js/app/packages/service-clients/service-auth/generated/client.ts@@ -43,7 +43,7 @@ import type {StripeSessionResponse,Team,TeamInvitesResponse,- TeamWithUsers,+ TeamWithMembers,UserLinkResponse,UserName,UserNames,@@ -1484,7 +1484,7 @@ export const createTeam = async (* @summary Joins a team by accepting an invite.*/export type joinTeamResponse200 = {- data: EmptyResponse;+ data: void;status: 200;};@@ -1539,7 +1539,7 @@ export const joinTeam = async (* @summary Rejects an invitation to join a team.*/export type rejectInvitationResponse200 = {- data: EmptyResponse;+ data: void;status: 200;};@@ -1720,7 +1720,7 @@ export const getUserInvites = async (* @summary Gets a team by ID.*/export type getTeamResponse200 = {- data: TeamWithUsers;+ data: TeamWithMembers;status: 200;};@@ -1783,7 +1783,7 @@ This will update all team members roles and cancel your subscription for the teaThis action is **irreversible** and you will not be able to recover the team afterwards.*/export type deleteTeamResponse200 = {- data: EmptyResponse;+ data: void;status: 200;};@@ -1844,7 +1844,7 @@ export const deleteTeam = async (* @summary Updates a team.*/export type patchTeamResponse200 = {- data: EmptyResponse;+ data: void;status: 200;};@@ -1986,6 +1986,80 @@ export const inviteToTeam = async (} as inviteToTeamResponse;};+/**+ * @summary Deletes a team invite from a team.+ */+export type deleteTeamInviteHandlerResponse200 = {+ data: void;+ status: 200;+};++export type deleteTeamInviteHandlerResponse400 = {+ data: ErrorResponse;+ status: 400;+};++export type deleteTeamInviteHandlerResponse401 = {+ data: ErrorResponse;+ status: 401;+};++export type deleteTeamInviteHandlerResponse404 = {+ data: ErrorResponse;+ status: 404;+};++export type deleteTeamInviteHandlerResponse500 = {+ data: ErrorResponse;+ status: 500;+};++export type deleteTeamInviteHandlerResponseSuccess =+ deleteTeamInviteHandlerResponse200 & {+ headers: Headers;+ };+export type deleteTeamInviteHandlerResponseError = (+ | deleteTeamInviteHandlerResponse400+ | deleteTeamInviteHandlerResponse401+ | deleteTeamInviteHandlerResponse404+ | deleteTeamInviteHandlerResponse500+) & {+ headers: Headers;+};++export type deleteTeamInviteHandlerResponse =+ | deleteTeamInviteHandlerResponseSuccess+ | deleteTeamInviteHandlerResponseError;++export const getDeleteTeamInviteHandlerUrl = (+ teamId: string,+ teamInviteId: string+) => {+ return `/team/${teamId}/invite/${teamInviteId}`;+};++export const deleteTeamInviteHandler = async (+ teamId: string,+ teamInviteId: string,+ options?: RequestInit+): Promise<deleteTeamInviteHandlerResponse> => {+ const res = await fetch(getDeleteTeamInviteHandlerUrl(teamId, teamInviteId), {+ ...options,+ method: 'DELETE',+ });++ const body = [204, 205, 304].includes(res.status) ? null : await res.text();++ const data: deleteTeamInviteHandlerResponse['data'] = body+ ? JSON.parse(body)+ : {};+ return {+ data,+ status: res.status,+ headers: res.headers,+ } as deleteTeamInviteHandlerResponse;+};+/*** @summary Gets all invites for a team.*/@@ -2051,7 +2125,7 @@ export const getTeamInvites = async (* @summary Regenerates a team invite notifying the user again.*/export type reinviteToTeamResponse200 = {- data: EmptyResponse;+ data: void;status: 200;};@@ -2119,7 +2193,7 @@ export const reinviteToTeam = async (* @summary Removes a user from a team.*/export type removeUserFromTeamResponse200 = {- data: EmptyResponse;+ data: void;status: 200;};@@ -2133,11 +2207,6 @@ export type removeUserFromTeamResponse401 = {status: 401;};-export type removeUserFromTeamResponse429 = {- data: ErrorResponse;- status: 429;-};-export type removeUserFromTeamResponse500 = {data: ErrorResponse;status: 500;@@ -2150,7 +2219,6 @@ export type removeUserFromTeamResponseSuccess =export type removeUserFromTeamResponseError = (| removeUserFromTeamResponse400| removeUserFromTeamResponse401- | removeUserFromTeamResponse429| removeUserFromTeamResponse500) & {headers: Headers;diff --git a/js/app/packages/service-clients/service-auth/generated/schemas/index.ts b/js/app/packages/service-clients/service-auth/generated/schemas/index.tsindex c5ad53684d..0edf4794a1 100644--- a/js/app/packages/service-clients/service-auth/generated/schemas/index.ts+++ b/js/app/packages/service-clients/service-auth/generated/schemas/index.ts@@ -52,16 +52,11 @@ export * from './ssoLoginParams';export * from './ssoRequiredResponse';export * from './stripeSessionResponse';export * from './team';-export * from './teamInvite';+export * from './teamInviteDetails';export * from './teamInvitesResponse';-export * from './teamInviteUpdate';-export * from './teamInviteUpdateTeamRole';+export * from './teamMember';export * from './teamRole';-export * from './teamUpdateOperation';-export * from './teamUser';-export * from './teamUserUpdate';-export * from './teamUserUpdateTeamRole';-export * from './teamWithUsers';+export * from './teamWithMembers';export * from './userLinkResponse';export * from './userName';export * from './userNameFirstName';diff --git a/js/app/packages/service-clients/service-auth/generated/schemas/patchTeamRequest.ts b/js/app/packages/service-clients/service-auth/generated/schemas/patchTeamRequest.tsindex df297d8fc6..cc7ea6ce76 100644--- a/js/app/packages/service-clients/service-auth/generated/schemas/patchTeamRequest.ts+++ b/js/app/packages/service-clients/service-auth/generated/schemas/patchTeamRequest.ts@@ -7,9 +7,9 @@import type { PatchTeamRequestName } from './patchTeamRequestName';/**- * The request body to update a team+ * Request to update a team*/export interface PatchTeamRequest {- /** The new name of the team */+ /** The new name for the team */name?: PatchTeamRequestName;}diff --git a/js/app/packages/service-clients/service-auth/generated/schemas/patchTeamRequestName.ts b/js/app/packages/service-clients/service-auth/generated/schemas/patchTeamRequestName.tsindex 65cbcd03bb..28fdf2fb7b 100644--- a/js/app/packages/service-clients/service-auth/generated/schemas/patchTeamRequestName.ts+++ b/js/app/packages/service-clients/service-auth/generated/schemas/patchTeamRequestName.ts@@ -6,6 +6,6 @@*//**- * The new name of the team+ * The new name for the team*/export type PatchTeamRequestName = string | null;diff --git a/js/app/packages/service-clients/service-auth/generated/schemas/team.ts b/js/app/packages/service-clients/service-auth/generated/schemas/team.tsindex 5ccd1624e8..ea16eaaa85 100644--- a/js/app/packages/service-clients/service-auth/generated/schemas/team.ts+++ b/js/app/packages/service-clients/service-auth/generated/schemas/team.ts@@ -5,6 +5,9 @@* OpenAPI spec version: 0.1.0*/+/**+ * The Team struct+ */export interface Team {id: string;name: string;diff --git a/js/app/packages/service-clients/service-auth/generated/schemas/teamInvite.ts b/js/app/packages/service-clients/service-auth/generated/schemas/teamInviteDetails.tssimilarity index 50%rename from js/app/packages/service-clients/service-auth/generated/schemas/teamInvite.tsrename to js/app/packages/service-clients/service-auth/generated/schemas/teamInviteDetails.tsindex e67f1fa928..5e1f04af0a 100644--- a/js/app/packages/service-clients/service-auth/generated/schemas/teamInvite.ts+++ b/js/app/packages/service-clients/service-auth/generated/schemas/teamInviteDetails.ts@@ -6,12 +6,22 @@*/import type { TeamRole } from './teamRole';-export interface TeamInvite {+/**+ * Detailed information about a team invite+ */+export interface TeamInviteDetails {+ /** When the invite was created */created_at: string;+ /** The invited email */email: string;+ /** The invite id */id: string;+ /** The user who sent the invitation */invited_by: string;+ /** When the invite was last sent */last_sent_at: string;+ /** The team id */team_id: string;+ /** The role being invited as */team_role: TeamRole;}diff --git a/js/app/packages/service-clients/service-auth/generated/schemas/teamInviteUpdate.ts b/js/app/packages/service-clients/service-auth/generated/schemas/teamInviteUpdate.tsdeleted file mode 100644index 04cefbe1d4..0000000000--- a/js/app/packages/service-clients/service-auth/generated/schemas/teamInviteUpdate.ts+++ /dev/null@@ -1,19 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * authentication_service- * OpenAPI spec version: 0.1.0- */--import type { TeamInviteUpdateTeamRole } from './teamInviteUpdateTeamRole';-import type { TeamUpdateOperation } from './teamUpdateOperation';--export interface TeamInviteUpdate {- /** The operation to perform-`Update` will update the existing invitation role-`Remove` will remove the invitation */- operation: TeamUpdateOperation;- /** The team invite id to update */- team_invite_id: string;- team_role?: TeamInviteUpdateTeamRole;-}diff --git a/js/app/packages/service-clients/service-auth/generated/schemas/teamInviteUpdateTeamRole.ts b/js/app/packages/service-clients/service-auth/generated/schemas/teamInviteUpdateTeamRole.tsdeleted file mode 100644index 7777a2beff..0000000000--- a/js/app/packages/service-clients/service-auth/generated/schemas/teamInviteUpdateTeamRole.ts+++ /dev/null@@ -1,9 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * authentication_service- * OpenAPI spec version: 0.1.0- */-import type { TeamRole } from './teamRole';--export type TeamInviteUpdateTeamRole = null | TeamRole;diff --git a/js/app/packages/service-clients/service-auth/generated/schemas/teamInvitesResponse.ts b/js/app/packages/service-clients/service-auth/generated/schemas/teamInvitesResponse.tsindex 3ee7be0438..60d61015b6 100644--- a/js/app/packages/service-clients/service-auth/generated/schemas/teamInvitesResponse.ts+++ b/js/app/packages/service-clients/service-auth/generated/schemas/teamInvitesResponse.ts@@ -4,8 +4,12 @@* authentication_service* OpenAPI spec version: 0.1.0*/-import type { TeamInvite } from './teamInvite';+import type { TeamInviteDetails } from './teamInviteDetails';+/**+ * Response containing a list of team invites+ */export interface TeamInvitesResponse {- invites: TeamInvite[];+ /** The invites */+ invites: TeamInviteDetails[];}diff --git a/js/app/packages/service-clients/service-auth/generated/schemas/teamUser.ts b/js/app/packages/service-clients/service-auth/generated/schemas/teamMember.tssimilarity index 54%rename from js/app/packages/service-clients/service-auth/generated/schemas/teamUser.tsrename to js/app/packages/service-clients/service-auth/generated/schemas/teamMember.tsindex c3c941e857..9dc94fa1e2 100644--- a/js/app/packages/service-clients/service-auth/generated/schemas/teamUser.ts+++ b/js/app/packages/service-clients/service-auth/generated/schemas/teamMember.ts@@ -6,8 +6,12 @@*/import type { TeamRole } from './teamRole';-export interface TeamUser {- team_id: string;- team_role: TeamRole;+/**+ * The team member struct+ */+export interface TeamMember {+ /** The role of the team member */+ role: TeamRole;+ /** The user id of the team member */user_id: string;}diff --git a/js/app/packages/service-clients/service-auth/generated/schemas/teamRole.ts b/js/app/packages/service-clients/service-auth/generated/schemas/teamRole.tsindex 944eb2632c..43ac3cd67a 100644--- a/js/app/packages/service-clients/service-auth/generated/schemas/teamRole.ts+++ b/js/app/packages/service-clients/service-auth/generated/schemas/teamRole.ts@@ -12,7 +12,7 @@ export type TeamRole = (typeof TeamRole)[keyof typeof TeamRole];// eslint-disable-next-line @typescript-eslint/no-redeclareexport const TeamRole = {- member: 'member',- admin: 'admin',- owner: 'owner',+ Member: 'Member',+ Admin: 'Admin',+ Owner: 'Owner',} as const;diff --git a/js/app/packages/service-clients/service-auth/generated/schemas/teamUpdateOperation.ts b/js/app/packages/service-clients/service-auth/generated/schemas/teamUpdateOperation.tsdeleted file mode 100644index 4eca679bac..0000000000--- a/js/app/packages/service-clients/service-auth/generated/schemas/teamUpdateOperation.ts+++ /dev/null@@ -1,15 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * authentication_service- * OpenAPI spec version: 0.1.0- */--export type TeamUpdateOperation =- (typeof TeamUpdateOperation)[keyof typeof TeamUpdateOperation];--// eslint-disable-next-line @typescript-eslint/no-redeclare-export const TeamUpdateOperation = {- update: 'update',- remove: 'remove',-} as const;diff --git a/js/app/packages/service-clients/service-auth/generated/schemas/teamUserUpdate.ts b/js/app/packages/service-clients/service-auth/generated/schemas/teamUserUpdate.tsdeleted file mode 100644index 4c31c8de8b..0000000000--- a/js/app/packages/service-clients/service-auth/generated/schemas/teamUserUpdate.ts+++ /dev/null@@ -1,18 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * authentication_service- * OpenAPI spec version: 0.1.0- */-import type { TeamUpdateOperation } from './teamUpdateOperation';-import type { TeamUserUpdateTeamRole } from './teamUserUpdateTeamRole';--export interface TeamUserUpdate {- /** The operation to perform-`Update` will update the existing user role-`Remove` will remove the user */- operation: TeamUpdateOperation;- team_role?: TeamUserUpdateTeamRole;- /** The user id to update or remove */- user_id: string;-}diff --git a/js/app/packages/service-clients/service-auth/generated/schemas/teamUserUpdateTeamRole.ts b/js/app/packages/service-clients/service-auth/generated/schemas/teamUserUpdateTeamRole.tsdeleted file mode 100644index 3cf1325b25..0000000000--- a/js/app/packages/service-clients/service-auth/generated/schemas/teamUserUpdateTeamRole.ts+++ /dev/null@@ -1,9 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * authentication_service- * OpenAPI spec version: 0.1.0- */-import type { TeamRole } from './teamRole';--export type TeamUserUpdateTeamRole = null | TeamRole;diff --git a/js/app/packages/service-clients/service-auth/generated/schemas/teamWithMembers.ts b/js/app/packages/service-clients/service-auth/generated/schemas/teamWithMembers.tsnew file mode 100644index 0000000000..939ab1a427--- /dev/null+++ b/js/app/packages/service-clients/service-auth/generated/schemas/teamWithMembers.ts@@ -0,0 +1,19 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * authentication_service+ * OpenAPI spec version: 0.1.0+ */++import type { Team } from './team';+import type { TeamMember } from './teamMember';++/**+ * A team with its members+ */+export interface TeamWithMembers {+ /** The members of the team */+ members: TeamMember[];+ /** The team */+ team: Team;+}diff --git a/js/app/packages/service-clients/service-auth/generated/schemas/teamWithUsers.ts b/js/app/packages/service-clients/service-auth/generated/schemas/teamWithUsers.tsdeleted file mode 100644index 5dafa5519b..0000000000--- a/js/app/packages/service-clients/service-auth/generated/schemas/teamWithUsers.ts+++ /dev/null@@ -1,13 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * authentication_service- * OpenAPI spec version: 0.1.0- */-import type { Team } from './team';-import type { TeamUser } from './teamUser';--export interface TeamWithUsers {- team: Team;- users: TeamUser[];-}diff --git a/js/app/packages/service-clients/service-auth/openapi.json b/js/app/packages/service-clients/service-auth/openapi.jsonindex 99026b15e1..fbf69dca10 100644--- a/js/app/packages/service-clients/service-auth/openapi.json+++ b/js/app/packages/service-clients/service-auth/openapi.json@@ -1190,7 +1190,7 @@},"/team": {"post": {- "tags": ["team::create_team"],+ "tags": ["teams::inbound::axum_router::create_team"],"summary": "Creates a new team.","operationId": "create_team","requestBody": {@@ -1239,7 +1239,7 @@},"/team/join/{team_invite_id}": {"get": {- "tags": ["team::join_team"],+ "tags": ["teams::inbound::axum_router::join_team"],"summary": "Joins a team by accepting an invite.","operationId": "join_team","parameters": [@@ -1255,14 +1255,7 @@],"responses": {"200": {- "description": "",- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/EmptyResponse"- }- }- }+ "description": ""},"400": {"description": "",@@ -1297,7 +1290,7 @@}},"delete": {- "tags": ["team::reject_invitation"],+ "tags": ["teams::inbound::axum_router::reject_invitation"],"summary": "Rejects an invitation to join a team.","operationId": "reject_invitation","parameters": [@@ -1313,14 +1306,7 @@],"responses": {"200": {- "description": "",- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/EmptyResponse"- }- }- }+ "description": ""},"400": {"description": "",@@ -1357,7 +1343,7 @@},"/team/user": {"get": {- "tags": ["team::get_user_teams"],+ "tags": ["teams::inbound::axum_router::get_user_teams"],"summary": "Gets all teams for the authenticated user.","operationId": "get_user_teams","responses": {@@ -1409,7 +1395,7 @@},"/team/user/invites": {"get": {- "tags": ["team::get_user_invites"],+ "tags": ["teams::inbound::axum_router::get_user_invites"],"summary": "Gets all of a user's invitations.","operationId": "get_user_invites","responses": {@@ -1458,7 +1444,7 @@},"/team/{team_id}": {"get": {- "tags": ["team::get_team"],+ "tags": ["teams::inbound::axum_router::get_team"],"summary": "Gets a team by ID.","operationId": "get_team","parameters": [@@ -1478,7 +1464,7 @@"content": {"application/json": {"schema": {- "$ref": "#/components/schemas/TeamWithUsers"+ "$ref": "#/components/schemas/TeamWithMembers"}}}@@ -1526,7 +1512,7 @@}},"delete": {- "tags": ["team::delete_team"],+ "tags": ["teams::inbound::axum_router::delete_team"],"summary": "Deletes a team.\nThis will update all team members roles and cancel your subscription for the team.\nThis action is **irreversible** and you will not be able to recover the team afterwards.","operationId": "delete_team","parameters": [@@ -1542,14 +1528,7 @@],"responses": {"200": {- "description": "",- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/EmptyResponse"- }- }- }+ "description": ""},"400": {"description": "",@@ -1584,7 +1563,7 @@}},"patch": {- "tags": ["team::patch_team"],+ "tags": ["teams::inbound::axum_router::patch_team"],"summary": "Updates a team.","operationId": "patch_team","parameters": [@@ -1610,14 +1589,7 @@},"responses": {"200": {- "description": "",- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/EmptyResponse"- }- }- }+ "description": ""},"400": {"description": "",@@ -1664,7 +1636,7 @@},"/team/{team_id}/invite": {"post": {- "tags": ["team::invite_to_team"],+ "tags": ["teams::inbound::axum_router::invite_to_team"],"summary": "Invites a user to a team.","operationId": "invite_to_team","parameters": [@@ -1738,9 +1710,81 @@}}},+ "/team/{team_id}/invite/{team_invite_id}": {+ "delete": {+ "tags": ["teams::inbound::axum_router::delete_team_invite"],+ "summary": "Deletes a team invite from a team.",+ "operationId": "delete_team_invite_handler",+ "parameters": [+ {+ "name": "team_id",+ "in": "path",+ "description": "The ID of the team",+ "required": true,+ "schema": {+ "type": "string"+ }+ },+ {+ "name": "team_invite_id",+ "in": "path",+ "description": "The ID of the team invite",+ "required": true,+ "schema": {+ "type": "string"+ }+ }+ ],+ "responses": {+ "200": {+ "description": ""+ },+ "400": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "401": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "404": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "500": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ }+ }+ }+ },"/team/{team_id}/invites": {"get": {- "tags": ["team::get_team_invites"],+ "tags": ["teams::inbound::axum_router::get_team_invites"],"summary": "Gets all invites for a team.","operationId": "get_team_invites","parameters": [@@ -1800,7 +1844,7 @@},"/team/{team_id}/reinvite/{team_invite_id}": {"post": {- "tags": ["team::reinvite_to_team"],+ "tags": ["teams::inbound::axum_router::reinvite_to_team"],"summary": "Regenerates a team invite notifying the user again.","operationId": "reinvite_to_team","parameters": [@@ -1825,14 +1869,7 @@],"responses": {"200": {- "description": "",- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/EmptyResponse"- }- }- }+ "description": ""},"400": {"description": "",@@ -1879,14 +1916,14 @@},"/team/{team_id}/remove/{remove_user_id}": {"delete": {- "tags": ["team::remove_user_from_team"],+ "tags": ["teams::inbound::axum_router::remove_user_from_team"],"summary": "Removes a user from a team.","operationId": "remove_user_from_team","parameters": [{"name": "team_id","in": "path",- "description": "The ID of the team to invite to",+ "description": "The ID of the team","required": true,"schema": {"type": "string"@@ -1904,14 +1941,7 @@],"responses": {"200": {- "description": "",- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/EmptyResponse"- }- }- }+ "description": ""},"400": {"description": "",@@ -1933,16 +1963,6 @@}}},- "429": {- "description": "",- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/ErrorResponse"- }- }- }- },"500": {"description": "","content": {@@ -3184,11 +3204,11 @@},"PatchTeamRequest": {"type": "object",- "description": "The request body to update a team",+ "description": "Request to update a team","properties": {"name": {"type": ["string", "null"],- "description": "The new name of the team"+ "description": "The new name for the team"}}},@@ -3327,6 +3347,7 @@},"Team": {"type": "object",+ "description": "The Team struct","required": ["id", "name", "owner_id"],"properties": {"id": {@@ -3341,8 +3362,9 @@}}},- "TeamInvite": {+ "TeamInviteDetails": {"type": "object",+ "description": "Detailed information about a team invite","required": ["id","email",@@ -3355,131 +3377,87 @@"properties": {"created_at": {"type": "string",- "format": "date-time"+ "format": "date-time",+ "description": "When the invite was created"},"email": {- "type": "string"+ "type": "string",+ "description": "The invited email"},"id": {"type": "string",- "format": "uuid"+ "format": "uuid",+ "description": "The invite id"},"invited_by": {- "type": "string"+ "type": "string",+ "description": "The user who sent the invitation"},"last_sent_at": {"type": "string",- "format": "date-time"+ "format": "date-time",+ "description": "When the invite was last sent"},"team_id": {- "type": "string",- "format": "uuid"- },- "team_role": {- "$ref": "#/components/schemas/TeamRole"- }- }- },- "TeamInviteUpdate": {- "type": "object",- "required": ["team_invite_id", "operation"],- "properties": {- "operation": {- "$ref": "#/components/schemas/TeamUpdateOperation",- "description": "The operation to perform\n`Update` will update the existing invitation role\n`Remove` will remove the invitation"- },- "team_invite_id": {"type": "string","format": "uuid",- "description": "The team invite id to update"+ "description": "The team id"},"team_role": {- "oneOf": [- {- "type": "null"- },- {- "$ref": "#/components/schemas/TeamRole",- "description": "The role to assign to the invited user\nThis is only used for `Update` operation"- }- ]+ "$ref": "#/components/schemas/TeamRole",+ "description": "The role being invited as"}}},"TeamInvitesResponse": {"type": "object",+ "description": "Response containing a list of team invites","required": ["invites"],"properties": {"invites": {"type": "array","items": {- "$ref": "#/components/schemas/TeamInvite"- }- }- }- },- "TeamRole": {- "type": "string",- "description": "Ordered from least to most access top -> bottom",- "enum": ["member", "admin", "owner"]- },- "TeamUpdateOperation": {- "type": "string",- "enum": ["update", "remove"]- },- "TeamUser": {- "type": "object",- "required": ["user_id", "team_id", "team_role"],- "properties": {- "team_id": {- "type": "string",- "format": "uuid"- },- "team_role": {- "$ref": "#/components/schemas/TeamRole"- },- "user_id": {- "type": "string"+ "$ref": "#/components/schemas/TeamInviteDetails"+ },+ "description": "The invites"}}},- "TeamUserUpdate": {+ "TeamMember": {"type": "object",- "required": ["user_id", "operation"],+ "description": "The team member struct",+ "required": ["user_id", "role"],"properties": {- "operation": {- "$ref": "#/components/schemas/TeamUpdateOperation",- "description": "The operation to perform\n`Update` will update the existing user role\n`Remove` will remove the user"- },- "team_role": {- "oneOf": [- {- "type": "null"- },- {- "$ref": "#/components/schemas/TeamRole",- "description": "The new role for the user if the operation is `Update`"- }- ]+ "role": {+ "$ref": "#/components/schemas/TeamRole",+ "description": "The role of the team member"},"user_id": {"type": "string",- "description": "The user id to update or remove"+ "description": "The user id of the team member"}}},- "TeamWithUsers": {+ "TeamRole": {+ "type": "string",+ "description": "Ordered from least to most access top -> bottom",+ "enum": ["Member", "Admin", "Owner"]+ },+ "TeamWithMembers": {"type": "object",- "required": ["team", "users"],+ "description": "A team with its members",+ "required": ["team", "members"],"properties": {- "team": {- "$ref": "#/components/schemas/Team"- },- "users": {+ "members": {"type": "array","items": {- "$ref": "#/components/schemas/TeamUser"- }+ "$ref": "#/components/schemas/TeamMember"+ },+ "description": "The members of the team"+ },+ "team": {+ "$ref": "#/components/schemas/Team",+ "description": "The team"}}},diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lockindex 1aee232215..39847fd649 100644--- a/rust/cloud-storage/Cargo.lock+++ b/rust/cloud-storage/Cargo.lock@@ -9694,15 +9694,24 @@ version = "0.1.0"dependencies = ["anyhow","async-stripe",+ "axum",+ "chrono","macro_db_migrator","macro_user_id","macro_uuid",+ "model-entity",+ "model-error-response",+ "model_notifications",+ "model_user","non_empty",+ "notification","roles_and_permissions",+ "serde","sqlx","thiserror 2.0.17","tokio","tracing",+ "utoipa","uuid",]diff --git a/rust/cloud-storage/authentication_service/src/api/context.rs b/rust/cloud-storage/authentication_service/src/api/context.rsindex 2314a0fbe8..41ff6508bf 100644--- a/rust/cloud-storage/authentication_service/src/api/context.rs+++ b/rust/cloud-storage/authentication_service/src/api/context.rs@@ -44,6 +44,14 @@ pub(crate) type NotificationIngressType = NotificationIngressService<StateMachine,>;+#[expect(dead_code, reason = "used by utoipa in swagger.rs")]+pub(crate) type TeamsServiceType = teams::domain::team_service::TeamServiceImpl<+ teams::outbound::team_repo::TeamRepositoryImpl,+ teams::outbound::customer_repo::CustomerRepositoryImpl,+ UserRolesAndPermissionsServiceImpl<MacroDB, MacroDB>,+ NotificationIngressType,+>;+pub(crate) type GithubLinkServiceType =GithubLinkServiceImpl<PgGithubRepo, GithubOauthImpl, GithubAuthImpl>;@@ -71,6 +79,7 @@ pub(crate) struct ApiContext {TeamRepositoryImpl,CustomerRepositoryImpl,UserRolesAndPermissionsServiceImpl<MacroDB, MacroDB>,+ NotificationIngressType,>,>,pub native_app_service: Arc<NativeAppServiceImpl<DefaultBundleFetcher>>,diff --git a/rust/cloud-storage/authentication_service/src/api/middleware/mod.rs b/rust/cloud-storage/authentication_service/src/api/middleware/mod.rsindex e67b746288..cddc498a47 100644--- a/rust/cloud-storage/authentication_service/src/api/middleware/mod.rs+++ b/rust/cloud-storage/authentication_service/src/api/middleware/mod.rs@@ -1,4 +1,2 @@pub(in crate::api) mod extract_tokens;-pub(in crate::api) mod has_payment_source;pub(in crate::api) mod rate_limit;-pub(in crate::api) mod team_access;diff --git a/rust/cloud-storage/authentication_service/src/api/mod.rs b/rust/cloud-storage/authentication_service/src/api/mod.rsindex 74db7561c4..ba20b68627 100644--- a/rust/cloud-storage/authentication_service/src/api/mod.rs+++ b/rust/cloud-storage/authentication_service/src/api/mod.rs@@ -29,7 +29,6 @@ mod oauth;mod oauth2;mod permissions;mod session;-mod team;mod user;mod webhooks;@@ -95,9 +94,21 @@ fn api_router(state: ApiContext) -> Router<ApiContext> {).nest("/team",- team::router(state.jwt_args.clone()).layer(ServiceBuilder::new().layer(- axum::middleware::from_fn(macro_middleware::tracking::attach_ip_context_handler),- )),+ teams::inbound::axum_router::teams_router(+ teams::inbound::axum_router::TeamRouterState {+ service: state.teams_service.clone(),+ },+ )+ .layer(+ ServiceBuilder::new()+ .layer(axum::middleware::from_fn(+ macro_middleware::tracking::attach_ip_context_handler,+ ))+ .layer(axum::middleware::from_fn_with_state(+ state.jwt_args.clone(),+ macro_middleware::auth::decode_jwt::handler,+ )),+ ),).nest("/jwt", jwt::router(state.jwt_args.clone())).nest("/session", session::router())diff --git a/rust/cloud-storage/authentication_service/src/api/swagger.rs b/rust/cloud-storage/authentication_service/src/api/swagger.rsindex 315aed03d5..5b735c8aaf 100644--- a/rust/cloud-storage/authentication_service/src/api/swagger.rs+++ b/rust/cloud-storage/authentication_service/src/api/swagger.rs@@ -1,7 +1,11 @@use model::authentication::login::request::{AppleLoginRequest, PasswordRequest};-use models_team::{- PatchTeamRequest, Team, TeamInvite, TeamInviteUpdate, TeamRole, TeamUpdateOperation, TeamUser,- TeamUserUpdate, TeamWithUsers,+use teams::domain::model::{+ PatchTeamRequest, Team, TeamInviteDetails, TeamMember, TeamRole, TeamWithMembers,+};+use teams::inbound::axum_router::get_team_invites::TeamInvitesResponse as TeamTeamInvitesResponse;+use teams::inbound::axum_router::get_user_invites::TeamInvitesResponse as UserTeamInvitesResponse;+use teams::inbound::axum_router::{+ create_team::CreateTeamRequest, invite_to_team::InviteToTeamRequest,};use user_quota::UserQuota;use utoipa::OpenApi;@@ -12,8 +16,6 @@ use crate::api::jwt::macro_api_token::MacroApiTokenResponse;use crate::api::link::create_in_progress_link::CreateInProgressLinkResponse;use crate::api::link::github::InitGithubLinkResponse;use crate::api::merge::create_merge_request::CreateAccountMergeRequest;-use crate::api::team::create_team::CreateTeamRequest;-use crate::api::team::get_team_invites::TeamInvitesResponse;use crate::api::user::create_user::CreateUserRequest;use crate::api::user::get_legacy_user_permissions::GetLegacyUserPermissionsResponse;use crate::api::user::get_user_link_exists::UserLinkResponse;@@ -27,7 +29,7 @@ use crate::api::user::stripe::{CreateCheckoutSessionRequest, CreatePortalSessionRequest, StripeSessionResponse,};use crate::api::{- email, health, jwt, link, login, logout, merge, oauth, oauth2, permissions, session, team, user,+ email, health, jwt, link, login, logout, merge, oauth, oauth2, permissions, session, user,};use model::authentication::login::response::SsoRequiredResponse;use model::authentication::{@@ -106,18 +108,19 @@ use model::user::{email::verify_email_link::handler,/// /team- team::create_team::handler,- team::delete_team::handler,- team::join_team::handler,- team::get_team::handler,- team::invite_to_team::handler,- team::get_team_invites::handler,- team::patch_team::handler,- team::reject_invitation::handler,- team::get_user_invites::handler,- team::reinvite_to_team::handler,- team::get_user_teams::handler,- team::remove_user_from_team::handler,+ teams::inbound::axum_router::create_team::handler::<crate::api::context::TeamsServiceType>,+ teams::inbound::axum_router::delete_team::handler::<crate::api::context::TeamsServiceType>,+ teams::inbound::axum_router::join_team::handler::<crate::api::context::TeamsServiceType>,+ teams::inbound::axum_router::get_team::handler::<crate::api::context::TeamsServiceType>,+ teams::inbound::axum_router::invite_to_team::handler::<crate::api::context::TeamsServiceType>,+ teams::inbound::axum_router::get_team_invites::handler::<crate::api::context::TeamsServiceType>,+ teams::inbound::axum_router::patch_team::handler::<crate::api::context::TeamsServiceType>,+ teams::inbound::axum_router::reject_invitation::handler::<crate::api::context::TeamsServiceType>,+ teams::inbound::axum_router::get_user_invites::handler::<crate::api::context::TeamsServiceType>,+ teams::inbound::axum_router::reinvite_to_team::handler::<crate::api::context::TeamsServiceType>,+ teams::inbound::axum_router::get_user_teams::handler::<crate::api::context::TeamsServiceType>,+ teams::inbound::axum_router::remove_user_from_team::handler::<crate::api::context::TeamsServiceType>,+ teams::inbound::axum_router::delete_team_invite::handler::<crate::api::context::TeamsServiceType>,/// /mergemerge::create_merge_request::handler,@@ -165,17 +168,15 @@ use model::user::{// TeamsTeamRole,- TeamInvite,- TeamUser,+ TeamMember,Team,+ TeamWithMembers,+ TeamInviteDetails,CreateTeamRequest,- TeamWithUsers,- TeamInvitesResponse,- // patch team- TeamUpdateOperation,- TeamUserUpdate,- TeamInviteUpdate,+ InviteToTeamRequest,PatchTeamRequest,+ TeamTeamInvitesResponse,+ UserTeamInvitesResponse,// MergeCreateAccountMergeRequest,diff --git a/rust/cloud-storage/authentication_service/src/api/team/create_team.rs b/rust/cloud-storage/authentication_service/src/api/team/create_team.rsindex bcd34221b0..82908a0e7a 100644--- a/rust/cloud-storage/authentication_service/src/api/team/create_team.rs+++ b/rust/cloud-storage/authentication_service/src/api/team/create_team.rs@@ -4,7 +4,9 @@ use axum::{http::StatusCode,response::{IntoResponse, Response},};+use macro_user_id::user_id::MacroUserIdStr;use models_team::Team;+use teams::domain::team_repo::TeamService;use crate::api::context::ApiContext;@@ -37,19 +39,29 @@ pub async fn handler() -> Result<Response, Response> {tracing::info!("create_team");- let team =- macro_db_client::team::create::create_team(&ctx.db, &user_context.user_id, &req.name)- .await- .map_err(|e| {- tracing::error!(error=?e, "failed to create team");- (- StatusCode::INTERNAL_SERVER_ERROR,- Json(ErrorResponse {- message: "unable to create team",- }),- )- .into_response()- })?;+ let macro_user_id = MacroUserIdStr::parse_from_str(&user_context.user_id).map_err(|_| {+ (+ StatusCode::BAD_REQUEST,+ Json(ErrorResponse {+ message: "invalid macro user id",+ }),+ )+ .into_response()+ })?;++ let team = ctx+ .teams_service+ .create_team(¯o_user_id, &req.name)+ .await+ .map_err(|_| {+ (+ StatusCode::INTERNAL_SERVER_ERROR,+ Json(ErrorResponse {+ message: "unable to create team",+ }),+ )+ .into_response()+ })?;Ok((StatusCode::OK, Json(team)).into_response())}diff --git a/rust/cloud-storage/authentication_service/src/main.rs b/rust/cloud-storage/authentication_service/src/main.rsindex d782c3b474..4342c0a7d9 100644--- a/rust/cloud-storage/authentication_service/src/main.rs+++ b/rust/cloud-storage/authentication_service/src/main.rs@@ -223,10 +223,13 @@ async fn main() -> anyhow::Result<()> {let teams_repo_impl = TeamRepositoryImpl::new(db.clone());let customer_repo_impl = CustomerRepositoryImpl::new(stripe_client.clone(), &stripe_price_id);+ let notification_ingress_service = Arc::new(notification_ingress_service);+let teams_service_impl = TeamServiceImpl::new(teams_repo_impl,customer_repo_impl,user_roles_and_permissions_service.clone(),+ notification_ingress_service.clone(),);let github_link_service_impl = GithubLinkServiceImpl::new(@@ -249,7 +252,7 @@ async fn main() -> anyhow::Result<()> {stripe_client: Arc::new(stripe_client),document_storage_service_client: Arc::new(document_storage_service_client),ses_client: Arc::new(ses_client),- notification_ingress_service: Arc::new(notification_ingress_service),+ notification_ingress_service: notification_ingress_service.clone(),sqs_client: Arc::new(sqs_client),environment: config.environment,jwt_args,diff --git a/rust/cloud-storage/frecency/src/domain/models.rs b/rust/cloud-storage/frecency/src/domain/models.rsindex 57a1fa8fce..bf62a23e67 100644--- a/rust/cloud-storage/frecency/src/domain/models.rs+++ b/rust/cloud-storage/frecency/src/domain/models.rs@@ -106,6 +106,7 @@ pub struct AggregateId<'a> {}impl<'a> AggregateId<'a> {+ #[allow(dead_code)]pub(crate) fn from_event_record<T>(r: &'a EventRecordWithId<'a, T>) -> Result<Self, ParseErr> {Ok(AggregateId {user_id: MacroUserIdStr::parse_from_str(r.event_record.event.entity.user_id.as_ref())?,@@ -363,6 +364,7 @@ pub struct FrecencyPageResponse {}impl FrecencyPageResponse {+ #[allow(dead_code)]pub(crate) fn new(iter: impl IntoIterator<Item = AggregateFrecency>) -> Self {let results = iter.into_iter()diff --git a/rust/cloud-storage/teams/.sqlx/query-20968294bc4a969511f02809aaa0267da032ee0de31f13d0ed1929550bd8adda.json b/rust/cloud-storage/teams/.sqlx/query-20968294bc4a969511f02809aaa0267da032ee0de31f13d0ed1929550bd8adda.jsonnew file mode 100644index 0000000000..7e6ffff347--- /dev/null+++ b/rust/cloud-storage/teams/.sqlx/query-20968294bc4a969511f02809aaa0267da032ee0de31f13d0ed1929550bd8adda.json@@ -0,0 +1,15 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE team\n SET name = $1\n WHERE id = $2\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text",+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "20968294bc4a969511f02809aaa0267da032ee0de31f13d0ed1929550bd8adda"+}diff --git a/rust/cloud-storage/teams/.sqlx/query-4656631949bab512d00e10664be31128b89c8047812362331ded6b6e0a12e1ac.json b/rust/cloud-storage/teams/.sqlx/query-4656631949bab512d00e10664be31128b89c8047812362331ded6b6e0a12e1ac.jsonnew file mode 100644index 0000000000..f621865b2b--- /dev/null+++ b/rust/cloud-storage/teams/.sqlx/query-4656631949bab512d00e10664be31128b89c8047812362331ded6b6e0a12e1ac.json@@ -0,0 +1,69 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT\n id,\n email,\n team_id,\n team_role as \"team_role!: TeamRole\",\n invited_by,\n created_at as \"created_at!: chrono::DateTime<chrono::Utc>\",\n last_sent_at as \"last_sent_at!: chrono::DateTime<chrono::Utc>\"\n FROM team_invite\n WHERE email = $1\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "email",+ "type_info": "Text"+ },+ {+ "ordinal": 2,+ "name": "team_id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 3,+ "name": "team_role!: TeamRole",+ "type_info": {+ "Custom": {+ "name": "team_role",+ "kind": {+ "Enum": [+ "member",+ "admin",+ "owner"+ ]+ }+ }+ }+ },+ {+ "ordinal": 4,+ "name": "invited_by",+ "type_info": "Text"+ },+ {+ "ordinal": 5,+ "name": "created_at!: chrono::DateTime<chrono::Utc>",+ "type_info": "Timestamp"+ },+ {+ "ordinal": 6,+ "name": "last_sent_at!: chrono::DateTime<chrono::Utc>",+ "type_info": "Timestamp"+ }+ ],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": [+ false,+ false,+ false,+ false,+ false,+ false,+ false+ ]+ },+ "hash": "4656631949bab512d00e10664be31128b89c8047812362331ded6b6e0a12e1ac"+}diff --git a/rust/cloud-storage/teams/.sqlx/query-4c4866e44650e9d0ebc04dfe61010f88b42d23348339fad30418bc2666c7947f.json b/rust/cloud-storage/teams/.sqlx/query-4c4866e44650e9d0ebc04dfe61010f88b42d23348339fad30418bc2666c7947f.jsonnew file mode 100644index 0000000000..ccb0629e96--- /dev/null+++ b/rust/cloud-storage/teams/.sqlx/query-4c4866e44650e9d0ebc04dfe61010f88b42d23348339fad30418bc2666c7947f.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE team_invite\n SET last_sent_at = NOW()\n WHERE id = $1\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "4c4866e44650e9d0ebc04dfe61010f88b42d23348339fad30418bc2666c7947f"+}diff --git a/rust/cloud-storage/teams/.sqlx/query-5b5a3e0954cb8130b507b73e771624fa3af4166de80e72dbcae524f63af9ae2e.json b/rust/cloud-storage/teams/.sqlx/query-5b5a3e0954cb8130b507b73e771624fa3af4166de80e72dbcae524f63af9ae2e.jsonnew file mode 100644index 0000000000..18f74966db--- /dev/null+++ b/rust/cloud-storage/teams/.sqlx/query-5b5a3e0954cb8130b507b73e771624fa3af4166de80e72dbcae524f63af9ae2e.json@@ -0,0 +1,69 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT\n id,\n email,\n team_id,\n team_role as \"team_role!: TeamRole\",\n invited_by,\n created_at as \"created_at!: chrono::DateTime<chrono::Utc>\",\n last_sent_at as \"last_sent_at!: chrono::DateTime<chrono::Utc>\"\n FROM team_invite\n WHERE team_id = $1\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "email",+ "type_info": "Text"+ },+ {+ "ordinal": 2,+ "name": "team_id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 3,+ "name": "team_role!: TeamRole",+ "type_info": {+ "Custom": {+ "name": "team_role",+ "kind": {+ "Enum": [+ "member",+ "admin",+ "owner"+ ]+ }+ }+ }+ },+ {+ "ordinal": 4,+ "name": "invited_by",+ "type_info": "Text"+ },+ {+ "ordinal": 5,+ "name": "created_at!: chrono::DateTime<chrono::Utc>",+ "type_info": "Timestamp"+ },+ {+ "ordinal": 6,+ "name": "last_sent_at!: chrono::DateTime<chrono::Utc>",+ "type_info": "Timestamp"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ false,+ false,+ false,+ false,+ false,+ false,+ false+ ]+ },+ "hash": "5b5a3e0954cb8130b507b73e771624fa3af4166de80e72dbcae524f63af9ae2e"+}diff --git a/rust/cloud-storage/teams/.sqlx/query-67cab3f29fef008aed42a34ebc208cae3c299ce7ea4d4e3b19100546ce6d7a1b.json b/rust/cloud-storage/teams/.sqlx/query-67cab3f29fef008aed42a34ebc208cae3c299ce7ea4d4e3b19100546ce6d7a1b.jsonnew file mode 100644index 0000000000..dcc26c7a76--- /dev/null+++ b/rust/cloud-storage/teams/.sqlx/query-67cab3f29fef008aed42a34ebc208cae3c299ce7ea4d4e3b19100546ce6d7a1b.json@@ -0,0 +1,69 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT\n id,\n email,\n team_id,\n team_role as \"team_role!: TeamRole\",\n invited_by,\n created_at as \"created_at!: chrono::DateTime<chrono::Utc>\",\n last_sent_at as \"last_sent_at!: chrono::DateTime<chrono::Utc>\"\n FROM team_invite\n WHERE id = $1\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "email",+ "type_info": "Text"+ },+ {+ "ordinal": 2,+ "name": "team_id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 3,+ "name": "team_role!: TeamRole",+ "type_info": {+ "Custom": {+ "name": "team_role",+ "kind": {+ "Enum": [+ "member",+ "admin",+ "owner"+ ]+ }+ }+ }+ },+ {+ "ordinal": 4,+ "name": "invited_by",+ "type_info": "Text"+ },+ {+ "ordinal": 5,+ "name": "created_at!: chrono::DateTime<chrono::Utc>",+ "type_info": "Timestamp"+ },+ {+ "ordinal": 6,+ "name": "last_sent_at!: chrono::DateTime<chrono::Utc>",+ "type_info": "Timestamp"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ false,+ false,+ false,+ false,+ false,+ false,+ false+ ]+ },+ "hash": "67cab3f29fef008aed42a34ebc208cae3c299ce7ea4d4e3b19100546ce6d7a1b"+}diff --git a/rust/cloud-storage/teams/.sqlx/query-a5aedcffb360128c84269103ae40fa87aa2f14601611e60570808bd0946f5baa.json b/rust/cloud-storage/teams/.sqlx/query-a5aedcffb360128c84269103ae40fa87aa2f14601611e60570808bd0946f5baa.jsonnew file mode 100644index 0000000000..db46df8eb6--- /dev/null+++ b/rust/cloud-storage/teams/.sqlx/query-a5aedcffb360128c84269103ae40fa87aa2f14601611e60570808bd0946f5baa.json@@ -0,0 +1,34 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT id, name, owner_id\n FROM team\n WHERE id = $1\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "name",+ "type_info": "Text"+ },+ {+ "ordinal": 2,+ "name": "owner_id",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ false,+ false,+ false+ ]+ },+ "hash": "a5aedcffb360128c84269103ae40fa87aa2f14601611e60570808bd0946f5baa"+}diff --git a/rust/cloud-storage/teams/.sqlx/query-b6b4b9bdcbfcf72d970393d915c68c6230d9cf7f96e816a3f98a01b62e4a0a6c.json b/rust/cloud-storage/teams/.sqlx/query-b6b4b9bdcbfcf72d970393d915c68c6230d9cf7f96e816a3f98a01b62e4a0a6c.jsonnew file mode 100644index 0000000000..43b1c4da65--- /dev/null+++ b/rust/cloud-storage/teams/.sqlx/query-b6b4b9bdcbfcf72d970393d915c68c6230d9cf7f96e816a3f98a01b62e4a0a6c.json@@ -0,0 +1,34 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT team_role as \"team_role!: TeamRole\"\n FROM team_user\n WHERE team_id = $1 AND user_id = $2\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "team_role!: TeamRole",+ "type_info": {+ "Custom": {+ "name": "team_role",+ "kind": {+ "Enum": [+ "member",+ "admin",+ "owner"+ ]+ }+ }+ }+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "Text"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "b6b4b9bdcbfcf72d970393d915c68c6230d9cf7f96e816a3f98a01b62e4a0a6c"+}diff --git a/rust/cloud-storage/teams/.sqlx/query-bcb0dfd2aa420f102d8dd3484f65defd6cbcf8e801c4c4d43d5e0d1338e1ab04.json b/rust/cloud-storage/teams/.sqlx/query-bcb0dfd2aa420f102d8dd3484f65defd6cbcf8e801c4c4d43d5e0d1338e1ab04.jsonnew file mode 100644index 0000000000..c645aa3823--- /dev/null+++ b/rust/cloud-storage/teams/.sqlx/query-bcb0dfd2aa420f102d8dd3484f65defd6cbcf8e801c4c4d43d5e0d1338e1ab04.json@@ -0,0 +1,39 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT user_id,\n team_role as \"team_role!: TeamRole\"\n FROM team_user\n WHERE team_id = $1\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "user_id",+ "type_info": "Text"+ },+ {+ "ordinal": 1,+ "name": "team_role!: TeamRole",+ "type_info": {+ "Custom": {+ "name": "team_role",+ "kind": {+ "Enum": [+ "member",+ "admin",+ "owner"+ ]+ }+ }+ }+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ false,+ false+ ]+ },+ "hash": "bcb0dfd2aa420f102d8dd3484f65defd6cbcf8e801c4c4d43d5e0d1338e1ab04"+}diff --git a/rust/cloud-storage/teams/.sqlx/query-c50d0f6d2aa615856bba86ac8460b637539f28a5e8644f0467eca7efdb06e387.json b/rust/cloud-storage/teams/.sqlx/query-c50d0f6d2aa615856bba86ac8460b637539f28a5e8644f0467eca7efdb06e387.jsonnew file mode 100644index 0000000000..e8d1d08574--- /dev/null+++ b/rust/cloud-storage/teams/.sqlx/query-c50d0f6d2aa615856bba86ac8460b637539f28a5e8644f0467eca7efdb06e387.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT name\n FROM team\n WHERE id = $1\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "name",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "c50d0f6d2aa615856bba86ac8460b637539f28a5e8644f0467eca7efdb06e387"+}diff --git a/rust/cloud-storage/teams/.sqlx/query-eb60dffb5b5eee74b267402d11b05e3c7edb39484f34fb204523df6cd46fa3fe.json b/rust/cloud-storage/teams/.sqlx/query-eb60dffb5b5eee74b267402d11b05e3c7edb39484f34fb204523df6cd46fa3fe.jsonnew file mode 100644index 0000000000..9ebaeb29e0--- /dev/null+++ b/rust/cloud-storage/teams/.sqlx/query-eb60dffb5b5eee74b267402d11b05e3c7edb39484f34fb204523df6cd46fa3fe.json@@ -0,0 +1,34 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT t.id, t.name, t.owner_id\n FROM team t\n JOIN team_user tu ON t.id = tu.team_id\n WHERE tu.user_id = $1\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "name",+ "type_info": "Text"+ },+ {+ "ordinal": 2,+ "name": "owner_id",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": [+ false,+ false,+ false+ ]+ },+ "hash": "eb60dffb5b5eee74b267402d11b05e3c7edb39484f34fb204523df6cd46fa3fe"+}diff --git a/rust/cloud-storage/teams/Cargo.toml b/rust/cloud-storage/teams/Cargo.tomlindex c2a25c4eb3..d3a8f5d2a4 100644--- a/rust/cloud-storage/teams/Cargo.toml+++ b/rust/cloud-storage/teams/Cargo.toml@@ -4,21 +4,52 @@ name = "teams"publish = falseversion = "0.1.0"+[features]+axum = ["dep:axum", "dep:model-error-response", "dep:model_user", "dep:utoipa"]+default = ["axum", "inbound", "outbound", "ports"]+inbound = ["axum", "ports"]+outbound = ["dep:sqlx", "ports"]+ports = [+ "dep:model-entity",+ "dep:model_notifications",+ "dep:notification",+ "dep:tokio",+]+[dependencies]+# Coreanyhow = { workspace = true }async-stripe = { workspace = true, default-features = false, features = ["billing","checkout","runtime-tokio-hyper",] }+chrono = { workspace = true }macro_user_id = { path = "../macro_user_id" }macro_uuid = { path = "../macro_uuid" }non_empty = { path = "../non_empty" }-sqlx = { workspace = true }+roles_and_permissions = { path = "../roles_and_permissions" }+serde = { workspace = true }thiserror = { workspace = true }tracing = { workspace = true }uuid = { workspace = true }-roles_and_permissions = { path = "../roles_and_permissions" }++# Async runtime (for ports)+tokio = { workspace = true, optional = true }++# Axum dependencies (for inbound)+axum = { workspace = true, optional = true }+model-error-response = { path = "../model-error-response", optional = true }+model_user = { path = "../model_user", optional = true, features = ["axum"] }+utoipa = { workspace = true, optional = true }++# Notification dependencies (for ports)+model-entity = { path = "../model-entity", optional = true }+model_notifications = { path = "../model_notifications", optional = true }+notification = { path = "../notification", optional = true, default-features = false }++# Outbound dependencies+sqlx = { workspace = true, optional = true }[dev-dependencies]macro_db_migrator = { path = "../macro_db_migrator" }diff --git a/rust/cloud-storage/teams/src/domain/model.rs b/rust/cloud-storage/teams/src/domain/model.rsindex 40579fe490..ffd468dff2 100644--- a/rust/cloud-storage/teams/src/domain/model.rs+++ b/rust/cloud-storage/teams/src/domain/model.rs@@ -2,10 +2,14 @@use std::collections::HashMap;+use chrono::{DateTime, Utc};use macro_user_id::{email::Email, lowercased::Lowercase, user_id::MacroUserIdStr};use roles_and_permissions::domain::model::UserRolesAndPermissionsError;-#[derive(Eq, PartialEq, Debug, Clone, PartialOrd, sqlx::Type, Copy, std::cmp::Ord)]+#[derive(+ Eq, PartialEq, Debug, Clone, PartialOrd, sqlx::Type, Copy, std::cmp::Ord, serde::Serialize,+)]+#[cfg_attr(feature = "axum", derive(utoipa::ToSchema))]#[sqlx(type_name = "\"team_role\"", rename_all = "lowercase")]/// Ordered from least to most access top -> bottompub enum TeamRole {@@ -28,16 +32,57 @@ impl std::fmt::Display for TeamRole {}/// The team member struct-#[derive(Debug, Clone)]+#[derive(Debug, Clone, serde::Serialize)]+#[cfg_attr(feature = "axum", derive(utoipa::ToSchema))]pub struct TeamMember<'a> {/// The user id of the team member+ #[cfg_attr(feature = "axum", schema(value_type = String))]pub user_id: MacroUserIdStr<'a>,/// The role of the team memberpub role: TeamRole,}+/// A team with its members+#[derive(Debug, Clone, serde::Serialize)]+#[cfg_attr(feature = "axum", derive(utoipa::ToSchema))]+pub struct TeamWithMembers {+ /// The team+ pub team: Team,+ /// The members of the team+ pub members: Vec<TeamMember<'static>>,+}++/// Detailed information about a team invite+#[derive(Debug, Clone, serde::Serialize)]+#[cfg_attr(feature = "axum", derive(utoipa::ToSchema))]+pub struct TeamInviteDetails {+ /// The invite id+ pub id: uuid::Uuid,+ /// The invited email+ pub email: String,+ /// The team id+ pub team_id: uuid::Uuid,+ /// The role being invited as+ pub team_role: TeamRole,+ /// The user who sent the invitation+ pub invited_by: String,+ /// When the invite was created+ pub created_at: DateTime<Utc>,+ /// When the invite was last sent+ pub last_sent_at: DateTime<Utc>,+}++/// Request to update a team+#[derive(Debug, serde::Deserialize)]+#[cfg_attr(feature = "axum", derive(utoipa::ToSchema))]+pub struct PatchTeamRequest {+ /// The new name for the team+ pub name: Option<String>,+}+/// The Team struct-#[derive(Debug, Clone)]+#[derive(Debug, Clone, serde::Serialize)]+#[cfg_attr(feature = "axum", derive(utoipa::ToSchema))]pub struct Team {pub(crate) id: uuid::Uuid,pub(crate) name: String,@@ -266,6 +311,20 @@ pub enum JoinTeamError {AddRolesToUserError(#[from] UserRolesAndPermissionsError),}+/// Errors for reinviting a user to a team+#[derive(Debug, thiserror::Error)]+pub enum ReinviteError {+ /// The invite was sent too recently+ #[error("Too many requests")]+ TooManyRequests,+ /// The invite does not exist+ #[error("Invite not found")]+ InviteNotFound,+ /// Storage layer error+ #[error("Storage layer error {0}")]+ StorageLayerError(#[from] anyhow::Error),+}+/// Errors for revoking permissions for team members#[derive(Debug, thiserror::Error)]pub enum RevokePermissionsForTeamMembersError {diff --git a/rust/cloud-storage/teams/src/domain/team_repo.rs b/rust/cloud-storage/teams/src/domain/team_repo.rsindex b8743c6108..8f88192825 100644--- a/rust/cloud-storage/teams/src/domain/team_repo.rs+++ b/rust/cloud-storage/teams/src/domain/team_repo.rs@@ -3,9 +3,10 @@use macro_user_id::{email::Email, lowercased::Lowercase, user_id::MacroUserIdStr};use crate::domain::model::{- CreateTeamError, DeleteTeamError, InviteUsersToTeamError, JoinTeamError, RemoveTeamInviteError,- RemoveUserFromTeamError, RevokePermissionsForTeamMembersError, Team, TeamError, TeamInvite,- TeamMember,+ CreateTeamError, DeleteTeamError, InviteUsersToTeamError, JoinTeamError, PatchTeamRequest,+ ReinviteError, RemoveTeamInviteError, RemoveUserFromTeamError,+ RevokePermissionsForTeamMembersError, Team, TeamError, TeamInvite, TeamInviteDetails,+ TeamMember, TeamRole, TeamWithMembers,};/// The TeamRepository defines a set of actions to perform on teams data@@ -106,6 +107,62 @@ pub trait TeamRepository: Clone + Send + Sync + 'static {ignore_team_ids: non_empty::NonEmpty<&[uuid::Uuid]>,users: non_empty::NonEmpty<&[MacroUserIdStr<'_>]>,) -> impl Future<Output = Result<Vec<MacroUserIdStr<'_>>, TeamError>> + Send;++ /// Gets a team by id with all its members+ fn get_team_by_id(+ &self,+ team_id: &uuid::Uuid,+ ) -> impl Future<Output = Result<TeamWithMembers, TeamError>> + Send;++ /// Gets all teams for a user+ fn get_user_teams(+ &self,+ user_id: &MacroUserIdStr<'_>,+ ) -> impl Future<Output = Result<Vec<Team>, TeamError>> + Send;++ /// Gets all team invites for a user (by email)+ fn get_user_team_invites(+ &self,+ user_id: &MacroUserIdStr<'_>,+ ) -> impl Future<Output = Result<Vec<TeamInviteDetails>, TeamError>> + Send;++ /// Gets all invites for a team+ fn get_team_invites(+ &self,+ team_id: &uuid::Uuid,+ ) -> impl Future<Output = Result<Vec<TeamInviteDetails>, TeamError>> + Send;++ /// Gets the name of a team+ fn get_team_name(+ &self,+ team_id: &uuid::Uuid,+ ) -> impl Future<Output = Result<String, TeamError>> + Send;++ /// Updates a team+ fn patch_team(+ &self,+ team_id: &uuid::Uuid,+ req: &PatchTeamRequest,+ ) -> impl Future<Output = Result<(), TeamError>> + Send;++ /// Gets detailed info about a team invite by id+ fn get_team_invite_details_by_id(+ &self,+ invite_id: &uuid::Uuid,+ ) -> impl Future<Output = Result<TeamInviteDetails, TeamError>> + Send;++ /// Updates the last_sent_at field of a team invite+ fn update_team_invite_last_sent_at(+ &self,+ invite_id: &uuid::Uuid,+ ) -> impl Future<Output = Result<(), TeamError>> + Send;++ /// Gets the role of a user in a team+ fn get_team_role(+ &self,+ team_id: &uuid::Uuid,+ user_id: &MacroUserIdStr<'_>,+ ) -> impl Future<Output = Result<Option<TeamRole>, TeamError>> + Send;}/// The TeamService defines a set of actions to perform on the teams@@ -167,4 +224,49 @@ pub trait TeamService: Clone + Send + Sync + 'static {&self,team_id: &uuid::Uuid,) -> impl Future<Output = Result<(), RevokePermissionsForTeamMembersError>> + Send;++ /// Gets a team by id with all its members+ fn get_team(+ &self,+ team_id: &uuid::Uuid,+ ) -> impl Future<Output = Result<TeamWithMembers, TeamError>> + Send;++ /// Gets all teams for a user+ fn get_user_teams(+ &self,+ user_id: &MacroUserIdStr<'_>,+ ) -> impl Future<Output = Result<Vec<Team>, TeamError>> + Send;++ /// Gets all team invites for the authenticated user+ fn get_user_invites(+ &self,+ user_id: &MacroUserIdStr<'_>,+ ) -> impl Future<Output = Result<Vec<TeamInviteDetails>, TeamError>> + Send;++ /// Gets all invites for a team+ fn get_team_invites(+ &self,+ team_id: &uuid::Uuid,+ ) -> impl Future<Output = Result<Vec<TeamInviteDetails>, TeamError>> + Send;++ /// Updates a team+ fn patch_team(+ &self,+ team_id: &uuid::Uuid,+ req: &PatchTeamRequest,+ ) -> impl Future<Output = Result<(), TeamError>> + Send;++ /// Reinvites a user to a team (rate-limited to 5 min)+ fn reinvite_to_team(+ &self,+ team_invite_id: &uuid::Uuid,+ invited_by: &MacroUserIdStr<'_>,+ ) -> impl Future<Output = Result<TeamInviteDetails, ReinviteError>> + Send;++ /// Gets the role of a user in a team+ fn get_team_role(+ &self,+ team_id: &uuid::Uuid,+ user_id: &MacroUserIdStr<'_>,+ ) -> impl Future<Output = Result<Option<TeamRole>, TeamError>> + Send;}diff --git a/rust/cloud-storage/teams/src/domain/team_service.rs b/rust/cloud-storage/teams/src/domain/team_service.rsindex 584c53fdab..969d99cadb 100644--- a/rust/cloud-storage/teams/src/domain/team_service.rs+++ b/rust/cloud-storage/teams/src/domain/team_service.rs@@ -1,27 +1,38 @@//! Contains the service logic for teams-use std::{collections::HashSet, str::FromStr};+use std::{collections::HashSet, str::FromStr, sync::Arc};-use macro_user_id::{email::Email, lowercased::Lowercase, user_id::MacroUserIdStr};+use macro_user_id::{+ cowlike::CowLike, email::Email, lowercased::Lowercase, user_id::MacroUserIdStr,+};use roles_and_permissions::domain::{model::RoleId, port::UserRolesAndPermissionsService};+#[cfg(feature = "ports")]+use model_entity::EntityType;+#[cfg(feature = "ports")]+use model_notifications::InviteToTeamMetadata;+#[cfg(feature = "ports")]+use notification::domain::{models::SendNotificationRequestBuilder, service::NotificationIngress};+use crate::domain::{customer_repo::CustomerRepository,model::{CreateSubscriptionArgs, CreateTeamError, CustomerError, DeleteTeamError,- InviteUsersToTeamError, JoinTeamError, RemoveTeamInviteError, RemoveUserFromTeamError,- RevokePermissionsForTeamMembersError, Team, TeamError, TeamInvite, TeamMember,+ InviteUsersToTeamError, JoinTeamError, PatchTeamRequest, ReinviteError,+ RemoveTeamInviteError, RemoveUserFromTeamError, RevokePermissionsForTeamMembersError, Team,+ TeamError, TeamInvite, TeamInviteDetails, TeamMember, TeamRole, TeamWithMembers,},team_repo::{TeamRepository, TeamService},};/// Implementation of the TeamService using a TeamRepository-#[derive(Debug, Clone)]-pub struct TeamServiceImpl<TR, CR, URPS>+#[derive(Debug)]+pub struct TeamServiceImpl<TR, CR, URPS, NI>whereTR: TeamRepository,CR: CustomerRepository,URPS: UserRolesAndPermissionsService,+ NI: NotificationIngress,{/// The underlying team repositoryteam_repository: TR,@@ -29,33 +40,101 @@ wherecustomer_repository: CR,/// The underlying user roles and permissions serviceuser_roles_and_permissions_service: URPS,+ /// The notification ingress service+ notification_ingress: Arc<NI>,+}++impl<TR, CR, URPS, NI> Clone for TeamServiceImpl<TR, CR, URPS, NI>+where+ TR: TeamRepository,+ CR: CustomerRepository,+ URPS: UserRolesAndPermissionsService,+ NI: NotificationIngress,+{+ fn clone(&self) -> Self {+ Self {+ team_repository: self.team_repository.clone(),+ customer_repository: self.customer_repository.clone(),+ user_roles_and_permissions_service: self.user_roles_and_permissions_service.clone(),+ notification_ingress: self.notification_ingress.clone(),+ }+ }}-impl<TR, CR, URPS> TeamServiceImpl<TR, CR, URPS>+impl<TR, CR, URPS, NI> TeamServiceImpl<TR, CR, URPS, NI>whereTR: TeamRepository,CR: CustomerRepository,URPS: UserRolesAndPermissionsService,+ NI: NotificationIngress,{/// Creates a new TeamServicepub fn new(team_repository: TR,customer_repository: CR,user_roles_and_permissions_service: URPS,+ notification_ingress: Arc<NI>,) -> Self {Self {team_repository,customer_repository,user_roles_and_permissions_service,+ notification_ingress,}}}-impl<TR, CR, URPS> TeamService for TeamServiceImpl<TR, CR, URPS>+impl<TR, CR, URPS, NI> TeamServiceImpl<TR, CR, URPS, NI>whereTR: TeamRepository,CR: CustomerRepository,URPS: UserRolesAndPermissionsService,+ NI: NotificationIngress,+{+ /// Sends an invite notification for a team invite+ async fn send_invite_notification(+ &self,+ team_id: &uuid::Uuid,+ team_invite_id: &uuid::Uuid,+ email: &str,+ team_name: &str,+ invited_by: &MacroUserIdStr<'static>,+ ) -> anyhow::Result<()> {+ let notification = InviteToTeamMetadata {+ invited_by: invited_by.clone(),+ team_name: team_name.to_string(),+ team_id: team_id.to_string(),+ role: None,+ };++ let recipient = MacroUserIdStr::try_from_email(email)+ .map_err(|e| anyhow::anyhow!("failed to parse email as macro user id: {}", e))?;++ let entity_id = team_invite_id.to_string();+ let request = SendNotificationRequestBuilder {+ notification_entity: EntityType::Team.with_entity_str(&entity_id),+ notification,+ sender_id: Some(invited_by.clone()),+ recipient_ids: HashSet::from([recipient]),+ }+ .into_request()+ .with_conn_gateway();++ self.notification_ingress+ .send_notification(request)+ .await+ .map_err(|e| anyhow::anyhow!("failed to send notification: {}", e))?;++ Ok(())+ }+}++impl<TR, CR, URPS, NI> TeamService for TeamServiceImpl<TR, CR, URPS, NI>+where+ TR: TeamRepository,+ CR: CustomerRepository,+ URPS: UserRolesAndPermissionsService,+ NI: NotificationIngress,{async fn create_team(&self,@@ -124,6 +203,29 @@ where}}+ // Send notifications for new invites+ if !invited.is_empty() {+ let team_name = self.team_repository.get_team_name(team_id).await.ok();++ if let Some(team_name) = team_name {+ let invited_by_owned = invited_by.clone().into_owned();+ for invite in &invited {+ self.send_invite_notification(+ team_id,+ &invite.team_invite_id,+ invite.email.as_ref(),+ &team_name,+ &invited_by_owned,+ )+ .await+ .inspect_err(+ |e| tracing::error!(error=?e, "unable to send invite notification"),+ )+ .ok();+ }+ }+ }+Ok(invited)}@@ -339,4 +441,89 @@ whereOk(())}++ async fn get_team(&self, team_id: &uuid::Uuid) -> Result<TeamWithMembers, TeamError> {+ self.team_repository.get_team_by_id(team_id).await+ }++ async fn get_user_teams(&self, user_id: &MacroUserIdStr<'_>) -> Result<Vec<Team>, TeamError> {+ self.team_repository.get_user_teams(user_id).await+ }++ async fn get_user_invites(+ &self,+ user_id: &MacroUserIdStr<'_>,+ ) -> Result<Vec<TeamInviteDetails>, TeamError> {+ self.team_repository.get_user_team_invites(user_id).await+ }++ async fn get_team_invites(+ &self,+ team_id: &uuid::Uuid,+ ) -> Result<Vec<TeamInviteDetails>, TeamError> {+ self.team_repository.get_team_invites(team_id).await+ }++ async fn patch_team(+ &self,+ team_id: &uuid::Uuid,+ req: &PatchTeamRequest,+ ) -> Result<(), TeamError> {+ self.team_repository.patch_team(team_id, req).await+ }++ async fn reinvite_to_team(+ &self,+ team_invite_id: &uuid::Uuid,+ invited_by: &MacroUserIdStr<'_>,+ ) -> Result<TeamInviteDetails, ReinviteError> {+ let invite = self+ .team_repository+ .get_team_invite_details_by_id(team_invite_id)+ .await+ .map_err(|e| match e {+ TeamError::TeamInviteDoesNotExist => ReinviteError::InviteNotFound,+ other => ReinviteError::StorageLayerError(other.into()),+ })?;++ // Rate limit: must wait 5 minutes between reinvites+ let five_minutes_ago = chrono::Utc::now() - chrono::Duration::minutes(5);+ if invite.last_sent_at > five_minutes_ago {+ return Err(ReinviteError::TooManyRequests);+ }++ self.team_repository+ .update_team_invite_last_sent_at(team_invite_id)+ .await+ .map_err(|e| ReinviteError::StorageLayerError(e.into()))?;++ // Send notification+ let team_name = self+ .team_repository+ .get_team_name(&invite.team_id)+ .await+ .map_err(|e| ReinviteError::StorageLayerError(e.into()))?;++ let invited_by = invited_by.clone().into_owned();+ self.send_invite_notification(+ &invite.team_id,+ team_invite_id,+ &invite.email,+ &team_name,+ &invited_by,+ )+ .await+ .inspect_err(|e| tracing::error!(error=?e, "unable to send reinvite notification"))+ .ok();++ Ok(invite)+ }++ async fn get_team_role(+ &self,+ team_id: &uuid::Uuid,+ user_id: &MacroUserIdStr<'_>,+ ) -> Result<Option<TeamRole>, TeamError> {+ self.team_repository.get_team_role(team_id, user_id).await+ }}diff --git a/rust/cloud-storage/teams/src/inbound.rs b/rust/cloud-storage/teams/src/inbound.rsnew file mode 100644index 0000000000..b30e1e36d6--- /dev/null+++ b/rust/cloud-storage/teams/src/inbound.rs@@ -0,0 +1,4 @@+//! Inbound adapters for the teams domain.++#[cfg(feature = "axum")]+pub mod axum_router;diff --git a/rust/cloud-storage/teams/src/inbound/axum_router/create_team.rs b/rust/cloud-storage/teams/src/inbound/axum_router/create_team.rsnew file mode 100644index 0000000000..10fa513c3b--- /dev/null+++ b/rust/cloud-storage/teams/src/inbound/axum_router/create_team.rs@@ -0,0 +1,38 @@+use axum::{Json, extract::State};+use model_user::axum_extractor::MacroUserExtractor;++use crate::domain::{model::Team, team_repo::TeamService};++use super::TeamRouterState;++/// The request body to create a new team+#[derive(serde::Serialize, serde::Deserialize, utoipa::ToSchema)]+pub struct CreateTeamRequest {+ /// The name of the team+ pub name: String,+}++/// Creates a new team.+#[utoipa::path(+ post,+ path = "/team",+ operation_id = "create_team",+ responses(+ (status = 200, body = Team),+ (status = 400, body = model_error_response::ErrorResponse),+ (status = 500, body = model_error_response::ErrorResponse),+ ),+)]+#[tracing::instrument(skip_all, err)]+pub async fn handler<T: TeamService>(+ State(state): State<TeamRouterState<T>>,+ user_context: MacroUserExtractor,+ Json(req): Json<CreateTeamRequest>,+) -> Result<Json<Team>, crate::domain::model::CreateTeamError> {+ let team = state+ .service+ .create_team(&user_context.macro_user_id, &req.name)+ .await?;++ Ok(Json(team))+}diff --git a/rust/cloud-storage/teams/src/inbound/axum_router/delete_team.rs b/rust/cloud-storage/teams/src/inbound/axum_router/delete_team.rsnew file mode 100644index 0000000000..3d6300ae3a--- /dev/null+++ b/rust/cloud-storage/teams/src/inbound/axum_router/delete_team.rs@@ -0,0 +1,33 @@+use axum::extract::{Path, State};+use model_error_response::ErrorResponse;++use crate::domain::{model::DeleteTeamError, team_repo::TeamService};++use super::{TeamPathParam, TeamRouterState, middleware::TeamAccessRoleExtractor};++/// Deletes a team.+/// This will update all team members roles and cancel your subscription for the team.+/// This action is **irreversible** and you will not be able to recover the team afterwards.+#[utoipa::path(+ delete,+ path = "/team/{team_id}",+ operation_id = "delete_team",+ params(+ ("team_id" = String, Path, description = "The ID of the team to delete")+ ),+ responses(+ (status = 200),+ (status = 400, body = ErrorResponse),+ (status = 401, body = ErrorResponse),+ (status = 500, body = ErrorResponse),+ ),+)]+#[tracing::instrument(skip_all, err)]+pub async fn handler<T: TeamService>(+ _access: TeamAccessRoleExtractor<super::middleware::OwnerRole, T>,+ State(state): State<TeamRouterState<T>>,+ Path(TeamPathParam { team_id }): Path<TeamPathParam>,+) -> Result<(), DeleteTeamError> {+ state.service.delete_team(&team_id).await?;+ Ok(())+}diff --git a/rust/cloud-storage/teams/src/inbound/axum_router/delete_team_invite.rs b/rust/cloud-storage/teams/src/inbound/axum_router/delete_team_invite.rsnew file mode 100644index 0000000000..02056349a5--- /dev/null+++ b/rust/cloud-storage/teams/src/inbound/axum_router/delete_team_invite.rs@@ -0,0 +1,48 @@+use axum::extract::{Path, State};+use model_error_response::ErrorResponse;++use crate::domain::{model::RemoveTeamInviteError, team_repo::TeamService};++use super::{TeamRouterState, middleware::TeamAccessRoleExtractor};++/// Path parameters for delete team invite endpoint.+#[derive(serde::Deserialize)]+pub struct Param {+ /// The team ID.+ pub team_id: uuid::Uuid,+ /// The team invite ID.+ pub team_invite_id: uuid::Uuid,+}++/// Deletes a team invite from a team.+#[utoipa::path(+ delete,+ path = "/team/{team_id}/invite/{team_invite_id}",+ operation_id = "delete_team_invite_handler",+ params(+ ("team_id" = String, Path, description = "The ID of the team"),+ ("team_invite_id" = String, Path, description = "The ID of the team invite")+ ),+ responses(+ (status = 200),+ (status = 400, body = ErrorResponse),+ (status = 401, body = ErrorResponse),+ (status = 404, body = ErrorResponse),+ (status = 500, body = ErrorResponse),+ ),+)]+#[tracing::instrument(skip_all, err)]+pub async fn handler<T: TeamService>(+ _access: TeamAccessRoleExtractor<super::middleware::OwnerRole, T>,+ State(state): State<TeamRouterState<T>>,+ Path(Param {+ team_id,+ team_invite_id,+ }): Path<Param>,+) -> Result<(), RemoveTeamInviteError> {+ state+ .service+ .delete_team_invite(&team_id, &team_invite_id)+ .await?;+ Ok(())+}diff --git a/rust/cloud-storage/teams/src/inbound/axum_router/get_team.rs b/rust/cloud-storage/teams/src/inbound/axum_router/get_team.rsnew file mode 100644index 0000000000..26d8d6d1d7--- /dev/null+++ b/rust/cloud-storage/teams/src/inbound/axum_router/get_team.rs@@ -0,0 +1,38 @@+use axum::{+ Json,+ extract::{Path, State},+};+use model_error_response::ErrorResponse;++use crate::domain::{+ model::{TeamError, TeamWithMembers},+ team_repo::TeamService,+};++use super::{TeamPathParam, TeamRouterState, middleware::TeamAccessRoleExtractor};++/// Gets a team by ID.+#[utoipa::path(+ get,+ path = "/team/{team_id}",+ operation_id = "get_team",+ params(+ ("team_id" = String, Path, description = "The ID of the team to retrieve")+ ),+ responses(+ (status = 200, body = TeamWithMembers),+ (status = 400, body = ErrorResponse),+ (status = 401, body = ErrorResponse),+ (status = 404, body = ErrorResponse),+ (status = 500, body = ErrorResponse),+ ),+)]+#[tracing::instrument(skip_all, err)]+pub async fn handler<T: TeamService>(+ _access: TeamAccessRoleExtractor<super::middleware::MemberRole, T>,+ State(state): State<TeamRouterState<T>>,+ Path(TeamPathParam { team_id }): Path<TeamPathParam>,+) -> Result<Json<TeamWithMembers>, TeamError> {+ let team = state.service.get_team(&team_id).await?;+ Ok(Json(team))+}diff --git a/rust/cloud-storage/teams/src/inbound/axum_router/get_team_invites.rs b/rust/cloud-storage/teams/src/inbound/axum_router/get_team_invites.rsnew file mode 100644index 0000000000..cc17767838--- /dev/null+++ b/rust/cloud-storage/teams/src/inbound/axum_router/get_team_invites.rs@@ -0,0 +1,44 @@+use axum::{+ Json,+ extract::{Path, State},+};+use model_error_response::ErrorResponse;++use crate::domain::{+ model::{TeamError, TeamInviteDetails},+ team_repo::TeamService,+};++use super::{TeamPathParam, TeamRouterState, middleware::TeamAccessRoleExtractor};++/// Response containing a list of team invites+#[derive(serde::Serialize, utoipa::ToSchema)]+pub struct TeamInvitesResponse {+ /// The invites+ pub invites: Vec<TeamInviteDetails>,+}++/// Gets all invites for a team.+#[utoipa::path(+ get,+ path = "/team/{team_id}/invites",+ operation_id = "get_team_invites",+ params(+ ("team_id" = String, Path, description = "The ID of the team to get invites for")+ ),+ responses(+ (status = 200, body = TeamInvitesResponse),+ (status = 400, body = ErrorResponse),+ (status = 401, body = ErrorResponse),+ (status = 500, body = ErrorResponse),+ ),+)]+#[tracing::instrument(skip_all, err)]+pub async fn handler<T: TeamService>(+ _access: TeamAccessRoleExtractor<super::middleware::AdminRole, T>,+ State(state): State<TeamRouterState<T>>,+ Path(TeamPathParam { team_id }): Path<TeamPathParam>,+) -> Result<Json<TeamInvitesResponse>, TeamError> {+ let invites = state.service.get_team_invites(&team_id).await?;+ Ok(Json(TeamInvitesResponse { invites }))+}diff --git a/rust/cloud-storage/teams/src/inbound/axum_router/get_user_invites.rs b/rust/cloud-storage/teams/src/inbound/axum_router/get_user_invites.rsnew file mode 100644index 0000000000..87eaac1662--- /dev/null+++ b/rust/cloud-storage/teams/src/inbound/axum_router/get_user_invites.rs@@ -0,0 +1,41 @@+use axum::{Json, extract::State};+use model_error_response::ErrorResponse;+use model_user::axum_extractor::MacroUserExtractor;++use crate::domain::{+ model::{TeamError, TeamInviteDetails},+ team_repo::TeamService,+};++use super::TeamRouterState;++/// Response containing a list of team invites+#[derive(serde::Serialize, utoipa::ToSchema)]+pub struct TeamInvitesResponse {+ /// The invites+ pub invites: Vec<TeamInviteDetails>,+}++/// Gets all of a user's invitations.+#[utoipa::path(+ get,+ path = "/team/user/invites",+ operation_id = "get_user_invites",+ responses(+ (status = 200, body = TeamInvitesResponse),+ (status = 400, body = ErrorResponse),+ (status = 401, body = ErrorResponse),+ (status = 500, body = ErrorResponse),+ ),+)]+#[tracing::instrument(skip_all, err)]+pub async fn handler<T: TeamService>(+ State(state): State<TeamRouterState<T>>,+ user_context: MacroUserExtractor,+) -> Result<Json<TeamInvitesResponse>, TeamError> {+ let invites = state+ .service+ .get_user_invites(&user_context.macro_user_id)+ .await?;+ Ok(Json(TeamInvitesResponse { invites }))+}diff --git a/rust/cloud-storage/teams/src/inbound/axum_router/get_user_teams.rs b/rust/cloud-storage/teams/src/inbound/axum_router/get_user_teams.rsnew file mode 100644index 0000000000..734737dfe9--- /dev/null+++ b/rust/cloud-storage/teams/src/inbound/axum_router/get_user_teams.rs@@ -0,0 +1,34 @@+use axum::{Json, extract::State};+use model_error_response::ErrorResponse;+use model_user::axum_extractor::MacroUserExtractor;++use crate::domain::{+ model::{Team, TeamError},+ team_repo::TeamService,+};++use super::TeamRouterState;++/// Gets all teams for the authenticated user.+#[utoipa::path(+ get,+ path = "/team/user",+ operation_id = "get_user_teams",+ responses(+ (status = 200, body = Vec<Team>),+ (status = 400, body = ErrorResponse),+ (status = 401, body = ErrorResponse),+ (status = 500, body = ErrorResponse),+ ),+)]+#[tracing::instrument(skip_all, err)]+pub async fn handler<T: TeamService>(+ State(state): State<TeamRouterState<T>>,+ user_context: MacroUserExtractor,+) -> Result<Json<Vec<Team>>, TeamError> {+ let teams = state+ .service+ .get_user_teams(&user_context.macro_user_id)+ .await?;+ Ok(Json(teams))+}diff --git a/rust/cloud-storage/teams/src/inbound/axum_router/invite_to_team.rs b/rust/cloud-storage/teams/src/inbound/axum_router/invite_to_team.rsnew file mode 100644index 0000000000..97b6f35bb7--- /dev/null+++ b/rust/cloud-storage/teams/src/inbound/axum_router/invite_to_team.rs@@ -0,0 +1,121 @@+use axum::{+ Json,+ extract::{Path, State},+ http::StatusCode,+};+use macro_user_id::{email::Email, lowercased::Lowercase};+use model_error_response::ErrorResponse;+use model_user::axum_extractor::MacroUserExtractor;++use crate::domain::{model::InviteUsersToTeamError, team_repo::TeamService};++use super::{TeamPathParam, TeamRouterState, middleware::TeamAccessRoleExtractor};++/// The request body to invite a user to a team+#[derive(serde::Serialize, serde::Deserialize, utoipa::ToSchema)]+pub struct InviteToTeamRequest {+ /// The emails of the users you want to invite to the team+ pub emails: Vec<String>,+}++/// Error type for the invite to team handler+#[derive(Debug, thiserror::Error)]+pub enum InviteToTeamError {+ /// Unable to invite users to team+ #[error("unable to invite users to team")]+ InviteUsersToTeamError(#[from] InviteUsersToTeamError),+ /// Invalid emails detected+ #[error("unable to parse email")]+ InvalidEmails,+ /// No valid emails provided+ #[error("no valid emails provided")]+ NoValidEmailsProvided,+}++impl axum::response::IntoResponse for InviteToTeamError {+ fn into_response(self) -> axum::response::Response {+ match self {+ InviteToTeamError::InvalidEmails => (+ StatusCode::BAD_REQUEST,+ Json(ErrorResponse {+ message: "invalid emails detected",+ }),+ ),+ InviteToTeamError::NoValidEmailsProvided => (+ StatusCode::BAD_REQUEST,+ Json(ErrorResponse {+ message: "no emails provided",+ }),+ ),+ InviteToTeamError::InviteUsersToTeamError(e) => match e {+ InviteUsersToTeamError::TooManyEmails => (+ StatusCode::BAD_REQUEST,+ Json(ErrorResponse {+ message: "too many emails",+ }),+ ),+ _ => (+ StatusCode::INTERNAL_SERVER_ERROR,+ Json(ErrorResponse {+ message: "unable to invite users to team",+ }),+ ),+ },+ }+ .into_response()+ }+}++/// Invites a user to a team.+#[utoipa::path(+ post,+ path = "/team/{team_id}/invite",+ operation_id = "invite_to_team",+ params(+ ("team_id" = String, Path, description = "The ID of the team to invite to")+ ),+ request_body = InviteToTeamRequest,+ responses(+ (status = 201),+ (status = 304),+ (status = 400, body = ErrorResponse),+ (status = 401, body = ErrorResponse),+ (status = 404, body = ErrorResponse),+ (status = 500, body = ErrorResponse),+ ),+)]+#[tracing::instrument(skip_all, err)]+pub async fn handler<T: TeamService>(+ _access: TeamAccessRoleExtractor<super::middleware::OwnerRole, T>,+ State(state): State<TeamRouterState<T>>,+ user_context: MacroUserExtractor,+ Path(TeamPathParam { team_id }): Path<TeamPathParam>,+ Json(req): Json<InviteToTeamRequest>,+) -> Result<StatusCode, InviteToTeamError> {+ let emails: Vec<Result<Email<Lowercase<'_>>, _>> = req+ .emails+ .iter()+ .map(|email| Email::parse_from_str(email).map(|email| email.lowercase()))+ .collect();++ if emails.iter().any(|e| e.is_err()) {+ return Err(InviteToTeamError::InvalidEmails);+ }++ let emails = emails.into_iter().map(|e| e.unwrap()).collect::<Vec<_>>();++ let emails = non_empty::NonEmpty::new(emails.as_slice())+ .map_err(|_| InviteToTeamError::NoValidEmailsProvided)?;++ let team_invites = state+ .service+ .invite_users_to_team(&team_id, &user_context.macro_user_id, emails)+ .await+ .map_err(InviteToTeamError::InviteUsersToTeamError)?;++ if team_invites.is_empty() {+ return Ok(StatusCode::NOT_MODIFIED);+ }++ Ok(StatusCode::CREATED)+}diff --git a/rust/cloud-storage/teams/src/inbound/axum_router/join_team.rs b/rust/cloud-storage/teams/src/inbound/axum_router/join_team.rsnew file mode 100644index 0000000000..5f53724d32--- /dev/null+++ b/rust/cloud-storage/teams/src/inbound/axum_router/join_team.rs@@ -0,0 +1,42 @@+use axum::extract::{Path, State};+use model_error_response::ErrorResponse;+use model_user::axum_extractor::MacroUserExtractor;++use crate::domain::{model::JoinTeamError, team_repo::TeamService};++use super::TeamRouterState;++/// Path parameters for join team endpoint.+#[derive(serde::Deserialize)]+pub struct TeamInvitePathParam {+ /// The team invite ID.+ pub team_invite_id: uuid::Uuid,+}++/// Joins a team by accepting an invite.+#[utoipa::path(+ get,+ path = "/team/join/{team_invite_id}",+ operation_id = "join_team",+ params(+ ("team_invite_id" = String, Path, description = "The team invite id")+ ),+ responses(+ (status = 200),+ (status = 400, body = ErrorResponse),+ (status = 401, body = ErrorResponse),+ (status = 500, body = ErrorResponse),+ ),+)]+#[tracing::instrument(skip_all, err)]+pub async fn handler<T: TeamService>(+ State(state): State<TeamRouterState<T>>,+ user_context: MacroUserExtractor,+ Path(TeamInvitePathParam { team_invite_id }): Path<TeamInvitePathParam>,+) -> Result<(), JoinTeamError> {+ state+ .service+ .join_team(&team_invite_id, &user_context.macro_user_id)+ .await?;+ Ok(())+}diff --git a/rust/cloud-storage/teams/src/inbound/axum_router/middleware.rs b/rust/cloud-storage/teams/src/inbound/axum_router/middleware.rsnew file mode 100644index 0000000000..f23b6d582b--- /dev/null+++ b/rust/cloud-storage/teams/src/inbound/axum_router/middleware.rs@@ -0,0 +1,136 @@+//! Middleware for team access control.++use std::marker::PhantomData;++use axum::{+ Json, RequestPartsExt,+ extract::{FromRef, FromRequestParts, Path},+ http::{StatusCode, request::Parts},+ response::{IntoResponse, Response},+};+use model_error_response::ErrorResponse;+use model_user::axum_extractor::MacroUserExtractor;++use crate::domain::{model::TeamRole, team_repo::TeamService};++use super::{TeamPathParam, TeamRouterState};++/// Marker for member-level access+#[derive(Debug)]+pub struct MemberRole;++/// Marker for admin-level access+#[derive(Debug)]+pub struct AdminRole;++/// Marker for owner-level access+#[derive(Debug)]+pub struct OwnerRole;++trait BuildTeamAccess {+ fn into_team_role() -> TeamRole;+}++impl BuildTeamAccess for MemberRole {+ fn into_team_role() -> TeamRole {+ TeamRole::Member+ }+}++impl BuildTeamAccess for AdminRole {+ fn into_team_role() -> TeamRole {+ TeamRole::Admin+ }+}++impl BuildTeamAccess for OwnerRole {+ fn into_team_role() -> TeamRole {+ TeamRole::Owner+ }+}++/// Extractor that verifies the user has at least the required role in the team.+#[derive(Debug)]+pub struct TeamAccessRoleExtractor<Role, TS: TeamService> {+ #[expect(dead_code)]+ role: TeamRole,+ _role: PhantomData<Role>,+ _ts: PhantomData<TS>,+}++/// Errors from team access role extraction+#[derive(Debug, thiserror::Error)]+pub enum RoleAccessErr {+ /// Team id not found in path params+ #[error("Team id not found in path params")]+ MissingTeamId,+ /// User context failed to extract+ #[error("Internal server err")]+ UserContextErr,+ /// Failed to get team role+ #[error("Failed to get team role")]+ DbErr(#[from] crate::domain::model::TeamError),+ /// User is not a member of this team+ #[error("User is not a member of this team")]+ NotInTeam,+ /// User does not have access to the desired resource+ #[error("User does not have access to the desired resource")]+ NotHighEnoughAccess,+}++impl IntoResponse for RoleAccessErr {+ fn into_response(self) -> Response {+ let err = Json(ErrorResponse {+ message: &self.to_string(),+ });+ match self {+ RoleAccessErr::MissingTeamId => (StatusCode::BAD_REQUEST, err),+ RoleAccessErr::UserContextErr => (StatusCode::INTERNAL_SERVER_ERROR, err),+ RoleAccessErr::DbErr(_) => (StatusCode::INTERNAL_SERVER_ERROR, err),+ RoleAccessErr::NotInTeam => (StatusCode::UNAUTHORIZED, err),+ RoleAccessErr::NotHighEnoughAccess => (StatusCode::UNAUTHORIZED, err),+ }+ .into_response()+ }+}++impl<S, Role, TS> FromRequestParts<S> for TeamAccessRoleExtractor<Role, TS>+where+ TeamRouterState<TS>: FromRef<S>,+ S: Send + Sync + Clone + 'static,+ Role: BuildTeamAccess,+ TS: TeamService,+{+ type Rejection = RoleAccessErr;++ async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {+ let router_state = TeamRouterState::<TS>::from_ref(state);++ let user_context: MacroUserExtractor = parts+ .extract()+ .await+ .map_err(|_| RoleAccessErr::UserContextErr)?;++ let Path(TeamPathParam { team_id }) = parts+ .extract()+ .await+ .map_err(|_| RoleAccessErr::MissingTeamId)?;++ let team_role = router_state+ .service+ .get_team_role(&team_id, &user_context.macro_user_id)+ .await?;++ let team_role = team_role.ok_or(RoleAccessErr::NotInTeam)?;++ if team_role < Role::into_team_role() {+ return Err(RoleAccessErr::NotHighEnoughAccess);+ }++ Ok(Self {+ role: team_role,+ _role: PhantomData,+ _ts: PhantomData,+ })+ }+}diff --git a/rust/cloud-storage/teams/src/inbound/axum_router/mod.rs b/rust/cloud-storage/teams/src/inbound/axum_router/mod.rsnew file mode 100644index 0000000000..85a743da3b--- /dev/null+++ b/rust/cloud-storage/teams/src/inbound/axum_router/mod.rs@@ -0,0 +1,298 @@+//! Axum router for team endpoints.++/// Create a new team.+pub mod create_team;+/// Delete a team.+pub mod delete_team;+/// Delete a team invite.+pub mod delete_team_invite;+/// Get a team by ID.+pub mod get_team;+/// Get all invites for a team.+pub mod get_team_invites;+/// Get all invites for a user.+pub mod get_user_invites;+/// Get all teams for a user.+pub mod get_user_teams;+/// Invite users to a team.+pub mod invite_to_team;+/// Join a team via invite.+pub mod join_team;+/// Team access control middleware.+pub mod middleware;+/// Update a team.+pub mod patch_team;+/// Reinvite a user to a team.+pub mod reinvite_to_team;+/// Reject a team invitation.+pub mod reject_invitation;+/// Remove a user from a team.+pub mod remove_user_from_team;++#[cfg(test)]+mod test;++use std::sync::Arc;++use axum::{+ Json, Router,+ http::StatusCode,+ response::{IntoResponse, Response},+ routing::{delete, get, patch, post},+};+use model_error_response::ErrorResponse;++use crate::domain::{+ model::{+ CreateTeamError, DeleteTeamError, InviteUsersToTeamError, JoinTeamError, ReinviteError,+ RemoveTeamInviteError, RemoveUserFromTeamError, TeamError,+ },+ team_repo::TeamService,+};++/// Shared path param for team endpoints.+#[derive(serde::Deserialize)]+pub struct TeamPathParam {+ /// The team id+ pub team_id: uuid::Uuid,+}++/// Router state containing the team service.+pub struct TeamRouterState<T> {+ /// The team service implementation.+ pub service: Arc<T>,+}++// Manual Clone impl so T doesn't need to be Clone (it's behind Arc).+impl<T> Clone for TeamRouterState<T> {+ fn clone(&self) -> Self {+ Self {+ service: self.service.clone(),+ }+ }+}++/// Build the teams router with all endpoints.+pub fn teams_router<T, S>(state: TeamRouterState<T>) -> Router<S>+where+ T: TeamService,+ S: Send + Sync + 'static,+{+ Router::new()+ .route("/", post(create_team::handler::<T>))+ .route("/join/{team_invite_id}", get(join_team::handler::<T>))+ .route("/user", get(get_user_teams::handler::<T>))+ .route("/user/invites", get(get_user_invites::handler::<T>))+ .route("/{team_id}", get(get_team::handler::<T>))+ .route("/{team_id}", patch(patch_team::handler::<T>))+ .route("/{team_id}", delete(delete_team::handler::<T>))+ .route("/{team_id}/invites", get(get_team_invites::handler::<T>))+ .route("/{team_id}/invite", post(invite_to_team::handler::<T>))+ .route(+ "/{team_id}/reinvite/{team_invite_id}",+ post(reinvite_to_team::handler::<T>),+ )+ .route(+ "/join/{team_invite_id}",+ delete(reject_invitation::handler::<T>),+ )+ .route(+ "/{team_id}/remove/{remove_user_id}",+ delete(remove_user_from_team::handler::<T>),+ )+ .route(+ "/{team_id}/invite/{team_invite_id}",+ delete(delete_team_invite::handler::<T>),+ )+ .with_state(state)+}++// --- Error IntoResponse implementations ---++impl IntoResponse for TeamError {+ fn into_response(self) -> Response {+ match self {+ TeamError::TeamDoesNotExist => (+ StatusCode::NOT_FOUND,+ Json(ErrorResponse {+ message: "team does not exist",+ }),+ ),+ TeamError::TeamInviteDoesNotExist => (+ StatusCode::NOT_FOUND,+ Json(ErrorResponse {+ message: "team invite does not exist",+ }),+ ),+ _ => (+ StatusCode::INTERNAL_SERVER_ERROR,+ Json(ErrorResponse {+ message: "internal server error",+ }),+ ),+ }+ .into_response()+ }+}++impl IntoResponse for CreateTeamError {+ fn into_response(self) -> Response {+ match self {+ CreateTeamError::InvalidTeamName(_) => (+ StatusCode::BAD_REQUEST,+ Json(ErrorResponse {+ message: "invalid team name",+ }),+ ),+ CreateTeamError::StorageLayerError(_) => (+ StatusCode::INTERNAL_SERVER_ERROR,+ Json(ErrorResponse {+ message: "unable to create team",+ }),+ ),+ }+ .into_response()+ }+}++impl IntoResponse for DeleteTeamError {+ fn into_response(self) -> Response {+ match self {+ DeleteTeamError::TeamError(_) | DeleteTeamError::StorageLayerError(_) => (+ StatusCode::INTERNAL_SERVER_ERROR,+ Json(ErrorResponse {+ message: "unable to delete team",+ }),+ ),+ DeleteTeamError::RemoveRolesFromUserError(_) => (+ StatusCode::INTERNAL_SERVER_ERROR,+ Json(ErrorResponse {+ message: "invalid roles provided",+ }),+ ),+ DeleteTeamError::CustomerError(_) => (+ StatusCode::INTERNAL_SERVER_ERROR,+ Json(ErrorResponse {+ message: "unable to delete team subscription",+ }),+ ),+ }+ .into_response()+ }+}++impl IntoResponse for InviteUsersToTeamError {+ fn into_response(self) -> Response {+ match self {+ InviteUsersToTeamError::TooManyEmails => (+ StatusCode::BAD_REQUEST,+ Json(ErrorResponse {+ message: "too many emails",+ }),+ ),+ _ => (+ StatusCode::INTERNAL_SERVER_ERROR,+ Json(ErrorResponse {+ message: "unable to invite users to team",+ }),+ ),+ }+ .into_response()+ }+}++impl IntoResponse for JoinTeamError {+ fn into_response(self) -> Response {+ (+ StatusCode::INTERNAL_SERVER_ERROR,+ Json(ErrorResponse {+ message: "unable to join team",+ }),+ )+ .into_response()+ }+}++impl IntoResponse for RemoveTeamInviteError {+ fn into_response(self) -> Response {+ match self {+ RemoveTeamInviteError::TeamInviteDoesNotExist => (+ StatusCode::NOT_FOUND,+ Json(ErrorResponse {+ message: "team invite does not exist",+ }),+ ),+ RemoveTeamInviteError::UserNotInTeam => (+ StatusCode::BAD_REQUEST,+ Json(ErrorResponse {+ message: "user not in team",+ }),+ ),+ _ => (+ StatusCode::INTERNAL_SERVER_ERROR,+ Json(ErrorResponse {+ message: "internal server error",+ }),+ ),+ }+ .into_response()+ }+}++impl IntoResponse for RemoveUserFromTeamError {+ fn into_response(self) -> Response {+ match self {+ RemoveUserFromTeamError::TeamDoesNotExist => (+ StatusCode::NOT_FOUND,+ Json(ErrorResponse {+ message: "team does not exist",+ }),+ ),+ RemoveUserFromTeamError::CannotRemoveOwner => (+ StatusCode::BAD_REQUEST,+ Json(ErrorResponse {+ message: "cannot remove owner",+ }),+ ),+ RemoveUserFromTeamError::UserNotInTeam => (+ StatusCode::NOT_FOUND,+ Json(ErrorResponse {+ message: "user not in team",+ }),+ ),+ _ => (+ StatusCode::INTERNAL_SERVER_ERROR,+ Json(ErrorResponse {+ message: "unable to remove user from team",+ }),+ ),+ }+ .into_response()+ }+}++impl IntoResponse for ReinviteError {+ fn into_response(self) -> Response {+ match self {+ ReinviteError::TooManyRequests => (+ StatusCode::TOO_MANY_REQUESTS,+ Json(ErrorResponse {+ message: "team invite has not been sent in the last 5 minutes",+ }),+ ),+ ReinviteError::InviteNotFound => (+ StatusCode::NOT_FOUND,+ Json(ErrorResponse {+ message: "team invite does not exist",+ }),+ ),+ ReinviteError::StorageLayerError(_) => (+ StatusCode::INTERNAL_SERVER_ERROR,+ Json(ErrorResponse {+ message: "internal server error",+ }),+ ),+ }+ .into_response()+ }+}diff --git a/rust/cloud-storage/teams/src/inbound/axum_router/patch_team.rs b/rust/cloud-storage/teams/src/inbound/axum_router/patch_team.rsnew file mode 100644index 0000000000..f1c5abc363--- /dev/null+++ b/rust/cloud-storage/teams/src/inbound/axum_router/patch_team.rs@@ -0,0 +1,40 @@+use axum::{+ Json,+ extract::{Path, State},+};+use model_error_response::ErrorResponse;++use crate::domain::{+ model::{PatchTeamRequest, TeamError},+ team_repo::TeamService,+};++use super::{TeamPathParam, TeamRouterState, middleware::TeamAccessRoleExtractor};++/// Updates a team.+#[utoipa::path(+ patch,+ path = "/team/{team_id}",+ operation_id = "patch_team",+ params(+ ("team_id" = String, Path, description = "The ID of the team to update")+ ),+ request_body = PatchTeamRequest,+ responses(+ (status = 200),+ (status = 400, body = ErrorResponse),+ (status = 401, body = ErrorResponse),+ (status = 404, body = ErrorResponse),+ (status = 500, body = ErrorResponse),+ ),+)]+#[tracing::instrument(skip_all, err)]+pub async fn handler<T: TeamService>(+ _access: TeamAccessRoleExtractor<super::middleware::AdminRole, T>,+ State(state): State<TeamRouterState<T>>,+ Path(TeamPathParam { team_id }): Path<TeamPathParam>,+ Json(req): Json<PatchTeamRequest>,+) -> Result<(), TeamError> {+ state.service.patch_team(&team_id, &req).await?;+ Ok(())+}diff --git a/rust/cloud-storage/teams/src/inbound/axum_router/reinvite_to_team.rs b/rust/cloud-storage/teams/src/inbound/axum_router/reinvite_to_team.rsnew file mode 100644index 0000000000..71e11b538a--- /dev/null+++ b/rust/cloud-storage/teams/src/inbound/axum_router/reinvite_to_team.rs@@ -0,0 +1,50 @@+use axum::extract::{Path, State};+use model_error_response::ErrorResponse;+use model_user::axum_extractor::MacroUserExtractor;++use crate::domain::{model::ReinviteError, team_repo::TeamService};++use super::{TeamRouterState, middleware::TeamAccessRoleExtractor};++/// Path parameters for reinvite endpoint.+#[derive(serde::Deserialize)]+pub struct Param {+ /// The team ID.+ pub team_id: uuid::Uuid,+ /// The team invite ID.+ pub team_invite_id: uuid::Uuid,+}++/// Regenerates a team invite notifying the user again.+#[utoipa::path(+ post,+ path = "/team/{team_id}/reinvite/{team_invite_id}",+ operation_id = "reinvite_to_team",+ params(+ ("team_id" = String, Path, description = "The ID of the team to invite to"),+ ("team_invite_id" = String, Path, description = "The ID of the team invite to reinvite")+ ),+ responses(+ (status = 200),+ (status = 400, body = ErrorResponse),+ (status = 401, body = ErrorResponse),+ (status = 429, body = ErrorResponse),+ (status = 500, body = ErrorResponse),+ ),+)]+#[tracing::instrument(skip_all, err)]+pub async fn handler<T: TeamService>(+ _access: TeamAccessRoleExtractor<super::middleware::AdminRole, T>,+ State(state): State<TeamRouterState<T>>,+ user_context: MacroUserExtractor,+ Path(Param {+ team_id: _,+ team_invite_id,+ }): Path<Param>,+) -> Result<(), ReinviteError> {+ state+ .service+ .reinvite_to_team(&team_invite_id, &user_context.macro_user_id)+ .await?;+ Ok(())+}diff --git a/rust/cloud-storage/teams/src/inbound/axum_router/reject_invitation.rs b/rust/cloud-storage/teams/src/inbound/axum_router/reject_invitation.rsnew file mode 100644index 0000000000..2fafd097da--- /dev/null+++ b/rust/cloud-storage/teams/src/inbound/axum_router/reject_invitation.rs@@ -0,0 +1,42 @@+use axum::extract::{Path, State};+use model_error_response::ErrorResponse;+use model_user::axum_extractor::MacroUserExtractor;++use crate::domain::{model::RemoveTeamInviteError, team_repo::TeamService};++use super::TeamRouterState;++/// Path parameters for reject invitation endpoint.+#[derive(serde::Deserialize)]+pub struct TeamInvitePathParam {+ /// The team invite ID.+ pub team_invite_id: uuid::Uuid,+}++/// Rejects an invitation to join a team.+#[utoipa::path(+ delete,+ path = "/team/join/{team_invite_id}",+ operation_id = "reject_invitation",+ params(+ ("team_invite_id" = String, Path, description = "The team invite id")+ ),+ responses(+ (status = 200),+ (status = 400, body = ErrorResponse),+ (status = 401, body = ErrorResponse),+ (status = 500, body = ErrorResponse),+ ),+)]+#[tracing::instrument(skip_all, err)]+pub async fn handler<T: TeamService>(+ State(state): State<TeamRouterState<T>>,+ user_context: MacroUserExtractor,+ Path(TeamInvitePathParam { team_invite_id }): Path<TeamInvitePathParam>,+) -> Result<(), RemoveTeamInviteError> {+ state+ .service+ .reject_invitation(&user_context.macro_user_id, &team_invite_id)+ .await?;+ Ok(())+}diff --git a/rust/cloud-storage/teams/src/inbound/axum_router/remove_user_from_team.rs b/rust/cloud-storage/teams/src/inbound/axum_router/remove_user_from_team.rsnew file mode 100644index 0000000000..052a3e1210--- /dev/null+++ b/rust/cloud-storage/teams/src/inbound/axum_router/remove_user_from_team.rs@@ -0,0 +1,49 @@+use axum::extract::{Path, State};+use model_error_response::ErrorResponse;+use model_user::axum_extractor::MacroUserExtractor;++use crate::domain::{model::RemoveUserFromTeamError, team_repo::TeamService};++use super::{TeamRouterState, middleware::TeamAccessRoleExtractor};++/// Path parameters for remove user endpoint.+#[derive(serde::Deserialize)]+pub struct Param {+ /// The team ID.+ pub team_id: uuid::Uuid,+ /// The ID of the user to remove.+ pub remove_user_id: String,+}++/// Removes a user from a team.+#[utoipa::path(+ delete,+ path = "/team/{team_id}/remove/{remove_user_id}",+ operation_id = "remove_user_from_team",+ params(+ ("team_id" = String, Path, description = "The ID of the team"),+ ("remove_user_id" = String, Path, description = "The ID of the user to remove")+ ),+ responses(+ (status = 200),+ (status = 400, body = ErrorResponse),+ (status = 401, body = ErrorResponse),+ (status = 500, body = ErrorResponse),+ ),+)]+#[tracing::instrument(skip_all, err)]+pub async fn handler<T: TeamService>(+ _access: TeamAccessRoleExtractor<super::middleware::OwnerRole, T>,+ State(state): State<TeamRouterState<T>>,+ user_context: MacroUserExtractor,+ Path(Param {+ team_id,+ remove_user_id: _,+ }): Path<Param>,+) -> Result<(), RemoveUserFromTeamError> {+ state+ .service+ .remove_user_from_team(&team_id, &user_context.macro_user_id)+ .await?;+ Ok(())+}diff --git a/rust/cloud-storage/teams/src/inbound/axum_router/test.rs b/rust/cloud-storage/teams/src/inbound/axum_router/test.rsnew file mode 100644index 0000000000..27b39c281b--- /dev/null+++ b/rust/cloud-storage/teams/src/inbound/axum_router/test.rs@@ -0,0 +1 @@+// Tests for team handlers will be added once the full integration is complete.diff --git a/rust/cloud-storage/teams/src/lib.rs b/rust/cloud-storage/teams/src/lib.rsindex 9ef44b5491..833cd00b6b 100644--- a/rust/cloud-storage/teams/src/lib.rs+++ b/rust/cloud-storage/teams/src/lib.rs@@ -1,8 +1,21 @@#![deny(missing_docs)]-//! This crate contains the domain for handling teams.+//! Teams hexagonal architecture crate.+//!+//! Encapsulates team management operations using a ports-and-adapters pattern.+//!+//! # Architecture+//!+//! - **domain**: Contains domain models, ports (traits), and the service implementation+//! - **outbound**: Contains adapters for external dependencies (PostgreSQL, Stripe)+//! - **inbound**: Contains adapters for incoming requests (Axum handlers)/// The domain module contains the domain logic for teamspub mod domain;+/// The inbound module contains the inbound adapters for teams+#[cfg(feature = "inbound")]+pub mod inbound;+/// The outbound module contains the outbound logic for teams+#[cfg(feature = "outbound")]pub mod outbound;diff --git a/rust/cloud-storage/teams/src/outbound/team_repo.rs b/rust/cloud-storage/teams/src/outbound/team_repo.rsindex 5414c5d257..ec9c390648 100644--- a/rust/cloud-storage/teams/src/outbound/team_repo.rs+++ b/rust/cloud-storage/teams/src/outbound/team_repo.rs@@ -1,8 +1,9 @@//! Implementation for TeamRepository using MacroDB.use crate::domain::{model::{- CreateTeamError, InviteUsersToTeamError, RemoveTeamInviteError, RemoveUserFromTeamError,- Team, TeamError, TeamInvite, TeamMember, TeamRole,+ CreateTeamError, InviteUsersToTeamError, PatchTeamRequest, RemoveTeamInviteError,+ RemoveUserFromTeamError, Team, TeamError, TeamInvite, TeamInviteDetails, TeamMember,+ TeamRole, TeamWithMembers,},team_repo::TeamRepository,};@@ -628,4 +629,246 @@ impl TeamRepository for TeamRepositoryImpl {Ok(members)}++ async fn get_team_by_id(&self, team_id: &uuid::Uuid) -> Result<TeamWithMembers, TeamError> {+ let team = sqlx::query!(+ r#"+ SELECT id, name, owner_id+ FROM team+ WHERE id = $1+ "#,+ team_id,+ )+ .map(|row| Team::new(row.id, row.name, row.owner_id))+ .fetch_one(&self.pool)+ .await?;++ let members = sqlx::query!(+ r#"+ SELECT user_id,+ team_role as "team_role!: TeamRole"+ FROM team_user+ WHERE team_id = $1+ "#,+ team_id,+ )+ .fetch_all(&self.pool)+ .await?;++ let members = members+ .into_iter()+ .filter_map(|row| {+ MacroUserIdStr::parse_from_str(&row.user_id)+ .map(|id| TeamMember {+ user_id: id.into_owned(),+ role: row.team_role,+ })+ .ok()+ })+ .collect();++ Ok(TeamWithMembers { team, members })+ }++ async fn get_user_teams(&self, user_id: &MacroUserIdStr<'_>) -> Result<Vec<Team>, TeamError> {+ let teams = sqlx::query!(+ r#"+ SELECT t.id, t.name, t.owner_id+ FROM team t+ JOIN team_user tu ON t.id = tu.team_id+ WHERE tu.user_id = $1+ "#,+ user_id.as_ref(),+ )+ .map(|row| Team::new(row.id, row.name, row.owner_id))+ .fetch_all(&self.pool)+ .await?;++ Ok(teams)+ }++ async fn get_user_team_invites(+ &self,+ user_id: &MacroUserIdStr<'_>,+ ) -> Result<Vec<TeamInviteDetails>, TeamError> {+ let email = user_id.email_part().lowercase();++ let invites = sqlx::query!(+ r#"+ SELECT+ id,+ email,+ team_id,+ team_role as "team_role!: TeamRole",+ invited_by,+ created_at as "created_at!: chrono::DateTime<chrono::Utc>",+ last_sent_at as "last_sent_at!: chrono::DateTime<chrono::Utc>"+ FROM team_invite+ WHERE email = $1+ "#,+ email.as_ref(),+ )+ .map(|row| TeamInviteDetails {+ id: row.id,+ email: row.email,+ team_id: row.team_id,+ team_role: row.team_role,+ invited_by: row.invited_by,+ created_at: row.created_at,+ last_sent_at: row.last_sent_at,+ })+ .fetch_all(&self.pool)+ .await?;++ Ok(invites)+ }++ async fn get_team_invites(+ &self,+ team_id: &uuid::Uuid,+ ) -> Result<Vec<TeamInviteDetails>, TeamError> {+ let invites = sqlx::query!(+ r#"+ SELECT+ id,+ email,+ team_id,+ team_role as "team_role!: TeamRole",+ invited_by,+ created_at as "created_at!: chrono::DateTime<chrono::Utc>",+ last_sent_at as "last_sent_at!: chrono::DateTime<chrono::Utc>"+ FROM team_invite+ WHERE team_id = $1+ "#,+ team_id,+ )+ .map(|row| TeamInviteDetails {+ id: row.id,+ email: row.email,+ team_id: row.team_id,+ team_role: row.team_role,+ invited_by: row.invited_by,+ created_at: row.created_at,+ last_sent_at: row.last_sent_at,+ })+ .fetch_all(&self.pool)+ .await?;++ Ok(invites)+ }++ async fn get_team_name(&self, team_id: &uuid::Uuid) -> Result<String, TeamError> {+ let name = sqlx::query!(+ r#"+ SELECT name+ FROM team+ WHERE id = $1+ "#,+ team_id,+ )+ .map(|row| row.name)+ .fetch_one(&self.pool)+ .await?;++ Ok(name)+ }++ async fn patch_team(+ &self,+ team_id: &uuid::Uuid,+ req: &PatchTeamRequest,+ ) -> Result<(), TeamError> {+ if let Some(name) = req.name.as_ref() {+ sqlx::query!(+ r#"+ UPDATE team+ SET name = $1+ WHERE id = $2+ "#,+ name,+ team_id,+ )+ .execute(&self.pool)+ .await?;+ }++ Ok(())+ }++ async fn get_team_invite_details_by_id(+ &self,+ invite_id: &uuid::Uuid,+ ) -> Result<TeamInviteDetails, TeamError> {+ let invite = sqlx::query!(+ r#"+ SELECT+ id,+ email,+ team_id,+ team_role as "team_role!: TeamRole",+ invited_by,+ created_at as "created_at!: chrono::DateTime<chrono::Utc>",+ last_sent_at as "last_sent_at!: chrono::DateTime<chrono::Utc>"+ FROM team_invite+ WHERE id = $1+ "#,+ invite_id,+ )+ .map(|row| TeamInviteDetails {+ id: row.id,+ email: row.email,+ team_id: row.team_id,+ team_role: row.team_role,+ invited_by: row.invited_by,+ created_at: row.created_at,+ last_sent_at: row.last_sent_at,+ })+ .fetch_one(&self.pool)+ .await+ .map_err(|e| match e {+ sqlx::Error::RowNotFound => TeamError::TeamInviteDoesNotExist,+ _ => e.into(),+ })?;++ Ok(invite)+ }++ async fn update_team_invite_last_sent_at(+ &self,+ invite_id: &uuid::Uuid,+ ) -> Result<(), TeamError> {+ sqlx::query!(+ r#"+ UPDATE team_invite+ SET last_sent_at = NOW()+ WHERE id = $1+ "#,+ invite_id,+ )+ .execute(&self.pool)+ .await?;++ Ok(())+ }++ async fn get_team_role(+ &self,+ team_id: &uuid::Uuid,+ user_id: &MacroUserIdStr<'_>,+ ) -> Result<Option<TeamRole>, TeamError> {+ let team_role = sqlx::query!(+ r#"+ SELECT team_role as "team_role!: TeamRole"+ FROM team_user+ WHERE team_id = $1 AND user_id = $2+ "#,+ team_id,+ user_id.as_ref(),+ )+ .map(|r| r.team_role)+ .fetch_optional(&self.pool)+ .await?;++ Ok(team_role)+ }}