Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Gde crud journey event step comment #11

Merged
merged 7 commits into from
Jun 24, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -109,15 +109,16 @@ CREATE TABLE "Step" (
);

-- CreateTable
CREATE TABLE "UserStep" (
CREATE TABLE "EventUserStep" (
"id" SERIAL NOT NULL,
"userId" INTEGER NOT NULL,
"stepId" INTEGER NOT NULL,
"startAt" TIMESTAMP(3) NOT NULL,
"endAt" TIMESTAMP(3) NOT NULL,
"duration" INTEGER NOT NULL,
"eventId" INTEGER NOT NULL,
"startAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"endAt" TIMESTAMP(3),
"durationMs" INTEGER,

CONSTRAINT "UserStep_pkey" PRIMARY KEY ("id")
CONSTRAINT "EventUserStep_pkey" PRIMARY KEY ("id")
);

-- CreateTable
Expand Down Expand Up @@ -161,10 +162,13 @@ ALTER TABLE "Journey" ADD CONSTRAINT "Journey_authorId_fkey" FOREIGN KEY ("autho
ALTER TABLE "Step" ADD CONSTRAINT "Step_journeyId_fkey" FOREIGN KEY ("journeyId") REFERENCES "Journey"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "UserStep" ADD CONSTRAINT "UserStep_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE "EventUserStep" ADD CONSTRAINT "EventUserStep_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "EventUserStep" ADD CONSTRAINT "EventUserStep_stepId_fkey" FOREIGN KEY ("stepId") REFERENCES "Step"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "UserStep" ADD CONSTRAINT "UserStep_stepId_fkey" FOREIGN KEY ("stepId") REFERENCES "Step"("id") ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE "EventUserStep" ADD CONSTRAINT "EventUserStep_eventId_fkey" FOREIGN KEY ("eventId") REFERENCES "Event"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "Comment" ADD CONSTRAINT "Comment_authorId_fkey" FOREIGN KEY ("authorId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;
Expand Down
105 changes: 54 additions & 51 deletions prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -21,24 +21,24 @@ model Role {
}

model User {
id Int @id @default(autoincrement())
name String?
lastName String?
email String @unique
username String
password String
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
isVerified Boolean @default(false)
dateOfBirth DateTime?
avatar String?
experience Int @default(0)
userRoles UserRole[] // liste des rôles de l'utilisateur
userEvents UserEvent[] // liste des events auxquels l'utilisateur participe
userSteps UserStep[] // liste des étapes réalisées par l'utilisateur
comments Comment[] // liste des commentaires créés par l'utilisateur
journey Journey[] // liste des parcours créés par l'utilisateur
events Event[] // liste des events créés par l'utilisateur
id Int @id @default(autoincrement())
name String?
lastName String?
email String @unique
username String
password String
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
isVerified Boolean @default(false)
dateOfBirth DateTime?
avatar String?
experience Int @default(0)
userRoles UserRole[] // liste des rôles de l'utilisateur
userEvents UserEvent[] // liste des events auxquels l'utilisateur participe
EventUserSteps EventUserStep[] // liste des étapes réalisées par l'utilisateur
comments Comment[] // liste des commentaires créés par l'utilisateur
journey Journey[] // liste des parcours créés par l'utilisateur
events Event[] // liste des events créés par l'utilisateur
}

model UserRole {
Expand All @@ -50,23 +50,24 @@ model UserRole {
}

model Event {
id Int @id @default(autoincrement())
id Int @id @default(autoincrement())
authorId Int
journeyId Int
title String
image String
numberPlayerMin Int
numberPlayerMax Int
description String
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
isPrivate Boolean @default(false)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
isPrivate Boolean @default(false)
accessCode String?
startAt DateTime
endAt DateTime
userEvents UserEvent[]
author User @relation(fields: [authorId], references: [id], onDelete: Cascade)
journey Journey @relation(fields: [journeyId], references: [id], onDelete: Cascade)
author User @relation(fields: [authorId], references: [id], onDelete: Cascade)
journey Journey @relation(fields: [journeyId], references: [id], onDelete: Cascade)
EventUserStep EventUserStep[]
}

model UserEvent {
Expand Down Expand Up @@ -102,35 +103,37 @@ model Journey {
}

model Step {
id Int @id @default(autoincrement())
journeyId Int
puzzle String
answer String
hint String
picturePuzzle String?
pictureHint String?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
latitude Float
longitude Float
address String?
city String?
postalCode String?
country String?
stepNumber Int
journey Journey @relation(fields: [journeyId], references: [id], onDelete: Cascade)
userSteps UserStep[]
id Int @id @default(autoincrement())
journeyId Int
puzzle String
answer String
hint String
picturePuzzle String?
pictureHint String?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
latitude Float
longitude Float
address String?
city String?
postalCode String?
country String?
stepNumber Int
journey Journey @relation(fields: [journeyId], references: [id], onDelete: Cascade)
EventUserSteps EventUserStep[]
}

model UserStep {
id Int @id @default(autoincrement())
userId Int
stepId Int
startAt DateTime
endAt DateTime
duration Int
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
step Step @relation(fields: [stepId], references: [id], onDelete: Cascade)
model EventUserStep {
id Int @id @default(autoincrement())
userId Int
stepId Int
eventId Int
startAt DateTime @default(now())
endAt DateTime?
durationMs Int?
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
step Step @relation(fields: [stepId], references: [id], onDelete: Cascade)
event Event @relation(fields: [eventId], references: [id], onDelete: Cascade)
}

model Comment {
Expand Down
45 changes: 22 additions & 23 deletions prisma/seed.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1039,7 +1039,7 @@ async function main() {
// Generate a random number of events for the user between 0 and 6
let numEvents = Math.floor(Math.random() * 7);

// Ensure that Bob, Henry, and Grace are registered for at least one event because we create userStep for this users
// Ensure that Bob, Henry, and Grace are registered for at least one event because we create EventUserStep for these users
if (
users[i].id === bob.id ||
users[i].id === henry.id ||
Expand Down Expand Up @@ -1258,29 +1258,27 @@ async function main() {
select: { eventId: true },
});

const generateUserSteps = async (userId: number, eventIds: number[]) => {
const journeyIds = new Set<number>();

const generateEventUserStep = async (userId: number, eventIds: number[]) => {
for (const eventId of eventIds) {
const event = await prisma.event.findUnique({ where: { id: eventId } });
const event = await prisma.event.findUnique({
where: { id: eventId },
select: { journeyId: true },
});
if (!event) continue;

journeyIds.add(event.journeyId);
}

const journeys = await prisma.journey.findMany({
where: { id: { in: Array.from(journeyIds) } },
select: { id: true, steps: true },
});
const journey = await prisma.journey.findUnique({
where: { id: event.journeyId },
select: { id: true, steps: true },
});

for (const journey of journeys) {
let numberOfStepsBeforeEnd: number = 0;
if (!journey) continue;

if (userId === bob.id) numberOfStepsBeforeEnd = 0;
if (userId === grace.id) numberOfStepsBeforeEnd = 1;
if (userId === henry.id) numberOfStepsBeforeEnd = 2;
// Randomize the number of steps completed by the user for this event
const numberOfStepsToComplete = Math.floor(
Math.random() * journey.steps.length
);

for (let i = 0; i < journey.steps.length - numberOfStepsBeforeEnd; i++) {
for (let i = 0; i < numberOfStepsToComplete; i++) {
const step = journey.steps[i];
const startAt = new Date();
// Randomly generate a duration between 30 minutes and 2 hours for each step
Expand All @@ -1293,28 +1291,29 @@ async function main() {
);
const duration = endAt.getTime() - startAt.getTime();

await prisma.userStep.create({
await prisma.eventUserStep.create({
data: {
userId: userId,
stepId: step.id,
eventId: eventId,
startAt: startAt,
endAt: endAt,
duration: duration,
durationMs: duration,
},
});
}
}
};

await generateUserSteps(
await generateEventUserStep(
bob.id,
bobEvents.map((event) => event.eventId)
);
await generateUserSteps(
await generateEventUserStep(
henry.id,
henryEvents.map((event) => event.eventId)
);
await generateUserSteps(
await generateEventUserStep(
grace.id,
graceEvents.map((event) => event.eventId)
);
Expand Down
4 changes: 3 additions & 1 deletion src/app/api/auth/[...nextauth]/route.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import NextAuth from "next-auth";
import { authOptions } from "@/lib/authOptions";

// TODO
// @ts-ignore
const handler = NextAuth(authOptions);

export { handler as GET, handler as POST };
export { handler as GET, handler as POST };
8 changes: 4 additions & 4 deletions src/app/api/comments/[id]/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@ import {
registerOrModifyComment,
removeComment,
} from "@/services/commentService";
import { CommentWithoutDates } from "@/types/CommentWithoutDates";
import { CommentWithoutDates } from "@/types/comment";
import { commentBodySchema } from "@/validators/api/commentSchema";
import { NextRequest, NextResponse } from "next/server";

/**
Expand Down Expand Up @@ -39,9 +40,8 @@ export async function PUT(
try {
const id: number = Number(params.id);
const body = await request.json();
const comment: CommentWithoutDates = body.comment;

console.log("COMMENT : " + comment);
// Parse the body with zod to get the comment
const comment: CommentWithoutDates = commentBodySchema.parse(body).comment;

const result = await registerOrModifyComment(id, comment);
return NextResponse.json({ data: result }, { status: 200 });
Expand Down
7 changes: 3 additions & 4 deletions src/app/api/comments/route.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { handleException } from "@/app/utils/errorHandlerUtils";
import { registerOrModifyComment } from "@/services/commentService";
import { CommentWithoutDates } from "@/types/CommentWithoutDates";
import { CommentWithoutDates } from "@/types/comment";
import { commentBodySchema } from "@/validators/api/commentSchema";
import { NextRequest, NextResponse } from "next/server";

Expand All @@ -12,9 +12,8 @@ import { NextRequest, NextResponse } from "next/server";
export async function POST(request: NextRequest) {
try {
const body = await request.json();
const commentParsed = commentBodySchema.parse(body);

const comment: CommentWithoutDates = commentParsed.comment;
// Parse the body with zod to get the comment
const comment: CommentWithoutDates = commentBodySchema.parse(body).comment;

const result = await registerOrModifyComment(null, comment);
return NextResponse.json({ data: result }, { status: 201 });
Expand Down
4 changes: 2 additions & 2 deletions src/app/api/events/[id]/join/[userId]/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,10 @@ export async function POST(
{ params }: { params: { id: string; userId: string } }
) {
try {
const id: number = Number(params.id);
const eventId: number = Number(params.id);
const userId: number = Number(params.userId);

const result = await joinEvent(id, userId);
const result = await joinEvent(eventId, userId);
return NextResponse.json({ data: result }, { status: 200 });
} catch (error: any) {
return handleException(error);
Expand Down
7 changes: 4 additions & 3 deletions src/app/api/events/[id]/leave/[userId]/route.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { handleException } from "@/app/utils/errorHandlerUtils";
import { leaveEvent } from "@/services/eventService";
import { NextRequest, NextResponse } from "next/server";
import { NextRequest } from "next/server";

/**
* @params request: NextRequest
Expand All @@ -13,10 +13,11 @@ export async function DELETE(
{ params }: { params: { id: string; userId: string } }
) {
try {
const id: number = Number(params.id);
const eventId: number = Number(params.id);
const userId: number = Number(params.userId);

const result = await leaveEvent(id, userId);
const result = await leaveEvent(eventId, userId);

// Using Response instead of NextResponse because NextResponse doesn't handle status 204 actually
return new Response(null, {
status: 204,
Expand Down
7 changes: 5 additions & 2 deletions src/app/api/events/[id]/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@ import {
registerOrModifyEvent,
removeEvent,
} from "@/services/eventService";
import { Event } from "@prisma/client";
import { EventWithoutId } from "@/types/event";
import { eventBodySchema } from "@/validators/api/eventSchema";
import { NextRequest, NextResponse } from "next/server";

/**
Expand Down Expand Up @@ -39,7 +40,9 @@ export async function PUT(
try {
const id: number = Number(params.id);
const body = await request.json();
const event: Event = body.event;

// Parse the body with zod to get the event
const event: EventWithoutId = eventBodySchema.parse(body).event;

const result = await registerOrModifyEvent(id, event);
return NextResponse.json({ data: result }, { status: 200 });
Expand Down
Loading
Loading