Skip to content

Commit

Permalink
refactor: bug fixes and further improvements in company setup
Browse files Browse the repository at this point in the history
  • Loading branch information
bencodes07 committed Sep 13, 2024
1 parent 099609a commit 0f093fd
Show file tree
Hide file tree
Showing 4 changed files with 124 additions and 88 deletions.
202 changes: 119 additions & 83 deletions src/app/company/setup/page.tsx
Original file line number Diff line number Diff line change
@@ -1,131 +1,167 @@
"use client";
import React, { useRef, useEffect } from "react";
import React, { useRef, useEffect, useState } from "react";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Progress } from "@/components/ui/progress";
import Image from "next/image";
// import { gql, useMutation } from "@apollo/client";
// import { CREATE_COMPANY} from "@/lib/graphql/mutations";
import { type FetchResult, useMutation } from "@apollo/client";
import { CREATE_COMPANY } from "@/lib/graphql/mutations";
import Loader from "@/components/layout/Loader";
import { router } from "next/client";
import { toast } from "@/components/ui/use-toast";

type Inputs = {
type DisplayInputs = {
"Full Company Name": string;
"CEO Email": string;
"CEO Name": string;
"CEO Password": string;
};

function Setup() {
const [step, setStep] = React.useState(0);
type MutationInputs = {
companyName: string;
ownerEmail: string;
ownerName: string;
ownerPassword: string;
};

const [inputs, setInputs] = React.useState<Inputs>({
function Setup() {
const [step, setStep] = useState(0);
const [inputs, setInputs] = useState<DisplayInputs>({
"Full Company Name": "",
"CEO Email": "",
"CEO Name": "",
"CEO Password": ""
});

const placeholders = ["Full Company Name", "CEO Email", "CEO Name", "CEO Password"];
const input: React.MutableRefObject<HTMLInputElement | null> = useRef(null);
const [error, setError] = React.useState<string>("");
// const [createCompany, { data, loading, error: mutationError }] = useMutation(CREATE_COMPANY);
const input = useRef<HTMLInputElement>(null);
const [error, setError] = useState<string>("");
const [createCompany, { loading, error: mutationError }] = useMutation(CREATE_COMPANY);

const nextStep = () => {
if (input.current?.value === "") {
if (input.current?.value === null) {
setError("Please fill in the input field");
return;
} else if (input.current?.validity.valid === false) {
}
if (step === 1 && input.current?.validity.valid === false) {
setError("Please enter a valid email");
return;
} else {
setError("");
setStep(step + 1);
}
setError("");
setStep((prev) => prev + 1);
};

const submit = async () => {
if (input.current?.value === "") {
if (input.current?.value === null) {
setError("Please fill in the input field");
return;
} else setError("");
}
if (input.current?.validity.valid === false) {
setError("Please enter a valid password");
return;
} else {
setError("");
console.info("submitting", inputs);

setStep(4);
// await createCompany({ variables: inputs }).then((res) => {
// console.log("done", res);
// });
}

const allInputsFilled = Object.values(inputs).every((value) => value.trim() !== "");
if (!allInputsFilled) {
setError("Please fill in all fields");
return;
}

setError("");
console.info("submitting", inputs);

const mutationInputs: MutationInputs = {
companyName: inputs["Full Company Name"],
ownerEmail: inputs["CEO Email"],
ownerName: inputs["CEO Name"],
ownerPassword: inputs["CEO Password"]
};

try {
const res: FetchResult<{ createCompany: string }> = await createCompany({ variables: mutationInputs });
if (res.data?.createCompany.includes("200") === true) {
toast({
title: "Company created!",
description: "You can now login to your account",
variant: "default",
className: "border-emerald-300"
});
setTimeout(() => {
void router.push("/login");
}, 1000);
} else {
setError("An error occurred while creating the company: " + res.data?.createCompany);
}
} catch (err) {
console.error("Mutation error:", err);
setError("An error occurred while creating the company");
}
};

useEffect(() => {
const onKeyDown = (e: KeyboardEvent) => {
const handleKeyDown = (e: KeyboardEvent) => {
if (e.key === "Enter") {
if (step === 3)
submit().catch((err) => {
console.error(err);
});
else nextStep();
if (step === 3) {
void submit();
} else {
nextStep();
}
}
};

window.addEventListener("keydown", onKeyDown);
window.addEventListener("keydown", handleKeyDown);
return () => {
window.removeEventListener("keydown", onKeyDown);
window.removeEventListener("keydown", handleKeyDown);
};
}, [step]);
}, [step, inputs]);

if (loading || step === 4) return <Loader />;

return (
<div className={"flex h-screen flex-col items-center justify-start"}>
<div className={"flex h-1/6 items-center justify-center gap-2"}>
<Image src={"/landingLogo.png"} width={40} height={40} alt={""} />
<h1 className={"text-2xl font-semibold"}>MeetMate</h1>
<div className="flex h-screen flex-col items-center justify-start">
<div className="flex h-1/6 items-center justify-center gap-2">
<Image src="/landingLogo.png" width={40} height={40} alt="" />
<h1 className="text-2xl font-semibold">MeetMate</h1>
</div>
<div className={"mt-[-16.667svh] flex h-full flex-col items-center justify-center"}>
{step === 4 ? (
<Loader />
) : (
<React.Fragment>
<Input
maxLength={45}
type={step === 1 ? "email" : step === 3 ? "password" : "text"}
ref={input}
value={inputs[placeholders[step] as keyof Inputs]}
onChange={(e) => {
setInputs({ ...inputs, [placeholders[step]]: e.target.value });
}}
placeholder={placeholders[step]}
className={"border-0 text-lg font-medium text-foreground focus-visible:ring-0"}
/>
<Progress
className={"h-1 drop-shadow-glow max-sm:w-[350px] sm:w-[450px] md:w-[600px] lg:w-[960px]"}
value={(step / 3) * 100}
/>

<div className={"mt-2 flex items-center justify-center gap-x-2 self-end"}>
<p className={"text-sm text-red-500"}>{error}</p>
{step > 0 && (
<Button
size={"sm"}
onClick={() => {
setStep(step - 1);
}}>
Back
</Button>
)}
{step < 3 && (
<Button size={"sm"} onClick={nextStep}>
Next
</Button>
)}
{step === 3 && (
<Button size={"sm"} onClick={submit}>
Finish
</Button>
)}
</div>
</React.Fragment>
)}
<div className="mt-[-16.667svh] flex h-full flex-col items-center justify-center">
<Input
maxLength={45}
type={step === 1 ? "email" : step === 3 ? "password" : "text"}
ref={input}
value={inputs[placeholders[step] as keyof DisplayInputs]}
onChange={(e) => {
setInputs((prev) => ({ ...prev, [placeholders[step]]: e.target.value }));
}}
placeholder={placeholders[step]}
className="border-0 text-lg font-medium text-foreground focus-visible:ring-0"
/>
<Progress
className="h-1 drop-shadow-glow max-sm:w-[350px] sm:w-[450px] md:w-[600px] lg:w-[960px]"
value={(step / 3) * 100}
/>

<div className="mt-2 flex items-center justify-center gap-x-2 self-end">
<p className="text-sm text-red-500">{error !== "" || (mutationError !== null && mutationError?.message)}</p>
{step > 0 && (
<Button
size="sm"
onClick={() => {
setStep((prev) => prev - 1);
}}>
Back
</Button>
)}
{step < 3 && (
<Button size="sm" onClick={nextStep}>
Next
</Button>
)}
{step === 3 && (
<Button size="sm" onClick={submit}>
Finish
</Button>
)}
</div>
</div>
</div>
);
Expand Down
2 changes: 1 addition & 1 deletion src/app/dashboard/bookings/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ function Bookings() {

useEffect(() => {
if (false) setAppointments([]);
setCompanies([]);
if (false) setCompanies([]);
}, []);

const [filteredAppointments, setFilteredAppointments] = useState<Appointment[]>(appointments);
Expand Down
6 changes: 3 additions & 3 deletions src/lib/authActions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ export async function refreshAccessToken(refreshToken?: string) {
});
return res.access_Token;
}
} else if (response.status === 401 || response.status === 403) {
} else if (response.status === 401 || response.status === 403 || response.status === 500) {
return undefined;
} else {
throw new Error("There was a problem refreshing the access token: " + response.statusText);
Expand All @@ -86,10 +86,10 @@ export async function getUser(accessToken?: string): Promise<User | null> {

if (response.ok) {
return (await response.json()) as User;
} else if (response.status === 403) {
} else if (response.status === 403 || response.status === 500) {
return null;
} else {
throw new Error("There was a problem fetching the user: " + response.statusText);
throw new Error("There was a problem fetching the user: " + response.statusText + " " + response.status);
}
}

Expand Down
2 changes: 1 addition & 1 deletion src/middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ export async function middleware(req: NextRequest) {
response = NextResponse.redirect(new URL("/company/dashboard", req.url));
} else if (
req.nextUrl.pathname.startsWith("/company/dashboard") &&
!["COMPANY_MEMBER", "COMPANY_ADMIN"].includes(user.role)
!["COMPANY_MEMBER", "COMPANY_OWNER"].includes(user.role)
) {
response = NextResponse.redirect(new URL("/dashboard", req.url));
}
Expand Down

0 comments on commit 0f093fd

Please sign in to comment.