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

Commit

Permalink
fix: fix pr issues
Browse files Browse the repository at this point in the history
  • Loading branch information
ArshiLamba committed Aug 11, 2024
1 parent ac7440b commit 29cec50
Show file tree
Hide file tree
Showing 7 changed files with 134 additions and 129 deletions.
24 changes: 23 additions & 1 deletion client/src/lib/api-types/dashboard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,32 @@ import * as z from 'zod';

import { dashboard } from './schemas';
import type { SuccessResponse, ErrorResponse } from './index';
import { dashboardUpdateSchema } from './schemas/dashboard';

/**
* Successful response for /v1/user endpoint
*/
// Define types for sales data and sustainability data
interface SalesData {
date: string;
amount: number;
}

interface SustainabilityData {
label: string; // Ensure the 'label' property is included
value: number;
}

// Define the Dashboard type using z.infer and dashboardUpdateSchema
export type Dashboard = z.infer<typeof dashboardUpdateSchema>;

export interface DashboardResponse {
data: DashboardResponse | PromiseLike<DashboardResponse>;
dashboard: Dashboard[];
salesData: SalesData[];
sustainabilityData: SustainabilityData[];
}

export interface GetDashboardSuccAPI
extends SuccessResponse<{
dashboard: Array<z.infer<typeof dashboard.dashboardSchema>>;
Expand All @@ -22,7 +44,7 @@ export interface GetDashboardSuccAPI
sustainabilityData: {
label: string;
value: number;
}[]; // Add this array for sustainability data
}[];
}> {}

/**
Expand Down
55 changes: 12 additions & 43 deletions client/src/pages/user/dashboard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import { useEffect, useState } from 'react';
import httpClient from '@utils/http';
import { PageComponent } from '@pages/route-map';
import { dashboardUpdateSchema } from '@lib/api-types/schemas/dashboard';
import { z } from 'zod';
import Graph from '@components/ui/graph';
import SustainabilityPieChart from '@components/ui/pieChart';
import { Input } from '@components/ui/input';
Expand All @@ -17,59 +16,29 @@ import {
} from '@tanstack/react-query';
import { isAxiosError } from 'axios';
import { cn } from '@utils/tailwind';
import { DashboardResponse, Dashboard } from '@lib/api-types/dashboard';

// Define types for sales data and sustainability data
interface SalesData {
date: string;
amount: number;
}

interface SustainabilityData {
label: string; // Ensure the 'label' property is included
value: number;
}

// Define the Dashboard type using z.infer and dashboardUpdateSchema
type Dashboard = z.infer<typeof dashboardUpdateSchema>;

interface DashboardResponse {
data: DashboardResponse | PromiseLike<DashboardResponse>;
dashboard: Dashboard[];
salesData: SalesData[];
sustainabilityData: SustainabilityData[];
}

const Dashboard: PageComponent = ({ className, ...props }) => {
const DashboardPage: PageComponent = ({ className, ...props }) => {
const [error, setError] = useState<string | null>(null);
const [successMessage, setSuccessMessage] = useState<string | null>(null);
const [isEditing, setIsEditing] = useState(false);
const queryClient = useQueryClient();

// Fetch dashboard data from the server
const { data, isError, isLoading }: UseQueryResult<DashboardResponse> =
const { data, isError, isLoading }: UseQueryResult<DashboardResponse, Error> =
useQuery<DashboardResponse>({
queryKey: ['dashboard'],
queryFn: async (): Promise<DashboardResponse> => {
try {
const response = await httpClient.get<DashboardResponse>({
uri: '/dashboard',
withCredentials: 'access', // Pass withCredentials as 'access'
});
return response.data; // Ensure you're returning the data property
} catch (err) {
console.error('Fetch error:', err);
throw err;
}
queryFn: async () => {
const response = await httpClient.get<DashboardResponse>({
uri: '/dashboard',
withCredentials: 'access',
});
return response.data;
},
onError: (err: unknown) => {
if (isAxiosError(err) && err.response) {
setError('Error fetching dashboard data! Please try again later.');
} else {
setError('An unexpected error occurred. Please try again later.');
}
console.error('Query error:', err);
console.log(err); // Simplified error logging
},
} as UseQueryOptions<DashboardResponse, Error>); // Ensure the options type matches
} as UseQueryOptions<DashboardResponse, Error>);

// Initialize form with empty values
const DashboardForm = useForm<Dashboard>({
Expand Down Expand Up @@ -223,4 +192,4 @@ const Dashboard: PageComponent = ({ className, ...props }) => {
);
};

export default Dashboard;
export default DashboardPage;
4 changes: 2 additions & 2 deletions client/src/pages/user/route-map.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import EventList from './event-list';
import AccountSettings from './settings';
import Home from './homepage';
import FeedbackForm from './feedback';
import Dashboard from './dashboard';
import DashboardPage from './dashboard';

const userRouteMap: RouteMap = {
'/settings': {
Expand Down Expand Up @@ -48,7 +48,7 @@ const userRouteMap: RouteMap = {
'/dashboard': {
title: 'Dashboard',
description: 'Check all the relevant details here',
component: Dashboard,
component: DashboardPage,
accessLevel: 'authenticated',
},
} as const;
Expand Down
2 changes: 1 addition & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

24 changes: 23 additions & 1 deletion server/src/lib/api-types/dashboard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,32 @@ import * as z from 'zod';

import { dashboard } from './schemas';
import type { SuccessResponse, ErrorResponse } from './index';
import { dashboardUpdateSchema } from './schemas/dashboard';

/**
* Successful response for /v1/user endpoint
*/
// Define types for sales data and sustainability data
interface SalesData {
date: string;
amount: number;
}

