Skip to content

Commit f4d0fa6

Browse files
authored
Merge pull request #99 from ungdev/refactor/challenges
Refactor/challenges
2 parents 5038f83 + f0b0363 commit f4d0fa6

9 files changed

Lines changed: 384 additions & 156 deletions

File tree

‎backend/src/controllers/tent.controller.ts‎

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -89,16 +89,20 @@ export const toggleTentConfirmation: AppRequestHandler<ToggleTentBody> = async (
8989
const emailOptions = {
9090
from: email_from,
9191
to: [user1.email, user2.email],
92-
subject: confirmed ? '🎉 Votre tente a été validée !' : '⛺ Votre tente a été dévalidée',
93-
text: '', // optionnel
92+
subject: confirmed
93+
? "🎉 Votre tente a été validée !"
94+
: "⛺ Votre tente a été invalidée",
95+
text: "", // optionnel
9496
html: htmlEmail,
9597
};
9698

9799
// Envoi
98100
await sendEmail(emailOptions);
99101

100102
Ok(res, {
101-
msg: confirmed ? 'Tente validée et email envoyé.' : 'Tente dévalidée et email envoyé.',
103+
msg: confirmed
104+
? "Tente validée et email envoyé."
105+
: "Tente invalidée et email envoyé.",
102106
});
103107
} catch (err: any) {
104108
console.error(err);

‎backend/src/services/challenge.service.ts‎

Lines changed: 24 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -82,7 +82,29 @@ export const validateChallenge = async ({
8282
throw new Error("Type de challenge non valide");
8383
}
8484

85-
// 3. Créer l'objet de validation du challenge
85+
// 3. Vérifier si ce challenge a déjà été validé pour cette cible
86+
const targetColumn =
87+
type === "user"
88+
? challengeValidationSchema.target_user_id
89+
: type === "team"
90+
? challengeValidationSchema.target_team_id
91+
: challengeValidationSchema.target_faction_id;
92+
93+
const existingValidation = await db
94+
.select()
95+
.from(challengeValidationSchema)
96+
.where(
97+
and(
98+
eq(challengeValidationSchema.challenge_id, challengeId),
99+
eq(targetColumn, targetId)
100+
)
101+
);
102+
103+
if (existingValidation.length > 0) {
104+
throw new Error("Ce challenge a déjà été validé pour cette cible");
105+
}
106+
107+
// 4. Créer l'objet de validation du challenge
86108
const newChallengeValidationPoints = {
87109
challenge_id: challengeId,
88110
validated_by_admin_id: validatedBy,
@@ -94,7 +116,7 @@ export const validateChallenge = async ({
94116
target_faction_id: target_faction_id,
95117
};
96118

97-
// 4. Insérer la validation du challenge dans la base de données
119+
// 5. Insérer la validation du challenge dans la base de données
98120
const inserted = await db.insert(challengeValidationSchema).values(newChallengeValidationPoints).returning();
99121

100122
return inserted[0];

‎backend/src/services/tent.service.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -131,5 +131,5 @@ export const toggleTentConfirmation = async (
131131
)
132132
);
133133

134-
return { success: true, message: confirmed ? "Tente validée." : "Tente dévalidée." };
134+
return { success: true, message: confirmed ? "Tente validée." : "Tente invalidée." };
135135
};

‎frontend/src/components/Admin/AdminChallenge/adminChalengeList.tsx‎

Lines changed: 40 additions & 51 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,16 @@
1-
import { CheckCircle2, Edit, Search, Trash2 } from 'lucide-react';
2-
import { useMemo, useState } from 'react';
3-
import Select, { type SingleValue } from 'react-select';
4-
import Swal from 'sweetalert2';
5-
6-
import { type Challenge } from '../../../interfaces/challenge.interface';
7-
import { type Faction } from '../../../interfaces/faction.interface';
8-
import { type Team } from '../../../interfaces/team.interface';
9-
import { type User } from '../../../interfaces/user.interface';
10-
import { deleteChallenge, validateChallenge } from '../../../services/requests/challenge.service';
11-
import { Button } from '../../ui/button';
12-
import { Card, CardContent, CardHeader, CardTitle } from '../../ui/card';
13-
import { Input } from '../../ui/input';
1+
import { CheckCircle2, Edit, Search, Trash2 } from "lucide-react";
2+
import { useMemo, useState } from "react";
3+
import Select from "react-select";
4+
import Swal from "sweetalert2";
5+
6+
import { type Challenge } from "../../../interfaces/challenge.interface";
7+
import { type Faction } from "../../../interfaces/faction.interface";
8+
import { type Team } from "../../../interfaces/team.interface";
9+
import { type User } from "../../../interfaces/user.interface";
10+
import { deleteChallenge, validateChallenge } from "../../../services/requests/challenge.service";
11+
import { Button } from "../../ui/button";
12+
import { Card, CardContent, CardHeader, CardTitle } from "../../ui/card";
13+
import { Input } from "../../ui/input";
1414

1515
interface Props {
1616
challenges: Challenge[];
@@ -26,8 +26,9 @@ type ValidationTarget = 'user' | 'team' | 'faction';
2626
const AdminChallengeList = ({ challenges, refreshChallenges, onEdit, teams, factions, users }: Props) => {
2727
const [showValidationFormForId, setShowValidationFormForId] = useState<number | null>(null);
2828
const [validationType, setValidationType] = useState<ValidationTarget | null>(null);
29-
const [selectedTargetId, setSelectedTargetId] = useState<number | null>(null);
30-
const [searchTerm, setSearchTerm] = useState('');
29+
const [selectedTargetIds, setSelectedTargetIds] = useState<number[]>([]);
30+
const [searchTerm, setSearchTerm] = useState("");
31+
3132

3233
const filteredChallenges = useMemo(() => {
3334
return challenges.filter(
@@ -61,14 +62,20 @@ const AdminChallengeList = ({ challenges, refreshChallenges, onEdit, teams, fact
6162
}
6263
};
6364

64-
const handleValidate = async () => {
65-
if (!showValidationFormForId || !validationType || !selectedTargetId) return;
65+
const handleValidationCLick = async (c: Challenge) => {
66+
setShowValidationFormForId(c.id);
67+
setValidationType(c.category.toLowerCase() as ValidationTarget);
68+
}
6669

70+
const handleValidate = async () => {
71+
if (!showValidationFormForId || !validationType || selectedTargetIds.length === 0) return;
72+
73+
for (const targetId of selectedTargetIds) {
6774
try {
6875
const res = await validateChallenge({
6976
challengeId: showValidationFormForId,
7077
type: validationType,
71-
targetId: selectedTargetId,
78+
targetId: targetId,
7279
});
7380

7481
Swal.fire({
@@ -81,16 +88,17 @@ const AdminChallengeList = ({ challenges, refreshChallenges, onEdit, teams, fact
8188

8289
setShowValidationFormForId(null);
8390
setValidationType(null);
84-
setSelectedTargetId(null);
91+
setSelectedTargetIds([]);
8592
refreshChallenges();
8693
} catch (err) {
8794
console.error('Erreur lors de la validation du challenge', err);
8895
Swal.fire({
89-
icon: 'error',
90-
title: 'Erreur ❌',
91-
text: 'Impossible de valider ce challenge. Réessaie plus tard.',
96+
icon: "error",
97+
title: "Erreur ❌",
98+
text: err as string,
9299
});
93100
}
101+
}
94102
};
95103

96104
return (
@@ -136,8 +144,9 @@ const AdminChallengeList = ({ challenges, refreshChallenges, onEdit, teams, fact
136144
<Trash2 className="w-4 h-4" /> Supprimer
137145
</Button>
138146
<Button
139-
onClick={() => setShowValidationFormForId(c.id)}
140-
className="bg-blue-600 hover:bg-blue-700 text-white flex items-center gap-2">
147+
onClick={() => {handleValidationCLick(c)}}
148+
className="bg-blue-600 hover:bg-blue-700 text-white flex items-center gap-2"
149+
>
141150
<CheckCircle2 className="w-4 h-4" /> Valider
142151
</Button>
143152
</div>
@@ -147,30 +156,12 @@ const AdminChallengeList = ({ challenges, refreshChallenges, onEdit, teams, fact
147156
<CardContent className="p-4 space-y-4">
148157
<h4 className="font-bold text-lg">✅ Valider le challenge</h4>
149158

150-
<Select
151-
placeholder="Choisir le type de cible"
152-
onChange={(
153-
option: SingleValue<{
154-
value: ValidationTarget;
155-
label: string;
156-
}>,
157-
) => {
158-
setValidationType(option?.value ?? null);
159-
setSelectedTargetId(null);
160-
}}
161-
options={[
162-
{ value: 'user', label: 'Utilisateur' },
163-
{ value: 'team', label: 'Équipe' },
164-
{ value: 'faction', label: 'Faction' },
165-
]}
166-
/>
167159

168160
{validationType === 'user' && (
169161
<Select
162+
isMulti
170163
placeholder="Sélectionner un utilisateur"
171-
onChange={(option) =>
172-
setSelectedTargetId(Number(option?.value))
173-
}
164+
onChange={(options) => setSelectedTargetIds(options.map((o) => Number(o.value)))}
174165
options={users.map((u: User) => ({
175166
value: u.userId,
176167
label: `${u.firstName} ${u.lastName}`,
@@ -180,10 +171,9 @@ const AdminChallengeList = ({ challenges, refreshChallenges, onEdit, teams, fact
180171

181172
{validationType === 'team' && (
182173
<Select
174+
isMulti
183175
placeholder="Sélectionner une équipe"
184-
onChange={(option) =>
185-
setSelectedTargetId(Number(option?.value))
186-
}
176+
onChange={(options) => setSelectedTargetIds(options.map((o) => Number(o.value)))}
187177
options={teams.map((t: Team) => ({
188178
value: t.teamId,
189179
label: t.name,
@@ -193,10 +183,9 @@ const AdminChallengeList = ({ challenges, refreshChallenges, onEdit, teams, fact
193183

194184
{validationType === 'faction' && (
195185
<Select
186+
isMulti
196187
placeholder="Sélectionner une faction"
197-
onChange={(option) =>
198-
setSelectedTargetId(Number(option?.value))
199-
}
188+
onChange={(options) => setSelectedTargetIds(options.map((o) => Number(o.value)))}
200189
options={factions.map((f: Faction) => ({
201190
value: f.factionId,
202191
label: f.name,
@@ -214,7 +203,7 @@ const AdminChallengeList = ({ challenges, refreshChallenges, onEdit, teams, fact
214203
onClick={() => {
215204
setShowValidationFormForId(null);
216205
setValidationType(null);
217-
setSelectedTargetId(null);
206+
setSelectedTargetIds([]);
218207
}}
219208
className="bg-gray-400 hover:bg-gray-500 text-white">
220209
❌ Annuler

‎frontend/src/components/Admin/AdminChallenge/adminChallengeEditor.tsx‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,9 +42,19 @@ const ChallengeEditor = ({ editingChallenge, setEditingChallenge, refreshChallen
4242
setEditingChallenge(null);
4343
};
4444

45+
const resetFormPostCreation = () => {
46+
setForm({ title: "", description: "", category: form.category, points: 0 });
47+
setEditingChallenge(null);
48+
};
49+
50+
4551
const handleSubmit = async () => {
4652
setLoading(true);
4753
try {
54+
if (!form.title || !form.description || !form.category) {
55+
Swal.fire({ icon: "error", title: "Tous les champs doivent être remplis" });
56+
return;
57+
}
4858
if (editingChallenge) {
4959
await updateChallenge({ id: editingChallenge.id, ...form });
5060
Swal.fire({ icon: 'success', title: 'Challenge mis à jour !' });
@@ -53,7 +63,7 @@ const ChallengeEditor = ({ editingChallenge, setEditingChallenge, refreshChallen
5363
Swal.fire({ icon: 'success', title: 'Challenge créé !' });
5464
}
5565
refreshChallenges();
56-
resetForm();
66+
resetFormPostCreation();
5767
} catch {
5868
Swal.fire({ icon: 'error', title: "Erreur lors de l'enregistrement" });
5969
} finally {

0 commit comments

Comments
 (0)