feat: slack integration frontend

This commit is contained in:
kunal_17 2023-04-21 13:36:35 +05:30
parent 2b280935a1
commit 6a0a272386
10 changed files with 324 additions and 27 deletions

View File

@ -7,4 +7,5 @@ NEXT_PUBLIC_SENTRY_DSN=""
NEXT_PUBLIC_ENABLE_OAUTH=0 NEXT_PUBLIC_ENABLE_OAUTH=0
NEXT_PUBLIC_ENABLE_SENTRY=0 NEXT_PUBLIC_ENABLE_SENTRY=0
NEXT_PUBLIC_ENABLE_SESSION_RECORDER=0 NEXT_PUBLIC_ENABLE_SESSION_RECORDER=0
NEXT_PUBLIC_TRACK_EVENTS=0 NEXT_PUBLIC_TRACK_EVENTS=0
NEXT_PUBLIC_SLACK_CLIENT_ID=""

View File

@ -8,3 +8,5 @@ export * from "./single-integration-card";
export * from "./github"; export * from "./github";
// jira // jira
export * from "./jira"; export * from "./jira";
// slack
export * from "./slack";

View File

@ -0,0 +1 @@
export * from "./select-channel";

View File

@ -0,0 +1,90 @@
import React,{useState} from "react";
import { useRouter } from "next/router";
import useSWR, { mutate } from "swr";
// services
import projectService from "services/project.service";
import IntegrationService from "services/integration";
// ui
import { DangerButton, Loader, SecondaryButton } from "components/ui";
// hooks
import useToast from "hooks/use-toast";
import useIntegrationPopup from "hooks/use-integration-popup";
// types
import { IAppIntegration, IWorkspaceIntegration } from "types";
// fetch-keys
import { WORKSPACE_INTEGRATIONS } from "constants/fetch-keys";
type Props = {
integration: IWorkspaceIntegration;
};
export const SelectChannel: React.FC<Props> = ({
integration,
}) => {
const [deletingIntegration, setDeletingIntegration] = useState(false);
const router = useRouter();
const { workspaceSlug } = router.query;
const { setToastAlert } = useToast();
const { startAuth, isConnecting: isInstalling } = useIntegrationPopup("slackChannel");
const { data: workspaceIntegrations } = useSWR(
workspaceSlug ? WORKSPACE_INTEGRATIONS(workspaceSlug as string) : null,
() =>
workspaceSlug
? IntegrationService.getWorkspaceIntegrationsList(workspaceSlug as string)
: null
);
const isInstalled = workspaceIntegrations?.find(
(i: any) => i.integration_detail.id === integration.id
);
const handleRemoveIntegration = async () => {
if (!workspaceSlug || !integration || !workspaceIntegrations) return;
const workspaceIntegrationId = workspaceIntegrations?.find(
(i) => i.integration === integration.id
)?.id;
setDeletingIntegration(true);
await IntegrationService.deleteWorkspaceIntegration(
workspaceSlug as string,
workspaceIntegrationId ?? ""
)
.then(() => {
setDeletingIntegration(false);
})
.catch(() => {
setDeletingIntegration(false);
});
};
return (
<>
{workspaceIntegrations ? (
isInstalled ? (
<DangerButton onClick={handleRemoveIntegration} loading={deletingIntegration}>
{deletingIntegration ? "Removing..." : "Remove channel"}
</DangerButton>
) : (
<SecondaryButton onClick={startAuth} loading={isInstalling}>
{isInstalling ? "Adding..." : "Add channel"}
</SecondaryButton>
)
) : (
<Loader>
<Loader.Item height="35px" width="150px" />
</Loader>
)}
</>
);
};

View File

