Skip to content

armgit / macro

Public Imported from GitHub
0

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

feat(channels): team channel edits (#5114)

Will Hutchinsond2c941f1061f
diff --git a/.sqlx/query-2c77b982d340967465a952f918b3ebd357faa0b3edc9a8bf325ffafe4b90d3ca.json b/.sqlx/query-2c77b982d340967465a952f918b3ebd357faa0b3edc9a8bf325ffafe4b90d3ca.json
new file mode 100644
index 0000000000..c9b636d8b7
--- /dev/null
+++ b/.sqlx/query-2c77b982d340967465a952f918b3ebd357faa0b3edc9a8bf325ffafe4b90d3ca.json
@@ -0,0 +1,18 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n UPDATE comms_channels\n SET name = COALESCE($2, name),\n channel_type = CASE\n WHEN $3 IS TRUE THEN 'team'::comms_channel_type\n WHEN $3 IS FALSE AND channel_type = 'team'::comms_channel_type\n THEN 'private'::comms_channel_type\n ELSE channel_type\n END,\n team_id = CASE\n WHEN $3 IS TRUE THEN $4\n WHEN $3 IS FALSE AND channel_type = 'team'::comms_channel_type THEN NULL\n ELSE team_id\n END,\n auto_join_team = CASE\n WHEN $3 IS FALSE AND channel_type = 'team'::comms_channel_type THEN FALSE\n ELSE COALESCE($5, auto_join_team)\n END\n WHERE id = $1\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Varchar",
+ "Bool",
+ "Uuid",
+ "Bool"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "2c77b982d340967465a952f918b3ebd357faa0b3edc9a8bf325ffafe4b90d3ca"
+}
diff --git a/.sqlx/query-42a6c7ad807c70148c8d347dd06ea6d733efb4c0eb0f1c06d7fea28bf3fef3aa.json b/.sqlx/query-42a6c7ad807c70148c8d347dd06ea6d733efb4c0eb0f1c06d7fea28bf3fef3aa.json
new file mode 100644
index 0000000000..d1ac79a250
--- /dev/null
+++ b/.sqlx/query-42a6c7ad807c70148c8d347dd06ea6d733efb4c0eb0f1c06d7fea28bf3fef3aa.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO comms_channel_participants (channel_id, role, user_id)\n SELECT $1, 'member'::comms_participant_role, user_id\n FROM team_user\n WHERE team_id = $2\n ON CONFLICT (channel_id, user_id) DO UPDATE\n SET role = EXCLUDED.role,\n joined_at = NOW(),\n left_at = NULL\n WHERE comms_channel_participants.left_at IS NOT NULL\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "42a6c7ad807c70148c8d347dd06ea6d733efb4c0eb0f1c06d7fea28bf3fef3aa"
+}
diff --git a/.sqlx/query-e1fc9c7524d0d20844d2cad0402fd1a2058e31c5692d66a0107d9a45c9d83f7b.json b/.sqlx/query-e1fc9c7524d0d20844d2cad0402fd1a2058e31c5692d66a0107d9a45c9d83f7b.json
deleted file mode 100644
index 7448650148..0000000000
--- a/.sqlx/query-e1fc9c7524d0d20844d2cad0402fd1a2058e31c5692d66a0107d9a45c9d83f7b.json
+++ /dev/null
@@ -1,15 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n UPDATE comms_channels\n SET name = $1\n WHERE id = $2\n ",
- "describe": {
- "columns": [],
- "parameters": {
- "Left": [
- "Varchar",
- "Uuid"
- ]
- },
- "nullable": []
- },
- "hash": "e1fc9c7524d0d20844d2cad0402fd1a2058e31c5692d66a0107d9a45c9d83f7b"
-}
diff --git a/apps/web/src/features/channel/Participants/ChannelParticipantsTab.tsx b/apps/web/src/features/channel/Participants/ChannelParticipantsTab.tsx
index 77589fd37e..c0c8dd4708 100644
--- a/apps/web/src/features/channel/Participants/ChannelParticipantsTab.tsx
+++ b/apps/web/src/features/channel/Participants/ChannelParticipantsTab.tsx
@@ -1,19 +1,23 @@
import { useSplitLayout } from '@components/app/split-layout/layout';
-import { useChannelType } from '@core/context/channels';
+import { useChannel, useChannelType } from '@core/context/channels';
import { useUserId } from '@core/context/user';
import { idToEmail } from '@core/user';
import { useChannelParticipantsQuery } from '@queries/channel/channel-participants';
+import { usePatchChannelMutation } from '@queries/channel/channels';
import { useGetOrCreateDirectMessageMutation } from '@queries/channel/get-or-create-dm';
import {
useAddParticipantsMutation,
useRemoveParticipantsMutation,
} from '@queries/channel/participants';
+import { useCurrentTeamQuery } from '@queries/team/teams';
import { ChannelType } from '@service-storage/generated/schemas/channelType';
+import { ParticipantRole } from '@service-storage/generated/schemas/participantRole';
import { Panel } from '@ui';
import { createSignal, Show } from 'solid-js';
import { ChannelBotsPanel } from './ChannelBotsPanel';
import { ChannelJoinLinkButton } from './ChannelJoinLinkButton';
+import { ChannelTeamSettingsPanel } from './ChannelTeamSettingsPanel';
import { ParticipantsAddPanel } from './ParticipantsAddPanel';
import { ParticipantsList } from './ParticipantsList';
import { ParticipantsSearchInput } from './ParticipantsSearchInput';
@@ -27,15 +31,48 @@ export function ChannelParticipantsTab(props: {
}) {
const { replaceOrInsertSplit } = useSplitLayout();
const userId = useUserId();
+ const channel = useChannel(props.channelId);
const channelType = useChannelType(props.channelId);
const participantsQuery = useChannelParticipantsQuery(() => props.channelId);
+ const currentTeamQuery = useCurrentTeamQuery();
+ const patchChannelMutation = usePatchChannelMutation();
const addParticipantsMutation = useAddParticipantsMutation();
const removeParticipantsMutation = useRemoveParticipantsMutation();
const getOrCreateDmMutation = useGetOrCreateDirectMessageMutation();
const [searchQuery, setSearchQuery] = createSignal('');
const participants = () => participantsQuery.data ?? [];
- const canAddParticipants = () => channelType() === ChannelType.private;
+ const currentParticipant = () =>
+ participants().find((participant) => participant.user_id === userId());
+ const canManageChannel = () => {
+ const role = currentParticipant()?.role;
+ return role === ParticipantRole.owner || role === ParticipantRole.admin;
+ };
+ const pendingPatch = () =>
+ patchChannelMutation.isPending ? patchChannelMutation.variables : undefined;
+ const isTeamChannel = () =>
+ channelType() === ChannelType.team ||
+ pendingPatch()?.convert_to_team_channel === true;
+ const autoJoinTeam = () => {
+ const pendingAutoJoin = pendingPatch()?.auto_join_team;
+ return typeof pendingAutoJoin === 'boolean'
+ ? pendingAutoJoin
+ : (channel()?.auto_join_team ?? false);
+ };
+ const supportsTeamSettings = () =>
+ channelType() === ChannelType.private ||
+ channelType() === ChannelType.public ||
+ channelType() === ChannelType.team;
+ const currentTeam = () => currentTeamQuery.data?.team;
+ const canConvertToTeam = () => !isTeamChannel() && !!currentTeam();
+ const conversionUnavailableReason = () => {
+ if (isTeamChannel() || currentTeam()) return undefined;
+ return currentTeamQuery.isLoading
+ ? 'Checking your team membership…'
+ : 'You need to belong to a team before converting this channel.';
+ };
+ const canAddParticipants = () =>
+ channelType() === ChannelType.private || channelType() === ChannelType.team;
const isEditable = () => canAddParticipants();
const filteredParticipants = () => {
@@ -73,6 +110,23 @@ export function ChannelParticipantsTab(props: {
});
};
+ const convertToTeamChannel = () => {
+ if (!canManageChannel() || !canConvertToTeam()) return;
+ patchChannelMutation.mutate({
+ channelId: props.channelId,
+ channel_name: channel()?.name,
+ convert_to_team_channel: true,
+ });
+ };
+
+ const updateAutoJoinTeam = (enabled: boolean) => {
+ if (!canManageChannel() || channelType() !== ChannelType.team) return;
+ patchChannelMutation.mutate({
+ channelId: props.channelId,
+ auto_join_team: enabled,
+ });
+ };
+
const openDirectMessage = (participantId: string) => {
getOrCreateDmMutation.mutate(
{ recipient_id: participantId },
@@ -102,6 +156,17 @@ export function ChannelParticipantsTab(props: {
</Panel.Toolbar>
<Panel.Body>
<div class="flex h-full flex-col">
+ <Show when={canManageChannel() && supportsTeamSettings()}>
+ <ChannelTeamSettingsPanel
+ isTeamChannel={isTeamChannel()}
+ autoJoinTeam={autoJoinTeam()}
+ canConvertToTeam={canConvertToTeam()}
+ conversionUnavailableReason={conversionUnavailableReason()}
+ disabled={patchChannelMutation.isPending}
+ onConvertToTeam={convertToTeamChannel}
+ onAutoJoinTeamChange={updateAutoJoinTeam}
+ />
+ </Show>
<Show when={isEditable()}>
<div class="px-6 py-3 border-b border-edge-muted shrink-0">
<ParticipantsAddPanel
diff --git a/apps/web/src/features/channel/Participants/ChannelTeamSettingsPanel.test.tsx b/apps/web/src/features/channel/Participants/ChannelTeamSettingsPanel.test.tsx
new file mode 100644
index 0000000000..5a80231f66
--- /dev/null
+++ b/apps/web/src/features/channel/Participants/ChannelTeamSettingsPanel.test.tsx
@@ -0,0 +1,74 @@
+/**
+ * @vitest-environment jsdom
+ */
+
+import { fireEvent, render, screen } from '@solidjs/testing-library';
+import { describe, expect, it, vi } from 'vitest';
+import { ChannelTeamSettingsPanel } from './ChannelTeamSettingsPanel';
+
+describe('ChannelTeamSettingsPanel', () => {
+ it('allows converting an eligible channel to a team channel', () => {
+ const onConvertToTeam = vi.fn();
+
+ render(() => (
+ <ChannelTeamSettingsPanel
+ isTeamChannel={false}
+ autoJoinTeam={false}
+ canConvertToTeam
+ disabled={false}
+ onConvertToTeam={onConvertToTeam}
+ onAutoJoinTeamChange={vi.fn()}
+ />
+ ));
+
+ expect(screen.getByText('Team access').closest('section')).not.toBeNull();
+ fireEvent.click(screen.getByRole('switch', { name: 'Team channel' }));
+
+ expect(onConvertToTeam).toHaveBeenCalledOnce();
+ expect(screen.queryByRole('switch', { name: 'Team auto-join' })).toBeNull();
+ });
+
+ it('disables conversion when the user does not have a team', () => {
+ render(() => (
+ <ChannelTeamSettingsPanel
+ isTeamChannel={false}
+ autoJoinTeam={false}
+ canConvertToTeam={false}
+ conversionUnavailableReason="You need to belong to a team."
+ disabled={false}
+ onConvertToTeam={vi.fn()}
+ onAutoJoinTeamChange={vi.fn()}
+ />
+ ));
+
+ expect(screen.getByRole('switch', { name: 'Team channel' })).toHaveProperty(
+ 'disabled',
+ true
+ );
+ expect(screen.getByText('You need to belong to a team.')).toBeTruthy();
+ });
+
+ it('allows toggling auto-join for a team channel', () => {
+ const onAutoJoinTeamChange = vi.fn();
+
+ render(() => (
+ <ChannelTeamSettingsPanel
+ isTeamChannel
+ autoJoinTeam={false}
+ canConvertToTeam={false}
+ disabled={false}
+ onConvertToTeam={vi.fn()}
+ onAutoJoinTeamChange={onAutoJoinTeamChange}
+ />
+ ));
+
+ const teamChannelSwitch = screen.getByRole('switch', {
+ name: 'Team channel',
+ });
+ expect(teamChannelSwitch).toHaveProperty('checked', true);
+ expect(teamChannelSwitch).toHaveProperty('disabled', true);
+
+ fireEvent.click(screen.getByRole('switch', { name: 'Team auto-join' }));
+ expect(onAutoJoinTeamChange).toHaveBeenCalledWith(true);
+ });
+});
diff --git a/apps/web/src/features/channel/Participants/ChannelTeamSettingsPanel.tsx b/apps/web/src/features/channel/Participants/ChannelTeamSettingsPanel.tsx
new file mode 100644
index 0000000000..25342bef5d
--- /dev/null
+++ b/apps/web/src/features/channel/Participants/ChannelTeamSettingsPanel.tsx
@@ -0,0 +1,63 @@
+import { ToggleSwitch } from '@ui';
+import { Show } from 'solid-js';
+
+export function ChannelTeamSettingsPanel(props: {
+ isTeamChannel: boolean;
+ autoJoinTeam: boolean;
+ canConvertToTeam: boolean;
+ conversionUnavailableReason?: string;
+ disabled: boolean;
+ onConvertToTeam: () => void;
+ onAutoJoinTeamChange: (enabled: boolean) => void;
+}) {
+ return (
+ <section class="shrink-0 border-b border-edge-muted text-ink">
+ <div class="flex min-h-10 items-center border-b border-edge-muted px-6 text-sm font-semibold">
+ Team access
+ </div>
+ <div class="divide-y divide-edge-muted px-6">
+ <div class="flex items-center justify-between gap-4 py-3">
+ <div class="min-w-0">
+ <div class="text-sm font-medium">Team channel</div>
+ <p class="text-xs text-ink-muted">
+ {props.isTeamChannel
+ ? 'This channel belongs to your team.'
+ : (props.conversionUnavailableReason ??
+ 'Convert this channel into a team channel. This cannot be undone.')}
+ </p>
+ </div>
+ <ToggleSwitch
+ size="md"
+ checked={props.isTeamChannel}
+ disabled={
+ props.disabled || props.isTeamChannel || !props.canConvertToTeam
+ }
+ onChange={(checked) => checked && props.onConvertToTeam()}
+ label="Team channel"
+ labelClass="sr-only"
+ />
+ </div>
+
+ <Show when={props.isTeamChannel}>
+ <div class="flex items-center justify-between gap-4 py-3">
+ <div class="min-w-0">
+ <div class="text-sm font-medium">Team auto-join</div>
+ <p class="text-xs text-ink-muted">
+ Add current and future team members to this channel
+ automatically.
+ </p>
+ </div>
+ <ToggleSwitch
+ size="md"
+ checked={props.autoJoinTeam}
+ disabled={props.disabled}
+ onChange={props.onAutoJoinTeamChange}
+ label="Team auto-join"
+ labelClass="sr-only"
+ />
+ </div>
+ </Show>
+ </div>
+ </section>
+ );
+}
diff --git a/apps/web/src/lib/queries/channel/channel-participants.ts b/apps/web/src/lib/queries/channel/channel-participants.ts
index 439acc1d2c..ed502d2b6b 100644
--- a/apps/web/src/lib/queries/channel/channel-participants.ts
+++ b/apps/web/src/lib/queries/channel/channel-participants.ts
@@ -27,8 +27,14 @@ export function useChannelParticipantsQuery(channelId: Accessor<string>) {
return useQuery(() => channelParticipantsQueryOptions(channelId()));
}
+export function invalidateChannelParticipants(channelId: string) {
+ return queryClient.invalidateQueries({
+ queryKey: channelKeys.participants(channelId).queryKey,
+ });
+}
+
export function softInvalidateChannelParticipants(channelId: string) {
- queryClient.invalidateQueries({
+ return queryClient.invalidateQueries({
queryKey: channelKeys.participants(channelId).queryKey,
refetchType: 'inactive',
});
diff --git a/apps/web/src/lib/queries/channel/channels.ts b/apps/web/src/lib/queries/channel/channels.ts
index 5a241d7717..ffff5a0032 100644
--- a/apps/web/src/lib/queries/channel/channels.ts
+++ b/apps/web/src/lib/queries/channel/channels.ts
@@ -1,11 +1,19 @@
import { analytics } from '@app/lib/analytics';
+import { toast } from '@core/component/Toast/Toast';
import { throwOnErr } from '@core/util/result';
import { queryClient } from '@queries/client';
import { type MutationCallbacks, withCallbacks } from '@queries/utils';
-import { storageServiceClient } from '@service-storage/client';
+import type { ApiChannelWithLatest } from '@service-storage/channel-list-types';
+import {
+ type MessageResponse,
+ storageServiceClient,
+} from '@service-storage/client';
+import { ChannelType } from '@service-storage/generated/schemas/channelType';
import type { CreateChannelRequest } from '@service-storage/generated/schemas/createChannelRequest';
import type { CreateChannelResponse } from '@service-storage/generated/schemas/createChannelResponse';
+import type { PatchChannelRequest } from '@service-storage/generated/schemas/patchChannelRequest';
import { useMutation, useQuery } from '@tanstack/solid-query';
+import { invalidateChannelParticipants } from './channel-participants';
import { channelKeys } from './keys';
export function useListChannelsQuery() {
@@ -61,3 +69,71 @@ export function useCreateChannelMutation(
),
}));
}
+
+export type PatchChannelParams = PatchChannelRequest & { channelId: string };
+type PatchChannelCallbacks = MutationCallbacks<
+ MessageResponse,
+ Error,
+ PatchChannelParams
+>;
+
+function updateCachedChannel(
+ channels: ApiChannelWithLatest[] | undefined,
+ vars: PatchChannelParams
+): ApiChannelWithLatest[] | undefined {
+ return channels?.map((channel) => {
+ if (channel.id !== vars.channelId) return channel;
+
+ return {
+ ...channel,
+ channel_type:
+ vars.convert_to_team_channel === true
+ ? ChannelType.team
+ : channel.channel_type,
+ auto_join_team:
+ typeof vars.auto_join_team === 'boolean'
+ ? vars.auto_join_team
+ : channel.auto_join_team,
+ };
+ });
+}
+
+/** Patch channel settings and refresh channel/participant state. */
+export function usePatchChannelMutation(callbacks?: PatchChannelCallbacks) {
+ return useMutation(() => ({
+ gcTime: 0,
+ mutationFn: async ({ channelId, ...request }: PatchChannelParams) =>
+ await throwOnErr(() =>
+ storageServiceClient.patchChannel({
+ channel_id: channelId,
+ ...request,
+ })
+ ),
+ ...withCallbacks<MessageResponse, Error, PatchChannelParams>(
+ {
+ onSuccess: async (_data, vars) => {
+ queryClient.setQueryData<ApiChannelWithLatest[]>(
+ channelKeys.listChannels.queryKey,
+ (channels) => updateCachedChannel(channels, vars)
+ );
+ if (typeof vars.auto_join_team === 'boolean') {
+ await invalidateChannelParticipants(vars.channelId);
+ }
+ toast.success(
+ vars.convert_to_team_channel === true
+ ? 'Channel converted to a team channel'
+ : vars.auto_join_team
+ ? 'Team auto-join enabled'
+ : 'Team auto-join disabled'
+ );
+ },
+ onError: (error) => {
+ console.error('failed to update channel settings', error);
+ toast.failure('Failed to update channel settings');
+ },
+ onSettled: () => void invalidateListChannels(),
+ },
+ callbacks
+ ),
+ }));
+}
diff --git a/apps/web/src/lib/service-clients/service-storage/channel-list-types.ts b/apps/web/src/lib/service-clients/service-storage/channel-list-types.ts
index a285f357f7..d477238fde 100644
--- a/apps/web/src/lib/service-clients/service-storage/channel-list-types.ts
+++ b/apps/web/src/lib/service-clients/service-storage/channel-list-types.ts
@@ -10,6 +10,8 @@ import type { LatestMessage } from './generated/schemas/latestMessage';
/** Channel metadata with its participants (channel fields flattened to the top level). */
export type ChannelWithParticipants = Channel & {
+ /** Whether current and future team members automatically join the channel. */
+ auto_join_team: boolean;
participants: ChannelParticipant[];
/** Whether the requesting user is an active participant of the channel. */
is_participant: boolean;
diff --git a/apps/web/src/lib/service-clients/service-storage/client.ts b/apps/web/src/lib/service-clients/service-storage/client.ts
index 917ab3c58e..bd6dd5b78e 100644
--- a/apps/web/src/lib/service-clients/service-storage/client.ts
+++ b/apps/web/src/lib/service-clients/service-storage/client.ts
@@ -655,11 +655,11 @@ export const storageServiceClient = {
},
async patchChannel(args: WithChannelId & PatchChannelRequest) {
- const { channel_id, channel_name } = args;
+ const { channel_id, ...request } = args;
return (
await dssFetch<MessageResponse>(`/channels/${channel_id}`, {
method: 'PATCH',
- body: JSON.stringify({ channel_name }),
+ body: JSON.stringify(request),
})
).map((result) => result);
},
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts
index 599d3b9698..8cd126c9bc 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts
@@ -675,7 +675,9 @@ export * from './paramsLimit';
export * from './paramsSortMethod';
export * from './participantRole';
export * from './patchChannelRequest';
+export * from './patchChannelRequestAutoJoinTeam';
export * from './patchChannelRequestChannelName';
+export * from './patchChannelRequestConvertToTeamChannel';
export * from './patchMessageRequest';
export * from './patchMessageRequestAttachmentIdsToDelete';
export * from './patchMessageRequestAttachmentsToAdd';
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/patchChannelRequest.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/patchChannelRequest.ts
index 5b1d132e6e..a357f00f63 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/patchChannelRequest.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/patchChannelRequest.ts
@@ -4,12 +4,21 @@
* document_storage_service
* OpenAPI spec version: 0.1.0
*/
+import type { PatchChannelRequestAutoJoinTeam } from './patchChannelRequestAutoJoinTeam';
import type { PatchChannelRequestChannelName } from './patchChannelRequestChannelName';
+import type { PatchChannelRequestConvertToTeamChannel } from './patchChannelRequestConvertToTeamChannel';
/**
* Request to patch a channel.
*/
export interface PatchChannelRequest {
+ /** Whether team members should automatically join the channel. */
+ auto_join_team?: PatchChannelRequestAutoJoinTeam;
/** New channel name. */
channel_name?: PatchChannelRequestChannelName;
+ /** Sets whether the channel is a team channel.
+
+`true` converts a non-team channel to a team channel, while `false`
+converts a team channel to a private channel. */
+ convert_to_team_channel?: PatchChannelRequestConvertToTeamChannel;
}
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/patchChannelRequestAutoJoinTeam.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/patchChannelRequestAutoJoinTeam.ts
new file mode 100644
index 0000000000..10e990ac94
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/patchChannelRequestAutoJoinTeam.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Whether team members should automatically join the channel.
+ */
+export type PatchChannelRequestAutoJoinTeam = boolean | null;
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/patchChannelRequestConvertToTeamChannel.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/patchChannelRequestConvertToTeamChannel.ts
new file mode 100644
index 0000000000..866dbc4a9d
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/patchChannelRequestConvertToTeamChannel.ts
@@ -0,0 +1,14 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Sets whether the channel is a team channel.
+
+`true` converts a non-team channel to a team channel, while `false`
+converts a team channel to a private channel.
+ */
+export type PatchChannelRequestConvertToTeamChannel = boolean | null;
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/zod.ts b/apps/web/src/lib/service-clients/service-storage/generated/zod.ts
index 957baf39be..d1d8c6f095 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/zod.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/zod.ts
@@ -1893,7 +1893,17 @@ export const patchChannelParams = zod.object({
export const patchChannelBody = zod
.object({
+ auto_join_team: zod
+ .boolean()
+ .nullish()
+ .describe('Whether team members should automatically join the channel.'),
channel_name: zod.string().nullish().describe('New channel name.'),
+ convert_to_team_channel: zod
+ .boolean()
+ .nullish()
+ .describe(
+ 'Sets whether the channel is a team channel.\n\n`true` converts a non-team channel to a team channel, while `false`\nconverts a team channel to a private channel.'
+ ),
})
.describe('Request to patch a channel.');
diff --git a/apps/web/src/lib/service-clients/service-storage/openapi.json b/apps/web/src/lib/service-clients/service-storage/openapi.json
index 26d6434bf1..f47e13393c 100644
--- a/apps/web/src/lib/service-clients/service-storage/openapi.json
+++ b/apps/web/src/lib/service-clients/service-storage/openapi.json
@@ -16957,9 +16957,17 @@
"type": "object",
"description": "Request to patch a channel.",
"properties": {
+ "auto_join_team": {
+ "type": ["boolean", "null"],
+ "description": "Whether team members should automatically join the channel."
+ },
"channel_name": {
"type": ["string", "null"],
"description": "New channel name."
+ },
+ "convert_to_team_channel": {
+ "type": ["boolean", "null"],
+ "description": "Sets whether the channel is a team channel.\n\n`true` converts a non-team channel to a team channel, while `false`\nconverts a team channel to a private channel."
}
}
},
diff --git a/crates/channels/src/domain/models.rs b/crates/channels/src/domain/models.rs
index 2143a31079..e903f8833a 100644
--- a/crates/channels/src/domain/models.rs
+++ b/crates/channels/src/domain/models.rs
@@ -768,6 +768,13 @@ pub struct GetOrCreateChannelResponse {
pub struct PatchChannelRequest {
/// New channel name.
pub channel_name: Option<String>,
+ /// Sets whether the channel is a team channel.
+ ///
+ /// `true` converts a non-team channel to a team channel, while `false`
+ /// converts a team channel to a private channel.
+ pub convert_to_team_channel: Option<bool>,
+ /// Whether team members should automatically join the channel.
+ pub auto_join_team: Option<bool>,
}
/// New attachment to add to a channel message.
@@ -1295,6 +1302,8 @@ pub struct ChannelListItem {
pub org_id: Option<i64>,
/// Team id.
pub team_id: Option<Uuid>,
+ /// Whether team members automatically join the channel.
+ pub auto_join_team: bool,
/// Creation timestamp.
pub created_at: DateTime<Utc>,
/// Update timestamp.
diff --git a/crates/channels/src/domain/ports.rs b/crates/channels/src/domain/ports.rs
index 5ce4ff70ff..b932c260db 100644
--- a/crates/channels/src/domain/ports.rs
+++ b/crates/channels/src/domain/ports.rs
@@ -266,6 +266,12 @@ pub trait ChannelRepo: Send + Sync + 'static {
team_id: Uuid,
) -> impl Future<Output = Result<bool, Self::Err>> + Send;
+ /// Fetch the team a user belongs to, if any.
+ fn get_user_team_id<'a>(
+ &self,
+ user_id: &MacroUserIdStr<'a>,
+ ) -> impl Future<Output = Result<Option<Uuid>, Self::Err>> + Send;
+
/// Create a channel and return its complete active participant set.
fn create_channel<'a>(
&self,
@@ -311,10 +317,13 @@ pub trait ChannelRepo: Send + Sync + 'static {
) -> impl Future<Output = Result<Option<Uuid>, Self::Err>> + Send;
/// Patch a channel.
+ ///
+ /// `team_id` is the channel's effective team after any requested conversion.
fn patch_channel(
&self,
channel_id: Uuid,
user_id: String,
+ team_id: Option<Uuid>,
req: PatchChannelRequest,
) -> impl Future<Output = Result<(), Self::Err>> + Send;
diff --git a/crates/channels/src/domain/service.rs b/crates/channels/src/domain/service.rs
index a7d9c2859b..b9818a91df 100644
--- a/crates/channels/src/domain/service.rs
+++ b/crates/channels/src/domain/service.rs
@@ -461,7 +461,7 @@ where
&self,
actor: Sender,
channel_id: Uuid,
- req: PatchChannelRequest,
+ mut req: PatchChannelRequest,
) -> Result<(), ChannelMutationErr> {
let actor = require_user_actor(&actor)?;
let info = self
@@ -474,9 +474,62 @@ where
"cannot change channel_name for direct message channels".to_string(),
));
}
+
+ let converting_to_team =
+ req.convert_to_team_channel == Some(true) && info.channel_type != ChannelType::Team;
+ let converting_to_private =
+ req.convert_to_team_channel == Some(false) && info.channel_type == ChannelType::Team;
+ let team_id = if converting_to_team {
+ Some(
+ self.repo
+ .get_user_team_id(&actor)
+ .await
+ .map_err(|e| ChannelMutationErr::Repo(e.into()))?
+ .ok_or_else(|| {
+ ChannelMutationErr::BadRequest(
+ "cannot convert channel because the user does not belong to a team"
+ .to_string(),
+ )
+ })?,
+ )
+ } else if converting_to_private {
+ req.auto_join_team = Some(false);
+ None
+ } else {
+ info.team_id
+ };
+
+ let is_team_channel =
+ info.channel_type == ChannelType::Team && !converting_to_private || converting_to_team;
+ if req.auto_join_team == Some(true) && (!is_team_channel || team_id.is_none()) {
+ return Err(ChannelMutationErr::BadRequest(
+ "auto-join is only available for team channels".to_string(),
+ ));
+ }
+
+ if converting_to_team {
+ let requested_name = req
+ .channel_name
+ .as_deref()
+ .filter(|name| !name.trim().is_empty());
+ let stored_name = info.name.as_deref().filter(|name| !name.trim().is_empty());
+ if requested_name.is_none() {
+ req.channel_name = if stored_name.is_some() {
+ None
+ } else {
+ Some(
+ self.repo
+ .resolve_channel_name(&info, actor.clone())
+ .await
+ .map_err(|e| ChannelMutationErr::Repo(e.into()))?,
+ )
+ };
+ }
+ }
+
let channel_name = req.channel_name.clone();
self.repo
- .patch_channel(channel_id, actor.as_ref().to_string(), req)
+ .patch_channel(channel_id, actor.as_ref().to_string(), team_id, req)
.await
.map_err(|e| ChannelMutationErr::Repo(e.into()))?;
if channel_name.is_some() {
diff --git a/crates/channels/src/domain/service/test.rs b/crates/channels/src/domain/service/test.rs
index 621933622b..318bcec2c4 100644
--- a/crates/channels/src/domain/service/test.rs
+++ b/crates/channels/src/domain/service/test.rs
@@ -284,7 +284,11 @@ struct FakeMutationRepo {
struct FakeMutationRepoState {
channel_id: Uuid,
+ channel_name: Option<String>,
channel_type: ChannelType,
+ channel_team_id: Option<Uuid>,
+ user_team_id: Option<Uuid>,
+ user_team_id_lookups: usize,
join_code: Option<Uuid>,
message: MutatedMessage,
owner: String,
@@ -295,6 +299,7 @@ struct FakeMutationRepoState {
patched_content: Option<String>,
activity_upserts: usize,
removed_participants: Vec<String>,
+ channel_patches: Vec<(PatchChannelRequest, Option<Uuid>)>,
created_mentions: Vec<SimpleMention>,
synced_mentions: Vec<SimpleMention>,
}
@@ -317,7 +322,11 @@ impl FakeMutationRepo {
Self {
state: Arc::new(Mutex::new(FakeMutationRepoState {
channel_id,
+ channel_name: Some("Project".to_string()),
channel_type: ChannelType::Private,
+ channel_team_id: None,
+ user_team_id: None,
+ user_team_id_lookups: 0,
join_code: None,
owner: sender.to_string(),
message,
@@ -345,6 +354,7 @@ impl FakeMutationRepo {
patched_content: None,
activity_upserts: 0,
removed_participants: vec![],
+ channel_patches: vec![],
created_mentions: vec![],
synced_mentions: vec![],
})),
@@ -462,10 +472,10 @@ impl ChannelRepo for FakeMutationRepo {
let state = self.state.lock().unwrap();
Ok(ChannelInfo {
id: channel_id,
- name: Some("Project".to_string()),
+ name: state.channel_name.clone(),
channel_type: state.channel_type,
org_id: None,
- team_id: None,
+ team_id: state.channel_team_id,
})
}
@@ -482,10 +492,10 @@ impl ChannelRepo for FakeMutationRepo {
let state = self.state.lock().unwrap();
Ok((state.join_code == Some(join_code)).then(|| ChannelInfo {
id: state.channel_id,
- name: Some("Project".to_string()),
+ name: state.channel_name.clone(),
channel_type: state.channel_type,
org_id: None,
- team_id: None,
+ team_id: state.channel_team_id,
}))
}
@@ -521,6 +531,15 @@ impl ChannelRepo for FakeMutationRepo {
Ok(true)
}
+ async fn get_user_team_id(
+ &self,
+ _user_id: &MacroUserIdStr<'_>,
+ ) -> Result<Option<Uuid>, Self::Err> {
+ let mut state = self.state.lock().unwrap();
+ state.user_team_id_lookups += 1;
+ Ok(state.user_team_id)
+ }
+
async fn create_channel(
&self,
owner_id: MacroUserIdStr<'_>,
@@ -589,8 +608,14 @@ impl ChannelRepo for FakeMutationRepo {
&self,
_channel_id: Uuid,
_user_id: String,
- _req: PatchChannelRequest,
+ team_id: Option<Uuid>,
+ req: PatchChannelRequest,
) -> Result<(), Self::Err> {
+ self.state
+ .lock()
+ .unwrap()
+ .channel_patches
+ .push((req, team_id));
Ok(())
}
@@ -2114,6 +2139,8 @@ async fn patch_channel_dispatches_channel_updated() {
channel_id,
PatchChannelRequest {
channel_name: Some("Renamed".to_string()),
+ convert_to_team_channel: None,
+ auto_join_team: None,
},
)
.await
@@ -2137,7 +2164,11 @@ async fn noop_patch_channel_dispatches_nothing() {
svc.patch_channel(
sender("macro|[email protected]"),
channel_id,
- PatchChannelRequest { channel_name: None },
+ PatchChannelRequest {
+ channel_name: None,
+ convert_to_team_channel: None,
+ auto_join_team: None,
+ },
)
.await
.unwrap();
@@ -2145,6 +2176,237 @@ async fn noop_patch_channel_dispatches_nothing() {
assert!(events.events.lock().unwrap().is_empty());
}
+#[tokio::test]
+async fn patch_channel_conversion_uses_the_users_team() {
+ let channel_id = Uuid::new_v4();
+ let team_id = Uuid::new_v4();
+ let repo = FakeMutationRepo::new(channel_id, "macro|[email protected]");
+ repo.state.lock().unwrap().user_team_id = Some(team_id);
+ let svc = mutation_service(
+ repo.clone(),
+ FakeEvents::default(),
+ FakeReferenceSharing::default(),
+ );
+
+ svc.patch_channel(
+ sender("macro|[email protected]"),
+ channel_id,
+ PatchChannelRequest {
+ channel_name: None,
+ convert_to_team_channel: Some(true),
+ auto_join_team: None,
+ },
+ )
+ .await
+ .unwrap();
+
+ let state = repo.state.lock().unwrap();
+ assert_eq!(state.user_team_id_lookups, 1);
+ assert_eq!(state.channel_patches.len(), 1);
+ assert_eq!(state.channel_patches[0].1, Some(team_id));
+ assert_eq!(
+ state.channel_patches[0].0.convert_to_team_channel,
+ Some(true)
+ );
+}
+
+#[tokio::test]
+async fn patch_channel_conversion_names_an_unnamed_private_channel() {
+ let channel_id = Uuid::new_v4();
+ let team_id = Uuid::new_v4();
+ let repo = FakeMutationRepo::new(channel_id, "macro|[email protected]");
+ {
+ let mut state = repo.state.lock().unwrap();
+ state.channel_name = None;
+ state.user_team_id = Some(team_id);
+ }
+ let svc = mutation_service(
+ repo.clone(),
+ FakeEvents::default(),
+ FakeReferenceSharing::default(),
+ );
+
+ svc.patch_channel(
+ sender("macro|[email protected]"),
+ channel_id,
+ PatchChannelRequest {
+ channel_name: None,
+ convert_to_team_channel: Some(true),
+ auto_join_team: None,
+ },
+ )
+ .await
+ .unwrap();
+
+ let state = repo.state.lock().unwrap();
+ assert_eq!(state.channel_patches.len(), 1);
+ assert_eq!(
+ state.channel_patches[0].0.channel_name.as_deref(),
+ Some("Project")
+ );
+}
+
+#[tokio::test]
+async fn patch_team_channel_conversion_to_private_clears_team_settings() {
+ let channel_id = Uuid::new_v4();
+ let team_id = Uuid::new_v4();
+ let repo = FakeMutationRepo::new(channel_id, "macro|[email protected]");
+ {
+ let mut state = repo.state.lock().unwrap();
+ state.channel_type = ChannelType::Team;
+ state.channel_team_id = Some(team_id);
+ }
+ let svc = mutation_service(
+ repo.clone(),
+ FakeEvents::default(),
+ FakeReferenceSharing::default(),
+ );
+
+ svc.patch_channel(
+ sender("macro|[email protected]"),
+ channel_id,
+ PatchChannelRequest {
+ channel_name: None,
+ convert_to_team_channel: Some(false),
+ auto_join_team: Some(true),
+ },
+ )
+ .await
+ .unwrap();
+
+ let state = repo.state.lock().unwrap();
+ assert_eq!(state.user_team_id_lookups, 0);
+ assert_eq!(state.channel_patches.len(), 1);
+ assert_eq!(state.channel_patches[0].1, None);
+ assert_eq!(
+ state.channel_patches[0].0.convert_to_team_channel,
+ Some(false)
+ );
+ assert_eq!(state.channel_patches[0].0.auto_join_team, Some(false));
+}
+
+#[tokio::test]
+async fn patch_channel_conversion_requires_the_user_to_have_a_team() {
+ let channel_id = Uuid::new_v4();
+ let repo = FakeMutationRepo::new(channel_id, "macro|[email protected]");
+ let svc = mutation_service(
+ repo.clone(),
+ FakeEvents::default(),
+ FakeReferenceSharing::default(),
+ );
+
+ let err = svc
+ .patch_channel(
+ sender("macro|[email protected]"),
+ channel_id,
+ PatchChannelRequest {
+ channel_name: None,
+ convert_to_team_channel: Some(true),
+ auto_join_team: None,
+ },
+ )
+ .await
+ .unwrap_err();
+
+ assert!(matches!(err, ChannelMutationErr::BadRequest(_)));
+ let state = repo.state.lock().unwrap();
+ assert_eq!(state.user_team_id_lookups, 1);
+ assert!(state.channel_patches.is_empty());
+}
+
+#[tokio::test]
+async fn patch_channel_rejects_enabling_auto_join_on_a_non_team_channel() {
+ let channel_id = Uuid::new_v4();
+ let repo = FakeMutationRepo::new(channel_id, "macro|[email protected]");
+ let svc = mutation_service(
+ repo.clone(),
+ FakeEvents::default(),
+ FakeReferenceSharing::default(),
+ );
+
+ let err = svc
+ .patch_channel(
+ sender("macro|[email protected]"),
+ channel_id,
+ PatchChannelRequest {
+ channel_name: None,
+ convert_to_team_channel: None,
+ auto_join_team: Some(true),
+ },
+ )
+ .await
+ .unwrap_err();
+
+ assert!(matches!(err, ChannelMutationErr::BadRequest(_)));
+ let state = repo.state.lock().unwrap();
+ assert_eq!(state.user_team_id_lookups, 0);
+ assert!(state.channel_patches.is_empty());
+}
+
+#[tokio::test]
+async fn patch_team_channel_auto_join_uses_its_existing_team() {
+ let channel_id = Uuid::new_v4();
+ let team_id = Uuid::new_v4();
+ let repo = FakeMutationRepo::new(channel_id, "macro|[email protected]");
+ {
+ let mut state = repo.state.lock().unwrap();
+ state.channel_type = ChannelType::Team;
+ state.channel_team_id = Some(team_id);
+ }
+ let svc = mutation_service(
+ repo.clone(),
+ FakeEvents::default(),
+ FakeReferenceSharing::default(),
+ );
+
+ svc.patch_channel(
+ sender("macro|[email protected]"),
+ channel_id,
+ PatchChannelRequest {
+ channel_name: None,
+ convert_to_team_channel: None,
+ auto_join_team: Some(true),
+ },
+ )
+ .await
+ .unwrap();
+
+ let state = repo.state.lock().unwrap();
+ assert_eq!(state.user_team_id_lookups, 0);
+ assert_eq!(state.channel_patches.len(), 1);
+ assert_eq!(state.channel_patches[0].1, Some(team_id));
+ assert_eq!(state.channel_patches[0].0.auto_join_team, Some(true));
+}
+
+#[tokio::test]
+async fn patch_channel_allows_disabling_auto_join_without_a_team() {
+ let channel_id = Uuid::new_v4();
+ let repo = FakeMutationRepo::new(channel_id, "macro|[email protected]");
+ let svc = mutation_service(
+ repo.clone(),
+ FakeEvents::default(),
+ FakeReferenceSharing::default(),
+ );
+
+ svc.patch_channel(
+ sender("macro|[email protected]"),
+ channel_id,
+ PatchChannelRequest {
+ channel_name: None,
+ convert_to_team_channel: None,
+ auto_join_team: Some(false),
+ },
+ )
+ .await
+ .unwrap();
+
+ let state = repo.state.lock().unwrap();
+ assert_eq!(state.user_team_id_lookups, 0);
+ assert_eq!(state.channel_patches.len(), 1);
+ assert_eq!(state.channel_patches[0].1, None);
+ assert_eq!(state.channel_patches[0].0.auto_join_team, Some(false));
+}
+
#[tokio::test]
async fn remove_participants_dispatches_participants_removed() {
let channel_id = Uuid::new_v4();
diff --git a/crates/channels/src/inbound/list_router.rs b/crates/channels/src/inbound/list_router.rs
index b1a46fba99..1f20e0a002 100644
--- a/crates/channels/src/inbound/list_router.rs
+++ b/crates/channels/src/inbound/list_router.rs
@@ -282,6 +282,8 @@ pub struct Channel {
pub org_id: Option<u32>,
/// id of the team this channel belongs to
pub team_id: Option<Uuid>,
+ /// whether team members automatically join the channel
+ pub auto_join_team: bool,
/// timestamp of when the channel was created
pub created_at: chrono::DateTime<chrono::Utc>,
/// timestamp of when the channel was last updated
@@ -299,6 +301,7 @@ impl Channel {
channel_type: ChannelType::new_from_domain(value.channel_type),
org_id: value.org_id.and_then(|org_id| u32::try_from(org_id).ok()),
team_id: value.team_id,
+ auto_join_team: value.auto_join_team,
created_at: value.created_at,
updated_at: value.updated_at,
owner_id: value.owner_id,
diff --git a/crates/channels/src/outbound/pg_channels_repo.rs b/crates/channels/src/outbound/pg_channels_repo.rs
index c054488ad0..aa1825a75f 100644
--- a/crates/channels/src/outbound/pg_channels_repo.rs
+++ b/crates/channels/src/outbound/pg_channels_repo.rs
@@ -729,6 +729,7 @@ static CHANNEL_LIST_SELECT: &str = r#"
uc.channel_type as "channel_type",
uc.org_id as "org_id",
uc.team_id as "team_id",
+ uc.auto_join_team as "auto_join_team",
uc.created_at as "created_at",
uc.updated_at as "updated_at",
uc.owner_id as "owner_id",
@@ -1120,6 +1121,7 @@ struct ChannelListRow {
channel_type: ChannelType,
org_id: Option<i64>,
team_id: Option<Uuid>,
+ auto_join_team: bool,
created_at: DateTime<Utc>,
updated_at: DateTime<Utc>,
owner_id: String,
@@ -1136,6 +1138,7 @@ impl ChannelListRow {
channel_type: self.channel_type,
org_id: self.org_id,
team_id: self.team_id,
+ auto_join_team: self.auto_join_team,
created_at: self.created_at,
updated_at: self.updated_at,
owner_id: MacroUserIdStr::parse_from_str(&self.owner_id)
@@ -1190,6 +1193,7 @@ impl ChannelListRepo for PgChannelsRepo {
channel_type: row.try_get("channel_type")?,
org_id: row.try_get("org_id")?,
team_id: row.try_get("team_id")?,
+ auto_join_team: row.try_get("auto_join_team")?,
created_at: row.try_get("created_at")?,
updated_at: row.try_get("updated_at")?,
owner_id: row.try_get("owner_id")?,
@@ -2732,6 +2736,23 @@ impl ChannelRepo for PgChannelsRepo {
Ok(has_team)
}
+ async fn get_user_team_id(
+ &self,
+ user_id: &MacroUserIdStr<'_>,
+ ) -> Result<Option<Uuid>, Self::Err> {
+ sqlx::query_scalar!(
+ r#"
+ SELECT team_id
+ FROM team_user
+ WHERE user_id = $1
+ "#,
+ user_id.as_ref(),
+ )
+ .fetch_optional(&self.pool)
+ .await
+ .context("unable to get user's team")
+ }
+
async fn create_channel(
&self,
owner_id: MacroUserIdStr<'_>,
@@ -2990,8 +3011,21 @@ impl ChannelRepo for PgChannelsRepo {
&self,
channel_id: Uuid,
user_id: String,
+ team_id: Option<Uuid>,
req: PatchChannelRequest,
) -> Result<(), Self::Err> {
+ let PatchChannelRequest {
+ channel_name,
+ convert_to_team_channel,
+ auto_join_team,
+ } = req;
+ let enables_auto_join =
+ auto_join_team == Some(true) && convert_to_team_channel != Some(false);
+ if (convert_to_team_channel == Some(true) || enables_auto_join) && team_id.is_none() {
+ anyhow::bail!("team id is required to patch team channel settings");
+ }
+
+ let mut transaction = self.pool.begin().await?;
let row = sqlx::query_as!(
ExistsRow,
r#"
@@ -3009,7 +3043,7 @@ impl ChannelRepo for PgChannelsRepo {
channel_id,
user_id,
)
- .fetch_one(&self.pool)
+ .fetch_one(&mut *transaction)
.await
.context("failed to check user authorization")?;
@@ -3019,19 +3053,62 @@ impl ChannelRepo for PgChannelsRepo {
);
}
- if let Some(channel_name) = req.channel_name {
+ sqlx::query!(
+ r#"
+ UPDATE comms_channels
+ SET name = COALESCE($2, name),
+ channel_type = CASE
+ WHEN $3 IS TRUE THEN 'team'::comms_channel_type
+ WHEN $3 IS FALSE AND channel_type = 'team'::comms_channel_type
+ THEN 'private'::comms_channel_type
+ ELSE channel_type
+ END,
+ team_id = CASE
+ WHEN $3 IS TRUE THEN $4
+ WHEN $3 IS FALSE AND channel_type = 'team'::comms_channel_type THEN NULL
+ ELSE team_id
+ END,
+ auto_join_team = CASE
+ WHEN $3 IS FALSE AND channel_type = 'team'::comms_channel_type THEN FALSE
+ ELSE COALESCE($5, auto_join_team)
+ END
+ WHERE id = $1
+ "#,
+ channel_id,
+ channel_name,
+ convert_to_team_channel,
+ team_id,
+ auto_join_team,
+ )
+ .execute(&mut *transaction)
+ .await
+ .context("unable to patch channel")?;
+
+ if enables_auto_join {
sqlx::query!(
r#"
- UPDATE comms_channels
- SET name = $1
- WHERE id = $2
+ INSERT INTO comms_channel_participants (channel_id, role, user_id)
+ SELECT $1, 'member'::comms_participant_role, user_id
+ FROM team_user
+ WHERE team_id = $2
+ ON CONFLICT (channel_id, user_id) DO UPDATE
+ SET role = EXCLUDED.role,
+ joined_at = NOW(),
+ left_at = NULL
+ WHERE comms_channel_participants.left_at IS NOT NULL
"#,
- channel_name,
channel_id,
+ team_id,
)
- .execute(&self.pool)
- .await?;
+ .execute(&mut *transaction)
+ .await
+ .context("unable to add current team members to channel")?;
}
+
+ transaction
+ .commit()
+ .await
+ .context("unable to commit channel patch")?;
Ok(())
}
diff --git a/crates/channels/src/outbound/pg_channels_repo/tests.rs b/crates/channels/src/outbound/pg_channels_repo/tests.rs
index b26c81e9c3..5a20bd4959 100644
--- a/crates/channels/src/outbound/pg_channels_repo/tests.rs
+++ b/crates/channels/src/outbound/pg_channels_repo/tests.rs
@@ -2,6 +2,7 @@ use crate::domain::models::{
AttachmentEntityReference, BotId, BotSenderProfile, ChannelMessageFilters, ChannelType,
CreateChannelRequest, CreateEntityMentionOptions, GetChannelsParams, GetChannelsRequest,
GetThreadReplyRowsRequest, MessagePageDirection, NotificationFilters, ParticipantRole,
+ PatchChannelRequest,
};
use crate::domain::ports::{ChannelListRepo, ChannelRepo};
use crate::outbound::pg_channels_repo::PgChannelsRepo;
@@ -14,7 +15,10 @@ use macro_db_migrator::MACRO_DB_MIGRATIONS;
use macro_user_id::user_id::MacroUserIdStr;
use models_pagination::{CreatedAt, Cursor, CursorVal, Query, SimpleSortMethod};
use sqlx::{Pool, Postgres};
-use std::{collections::HashSet, sync::Arc};
+use std::{
+ collections::{HashMap, HashSet},
+ sync::Arc,
+};
use uuid::Uuid;
const NO_FILTERS: ChannelMessageFilters = ChannelMessageFilters {
@@ -36,6 +40,7 @@ const TEAM_A_AUTO_ACTIVE: Uuid = Uuid::from_u128(0x00000000_0000_0000_0000_00000
const TEAM_A_AUTO_LEFT: Uuid = Uuid::from_u128(0x00000000_0000_0000_0000_000000000c12);
const TEAM_A_MANUAL: Uuid = Uuid::from_u128(0x00000000_0000_0000_0000_000000000c13);
const TEAM_B_AUTO: Uuid = Uuid::from_u128(0x00000000_0000_0000_0000_000000000c21);
+const TEAM_OWNER_A: &str = "macro|[email protected]";
const MSG1: Uuid = Uuid::from_u128(0x00000000_0000_0000_0000_000000000001);
const MSG2: Uuid = Uuid::from_u128(0x00000000_0000_0000_0000_000000000002);
const MSG3: Uuid = Uuid::from_u128(0x00000000_0000_0000_0000_000000000003);
@@ -121,6 +126,12 @@ async fn channel_list_flags_active_participation(pool: Pool<Postgres>) {
HashSet::from([TEAM_A_AUTO_ACTIVE, TEAM_A_MANUAL, TEAM_B_AUTO])
);
assert!(channels.iter().all(|c| c.is_participant));
+ let auto_join_by_id: HashMap<_, _> = channels
+ .iter()
+ .map(|channel| (channel.channel.id, channel.channel.auto_join_team))
+ .collect();
+ assert_eq!(auto_join_by_id.get(&TEAM_A_AUTO_ACTIVE), Some(&true));
+ assert_eq!(auto_join_by_id.get(&TEAM_A_MANUAL), Some(&false));
}
#[sqlx::test(
@@ -323,6 +334,178 @@ async fn create_channel_persists_auto_join_team_and_adds_current_members(pool: P
);
}
+#[sqlx::test(
+ fixtures(path = "../../../fixtures", scripts("channels_repo")),
+ migrator = "MACRO_DB_MIGRATIONS"
+)]
+async fn patch_channel_converts_to_team_and_updates_auto_join_members(pool: Pool<Postgres>) {
+ let repo = repo(pool.clone());
+ let user_id = macro_user_id(TEAM_OWNER_A);
+ sqlx::query!(
+ r#"
+ INSERT INTO team_user (user_id, team_id, team_role)
+ VALUES ($1, $2, 'admin'::team_role)
+ "#,
+ TEAM_OWNER_A,
+ TEAM_A,
+ )
+ .execute(&pool)
+ .await
+ .unwrap();
+ sqlx::query!(
+ r#"
+ INSERT INTO comms_channel_participants (channel_id, user_id, role)
+ VALUES ($1, $2, 'admin'::comms_participant_role)
+ "#,
+ CH1,
+ TEAM_OWNER_A,
+ )
+ .execute(&pool)
+ .await
+ .unwrap();
+
+ assert_eq!(repo.get_user_team_id(&user_id).await.unwrap(), Some(TEAM_A));
+
+ repo.patch_channel(
+ CH1,
+ TEAM_OWNER_A.to_string(),
+ Some(TEAM_A),
+ PatchChannelRequest {
+ channel_name: None,
+ convert_to_team_channel: Some(true),
+ auto_join_team: Some(true),
+ },
+ )
+ .await
+ .unwrap();
+
+ let channel = sqlx::query!(
+ r#"
+ SELECT
+ channel_type AS "channel_type: ChannelType",
+ team_id,
+ auto_join_team
+ FROM comms_channels
+ WHERE id = $1
+ "#,
+ CH1,
+ )
+ .fetch_one(&pool)
+ .await
+ .unwrap();
+ assert_eq!(channel.channel_type, ChannelType::Team);
+ assert_eq!(channel.team_id, Some(TEAM_A));
+ assert!(channel.auto_join_team);
+
+ let rejoined_team_member = sqlx::query!(
+ r#"
+ SELECT role AS "role: ParticipantRole", left_at
+ FROM comms_channel_participants
+ WHERE channel_id = $1 AND user_id = $2
+ "#,
+ CH1,
+ LEFT_USER,
+ )
+ .fetch_one(&pool)
+ .await
+ .unwrap();
+ assert_eq!(rejoined_team_member.role, ParticipantRole::Member);
+ assert!(rejoined_team_member.left_at.is_none());
+
+ let participant_count = sqlx::query_scalar!(
+ "SELECT COUNT(*) FROM comms_channel_participants WHERE channel_id = $1",
+ CH1,
+ )
+ .fetch_one(&pool)
+ .await
+ .unwrap();
+
+ repo.patch_channel(
+ CH1,
+ TEAM_OWNER_A.to_string(),
+ Some(TEAM_A),
+ PatchChannelRequest {
+ channel_name: None,
+ convert_to_team_channel: None,
+ auto_join_team: Some(false),
+ },
+ )
+ .await
+ .unwrap();
+
+ let auto_join_team = sqlx::query_scalar!(
+ "SELECT auto_join_team FROM comms_channels WHERE id = $1",
+ CH1,
+ )
+ .fetch_one(&pool)
+ .await
+ .unwrap();
+ let participant_count_after = sqlx::query_scalar!(
+ "SELECT COUNT(*) FROM comms_channel_participants WHERE channel_id = $1",
+ CH1,
+ )
+ .fetch_one(&pool)
+ .await
+ .unwrap();
+ assert!(!auto_join_team);
+ assert_eq!(participant_count_after, participant_count);
+}
+
+#[sqlx::test(
+ fixtures(path = "../../../fixtures", scripts("channels_repo")),
+ migrator = "MACRO_DB_MIGRATIONS"
+)]
+async fn patch_team_channel_converts_to_private_and_clears_team_settings(pool: Pool<Postgres>) {
+ let repo = repo(pool.clone());
+ let participant_count = sqlx::query_scalar!(
+ "SELECT COUNT(*) FROM comms_channel_participants WHERE channel_id = $1",
+ TEAM_A_AUTO_ACTIVE,
+ )
+ .fetch_one(&pool)
+ .await
+ .unwrap();
+
+ repo.patch_channel(
+ TEAM_A_AUTO_ACTIVE,
+ LEFT_USER.to_string(),
+ None,
+ PatchChannelRequest {
+ channel_name: None,
+ convert_to_team_channel: Some(false),
+ auto_join_team: Some(true),
+ },
+ )
+ .await
+ .unwrap();
+
+ let channel = sqlx::query!(
+ r#"
+ SELECT
+ channel_type AS "channel_type: ChannelType",
+ team_id,
+ auto_join_team
+ FROM comms_channels
+ WHERE id = $1
+ "#,
+ TEAM_A_AUTO_ACTIVE,
+ )
+ .fetch_one(&pool)
+ .await
+ .unwrap();
+ assert_eq!(channel.channel_type, ChannelType::Private);
+ assert_eq!(channel.team_id, None);
+ assert!(!channel.auto_join_team);
+
+ let participant_count_after = sqlx::query_scalar!(
+ "SELECT COUNT(*) FROM comms_channel_participants WHERE channel_id = $1",
+ TEAM_A_AUTO_ACTIVE,
+ )
+ .fetch_one(&pool)
+ .await
+ .unwrap();
+ assert_eq!(participant_count_after, participant_count);
+}
+
#[sqlx::test(
fixtures(path = "../../../fixtures", scripts("channels_repo")),
migrator = "MACRO_DB_MIGRATIONS"