fix: Auth fixes and Layout fixes (#2408)

* fix: auth fixes and layout improvements

* fix: layout fixes
This commit is contained in:
sriram veeraghanta 2023-10-11 13:57:47 +05:30 committed by GitHub
parent 4dec6761d0
commit 991a6858ec
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
23 changed files with 505 additions and 370 deletions

View File

@ -1,21 +1,19 @@
import React from "react"; import { FC } from "react";
import { useRouter } from "next/router"; import { useRouter } from "next/router";
import { useForm } from "react-hook-form"; import { useForm } from "react-hook-form";
// services
import userService from "services/user.service";
// hooks
import useToast from "hooks/use-toast";
// ui // ui
import { Input, PrimaryButton, SecondaryButton } from "components/ui"; import { Input, PrimaryButton, SecondaryButton } from "components/ui";
// types
type Props = {
onSubmit: (formValues: any) => void;
};
export const EmailResetPasswordForm: React.FC<Props> = (props) => { export interface EmailForgotPasswordFormValues {
email: string;
}
export interface IEmailForgotPasswordForm {
onSubmit: (formValues: any) => Promise<void>;
}
export const EmailForgotPasswordForm: FC<IEmailForgotPasswordForm> = (props) => {
const { onSubmit } = props; const { onSubmit } = props;
// toast
const { setToastAlert } = useToast();
// router // router
const router = useRouter(); const router = useRouter();
// form data // form data
@ -23,7 +21,7 @@ export const EmailResetPasswordForm: React.FC<Props> = (props) => {
register, register,
handleSubmit, handleSubmit,
formState: { errors, isSubmitting }, formState: { errors, isSubmitting },
} = useForm({ } = useForm<EmailForgotPasswordFormValues>({
defaultValues: { defaultValues: {
email: "", email: "",
}, },
@ -31,38 +29,8 @@ export const EmailResetPasswordForm: React.FC<Props> = (props) => {
reValidateMode: "onChange", reValidateMode: "onChange",
}); });
const forgotPassword = async (formData: any) => {
const payload = {
email: formData.email,
};
await userService
.forgotPassword(payload)
.then(() =>
setToastAlert({
type: "success",
title: "Success!",
message: "Password reset link has been sent to your email address.",
})
)
.catch((err) => {
if (err.status === 400)
setToastAlert({
type: "error",
title: "Error!",
message: "Please check the Email ID entered.",
});
else
setToastAlert({
type: "error",
title: "Error!",
message: "Something went wrong. Please try again.",
});
});
};
return ( return (
<form className="space-y-4 mt-10 w-full sm:w-[360px] mx-auto" onSubmit={handleSubmit(forgotPassword)}> <form className="space-y-4 mt-10 w-full sm:w-[360px] mx-auto" onSubmit={handleSubmit(onSubmit)}>
<div className="space-y-1"> <div className="space-y-1">
<Input <Input
id="email" id="email"

View File

@ -1,7 +1,9 @@
import React from "react"; import React from "react";
import { useForm } from "react-hook-form"; import { useForm } from "react-hook-form";
import { useRouter } from "next/router";
// ui // ui
import { Input, PrimaryButton } from "components/ui"; import { Input, PrimaryButton } from "components/ui";
import Link from "next/link";
// types // types
export interface EmailPasswordFormValues { export interface EmailPasswordFormValues {
email: string; email: string;
@ -15,6 +17,8 @@ export interface IEmailPasswordForm {
export const EmailPasswordForm: React.FC<IEmailPasswordForm> = (props) => { export const EmailPasswordForm: React.FC<IEmailPasswordForm> = (props) => {
const { onSubmit } = props; const { onSubmit } = props;
// router
const router = useRouter();
// form info // form info
const { const {
register, register,
@ -66,7 +70,11 @@ export const EmailPasswordForm: React.FC<IEmailPasswordForm> = (props) => {
/> />
</div> </div>
<div className="text-right text-xs"> <div className="text-right text-xs">
<button type="button" onClick={() => {}} className="text-custom-text-200 hover:text-custom-primary-100"> <button
type="button"
onClick={() => router.push("/accounts/forgot-password")}
className="text-custom-text-200 hover:text-custom-primary-100"
>
Forgot your password? Forgot your password?
</button> </button>
</div> </div>
@ -80,6 +88,15 @@ export const EmailPasswordForm: React.FC<IEmailPasswordForm> = (props) => {
{isSubmitting ? "Signing in..." : "Sign in"} {isSubmitting ? "Signing in..." : "Sign in"}
</PrimaryButton> </PrimaryButton>
</div> </div>
<div className="text-xs">
<button
type="button"
onClick={() => router.push("/accounts/sign-up")}
className="text-custom-text-200 hover:text-custom-primary-100"
>
{"Don't have an account? Sign Up"}
</button>
</div>
</form> </form>
</> </>
); );

View File

@ -1,6 +1,6 @@
export * from "./email-code-form"; export * from "./email-code-form";
export * from "./email-password-form"; export * from "./email-password-form";
export * from "./email-reset-password-form"; export * from "./email-forgot-password-form";
export * from "./github-login-button"; export * from "./github-login-button";
export * from "./google-login"; export * from "./google-login";
export * from "./email-signup-form"; export * from "./email-signup-form";

View File

@ -0,0 +1 @@
export * from "./product-updates-modal";

View File

@ -0,0 +1,52 @@
import { useState } from "react";
import { LayoutGrid, Zap } from "lucide-react";
import Image from "next/image";
import { useTheme } from "next-themes";
// images
import githubBlackImage from "/public/logos/github-black.png";
import githubWhiteImage from "/public/logos/github-white.png";
// components
import { ProductUpdatesModal } from "components/common";
export const WorkspaceDashboardHeader = () => {
const [isProductUpdatesModalOpen, setIsProductUpdatesModalOpen] = useState(false);
// theme
const { resolvedTheme } = useTheme();
return (
<>
<ProductUpdatesModal isOpen={isProductUpdatesModalOpen} setIsOpen={setIsProductUpdatesModalOpen} />
<div
className={`relative flex w-full flex-shrink-0 flex-row z-10 items-center justify-between gap-x-2 gap-y-4 border-b border-custom-border-200 bg-custom-sidebar-background-100 p-4`}
>
<div className="flex items-center gap-2 pl-3">
<LayoutGrid size={14} strokeWidth={2} />
Dashboard
</div>
<div className="flex items-center gap-3 px-3">
<button
onClick={() => setIsProductUpdatesModalOpen(true)}
className="flex items-center gap-1.5 bg-custom-background-80 text-xs font-medium py-1.5 px-3 rounded"
>
<Zap size={14} strokeWidth={2} fill="rgb(var(--color-text-100))" />
{"What's New?"}
</button>
<a
className="flex items-center gap-1.5 bg-custom-background-80 text-xs font-medium py-1.5 px-3 rounded"
href="https://github.com/makeplane/plane"
target="_blank"
rel="noopener noreferrer"
>
<Image
src={resolvedTheme === "dark" ? githubWhiteImage : githubBlackImage}
height={16}
width={16}
alt="GitHub Logo"
/>
Star us on GitHub
</a>
</div>
</div>
</>
);
};

View File

@ -19,7 +19,6 @@ export * from "./spinner";
export * from "./tooltip"; export * from "./tooltip";
export * from "./toggle-switch"; export * from "./toggle-switch";
export * from "./markdown-to-component"; export * from "./markdown-to-component";
export * from "./product-updates-modal";
export * from "./integration-and-import-export-banner"; export * from "./integration-and-import-export-banner";
export * from "./range-datepicker"; export * from "./range-datepicker";
export * from "./circular-progress"; export * from "./circular-progress";

View File

@ -0,0 +1 @@
export * from "./user-greetings";

View File

@ -0,0 +1,49 @@
import { FC } from "react";
import { IUser } from "types";
export interface IUserGreetingsView {
user: IUser;
}
export const UserGreetingsView: FC<IUserGreetingsView> = (props) => {
const { user } = props;
const currentTime = new Date();
const hour = new Intl.DateTimeFormat("en-US", {
hour12: false,
hour: "numeric",
}).format(currentTime);
const date = new Intl.DateTimeFormat("en-US", {
month: "short",
day: "numeric",
}).format(currentTime);
const weekDay = new Intl.DateTimeFormat("en-US", {
weekday: "long",
}).format(currentTime);
const timeString = new Intl.DateTimeFormat("en-US", {
timeZone: user?.user_timezone,
hour12: false, // Use 24-hour format
hour: "2-digit",
minute: "2-digit",
}).format(currentTime);
const greeting = parseInt(hour, 10) < 12 ? "morning" : parseInt(hour, 10) < 18 ? "afternoon" : "evening";
return (
<div>
<h3 className="text-2xl font-semibold">
Good {greeting}, {user?.first_name} {user?.last_name}
</h3>
<h6 className="text-custom-text-400 font-medium flex items-center gap-2">
<div>{greeting === "morning" ? "🌤️" : greeting === "afternoon" ? "🌥️" : "🌙️"}</div>
<div>
{weekDay}, {date} {timeString}
</div>
</h6>
</div>
);
};

View File

@ -5,3 +5,4 @@ export * from "./modal";
export * from "./select-filters"; export * from "./select-filters";
export * from "./single-view-item"; export * from "./single-view-item";
export * from "./signin"; export * from "./signin";
export * from "./workspace-dashboard";

View File

@ -1,6 +1,7 @@
import useSWR from "swr"; import useSWR from "swr";
import { observer } from "mobx-react-lite"; import { observer } from "mobx-react-lite";
import Image from "next/image"; import Image from "next/image";
import { useRouter } from "next/router";
// hooks // hooks
import useToast from "hooks/use-toast"; import useToast from "hooks/use-toast";
import { useMobxStore } from "lib/mobx/store-provider"; import { useMobxStore } from "lib/mobx/store-provider";
@ -13,25 +14,37 @@ import {
GithubLoginButton, GithubLoginButton,
EmailCodeForm, EmailCodeForm,
EmailPasswordForm, EmailPasswordForm,
EmailResetPasswordForm,
EmailPasswordFormValues, EmailPasswordFormValues,
} from "components/account"; } from "components/account";
// ui // ui
import { Spinner } from "@plane/ui"; import { Spinner } from "@plane/ui";
// images // images
import BluePlaneLogoWithoutText from "public/plane-logos/blue-without-text.png"; import BluePlaneLogoWithoutText from "public/plane-logos/blue-without-text.png";
import { IUserSettings } from "types";
const appConfigService = new AppConfigService(); const appConfigService = new AppConfigService();
const authService = new AuthService(); const authService = new AuthService();
export const SignInView = observer(() => { export const SignInView = observer(() => {
const { user: userStore } = useMobxStore(); const { user: userStore } = useMobxStore();
// router
const router = useRouter();
// toast // toast
const { setToastAlert } = useToast(); const { setToastAlert } = useToast();
// fetch app config // fetch app config
const { data } = useSWR("APP_CONFIG", () => appConfigService.envConfig()); const { data } = useSWR("APP_CONFIG", () => appConfigService.envConfig());
// fetch user info // fetch user info
const { data: user, error } = useSWR("USER_INFO", () => userStore.fetchCurrentUser()); const { data: user, error } = useSWR("USER_INFO", () => userStore.fetchCurrentUser());
// computed
const enableEmailPassword =
data?.email_password_login || !(data?.email_password_login || data?.magic_login || data?.google || data?.github);
const handleLoginRedirection = () =>
userStore.fetchCurrentUserSettings().then((userSettings: IUserSettings) => {
const workspaceSlug =
userSettings?.workspace?.last_workspace_slug || userSettings?.workspace?.fallback_workspace_slug;
router.push(`/${workspaceSlug}`);
});
const handleGoogleSignIn = async ({ clientId, credential }: any) => { const handleGoogleSignIn = async ({ clientId, credential }: any) => {
try { try {
@ -42,9 +55,8 @@ export const SignInView = observer(() => {
clientId, clientId,
}; };
const response = await authService.socialAuth(socialAuthPayload); const response = await authService.socialAuth(socialAuthPayload);
if (response && response?.user) { if (response) {
mutateUser(); handleLoginRedirection();
handleTheme(response?.user);
} }
} else { } else {
throw Error("Cant find credentials"); throw Error("Cant find credentials");
@ -67,9 +79,8 @@ export const SignInView = observer(() => {
clientId: data.github, clientId: data.github,
}; };
const response = await authService.socialAuth(socialAuthPayload); const response = await authService.socialAuth(socialAuthPayload);
if (response && response?.user) { if (response) {
mutateUser(); handleLoginRedirection();
handleTheme(response?.user);
} }
} else { } else {
throw Error("Cant find credentials"); throw Error("Cant find credentials");
@ -87,17 +98,8 @@ export const SignInView = observer(() => {
await authService await authService
.emailLogin(formData) .emailLogin(formData)
.then((response) => { .then((response) => {
try { if (response) {
if (response) { handleLoginRedirection();
mutateUser();
handleTheme(response?.user);
}
} catch (err: any) {
setToastAlert({
type: "error",
title: "Error!",
message: err?.error || "Something went wrong. Please try again later or contact the support team.",
});
} }
}) })
.catch((err) => .catch((err) =>
@ -112,8 +114,7 @@ export const SignInView = observer(() => {
const handleEmailCodeSignIn = async (response: any) => { const handleEmailCodeSignIn = async (response: any) => {
try { try {
if (response) { if (response) {
mutateUser(); handleLoginRedirection();
handleTheme(response?.user);
} }
} catch (err: any) { } catch (err: any) {
setToastAlert({ setToastAlert({
@ -147,9 +148,8 @@ export const SignInView = observer(() => {
<h1 className="text-center text-2xl sm:text-2.5xl font-semibold text-custom-text-100"> <h1 className="text-center text-2xl sm:text-2.5xl font-semibold text-custom-text-100">
Sign in to Plane Sign in to Plane
</h1> </h1>
<EmailResetPasswordForm />
<> <>
{data?.email_password_login && <EmailPasswordForm onSubmit={handlePasswordSignIn} />} {enableEmailPassword && <EmailPasswordForm onSubmit={handlePasswordSignIn} />}
{data?.magic_login && ( {data?.magic_login && (
<div className="flex flex-col divide-y divide-custom-border-200"> <div className="flex flex-col divide-y divide-custom-border-200">
<div className="pb-7"> <div className="pb-7">

View File

@ -0,0 +1,90 @@
import { useState } from "react";
import Image from "next/image";
import { useRouter } from "next/router";
import useSWR from "swr";
import { observer } from "mobx-react-lite";
// hooks
import { useMobxStore } from "lib/mobx/store-provider";
// components
import { TourRoot } from "components/onboarding";
import { UserGreetingsView } from "components/user";
import { CompletedIssuesGraph, IssuesList, IssuesPieChart, IssuesStats } from "components/workspace";
import { PrimaryButton } from "components/ui";
// images
import emptyDashboard from "public/empty-state/dashboard.svg";
export const WorkspaceDashboardView = observer(() => {
// router
const router = useRouter();
const { workspaceSlug } = router.query;
// store
const { user: userStore, project: projectStore } = useMobxStore();
const user = userStore.currentUser;
const projects = workspaceSlug ? projectStore.projects[workspaceSlug.toString()] : null;
const workspaceDashboardInfo = userStore.dashboardInfo;
// states
const [month, setMonth] = useState(new Date().getMonth() + 1);
// fetch user dashboard info
useSWR(
workspaceSlug ? `USER_WORKSPACE_DASHBOARD_${workspaceSlug}_${month}` : null,
workspaceSlug ? () => userStore.fetchUserDashboardInfo(workspaceSlug.toString(), month) : null
);
const handleTourCompleted = () => {
userStore.updateTourCompleted();
};
return (
<>
{/* {isProductUpdatesModalOpen && (
<ProductUpdatesModal isOpen={isProductUpdatesModalOpen} setIsOpen={setIsProductUpdatesModalOpen} />
)} */}
{user && !user.is_tour_completed && (
<div className="fixed top-0 left-0 h-full w-full bg-custom-backdrop bg-opacity-50 transition-opacity z-20 grid place-items-center">
<TourRoot onComplete={handleTourCompleted} />
</div>
)}
<div className="p-8 space-y-8">
{user && <UserGreetingsView user={user} />}
{projects ? (
projects.length > 0 ? (
<div className="flex flex-col gap-8">
<IssuesStats data={workspaceDashboardInfo} />
<div className="grid grid-cols-1 gap-8 lg:grid-cols-2">
<IssuesList issues={workspaceDashboardInfo?.overdue_issues} type="overdue" />
<IssuesList issues={workspaceDashboardInfo?.upcoming_issues} type="upcoming" />
<IssuesPieChart groupedIssues={workspaceDashboardInfo?.state_distribution} />
<CompletedIssuesGraph
issues={workspaceDashboardInfo?.completed_issues}
month={month}
setMonth={setMonth}
/>
</div>
</div>
) : (
<div className="bg-custom-primary-100/5 flex justify-between gap-5 md:gap-8">
<div className="p-5 md:p-8 pr-0">
<h5 className="text-xl font-semibold">Create a project</h5>
<p className="mt-2 mb-5">Manage your projects by creating issues, cycles, modules, views and pages.</p>
<PrimaryButton
onClick={() => {
const e = new KeyboardEvent("keydown", {
key: "p",
});
document.dispatchEvent(e);
}}
>
Create Project
</PrimaryButton>
</div>
<div className="hidden md:block self-end overflow-hidden pt-8">
<Image src={emptyDashboard} alt="Empty Dashboard" />
</div>
</div>
)
) : null}
</div>
</>
);
});

View File

@ -6,29 +6,22 @@ import { CommandPalette } from "components/command-palette";
import { AppSidebar } from "./sidebar"; import { AppSidebar } from "./sidebar";
export interface IAppLayout { export interface IAppLayout {
bg: string;
children: ReactNode; children: ReactNode;
header: ReactNode;
} }
export const AppLayout: FC<IAppLayout> = (props) => { export const AppLayout: FC<IAppLayout> = (props) => {
const { bg = "primary", children } = props; const { children, header } = props;
return ( return (
<div> <div>
<CommandPalette /> {/* <CommandPalette /> */}
<UserAuthWrapper> <UserAuthWrapper>
<WorkspaceAuthWrapper> <WorkspaceAuthWrapper>
<div> <div className="flex w-full h-full">
<AppSidebar /> <AppSidebar />
<div className="relative flex h-screen w-full overflow-hidden"> <div className="relative flex flex-col h-screen w-full overflow-hidden">
<main <div className="w-full">{header}</div>
className={`relative flex h-full w-full flex-col overflow-hidden ${ <main className={`relative flex h-full w-full flex-col overflow-hidden bg-custom-background-100`}>
bg === "primary"
? "bg-custom-background-100"
: bg === "secondary"
? "bg-custom-background-90"
: "bg-custom-background-80"
}`}
>
<div className="h-full w-full overflow-hidden"> <div className="h-full w-full overflow-hidden">
<div className="relative h-full w-full overflow-x-hidden overflow-y-scroll">{children}</div> <div className="relative h-full w-full overflow-x-hidden overflow-y-scroll">{children}</div>
</div> </div>

View File

@ -2,12 +2,11 @@ import { FC, ReactNode } from "react";
import { useRouter } from "next/router"; import { useRouter } from "next/router";
import Link from "next/link"; import Link from "next/link";
import useSWR from "swr"; import useSWR from "swr";
// services import { observer } from "mobx-react-lite";
import workspaceServices from "services/workspace.service";
// icons // icons
import { Spinner, PrimaryButton, SecondaryButton } from "components/ui"; import { Spinner, PrimaryButton, SecondaryButton } from "components/ui";
// fetch-keys // hooks
import { WORKSPACE_MEMBERS_ME } from "constants/fetch-keys"; import { useMobxStore } from "lib/mobx/store-provider";
export interface IWorkspaceAuthWrapper { export interface IWorkspaceAuthWrapper {
children: ReactNode; children: ReactNode;
@ -18,18 +17,30 @@ export interface IWorkspaceAuthWrapper {
right?: JSX.Element; right?: JSX.Element;
} }
export const WorkspaceAuthWrapper: FC<IWorkspaceAuthWrapper> = (props) => { export const WorkspaceAuthWrapper: FC<IWorkspaceAuthWrapper> = observer((props) => {
const { children } = props; const { children } = props;
// store
const { user: userStore, project: projectStore } = useMobxStore();
// router // router
const router = useRouter(); const router = useRouter();
const { workspaceSlug } = router.query; const { workspaceSlug } = router.query;
// fetching user workspace information // fetching user workspace information
const { data: workspaceMemberMe, error } = useSWR( useSWR(
workspaceSlug ? WORKSPACE_MEMBERS_ME(workspaceSlug as string) : null, workspaceSlug ? `WORKSPACE_MEMBERS_ME_${workspaceSlug}` : null,
workspaceSlug ? () => workspaceServices.workspaceMemberMe(workspaceSlug.toString()) : null workspaceSlug ? () => userStore.fetchUserWorkspaceInfo(workspaceSlug.toString()) : null
); );
// fetching workspace projects
useSWR(
workspaceSlug ? `WORKSPACE_PROJECTS_${workspaceSlug}` : null,
workspaceSlug ? () => projectStore.fetchProjects(workspaceSlug.toString()) : null
);
console.log("workspaceSlug", workspaceSlug);
console.log("userStore.memberInfo", userStore.memberInfo);
// while data is being loaded // while data is being loaded
if (!workspaceMemberMe && !error) { if (!userStore.memberInfo && userStore.hasPermissionToWorkspace === null) {
return ( return (
<div className="grid h-screen place-items-center p-4 bg-custom-background-100"> <div className="grid h-screen place-items-center p-4 bg-custom-background-100">
<div className="flex flex-col items-center gap-3 text-center"> <div className="flex flex-col items-center gap-3 text-center">
@ -39,7 +50,7 @@ export const WorkspaceAuthWrapper: FC<IWorkspaceAuthWrapper> = (props) => {
); );
} }
// while user does not have access to view that workspace // while user does not have access to view that workspace
if (error?.status === 401 || error?.status === 403) { if (userStore.hasPermissionToWorkspace !== null && userStore.hasPermissionToWorkspace === false) {
return ( return (
<div className={`h-screen w-full overflow-hidden bg-custom-background-100`}> <div className={`h-screen w-full overflow-hidden bg-custom-background-100`}>
<div className="grid h-full place-items-center p-4"> <div className="grid h-full place-items-center p-4">
@ -70,4 +81,4 @@ export const WorkspaceAuthWrapper: FC<IWorkspaceAuthWrapper> = (props) => {
} }
return <>{children}</>; return <>{children}</>;
}; });

View File

@ -1,200 +1,14 @@
import React, { useEffect, useState } from "react";
import { useRouter } from "next/router";
import Image from "next/image";
import Link from "next/link";
import useSWR, { mutate } from "swr";
// next-themes
import { useTheme } from "next-themes";
// layouts
import { WorkspaceAuthorizationLayout } from "layouts/auth-layout-legacy";
// services
import userService from "services/user.service";
// hooks
import useUser from "hooks/use-user";
import useProjects from "hooks/use-projects";
// components
import { CompletedIssuesGraph, IssuesList, IssuesPieChart, IssuesStats } from "components/workspace";
import { TourRoot } from "components/onboarding";
// ui
import { PrimaryButton, ProductUpdatesModal } from "components/ui";
// icons
import { BoltOutlined, GridViewOutlined } from "@mui/icons-material";
// images
import emptyDashboard from "public/empty-state/dashboard.svg";
import githubBlackImage from "/public/logos/github-black.png";
import githubWhiteImage from "/public/logos/github-white.png";
// types
import { ICurrentUserResponse } from "types";
import type { NextPage } from "next"; import type { NextPage } from "next";
// fetch-keys // layouts
import { CURRENT_USER, USER_WORKSPACE_DASHBOARD } from "constants/fetch-keys"; import { AppLayout } from "layouts/app-layout";
// components
import { WorkspaceDashboardView } from "components/views";
import { WorkspaceDashboardHeader } from "components/headers/workspace-dashboard";
const Greeting = ({ user }: { user: ICurrentUserResponse | undefined }) => { const WorkspacePage: NextPage = () => (
const currentTime = new Date(); <AppLayout header={<WorkspaceDashboardHeader />}>
<WorkspaceDashboardView />
const hour = new Intl.DateTimeFormat("en-US", { </AppLayout>
hour12: false, );
hour: "numeric",
}).format(currentTime);
const date = new Intl.DateTimeFormat("en-US", {
month: "short",
day: "numeric",
}).format(currentTime);
const weekDay = new Intl.DateTimeFormat("en-US", {
weekday: "long",
}).format(currentTime);
const timeString = new Intl.DateTimeFormat("en-US", {
timeZone: user?.user_timezone,
hour12: false, // Use 24-hour format
hour: "2-digit",
minute: "2-digit",
}).format(currentTime);
const greeting = parseInt(hour, 10) < 12 ? "morning" : parseInt(hour, 10) < 18 ? "afternoon" : "evening";
return (
<div>
<h3 className="text-2xl font-semibold">
Good {greeting}, {user?.first_name} {user?.last_name}
</h3>
<h6 className="text-custom-text-400 font-medium flex items-center gap-2">
<div>{greeting === "morning" ? "🌤️" : greeting === "afternoon" ? "🌥️" : "🌙️"}</div>
<div>
{weekDay}, {date} {timeString}
</div>
</h6>
</div>
);
};
const WorkspacePage: NextPage = () => {
const [month, setMonth] = useState(new Date().getMonth() + 1);
const [isProductUpdatesModalOpen, setIsProductUpdatesModalOpen] = useState(false);
const router = useRouter();
const { workspaceSlug } = router.query;
const { theme } = useTheme();
const { user } = useUser();
const { projects } = useProjects();
const { data: workspaceDashboardData } = useSWR(
workspaceSlug ? USER_WORKSPACE_DASHBOARD(workspaceSlug as string) : null,
workspaceSlug ? () => userService.userWorkspaceDashboard(workspaceSlug as string, month) : null
);
useEffect(() => {
if (!workspaceSlug) return;
mutate(USER_WORKSPACE_DASHBOARD(workspaceSlug as string));
}, [month, workspaceSlug]);
return (
<WorkspaceAuthorizationLayout
left={
<div className="flex items-center gap-2 pl-3">
<GridViewOutlined fontSize="small" />
Dashboard
</div>
}
right={
<div className="flex items-center gap-3 px-3">
<button
onClick={() => setIsProductUpdatesModalOpen(true)}
className="flex items-center gap-1.5 bg-custom-background-80 text-xs font-medium py-1.5 px-3 rounded"
>
<BoltOutlined fontSize="small" className="-my-1" />
What{"'"}s New?
</button>
<Link href="https://github.com/makeplane/plane" target="_blank" rel="noopener noreferrer">
<a className="flex items-center gap-1.5 bg-custom-background-80 text-xs font-medium py-1.5 px-3 rounded">
<Image
src={theme === "dark" ? githubWhiteImage : githubBlackImage}
height={16}
width={16}
alt="GitHub Logo"
/>
Star us on GitHub
</a>
</Link>
</div>
}
>
{isProductUpdatesModalOpen && (
<ProductUpdatesModal isOpen={isProductUpdatesModalOpen} setIsOpen={setIsProductUpdatesModalOpen} />
)}
{user && !user.is_tour_completed && (
<div className="fixed top-0 left-0 h-full w-full bg-custom-backdrop bg-opacity-50 transition-opacity z-20 grid place-items-center">
<TourRoot
onComplete={() => {
mutate<ICurrentUserResponse>(
CURRENT_USER,
(prevData) => {
if (!prevData) return prevData;
return {
...prevData,
is_tour_completed: true,
};
},
false
);
userService.updateUserTourCompleted(user).catch(() => mutate(CURRENT_USER));
}}
/>
</div>
)}
<div className="p-8 space-y-8">
<Greeting user={user} />
{projects ? (
projects.length > 0 ? (
<div className="flex flex-col gap-8">
<IssuesStats data={workspaceDashboardData} />
<div className="grid grid-cols-1 gap-8 lg:grid-cols-2">
<IssuesList issues={workspaceDashboardData?.overdue_issues} type="overdue" />
<IssuesList issues={workspaceDashboardData?.upcoming_issues} type="upcoming" />
<IssuesPieChart groupedIssues={workspaceDashboardData?.state_distribution} />
<CompletedIssuesGraph
issues={workspaceDashboardData?.completed_issues}
month={month}
setMonth={setMonth}
/>
</div>
</div>
) : (
<div className="bg-custom-primary-100/5 flex justify-between gap-5 md:gap-8">
<div className="p-5 md:p-8 pr-0">
<h5 className="text-xl font-semibold">Create a project</h5>
<p className="mt-2 mb-5">Manage your projects by creating issues, cycles, modules, views and pages.</p>
<PrimaryButton
onClick={() => {
const e = new KeyboardEvent("keydown", {
key: "p",
});
document.dispatchEvent(e);
}}
>
Create Project
</PrimaryButton>
</div>
<div className="hidden md:block self-end overflow-hidden pt-8">
<Image src={emptyDashboard} alt="Empty Dashboard" />
</div>
</div>
)
) : null}
</div>
</WorkspaceAuthorizationLayout>
);
};
export default WorkspacePage; export default WorkspacePage;

View File

@ -0,0 +1,71 @@
import { NextPage } from "next";
import Image from "next/image";
// components
import { EmailForgotPasswordForm, EmailForgotPasswordFormValues } from "components/account";
// layouts
import DefaultLayout from "layouts/default-layout";
// services
import { UserService } from "services/user.service";
// hooks
import useToast from "hooks/use-toast";
// images
import BluePlaneLogoWithoutText from "public/plane-logos/blue-without-text.png";
const userService = new UserService();
const ForgotPasswordPage: NextPage = () => {
// toast
const { setToastAlert } = useToast();
const handleForgotPassword = (formData: EmailForgotPasswordFormValues) => {
const payload = {
email: formData.email,
};
return userService
.forgotPassword(payload)
.then(() =>
setToastAlert({
type: "success",
title: "Success!",
message: "Password reset link has been sent to your email address.",
})
)
.catch((err) => {
if (err.status === 400)
setToastAlert({
type: "error",
title: "Error!",
message: "Please check the Email ID entered.",
});
else
setToastAlert({
type: "error",
title: "Error!",
message: "Something went wrong. Please try again.",
});
});
};
return (
<DefaultLayout>
<>
<div className="hidden sm:block sm:fixed border-r-[0.5px] border-custom-border-200 h-screen w-[0.5px] top-0 left-20 lg:left-32" />
<div className="fixed grid place-items-center bg-custom-background-100 sm:py-5 top-11 sm:top-12 left-7 sm:left-16 lg:left-28">
<div className="grid place-items-center bg-custom-background-100">
<div className="h-[30px] w-[30px]">
<Image src={BluePlaneLogoWithoutText} alt="Plane Logo" />
</div>
</div>
</div>
</>
<div className="grid place-items-center h-full overflow-y-auto py-6 px-7">
<div>
<h1 className="text-center text-2xl sm:text-2.5xl font-semibold text-custom-text-100">Forgot Password</h1>
<EmailForgotPasswordForm onSubmit={handleForgotPassword} />
</div>
</div>
</DefaultLayout>
);
};
export default ForgotPasswordPage;

View File

@ -3,12 +3,12 @@ import APIService from "services/api.service";
import trackEventServices from "services/track_event.service"; import trackEventServices from "services/track_event.service";
import type { import type {
ICurrentUserResponse,
IIssue, IIssue,
IUser, IUser,
IUserActivityResponse, IUserActivityResponse,
IUserProfileData, IUserProfileData,
IUserProfileProjectSegregation, IUserProfileProjectSegregation,
IUserSettings,
IUserWorkspaceDashboard, IUserWorkspaceDashboard,
} from "types"; } from "types";
@ -44,7 +44,7 @@ export class UserService extends APIService {
}); });
} }
async currentUser(): Promise<ICurrentUserResponse> { async currentUser(): Promise<IUser> {
return this.get("/api/users/me/") return this.get("/api/users/me/")
.then((response) => response?.data) .then((response) => response?.data)
.catch((error) => { .catch((error) => {
@ -52,6 +52,14 @@ export class UserService extends APIService {
}); });
} }
async currentUserSettings(): Promise<IUserSettings> {
return this.get("/api/users/me/settings/")
.then((response) => response?.data)
.catch((error) => {
throw error?.response;
});
}
async updateUser(data: Partial<IUser>): Promise<any> { async updateUser(data: Partial<IUser>): Promise<any> {
return this.patch("/api/users/me/", data) return this.patch("/api/users/me/", data)
.then((response) => response?.data) .then((response) => response?.data)
@ -60,7 +68,7 @@ export class UserService extends APIService {
}); });
} }
async updateUserOnBoard({ userRole }: any, user: ICurrentUserResponse | undefined): Promise<any> { async updateUserOnBoard({ userRole }: any, user: IUser | undefined): Promise<any> {
return this.patch("/api/users/me/onboard/", { return this.patch("/api/users/me/onboard/", {
is_onboarded: true, is_onboarded: true,
}) })
@ -78,7 +86,7 @@ export class UserService extends APIService {
}); });
} }
async updateUserTourCompleted(user: ICurrentUserResponse): Promise<any> { async updateUserTourCompleted(user: IUser): Promise<any> {
return this.patch("/api/users/me/tour-completed/", { return this.patch("/api/users/me/tour-completed/", {
is_tour_completed: true, is_tour_completed: true,
}) })

View File

@ -2,24 +2,34 @@
import { action, observable, computed, runInAction, makeObservable } from "mobx"; import { action, observable, computed, runInAction, makeObservable } from "mobx";
// services // services
import { UserService } from "services/user.service"; import { UserService } from "services/user.service";
import { WorkspaceService } from "services/workspace.service";
// interfaces // interfaces
import { ICurrentUser, ICurrentUserSettings } from "types/users"; import { IUser, IUserSettings } from "types/users";
interface IUserStore { interface IUserStore {
loader: boolean; loader: boolean;
currentUser: ICurrentUser | null; currentUser: IUser | null;
currentUserSettings: ICurrentUserSettings | null; currentUserSettings: IUserSettings | null;
fetchCurrentUser: () => Promise<ICurrentUser>; dashboardInfo: any;
memberInfo: any;
hasPermissionToWorkspace: boolean | null;
fetchCurrentUser: () => Promise<IUser>;
fetchCurrentUserSettings: () => Promise<IUserSettings>;
updateTourCompleted: () => Promise<void>;
} }
class UserStore implements IUserStore { class UserStore implements IUserStore {
loader: boolean = false; loader: boolean = false;
currentUser: ICurrentUser | null = null; currentUser: IUser | null = null;
currentUserSettings: ICurrentUserSettings | null = null; currentUserSettings: IUserSettings | null = null;
dashboardInfo: any = null;
memberInfo: any = null;
hasPermissionToWorkspace: boolean | null = null;
// root store // root store
rootStore; rootStore;
// services // services
userService; userService;
workspaceService;
constructor(_rootStore: any) { constructor(_rootStore: any) {
makeObservable(this, { makeObservable(this, {
@ -27,18 +37,22 @@ class UserStore implements IUserStore {
loader: observable.ref, loader: observable.ref,
currentUser: observable.ref, currentUser: observable.ref,
currentUserSettings: observable.ref, currentUserSettings: observable.ref,
dashboardInfo: observable.ref,
memberInfo: observable.ref,
hasPermissionToWorkspace: observable.ref,
// action // action
fetchCurrentUser: action, fetchCurrentUser: action,
fetchCurrentUserSettings: action,
// computed // computed
}); });
this.rootStore = _rootStore; this.rootStore = _rootStore;
this.userService = new UserService(); this.userService = new UserService();
this.workspaceService = new WorkspaceService();
} }
fetchCurrentUser = async () => { fetchCurrentUser = async () => {
try { try {
const response = await this.userService.currentUser(); const response = await this.userService.currentUser();
console.log("response", response);
if (response) { if (response) {
runInAction(() => { runInAction(() => {
this.currentUser = response; this.currentUser = response;
@ -50,6 +64,65 @@ class UserStore implements IUserStore {
} }
}; };
fetchCurrentUserSettings = async () => {
try {
const response = await this.userService.currentUserSettings();
if (response) {
runInAction(() => {
this.currentUserSettings = response;
});
}
return response;
} catch (error) {
throw error;
}
};
fetchUserDashboardInfo = async (workspaceSlug: string, month: number) => {
try {
const response = await this.userService.userWorkspaceDashboard(workspaceSlug, month);
runInAction(() => {
this.dashboardInfo = response;
});
return response;
} catch (error) {
throw error;
}
};
fetchUserWorkspaceInfo = async (workspaceSlug: string) => {
try {
const response = await this.workspaceService.workspaceMemberMe(workspaceSlug.toString());
runInAction(() => {
this.memberInfo = response;
this.hasPermissionToWorkspace = true;
});
return response;
} catch (error) {
runInAction(() => {
this.hasPermissionToWorkspace = false;
});
throw error;
}
};
updateTourCompleted = async () => {
try {
if (this.currentUser) {
runInAction(() => {
this.currentUser = {
...this.currentUser,
is_tour_completed: true,
} as IUser;
});
const response = await this.userService.updateUserTourCompleted(this.currentUser);
return response;
}
} catch (error) {
throw error;
}
};
// setCurrentUser = async () => { // setCurrentUser = async () => {
// try { // try {
// let userResponse: ICurrentUser | null = await UserService.currentUser(); // let userResponse: ICurrentUser | null = await UserService.currentUser();

125
web/types/users.d.ts vendored
View File

@ -1,44 +1,43 @@
import { import { IIssueActivity, IIssueLite, TStateGroups } from ".";
IIssue,
IIssueActivity,
IIssueLite,
IWorkspace,
IWorkspaceLite,
NestedKeyOf,
Properties,
TStateGroups,
} from ".";
export interface IUser { export interface IUser {
id: string;
avatar: string; avatar: string;
cover_image: string | null; cover_image: string | null;
created_at: readonly Date; date_joined: string;
created_location: readonly string;
date_joined: readonly Date;
email: string;
display_name: string; display_name: string;
email: string;
first_name: string; first_name: string;
id: readonly string; last_name: string;
is_active: boolean;
is_bot: boolean;
is_email_verified: boolean; is_email_verified: boolean;
is_managed: boolean;
is_onboarded: boolean; is_onboarded: boolean;
is_tour_completed: boolean; is_tour_completed: boolean;
last_location: readonly string; mobile_number: string | null;
last_login: readonly Date; role: string | null;
last_name: string; onboarding_step: {
mobile_number: string; workspace_join?: boolean;
my_issues_prop: { profile_complete?: boolean;
properties: Properties; workspace_create?: boolean;
groupBy: NestedKeyOf<IIssue> | null; workspace_invite?: boolean;
} | null; };
onboarding_step: TOnboardingSteps;
role: string;
token: string;
theme: ICustomTheme;
updated_at: readonly Date;
username: string;
user_timezone: string; user_timezone: string;
username: string;
theme: ICustomTheme | {};
}
[...rest: string]: any; export interface IUserSettings {
id: string;
email: string;
workspace: {
last_workspace_id: string;
last_workspace_slug: string;
fallback_workspace_id: string;
fallback_workspace_slug: string;
invites: number;
};
} }
export interface ICustomTheme { export interface ICustomTheme {
@ -52,18 +51,6 @@ export interface ICustomTheme {
theme: string; theme: string;
} }
export interface ICurrentUserResponse extends IUser {
assigned_issues: number;
last_workspace_id: string | null;
workspace_invites: number;
workspace: {
fallback_workspace_id: string | null;
fallback_workspace_slug: string | null;
invites: number;
last_workspace_id: string | null;
last_workspace_slug: string | null;
};
}
export interface IUserLite { export interface IUserLite {
avatar: string; avatar: string;
created_at: Date; created_at: Date;
@ -166,32 +153,32 @@ export interface IUserProfileProjectSegregation {
}; };
} }
export interface ICurrentUser { // export interface ICurrentUser {
id: readonly string; // id: readonly string;
avatar: string; // avatar: string;
first_name: string; // first_name: string;
last_name: string; // last_name: string;
username: string; // username: string;
email: string; // email: string;
mobile_number: string; // mobile_number: string;
is_email_verified: boolean; // is_email_verified: boolean;
is_tour_completed: boolean; // is_tour_completed: boolean;
onboarding_step: TOnboardingSteps; // onboarding_step: TOnboardingSteps;
is_onboarded: boolean; // is_onboarded: boolean;
role: string; // role: string;
} // }
export interface ICustomTheme { // export interface ICustomTheme {
background: string; // background: string;
text: string; // text: string;
primary: string; // primary: string;
sidebarBackground: string; // sidebarBackground: string;
sidebarText: string; // sidebarText: string;
darkPalette: boolean; // darkPalette: boolean;
palette: string; // palette: string;
theme: string; // theme: string;
} // }
export interface ICurrentUserSettings { // export interface ICurrentUserSettings {
theme: ICustomTheme; // theme: ICustomTheme;
} // }