@ -10,18 +10,34 @@ import projectService from "services/project.service";
import { useRouter } from "next/router"; import { useRouter } from "next/router";
import useToast from "hooks/use-toast"; import useToast from "hooks/use-toast";
// components // components
import { SelectRepository } from "components/integration"; import { SelectRepository, SelectChannel } from "components/integration";
// icons // icons
import GithubLogo from "public/logos/github-square.png"; import GithubLogo from "public/logos/github-square.png";
import SlackLogo from "public/services/slack.png";
// types // types
import { IWorkspaceIntegration } from "types"; import { IWorkspaceIntegration } from "types";
// fetch-keys // fetch-keys
import { PROJECT_GITHUB_REPOSITORY } from "constants/fetch-keys"; import { PROJECT_GITHUB_REPOSITORY } from "constants/fetch-keys";
import { comboMatches } from "@blueprintjs/core";
type Props = { type Props = {
integration: IWorkspaceIntegration; integration: IWorkspaceIntegration;
}; };
const integrationDetails: { [key: string]: any } = {
github: {
logo: GithubLogo,
installed:
"Activate GitHub integrations on individual projects to sync with specific repositories.",
notInstalled: "Connect with GitHub with your Plane workspace to sync project issues.",
},
slack: {
logo: SlackLogo,
installed: "Activate Slack integrations on individual projects to sync with specific cahnnels.",
notInstalled: "Connect with Slack with your Plane workspace to sync project issues.",
},
};
export const SingleIntegration: React.FC<Props> = ({ integration }) => { export const SingleIntegration: React.FC<Props> = ({ integration }) => {
const router = useRouter(); const router = useRouter();
const { workspaceSlug, projectId } = router.query; const { workspaceSlug, projectId } = router.query;
@ -83,29 +99,43 @@ export const SingleIntegration: React.FC<Props> = ({ integration }) => {
<div className="flex items-center justify-between gap-2 rounded-[10px] border bg-white p-5"> <div className="flex items-center justify-between gap-2 rounded-[10px] border bg-white p-5">
<div className="flex items-start gap-4"> <div className="flex items-start gap-4">
<div className="h-12 w-12 flex-shrink-0"> <div className="h-12 w-12 flex-shrink-0">
<Image src={GithubLogo} alt="GithubLogo" /> <Image
src={integrationDetails[integration.integration_detail.provider].logo}
alt="GithubLogo"
/>
</div> </div>
<div> <div>
<h3 className="flex items-center gap-4 text-xl font-semibold"> <h3 className="flex items-center gap-4 text-xl font-semibold">
{integration.integration_detail.title} {integration.integration_detail.title}
</h3> </h3>
<p className="text-sm text-gray-400">Select GitHub repository to enable sync.</p> <p className="text-sm text-gray-400">
{integration.integration_detail.provider === "github"
? "Select GitHub repository to enable sync."
: integration.integration_detail.provider === "slack"
? "Select Slack channel to enable sync."
: null}
</p>
</div> </div>
</div> </div>
<SelectRepository {integration.integration_detail.provider === "github" && (
integration={integration} <SelectRepository
value={ integration={integration}
syncedGithubRepository && syncedGithubRepository.length > 0 value={
? `${syncedGithubRepository[0].repo_detail.owner}/${syncedGithubRepository[0].repo_detail.name}` syncedGithubRepository && syncedGithubRepository.length > 0
: null ? `${syncedGithubRepository[0].repo_detail.owner}/${syncedGithubRepository[0].repo_detail.name}`
} : null
label={ }
syncedGithubRepository && syncedGithubRepository.length > 0 label={
? `${syncedGithubRepository[0].repo_detail.owner}/${syncedGithubRepository[0].repo_detail.name}` syncedGithubRepository && syncedGithubRepository.length > 0
: "Select Repository" ? `${syncedGithubRepository[0].repo_detail.owner}/${syncedGithubRepository[0].repo_detail.name}`
} : "Select Repository"
onChange={handleChange} }
/> onChange={handleChange}
/>
)}
{integration.integration_detail.provider === "slack" && (
<SelectChannel integration={integration} />
)}
</div> </div>
)} )}
</> </>

View File

