Skip to content

Commit

Permalink
v2024.05.28
Browse files Browse the repository at this point in the history
  • Loading branch information
jonassimoen committed May 28, 2024
2 parents fbe8a44 + 4201345 commit 3552dc8
Show file tree
Hide file tree
Showing 13 changed files with 155 additions and 356 deletions.
7 changes: 3 additions & 4 deletions api/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,7 @@ import dotenv from "dotenv";
dotenv.config();

export const server = fastify({
logger: {
level: "info",
},
logger: true,
disableRequestLogging: true,
});

Expand All @@ -36,7 +34,7 @@ server.register(require("fastify-stripe"), {

server.register(cors, {
origin:
process.env.ENV === ("production" || "prod")
["production", "staging"].includes(process.env.ENV || "dev")
? process.env.CORS_ORIGIN
: "*",
credentials: true,
Expand Down Expand Up @@ -65,6 +63,7 @@ server.get("/metrics/prisma", async (req: any, res: any) => {
})

server.setErrorHandler((err, req, rep) => {
req.log.error(err);
if (err instanceof HttpError) {
rep.status(err.statusCode || 500).send({
statusCode: err.statusCode || 500,
Expand Down
41 changes: 10 additions & 31 deletions prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,6 @@ model User {
teams Team[]
Audit Audit[]
NotificationToken NotificationToken[]
Article Article[]
}

model Player {
Expand All @@ -58,10 +56,10 @@ model Player {
value Float?
selections Selection[]
club Club? @relation(fields: [clubId], references: [id], onDelete: Cascade)
club Club? @relation(fields: [clubId], references: [id], onDelete: Cascade)
stats Statistic[]
inPlayer Transfer[] @relation("inPlayer")
outPlayer Transfer[] @relation("outPlayer")
inPlayer Transfer[] @relation("inPlayer")
outPlayer Transfer[] @relation("outPlayer")
}

model Statistic {
Expand Down Expand Up @@ -182,9 +180,11 @@ model Week {
id Int @id @default(autoincrement())
deadlineDate DateTime @db.Timestamptz()
name String?
validated Boolean @default(false)
maxTransfers Int @default(2)
maxSameClub Int @default(3)
Team Team[]
Match Match[]
validated Boolean @default(false)
Selection Selection[]
Transfer Transfer[]
}
Expand Down Expand Up @@ -225,8 +225,8 @@ model Match {
// roundId Int
date DateTime @db.Timestamptz()
postponed Int?
homeScore Int? @default(-1)
awayScore Int? @default(-1)
homeScore Int? @default(0)
awayScore Int? @default(0)
homeId Int?
awayId Int?
Expand All @@ -235,8 +235,8 @@ model Match {
home Club? @relation(name: "homeMatch", fields: [homeId], references: [id])
away Club? @relation(name: "awayMatch", fields: [awayId], references: [id])
week Week? @relation(fields: [weekId], references: [id])
Statistic Statistic[]
week Week? @relation(fields: [weekId], references: [id])
Statistic Statistic[]
}

model Transfer {
Expand Down Expand Up @@ -284,24 +284,3 @@ model Audit {
user User @relation(fields: [userId], references: [id])
}

model NotificationToken {
id Int @id @default(autoincrement())
token String
timestamp DateTime
user User @relation(fields: [userId], references: [id])
userId Int
}

model Article {
id Int @id @default(autoincrement())
slug String
title String
description String
imageUrl String?
readMore Boolean?
timestampCreated DateTime
timestampUpdated DateTime?
author User @relation(fields: [authorId], references: [id])
authorId Int
}
94 changes: 0 additions & 94 deletions src/controllers/News.ts

This file was deleted.

38 changes: 0 additions & 38 deletions src/controllers/Notification.ts

This file was deleted.

73 changes: 44 additions & 29 deletions src/controllers/Team.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,38 @@
import { finalWeekId, upcomingWeekId } from '../utils/Common';
import { finalWeekId, upcomingWeekId, validateStartingLineup } from '../utils/Common';
import { prisma } from "../db/client"
import HttpError from "../utils/HttpError";
import { max } from "lodash";
import { isValidLineup } from '../utils/FootballPicker';

const GetPlayerByIds = async (allPlayerIds: number[], reqBody: any, weekId: number, skipReturn?: boolean) => {
const allPlayers = await prisma.player.findMany({
where: {
id: {
in: allPlayerIds
const CheckValidTeam = async (allPlayerIds: number[], reqBody: any, weekId: number, skipReturn?: boolean) => {
const [allPlayers, maxSameClub] = await Promise.all([
await prisma.player.findMany({
where: {
id: {
in: allPlayerIds
}
},
select: {
id: true,
clubId: true,
positionId: true,
value: true,
},
}),
(await prisma.week.findFirst({
select: {
maxSameClub: true
},
where: {
deadlineDate: {
gte: new Date()
}
},
orderBy: {
deadlineDate: 'asc',
}
},
select: {
id: true,
clubId: true,
positionId: true,
value: true,
},
});

}))?.maxSameClub || 0
]) ;
// Business rules checks
// 1. Correct positions
const pos = allPlayers.reduce((res: number[], cur: any) => {
Expand All @@ -27,13 +41,13 @@ const GetPlayerByIds = async (allPlayerIds: number[], reqBody: any, weekId: numb
}, [0,0,0,0,0])
if(pos.toString() !== "0,2,5,5,3")
throw new HttpError("Wrong selection of positions", 403);
// 2. Max 3 players from club
// 2. Max players from same club
const clubs = allPlayers.reduce((res: number[], cur: any) => {
res[cur.clubId] = (res[cur.clubId] || 0) + 1;
return res;
}, [])
if(clubs.some(count => count > 3)) {
throw new HttpError("Too much player of same club", 403);
if(clubs.some(count => count > maxSameClub)) {
throw new HttpError("Too much players of the same club", 403);
}
// 3. Within budget
const totalValue = allPlayers.reduce((prev, curr) => ({ id: 0, value: (prev.value || 0) + (curr.value || 0) }), { id: 0, value: 0 }).value || 0;
Expand All @@ -42,7 +56,7 @@ const GetPlayerByIds = async (allPlayerIds: number[], reqBody: any, weekId: numb
throw new HttpError(`Invalid budget (${budget})`, 403);
}
// 4. Valid position
if(!isValidLineup(allPlayers.filter(p => allPlayerIds.slice(0,11).indexOf(p.id) > -1 ))) {
if(validateStartingLineup(allPlayerIds.slice(0,11))) {
throw new HttpError('Invalid lineup', 403);
}
if(skipReturn) {
Expand Down Expand Up @@ -70,7 +84,7 @@ export const PostAddTeamHandler = async (req: any, rep: any) => {

const [weekId, lastWeekId] = await Promise.all([upcomingWeekId(), finalWeekId()]);

const allWithValues = await GetPlayerByIds(allIds, req.body, weekId);
const allWithValues = await CheckValidTeam(allIds, req.body, weekId);

const totalValue = allWithValues!.reduce((prev, curr) => ({ id: 0, value: (prev.value || 0) + (curr.value || 0) }), { id: 0, value: 0 }).value || 0;
const budget = 100 - totalValue;
Expand Down Expand Up @@ -426,7 +440,7 @@ export const PostEditTeamHandler = async (req: any, rep: any) => {

const allIds = req.body.starting.concat(req.body.bench);

let allWithValues = await GetPlayerByIds(allIds, req.body, weekId);
let allWithValues = await CheckValidTeam(allIds, req.body, weekId);
let weekIds = [weekId];

const totalValue = allWithValues!.reduce((prev, curr) => ({ id: 0, value: (prev.value || 0) + (curr.value || 0) }), { id: 0, value: 0 }).value || 0;
Expand Down Expand Up @@ -500,7 +514,7 @@ export const PostSelectionsTeamHandler = async (req: any, rep: any) => {
throw new HttpError("Invalid team: invalid number of players", 400);
}
const allIds = req.body.starting.concat(req.body.bench);
const allWithValues = await GetPlayerByIds(allIds, req.body, weekId);
const allWithValues = await CheckValidTeam(allIds, req.body, weekId);

try {
await prisma.$transaction( async (prisma) => {
Expand Down Expand Up @@ -559,7 +573,10 @@ export const PostSelectionsTeamHandler = async (req: any, rep: any) => {

export const PostTransfersTeamHandler = async (req: any, rep: any) => {
const transfers = req.body.transfers;
const [weekId, lastWeekId] = await Promise.all([upcomingWeekId(), finalWeekId()]);
const [weekId, lastWeekId] = await Promise.all([
upcomingWeekId(),
finalWeekId()
]);
const remainingWeekIds = Array.from(Array(lastWeekId - weekId + 1).keys()).map(x => x + weekId);

if (transfers) {
Expand All @@ -569,24 +586,22 @@ export const PostTransfersTeamHandler = async (req: any, rep: any) => {
weekId,
}
});

if(process.env.MAX_TRANSFERS && (transfers.length + alreadyPerformedTransfers.length) > +process.env.MAX_TRANSFERS) {
rep.status(403).send({ msg: "Whoaaa, too much transfers!" });
return;
}
const allTfIds = (await prisma.selection.findMany({
where: {
teamId: +req.params.id,
weekId: weekId,
},
select: {
playerId: true
},
orderBy: {
order: 'asc'
}
})).map((n: { playerId: number; }) => {
const tf = transfers.find((t: any) => t.outId === n.playerId);
return tf ? tf.inId : n.playerId;
});
await GetPlayerByIds(allTfIds, req.body, weekId, true);
await CheckValidTeam(allTfIds, req.body, weekId, true);

const transferCreateInput = transfers.map((transfer: any) => {
return {
Expand Down
Loading

0 comments on commit 3552dc8

Please sign in to comment.