Skip to content
This repository has been archived by the owner on Mar 12, 2024. It is now read-only.

Feature/posthog analytics #204

Merged
merged 13 commits into from
Jul 12, 2023
44 changes: 28 additions & 16 deletions app/layout.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,18 @@
import "@primer/css/index.scss";

import AuthProvider from "../lib/auth/AuthProvider";
import Navbar from "../components/Navbar";
import { getServerSession } from "next-auth";

import Navbar from "../components/Navbar";
import Header from "../components/Header";
import { authOptions } from "./api/auth/[...nextauth]/route";
import LogInBtn from "../components/login-btn";

import AuthProvider from "../lib/auth/AuthProvider";

import { PHProvider, PostHogPageview } from "./providers";

import { authOptions } from "./api/auth/[...nextauth]/route";
import { ReactNode, Suspense } from "react";

export const metadata = {
title: {
template: "%s | Watermelon",
Expand All @@ -17,26 +24,31 @@ export const metadata = {
export default async function RootLayout({
children,
}: {
children: React.ReactNode;
children: ReactNode;
}) {
const session = await getServerSession(authOptions);
let userEmail = session?.user?.email;
let userName = session?.user?.name;

return (
<html lang="en" data-color-mode="dark" data-dark-theme="dark">
<body>
{userEmail ? (
<>
<Header userEmail={userEmail} userToken={userName} />
<Navbar>
<AuthProvider>{children}</AuthProvider>
</Navbar>
</>
) : (
<LogInBtn />
)}
</body>
<Suspense fallback={null}>
<PostHogPageview />
</Suspense>
<PHProvider>
<body>
{userEmail ? (
<>
<Header userEmail={userEmail} userToken={userName} />
<Navbar>
<AuthProvider>{children}</AuthProvider>
</Navbar>
</>
) : (
<LogInBtn />
)}
</body>
</PHProvider>
</html>
);
}
34 changes: 34 additions & 0 deletions app/providers.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
"use client";
import posthog from "posthog-js";
import { PostHogProvider } from "posthog-js/react";
import { usePathname, useSearchParams } from "next/navigation";
import { useEffect } from "react";

if (typeof window !== "undefined") {
posthog.init(process.env.NEXT_PUBLIC_POSTHOG_KEY!, {
api_host: process.env.NEXT_PUBLIC_POSTHOG_HOST!,
});
}

export function PostHogPageview(): JSX.Element {
const pathname = usePathname();
const searchParams = useSearchParams();

useEffect(() => {
if (pathname) {
let url = window.origin + pathname;
if (searchParams && searchParams.toString()) {
url = url + `?${searchParams.toString()}`;
}
posthog.capture("$pageview", {
$current_url: url,
});
}
}, [pathname, searchParams]);

return <></>;
}

export function PHProvider({ children }: { children: React.ReactNode }) {
return <PostHogProvider client={posthog}>{children}</PostHogProvider>;
}
10 changes: 10 additions & 0 deletions lib/track/posthogTracker.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import "server-only";

import { PostHog } from "posthog-node";

export default function PostHogTracker() {
const posthogClient = new PostHog(process.env.NEXT_PUBLIC_POSTHOG_KEY!, {
host: process.env.NEXT_PUBLIC_POSTHOG_HOST!,
});
return posthogClient;
}
2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@
"nodemailer": "^6.7.8",
"octokit": "^2.0.9",
"openai": "^3.2.1",
"posthog-js": "^1.70.2",
"posthog-node": "^3.1.1",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"server-only": "0.0.1",
Expand Down
26 changes: 19 additions & 7 deletions pages/api/actions/github.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import linearMarkdown from "../../../utils/actions/markdownHelpers/linear";
import countMarkdown from "../../../utils/actions/markdownHelpers/count";

import addActionLog from "../../../utils/db/github/addActionLog";
import PostHogTracker from "../../../lib/track/posthogTracker";
const app = new App({
appId: process.env.GITHUB_APP_ID!,
privateKey: process.env.GITHUB_PRIVATE_KEY!,
Expand Down Expand Up @@ -301,12 +302,10 @@ export default async (req, res) => {
searchStringSet
.concat(` ${title.split("/").join(" ")}`)
.concat(` ${body}`.split("\n").join(" "))
.split("\n")
.flatMap((line) => line.split(","))
.map((commit: string) => commit.toLowerCase())
.filter((commit) => !stopwords.includes(commit))
.join(" ")
.split(" ")
.flatMap((word) => word.split(","))
.map((word: string) => word.toLowerCase())
.filter((word) => !stopwords.includes(word))
)
).join(" ");
// select six random words from the search string
Expand Down Expand Up @@ -376,7 +375,8 @@ export default async (req, res) => {
if (businessLogicSummary) {
textToWrite += businessLogicSummary;
} else {
textToWrite += "Error getting summary" + businessLogicSummary.error + "\n";
textToWrite +=
"Error getting summary" + businessLogicSummary.error + "\n";
}
} else {
textToWrite += `AI Summary deactivated by ${userLogin} \n`;
Expand Down Expand Up @@ -412,6 +412,19 @@ export default async (req, res) => {
isPrivateRepo: repository.private,
repoName: repo,
});

PostHogTracker().capture({
distinctId: watermelon_user,
event: "GitHub Action",
properties: {
user: userLogin,
owner,
repo,
action: payload.action,
//@ts-ignore
issue_number: number,
},
});
await addActionLog({
randomWords,
ghValue,
Expand All @@ -428,7 +441,6 @@ export default async (req, res) => {
count,
watermelon_user,
});

// Fetch all comments on the PR
const comments = await octokit.request(
"GET /repos/{owner}/{repo}/issues/{issue_number}/comments?sort=created&direction=desc",
Expand Down
25 changes: 19 additions & 6 deletions pages/api/extension/getContext.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import getAllData from "../../../utils/db/user/getAllData";
import updateTokensFromJira from "../../../utils/jira/updateTokens";
import updateTokens from "../../../utils/db/jira/updateTokens";
import searchMessageByText from "../../../utils/slack/searchMessageByText";
import PostHogTracker from "../../../lib/track/posthogTracker";
function replaceSpecialChars(inputString) {
const specialChars = /[!"#$%&/()=?_"{}¨*]/g; // Edit this list to include or exclude characters
return inputString.toLowerCase().replace(specialChars, " ");
Expand Down Expand Up @@ -183,12 +184,24 @@ export default async function handler(req, res) {
}

const githubIssues = await fetchGitHubIssues(userTokens, owner, repo);
let PRTitles = githubIssues.map((issue) => issue.title);
const jiraIssues = await fetchJiraTickets({ user, ...userTokens }, PRTitles);
const slackConversations = await fetchSlackConversations(
userTokens,
PRTitles
);
const PRTitles = githubIssues.map((issue) => issue.title);
const [jiraIssues, slackConversations] = await Promise.all([
fetchJiraTickets({ user, ...userTokens }, PRTitles),
fetchSlackConversations(userTokens, PRTitles),
]);
PostHogTracker().capture({
distinctId: user,
event: "extensionContext",
properties: {
githubIssues,
jiraIssues,
slackConversations,
user,
repo,
owner,
gitSystem,
},
});

return res.send({
github: githubIssues,
Expand Down
43 changes: 37 additions & 6 deletions pages/api/hover/getHoverData.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,15 @@ import { trackEvent } from "../../../utils/analytics/azureAppInsights";
import updateTokensFromJira from "../../../utils/jira/updateTokens";
import updateTokens from "../../../utils/db/jira/updateTokens";
import searchMessageByText from "../../../utils/slack/searchMessageByText";
import PostHogTracker from "../../../lib/track/posthogTracker";
function replaceSpecialChars(inputString) {
const specialChars = /[!"#$%&/()=?_"{}¨*]/g; // Edit this list to include or exclude characters
return inputString.toLowerCase().replace(specialChars, " ");
}
function handleRejection(reason) {
console.error(reason);
return { error: reason };
}
export default async function handler(req, res) {
const { user, gitSystem, repo, owner, commitTitle } = req.body;

Expand Down Expand Up @@ -122,12 +127,38 @@ export default async function handler(req, res) {
}
return slackValue;
}
const githubIssues = await fetchGitHubIssues(userTokens, owner, repo);
const jiraTickets = await fetchJiraTickets(userTokens, commitTitle);
const slackConversations = await fetchSlackConversations(
userTokens,
commitTitle
);
const [githubResult, jiraResult, slackResult] = await Promise.allSettled([
fetchGitHubIssues(userTokens, owner, repo),
fetchJiraTickets(userTokens, commitTitle),
fetchSlackConversations(userTokens, commitTitle),
]);

const githubIssues =
githubResult.status === "fulfilled"
? githubResult.value
: handleRejection(githubResult.reason);
const jiraTickets =
jiraResult.status === "fulfilled"
? jiraResult.value
: handleRejection(jiraResult.reason);
const slackConversations =
slackResult.status === "fulfilled"
? slackResult.value
: handleRejection(slackResult.reason);

PostHogTracker().capture({
distinctId: user,
event: "unifiedHoverData",
properties: {
gitSystem,
repo,
owner,
commitTitle,
githubIssues,
jiraTickets,
slackConversations,
},
});
trackEvent({
name: "unifiedHoverData",
properties: { user, gitSystem, repo, owner, commitTitle },
Expand Down