Skip to content

Commit

Permalink
add absences to profile page
Browse files Browse the repository at this point in the history
- create endpoints for user absences and id by email
  • Loading branch information
135ze committed Jul 11, 2024
1 parent a254945 commit f1f9ee0
Show file tree
Hide file tree
Showing 7 changed files with 237 additions and 41 deletions.
7 changes: 6 additions & 1 deletion Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,17 @@ WORKDIR /sistema

# Copy package.json and package-lock.json
COPY package.json package-lock.json ./
COPY prisma ./prisma/

# Install dependencies using npm
RUN npm install

# Expose the port the app runs on
# Generate the Prisma client
RUN npx prisma generate

# Expose the ports the app runs on
EXPOSE 3000
EXPOSE 5432

# Start the Next.js application in development mode
CMD ["npm", "run", "dev"]
30 changes: 30 additions & 0 deletions app/api/users/absences/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { PrismaClient } from '@prisma/client';
import { NextRequest, NextResponse } from 'next/server';

const prisma = new PrismaClient();

export async function GET(req: NextRequest) {
const { searchParams } = new URL(req.url);
const encodedId = searchParams.get('id');
console.log('ID: ' + encodedId);

if (!encodedId) {
return new NextResponse('ID not provided', { status: 400 });
}

const id = Number(decodeURIComponent(encodedId));

if (Number.isNaN(id)) {
return new NextResponse('ID not a number', { status: 400 });
}

try {
const absences = await prisma.absence.findMany({
where: { id: id },
});

return new NextResponse(JSON.stringify(absences), { status: 200 });
} catch (error) {
return new NextResponse('Internal server error', { status: 500 });
}
}
31 changes: 31 additions & 0 deletions app/api/users/get-user-by-email/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { PrismaClient } from '@prisma/client';
import { NextRequest, NextResponse } from 'next/server';

const prisma = new PrismaClient();

export async function GET(req: NextRequest) {
const { searchParams } = new URL(req.url);
const encodedEmail = searchParams.get('email');

if (!encodedEmail) {
return new NextResponse('Email not provided', { status: 400 });
}

// const email = decodeURIComponent(encodedEmail);
console.log('email: ' + decodeURIComponent(encodedEmail)); // proof
// choosing an email inside the db instead:
const email = '[email protected]';
try {
const user = await prisma.user.findUnique({
where: { email },
});

if (!user) {
return new NextResponse('User not found', { status: 400 });
} else {
return new NextResponse(JSON.stringify(user), { status: 200 });
}
} catch (error) {
return new NextResponse('Internal server error', { status: 500 });
}
}
10 changes: 10 additions & 0 deletions app/api/users/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { PrismaClient } from '@prisma/client';
import { NextRequest, NextResponse } from 'next/server';

const prisma = new PrismaClient();

export async function GET(req: NextRequest) {
const users = await prisma.user.findMany();
console.log(users);
return NextResponse.json(users);
}
77 changes: 72 additions & 5 deletions package-lock.json

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

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
"@emotion/react": "^11.9.0",
"@emotion/styled": "^11.9.0",
"@faker-js/faker": "^8.4.1",
"@prisma/client": "^5.15.1",
"@prisma/client": "^5.16.2",
"@snaplet/copycat": "^5.0.0",
"@snaplet/seed": "^0.97.20",
"framer-motion": "^6.3.0",
Expand Down
121 changes: 87 additions & 34 deletions src/pages/profile.tsx
Original file line number Diff line number Diff line change
@@ -1,34 +1,87 @@
import { useSession } from 'next-auth/react';
import { SignInButton } from '../components/SignInButton';
import { SignOutButton } from '../components/SignOutButton';

export default function AnotherPage() {
const { data: session, status } = useSession();

return (
<div>
<h1>Profile</h1>
<hr/>
{status === 'loading' ? (
<p>Loading...</p>
) : session && session.user ? (
<div>
<h2>Personal Information</h2>
<p>Name: {session.user.name}</p>
<p>Email: {session.user.email}</p>
<p>Image:</p>
{session.user.image && <img src={session.user.image} alt="User Image" />}

<hr/>
<h2>Metrics</h2>
<p>Absences:</p>
<hr/>
</div>
) : (
<p>Error: Signed out</p>
)}
<hr/>
<SignOutButton />
</div>
);
}
import { useSession } from 'next-auth/react';
import { useEffect, useState } from 'react';
import { SignOutButton } from '../components/SignOutButton';

export default function AnotherPage() {
const { data: session, status } = useSession();
const [userId, setUserId] = useState(null);
const [numAbsences, setNumAbsences] = useState(null);
const [usedAbsences, setUsedAbsences] = useState(null);

useEffect(() => {
const fetchUserInfoByEmail = async () => {
if (!session || !session.user || !session.user.email) return;

const email = session.user.email;
const apiUrl = `/api/users/get-user-by-email?email=${encodeURIComponent(email)}`;

try {
const response = await fetch(apiUrl);
if (!response.ok) {
throw new Error(response.statusText);
}
const data = await response.json();
setUserId(data['id']);
setNumAbsences(data['numOfAbsences']);
} catch (error) {
console.error('Error fetching data:', error);
}
};

fetchUserInfoByEmail();
}, [session]);

useEffect(() => {
const fetctUsedAbsences = async () => {
if (userId === null || userId === undefined) return;

const apiUrl = `/api/users/absences?id=${encodeURIComponent(userId)}`;

try {
const response = await fetch(apiUrl);
if (!response.ok) {
throw new Error(response.statusText);
}
const data = await response.json();
const usedAbsences = data.length;
setUsedAbsences(usedAbsences);
console.log('used absences: ' + usedAbsences);
} catch (error) {
console.error('Error fetching data:', error);
}
};

fetctUsedAbsences();
}, [userId]);

return (
<div>
<h1>Profile</h1>
<hr />
{status === 'loading' ? (
<p>Loading...</p>
) : session && session.user ? (
<div>
<h2>Personal Information</h2>
<p>Name: {session.user.name}</p>
<p>Email: {session.user.email}</p>
<p>Image:</p>
{session.user.image && (
<img src={session.user.image} alt="User Image" />

Check warning on line 70 in src/pages/profile.tsx

View workflow job for this annotation

GitHub Actions / lint

Using `<img>` could result in slower LCP and higher bandwidth. Consider using `<Image />` from `next/image` to automatically optimize images. This may incur additional usage or cost from your provider. See: https://nextjs.org/docs/messages/no-img-element
)}

<hr />
<h2>Metrics</h2>
<p>
Absences: {usedAbsences} / {numAbsences}{' '}
</p>
<hr />
</div>
) : (
<p>Error: Signed out</p>
)}
<hr />
<SignOutButton />
</div>
);
}

0 comments on commit f1f9ee0

Please sign in to comment.