Modification BDD stockage défi actif

This commit is contained in:
Emmy D'Anello 2024-12-12 21:03:42 +01:00
parent db8a8b4b7b
commit 9d0b5cb254
Signed by: ynerant
GPG Key ID: 3A75C55819C8CF85
9 changed files with 78 additions and 61 deletions

View File

@ -0,0 +1,18 @@
/*
Warnings:
- You are about to drop the column `active` on the `ChallengeAction` table. All the data in the column will be lost.
- A unique constraint covering the columns `[activeChallengeId]` on the table `Player` will be added. If there are existing duplicate values, this will fail.
*/
-- AlterTable
ALTER TABLE "ChallengeAction" DROP COLUMN "active";
-- AlterTable
ALTER TABLE "Player" ADD COLUMN "activeChallengeId" INTEGER;
-- CreateIndex
CREATE UNIQUE INDEX "Player_activeChallengeId_key" ON "Player"("activeChallengeId");
-- AddForeignKey
ALTER TABLE "Player" ADD CONSTRAINT "Player_activeChallengeId_fkey" FOREIGN KEY ("activeChallengeId") REFERENCES "ChallengeAction"("id") ON DELETE SET NULL ON UPDATE CASCADE;

View File

@ -8,15 +8,17 @@ datasource db {
} }
model Player { model Player {
id Int @id @default(autoincrement()) id Int @id @default(autoincrement())
name String @unique name String @unique
password String password String
money Int @default(0) money Int @default(0)
actions ChallengeAction[] activeChallenge ChallengeAction? @relation("ActiveChallenge", fields: [activeChallengeId], references: [id])
geolocations Geolocation[] activeChallengeId Int? @unique
moneyUpdates MoneyUpdate[] actions ChallengeAction[]
trips TrainTrip[] geolocations Geolocation[]
runs PlayerRun[] moneyUpdates MoneyUpdate[]
trips TrainTrip[]
runs PlayerRun[]
} }
model Game { model Game {
@ -68,7 +70,6 @@ model ChallengeAction {
playerId Int playerId Int
challenge Challenge @relation(fields: [challengeId], references: [id]) challenge Challenge @relation(fields: [challengeId], references: [id])
challengeId Int @unique challengeId Int @unique
active Boolean @default(false)
success Boolean @default(false) success Boolean @default(false)
start DateTime @default(now()) @db.Timestamptz(3) start DateTime @default(now()) @db.Timestamptz(3)
end DateTime? @db.Timestamptz(3) end DateTime? @db.Timestamptz(3)
@ -76,6 +77,7 @@ model ChallengeAction {
penaltyEnd DateTime? @db.Timestamptz(3) penaltyEnd DateTime? @db.Timestamptz(3)
run PlayerRun @relation(fields: [runId], references: [id]) run PlayerRun @relation(fields: [runId], references: [id])
runId Int runId Int
activePlayer Player? @relation("ActiveChallenge")
moneyUpdate MoneyUpdate? moneyUpdate MoneyUpdate?
} }

View File

@ -20,11 +20,15 @@ export class ChallengeActionsService {
}) })
} }
async findAll(queryPagination: QueryPaginationDto, filterChallengeActions: FilterChallengeActionsDto): Promise<[ChallengeAction[], number]> { async findAll(queryPagination: QueryPaginationDto, { playerId, challengeId, success }: FilterChallengeActionsDto): Promise<[ChallengeAction[], number]> {
return [ return [
await this.prisma.challengeAction.findMany({ await this.prisma.challengeAction.findMany({
...paginate(queryPagination), ...paginate(queryPagination),
where: filterChallengeActions, where: {
playerId: playerId,
challengeId: challengeId,
success: success,
}
}), }),
await this.prisma.challengeAction.count(), await this.prisma.challengeAction.count(),
] ]
@ -54,20 +58,14 @@ export class ChallengeActionsService {
} }
async endCurrentChallenge(player: Player, success: boolean): Promise<ChallengeAction> { async endCurrentChallenge(player: Player, success: boolean): Promise<ChallengeAction> {
const challengeAction = await this.prisma.challengeAction.findFirst({ if (!player.activeChallengeId)
where: {
playerId: player.id,
active: true,
}
})
if (!challengeAction)
throw new BadRequestException("Aucun défi n'est en cours") throw new BadRequestException("Aucun défi n'est en cours")
const challengeAction = await this.prisma.challengeAction.findUnique({ where: { id: player.activeChallengeId } })
let data let data
const now = new Date() const now = new Date()
if (success) { if (success) {
data = { data = {
success: success, success: success,
active: false,
end: now, end: now,
} }
@ -85,12 +83,15 @@ export class ChallengeActionsService {
else { else {
data = { data = {
success: success, success: success,
active: false,
end: now, end: now,
penaltyStart: now, penaltyStart: now,
penaltyEnd: new Date(now.getTime() + Constants.PENALTY_TIME * 60 * 1000), penaltyEnd: new Date(now.getTime() + Constants.PENALTY_TIME * 60 * 1000),
} }
} }
await this.prisma.player.update({
where: { id: player.id },
data: { activeChallengeId: null },
})
return await this.prisma.challengeAction.update({ return await this.prisma.challengeAction.update({
where: { where: {
id: challengeAction.id, id: challengeAction.id,

View File

@ -9,12 +9,6 @@ export class CreateChallengeActionDto {
@ApiProperty({ description: "Identifiant du défi rattaché à l'action" }) @ApiProperty({ description: "Identifiant du défi rattaché à l'action" })
challengeId: number challengeId: number
@IsOptional()
@IsBoolean()
@BooleanTransform()
@ApiProperty({ description: "Est-ce que le défi est actuellement en train d'être réalisé", default: true })
active: boolean = true
@IsOptional() @IsOptional()
@IsBoolean() @IsBoolean()
@BooleanTransform() @BooleanTransform()

View File

@ -16,12 +16,6 @@ export class FilterChallengeActionsDto {
@ApiProperty({ description: "Identifiant du défi attaché à cette action", required: false }) @ApiProperty({ description: "Identifiant du défi attaché à cette action", required: false })
challengeId?: number challengeId?: number
@IsOptional()
@IsBoolean()
@BooleanTransform()
@ApiProperty({ description: "Défi en train d'être accompli", required: false })
active?: boolean
@IsOptional() @IsOptional()
@IsBoolean() @IsBoolean()
@BooleanTransform() @BooleanTransform()

View File

@ -22,11 +22,6 @@ export class ChallengeActionEntity implements ChallengeAction {
*/ */
challengeId: number challengeId: number
/**
* Est-ce que le défi est actuellement en train d'être réalisé
*/
active: boolean
/** /**
* Est-ce que le défi a é réussi * Est-ce que le défi a é réussi
*/ */

View File

@ -64,13 +64,7 @@ export class ChallengesService {
const game = await this.prisma.game.findUnique({ where: { id: 1 }, include: { currentRun: true } }) const game = await this.prisma.game.findUnique({ where: { id: 1 }, include: { currentRun: true } })
if (game.currentRun?.runnerId !== player.id) if (game.currentRun?.runnerId !== player.id)
throw new ConflictException("Vous n'êtes pas en course, ce n'est pas à vous de tirer un défi.") throw new ConflictException("Vous n'êtes pas en course, ce n'est pas à vous de tirer un défi.")
const currentChallengeAction = await this.prisma.challengeAction.findFirst({ if (player.activeChallengeId)
where: {
playerId: player.id,
active: true,
}
})
if (currentChallengeAction)
throw new ConflictException("Un défi est déjà en cours d'accomplissement") throw new ConflictException("Un défi est déjà en cours d'accomplissement")
const remaningChallenges = await this.prisma.challenge.count({ const remaningChallenges = await this.prisma.challenge.count({
where: { where: {
@ -92,10 +86,13 @@ export class ChallengesService {
playerId: player.id, playerId: player.id,
challengeId: challenge.id, challengeId: challenge.id,
runId: game.currentRunId, runId: game.currentRunId,
active: true,
success: false, success: false,
} }
}) })
await this.prisma.player.update({
where: { id: player.id },
data: { activeChallengeId: action.id },
})
challengeEntity.action = action challengeEntity.action = action
return challengeEntity return challengeEntity
} }

View File

@ -58,17 +58,17 @@ export class GameService {
throw new ConflictException("La partie n'a pas encore démarré.") throw new ConflictException("La partie n'a pas encore démarré.")
// Clôture de l'éventuel défi en cours, qui n'a alors pas été réussi // Clôture de l'éventuel défi en cours, qui n'a alors pas été réussi
await this.prisma.challengeAction.updateMany({ const currentRunner = await this.prisma.player.findUnique({ where: { id: game.currentRun.runnerId } })
where: { if (currentRunner.activeChallengeId) {
playerId: game.currentRun.runnerId, await this.prisma.challengeAction.update({
runId: game.currentRunId, where: { id: currentRunner.activeChallengeId },
active: true, data: { success: false },
}, })
data: { await this.prisma.player.update({
active: false, where: { id: currentRunner.id },
success: false, data: { activeChallengeId: null },
}, })
}) }
await this.prisma.playerRun.update({ await this.prisma.playerRun.update({
where: { id: game.currentRunId }, where: { id: game.currentRunId },
@ -173,7 +173,7 @@ export class GameService {
const orpanChallengeMoneyUpdates = await this.prisma.moneyUpdate.findMany({ where: { reason: MoneyUpdateType.WIN_CHALLENGE, actionId: null } }) const orpanChallengeMoneyUpdates = await this.prisma.moneyUpdate.findMany({ where: { reason: MoneyUpdateType.WIN_CHALLENGE, actionId: null } })
await this.prisma.moneyUpdate.deleteMany({ where: { reason: MoneyUpdateType.WIN_CHALLENGE, actionId: null } }) await this.prisma.moneyUpdate.deleteMany({ where: { reason: MoneyUpdateType.WIN_CHALLENGE, actionId: null } })
deleted.push(...orpanTrainMoneyUpdates) deleted.push(...orpanChallengeMoneyUpdates)
return { added: added, deleted: deleted } return { added: added, deleted: deleted }
} }

View File

@ -1,21 +1,37 @@
import { ApiProperty } from "@nestjs/swagger" import { ApiProperty } from "@nestjs/swagger"
import { Player } from "@prisma/client" import { Player } from "@prisma/client"
import { Exclude } from 'class-transformer' import { Exclude } from 'class-transformer'
import { IsOptional } from "class-validator"
export class PlayerEntity implements Player { export class PlayerEntity implements Player {
constructor(partial: Partial<PlayerEntity>) { constructor(partial: Partial<PlayerEntity>) {
Object.assign(this, partial) Object.assign(this, partial)
} }
@ApiProperty({description: "Identifiant unique"}) /**
* Identifiant unique
*/
id: number id: number
@ApiProperty({description: "Nom de læ joueur⋅se"}) /**
* Nom de joueurse
*/
name: string name: string
/**
* Mot de passe hashé
*/
@Exclude() @Exclude()
password: string password: string
@ApiProperty({description: "Nombre de jetons dont dispose actuellement læ joueur⋅se"}) /**
* Nombre de jetons dont dispose actuellement joueurse
*/
money: number money: number
/**
* Identifiant du défi en cours d'accomplissement
*/
@IsOptional()
activeChallengeId: number | null
} }