@ -6,14 +6,22 @@ const useIntegrationPopup = (provider: string | undefined) => {
const [authLoader, setAuthLoader] = useState(false); const [authLoader, setAuthLoader] = useState(false);
const router = useRouter(); const router = useRouter();
const { workspaceSlug } = router.query; const { workspaceSlug, projectId } = router.query;
const providerUrls: { [key: string]: string } = { const providerUrls: { [key: string]: string } = {
github: `https://github.com/apps/${ github: `https://github.com/apps/${
process.env.NEXT_PUBLIC_GITHUB_APP_NAME process.env.NEXT_PUBLIC_GITHUB_APP_NAME
}/installations/new?state=${workspaceSlug as string}`, }/installations/new?state=${workspaceSlug?.toString()}`,
slack: "", 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
}&state=${workspaceSlug?.toString()}&redirect_uri=https://53ff-2405-201-3005-e03e-bc47-b3f9-495d-414d.ngrok-free.app/installations/slack`,
slackChannel: `https://slack.com/oauth/v2/authorize?scope=incoming-webhook&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`,
}; };
//&project=${projectId?.toString()}
const popup = useRef<any>(); const popup = useRef<any>();
const checkPopup = () => { const checkPopup = () => {

View File

@ -0,0 +1,21 @@
// pages/api/slack/authorize.js
import axios from "axios";
import { NextApiRequest, NextApiResponse } from "next";
export default async function handleSlackAuthorize(req: NextApiRequest, res: NextApiResponse) {
const { code } = req.body;
if (!code || code === "") return res.status(400).json({ message: "Code is required" });
const response = await axios({
method: "post",
url: "https://slack.com/api/oauth.v2.access",
params: {
client_id: process.env.NEXT_PUBLIC_SLACK_CLIENT_ID,
client_secret: process.env.NEXT_PUBLIC_SLACK_CLIENT_SECRET,
code,
},
});
res.status(200).json(response.data);
}

View File

@ -0,0 +1,88 @@
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,15 +1,17 @@
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";
// components // components
import { Spinner } from "components/ui"; import { Spinner } from "components/ui";
import { useRouter } from "next/router";
interface IGithuPostInstallationProps { interface IGithuPostInstallationProps {
installation_id: string; installation_id: string;
setup_action: string; setup_action: string;
state: string; state: string;
provider: string; provider: string;
code: string;
} }
// TODO:Change getServerSideProps to router.query // TODO:Change getServerSideProps to router.query
@ -18,12 +20,13 @@ const AppPostInstallation = ({
setup_action, setup_action,
state, state,
provider, provider,
code,
}: IGithuPostInstallationProps) => { }: IGithuPostInstallationProps) => {
useEffect(() => { useEffect(() => {
if (state && installation_id) { if (provider === "github" && state && installation_id) {
appinstallationsService appinstallationsService
.addGithubApp(state, provider, { installation_id }) .addInstallationApp(state, provider, { installation_id })
.then((res) => { .then(() => {
window.opener = null; window.opener = null;
window.open("", "_self"); window.open("", "_self");
window.close(); window.close();
@ -31,8 +34,32 @@ const AppPostInstallation = ({
.catch((err) => { .catch((err) => {
console.log(err); console.log(err);
}); });
} else if (provider === "slack" && state && code) {
appinstallationsService
.getSlackAuthDetails(code)
.then((res) => {
const payload = {
metadata: {
...res,
},
};
appinstallationsService
.addInstallationApp(state, provider, 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]); }, [state, installation_id, provider, code]);
return ( 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"> <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">

View File

@ -1,5 +1,11 @@
// services // services
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;
@ -8,13 +14,36 @@ class AppInstallationsService extends APIService {
super(NEXT_PUBLIC_API_BASE_URL || "http://localhost:8000"); super(NEXT_PUBLIC_API_BASE_URL || "http://localhost:8000");
} }
async addGithubApp(workspaceSlug: string, provider: string, data: any): Promise<any> { async addInstallationApp(workspaceSlug: string, provider: string, data: any): Promise<any> {
return this.post(`/api/workspaces/${workspaceSlug}/workspace-integrations/${provider}/`, data) return this.post(`/api/workspaces/${workspaceSlug}/workspace-integrations/${provider}/`, data)
.then((response) => response?.data) .then((response) => response?.data)
.catch((error) => { .catch((error) => {
throw error?.response; throw error?.response;
}); });
} }
async addSlackChannel(workspaceSlug: string, projectId: string, integrationId: string | null | undefined, data: any): Promise<any> {
return this.post(
`/api/workspaces/${workspaceSlug}/projects/${projectId}/workspace-integrations/${integrationId}/project-slack-sync/`,
data
)
.then((response) => response?.data)
.catch((error) => {
throw error?.response;
});
}
async getSlackAuthDetails(code: string): Promise<any> {
const response = await axios({
method: "post",
url: "/api/slack-redirect",
data: {
code,
},
});
return response.data;
}
} }
export default new AppInstallationsService(); export default new AppInstallationsService();