Skip to content

Commit

Permalink
merge with dev
Browse files Browse the repository at this point in the history
  • Loading branch information
vancik01 committed Apr 11, 2024
2 parents 9250016 + b4c4124 commit e150c8f
Show file tree
Hide file tree
Showing 20 changed files with 553 additions and 62 deletions.
9 changes: 8 additions & 1 deletion @types/event.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { HarmonogramItem, SallaryType } from "@prisma/client";
import { EventPresenceStatus, SallaryType } from "@prisma/client";

/**
* Request
Expand Down Expand Up @@ -54,3 +54,10 @@ export interface CreateHarmonogramItemData {
from: string;
to: string;
}

export interface AttendanceItemData {
userID: string;
presenceStatus: EventPresenceStatus;
arrivedAt: string;
leftAt: string;
}
3 changes: 2 additions & 1 deletion prisma/dbml/schema.dbml
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,9 @@ Table User {
id String [pk]
email String [unique, not null]
createdAt DateTime [default: `now()`, not null]
deletedAt DateTime
password String [not null]
name String [not null]
verificationToken String
phoneNumber String
type AccountType
avatarURL String
Expand Down Expand Up @@ -66,6 +66,7 @@ Table EventAssignment {
arrivedAt DateTime
leftAt DateTime
presenceStatus EventPresenceStatus [not null, default: 'NOT_PRESENT']
hoursWorked Int
}

Table EventCategory {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
/*
Warnings:
- You are about to drop the column `verificationToken` on the `User` table. All the data in the column will be lost.
*/
-- AlterTable
ALTER TABLE "User" DROP COLUMN "verificationToken";
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
-- AlterTable
ALTER TABLE "EventAssignment" ADD COLUMN "hoursWorked" INTEGER;
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
-- AlterTable
ALTER TABLE "User" ADD COLUMN "deletedAt" TIMESTAMP(3);
25 changes: 13 additions & 12 deletions prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -56,18 +56,18 @@ enum ColorVariant {
}

model User {
id String @id @default(cuid())
email String @unique
createdAt DateTime @default(now())
password String
name String
verificationToken String?
phoneNumber String?
type AccountType?
avatarURL String?
EventAssignment EventAssignment[]
AnnouncementItem AnnouncementItem[]
Event Event[]
id String @id @default(cuid())
email String @unique
createdAt DateTime @default(now())
deletedAt DateTime?
password String
name String
phoneNumber String?
type AccountType?
avatarURL String?
EventAssignment EventAssignment[]
AnnouncementItem AnnouncementItem[]
Event Event[]
}

