traintrape-moi/server/src/challenge-actions/challenge-actions.service.ts

87 lines
2.7 KiB
TypeScript
Raw Normal View History

import { Injectable, NotAcceptableException } from '@nestjs/common'
2024-12-07 19:29:38 +01:00
import { CreateChallengeActionDto } from './dto/create-challenge-action.dto'
import { UpdateChallengeActionDto } from './dto/update-challenge-action.dto'
import { ChallengeAction, User } from '@prisma/client'
import { PrismaService } from 'src/prisma/prisma.service'
import { QueryPaginationDto } from 'src/common/dto/pagination-query.dto'
import { paginate } from 'src/common/utils/pagination.utils'
2024-12-07 20:17:45 +01:00
import { FilterChallengeActionsDto } from './dto/filter-challenge-action.dto'
2024-12-07 19:29:38 +01:00
@Injectable()
export class ChallengeActionsService {
constructor(private prisma: PrismaService) { }
async create(authenticatedUser: User, createChallengeActionDto: CreateChallengeActionDto): Promise<ChallengeAction> {
const data = { ...createChallengeActionDto, userId: authenticatedUser.id }
return await this.prisma.challengeAction.create({
data: data,
})
2024-12-07 19:29:38 +01:00
}
2024-12-07 20:17:45 +01:00
async findAll(queryPagination: QueryPaginationDto, filterChallengeActions: FilterChallengeActionsDto): Promise<[ChallengeAction[], number]> {
console.log(filterChallengeActions)
2024-12-07 19:29:38 +01:00
return [
await this.prisma.challengeAction.findMany({
...paginate(queryPagination),
2024-12-07 20:17:45 +01:00
where: filterChallengeActions,
2024-12-07 19:29:38 +01:00
}),
2024-12-07 21:00:55 +01:00
await this.prisma.challengeAction.count(),
2024-12-07 19:29:38 +01:00
]
}
async findOne(id: number): Promise<ChallengeAction> {
return await this.prisma.challengeAction.findUnique({
where: { id },
})
2024-12-07 19:29:38 +01:00
}
async update(id: number, updateChallengeActionDto: UpdateChallengeActionDto): Promise<ChallengeAction> {
2024-12-07 21:00:55 +01:00
console.log(updateChallengeActionDto)
2024-12-07 19:29:38 +01:00
return await this.prisma.challengeAction.update({
where: { id },
data: updateChallengeActionDto,
})
}
async remove(id: number): Promise<ChallengeAction> {
return await this.prisma.challengeAction.delete({
where: { id },
})
2024-12-07 19:29:38 +01:00
}
async endCurrentChallenge(user: User, success: boolean): Promise<ChallengeAction> {
const challengeAction = await this.prisma.challengeAction.findFirst({
where: {
userId: user.id,
active: true,
}
})
if (!challengeAction)
throw new NotAcceptableException("Aucun défi n'est en cours")
let data
const now = new Date()
if (success) {
data = {
success: success,
active: false,
end: now,
}
}
else {
data = {
success: success,
active: false,
end: now,
penaltyStart: now,
penaltyEnd: new Date(now.getTime() + 45 * 60 * 1000),
}
}
return await this.prisma.challengeAction.update({
where: {
id: challengeAction.id,
},
data: data,
})
}
2024-12-07 19:29:38 +01:00
}