Skip to content

Commit

Permalink
feat: removed company store; added graphql fetching
Browse files Browse the repository at this point in the history
  • Loading branch information
bencodes07 committed Oct 24, 2024
1 parent 7c28a4b commit e48062a
Show file tree
Hide file tree
Showing 7 changed files with 97 additions and 129 deletions.
7 changes: 4 additions & 3 deletions src/app/dashboard/bookings/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -43,13 +43,14 @@ import { useDashboardData } from "@/components/dashboard/DashboardContext";
import { type Appointment } from "@/types";
import { useSelector } from "react-redux";
import { type RootState } from "@/store/store";
import { useCollection } from "@/components/dashboard/CollectionContext";

function Bookings() {
const { user } = useDashboardData();
const [searchQuery, setSearchQuery] = useState("");
const appointments = useSelector((state: RootState) => state.collection.appointments);

const companies = useSelector((state: RootState) => state.collection.companies);
const { companies } = useCollection();

const [filteredAppointments, setFilteredAppointments] = useState<Appointment[]>(appointments);
const router = useRouter();
Expand Down Expand Up @@ -223,7 +224,7 @@ function Bookings() {
<SelectValue placeholder="Select a company" />
</SelectTrigger>
<SelectContent className={"border-border"}>
{companies.map((company) => (
{companies?.map((company) => (
<SelectItem key={company.id} value={company.id}>
{company.name}
</SelectItem>
Expand Down Expand Up @@ -268,7 +269,7 @@ function Bookings() {
<DialogTitle>Confirm Booking</DialogTitle>
<DialogDescription>Please confirm your appointment details:</DialogDescription>
<div>
<p>Company: {companies.find((c) => c.id === bookingState.selectedCompany)?.name}</p>
<p>Company: {companies?.find((c) => c.id === bookingState.selectedCompany)?.name}</p>
<p>Date: {bookingState.selectedDate.toDateString()}</p>
<p>Time: {bookingState.selectedTime}</p>
</div>
Expand Down
7 changes: 3 additions & 4 deletions src/app/dashboard/browse/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,16 +13,15 @@ import { Avatar, AvatarFallback } from "@/components/ui/avatar";
import { extractNameInitials } from "@/lib/utils";
import { useRouter } from "next/navigation";
import { deleteToken } from "@/lib/authActions";
import { useSelector } from "react-redux";
import type { RootState } from "@/store/store";
import FollowButton from "@/components/dashboard/FollowButton";
import { useUser } from "@/components/dashboard/UserContext";
import { useCollection } from "@/components/dashboard/CollectionContext";

function CompanyBrowse() {
const { user } = useUser();
const router = useRouter();

const { companies } = useSelector((state: RootState) => state.collection);
const { companies } = useCollection();

const logout = async () => {
try {
Expand Down Expand Up @@ -74,7 +73,7 @@ function CompanyBrowse() {
className={
"mt-8 grid w-full gap-6 max-lg:grid-cols-1 lg:grid-cols-2 xl:grid-cols-2 2xl:grid-cols-3 min-[1900px]:grid-cols-4"
}>
{companies.map((company) => (
{companies?.map((company) => (
<div
key={company.id}
className={
Expand Down
64 changes: 33 additions & 31 deletions src/app/dashboard/company/[id]/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,28 +14,43 @@ import { extractNameInitials } from "@/lib/utils";
import React from "react";
import { useRouter } from "next/navigation";
import { deleteToken } from "@/lib/authActions";
import Image from "next/image";
import FollowButton from "@/components/dashboard/FollowButton";
import { useUser } from "@/components/dashboard/UserContext";
import { useQuery } from "@apollo/client";
import { getCompany } from "@/lib/graphql/queries";
import Loader from "@/components/layout/Loader";

export default function Page({ params }: { params: { id: string } }) {
const { user } = useUser();

const router = useRouter();
const { loading, error, data } = useQuery(getCompany, {
variables: { id: params.id },
// Optional: configure caching and refetching
fetchPolicy: "cache-and-network",
// Optional: refetch every 5 minutes
pollInterval: 300000
});

const logout = async () => {
try {
await deleteToken();
window.location.reload();
} catch (error) {
console.error("Logout failed", error);
throw error;
} catch (logoutError) {
console.error("Logout failed", logoutError);
throw logoutError;
}
};

if (loading) return <Loader />;

if (error !== undefined) return <div>Error: {error.message}</div>;

return (
<div className="flex h-[calc(100%-32px)] flex-col items-start justify-start p-8 px-6">
<header className="flex w-full flex-row items-center justify-between">
<h1 className="m-4 font-medium text-muted-foreground md:text-2xl">GitHub (ID: {params.id})</h1>
<h1 className="m-4 font-medium text-muted-foreground md:text-2xl">
{data.getCompany.name} (ID: {params.id})
</h1>
<div className="flex items-center gap-x-6">
<Input className="w-[320px]" placeholder="Search"></Input>
<DropdownMenu modal={false}>
Expand Down Expand Up @@ -69,40 +84,27 @@ export default function Page({ params }: { params: { id: string } }) {
</div>
</header>

<Image
className={"mt-8 flex w-full rounded-[20px]"}
src={"https://files.readme.io/d14112d-Cloudsmith-Integrations-Banner-GitHub.png"}
width={1410}
height={300}
alt={""}
/>

<div className="mt-8 flex h-[600px] w-full flex-col rounded-[20px] px-12">
<div className={"mt-6 flex h-[200px] w-full items-center justify-between"}>
<div className={"flex flex-row items-center justify-center"}>
<Image
className={"size-[200px] rounded-full"}
src={"https://github.githubassets.com/assets/GitHub-Mark-ea2971cee799.png"}
alt={""}
width={200}
height={200}
/>
<div
className={
"flex size-[200px] items-center justify-center rounded-full bg-primary text-6xl font-medium text-foreground"
}>
{extractNameInitials(data.getCompany.name as string)}
</div>
<div className={"ml-12 flex flex-col"}>
<h1 className={"text-4xl font-semibold"}>GitHub</h1>
<p className={"ml-2 mt-2"}>
GitHub is a code hosting platform for version control and collaboration. It lets you and others work
together on projects from anywhere.
</p>
<h1 className={"text-4xl font-semibold"}>{data.getCompany.name}</h1>
</div>
</div>
<FollowButton companyId={params.id} />
</div>
<p className={"mt-10 text-muted-foreground"}>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore
magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla
pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id
est laborum.
{data.getCompany.description !== "" ? (
data.getCompany.description
) : (
<i>This company has not provided a description</i>
)}
</p>
</div>
</div>
Expand Down
17 changes: 9 additions & 8 deletions src/app/dashboard/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,14 @@ import { cn } from "@/lib/utils";
import Loader from "@/components/layout/Loader";
import { DashboardProvider } from "@/components/dashboard/DashboardContext";
import { FaPlus } from "react-icons/fa6";
import { useSelector } from "react-redux";
import type { RootState } from "@/store/store";
import { UserProvider, useUser } from "@/components/dashboard/UserContext";
import { CollectionProvider, useCollection } from "@/components/dashboard/CollectionContext";

function DashboardContent({ children }: { children: React.ReactNode }) {
const { user, loading } = useUser();
const [active, setActive] = useState<"dashboard" | "bookings" | "settings">("dashboard");
const [companyIndicatorTop, setCompanyIndicatorTop] = useState(0);
const companies = useSelector((state: RootState) => state.collection.companies);
const { companies } = useCollection();
const pathname = usePathname();

useEffect(() => {
Expand All @@ -30,11 +29,11 @@ function DashboardContent({ children }: { children: React.ReactNode }) {
setActive("dashboard");
}

if (pathname.includes("/dashboard/browse")) {
if (pathname.includes("/dashboard/browse") && companies !== undefined) {
setCompanyIndicatorTop(companies.length * 72 + 144);
} else {
// Derive the top position of the company indicator
const companyIndex = companies.findIndex((company) => pathname.includes(company.id));
const companyIndex = companies?.findIndex((company) => pathname.includes(company.id)) ?? 0;
setCompanyIndicatorTop(companyIndex === -1 ? 40 : 144 + 72 * companyIndex);
}
}, [pathname, companies]);
Expand All @@ -55,7 +54,7 @@ function DashboardContent({ children }: { children: React.ReactNode }) {
</Link>
</div>
<div className="mt-14 flex flex-col gap-y-6">
{companies.map((company) => (
{companies?.map((company) => (
<Link key={company.id} className={"size-12"} href={`/dashboard/company/${company.id}`}>
<div
title={company.name}
Expand Down Expand Up @@ -93,7 +92,7 @@ function DashboardContent({ children }: { children: React.ReactNode }) {
: "Dashboard"}
</Button>
</Link>
{!companies.some((company) => pathname.includes(company.id)) &&
{companies?.some((company) => pathname.includes(company.id)) === false &&
!pathname.includes("/dashboard/browse") && (
<Link href={"/dashboard/bookings"}>
<Button
Expand Down Expand Up @@ -160,7 +159,9 @@ function DashboardContent({ children }: { children: React.ReactNode }) {
export default function DashboardLayout({ children }: { children: React.ReactNode }) {
return (
<UserProvider>
<DashboardContent>{children}</DashboardContent>
<CollectionProvider>
<DashboardContent>{children}</DashboardContent>
</CollectionProvider>
</UserProvider>
);
}
32 changes: 32 additions & 0 deletions src/components/dashboard/CollectionContext.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import React, { createContext, useContext } from "react";
import { type Company } from "@/types";
import { useQuery } from "@apollo/client";
import { getCompanies } from "@/lib/graphql/queries";

type CollectionContextType = {
companies: Company[] | undefined;
loading: boolean;
refreshCompanies: () => Promise<void>;
};

const CollectionContext = createContext<CollectionContextType | undefined>(undefined);

export function CollectionProvider({ children }: { children: React.ReactNode }) {
const { loading, data: companies = [], refetch } = useQuery(getCompanies, { pollInterval: 300000 });

const refreshCompanies = async () => {
await refetch();
};

return (
<CollectionContext.Provider value={{ companies, loading, refreshCompanies }}>{children}</CollectionContext.Provider>
);
}

export function useCollection() {
const context = useContext(CollectionContext);
if (context === undefined) {
throw new Error("useCollection must be used within a CollectionProvider");
}
return context;
}
15 changes: 14 additions & 1 deletion src/lib/graphql/queries.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,21 @@
import { gql } from "@apollo/client";

export const getCompany = gql`
query GetCompany($id: ID!) {
getCompany(id: $id) {
id
name
description
businessType
memberIds
ownerEmail
}
}
`;

export const getCompanies = gql`
query {
getCompany {
getCompanies {
id
name
description
Expand Down
84 changes: 2 additions & 82 deletions src/store/features/collectionSlice.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
import { createSlice, type PayloadAction } from "@reduxjs/toolkit";
import { type Appointment, type Company } from "@/types";
import { Role } from "@/types/role";
import { type Appointment } from "@/types";

type CollectionState = {
appointments: Appointment[];
companies: Company[];
};

const initialState: CollectionState = {
Expand Down Expand Up @@ -42,81 +40,6 @@ const initialState: CollectionState = {
client: null,
status: "BOOKED"
}
],
companies: [
{
id: "0",
name: "GitHub",
createdAt: new Date(2024, 8, 23).toDateString(),
description: "GitHub is a web-based platform for version control and collaboration.",
owner: {
id: 124,
name: "John Doe",
email: "[email protected]",
role: Role.COMPANY_ADMIN,
companyID: "1"
},
members: [],
settings: {
appointmentDuration: 60,
appointmentBuffer: 15,
appointmentTypes: [],
appointmentLocations: [],
openingHours: {
from: "08:00",
to: "18:00"
}
}
},
{
id: "1",
name: "Vercel",
createdAt: new Date(2024, 8, 23).toDateString(),
description: "Vercel is a cloud platform for static sites and Serverless Functions.",
owner: {
id: 123,
name: "John Doe",
email: "[email protected]",
role: Role.COMPANY_ADMIN,
companyID: "2"
},
members: [],
settings: {
appointmentDuration: 60,
appointmentBuffer: 15,
appointmentTypes: [],
appointmentLocations: [],
openingHours: {
from: "08:00",
to: "18:00"
}
}
},
{
id: "2",
name: "Google",
createdAt: new Date(2024, 8, 23).toDateString(),
description:
"Google is an American multinational technology company that specializes in Internet-related services and products.",
owner: {
id: 125,
name: "John Doe",
email: "[email protected]",
role: Role.COMPANY_ADMIN,
companyID: "3"
},
members: [],
settings: {
appointmentDuration: 60,
appointmentBuffer: 15,
appointmentTypes: [],
appointmentLocations: [],
openingHours: {
from: "08:00",
to: "18:00"
}
}
}
]
};

Expand All @@ -126,13 +49,10 @@ export const collectionSlice = createSlice({
reducers: {
setAppointments(state, action: PayloadAction<Appointment[]>) {
state.appointments = action.payload;
},
setCompanies(state, action: PayloadAction<Company[]>) {
state.companies = action.payload;
}
}
});

export const { setAppointments, setCompanies } = collectionSlice.actions;
export const { setAppointments } = collectionSlice.actions;

export default collectionSlice.reducer;

0 comments on commit e48062a

Please sign in to comment.