feat: slack integration frontend complete

This commit is contained in:
kunal_17 2023-04-21 22:21:25 +05:30
parent 6a0a272386
commit 277c36cfdb
9 changed files with 159 additions and 181 deletions

View File

@ -11,7 +11,7 @@ import IntegrationService from "services/integration";
import useToast from "hooks/use-toast"; import useToast from "hooks/use-toast";
import useIntegrationPopup from "hooks/use-integration-popup"; import useIntegrationPopup from "hooks/use-integration-popup";
// ui // ui
import { DangerButton, Loader, SecondaryButton } from "components/ui"; import { DangerButton, Loader, PrimaryButton } from "components/ui";
// icons // icons
import GithubLogo from "public/services/github.png"; import GithubLogo from "public/services/github.png";
import SlackLogo from "public/services/slack.png"; import SlackLogo from "public/services/slack.png";
@ -33,7 +33,7 @@ const integrationDetails: { [key: string]: any } = {
}, },
slack: { slack: {
logo: SlackLogo, logo: SlackLogo,
installed: "Activate Slack integrations on individual projects to sync with specific cahnnels.", installed: "Activate Slack integrations on individual projects to sync with specific channels.",
notInstalled: "Connect with Slack with your Plane workspace to sync project issues.", notInstalled: "Connect with Slack with your Plane workspace to sync project issues.",
}, },
}; };
@ -139,9 +139,9 @@ export const SingleIntegrationCard: React.FC<Props> = ({ integration }) => {
{deletingIntegration ? "Removing..." : "Remove installation"} {deletingIntegration ? "Removing..." : "Remove installation"}
</DangerButton> </DangerButton>
) : ( ) : (
<SecondaryButton onClick={startAuth} loading={isInstalling}> <PrimaryButton onClick={startAuth} loading={isInstalling}>
{isInstalling ? "Installing..." : "Add installation"} {isInstalling ? "Installing..." : "Add installation"}
</SecondaryButton> </PrimaryButton>
) )
) : ( ) : (
<Loader> <Loader>

View File

@ -1,85 +1,100 @@
import React,{useState} from "react"; import React, { useState, useEffect } from "react";
import { useRouter } from "next/router"; import { useRouter } from "next/router";
import useSWR, { mutate } from "swr"; import useSWR, { mutate } from "swr";
// services // services
import projectService from "services/project.service"; import appinstallationsService from "services/app-installations.service";
import IntegrationService from "services/integration";
// ui // ui
import { DangerButton, Loader, SecondaryButton } from "components/ui"; import { Loader } from "components/ui";
// hooks // hooks
import useToast from "hooks/use-toast"; import useToast from "hooks/use-toast";
import useIntegrationPopup from "hooks/use-integration-popup"; import useIntegrationPopup from "hooks/use-integration-popup";
// types // types
import { IAppIntegration, IWorkspaceIntegration } from "types"; import { IWorkspaceIntegration } from "types";
// fetch-keys // fetch-keys
import { WORKSPACE_INTEGRATIONS } from "constants/fetch-keys"; import { SLACK_CHANNEL_INFO } from "constants/fetch-keys";
type Props = { type Props = {
integration: IWorkspaceIntegration; integration: IWorkspaceIntegration;
}; };
export const SelectChannel: React.FC<Props> = ({ export const SelectChannel: React.FC<Props> = ({ integration }) => {
integration, const [deletingProjectSync, setDeletingProjectSync] = useState(false);
}) => {
const [deletingIntegration, setDeletingIntegration] = useState(false);
const router = useRouter(); const router = useRouter();
const { workspaceSlug } = router.query; const { workspaceSlug, projectId } = router.query;
const { setToastAlert } = useToast(); const { startAuth } = useIntegrationPopup("slackChannel", integration.id);
const { startAuth, isConnecting: isInstalling } = useIntegrationPopup("slackChannel"); const { data: projectIntegration } = useSWR(
workspaceSlug && projectId && integration.id
const { data: workspaceIntegrations } = useSWR( ? SLACK_CHANNEL_INFO(workspaceSlug as string, projectId as string)
workspaceSlug ? WORKSPACE_INTEGRATIONS(workspaceSlug as string) : null, : null,
() => () =>
workspaceSlug workspaceSlug && projectId && integration.id
? IntegrationService.getWorkspaceIntegrationsList(workspaceSlug as string) ? appinstallationsService.getSlackChannelDetail(
: null workspaceSlug as string,
projectId as string,
integration.id as string
)
: null
); );
const isInstalled = workspaceIntegrations?.find( useEffect(() => {
(i: any) => i.integration_detail.id === integration.id if (projectIntegration?.length > 0) {
); setDeletingProjectSync(true);
}
if (projectIntegration?.length === 0) {
setDeletingProjectSync(false);
}
}, [projectIntegration]);
const handleRemoveIntegration = async () => { const handleDelete = async () => {
if (!workspaceSlug || !integration || !workspaceIntegrations) return; if (projectIntegration.length === 0) return;
mutate(SLACK_CHANNEL_INFO, (prevData: any) => {
const workspaceIntegrationId = workspaceIntegrations?.find( if (!prevData) return;
(i) => i.integration === integration.id return prevData.id !== integration.id;
)?.id; }).then(() => setDeletingProjectSync(false));
appinstallationsService
setDeletingIntegration(true); .removeSlackChannel(
await IntegrationService.deleteWorkspaceIntegration(
workspaceSlug as string, workspaceSlug as string,
workspaceIntegrationId ?? "" projectId as string,
integration.id as string,
projectIntegration?.[0]?.id
) )
.then(() => { .catch((err) => console.log(err));
setDeletingIntegration(false); };
})
.catch(() => { const handleAuth = async () => {
setDeletingIntegration(false); await startAuth();
}); setDeletingProjectSync(true);
}; };
return ( return (
<> <>
{workspaceIntegrations ? ( {projectIntegration ? (
isInstalled ? ( <button
<DangerButton onClick={handleRemoveIntegration} loading={deletingIntegration}> type="button"
{deletingIntegration ? "Removing..." : "Remove channel"} className={`relative inline-flex h-6 w-11 flex-shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200 ease-in-out focus:outline-none ${
</DangerButton> projectIntegration.length > 0 && deletingProjectSync ? "bg-green-500" : "bg-gray-200"
) : ( }`}
<SecondaryButton onClick={startAuth} loading={isInstalling}> role="switch"
{isInstalling ? "Adding..." : "Add channel"} aria-checked
</SecondaryButton> onClick={() => {
) deletingProjectSync ? handleDelete() : handleAuth();
}}
>
<span
aria-hidden="true"
className={`inline-block h-5 w-5 transform rounded-full bg-white shadow ring-0 transition duration-200 ease-in-out ${
projectIntegration.length > 0 && deletingProjectSync
? "translate-x-5"
: "translate-x-0"
}`}
/>
</button>
) : ( ) : (
<Loader> <Loader>
<Loader.Item height="35px" width="150px" /> <Loader.Item height="35px" width="150px" />

View File

@ -112,7 +112,7 @@ export const SingleIntegration: React.FC<Props> = ({ integration }) => {
{integration.integration_detail.provider === "github" {integration.integration_detail.provider === "github"
? "Select GitHub repository to enable sync." ? "Select GitHub repository to enable sync."
: integration.integration_detail.provider === "slack" : integration.integration_detail.provider === "slack"
? "Select Slack channel to enable sync." ? "Connect your slack channel to this project to get regular updates. Control which notification you want to receive"
: null} : null}
</p> </p>
</div> </div>

View File

@ -130,6 +130,10 @@ export const IMPORTER_SERVICES_LIST = (workspaceSlug: string) =>
export const GITHUB_REPOSITORY_INFO = (workspaceSlug: string, repoName: string) => export const GITHUB_REPOSITORY_INFO = (workspaceSlug: string, repoName: string) =>
`GITHUB_REPO_INFO_${workspaceSlug.toString().toUpperCase()}_${repoName.toUpperCase()}`; `GITHUB_REPO_INFO_${workspaceSlug.toString().toUpperCase()}_${repoName.toUpperCase()}`;
// slack-project-integration
export const SLACK_CHANNEL_INFO = (workspaceSlug: string, projectId: string) =>
`SLACK_CHANNEL_INFO_${workspaceSlug.toString().toUpperCase()}_${projectId.toUpperCase()}`;
// Calendar // Calendar
export const PROJECT_CALENDAR_ISSUES = (projectId: string) => export const PROJECT_CALENDAR_ISSUES = (projectId: string) =>
`CALENDAR_ISSUES_${projectId.toUpperCase()}`; `CALENDAR_ISSUES_${projectId.toUpperCase()}`;

View File

@ -2,7 +2,7 @@ import { useRef, useState } from "react";
import { useRouter } from "next/router"; import { useRouter } from "next/router";
const useIntegrationPopup = (provider: string | undefined) => { const useIntegrationPopup = (provider: string | undefined, stateParams?: string) => {
const [authLoader, setAuthLoader] = useState(false); const [authLoader, setAuthLoader] = useState(false);
const router = useRouter(); const router = useRouter();
@ -14,14 +14,13 @@ const useIntegrationPopup = (provider: string | undefined) => {
}/installations/new?state=${workspaceSlug?.toString()}`, }/installations/new?state=${workspaceSlug?.toString()}`,
slack: `https://slack.com/oauth/v2/authorize?scope=chat%3Awrite%2Cim%3Ahistory%2Cim%3Awrite%2Clinks%3Aread%2Clinks%3Awrite%2Cusers%3Aread%2Cusers%3Aread.email&amp;user_scope=&amp;&client_id=${ slack: `https://slack.com/oauth/v2/authorize?scope=chat%3Awrite%2Cim%3Ahistory%2Cim%3Awrite%2Clinks%3Aread%2Clinks%3Awrite%2Cusers%3Aread%2Cusers%3Aread.email&amp;user_scope=&amp;&client_id=${
process.env.NEXT_PUBLIC_SLACK_CLIENT_ID process.env.NEXT_PUBLIC_SLACK_CLIENT_ID
}&state=${workspaceSlug?.toString()}&redirect_uri=https://53ff-2405-201-3005-e03e-bc47-b3f9-495d-414d.ngrok-free.app/installations/slack`, }&state=${workspaceSlug?.toString()}`,
slackChannel: `https://slack.com/oauth/v2/authorize?scope=incoming-webhook&client_id=${ slackChannel: `https://slack.com/oauth/v2/authorize?scope=incoming-webhook&client_id=${
process.env.NEXT_PUBLIC_SLACK_CLIENT_ID process.env.NEXT_PUBLIC_SLACK_CLIENT_ID
}&state=${workspaceSlug?.toString()}_${projectId?.toString()}&redirect_uri=https://53ff-2405-201-3005-e03e-bc47-b3f9-495d-414d.ngrok-free.app/installations/slack/connect-project`, }&state=${workspaceSlug?.toString()},${projectId?.toString()}${
stateParams ? "," + stateParams : ""
}`,
}; };
//&project=${projectId?.toString()}
const popup = useRef<any>(); const popup = useRef<any>();
const checkPopup = () => { const checkPopup = () => {

View File

@ -17,5 +17,7 @@ export default async function handleSlackAuthorize(req: NextApiRequest, res: Nex
}, },
}); });
res.status(200).json(response.data); // if (response?.data?.ok)
res.status(200).json(response.data);
// else res.status(404).json(response.data);
} }

View File

@ -1,88 +0,0 @@
import React, { useEffect } from "react";
import useSWR from "swr";
// services
import appinstallationsService from "services/app-installations.service";
import IntegrationService from "services/integration";
// components
import { Spinner } from "components/ui";
import { useRouter } from "next/router";
import { WORKSPACE_INTEGRATIONS } from "constants/fetch-keys";
interface IGithuPostInstallationProps {
installation_id: string;
setup_action: string;
state: string;
provider: string;
code: string;
projectId: string;
}
// TODO:Change getServerSideProps to router.query
const AppPostInstallation = ({
installation_id,
setup_action,
state,
provider,
code,
projectId,
}: IGithuPostInstallationProps) => {
console.log(state, provider, code)
const { data: workspaceIntegrations } = useSWR(
state ? WORKSPACE_INTEGRATIONS(state as string) : null,
() => (state ? IntegrationService.getWorkspaceIntegrationsList(state as string) : null)
);
console.log(workspaceIntegrations)
const workspaceIntegrationId = workspaceIntegrations?.find(
(integration) => integration.integration_detail.provider === provider
);
console.log(workspaceIntegrationId);
useEffect(() => {
if (provider && state && code) {
appinstallationsService
.getSlackAuthDetails(code)
.then((res) => {
const payload = {
metadata: {
...res,
},
};
workspaceIntegrationId && appinstallationsService
.addSlackChannel(state, projectId, workspaceIntegrationId?.integration?.toString(), payload)
.then((r) => {
window.opener = null;
window.open("", "_self");
window.close();
})
.catch((err) => {
throw err?.response;
});
})
.catch((err) => {
console.log(err);
});
}
}, [state, installation_id, provider, code, projectId, workspaceIntegrationId]);
return (
<div className="absolute top-0 left-0 z-50 flex h-full w-full flex-col items-center justify-center gap-y-3 bg-white">
<h2 className="text-2xl text-gray-900">Installing. Please wait...</h2>
<Spinner />
</div>
);
};
export async function getServerSideProps(context: any) {
return {
props: context.query,
};
}
export default AppPostInstallation;

View File

@ -1,6 +1,10 @@
import React, { useEffect } from "react"; import React, { useEffect } from "react";
// services // services
import appinstallationsService from "services/app-installations.service"; import appinstallationsService from "services/app-installations.service";
import useToast from "hooks/use-toast";
// components // components
import { Spinner } from "components/ui"; import { Spinner } from "components/ui";
@ -22,6 +26,9 @@ const AppPostInstallation = ({
provider, provider,
code, code,
}: IGithuPostInstallationProps) => { }: IGithuPostInstallationProps) => {
const { setToastAlert } = useToast();
useEffect(() => { useEffect(() => {
if (provider === "github" && state && installation_id) { if (provider === "github" && state && installation_id) {
appinstallationsService appinstallationsService
@ -35,29 +42,53 @@ const AppPostInstallation = ({
console.log(err); console.log(err);
}); });
} else if (provider === "slack" && state && code) { } else if (provider === "slack" && state && code) {
appinstallationsService appinstallationsService
.getSlackAuthDetails(code) .getSlackAuthDetails(code)
.then((res) => { .then((res) => {
const payload = { const [workspaceSlug, projectId, integrationId] = state.split(",");
metadata: {
...res,
},
};
appinstallationsService if(!projectId) {
.addInstallationApp(state, provider, payload) const payload = {
.then((r) => { metadata: {
window.opener = null; ...res,
window.open("", "_self"); },
window.close(); };
})
.catch((err) => { appinstallationsService
throw err?.response; .addInstallationApp(state, provider, payload)
}); .then((r) => {
}) window.opener = null;
.catch((err) => { window.open("", "_self");
console.log(err); window.close();
}); })
.catch((err) => {
throw err?.response;
});
} else {
const payload = {
access_token: res.access_token,
bot_user_id: res.bot_user_id,
webhook_url: res.incoming_webhook.url,
data: res,
team_id: res.team.id,
team_name: res.team.name,
scopes: res.scope,
};
appinstallationsService
.addSlackChannel(workspaceSlug, projectId, integrationId, payload)
.then((r) => {
window.opener = null;
window.open("", "_self");
window.close();
})
.catch((err) => {
throw err.response
})
}
})
.catch((err) => {
console.log(err);
});
} }
}, [state, installation_id, provider, code]); }, [state, installation_id, provider, code]);

View File

@ -1,11 +1,6 @@
// services // services
import axios from "axios"; import axios from "axios";
import APIService from "services/api.service"; import APIService from "services/api.service";
import IntegrationService from "services/integration";
import {
WORKSPACE_INTEGRATIONS,
} from "constants/fetch-keys";
const { NEXT_PUBLIC_API_BASE_URL } = process.env; const { NEXT_PUBLIC_API_BASE_URL } = process.env;
@ -33,6 +28,26 @@ class AppInstallationsService extends APIService {
}); });
} }
async getSlackChannelDetail(workspaceSlug: string, projectId: string, integrationId: string | null | undefined): Promise<any> {
return this.get(
`/api/workspaces/${workspaceSlug}/projects/${projectId}/workspace-integrations/${integrationId}/project-slack-sync/`
)
.then((response) => response?.data)
.catch((error) => {
throw error?.response;
});
}
async removeSlackChannel(workspaceSlug: string, projectId: string, integrationId: string | null | undefined, slackSyncId: string | undefined): Promise<any> {
return this.delete(
`/api/workspaces/${workspaceSlug}/projects/${projectId}/workspace-integrations/${integrationId}/project-slack-sync/${slackSyncId}`
)
.then((response) => response?.data)
.catch((error) => {
throw error?.response;
});
}
async getSlackAuthDetails(code: string): Promise<any> { async getSlackAuthDetails(code: string): Promise<any> {
const response = await axios({ const response = await axios({
method: "post", method: "post",