interface SustainabilityData {
label: string; // Ensure the 'label' property is included
value: number;
}

// Define the Dashboard type using z.infer and dashboardUpdateSchema
export type Dashboard = z.infer<typeof dashboardUpdateSchema>;

export interface DashboardResponse {
data: DashboardResponse | PromiseLike<DashboardResponse>;
dashboard: Dashboard[];
salesData: SalesData[];
sustainabilityData: SustainabilityData[];
}

export interface GetDashboardSuccAPI
extends SuccessResponse<{
dashboard: Array<z.infer<typeof dashboard.dashboardSchema>>;
Expand All @@ -22,7 +44,7 @@ export interface GetDashboardSuccAPI
sustainabilityData: {
label: string;
value: number;
}[]; // Add this array for sustainability data
}[];
}> {}

/**
Expand Down
130 changes: 50 additions & 80 deletions server/src/v1/dashboard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,79 +13,57 @@ import { Http4XX } from '../lib/api-types/http-codes';
import { ZodIssue } from 'zod';

export const getDashboard: IAuthedRouteHandler = async (req, res) => {
if (!req.user) {
return res.status(401).json({
status: 401,
errors: [{ message: 'User is not logged in' }],
// Fetch dashboard data from the database
const dashboard = await db
.select()
.from(dashboardTable)
.where(eq(dashboardTable.userId, req.user.id)); // Filter by the user's ID

if (dashboard.length === 0) {
return res.status(404).json({
status: 404,
errors: [{ message: 'No dashboard found for this user' }],
} satisfies GetDashboardFailAPI);
}

try {
// Fetch dashboard data from the database
const dashboard = await db
.select()
.from(dashboardTable)
.where(eq(dashboardTable.userId, req.user.id)); // Filter by the user's ID

if (dashboard.length === 0) {
return res.status(404).json({
status: 404,
errors: [{ message: 'No dashboard found for this user' }],
} satisfies GetDashboardFailAPI);
}

const formattedDashboard = dashboard.map((dashboard) => ({
id: dashboard.id,
title: dashboard.title,
description: dashboard.description || undefined,
createdAt: dashboard.createdAt,
updatedAt: dashboard.updatedAt,
}));
const formattedDashboard = dashboard.map((dashboard) => ({
id: dashboard.id,
title: dashboard.title,
description: dashboard.description || undefined,
createdAt: dashboard.createdAt,
updatedAt: dashboard.updatedAt,
}));

// Calculate sales data (dummy data for illustration)
const salesData = [
{ date: '2023-01-01', amount: 100 },
{ date: '2023-02-01', amount: 200 },
{ date: '2023-03-01', amount: 150 },
{ date: '2023-04-01', amount: 350 },
{ date: '2023-05-01', amount: 250 },
{ date: '2023-06-01', amount: 400 },
];
// Calculate sales data (dummy data for illustration)
const salesData = [
{ date: '2023-01-01', amount: 100 },
{ date: '2023-02-01', amount: 200 },
{ date: '2023-03-01', amount: 150 },
{ date: '2023-04-01', amount: 350 },
{ date: '2023-05-01', amount: 250 },
{ date: '2023-06-01', amount: 400 },
];

// Food sustainability data for the pie chart (dummy data)
const sustainabilityData = [
{ label: 'Local Sourcing', value: 30 },
{ label: 'Organic Produce', value: 25 },
{ label: 'Waste Reduction', value: 20 },
{ label: 'Energy Efficiency', value: 15 },
{ label: 'Water Conservation', value: 10 },
];
// Food sustainability data for the pie chart (dummy data)
const sustainabilityData = [
{ label: 'Local Sourcing', value: 30 },
{ label: 'Organic Produce', value: 25 },
{ label: 'Waste Reduction', value: 20 },
{ label: 'Energy Efficiency', value: 15 },
{ label: 'Water Conservation', value: 10 },
];

return res.status(200).json({
status: 200,
data: {
dashboard: formattedDashboard,
salesData: salesData,
sustainabilityData: sustainabilityData, // Include sustainability data here
},
} satisfies GetDashboardSuccAPI);
} catch (error) {
console.error(error);
return res.status(500).json({
status: 500,
errors: [{ message: 'Internal server error!' }],
} satisfies GetDashboardFailAPI);
}
return res.status(200).json({
status: 200,
data: {
dashboard: formattedDashboard,
salesData: salesData,
sustainabilityData: sustainabilityData, // Include sustainability data here
},
} satisfies GetDashboardSuccAPI);
};

export const updateDashboard: IAuthedRouteHandler = async (req, res) => {
if (!req.user) {
return res.status(401).json({
status: 401,
errors: [{ message: 'User is not logged in' }],
} satisfies UpdateDashboardFailAPI);
}

const validated = schemas.dashboard.dashboardUpdateSchema.safeParse(req.body);
if (!validated.success) {
const errorStack: errors.CustomErrorContext[] = [];
Expand All @@ -112,21 +90,13 @@ export const updateDashboard: IAuthedRouteHandler = async (req, res) => {
} satisfies UpdateDashboardFailAPI);
}

try {
await db
.update(dashboardTable)
.set(validated.data)
.where(eq(dashboardTable.userId, req.user.id)); // Filter by the user's ID
await db
.update(dashboardTable)
.set(validated.data)
.where(eq(dashboardTable.userId, req.user.id)); // Filter by the user's ID

return res.status(200).json({
status: 200,
data: { updated: true },
} satisfies UpdateDashboardSuccAPI);
} catch (error) {
console.error('Database update error:', error);
return res.status(500).json({
status: 500,
errors: [{ message: 'Internal server error!' }],
} satisfies UpdateDashboardFailAPI);
}
return res.status(200).json({
status: 200,
data: { updated: true },
} satisfies UpdateDashboardSuccAPI);
};
24 changes: 23 additions & 1 deletion shared/api-types/src/dashboard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,32 @@ import * as z from 'zod';

import { dashboard } from './schemas';
import type { SuccessResponse, ErrorResponse } from './index';
import { dashboardUpdateSchema } from './schemas/dashboard';

/**
* Successful response for /v1/user endpoint
*/
// Define types for sales data and sustainability data
interface SalesData {
date: string;
amount: number;
}

interface SustainabilityData {
label: string; // Ensure the 'label' property is included
value: number;
}

// Define the Dashboard type using z.infer and dashboardUpdateSchema
export type Dashboard = z.infer<typeof dashboardUpdateSchema>;

export interface DashboardResponse {
data: DashboardResponse | PromiseLike<DashboardResponse>;
dashboard: Dashboard[];
salesData: SalesData[];
sustainabilityData: SustainabilityData[];
}

export interface GetDashboardSuccAPI
extends SuccessResponse<{
dashboard: Array<z.infer<typeof dashboard.dashboardSchema>>;
Expand All @@ -22,7 +44,7 @@ export interface GetDashboardSuccAPI
sustainabilityData: {
label: string;
value: number;
}[]; // Add this array for sustainability data
}[];
}> {}

/**
Expand Down

0 comments on commit 29cec50

Please sign in to comment.