model Location {
Expand Down Expand Up @@ -121,6 +121,7 @@ model EventAssignment {
arrivedAt DateTime?
leftAt DateTime?
presenceStatus EventPresenceStatus @default(NOT_PRESENT)
hoursWorked Int?
}

model EventCategory {
Expand Down
116 changes: 98 additions & 18 deletions prisma/seed.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ import {
AccountType,
ColorVariant,
Event,
EventAssignmentStatus,
EventPresenceStatus,
EventStatus,
PrismaClient,
SallaryType,
Expand Down Expand Up @@ -30,11 +32,17 @@ const getRandomimage = () =>
max: 1000
})}/1280/720`;

const getRandomUser = (type: AccountType, n: number, email?: string) => {
const getRandomUser = (
type: AccountType,
n: number,
email?: string,
id?: string
) => {
return Array(n)
.fill("")
.map((_, i) => {
return {
id: id ? id : undefined,
email: email ? email : faker.internet.email(),
name: faker.person.fullName(),
phoneNumber: faker.phone.number(),
Expand All @@ -45,15 +53,18 @@ const getRandomUser = (type: AccountType, n: number, email?: string) => {
});
};

const getRandomEventData = () => {
const getRandomEventData = (capacity?: number, id?: string) => {
const sallaryType = faker.datatype.boolean()
? SallaryType.GOODS
: SallaryType.MONEY;

const ret = {
capacity: faker.number.int({ min: 5, max: 10 }),
id: id ? id : undefined,
capacity: capacity ? capacity : faker.number.int({ min: 5, max: 10 }),
description: faker.commerce.productDescription(),
happeningAt: faker.date.future(),
happeningAt: moment(faker.date.soon())
.set("hour", faker.number.int({ min: 6, max: 10 }))
.toDate(),
name: faker.commerce.productName(),
sallaryType: sallaryType,
sallaryAmount:
Expand Down Expand Up @@ -98,6 +109,21 @@ function slugify(title: string) {
.toLowerCase(); // Convert to lowercase
}

function generateNearbyCoordinate(
centerLat: number,
centerLon: number,
radius = 0.1
) {
return {
latitude:
centerLat +
faker.number.float() * radius * (faker.datatype.boolean() ? 1 : -1),
longitude:
centerLon +
faker.number.float() * radius * (faker.datatype.boolean() ? 1 : -1)
};
}

async function main() {
const fruitsAndVegetablesEmojis: {
emoji: string;
Expand Down Expand Up @@ -150,23 +176,29 @@ async function main() {

await prisma.user.createMany({
data: [
...getRandomUser("ORGANISER", 1, "[email protected]"),
...getRandomUser("ORGANISER", 1, "[email protected]"),
...getRandomUser("ORGANISER", 1, "[email protected]")
...getRandomUser("ORGANISER", 1, "[email protected]", "admin1"),
...getRandomUser("ORGANISER", 1, "[email protected]", "admin2"),
...getRandomUser("ORGANISER", 1, "[email protected]", "admin3")
]
});
const adminUsers = await prisma.user.findMany({ select: { id: true } });

await prisma.location.createMany({
data: Array(15)
.fill("")
.map((_, i) => ({
name: faker.company.name(),
address: faker.location.streetAddress(),
city: faker.location.city(),
locationLat: faker.location.latitude({ max: 180, min: -180 }),
locationLon: faker.location.longitude({ max: 180, min: -180 })
}))
.map((_, i) => {
const { latitude, longitude } = generateNearbyCoordinate(
48.934328,
18.160032
);
return {
name: faker.company.name(),
address: faker.location.streetAddress(),
city: faker.location.city(),
locationLat: latitude,
locationLon: longitude
};
})
});

const locations = await prisma.location.findMany({ select: { id: true } });
Expand All @@ -193,7 +225,7 @@ async function main() {
{ length: faker.number.int({ min: 0, max: event.capacity }) },
async () =>
prisma.user.create({
data: getRandomUser("ORGANISER", 1)[0],
data: getRandomUser("HARVESTER", 1)[0],
select: { id: true }
})
);
Expand Down Expand Up @@ -248,7 +280,12 @@ async function main() {
});

const workerId = await prisma.user.create({
data: getRandomUser("ORGANISER", 1, "[email protected]")[0],
data: getRandomUser(
"HARVESTER",
1,
"[email protected]",
"harvester1"
)[0],
select: {
id: true
}
Expand All @@ -258,7 +295,11 @@ async function main() {
data: {
userId: adminUsers[0].id,
locationId: locations[0].id,
...{ ...getRandomEventData(), status: "PROGRESS" }
...{
...getRandomEventData(15, "liveEventId"),
status: "PROGRESS",
happeningAt: moment().set("hours", 7).toDate()
}
},
select: {
id: true,
Expand All @@ -278,7 +319,7 @@ async function main() {

const userIds = await Promise.all(userPromises);

await Promise.all(
const assignments = await Promise.all(
userIds.map((user) =>
prisma.eventAssignment.create({
data: {
Expand All @@ -296,6 +337,45 @@ async function main() {
}
});

await Promise.all(
assignments.map((assignment) => {
const statusChangeTo = faker.helpers.arrayElement([
EventPresenceStatus.PRESENT,
EventPresenceStatus.LEFT,
EventPresenceStatus.DID_NOT_ARRIVE
]);

const arrivedAt = [
EventPresenceStatus.PRESENT.toString(),
EventPresenceStatus.LEFT.toString()
].includes(statusChangeTo)
? moment(liveEvent.happeningAt)
.add(faker.number.int({ min: 2, max: 45 }), "minutes")
.toDate()
: undefined;

const leftAt = [EventPresenceStatus.LEFT.toString()].includes(
statusChangeTo
)
? moment(arrivedAt)
.add(faker.number.int({ min: 2, max: 12 }), "hours")
.add(faker.number.int({ min: 2, max: 45 }), "minutes")
.toDate()
: undefined;

return prisma.eventAssignment.update({
data: {
presenceStatus: statusChangeTo,
arrivedAt: arrivedAt,
leftAt: leftAt
},
where: {
id: assignment.id
}
});
})
);

await Promise.all(
Array(5)
.fill("")
Expand Down
Binary file added src/.DS_Store
Binary file not shown.
43 changes: 40 additions & 3 deletions src/endpoints/events/[eventId]/endEvent.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import {
AccountType,
EventAssignmentStatus,
EventPresenceStatus,
EventStatus,
PrismaClient
Expand All @@ -9,6 +10,7 @@ import { ThrowInternalServerError } from "../../../errorResponses/internalServer
import { ThrowNotFound } from "../../../errorResponses/notFound404";
import { UserDecodedData } from "../../../../@types/jwtToken";
import { ThrowForbidden } from "../../../errorResponses/forbidden403";
import moment from "moment";

const prisma = new PrismaClient();

Expand All @@ -33,16 +35,53 @@ export const endEvent = async (req: Request, res: Response) => {
return ThrowNotFound(res);
}

const qwe = await prisma.eventAssignment.findMany({
where: {
eventId: eventId,
presenceStatus: {
in: [EventPresenceStatus.LEFT]
}
}
});

await prisma.eventAssignment.updateMany({
where: {
eventId: eventId
eventId: eventId,
presenceStatus: EventPresenceStatus.PRESENT,
assignmentStatus: EventAssignmentStatus.ACTIVE
},
data: {
presenceStatus: EventPresenceStatus.LEFT,
leftAt: new Date()
}
});

const assignmentIds = await prisma.eventAssignment.findMany({
where: {
presenceStatus: EventPresenceStatus.LEFT,
assignmentStatus: EventAssignmentStatus.ACTIVE
}
});

await Promise.all(
assignmentIds.map(async (assignment) => {
const hours_worked =
moment(assignment.leftAt).diff(
moment(assignment.arrivedAt),
"hours"
) + 1;
console.log(assignment, hours_worked);
await prisma.eventAssignment.update({
where: {
id: assignment.id
},
data: {
hoursWorked: hours_worked > 0 ? hours_worked : 0
}
});
})
);

await prisma.event.update({
where: {
id: eventId
Expand All @@ -52,8 +91,6 @@ export const endEvent = async (req: Request, res: Response) => {
}
});

// TODO: calculate insights for the company about sallary for each worker

return res.status(200).send();
} catch (error) {
return ThrowInternalServerError(res);
Expand Down
Loading

0 comments on commit e150c8f

Please sign in to comment.