Compare commits
136 Commits
b1f36f6210
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0c47bf916c | ||
|
|
9bcafe54d3 | ||
|
|
14c767cfc0 | ||
|
|
82069c74bc | ||
|
|
a062f5573b | ||
|
|
6e7c5d3eaf | ||
|
|
5dc178543e | ||
|
|
881b8149e5 | ||
|
|
d6a1e21e9f | ||
|
|
0b56d625ec | ||
|
|
f5dab3cb95 | ||
|
|
1b82bd9ee6 | ||
|
|
12bc44e3ac | ||
|
|
4a415f79e0 | ||
|
|
a62e61a314 | ||
|
|
91460930a4 | ||
|
|
fdedc1cf65 | ||
|
|
4fcf34c9aa | ||
|
|
85ee812ab1 | ||
|
|
cb02b494f4 | ||
|
|
2c7a346cde | ||
|
|
5875813f2f | ||
|
|
20c3043572 | ||
|
|
8ad09ab9c8 | ||
|
|
1f59cc7f9d | ||
|
|
67b3d9e2a9 | ||
|
|
ba3b2c17b9 | ||
|
|
7c0b3bc848 | ||
|
|
5eddf36121 | ||
|
|
ec965cd59d | ||
|
|
79c21955e0 | ||
|
|
16e4b63ffd | ||
|
|
3dd82c2bd4 | ||
|
|
f45cc1839e | ||
|
|
ffbf3cd42f | ||
|
|
a9a4120874 | ||
|
|
c7595c4173 | ||
|
|
bfaf30ee26 | ||
|
|
633245c1f1 | ||
|
|
bee8999362 | ||
|
|
d3a4fa7cf5 | ||
|
|
83446759fe | ||
|
|
b790ee21f2 | ||
|
|
321da3176e | ||
|
|
e4b0907801 | ||
|
|
9b9cc3885a | ||
|
|
d45475fb5a | ||
|
|
042b3128d4 | ||
|
|
5e179fb97a | ||
|
|
d9555a5d49 | ||
|
|
83aa54ff44 | ||
|
|
d08f6f6a9c | ||
|
|
699de28868 | ||
|
|
bbb0fbb9a1 | ||
|
|
f2bb02406e | ||
|
|
177b34d70f | ||
|
|
5e810202bb | ||
|
|
f093977b34 | ||
|
|
9518eef3d4 | ||
|
|
dcba162663 | ||
|
|
1e865330a0 | ||
|
|
7dfd426d1f | ||
|
|
b1925cd904 | ||
|
|
bd8d698c4e | ||
|
|
268b99ebd6 | ||
|
|
6d1e3daebb | ||
|
|
5b96cf907e | ||
|
|
97db800c73 | ||
|
|
880e96d6e4 | ||
|
|
99a475736b | ||
|
|
db01c25de7 | ||
|
|
494ac3f503 | ||
|
|
fd095246a3 | ||
|
|
ce0697a908 | ||
|
|
f69fbbd0e1 | ||
|
|
702476c349 | ||
|
|
aada4ad08b | ||
|
|
dbe5e1e9cc | ||
|
|
5c06ec20a6 | ||
|
|
f2805505a1 | ||
|
|
ae08ed7793 | ||
|
|
3ad680f416 | ||
|
|
09a3f6a106 | ||
|
|
6f98013382 | ||
|
|
db2993c50b | ||
| 369c83d162 | |||
|
|
41234f0729 | ||
|
|
2cfb9ad041 | ||
|
|
bbdb7d6ad2 | ||
|
|
8c17ed44e3 | ||
|
|
216f438b0a | ||
|
|
9b40210b36 | ||
|
|
8b1ed1b8b9 | ||
|
|
155d026284 | ||
|
|
bd25738486 | ||
|
|
23ca6345de | ||
|
|
93c6624aec | ||
|
|
6c08789555 | ||
|
|
7dbd044859 | ||
|
|
f0c9a9e4cc | ||
|
|
53e5e7de3c | ||
|
|
1152389785 | ||
|
|
65c73688e7 | ||
|
|
ae91ae5894 | ||
|
|
18d11d623a | ||
|
|
30dc84ccc0 | ||
|
|
378cf3d66a | ||
|
|
3c318e1763 | ||
|
|
9fde18a35e | ||
|
|
80e9d953ae | ||
|
|
d11059dac2 | ||
|
|
66237458ec | ||
|
|
3bd43e777e | ||
|
|
44be5d2e98 | ||
|
|
13b8971cc7 | ||
|
|
88d377e7b2 | ||
|
|
125e9b345d | ||
|
|
95e580aff6 | ||
|
|
a6c329ff15 | ||
|
|
a69613a232 | ||
|
|
fb830c6fcc | ||
|
|
56de7d6b01 | ||
|
|
1b07fe8ae5 | ||
|
|
fdd860c456 | ||
|
|
fb5c8c1466 | ||
|
|
b643e283fa | ||
|
|
e6201120b9 | ||
|
|
0ac6dbd423 | ||
|
|
b245be3bf4 | ||
|
|
3a0dd57bb6 | ||
|
|
16b0437ecb | ||
|
|
50a2eaf109 | ||
|
|
5ae6cde14e | ||
|
|
6dc08dc818 | ||
|
|
b8f4672206 | ||
|
|
67131f6470 |
32
.cursor/rules/api-routes.mdc
Normal file
32
.cursor/rules/api-routes.mdc
Normal file
@@ -0,0 +1,32 @@
|
|||||||
|
---
|
||||||
|
globs: app/api/**/*.ts
|
||||||
|
---
|
||||||
|
|
||||||
|
# API Routes Rules
|
||||||
|
|
||||||
|
1. Routes MUST only use services for data access
|
||||||
|
2. Routes MUST handle input validation
|
||||||
|
3. Routes MUST return typed responses
|
||||||
|
4. Routes MUST use proper error handling
|
||||||
|
|
||||||
|
Example of correct API route:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import { MyService } from "@/services/my-service";
|
||||||
|
|
||||||
|
export async function GET(request: Request) {
|
||||||
|
try {
|
||||||
|
const service = new MyService(pool);
|
||||||
|
const data = await service.getData();
|
||||||
|
return Response.json(data);
|
||||||
|
} catch (error) {
|
||||||
|
return Response.error();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
❌ FORBIDDEN:
|
||||||
|
|
||||||
|
- Direct database queries
|
||||||
|
- Business logic implementation
|
||||||
|
- Untyped responses
|
||||||
167
.cursor/rules/business-logic-separation.mdc
Normal file
167
.cursor/rules/business-logic-separation.mdc
Normal file
@@ -0,0 +1,167 @@
|
|||||||
|
---
|
||||||
|
alwaysApply: true
|
||||||
|
description: Enforce business logic separation between frontend and backend
|
||||||
|
---
|
||||||
|
|
||||||
|
# Business Logic Separation Rules
|
||||||
|
|
||||||
|
## Core Principle: NO Business Logic in Frontend
|
||||||
|
|
||||||
|
All business logic, data processing, and domain rules MUST be implemented in the backend services layer. The frontend is purely for presentation and user interaction.
|
||||||
|
|
||||||
|
## ✅ ALLOWED in Frontend ([src/components/](mdc:src/components/), [src/hooks/](mdc:src/hooks/), [src/clients/](mdc:src/clients/))
|
||||||
|
|
||||||
|
### Components
|
||||||
|
- UI rendering and presentation logic
|
||||||
|
- Form validation (UI-level only, not business rules)
|
||||||
|
- User interaction handling (clicks, inputs, navigation)
|
||||||
|
- Visual state management (loading, errors, UI states)
|
||||||
|
- Data formatting for display purposes only
|
||||||
|
|
||||||
|
### Hooks
|
||||||
|
- React state management
|
||||||
|
- API call orchestration (using clients)
|
||||||
|
- UI-specific logic (modals, forms, animations)
|
||||||
|
- Data fetching and caching coordination
|
||||||
|
|
||||||
|
### Clients
|
||||||
|
- HTTP requests to API routes
|
||||||
|
- Request/response transformation (serialization only)
|
||||||
|
- Error handling and retry logic
|
||||||
|
- Authentication token management
|
||||||
|
|
||||||
|
## ❌ FORBIDDEN in Frontend
|
||||||
|
|
||||||
|
### Business Rules
|
||||||
|
```typescript
|
||||||
|
// ❌ BAD: Business logic in component
|
||||||
|
const TaskCard = ({ task }) => {
|
||||||
|
const canEdit = task.status === 'open' && task.assignee === currentUser.id;
|
||||||
|
const priority = task.dueDate < new Date() ? 'high' : 'normal';
|
||||||
|
// This is business logic!
|
||||||
|
}
|
||||||
|
|
||||||
|
// ✅ GOOD: Get computed values from backend
|
||||||
|
const TaskCard = ({ task }) => {
|
||||||
|
const { canEdit, priority } = task; // Computed by backend service
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Data Processing
|
||||||
|
```typescript
|
||||||
|
// ❌ BAD: Data transformation in frontend
|
||||||
|
const processJiraTasks = (tasks) => {
|
||||||
|
return tasks.map(task => ({
|
||||||
|
...task,
|
||||||
|
normalizedStatus: mapJiraStatus(task.status),
|
||||||
|
estimatedHours: calculateEstimate(task.storyPoints)
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ✅ GOOD: Data already processed by backend service
|
||||||
|
const { processedTasks } = await tasksClient.getTasks();
|
||||||
|
```
|
||||||
|
|
||||||
|
### Domain Logic
|
||||||
|
```typescript
|
||||||
|
// ❌ BAD: Domain calculations in frontend
|
||||||
|
const calculateTeamVelocity = (sprints) => {
|
||||||
|
// Complex business calculation
|
||||||
|
}
|
||||||
|
|
||||||
|
// ✅ GOOD: Domain logic in service
|
||||||
|
// This belongs in services/team-analytics.ts
|
||||||
|
```
|
||||||
|
|
||||||
|
## ✅ REQUIRED in Backend ([src/services/](mdc:src/services/), [src/app/api/](mdc:src/app/api/))
|
||||||
|
|
||||||
|
### Services Layer
|
||||||
|
- All business rules and domain logic
|
||||||
|
- Data validation and processing
|
||||||
|
- Integration with external APIs (Jira, macOS Reminders)
|
||||||
|
- Complex calculations and algorithms
|
||||||
|
- Data aggregation and analytics
|
||||||
|
- Permission and authorization logic
|
||||||
|
|
||||||
|
### API Routes
|
||||||
|
- Input validation and sanitization
|
||||||
|
- Service orchestration
|
||||||
|
- Response formatting
|
||||||
|
- Error handling and logging
|
||||||
|
- Authentication and authorization
|
||||||
|
|
||||||
|
## Implementation Pattern
|
||||||
|
|
||||||
|
### ✅ Correct Flow
|
||||||
|
```
|
||||||
|
User Action → Component → Client → API Route → Service → Database
|
||||||
|
↑ ↓
|
||||||
|
Pure UI Logic Business Logic
|
||||||
|
```
|
||||||
|
|
||||||
|
### ❌ Incorrect Flow
|
||||||
|
```
|
||||||
|
User Action → Component with Business Logic → Database
|
||||||
|
```
|
||||||
|
|
||||||
|
## Examples
|
||||||
|
|
||||||
|
### Task Status Management
|
||||||
|
```typescript
|
||||||
|
// ❌ BAD: In component
|
||||||
|
const updateTaskStatus = (taskId, newStatus) => {
|
||||||
|
if (newStatus === 'done' && !task.hasAllSubtasks) {
|
||||||
|
throw new Error('Cannot complete task with pending subtasks');
|
||||||
|
}
|
||||||
|
// Business rule in frontend!
|
||||||
|
}
|
||||||
|
|
||||||
|
// ✅ GOOD: In services/task-processor.ts
|
||||||
|
export const updateTaskStatus = async (taskId: string, newStatus: TaskStatus) => {
|
||||||
|
const task = await getTask(taskId);
|
||||||
|
|
||||||
|
// Business rules in service
|
||||||
|
if (newStatus === 'done' && !await hasAllSubtasksCompleted(taskId)) {
|
||||||
|
throw new BusinessError('Cannot complete task with pending subtasks');
|
||||||
|
}
|
||||||
|
|
||||||
|
return await updateTask(taskId, { status: newStatus });
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Team Analytics
|
||||||
|
```typescript
|
||||||
|
// ❌ BAD: In component
|
||||||
|
const TeamDashboard = () => {
|
||||||
|
const calculateBurndown = (tasks) => {
|
||||||
|
// Complex business calculation in component
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ✅ GOOD: In services/team-analytics.ts
|
||||||
|
export const getTeamBurndown = async (teamId: string, sprintId: string) => {
|
||||||
|
// All calculation logic in service
|
||||||
|
const tasks = await getSprintTasks(sprintId);
|
||||||
|
return calculateBurndownMetrics(tasks);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Enforcement
|
||||||
|
|
||||||
|
When reviewing code:
|
||||||
|
1. **Components**: Should only contain JSX, event handlers, and UI state
|
||||||
|
2. **Hooks**: Should only orchestrate API calls and manage React state
|
||||||
|
3. **Clients**: Should only make HTTP requests and handle responses
|
||||||
|
4. **Services**: Should contain ALL business logic and data processing
|
||||||
|
5. **API Routes**: Should validate input and call appropriate services
|
||||||
|
|
||||||
|
## Red Flags
|
||||||
|
|
||||||
|
Watch for these patterns that indicate business logic in frontend:
|
||||||
|
- Complex calculations in components/hooks
|
||||||
|
- Business rule validation in forms
|
||||||
|
- Data transformation beyond display formatting
|
||||||
|
- Domain-specific constants and rules
|
||||||
|
- Integration logic with external systems
|
||||||
|
|
||||||
|
Remember: **The frontend is a thin presentation layer. All intelligence lives in the backend.**
|
||||||
31
.cursor/rules/clients.mdc
Normal file
31
.cursor/rules/clients.mdc
Normal file
@@ -0,0 +1,31 @@
|
|||||||
|
---
|
||||||
|
globs: clients/**/*.ts
|
||||||
|
---
|
||||||
|
|
||||||
|
# HTTP Clients Rules
|
||||||
|
|
||||||
|
1. All HTTP calls MUST be in clients/domains/
|
||||||
|
2. Each domain MUST have its own client
|
||||||
|
3. Clients MUST use the base HTTP client
|
||||||
|
4. Clients MUST type their responses
|
||||||
|
|
||||||
|
Example of correct client:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import { HttpClient } from "@/clients/base/http-client";
|
||||||
|
import { MyData } from "@/lib/types";
|
||||||
|
|
||||||
|
export class MyClient {
|
||||||
|
constructor(private httpClient: HttpClient) {}
|
||||||
|
|
||||||
|
async getData(): Promise<MyData[]> {
|
||||||
|
return this.httpClient.get("/api/data");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
❌ FORBIDDEN:
|
||||||
|
|
||||||
|
- Direct fetch calls
|
||||||
|
- Business logic in clients
|
||||||
|
- Untyped responses
|
||||||
28
.cursor/rules/components.mdc
Normal file
28
.cursor/rules/components.mdc
Normal file
@@ -0,0 +1,28 @@
|
|||||||
|
---
|
||||||
|
globs: src/components/**/*.tsx
|
||||||
|
---
|
||||||
|
|
||||||
|
# Components Rules
|
||||||
|
|
||||||
|
1. UI components MUST be in src/components/ui/
|
||||||
|
2. Feature components MUST be in their feature folder
|
||||||
|
3. Components MUST use clients for data fetching
|
||||||
|
4. Components MUST be properly typed
|
||||||
|
|
||||||
|
Example of correct component:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import { useMyClient } from '@/hooks/use-my-client';
|
||||||
|
|
||||||
|
export const MyComponent = () => {
|
||||||
|
const { data } = useMyClient();
|
||||||
|
return <div>{data.map(item => <Item key={item.id} {...item} />)}</div>;
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
❌ FORBIDDEN:
|
||||||
|
|
||||||
|
- Direct service usage
|
||||||
|
- Direct database queries
|
||||||
|
- Direct fetch calls
|
||||||
|
- Untyped props
|
||||||
167
.cursor/rules/css-variables-theme.mdc
Normal file
167
.cursor/rules/css-variables-theme.mdc
Normal file
@@ -0,0 +1,167 @@
|
|||||||
|
---
|
||||||
|
alwaysApply: true
|
||||||
|
description: CSS Variables theme system best practices
|
||||||
|
---
|
||||||
|
|
||||||
|
# CSS Variables Theme System
|
||||||
|
|
||||||
|
## Core Principle: Pure CSS Variables for Theming
|
||||||
|
|
||||||
|
This project uses **CSS Variables exclusively** for theming. No Tailwind `dark:` classes or conditional CSS classes.
|
||||||
|
|
||||||
|
## ✅ Architecture Pattern
|
||||||
|
|
||||||
|
### CSS Structure
|
||||||
|
```css
|
||||||
|
:root {
|
||||||
|
/* Light theme (default values) */
|
||||||
|
--background: #f1f5f9;
|
||||||
|
--foreground: #0f172a;
|
||||||
|
--primary: #0891b2;
|
||||||
|
--success: #059669;
|
||||||
|
--destructive: #dc2626;
|
||||||
|
--accent: #d97706;
|
||||||
|
--purple: #8b5cf6;
|
||||||
|
--yellow: #eab308;
|
||||||
|
--green: #059669;
|
||||||
|
--blue: #2563eb;
|
||||||
|
--gray: #6b7280;
|
||||||
|
--gray-light: #e5e7eb;
|
||||||
|
}
|
||||||
|
|
||||||
|
.dark {
|
||||||
|
/* Dark theme (override values) */
|
||||||
|
--background: #1e293b;
|
||||||
|
--foreground: #f1f5f9;
|
||||||
|
--primary: #06b6d4;
|
||||||
|
--success: #10b981;
|
||||||
|
--destructive: #ef4444;
|
||||||
|
--accent: #f59e0b;
|
||||||
|
--purple: #8b5cf6;
|
||||||
|
--yellow: #eab308;
|
||||||
|
--green: #10b981;
|
||||||
|
--blue: #3b82f6;
|
||||||
|
--gray: #9ca3af;
|
||||||
|
--gray-light: #374151;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Theme Application
|
||||||
|
- **Single source of truth**: [ThemeContext.tsx](mdc:src/contexts/ThemeContext.tsx) applies theme class to `document.documentElement`
|
||||||
|
- **No duplication**: Theme is applied only once, not in multiple places
|
||||||
|
- **SSR safe**: Initial theme from server-side preferences
|
||||||
|
|
||||||
|
## ✅ Component Usage Patterns
|
||||||
|
|
||||||
|
### Correct: Using CSS Variables
|
||||||
|
```tsx
|
||||||
|
// ✅ GOOD: CSS Variables in className
|
||||||
|
<div className="bg-[var(--card)] text-[var(--foreground)] border-[var(--border)]">
|
||||||
|
|
||||||
|
// ✅ GOOD: CSS Variables in style prop
|
||||||
|
<div style={{ color: 'var(--primary)', backgroundColor: 'var(--card)' }}>
|
||||||
|
|
||||||
|
// ✅ GOOD: CSS Variables with color-mix for transparency
|
||||||
|
<div style={{
|
||||||
|
backgroundColor: 'color-mix(in srgb, var(--primary) 10%, transparent)',
|
||||||
|
borderColor: 'color-mix(in srgb, var(--primary) 20%, var(--border))'
|
||||||
|
}}>
|
||||||
|
```
|
||||||
|
|
||||||
|
### ❌ Forbidden: Tailwind Dark Mode Classes
|
||||||
|
```tsx
|
||||||
|
// ❌ BAD: Tailwind dark: classes
|
||||||
|
<div className="bg-white dark:bg-gray-800 text-black dark:text-white">
|
||||||
|
|
||||||
|
// ❌ BAD: Conditional classes
|
||||||
|
<div className={theme === 'dark' ? 'bg-gray-800' : 'bg-white'}>
|
||||||
|
|
||||||
|
// ❌ BAD: Hardcoded colors
|
||||||
|
<div className="bg-red-500 text-blue-600">
|
||||||
|
```
|
||||||
|
|
||||||
|
## ✅ Color System
|
||||||
|
|
||||||
|
### Semantic Color Tokens
|
||||||
|
- `--background`: Main background color
|
||||||
|
- `--foreground`: Main text color
|
||||||
|
- `--card`: Card/panel background
|
||||||
|
- `--card-hover`: Card hover state
|
||||||
|
- `--card-column`: Column background (darker than cards)
|
||||||
|
- `--border`: Border color
|
||||||
|
- `--input`: Input field background
|
||||||
|
- `--primary`: Primary brand color
|
||||||
|
- `--primary-foreground`: Text on primary background
|
||||||
|
- `--muted`: Muted text color
|
||||||
|
- `--muted-foreground`: Secondary text color
|
||||||
|
- `--accent`: Accent color (orange/amber)
|
||||||
|
- `--destructive`: Error/danger color (red)
|
||||||
|
- `--success`: Success color (green)
|
||||||
|
- `--purple`: Purple accent
|
||||||
|
- `--yellow`: Yellow accent
|
||||||
|
- `--green`: Green accent
|
||||||
|
- `--blue`: Blue accent
|
||||||
|
- `--gray`: Gray color
|
||||||
|
- `--gray-light`: Light gray background
|
||||||
|
|
||||||
|
### Color Mixing Patterns
|
||||||
|
```css
|
||||||
|
/* Background with transparency */
|
||||||
|
background-color: color-mix(in srgb, var(--primary) 10%, transparent);
|
||||||
|
|
||||||
|
/* Border with transparency */
|
||||||
|
border-color: color-mix(in srgb, var(--primary) 20%, var(--border));
|
||||||
|
|
||||||
|
/* Text with opacity */
|
||||||
|
color: color-mix(in srgb, var(--destructive) 80%, transparent);
|
||||||
|
```
|
||||||
|
|
||||||
|
## ✅ Theme Context Usage
|
||||||
|
|
||||||
|
### ThemeProvider Setup
|
||||||
|
```tsx
|
||||||
|
// In layout.tsx
|
||||||
|
<ThemeProvider initialTheme={initialPreferences.viewPreferences.theme}>
|
||||||
|
{children}
|
||||||
|
</ThemeProvider>
|
||||||
|
```
|
||||||
|
|
||||||
|
### Component Usage
|
||||||
|
```tsx
|
||||||
|
import { useTheme } from '@/contexts/ThemeContext';
|
||||||
|
|
||||||
|
function MyComponent() {
|
||||||
|
const { theme, toggleTheme, setTheme } = useTheme();
|
||||||
|
|
||||||
|
return (
|
||||||
|
<button onClick={toggleTheme}>
|
||||||
|
Switch to {theme === 'dark' ? 'light' : 'dark'} theme
|
||||||
|
</button>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## ✅ Future Extensibility
|
||||||
|
|
||||||
|
This system is designed to support:
|
||||||
|
- **Custom color themes**: Easy to add new color variables
|
||||||
|
- **User preferences**: Colors can be dynamically changed
|
||||||
|
- **Theme presets**: Multiple predefined themes
|
||||||
|
- **Accessibility**: High contrast modes
|
||||||
|
|
||||||
|
## 🚨 Anti-patterns to Avoid
|
||||||
|
|
||||||
|
1. **Don't mix approaches**: Never use both CSS variables and Tailwind dark: classes
|
||||||
|
2. **Don't duplicate theme application**: Theme should be applied only in ThemeContext
|
||||||
|
3. **Don't hardcode colors**: Always use semantic color tokens
|
||||||
|
4. **Don't use conditional classes**: Use CSS variables instead
|
||||||
|
5. **Don't forget transparency**: Use `color-mix()` for semi-transparent colors
|
||||||
|
|
||||||
|
## 📁 Key Files
|
||||||
|
|
||||||
|
- [globals.css](mdc:src/app/globals.css) - CSS Variables definitions
|
||||||
|
- [ThemeContext.tsx](mdc:src/contexts/ThemeContext.tsx) - Theme management
|
||||||
|
- [UserPreferencesContext.tsx](mdc:src/contexts/UserPreferencesContext.tsx) - Preferences sync
|
||||||
|
- [layout.tsx](mdc:src/app/layout.tsx) - Theme provider setup
|
||||||
|
|
||||||
|
Remember: **CSS Variables are the single source of truth for theming. Keep it pure and consistent.**
|
||||||
30
.cursor/rules/project-structure.mdc
Normal file
30
.cursor/rules/project-structure.mdc
Normal file
@@ -0,0 +1,30 @@
|
|||||||
|
---
|
||||||
|
alwaysApply: true
|
||||||
|
---
|
||||||
|
|
||||||
|
# Project Structure Rules
|
||||||
|
|
||||||
|
1. Backend:
|
||||||
|
- [src/services/](mdc:src/services/) - ALL database access
|
||||||
|
- [src/app/api/](mdc:src/app/api/) - API routes using services
|
||||||
|
|
||||||
|
2. Frontend:
|
||||||
|
- [src/clients/](mdc:src/clients/) - HTTP clients
|
||||||
|
- [src/components/](mdc:src/components/) - React components (organized by domain)
|
||||||
|
- [src/hooks/](mdc:src/hooks/) - React hooks
|
||||||
|
|
||||||
|
3. Shared:
|
||||||
|
- [src/lib/](mdc:src/lib/) - Types and utilities
|
||||||
|
- [scripts/](mdc:scripts/) - Utility scripts
|
||||||
|
|
||||||
|
Key Files:
|
||||||
|
|
||||||
|
- [src/services/database.ts](mdc:src/services/database.ts) - Database pool
|
||||||
|
- [src/clients/base/http-client.ts](mdc:src/clients/base/http-client.ts) - Base HTTP client
|
||||||
|
- [src/lib/types.ts](mdc:src/lib/types.ts) - Shared types
|
||||||
|
|
||||||
|
❌ FORBIDDEN:
|
||||||
|
|
||||||
|
- Database access outside src/services/
|
||||||
|
- HTTP calls outside src/clients/
|
||||||
|
- Business logic in src/components/
|
||||||
113
.cursor/rules/server-actions.mdc
Normal file
113
.cursor/rules/server-actions.mdc
Normal file
@@ -0,0 +1,113 @@
|
|||||||
|
---
|
||||||
|
alwaysApply: true
|
||||||
|
description: Guide for when to use Server Actions vs API Routes in Next.js App Router
|
||||||
|
---
|
||||||
|
|
||||||
|
# Server Actions vs API Routes - Decision Guide
|
||||||
|
|
||||||
|
## ✅ USE SERVER ACTIONS for:
|
||||||
|
|
||||||
|
### Quick Actions & Mutations
|
||||||
|
- **TaskCard actions**: `updateTaskStatus()`, `updateTaskTitle()`, `deleteTask()`
|
||||||
|
- **Daily checkboxes**: `toggleCheckbox()`, `addCheckbox()`, `updateCheckbox()`
|
||||||
|
- **User preferences**: `updateTheme()`, `updateViewPreferences()`, `updateFilters()`
|
||||||
|
- **Simple CRUD**: `createTag()`, `updateTag()`, `deleteTag()`
|
||||||
|
|
||||||
|
### Characteristics of Server Action candidates:
|
||||||
|
- Simple, frequent mutations
|
||||||
|
- No complex business logic
|
||||||
|
- Used in interactive components (forms, buttons, toggles)
|
||||||
|
- Need immediate UI feedback with `useTransition`
|
||||||
|
- Benefit from automatic cache revalidation
|
||||||
|
|
||||||
|
## ❌ KEEP API ROUTES for:
|
||||||
|
|
||||||
|
### Complex Endpoints
|
||||||
|
- **Initial data fetching**: `GET /api/tasks` with complex filters
|
||||||
|
- **External integrations**: `POST /api/jira/sync` with complex logic
|
||||||
|
- **Analytics & reports**: Complex data aggregation
|
||||||
|
- **Public API**: Endpoints that might be called from mobile/external
|
||||||
|
|
||||||
|
### Characteristics that require API Routes:
|
||||||
|
- Complex business logic or data processing
|
||||||
|
- Multiple service orchestration
|
||||||
|
- Need for HTTP monitoring/logging
|
||||||
|
- External consumption (mobile apps, webhooks)
|
||||||
|
- Real-time features (WebSockets, SSE)
|
||||||
|
- File uploads or special content types
|
||||||
|
|
||||||
|
## 🔄 Implementation Pattern
|
||||||
|
|
||||||
|
### Server Actions Structure
|
||||||
|
```typescript
|
||||||
|
// actions/tasks.ts
|
||||||
|
'use server'
|
||||||
|
|
||||||
|
import { tasksService } from '@/services/tasks';
|
||||||
|
import { revalidatePath } from 'next/cache';
|
||||||
|
|
||||||
|
export async function updateTaskStatus(taskId: string, status: TaskStatus) {
|
||||||
|
try {
|
||||||
|
const task = await tasksService.updateTask(taskId, { status });
|
||||||
|
revalidatePath('/'); // Auto cache invalidation
|
||||||
|
return { success: true, data: task };
|
||||||
|
} catch (error) {
|
||||||
|
return { success: false, error: error.message };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Component Usage with useTransition
|
||||||
|
```typescript
|
||||||
|
// components/TaskCard.tsx
|
||||||
|
'use client';
|
||||||
|
|
||||||
|
import { updateTaskStatus } from '@/actions/tasks';
|
||||||
|
import { useTransition } from 'react';
|
||||||
|
|
||||||
|
export function TaskCard({ task }) {
|
||||||
|
const [isPending, startTransition] = useTransition();
|
||||||
|
|
||||||
|
const handleStatusChange = (status) => {
|
||||||
|
startTransition(async () => {
|
||||||
|
const result = await updateTaskStatus(task.id, status);
|
||||||
|
if (!result.success) {
|
||||||
|
// Handle error
|
||||||
|
}
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className={isPending ? 'opacity-50' : ''}>
|
||||||
|
{/* UI with loading state */}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## 🏗️ Migration Strategy
|
||||||
|
|
||||||
|
When migrating from API Routes to Server Actions:
|
||||||
|
|
||||||
|
1. **Create server action** in `actions/` directory
|
||||||
|
2. **Update component** to use server action directly
|
||||||
|
3. **Remove API route** (PATCH, POST, DELETE for mutations)
|
||||||
|
4. **Simplify client** (remove mutation methods, keep GET only)
|
||||||
|
5. **Update hooks** to use server actions instead of HTTP calls
|
||||||
|
|
||||||
|
## 🎯 Benefits of Server Actions
|
||||||
|
|
||||||
|
- **🚀 Performance**: No HTTP serialization overhead
|
||||||
|
- **🔄 Cache intelligence**: Automatic revalidation with `revalidatePath()`
|
||||||
|
- **📦 Bundle reduction**: Less client-side HTTP code
|
||||||
|
- **⚡ UX**: Native loading states with `useTransition`
|
||||||
|
- **🎯 Simplicity**: Direct service calls, less boilerplate
|
||||||
|
|
||||||
|
## 🚨 Anti-patterns to Avoid
|
||||||
|
|
||||||
|
- Don't use server actions for complex data fetching
|
||||||
|
- Don't use server actions for endpoints that need HTTP monitoring
|
||||||
|
- Don't use server actions for public API endpoints
|
||||||
|
- Don't mix server actions with client-side state management for the same data
|
||||||
|
|
||||||
|
Remember: Server Actions are for **direct mutations**, API Routes are for **complex operations** and **public interfaces**.
|
||||||
42
.cursor/rules/services.mdc
Normal file
42
.cursor/rules/services.mdc
Normal file
@@ -0,0 +1,42 @@
|
|||||||
|
---
|
||||||
|
globs: src/services/*.ts
|
||||||
|
---
|
||||||
|
|
||||||
|
# Services Rules
|
||||||
|
|
||||||
|
1. Services MUST contain ALL PostgreSQL queries
|
||||||
|
2. Services are the ONLY layer allowed to communicate with the database
|
||||||
|
3. Each service MUST:
|
||||||
|
- Use the pool from [src/services/database.ts](mdc:src/services/database.ts)
|
||||||
|
- Implement proper transaction management
|
||||||
|
- Handle errors and logging
|
||||||
|
- Validate data before insertion
|
||||||
|
- Have a clear interface
|
||||||
|
|
||||||
|
Example of correct service implementation:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
export class MyService {
|
||||||
|
constructor(private pool: Pool) {}
|
||||||
|
|
||||||
|
async myMethod(): Promise<Result> {
|
||||||
|
const client = await this.pool.connect();
|
||||||
|
try {
|
||||||
|
await client.query("BEGIN");
|
||||||
|
// ... queries
|
||||||
|
await client.query("COMMIT");
|
||||||
|
} catch (error) {
|
||||||
|
await client.query("ROLLBACK");
|
||||||
|
throw error;
|
||||||
|
} finally {
|
||||||
|
client.release();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
❌ FORBIDDEN:
|
||||||
|
|
||||||
|
- Direct database queries outside src/services
|
||||||
|
- Raw SQL in API routes
|
||||||
|
- Database logic in components
|
||||||
54
.cursor/rules/todo-tracking.mdc
Normal file
54
.cursor/rules/todo-tracking.mdc
Normal file
@@ -0,0 +1,54 @@
|
|||||||
|
---
|
||||||
|
alwaysApply: true
|
||||||
|
description: Automatic TODO tracking and task completion management
|
||||||
|
---
|
||||||
|
|
||||||
|
# TODO Task Tracking Rules
|
||||||
|
|
||||||
|
## Automatic Task Completion
|
||||||
|
|
||||||
|
Whenever you complete a task or implement a feature mentioned in [TODO.md](mdc:TODO.md), you MUST:
|
||||||
|
|
||||||
|
1. **Immediately update the TODO.md** by changing `- [ ]` to `- [x]` for the completed task
|
||||||
|
2. **Use the exact task description** from the TODO - don't modify the text
|
||||||
|
3. **Update related sub-tasks** if completing a parent task affects them
|
||||||
|
4. **Add completion timestamp** in a comment if the task was significant
|
||||||
|
|
||||||
|
## Task Completion Examples
|
||||||
|
|
||||||
|
### ✅ Correct completion marking:
|
||||||
|
```markdown
|
||||||
|
- [x] Initialiser Next.js avec TypeScript
|
||||||
|
- [x] Configurer ESLint, Prettier
|
||||||
|
- [x] Setup structure de dossiers selon les règles du workspace
|
||||||
|
```
|
||||||
|
|
||||||
|
### ✅ With timestamp for major milestones:
|
||||||
|
```markdown
|
||||||
|
- [x] Créer `services/database.ts` - Pool de connexion DB <!-- Completed 2025-01-15 -->
|
||||||
|
```
|
||||||
|
|
||||||
|
## When to Update TODO.md
|
||||||
|
|
||||||
|
Update the TODO immediately after:
|
||||||
|
- Creating/modifying files mentioned in tasks
|
||||||
|
- Implementing features described in tasks
|
||||||
|
- Completing configuration steps
|
||||||
|
- Finishing any work item listed in the TODO
|
||||||
|
|
||||||
|
## Task Dependencies
|
||||||
|
|
||||||
|
When completing tasks, consider:
|
||||||
|
- **Parent tasks**: Mark parent complete only when ALL sub-tasks are done
|
||||||
|
- **Blocking tasks**: Some tasks may unblock others - mention this in updates
|
||||||
|
- **Phase completion**: Note when entire phases are completed
|
||||||
|
|
||||||
|
## Progress Tracking
|
||||||
|
|
||||||
|
Always maintain visibility of:
|
||||||
|
- Current phase progress
|
||||||
|
- Next logical task to tackle
|
||||||
|
- Any blockers or issues encountered
|
||||||
|
- Completed vs remaining work ratio
|
||||||
|
|
||||||
|
This ensures the TODO.md remains an accurate reflection of project progress and helps maintain momentum.
|
||||||
64
.dockerignore
Normal file
64
.dockerignore
Normal file
@@ -0,0 +1,64 @@
|
|||||||
|
# Dependencies
|
||||||
|
node_modules
|
||||||
|
npm-debug.log*
|
||||||
|
yarn-debug.log*
|
||||||
|
yarn-error.log*
|
||||||
|
pnpm-debug.log*
|
||||||
|
|
||||||
|
# Testing
|
||||||
|
coverage
|
||||||
|
.nyc_output
|
||||||
|
|
||||||
|
# Next.js
|
||||||
|
.next
|
||||||
|
out
|
||||||
|
dist
|
||||||
|
|
||||||
|
# Production
|
||||||
|
build
|
||||||
|
|
||||||
|
# Misc
|
||||||
|
.DS_Store
|
||||||
|
*.pem
|
||||||
|
|
||||||
|
# Debug
|
||||||
|
npm-debug.log*
|
||||||
|
yarn-debug.log*
|
||||||
|
yarn-error.log*
|
||||||
|
|
||||||
|
# Local env files
|
||||||
|
.env*.local
|
||||||
|
.env
|
||||||
|
|
||||||
|
# Vercel
|
||||||
|
.vercel
|
||||||
|
|
||||||
|
# Typescript
|
||||||
|
*.tsbuildinfo
|
||||||
|
next-env.d.ts
|
||||||
|
|
||||||
|
# IDE
|
||||||
|
.vscode
|
||||||
|
.idea
|
||||||
|
*.swp
|
||||||
|
*.swo
|
||||||
|
*~
|
||||||
|
|
||||||
|
# Git
|
||||||
|
.git
|
||||||
|
.gitignore
|
||||||
|
|
||||||
|
# Docker
|
||||||
|
Dockerfile
|
||||||
|
.dockerignore
|
||||||
|
docker-compose.yml
|
||||||
|
|
||||||
|
# Database
|
||||||
|
*.db
|
||||||
|
*.db-journal
|
||||||
|
dev.db
|
||||||
|
prisma/dev.db
|
||||||
|
|
||||||
|
# Prisma generated (will be regenerated in container)
|
||||||
|
prisma/generated
|
||||||
|
|
||||||
28
.env
28
.env
@@ -5,6 +5,28 @@
|
|||||||
# Prisma supports the native connection string format for PostgreSQL, MySQL, SQLite, SQL Server, MongoDB and CockroachDB.
|
# Prisma supports the native connection string format for PostgreSQL, MySQL, SQLite, SQL Server, MongoDB and CockroachDB.
|
||||||
# See the documentation for all the connection string options: https://pris.ly/d/connection-strings
|
# See the documentation for all the connection string options: https://pris.ly/d/connection-strings
|
||||||
|
|
||||||
DATABASE_URL="file:./dev.db"
|
# DATABASE_URL="file:./data/dev.db"
|
||||||
AUTH_SECRET="your-secret-key-change-this-in-production"
|
# AUTH_SECRET="your-secret-key-change-this-in-production"
|
||||||
AUTH_URL="http://localhost:3000"
|
# AUTH_URL="http://localhost:3000"
|
||||||
|
# PRISMA_DATA_PATH="/Users/julien.froidefond/Sites/DAIS/public/got-gaming/data"
|
||||||
|
# UPLOADS_PATH="/Users/julien.froidefond/Sites/DAIS/public/got-gaming/public/uploads"
|
||||||
|
|
||||||
|
# NextAuth Configuration
|
||||||
|
NEXTAUTH_SECRET=change-this-secret-in-production
|
||||||
|
NEXTAUTH_URL=http://localhost:3000
|
||||||
|
|
||||||
|
# PostgreSQL Configuration
|
||||||
|
POSTGRES_USER=gotgaming
|
||||||
|
POSTGRES_PASSWORD=change-this-in-production
|
||||||
|
POSTGRES_DB=gotgaming
|
||||||
|
POSTGRES_HOST=localhost
|
||||||
|
POSTGRES_PORT=5433
|
||||||
|
|
||||||
|
# Database URL (construite automatiquement si non définie)
|
||||||
|
# Si vous définissez cette variable, elle sera utilisée telle quelle
|
||||||
|
# Sinon, elle sera construite à partir des variables POSTGRES_* ci-dessus
|
||||||
|
DATABASE_URL=postgresql://gotgaming:change-this-in-production@localhost:5433/gotgaming?schema=public
|
||||||
|
|
||||||
|
# Docker Volumes (optionnel)
|
||||||
|
POSTGRES_DATA_PATH=./data/postgres
|
||||||
|
UPLOADS_PATH=./public/uploads
|
||||||
|
|||||||
19
.env.example
Normal file
19
.env.example
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
# NextAuth Configuration
|
||||||
|
NEXTAUTH_SECRET=change-this-secret-in-production
|
||||||
|
NEXTAUTH_URL=http://localhost:3000
|
||||||
|
|
||||||
|
# PostgreSQL Configuration
|
||||||
|
POSTGRES_USER=gotgaming
|
||||||
|
POSTGRES_PASSWORD=change-this-in-production
|
||||||
|
POSTGRES_DB=gotgaming
|
||||||
|
POSTGRES_HOST=got-postgres
|
||||||
|
POSTGRES_PORT=5432
|
||||||
|
|
||||||
|
# Database URL (construite automatiquement si non définie)
|
||||||
|
# Si vous définissez cette variable, elle sera utilisée telle quelle
|
||||||
|
# Sinon, elle sera construite à partir des variables POSTGRES_* ci-dessus
|
||||||
|
# DATABASE_URL=postgresql://gotgaming:change-this-in-production@got-postgres:5432/gotgaming?schema=public
|
||||||
|
|
||||||
|
# Docker Volumes (optionnel)
|
||||||
|
POSTGRES_DATA_PATH=./data/postgres
|
||||||
|
UPLOADS_PATH=./public/uploads
|
||||||
26
.gitea/workflows/deploy.yml
Normal file
26
.gitea/workflows/deploy.yml
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
name: Deploy with Docker Compose
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches:
|
||||||
|
- main # adapte la branche que tu veux déployer
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
deploy:
|
||||||
|
runs-on: mac-orbstack-runner # le nom que tu as donné au runner
|
||||||
|
steps:
|
||||||
|
- name: Checkout
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: Deploy stack
|
||||||
|
env:
|
||||||
|
DOCKER_BUILDKIT: 1
|
||||||
|
COMPOSE_DOCKER_CLI_BUILD: 1
|
||||||
|
NEXTAUTH_URL: ${{ vars.NEXTAUTH_URL }}
|
||||||
|
NEXTAUTH_SECRET: ${{ secrets.NEXTAUTH_SECRET }}
|
||||||
|
PRISMA_DATA_PATH: ${{ vars.PRISMA_DATA_PATH }}
|
||||||
|
UPLOADS_PATH: ${{ vars.UPLOADS_PATH }}
|
||||||
|
POSTGRES_DATA_PATH: ${{ vars.POSTGRES_DATA_PATH }}
|
||||||
|
POSTGRES_PASSWORD: ${{ secrets.POSTGRES_PASSWORD }}
|
||||||
|
run: |
|
||||||
|
docker compose up -d --build
|
||||||
7
.gitignore
vendored
7
.gitignore
vendored
@@ -25,6 +25,7 @@ yarn-debug.log*
|
|||||||
yarn-error.log*
|
yarn-error.log*
|
||||||
|
|
||||||
# local env files
|
# local env files
|
||||||
|
.env
|
||||||
.env*.local
|
.env*.local
|
||||||
|
|
||||||
# vercel
|
# vercel
|
||||||
@@ -41,3 +42,9 @@ dev.db*
|
|||||||
|
|
||||||
# prisma
|
# prisma
|
||||||
/app/generated/prisma
|
/app/generated/prisma
|
||||||
|
prisma/generated/
|
||||||
|
|
||||||
|
# database data
|
||||||
|
data/postgres/
|
||||||
|
data/*.db
|
||||||
|
data/*.db-journal
|
||||||
|
|||||||
10
.prettierignore
Normal file
10
.prettierignore
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
node_modules
|
||||||
|
.next
|
||||||
|
out
|
||||||
|
build
|
||||||
|
dist
|
||||||
|
*.db
|
||||||
|
*.db-journal
|
||||||
|
pnpm-lock.yaml
|
||||||
|
package-lock.json
|
||||||
|
yarn.lock
|
||||||
8
.prettierrc
Normal file
8
.prettierrc
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
{
|
||||||
|
"semi": true,
|
||||||
|
"trailingComma": "es5",
|
||||||
|
"singleQuote": false,
|
||||||
|
"printWidth": 80,
|
||||||
|
"tabWidth": 2,
|
||||||
|
"useTabs": false
|
||||||
|
}
|
||||||
95
Dockerfile
Normal file
95
Dockerfile
Normal file
@@ -0,0 +1,95 @@
|
|||||||
|
# Stage 1: Dependencies
|
||||||
|
FROM node:20-alpine AS deps
|
||||||
|
RUN apk add --no-cache libc6-compat python3 make g++
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
RUN corepack enable && corepack prepare pnpm@latest --activate
|
||||||
|
|
||||||
|
COPY package.json pnpm-lock.yaml ./
|
||||||
|
RUN --mount=type=cache,id=pnpm-store,target=/root/.local/share/pnpm/store \
|
||||||
|
pnpm install --frozen-lockfile
|
||||||
|
|
||||||
|
# Stage 2: Builder
|
||||||
|
FROM node:20-alpine AS builder
|
||||||
|
RUN apk add --no-cache libc6-compat python3 make g++
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
RUN corepack enable && corepack prepare pnpm@latest --activate
|
||||||
|
|
||||||
|
COPY --from=deps /app/node_modules ./node_modules
|
||||||
|
COPY . .
|
||||||
|
|
||||||
|
# ARG pour DATABASE_URL au build (valeur factice par défaut, car prisma generate n'a pas besoin de vraie DB)
|
||||||
|
ARG DATABASE_URL_BUILD="postgresql://user:pass@localhost:5432/db"
|
||||||
|
ENV DATABASE_URL=$DATABASE_URL_BUILD
|
||||||
|
RUN pnpm prisma generate
|
||||||
|
|
||||||
|
ENV NEXT_TELEMETRY_DISABLED=1
|
||||||
|
RUN pnpm build
|
||||||
|
|
||||||
|
# Stage 3: Runner
|
||||||
|
FROM node:20-alpine AS runner
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
ENV NODE_ENV=production
|
||||||
|
ENV NEXT_TELEMETRY_DISABLED=1
|
||||||
|
|
||||||
|
RUN apk add --no-cache python3 make g++
|
||||||
|
|
||||||
|
RUN addgroup --system --gid 1001 nodejs && \
|
||||||
|
adduser --system --uid 1001 nextjs
|
||||||
|
|
||||||
|
RUN corepack enable && corepack prepare pnpm@latest --activate
|
||||||
|
|
||||||
|
# Copier les fichiers nécessaires
|
||||||
|
COPY --from=builder --chown=nextjs:nodejs /app/.next ./.next
|
||||||
|
COPY --from=builder --chown=nextjs:nodejs /app/public ./public
|
||||||
|
COPY --from=builder /app/package.json ./package.json
|
||||||
|
COPY --from=builder /app/pnpm-lock.yaml ./pnpm-lock.yaml
|
||||||
|
COPY --from=builder /app/next.config.js ./next.config.js
|
||||||
|
# Copier le répertoire prisma complet (schema + migrations)
|
||||||
|
COPY --from=builder --chown=nextjs:nodejs /app/prisma ./prisma
|
||||||
|
# Copier prisma.config.ts (nécessaire pour Prisma 7)
|
||||||
|
COPY --from=builder --chown=nextjs:nodejs /app/prisma.config.ts ./prisma.config.ts
|
||||||
|
|
||||||
|
# Installer seulement les dépendances de production puis générer Prisma Client
|
||||||
|
# ARG pour DATABASE_URL au build (valeur factice par défaut, car prisma generate n'a pas besoin de vraie DB)
|
||||||
|
# Au runtime, DATABASE_URL sera définie par docker-compose.yml (voir ligne 41)
|
||||||
|
ARG DATABASE_URL_BUILD="postgresql://user:pass@localhost:5432/db"
|
||||||
|
ENV DATABASE_URL=$DATABASE_URL_BUILD
|
||||||
|
RUN --mount=type=cache,id=pnpm-store,target=/root/.local/share/pnpm/store \
|
||||||
|
pnpm install --frozen-lockfile --prod && \
|
||||||
|
pnpm dlx prisma generate
|
||||||
|
# Ne pas définir ENV DATABASE_URL ici - elle sera définie par docker-compose.yml au runtime
|
||||||
|
|
||||||
|
# Create uploads directories
|
||||||
|
RUN mkdir -p /app/public/uploads /app/public/uploads/backgrounds && \
|
||||||
|
chown -R nextjs:nodejs /app/public/uploads
|
||||||
|
|
||||||
|
RUN echo '#!/bin/sh' > /app/entrypoint.sh && \
|
||||||
|
echo 'set -e' >> /app/entrypoint.sh && \
|
||||||
|
echo 'mkdir -p /app/public/uploads' >> /app/entrypoint.sh && \
|
||||||
|
echo 'mkdir -p /app/public/uploads/backgrounds' >> /app/entrypoint.sh && \
|
||||||
|
echo 'if [ -z "$DATABASE_URL" ]; then' >> /app/entrypoint.sh && \
|
||||||
|
echo ' echo "ERROR: DATABASE_URL is not set"' >> /app/entrypoint.sh && \
|
||||||
|
echo ' exit 1' >> /app/entrypoint.sh && \
|
||||||
|
echo 'fi' >> /app/entrypoint.sh && \
|
||||||
|
echo 'export DATABASE_URL' >> /app/entrypoint.sh && \
|
||||||
|
echo 'cd /app' >> /app/entrypoint.sh && \
|
||||||
|
echo 'echo "Applying migrations..."' >> /app/entrypoint.sh && \
|
||||||
|
echo 'if ! pnpm dlx prisma migrate deploy; then' >> /app/entrypoint.sh && \
|
||||||
|
echo ' echo "Migration failed. Attempting to resolve failed migration..."' >> /app/entrypoint.sh && \
|
||||||
|
echo ' pnpm dlx prisma migrate resolve --applied 20251217101717_init_postgres 2>/dev/null || true' >> /app/entrypoint.sh && \
|
||||||
|
echo ' pnpm dlx prisma migrate deploy || echo "WARNING: Some migrations may need manual resolution"' >> /app/entrypoint.sh && \
|
||||||
|
echo 'fi' >> /app/entrypoint.sh && \
|
||||||
|
echo 'exec pnpm start' >> /app/entrypoint.sh && \
|
||||||
|
chmod +x /app/entrypoint.sh && \
|
||||||
|
chown nextjs:nodejs /app/entrypoint.sh
|
||||||
|
|
||||||
|
USER nextjs
|
||||||
|
|
||||||
|
EXPOSE 3000
|
||||||
|
ENV PORT=3000
|
||||||
|
ENV HOSTNAME="0.0.0.0"
|
||||||
|
|
||||||
|
ENTRYPOINT ["./entrypoint.sh"]
|
||||||
98
README.docker.md
Normal file
98
README.docker.md
Normal file
@@ -0,0 +1,98 @@
|
|||||||
|
# Docker Setup
|
||||||
|
|
||||||
|
Ce projet inclut des fichiers Docker pour faciliter le déploiement.
|
||||||
|
|
||||||
|
## Fichiers Docker
|
||||||
|
|
||||||
|
- `Dockerfile` - Image de production optimisée (multi-stage build)
|
||||||
|
- `docker-compose.yml` - Configuration pour la production
|
||||||
|
|
||||||
|
## Production
|
||||||
|
|
||||||
|
Pour construire et démarrer l'application en production :
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Construire l'image
|
||||||
|
docker-compose build
|
||||||
|
|
||||||
|
# Démarrer les services
|
||||||
|
docker-compose up -d
|
||||||
|
|
||||||
|
# Voir les logs
|
||||||
|
docker-compose logs -f
|
||||||
|
```
|
||||||
|
|
||||||
|
## Variables d'environnement
|
||||||
|
|
||||||
|
Créez un fichier `.env` à la racine du projet à partir du template `.env.example` :
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cp .env.example .env
|
||||||
|
```
|
||||||
|
|
||||||
|
Puis modifiez les valeurs dans `.env` selon votre configuration :
|
||||||
|
|
||||||
|
```env
|
||||||
|
# NextAuth Configuration
|
||||||
|
NEXTAUTH_SECRET=your-secret-key-here
|
||||||
|
NEXTAUTH_URL=http://localhost:3000
|
||||||
|
|
||||||
|
# PostgreSQL Configuration
|
||||||
|
POSTGRES_USER=gotgaming
|
||||||
|
POSTGRES_PASSWORD=change-this-in-production
|
||||||
|
POSTGRES_DB=gotgaming
|
||||||
|
|
||||||
|
# Database URL (optionnel - construite automatiquement si non définie)
|
||||||
|
# DATABASE_URL=postgresql://gotgaming:change-this-in-production@got-postgres:5432/gotgaming?schema=public
|
||||||
|
|
||||||
|
# Docker Volumes (optionnel)
|
||||||
|
POSTGRES_DATA_PATH=./data/postgres
|
||||||
|
UPLOADS_PATH=./public/uploads
|
||||||
|
```
|
||||||
|
|
||||||
|
**Important** :
|
||||||
|
- Le fichier `.env` est ignoré par Git (ne pas commiter vos secrets)
|
||||||
|
- Si vous changez `POSTGRES_PASSWORD` après la première initialisation, vous devrez soit réinitialiser la base, soit changer le mot de passe manuellement dans PostgreSQL
|
||||||
|
|
||||||
|
## Volumes persistants
|
||||||
|
|
||||||
|
### Base de données PostgreSQL
|
||||||
|
|
||||||
|
La base de données PostgreSQL est persistée via un volume Docker. Par défaut, elle est stockée dans `./data/postgres`, mais vous pouvez la personnaliser avec la variable d'environnement `POSTGRES_DATA_PATH`.
|
||||||
|
|
||||||
|
Les migrations Prisma sont appliquées automatiquement au démarrage du conteneur.
|
||||||
|
|
||||||
|
Pour appliquer manuellement les migrations :
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker-compose exec got-app pnpm dlx prisma migrate deploy
|
||||||
|
```
|
||||||
|
|
||||||
|
### Images uploadées
|
||||||
|
|
||||||
|
Les images uploadées (avatars et backgrounds) sont persistées dans un volume Docker. Par défaut, elles sont stockées dans `./uploads` à la racine du projet, mais vous pouvez personnaliser le chemin avec la variable d'environnement `UPLOADS_PATH`.
|
||||||
|
|
||||||
|
- Les avatars sont stockés dans `uploads/`
|
||||||
|
- Les backgrounds sont stockés dans `uploads/backgrounds/`
|
||||||
|
|
||||||
|
Exemple pour utiliser un chemin personnalisé :
|
||||||
|
|
||||||
|
```bash
|
||||||
|
UPLOADS_PATH=/path/to/your/uploads docker-compose up -d
|
||||||
|
```
|
||||||
|
|
||||||
|
## Commandes utiles
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Arrêter les conteneurs
|
||||||
|
docker-compose down
|
||||||
|
|
||||||
|
# Reconstruire sans cache
|
||||||
|
docker-compose build --no-cache
|
||||||
|
|
||||||
|
# Accéder au shell du conteneur
|
||||||
|
docker-compose exec got-app sh
|
||||||
|
|
||||||
|
# Voir les logs en temps réel
|
||||||
|
docker-compose logs -f got-app
|
||||||
|
```
|
||||||
17
README.md
17
README.md
@@ -1,6 +1,6 @@
|
|||||||
# Farmine Land - Site Gaming
|
# Game of Tech - Peaksys
|
||||||
|
|
||||||
Site web Next.js pour le jeu Farmine Land, un MMORPG 2D Open-World.
|
Plateforme de gamification tech pour Peaksys. Transformez votre apprentissage en aventure : participez aux événements tech (ateliers, katas, présentations), gagnez de l'expérience, montez en niveau et affrontez vos collègues sur le classement.
|
||||||
|
|
||||||
## Installation
|
## Installation
|
||||||
|
|
||||||
@@ -27,9 +27,13 @@ pnpm start
|
|||||||
|
|
||||||
- `/app` - Pages et layout Next.js
|
- `/app` - Pages et layout Next.js
|
||||||
- `/components` - Composants React réutilisables
|
- `/components` - Composants React réutilisables
|
||||||
- `Navigation.tsx` - Barre de navigation
|
- `Navigation.tsx` - Barre de navigation avec logo cliquable
|
||||||
- `HeroSection.tsx` - Section principale avec logo et description
|
- `HeroSection.tsx` - Section principale avec description
|
||||||
- `Leaderboard.tsx` - Tableau des classements
|
- `EventsSection.tsx` - Section des événements à venir
|
||||||
|
- `EventsPageSection.tsx` - Page complète des événements
|
||||||
|
- `LeaderboardSection.tsx` - Tableau des classements
|
||||||
|
- `PlayerStats.tsx` - Statistiques du joueur (HP, XP, niveau)
|
||||||
|
- `AdminPanel.tsx` - Panneau d'administration
|
||||||
|
|
||||||
## Technologies
|
## Technologies
|
||||||
|
|
||||||
@@ -37,4 +41,5 @@ pnpm start
|
|||||||
- React 18
|
- React 18
|
||||||
- TypeScript
|
- TypeScript
|
||||||
- Tailwind CSS
|
- Tailwind CSS
|
||||||
|
- Prisma (PostgreSQL)
|
||||||
|
- NextAuth.js
|
||||||
|
|||||||
270
actions/admin/challenges.ts
Normal file
270
actions/admin/challenges.ts
Normal file
@@ -0,0 +1,270 @@
|
|||||||
|
"use server";
|
||||||
|
|
||||||
|
import { revalidatePath } from "next/cache";
|
||||||
|
import { auth } from "@/lib/auth";
|
||||||
|
import { challengeService } from "@/services/challenges/challenge.service";
|
||||||
|
import { Role } from "@/prisma/generated/prisma/client";
|
||||||
|
import { ValidationError, NotFoundError } from "@/services/errors";
|
||||||
|
|
||||||
|
async function checkAdminAccess() {
|
||||||
|
const session = await auth();
|
||||||
|
if (!session?.user || session.user.role !== Role.ADMIN) {
|
||||||
|
throw new Error("Accès refusé - Admin uniquement");
|
||||||
|
}
|
||||||
|
return session;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function validateChallenge(
|
||||||
|
challengeId: string,
|
||||||
|
winnerId: string,
|
||||||
|
adminComment?: string
|
||||||
|
) {
|
||||||
|
try {
|
||||||
|
const session = await checkAdminAccess();
|
||||||
|
|
||||||
|
const challenge = await challengeService.validateChallenge(
|
||||||
|
challengeId,
|
||||||
|
session.user.id,
|
||||||
|
winnerId,
|
||||||
|
adminComment
|
||||||
|
);
|
||||||
|
|
||||||
|
revalidatePath("/admin");
|
||||||
|
revalidatePath("/challenges");
|
||||||
|
revalidatePath("/leaderboard");
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
message: "Défi validé avec succès",
|
||||||
|
data: challenge,
|
||||||
|
};
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Validate challenge error:", error);
|
||||||
|
|
||||||
|
if (error instanceof ValidationError) {
|
||||||
|
return { success: false, error: error.message };
|
||||||
|
}
|
||||||
|
if (error instanceof NotFoundError) {
|
||||||
|
return { success: false, error: error.message };
|
||||||
|
}
|
||||||
|
if (error instanceof Error && error.message.includes("Accès refusé")) {
|
||||||
|
return { success: false, error: error.message };
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: "Une erreur est survenue lors de la validation du défi",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function rejectChallenge(
|
||||||
|
challengeId: string,
|
||||||
|
adminComment?: string
|
||||||
|
) {
|
||||||
|
try {
|
||||||
|
const session = await checkAdminAccess();
|
||||||
|
|
||||||
|
const challenge = await challengeService.rejectChallenge(
|
||||||
|
challengeId,
|
||||||
|
session.user.id,
|
||||||
|
adminComment
|
||||||
|
);
|
||||||
|
|
||||||
|
revalidatePath("/admin");
|
||||||
|
revalidatePath("/challenges");
|
||||||
|
|
||||||
|
return { success: true, message: "Défi rejeté", data: challenge };
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Reject challenge error:", error);
|
||||||
|
|
||||||
|
if (error instanceof ValidationError) {
|
||||||
|
return { success: false, error: error.message };
|
||||||
|
}
|
||||||
|
if (error instanceof NotFoundError) {
|
||||||
|
return { success: false, error: error.message };
|
||||||
|
}
|
||||||
|
if (error instanceof Error && error.message.includes("Accès refusé")) {
|
||||||
|
return { success: false, error: error.message };
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: "Une erreur est survenue lors du rejet du défi",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function updateChallenge(
|
||||||
|
challengeId: string,
|
||||||
|
data: {
|
||||||
|
title?: string;
|
||||||
|
description?: string;
|
||||||
|
pointsReward?: number;
|
||||||
|
}
|
||||||
|
) {
|
||||||
|
try {
|
||||||
|
await checkAdminAccess();
|
||||||
|
|
||||||
|
const challenge = await challengeService.updateChallenge(challengeId, {
|
||||||
|
title: data.title,
|
||||||
|
description: data.description,
|
||||||
|
pointsReward: data.pointsReward,
|
||||||
|
});
|
||||||
|
|
||||||
|
revalidatePath("/admin");
|
||||||
|
revalidatePath("/challenges");
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
message: "Défi mis à jour avec succès",
|
||||||
|
data: challenge,
|
||||||
|
};
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Update challenge error:", error);
|
||||||
|
|
||||||
|
if (error instanceof ValidationError) {
|
||||||
|
return { success: false, error: error.message };
|
||||||
|
}
|
||||||
|
if (error instanceof NotFoundError) {
|
||||||
|
return { success: false, error: error.message };
|
||||||
|
}
|
||||||
|
if (error instanceof Error && error.message.includes("Accès refusé")) {
|
||||||
|
return { success: false, error: error.message };
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: "Une erreur est survenue lors de la mise à jour du défi",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function deleteChallenge(challengeId: string) {
|
||||||
|
try {
|
||||||
|
await checkAdminAccess();
|
||||||
|
|
||||||
|
await challengeService.deleteChallenge(challengeId);
|
||||||
|
|
||||||
|
revalidatePath("/admin");
|
||||||
|
revalidatePath("/challenges");
|
||||||
|
|
||||||
|
return { success: true, message: "Défi supprimé avec succès" };
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Delete challenge error:", error);
|
||||||
|
|
||||||
|
if (error instanceof NotFoundError) {
|
||||||
|
return { success: false, error: error.message };
|
||||||
|
}
|
||||||
|
if (error instanceof Error && error.message.includes("Accès refusé")) {
|
||||||
|
return { success: false, error: error.message };
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: "Une erreur est survenue lors de la suppression du défi",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function adminCancelChallenge(challengeId: string) {
|
||||||
|
try {
|
||||||
|
await checkAdminAccess();
|
||||||
|
|
||||||
|
const challenge = await challengeService.adminCancelChallenge(challengeId);
|
||||||
|
|
||||||
|
revalidatePath("/admin");
|
||||||
|
revalidatePath("/challenges");
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
message: "Défi annulé avec succès",
|
||||||
|
data: challenge,
|
||||||
|
};
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Admin cancel challenge error:", error);
|
||||||
|
|
||||||
|
if (error instanceof ValidationError) {
|
||||||
|
return { success: false, error: error.message };
|
||||||
|
}
|
||||||
|
if (error instanceof NotFoundError) {
|
||||||
|
return { success: false, error: error.message };
|
||||||
|
}
|
||||||
|
if (error instanceof Error && error.message.includes("Accès refusé")) {
|
||||||
|
return { success: false, error: error.message };
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: "Une erreur est survenue lors de l'annulation du défi",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function reactivateChallenge(challengeId: string) {
|
||||||
|
try {
|
||||||
|
await checkAdminAccess();
|
||||||
|
|
||||||
|
const challenge = await challengeService.reactivateChallenge(challengeId);
|
||||||
|
|
||||||
|
revalidatePath("/admin");
|
||||||
|
revalidatePath("/challenges");
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
message: "Défi réactivé avec succès",
|
||||||
|
data: challenge,
|
||||||
|
};
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Reactivate challenge error:", error);
|
||||||
|
|
||||||
|
if (error instanceof ValidationError) {
|
||||||
|
return { success: false, error: error.message };
|
||||||
|
}
|
||||||
|
if (error instanceof NotFoundError) {
|
||||||
|
return { success: false, error: error.message };
|
||||||
|
}
|
||||||
|
if (error instanceof Error && error.message.includes("Accès refusé")) {
|
||||||
|
return { success: false, error: error.message };
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: "Une erreur est survenue lors de la réactivation du défi",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function adminAcceptChallenge(challengeId: string) {
|
||||||
|
try {
|
||||||
|
await checkAdminAccess();
|
||||||
|
|
||||||
|
const challenge = await challengeService.adminAcceptChallenge(challengeId);
|
||||||
|
|
||||||
|
revalidatePath("/admin");
|
||||||
|
revalidatePath("/challenges");
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
message: "Défi accepté avec succès",
|
||||||
|
data: challenge,
|
||||||
|
};
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Admin accept challenge error:", error);
|
||||||
|
|
||||||
|
if (error instanceof ValidationError) {
|
||||||
|
return { success: false, error: error.message };
|
||||||
|
}
|
||||||
|
if (error instanceof NotFoundError) {
|
||||||
|
return { success: false, error: error.message };
|
||||||
|
}
|
||||||
|
if (error instanceof Error && error.message.includes("Accès refusé")) {
|
||||||
|
return { success: false, error: error.message };
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: "Une erreur est survenue lors de l'acceptation du défi",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
142
actions/admin/events.ts
Normal file
142
actions/admin/events.ts
Normal file
@@ -0,0 +1,142 @@
|
|||||||
|
"use server";
|
||||||
|
|
||||||
|
import { revalidatePath } from "next/cache";
|
||||||
|
import { auth } from "@/lib/auth";
|
||||||
|
import { eventService } from "@/services/events/event.service";
|
||||||
|
import { Role, EventType } from "@/prisma/generated/prisma/client";
|
||||||
|
import { ValidationError, NotFoundError } from "@/services/errors";
|
||||||
|
|
||||||
|
function checkAdminAccess() {
|
||||||
|
return async () => {
|
||||||
|
const session = await auth();
|
||||||
|
if (!session?.user || session.user.role !== Role.ADMIN) {
|
||||||
|
throw new Error("Accès refusé");
|
||||||
|
}
|
||||||
|
return session;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function createEvent(data: {
|
||||||
|
date: string;
|
||||||
|
name: string;
|
||||||
|
description?: string | null;
|
||||||
|
type: string;
|
||||||
|
room?: string | null;
|
||||||
|
time?: string | null;
|
||||||
|
maxPlaces?: number | null;
|
||||||
|
}) {
|
||||||
|
try {
|
||||||
|
await checkAdminAccess()();
|
||||||
|
|
||||||
|
const event = await eventService.validateAndCreateEvent({
|
||||||
|
date: data.date,
|
||||||
|
name: data.name,
|
||||||
|
description: data.description ?? "",
|
||||||
|
type: data.type as EventType,
|
||||||
|
room: data.room ?? undefined,
|
||||||
|
time: data.time ?? undefined,
|
||||||
|
maxPlaces: data.maxPlaces ?? undefined,
|
||||||
|
});
|
||||||
|
|
||||||
|
revalidatePath("/admin");
|
||||||
|
revalidatePath("/events");
|
||||||
|
revalidatePath("/");
|
||||||
|
|
||||||
|
return { success: true, data: event };
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error creating event:", error);
|
||||||
|
|
||||||
|
if (error instanceof ValidationError) {
|
||||||
|
return { success: false, error: error.message };
|
||||||
|
}
|
||||||
|
if (error instanceof Error && error.message === "Accès refusé") {
|
||||||
|
return { success: false, error: "Accès refusé" };
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: "Erreur lors de la création de l'événement",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function updateEvent(
|
||||||
|
eventId: string,
|
||||||
|
data: {
|
||||||
|
date?: string;
|
||||||
|
name?: string;
|
||||||
|
description?: string | null;
|
||||||
|
type?: string;
|
||||||
|
room?: string | null;
|
||||||
|
time?: string | null;
|
||||||
|
maxPlaces?: number | null;
|
||||||
|
}
|
||||||
|
) {
|
||||||
|
try {
|
||||||
|
await checkAdminAccess()();
|
||||||
|
|
||||||
|
const event = await eventService.validateAndUpdateEvent(eventId, {
|
||||||
|
date: data.date,
|
||||||
|
name: data.name,
|
||||||
|
description: data.description ?? undefined,
|
||||||
|
type: data.type as EventType,
|
||||||
|
room: data.room ?? undefined,
|
||||||
|
time: data.time ?? undefined,
|
||||||
|
maxPlaces: data.maxPlaces ?? undefined,
|
||||||
|
});
|
||||||
|
|
||||||
|
revalidatePath("/admin");
|
||||||
|
revalidatePath("/events");
|
||||||
|
revalidatePath("/");
|
||||||
|
|
||||||
|
return { success: true, data: event };
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error updating event:", error);
|
||||||
|
|
||||||
|
if (error instanceof ValidationError) {
|
||||||
|
return { success: false, error: error.message };
|
||||||
|
}
|
||||||
|
if (error instanceof NotFoundError) {
|
||||||
|
return { success: false, error: error.message };
|
||||||
|
}
|
||||||
|
if (error instanceof Error && error.message === "Accès refusé") {
|
||||||
|
return { success: false, error: "Accès refusé" };
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: "Erreur lors de la mise à jour de l'événement",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function deleteEvent(eventId: string) {
|
||||||
|
try {
|
||||||
|
await checkAdminAccess()();
|
||||||
|
|
||||||
|
const existingEvent = await eventService.getEventById(eventId);
|
||||||
|
|
||||||
|
if (!existingEvent) {
|
||||||
|
return { success: false, error: "Événement non trouvé" };
|
||||||
|
}
|
||||||
|
|
||||||
|
await eventService.deleteEvent(eventId);
|
||||||
|
|
||||||
|
revalidatePath("/admin");
|
||||||
|
revalidatePath("/events");
|
||||||
|
revalidatePath("/");
|
||||||
|
|
||||||
|
return { success: true };
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error deleting event:", error);
|
||||||
|
|
||||||
|
if (error instanceof Error && error.message === "Accès refusé") {
|
||||||
|
return { success: false, error: "Accès refusé" };
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: "Erreur lors de la suppression de l'événement",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
127
actions/admin/feedback.ts
Normal file
127
actions/admin/feedback.ts
Normal file
@@ -0,0 +1,127 @@
|
|||||||
|
"use server";
|
||||||
|
|
||||||
|
import { revalidatePath } from "next/cache";
|
||||||
|
import { auth } from "@/lib/auth";
|
||||||
|
import { prisma } from "@/services/database";
|
||||||
|
import { Role } from "@/prisma/generated/prisma/client";
|
||||||
|
import { NotFoundError } from "@/services/errors";
|
||||||
|
|
||||||
|
function checkAdminAccess() {
|
||||||
|
return async () => {
|
||||||
|
const session = await auth();
|
||||||
|
if (!session?.user || session.user.role !== Role.ADMIN) {
|
||||||
|
throw new Error("Accès refusé");
|
||||||
|
}
|
||||||
|
return session;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function addFeedbackBonusPoints(
|
||||||
|
userId: string,
|
||||||
|
points: number
|
||||||
|
) {
|
||||||
|
try {
|
||||||
|
await checkAdminAccess()();
|
||||||
|
|
||||||
|
// Vérifier que l'utilisateur existe
|
||||||
|
const user = await prisma.user.findUnique({
|
||||||
|
where: { id: userId },
|
||||||
|
select: { id: true, score: true },
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!user) {
|
||||||
|
throw new NotFoundError("Utilisateur");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Ajouter les points
|
||||||
|
const updatedUser = await prisma.user.update({
|
||||||
|
where: { id: userId },
|
||||||
|
data: {
|
||||||
|
score: {
|
||||||
|
increment: points,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
select: {
|
||||||
|
id: true,
|
||||||
|
username: true,
|
||||||
|
score: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
revalidatePath("/admin");
|
||||||
|
revalidatePath("/leaderboard");
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
message: `${points} points ajoutés avec succès`,
|
||||||
|
data: updatedUser,
|
||||||
|
};
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error adding bonus points:", error);
|
||||||
|
|
||||||
|
if (error instanceof NotFoundError) {
|
||||||
|
return { success: false, error: error.message };
|
||||||
|
}
|
||||||
|
if (error instanceof Error && error.message === "Accès refusé") {
|
||||||
|
return { success: false, error: "Accès refusé" };
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: "Erreur lors de l'ajout des points",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function markFeedbackAsRead(feedbackId: string, isRead: boolean) {
|
||||||
|
try {
|
||||||
|
await checkAdminAccess()();
|
||||||
|
|
||||||
|
// Vérifier que le feedback existe
|
||||||
|
const feedback = await prisma.eventFeedback.findUnique({
|
||||||
|
where: { id: feedbackId },
|
||||||
|
select: { id: true },
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!feedback) {
|
||||||
|
throw new NotFoundError("Feedback");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Mettre à jour le statut
|
||||||
|
const updatedFeedback = await prisma.eventFeedback.update({
|
||||||
|
where: { id: feedbackId },
|
||||||
|
data: {
|
||||||
|
isRead,
|
||||||
|
},
|
||||||
|
select: {
|
||||||
|
id: true,
|
||||||
|
isRead: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
revalidatePath("/admin");
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
message: isRead
|
||||||
|
? "Feedback marqué comme lu"
|
||||||
|
: "Feedback marqué comme non lu",
|
||||||
|
data: updatedFeedback,
|
||||||
|
};
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error marking feedback as read:", error);
|
||||||
|
|
||||||
|
if (error instanceof NotFoundError) {
|
||||||
|
return { success: false, error: error.message };
|
||||||
|
}
|
||||||
|
if (error instanceof Error && error.message === "Accès refusé") {
|
||||||
|
return { success: false, error: "Accès refusé" };
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: "Erreur lors de la mise à jour du feedback",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
139
actions/admin/houses.ts
Normal file
139
actions/admin/houses.ts
Normal file
@@ -0,0 +1,139 @@
|
|||||||
|
"use server";
|
||||||
|
|
||||||
|
import { revalidatePath } from "next/cache";
|
||||||
|
import { auth } from "@/lib/auth";
|
||||||
|
import { houseService } from "@/services/houses/house.service";
|
||||||
|
import { Role } from "@/prisma/generated/prisma/client";
|
||||||
|
import {
|
||||||
|
ValidationError,
|
||||||
|
NotFoundError,
|
||||||
|
ConflictError,
|
||||||
|
ForbiddenError,
|
||||||
|
} from "@/services/errors";
|
||||||
|
|
||||||
|
function checkAdminAccess() {
|
||||||
|
return async () => {
|
||||||
|
const session = await auth();
|
||||||
|
if (!session?.user || session.user.role !== Role.ADMIN) {
|
||||||
|
throw new Error("Accès refusé");
|
||||||
|
}
|
||||||
|
return session;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function updateHouse(
|
||||||
|
houseId: string,
|
||||||
|
data: {
|
||||||
|
name?: string;
|
||||||
|
description?: string | null;
|
||||||
|
}
|
||||||
|
) {
|
||||||
|
try {
|
||||||
|
await checkAdminAccess()();
|
||||||
|
|
||||||
|
// L'admin peut modifier n'importe quelle maison sans vérifier les permissions normales
|
||||||
|
// On utilise directement le service mais on bypass les vérifications de propriétaire/admin
|
||||||
|
const house = await houseService.getHouseById(houseId);
|
||||||
|
if (!house) {
|
||||||
|
return { success: false, error: "Maison non trouvée" };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Utiliser le service avec le creatorId pour bypass les vérifications
|
||||||
|
const updatedHouse = await houseService.updateHouse(
|
||||||
|
houseId,
|
||||||
|
house.creatorId, // Utiliser le creatorId pour bypass
|
||||||
|
data
|
||||||
|
);
|
||||||
|
|
||||||
|
revalidatePath("/admin");
|
||||||
|
revalidatePath("/houses");
|
||||||
|
|
||||||
|
return { success: true, data: updatedHouse };
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error updating house:", error);
|
||||||
|
|
||||||
|
if (error instanceof ValidationError) {
|
||||||
|
return { success: false, error: error.message };
|
||||||
|
}
|
||||||
|
if (error instanceof ConflictError) {
|
||||||
|
return { success: false, error: error.message };
|
||||||
|
}
|
||||||
|
if (error instanceof Error && error.message === "Accès refusé") {
|
||||||
|
return { success: false, error: "Accès refusé" };
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: "Erreur lors de la mise à jour de la maison",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function deleteHouse(houseId: string) {
|
||||||
|
try {
|
||||||
|
await checkAdminAccess()();
|
||||||
|
|
||||||
|
const house = await houseService.getHouseById(houseId);
|
||||||
|
if (!house) {
|
||||||
|
return { success: false, error: "Maison non trouvée" };
|
||||||
|
}
|
||||||
|
|
||||||
|
// L'admin peut supprimer n'importe quelle maison
|
||||||
|
// On utilise le creatorId pour bypass les vérifications
|
||||||
|
await houseService.deleteHouse(houseId, house.creatorId);
|
||||||
|
|
||||||
|
revalidatePath("/admin");
|
||||||
|
revalidatePath("/houses");
|
||||||
|
|
||||||
|
return { success: true };
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error deleting house:", error);
|
||||||
|
|
||||||
|
if (error instanceof NotFoundError) {
|
||||||
|
return { success: false, error: error.message };
|
||||||
|
}
|
||||||
|
if (error instanceof ForbiddenError) {
|
||||||
|
return { success: false, error: error.message };
|
||||||
|
}
|
||||||
|
if (error instanceof Error && error.message === "Accès refusé") {
|
||||||
|
return { success: false, error: "Accès refusé" };
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: "Erreur lors de la suppression de la maison",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function removeMember(houseId: string, memberId: string) {
|
||||||
|
try {
|
||||||
|
await checkAdminAccess()();
|
||||||
|
|
||||||
|
// L'admin peut retirer n'importe quel membre (sauf le propriétaire)
|
||||||
|
await houseService.removeMemberAsAdmin(houseId, memberId);
|
||||||
|
|
||||||
|
revalidatePath("/admin");
|
||||||
|
revalidatePath("/houses");
|
||||||
|
|
||||||
|
return { success: true, message: "Membre retiré de la maison" };
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error removing member:", error);
|
||||||
|
|
||||||
|
if (error instanceof NotFoundError) {
|
||||||
|
return { success: false, error: error.message };
|
||||||
|
}
|
||||||
|
if (error instanceof ForbiddenError) {
|
||||||
|
return { success: false, error: error.message };
|
||||||
|
}
|
||||||
|
if (error instanceof Error && error.message === "Accès refusé") {
|
||||||
|
return { success: false, error: "Accès refusé" };
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: "Erreur lors du retrait du membre",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
69
actions/admin/preferences.ts
Normal file
69
actions/admin/preferences.ts
Normal file
@@ -0,0 +1,69 @@
|
|||||||
|
"use server";
|
||||||
|
|
||||||
|
import { revalidatePath } from "next/cache";
|
||||||
|
import { auth } from "@/lib/auth";
|
||||||
|
import { sitePreferencesService } from "@/services/preferences/site-preferences.service";
|
||||||
|
import { Role } from "@/prisma/generated/prisma/client";
|
||||||
|
|
||||||
|
function checkAdminAccess() {
|
||||||
|
return async () => {
|
||||||
|
const session = await auth();
|
||||||
|
if (!session?.user || session.user.role !== Role.ADMIN) {
|
||||||
|
throw new Error("Accès refusé");
|
||||||
|
}
|
||||||
|
return session;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function updateSitePreferences(data: {
|
||||||
|
homeBackground?: string | null;
|
||||||
|
eventsBackground?: string | null;
|
||||||
|
leaderboardBackground?: string | null;
|
||||||
|
challengesBackground?: string | null;
|
||||||
|
profileBackground?: string | null;
|
||||||
|
houseBackground?: string | null;
|
||||||
|
eventRegistrationPoints?: number;
|
||||||
|
eventFeedbackPoints?: number;
|
||||||
|
houseJoinPoints?: number;
|
||||||
|
houseLeavePoints?: number;
|
||||||
|
houseCreatePoints?: number;
|
||||||
|
}) {
|
||||||
|
try {
|
||||||
|
await checkAdminAccess()();
|
||||||
|
|
||||||
|
const preferences = await sitePreferencesService.updateSitePreferences({
|
||||||
|
homeBackground: data.homeBackground,
|
||||||
|
eventsBackground: data.eventsBackground,
|
||||||
|
leaderboardBackground: data.leaderboardBackground,
|
||||||
|
challengesBackground: data.challengesBackground,
|
||||||
|
profileBackground: data.profileBackground,
|
||||||
|
houseBackground: data.houseBackground,
|
||||||
|
eventRegistrationPoints: data.eventRegistrationPoints,
|
||||||
|
eventFeedbackPoints: data.eventFeedbackPoints,
|
||||||
|
houseJoinPoints: data.houseJoinPoints,
|
||||||
|
houseLeavePoints: data.houseLeavePoints,
|
||||||
|
houseCreatePoints: data.houseCreatePoints,
|
||||||
|
});
|
||||||
|
|
||||||
|
revalidatePath("/admin");
|
||||||
|
revalidatePath("/");
|
||||||
|
revalidatePath("/events");
|
||||||
|
revalidatePath("/leaderboard");
|
||||||
|
revalidatePath("/challenges");
|
||||||
|
revalidatePath("/profile");
|
||||||
|
revalidatePath("/houses");
|
||||||
|
|
||||||
|
return { success: true, data: preferences };
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error updating admin preferences:", error);
|
||||||
|
|
||||||
|
if (error instanceof Error && error.message === "Accès refusé") {
|
||||||
|
return { success: false, error: "Accès refusé" };
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: "Erreur lors de la mise à jour des préférences",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
129
actions/admin/users.ts
Normal file
129
actions/admin/users.ts
Normal file
@@ -0,0 +1,129 @@
|
|||||||
|
"use server";
|
||||||
|
|
||||||
|
import { revalidatePath } from "next/cache";
|
||||||
|
import { auth } from "@/lib/auth";
|
||||||
|
import { userService } from "@/services/users/user.service";
|
||||||
|
import { userStatsService } from "@/services/users/user-stats.service";
|
||||||
|
import { Role } from "@/prisma/generated/prisma/client";
|
||||||
|
import {
|
||||||
|
ValidationError,
|
||||||
|
NotFoundError,
|
||||||
|
ConflictError,
|
||||||
|
} from "@/services/errors";
|
||||||
|
|
||||||
|
function checkAdminAccess() {
|
||||||
|
return async () => {
|
||||||
|
const session = await auth();
|
||||||
|
if (!session?.user || session.user.role !== Role.ADMIN) {
|
||||||
|
throw new Error("Accès refusé");
|
||||||
|
}
|
||||||
|
return session;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function updateUser(
|
||||||
|
userId: string,
|
||||||
|
data: {
|
||||||
|
username?: string;
|
||||||
|
avatar?: string | null;
|
||||||
|
hpDelta?: number;
|
||||||
|
xpDelta?: number;
|
||||||
|
score?: number;
|
||||||
|
level?: number;
|
||||||
|
role?: string;
|
||||||
|
}
|
||||||
|
) {
|
||||||
|
try {
|
||||||
|
await checkAdminAccess()();
|
||||||
|
|
||||||
|
// Valider username si fourni
|
||||||
|
if (data.username !== undefined) {
|
||||||
|
try {
|
||||||
|
await userService.validateAndUpdateUserProfile(userId, {
|
||||||
|
username: data.username,
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
if (
|
||||||
|
error instanceof ValidationError ||
|
||||||
|
error instanceof ConflictError
|
||||||
|
) {
|
||||||
|
return { success: false, error: error.message };
|
||||||
|
}
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Mettre à jour stats et profil
|
||||||
|
const updatedUser = await userStatsService.updateUserStatsAndProfile(
|
||||||
|
userId,
|
||||||
|
{
|
||||||
|
username: data.username,
|
||||||
|
avatar: data.avatar,
|
||||||
|
hpDelta: data.hpDelta,
|
||||||
|
xpDelta: data.xpDelta,
|
||||||
|
score: data.score,
|
||||||
|
level: data.level,
|
||||||
|
role: data.role ? (data.role as Role) : undefined,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: true,
|
||||||
|
username: true,
|
||||||
|
email: true,
|
||||||
|
role: true,
|
||||||
|
score: true,
|
||||||
|
level: true,
|
||||||
|
hp: true,
|
||||||
|
maxHp: true,
|
||||||
|
xp: true,
|
||||||
|
maxXp: true,
|
||||||
|
avatar: true,
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
revalidatePath("/admin");
|
||||||
|
revalidatePath("/leaderboard");
|
||||||
|
|
||||||
|
return { success: true, data: updatedUser };
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error updating user:", error);
|
||||||
|
|
||||||
|
if (error instanceof Error && error.message === "Accès refusé") {
|
||||||
|
return { success: false, error: "Accès refusé" };
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: "Erreur lors de la mise à jour de l'utilisateur",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function deleteUser(userId: string) {
|
||||||
|
try {
|
||||||
|
const session = await checkAdminAccess()();
|
||||||
|
|
||||||
|
await userService.validateAndDeleteUser(userId, session.user.id);
|
||||||
|
|
||||||
|
revalidatePath("/admin");
|
||||||
|
revalidatePath("/leaderboard");
|
||||||
|
|
||||||
|
return { success: true };
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error deleting user:", error);
|
||||||
|
|
||||||
|
if (error instanceof ValidationError) {
|
||||||
|
return { success: false, error: error.message };
|
||||||
|
}
|
||||||
|
if (error instanceof NotFoundError) {
|
||||||
|
return { success: false, error: error.message };
|
||||||
|
}
|
||||||
|
if (error instanceof Error && error.message === "Accès refusé") {
|
||||||
|
return { success: false, error: "Accès refusé" };
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: "Erreur lors de la suppression de l'utilisateur",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
131
actions/challenges/create.ts
Normal file
131
actions/challenges/create.ts
Normal file
@@ -0,0 +1,131 @@
|
|||||||
|
"use server";
|
||||||
|
|
||||||
|
import { revalidatePath } from "next/cache";
|
||||||
|
import { auth } from "@/lib/auth";
|
||||||
|
import { challengeService } from "@/services/challenges/challenge.service";
|
||||||
|
import {
|
||||||
|
ValidationError,
|
||||||
|
NotFoundError,
|
||||||
|
ConflictError,
|
||||||
|
} from "@/services/errors";
|
||||||
|
|
||||||
|
export async function createChallenge(data: {
|
||||||
|
challengedId: string;
|
||||||
|
title: string;
|
||||||
|
description: string;
|
||||||
|
pointsReward?: number;
|
||||||
|
}) {
|
||||||
|
try {
|
||||||
|
const session = await auth();
|
||||||
|
|
||||||
|
if (!session?.user?.id) {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: "Vous devez être connecté pour créer un défi",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const challenge = await challengeService.createChallenge({
|
||||||
|
challengerId: session.user.id,
|
||||||
|
challengedId: data.challengedId,
|
||||||
|
title: data.title,
|
||||||
|
description: data.description,
|
||||||
|
pointsReward: data.pointsReward || 100,
|
||||||
|
});
|
||||||
|
|
||||||
|
revalidatePath("/challenges");
|
||||||
|
revalidatePath("/profile");
|
||||||
|
|
||||||
|
return { success: true, message: "Défi créé avec succès", data: challenge };
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Create challenge error:", error);
|
||||||
|
|
||||||
|
if (error instanceof ValidationError || error instanceof ConflictError) {
|
||||||
|
return { success: false, error: error.message };
|
||||||
|
}
|
||||||
|
if (error instanceof NotFoundError) {
|
||||||
|
return { success: false, error: error.message };
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: "Une erreur est survenue lors de la création du défi",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function acceptChallenge(challengeId: string) {
|
||||||
|
try {
|
||||||
|
const session = await auth();
|
||||||
|
|
||||||
|
if (!session?.user?.id) {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: "Vous devez être connecté pour accepter un défi",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const challenge = await challengeService.acceptChallenge(
|
||||||
|
challengeId,
|
||||||
|
session.user.id
|
||||||
|
);
|
||||||
|
|
||||||
|
revalidatePath("/challenges");
|
||||||
|
revalidatePath("/profile");
|
||||||
|
|
||||||
|
return { success: true, message: "Défi accepté", data: challenge };
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Accept challenge error:", error);
|
||||||
|
|
||||||
|
if (error instanceof ValidationError) {
|
||||||
|
return { success: false, error: error.message };
|
||||||
|
}
|
||||||
|
if (error instanceof NotFoundError) {
|
||||||
|
return { success: false, error: error.message };
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: "Une erreur est survenue lors de l'acceptation du défi",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function cancelChallenge(challengeId: string) {
|
||||||
|
try {
|
||||||
|
const session = await auth();
|
||||||
|
|
||||||
|
if (!session?.user?.id) {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: "Vous devez être connecté pour annuler un défi",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const challenge = await challengeService.cancelChallenge(
|
||||||
|
challengeId,
|
||||||
|
session.user.id
|
||||||
|
);
|
||||||
|
|
||||||
|
revalidatePath("/challenges");
|
||||||
|
revalidatePath("/profile");
|
||||||
|
|
||||||
|
return { success: true, message: "Défi annulé", data: challenge };
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Cancel challenge error:", error);
|
||||||
|
|
||||||
|
if (error instanceof ValidationError) {
|
||||||
|
return { success: false, error: error.message };
|
||||||
|
}
|
||||||
|
if (error instanceof NotFoundError) {
|
||||||
|
return { success: false, error: error.message };
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: "Une erreur est survenue lors de l'annulation du défi",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
47
actions/events/feedback.ts
Normal file
47
actions/events/feedback.ts
Normal file
@@ -0,0 +1,47 @@
|
|||||||
|
"use server";
|
||||||
|
|
||||||
|
import { revalidatePath } from "next/cache";
|
||||||
|
import { auth } from "@/lib/auth";
|
||||||
|
import { eventFeedbackService } from "@/services/events/event-feedback.service";
|
||||||
|
import { ValidationError, NotFoundError } from "@/services/errors";
|
||||||
|
|
||||||
|
export async function createFeedback(
|
||||||
|
eventId: string,
|
||||||
|
data: {
|
||||||
|
rating: number;
|
||||||
|
comment?: string | null;
|
||||||
|
}
|
||||||
|
) {
|
||||||
|
try {
|
||||||
|
const session = await auth();
|
||||||
|
|
||||||
|
if (!session?.user?.id) {
|
||||||
|
return { success: false, error: "Non authentifié" };
|
||||||
|
}
|
||||||
|
|
||||||
|
const feedback = await eventFeedbackService.validateAndCreateFeedback(
|
||||||
|
session.user.id,
|
||||||
|
eventId,
|
||||||
|
{ rating: data.rating, comment: data.comment }
|
||||||
|
);
|
||||||
|
|
||||||
|
revalidatePath(`/feedback/${eventId}`);
|
||||||
|
revalidatePath("/events");
|
||||||
|
|
||||||
|
return { success: true, data: feedback };
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error saving feedback:", error);
|
||||||
|
|
||||||
|
if (error instanceof ValidationError) {
|
||||||
|
return { success: false, error: error.message };
|
||||||
|
}
|
||||||
|
if (error instanceof NotFoundError) {
|
||||||
|
return { success: false, error: error.message };
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: "Erreur lors de l'enregistrement du feedback",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
77
actions/events/register.ts
Normal file
77
actions/events/register.ts
Normal file
@@ -0,0 +1,77 @@
|
|||||||
|
"use server";
|
||||||
|
|
||||||
|
import { revalidatePath } from "next/cache";
|
||||||
|
import { auth } from "@/lib/auth";
|
||||||
|
import { eventRegistrationService } from "@/services/events/event-registration.service";
|
||||||
|
import {
|
||||||
|
ValidationError,
|
||||||
|
NotFoundError,
|
||||||
|
ConflictError,
|
||||||
|
} from "@/services/errors";
|
||||||
|
|
||||||
|
export async function registerForEvent(eventId: string) {
|
||||||
|
try {
|
||||||
|
const session = await auth();
|
||||||
|
|
||||||
|
if (!session?.user?.id) {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: "Vous devez être connecté pour vous inscrire",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const registration = await eventRegistrationService.validateAndRegisterUser(
|
||||||
|
session.user.id,
|
||||||
|
eventId
|
||||||
|
);
|
||||||
|
|
||||||
|
revalidatePath("/events");
|
||||||
|
revalidatePath("/");
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
message: "Inscription réussie",
|
||||||
|
data: registration,
|
||||||
|
};
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Registration error:", error);
|
||||||
|
|
||||||
|
if (error instanceof ValidationError || error instanceof ConflictError) {
|
||||||
|
return { success: false, error: error.message };
|
||||||
|
}
|
||||||
|
if (error instanceof NotFoundError) {
|
||||||
|
return { success: false, error: error.message };
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: "Une erreur est survenue lors de l'inscription",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function unregisterFromEvent(eventId: string) {
|
||||||
|
try {
|
||||||
|
const session = await auth();
|
||||||
|
|
||||||
|
if (!session?.user?.id) {
|
||||||
|
return { success: false, error: "Vous devez être connecté" };
|
||||||
|
}
|
||||||
|
|
||||||
|
await eventRegistrationService.unregisterUserFromEvent(
|
||||||
|
session.user.id,
|
||||||
|
eventId
|
||||||
|
);
|
||||||
|
|
||||||
|
revalidatePath("/events");
|
||||||
|
revalidatePath("/");
|
||||||
|
|
||||||
|
return { success: true, message: "Inscription annulée" };
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Unregistration error:", error);
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: "Une erreur est survenue lors de l'annulation",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
48
actions/houses/create.ts
Normal file
48
actions/houses/create.ts
Normal file
@@ -0,0 +1,48 @@
|
|||||||
|
"use server";
|
||||||
|
|
||||||
|
import { revalidatePath } from "next/cache";
|
||||||
|
import { auth } from "@/lib/auth";
|
||||||
|
import { houseService } from "@/services/houses/house.service";
|
||||||
|
import {
|
||||||
|
ValidationError,
|
||||||
|
ConflictError,
|
||||||
|
} from "@/services/errors";
|
||||||
|
|
||||||
|
export async function createHouse(data: {
|
||||||
|
name: string;
|
||||||
|
description?: string | null;
|
||||||
|
}) {
|
||||||
|
try {
|
||||||
|
const session = await auth();
|
||||||
|
|
||||||
|
if (!session?.user?.id) {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: "Vous devez être connecté pour créer une maison",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const house = await houseService.createHouse({
|
||||||
|
name: data.name,
|
||||||
|
description: data.description,
|
||||||
|
creatorId: session.user.id,
|
||||||
|
});
|
||||||
|
|
||||||
|
revalidatePath("/houses");
|
||||||
|
revalidatePath("/profile");
|
||||||
|
|
||||||
|
return { success: true, message: "Maison créée avec succès", data: house };
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Create house error:", error);
|
||||||
|
|
||||||
|
if (error instanceof ValidationError || error instanceof ConflictError) {
|
||||||
|
return { success: false, error: error.message };
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: "Une erreur est survenue lors de la création de la maison",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
173
actions/houses/invitations.ts
Normal file
173
actions/houses/invitations.ts
Normal file
@@ -0,0 +1,173 @@
|
|||||||
|
"use server";
|
||||||
|
|
||||||
|
import { revalidatePath } from "next/cache";
|
||||||
|
import { auth } from "@/lib/auth";
|
||||||
|
import { houseService } from "@/services/houses/house.service";
|
||||||
|
import {
|
||||||
|
ValidationError,
|
||||||
|
ConflictError,
|
||||||
|
ForbiddenError,
|
||||||
|
NotFoundError,
|
||||||
|
} from "@/services/errors";
|
||||||
|
|
||||||
|
export async function inviteUser(houseId: string, inviteeId: string) {
|
||||||
|
try {
|
||||||
|
const session = await auth();
|
||||||
|
|
||||||
|
if (!session?.user?.id) {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: "Vous devez être connecté",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const invitation = await houseService.inviteUser({
|
||||||
|
houseId,
|
||||||
|
inviterId: session.user.id,
|
||||||
|
inviteeId,
|
||||||
|
});
|
||||||
|
|
||||||
|
revalidatePath("/houses");
|
||||||
|
revalidatePath(`/houses/${houseId}`);
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
message: "Invitation envoyée",
|
||||||
|
data: invitation,
|
||||||
|
};
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Invite user error:", error);
|
||||||
|
|
||||||
|
if (
|
||||||
|
error instanceof ValidationError ||
|
||||||
|
error instanceof ConflictError ||
|
||||||
|
error instanceof ForbiddenError
|
||||||
|
) {
|
||||||
|
return { success: false, error: error.message };
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: "Une erreur est survenue lors de l'envoi de l'invitation",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function acceptInvitation(invitationId: string) {
|
||||||
|
try {
|
||||||
|
const session = await auth();
|
||||||
|
|
||||||
|
if (!session?.user?.id) {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: "Vous devez être connecté",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const membership = await houseService.acceptInvitation(
|
||||||
|
invitationId,
|
||||||
|
session.user.id
|
||||||
|
);
|
||||||
|
|
||||||
|
revalidatePath("/houses");
|
||||||
|
revalidatePath("/profile");
|
||||||
|
revalidatePath("/invitations");
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
message: "Invitation acceptée",
|
||||||
|
data: membership,
|
||||||
|
};
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Accept invitation error:", error);
|
||||||
|
|
||||||
|
if (
|
||||||
|
error instanceof ValidationError ||
|
||||||
|
error instanceof ConflictError ||
|
||||||
|
error instanceof ForbiddenError ||
|
||||||
|
error instanceof NotFoundError
|
||||||
|
) {
|
||||||
|
return { success: false, error: error.message };
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: "Une erreur est survenue lors de l'acceptation de l'invitation",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function rejectInvitation(invitationId: string) {
|
||||||
|
try {
|
||||||
|
const session = await auth();
|
||||||
|
|
||||||
|
if (!session?.user?.id) {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: "Vous devez être connecté",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
await houseService.rejectInvitation(invitationId, session.user.id);
|
||||||
|
|
||||||
|
revalidatePath("/houses");
|
||||||
|
revalidatePath("/invitations");
|
||||||
|
|
||||||
|
return { success: true, message: "Invitation refusée" };
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Reject invitation error:", error);
|
||||||
|
|
||||||
|
if (
|
||||||
|
error instanceof ConflictError ||
|
||||||
|
error instanceof ForbiddenError ||
|
||||||
|
error instanceof NotFoundError
|
||||||
|
) {
|
||||||
|
return { success: false, error: error.message };
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: "Une erreur est survenue lors du refus de l'invitation",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function cancelInvitation(invitationId: string) {
|
||||||
|
try {
|
||||||
|
const session = await auth();
|
||||||
|
|
||||||
|
if (!session?.user?.id) {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: "Vous devez être connecté",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// Récupérer l'invitation pour obtenir le houseId avant de l'annuler
|
||||||
|
const invitation = await houseService.getInvitationById(invitationId);
|
||||||
|
|
||||||
|
await houseService.cancelInvitation(invitationId, session.user.id);
|
||||||
|
|
||||||
|
revalidatePath("/houses");
|
||||||
|
if (invitation?.houseId) {
|
||||||
|
revalidatePath(`/houses/${invitation.houseId}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
return { success: true, message: "Invitation annulée" };
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Cancel invitation error:", error);
|
||||||
|
|
||||||
|
if (
|
||||||
|
error instanceof ConflictError ||
|
||||||
|
error instanceof ForbiddenError ||
|
||||||
|
error instanceof NotFoundError
|
||||||
|
) {
|
||||||
|
return { success: false, error: error.message };
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: "Une erreur est survenue lors de l'annulation de l'invitation",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
163
actions/houses/requests.ts
Normal file
163
actions/houses/requests.ts
Normal file
@@ -0,0 +1,163 @@
|
|||||||
|
"use server";
|
||||||
|
|
||||||
|
import { revalidatePath } from "next/cache";
|
||||||
|
import { auth } from "@/lib/auth";
|
||||||
|
import { houseService } from "@/services/houses/house.service";
|
||||||
|
import {
|
||||||
|
ValidationError,
|
||||||
|
ConflictError,
|
||||||
|
ForbiddenError,
|
||||||
|
NotFoundError,
|
||||||
|
} from "@/services/errors";
|
||||||
|
|
||||||
|
export async function requestToJoin(houseId: string) {
|
||||||
|
try {
|
||||||
|
const session = await auth();
|
||||||
|
|
||||||
|
if (!session?.user?.id) {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: "Vous devez être connecté",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const request = await houseService.requestToJoin({
|
||||||
|
houseId,
|
||||||
|
requesterId: session.user.id,
|
||||||
|
});
|
||||||
|
|
||||||
|
revalidatePath("/houses");
|
||||||
|
revalidatePath(`/houses/${houseId}`);
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
message: "Demande envoyée",
|
||||||
|
data: request,
|
||||||
|
};
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Request to join error:", error);
|
||||||
|
|
||||||
|
if (
|
||||||
|
error instanceof ValidationError ||
|
||||||
|
error instanceof ConflictError
|
||||||
|
) {
|
||||||
|
return { success: false, error: error.message };
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: "Une erreur est survenue lors de l'envoi de la demande",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function acceptRequest(requestId: string) {
|
||||||
|
try {
|
||||||
|
const session = await auth();
|
||||||
|
|
||||||
|
if (!session?.user?.id) {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: "Vous devez être connecté",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const membership = await houseService.acceptRequest(
|
||||||
|
requestId,
|
||||||
|
session.user.id
|
||||||
|
);
|
||||||
|
|
||||||
|
revalidatePath("/houses");
|
||||||
|
revalidatePath("/profile");
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
message: "Demande acceptée",
|
||||||
|
data: membership,
|
||||||
|
};
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Accept request error:", error);
|
||||||
|
|
||||||
|
if (
|
||||||
|
error instanceof ConflictError ||
|
||||||
|
error instanceof ForbiddenError ||
|
||||||
|
error instanceof NotFoundError
|
||||||
|
) {
|
||||||
|
return { success: false, error: error.message };
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: "Une erreur est survenue lors de l'acceptation de la demande",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function rejectRequest(requestId: string) {
|
||||||
|
try {
|
||||||
|
const session = await auth();
|
||||||
|
|
||||||
|
if (!session?.user?.id) {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: "Vous devez être connecté",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
await houseService.rejectRequest(requestId, session.user.id);
|
||||||
|
|
||||||
|
revalidatePath("/houses");
|
||||||
|
|
||||||
|
return { success: true, message: "Demande refusée" };
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Reject request error:", error);
|
||||||
|
|
||||||
|
if (
|
||||||
|
error instanceof ConflictError ||
|
||||||
|
error instanceof ForbiddenError ||
|
||||||
|
error instanceof NotFoundError
|
||||||
|
) {
|
||||||
|
return { success: false, error: error.message };
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: "Une erreur est survenue lors du refus de la demande",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function cancelRequest(requestId: string) {
|
||||||
|
try {
|
||||||
|
const session = await auth();
|
||||||
|
|
||||||
|
if (!session?.user?.id) {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: "Vous devez être connecté",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
await houseService.cancelRequest(requestId, session.user.id);
|
||||||
|
|
||||||
|
revalidatePath("/houses");
|
||||||
|
|
||||||
|
return { success: true, message: "Demande annulée" };
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Cancel request error:", error);
|
||||||
|
|
||||||
|
if (
|
||||||
|
error instanceof ConflictError ||
|
||||||
|
error instanceof ForbiddenError ||
|
||||||
|
error instanceof NotFoundError
|
||||||
|
) {
|
||||||
|
return { success: false, error: error.message };
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: "Une erreur est survenue lors de l'annulation de la demande",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
149
actions/houses/update.ts
Normal file
149
actions/houses/update.ts
Normal file
@@ -0,0 +1,149 @@
|
|||||||
|
"use server";
|
||||||
|
|
||||||
|
import { revalidatePath } from "next/cache";
|
||||||
|
import { auth } from "@/lib/auth";
|
||||||
|
import { houseService } from "@/services/houses/house.service";
|
||||||
|
import {
|
||||||
|
ValidationError,
|
||||||
|
ConflictError,
|
||||||
|
ForbiddenError,
|
||||||
|
NotFoundError,
|
||||||
|
} from "@/services/errors";
|
||||||
|
|
||||||
|
export async function updateHouse(
|
||||||
|
houseId: string,
|
||||||
|
data: {
|
||||||
|
name?: string;
|
||||||
|
description?: string | null;
|
||||||
|
}
|
||||||
|
) {
|
||||||
|
try {
|
||||||
|
const session = await auth();
|
||||||
|
|
||||||
|
if (!session?.user?.id) {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: "Vous devez être connecté",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const house = await houseService.updateHouse(houseId, session.user.id, data);
|
||||||
|
|
||||||
|
revalidatePath("/houses");
|
||||||
|
revalidatePath(`/houses/${houseId}`);
|
||||||
|
|
||||||
|
return { success: true, message: "Maison mise à jour", data: house };
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Update house error:", error);
|
||||||
|
|
||||||
|
if (
|
||||||
|
error instanceof ValidationError ||
|
||||||
|
error instanceof ConflictError ||
|
||||||
|
error instanceof ForbiddenError
|
||||||
|
) {
|
||||||
|
return { success: false, error: error.message };
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: "Une erreur est survenue lors de la mise à jour de la maison",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function deleteHouse(houseId: string) {
|
||||||
|
try {
|
||||||
|
const session = await auth();
|
||||||
|
|
||||||
|
if (!session?.user?.id) {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: "Vous devez être connecté",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
await houseService.deleteHouse(houseId, session.user.id);
|
||||||
|
|
||||||
|
revalidatePath("/houses");
|
||||||
|
revalidatePath("/profile");
|
||||||
|
|
||||||
|
return { success: true, message: "Maison supprimée" };
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Delete house error:", error);
|
||||||
|
|
||||||
|
if (error instanceof ForbiddenError) {
|
||||||
|
return { success: false, error: error.message };
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: "Une erreur est survenue lors de la suppression de la maison",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function leaveHouse(houseId: string) {
|
||||||
|
try {
|
||||||
|
const session = await auth();
|
||||||
|
|
||||||
|
if (!session?.user?.id) {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: "Vous devez être connecté",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
await houseService.leaveHouse(houseId, session.user.id);
|
||||||
|
|
||||||
|
revalidatePath("/houses");
|
||||||
|
revalidatePath("/profile");
|
||||||
|
|
||||||
|
return { success: true, message: "Vous avez quitté la maison" };
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Leave house error:", error);
|
||||||
|
|
||||||
|
if (error instanceof ForbiddenError) {
|
||||||
|
return { success: false, error: error.message };
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: "Une erreur est survenue lors de la sortie de la maison",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function removeMember(houseId: string, memberId: string) {
|
||||||
|
try {
|
||||||
|
const session = await auth();
|
||||||
|
|
||||||
|
if (!session?.user?.id) {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: "Vous devez être connecté",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
await houseService.removeMember(houseId, memberId, session.user.id);
|
||||||
|
|
||||||
|
revalidatePath("/houses");
|
||||||
|
revalidatePath("/profile");
|
||||||
|
|
||||||
|
return { success: true, message: "Membre retiré de la maison" };
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Remove member error:", error);
|
||||||
|
|
||||||
|
if (
|
||||||
|
error instanceof ForbiddenError ||
|
||||||
|
error instanceof NotFoundError
|
||||||
|
) {
|
||||||
|
return { success: false, error: error.message };
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: "Une erreur est survenue lors du retrait du membre",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
45
actions/profile/update-password.ts
Normal file
45
actions/profile/update-password.ts
Normal file
@@ -0,0 +1,45 @@
|
|||||||
|
"use server";
|
||||||
|
|
||||||
|
import { revalidatePath } from "next/cache";
|
||||||
|
import { auth } from "@/lib/auth";
|
||||||
|
import { userService } from "@/services/users/user.service";
|
||||||
|
import { ValidationError, NotFoundError } from "@/services/errors";
|
||||||
|
|
||||||
|
export async function updatePassword(data: {
|
||||||
|
currentPassword: string;
|
||||||
|
newPassword: string;
|
||||||
|
confirmPassword: string;
|
||||||
|
}) {
|
||||||
|
try {
|
||||||
|
const session = await auth();
|
||||||
|
|
||||||
|
if (!session?.user) {
|
||||||
|
return { success: false, error: "Non authentifié" };
|
||||||
|
}
|
||||||
|
|
||||||
|
await userService.validateAndUpdatePassword(
|
||||||
|
session.user.id,
|
||||||
|
data.currentPassword,
|
||||||
|
data.newPassword,
|
||||||
|
data.confirmPassword
|
||||||
|
);
|
||||||
|
|
||||||
|
revalidatePath("/profile");
|
||||||
|
|
||||||
|
return { success: true, message: "Mot de passe modifié avec succès" };
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error updating password:", error);
|
||||||
|
|
||||||
|
if (error instanceof ValidationError) {
|
||||||
|
return { success: false, error: error.message };
|
||||||
|
}
|
||||||
|
if (error instanceof NotFoundError) {
|
||||||
|
return { success: false, error: error.message };
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: "Erreur lors de la modification du mot de passe",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
61
actions/profile/update-profile.ts
Normal file
61
actions/profile/update-profile.ts
Normal file
@@ -0,0 +1,61 @@
|
|||||||
|
"use server";
|
||||||
|
|
||||||
|
import { revalidatePath } from "next/cache";
|
||||||
|
import { auth } from "@/lib/auth";
|
||||||
|
import { userService } from "@/services/users/user.service";
|
||||||
|
import { CharacterClass } from "@/prisma/generated/prisma/client";
|
||||||
|
import { ValidationError, ConflictError } from "@/services/errors";
|
||||||
|
|
||||||
|
export async function updateProfile(data: {
|
||||||
|
username?: string;
|
||||||
|
avatar?: string | null;
|
||||||
|
bio?: string | null;
|
||||||
|
characterClass?: string | null;
|
||||||
|
}) {
|
||||||
|
try {
|
||||||
|
const session = await auth();
|
||||||
|
|
||||||
|
if (!session?.user) {
|
||||||
|
return { success: false, error: "Non authentifié" };
|
||||||
|
}
|
||||||
|
|
||||||
|
const updatedUser = await userService.validateAndUpdateUserProfile(
|
||||||
|
session.user.id,
|
||||||
|
{
|
||||||
|
username: data.username,
|
||||||
|
avatar: data.avatar,
|
||||||
|
bio: data.bio,
|
||||||
|
characterClass: data.characterClass
|
||||||
|
? (data.characterClass as CharacterClass)
|
||||||
|
: null,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: true,
|
||||||
|
email: true,
|
||||||
|
username: true,
|
||||||
|
avatar: true,
|
||||||
|
bio: true,
|
||||||
|
characterClass: true,
|
||||||
|
hp: true,
|
||||||
|
maxHp: true,
|
||||||
|
xp: true,
|
||||||
|
maxXp: true,
|
||||||
|
level: true,
|
||||||
|
score: true,
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
revalidatePath("/profile");
|
||||||
|
revalidatePath("/");
|
||||||
|
|
||||||
|
return { success: true, data: updatedUser };
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error updating profile:", error);
|
||||||
|
|
||||||
|
if (error instanceof ValidationError || error instanceof ConflictError) {
|
||||||
|
return { success: false, error: error.message };
|
||||||
|
}
|
||||||
|
|
||||||
|
return { success: false, error: "Erreur lors de la mise à jour du profil" };
|
||||||
|
}
|
||||||
|
}
|
||||||
26
app/admin/challenges/page.tsx
Normal file
26
app/admin/challenges/page.tsx
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
import ChallengeManagement from "@/components/admin/ChallengeManagement";
|
||||||
|
import { Card } from "@/components/ui";
|
||||||
|
import { challengeService } from "@/services/challenges/challenge.service";
|
||||||
|
|
||||||
|
export const dynamic = "force-dynamic";
|
||||||
|
|
||||||
|
export default async function AdminChallengesPage() {
|
||||||
|
const challenges = await challengeService.getAllChallenges();
|
||||||
|
|
||||||
|
// Sérialiser les dates pour le client
|
||||||
|
const serializedChallenges = challenges.map((challenge) => ({
|
||||||
|
...challenge,
|
||||||
|
createdAt: challenge.createdAt.toISOString(),
|
||||||
|
acceptedAt: challenge.acceptedAt?.toISOString() ?? null,
|
||||||
|
completedAt: challenge.completedAt?.toISOString() ?? null,
|
||||||
|
}));
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Card variant="dark" className="p-6">
|
||||||
|
<h2 className="text-2xl font-gaming font-bold mb-6 text-pixel-gold">
|
||||||
|
Gestion des Défis
|
||||||
|
</h2>
|
||||||
|
<ChallengeManagement initialChallenges={serializedChallenges} />
|
||||||
|
</Card>
|
||||||
|
);
|
||||||
|
}
|
||||||
34
app/admin/events/page.tsx
Normal file
34
app/admin/events/page.tsx
Normal file
@@ -0,0 +1,34 @@
|
|||||||
|
import EventManagement from "@/components/admin/EventManagement";
|
||||||
|
import { Card } from "@/components/ui";
|
||||||
|
import { eventService } from "@/services/events/event.service";
|
||||||
|
|
||||||
|
export const dynamic = "force-dynamic";
|
||||||
|
|
||||||
|
export default async function AdminEventsPage() {
|
||||||
|
const events = await eventService.getEventsWithStatus();
|
||||||
|
|
||||||
|
// Transformer les données pour la sérialisation
|
||||||
|
const serializedEvents = events.map((event) => ({
|
||||||
|
id: event.id,
|
||||||
|
date: event.date.toISOString(),
|
||||||
|
name: event.name,
|
||||||
|
description: event.description,
|
||||||
|
type: event.type,
|
||||||
|
status: event.status,
|
||||||
|
room: event.room,
|
||||||
|
time: event.time,
|
||||||
|
maxPlaces: event.maxPlaces,
|
||||||
|
createdAt: event.createdAt.toISOString(),
|
||||||
|
updatedAt: event.updatedAt.toISOString(),
|
||||||
|
registrationsCount: event.registrationsCount,
|
||||||
|
}));
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Card variant="dark" className="p-6">
|
||||||
|
<h2 className="text-2xl font-gaming font-bold mb-6 text-pixel-gold">
|
||||||
|
Gestion des Événements
|
||||||
|
</h2>
|
||||||
|
<EventManagement initialEvents={serializedEvents} />
|
||||||
|
</Card>
|
||||||
|
);
|
||||||
|
}
|
||||||
77
app/admin/feedbacks/page.tsx
Normal file
77
app/admin/feedbacks/page.tsx
Normal file
@@ -0,0 +1,77 @@
|
|||||||
|
import FeedbackManagement from "@/components/admin/FeedbackManagement";
|
||||||
|
import { Card } from "@/components/ui";
|
||||||
|
import { eventFeedbackService } from "@/services/events/event-feedback.service";
|
||||||
|
|
||||||
|
export const dynamic = "force-dynamic";
|
||||||
|
|
||||||
|
export default async function AdminFeedbacksPage() {
|
||||||
|
const [feedbacksRaw, statistics] = await Promise.all([
|
||||||
|
eventFeedbackService.getAllFeedbacks(),
|
||||||
|
eventFeedbackService.getFeedbackStatistics(),
|
||||||
|
]);
|
||||||
|
|
||||||
|
// Type assertion car getAllFeedbacks inclut event et user par défaut
|
||||||
|
const feedbacks = feedbacksRaw as unknown as Array<{
|
||||||
|
id: string;
|
||||||
|
rating: number;
|
||||||
|
comment: string | null;
|
||||||
|
isRead: boolean;
|
||||||
|
createdAt: Date;
|
||||||
|
event: {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
date: Date;
|
||||||
|
type: string;
|
||||||
|
};
|
||||||
|
user: {
|
||||||
|
id: string;
|
||||||
|
username: string;
|
||||||
|
email: string;
|
||||||
|
avatar: string | null;
|
||||||
|
score: number;
|
||||||
|
};
|
||||||
|
}>;
|
||||||
|
|
||||||
|
// Sérialiser les dates pour le client
|
||||||
|
const serializedFeedbacks = feedbacks.map((feedback) => ({
|
||||||
|
id: feedback.id,
|
||||||
|
rating: feedback.rating,
|
||||||
|
comment: feedback.comment,
|
||||||
|
isRead: feedback.isRead,
|
||||||
|
createdAt: feedback.createdAt.toISOString(),
|
||||||
|
event: {
|
||||||
|
id: feedback.event.id,
|
||||||
|
name: feedback.event.name,
|
||||||
|
date: feedback.event.date.toISOString(),
|
||||||
|
type: feedback.event.type,
|
||||||
|
},
|
||||||
|
user: {
|
||||||
|
id: feedback.user.id,
|
||||||
|
username: feedback.user.username,
|
||||||
|
email: feedback.user.email,
|
||||||
|
avatar: feedback.user.avatar,
|
||||||
|
score: feedback.user.score,
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
|
||||||
|
const serializedStatistics = statistics.map((stat) => ({
|
||||||
|
eventId: stat.eventId,
|
||||||
|
eventName: stat.eventName,
|
||||||
|
eventDate: stat.eventDate?.toISOString() ?? null,
|
||||||
|
eventType: stat.eventType,
|
||||||
|
averageRating: stat.averageRating,
|
||||||
|
feedbackCount: stat.feedbackCount,
|
||||||
|
}));
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Card variant="dark" className="p-6">
|
||||||
|
<h2 className="text-2xl font-gaming font-bold mb-6 text-pixel-gold">
|
||||||
|
Gestion des Feedbacks
|
||||||
|
</h2>
|
||||||
|
<FeedbackManagement
|
||||||
|
initialFeedbacks={serializedFeedbacks}
|
||||||
|
initialStatistics={serializedStatistics}
|
||||||
|
/>
|
||||||
|
</Card>
|
||||||
|
);
|
||||||
|
}
|
||||||
90
app/admin/houses/page.tsx
Normal file
90
app/admin/houses/page.tsx
Normal file
@@ -0,0 +1,90 @@
|
|||||||
|
import HouseManagement from "@/components/admin/HouseManagement";
|
||||||
|
import { Card } from "@/components/ui";
|
||||||
|
import { houseService } from "@/services/houses/house.service";
|
||||||
|
import { Prisma } from "@/prisma/generated/prisma/client";
|
||||||
|
|
||||||
|
export const dynamic = "force-dynamic";
|
||||||
|
|
||||||
|
export default async function AdminHousesPage() {
|
||||||
|
type HouseWithIncludes = Prisma.HouseGetPayload<{
|
||||||
|
include: {
|
||||||
|
creator: {
|
||||||
|
select: {
|
||||||
|
id: true;
|
||||||
|
username: true;
|
||||||
|
avatar: true;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
memberships: {
|
||||||
|
include: {
|
||||||
|
user: {
|
||||||
|
select: {
|
||||||
|
id: true;
|
||||||
|
username: true;
|
||||||
|
avatar: true;
|
||||||
|
score: true;
|
||||||
|
level: true;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
};
|
||||||
|
};
|
||||||
|
};
|
||||||
|
}>;
|
||||||
|
|
||||||
|
const houses = (await houseService.getAllHouses({
|
||||||
|
include: {
|
||||||
|
creator: {
|
||||||
|
select: {
|
||||||
|
id: true,
|
||||||
|
username: true,
|
||||||
|
avatar: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
memberships: {
|
||||||
|
include: {
|
||||||
|
user: {
|
||||||
|
select: {
|
||||||
|
id: true,
|
||||||
|
username: true,
|
||||||
|
avatar: true,
|
||||||
|
score: true,
|
||||||
|
level: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
orderBy: [{ role: "asc" }, { joinedAt: "asc" }],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
orderBy: {
|
||||||
|
createdAt: "desc",
|
||||||
|
},
|
||||||
|
})) as unknown as HouseWithIncludes[];
|
||||||
|
|
||||||
|
// Transformer les données pour la sérialisation
|
||||||
|
const serializedHouses = houses.map((house) => ({
|
||||||
|
id: house.id,
|
||||||
|
name: house.name,
|
||||||
|
description: house.description,
|
||||||
|
creatorId: house.creatorId,
|
||||||
|
creator: house.creator,
|
||||||
|
createdAt: house.createdAt.toISOString(),
|
||||||
|
updatedAt: house.updatedAt.toISOString(),
|
||||||
|
membersCount: house.memberships?.length || 0,
|
||||||
|
memberships:
|
||||||
|
house.memberships?.map((membership) => ({
|
||||||
|
id: membership.id,
|
||||||
|
role: membership.role,
|
||||||
|
joinedAt: membership.joinedAt.toISOString(),
|
||||||
|
user: membership.user,
|
||||||
|
})) || [],
|
||||||
|
}));
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Card variant="dark" className="p-6">
|
||||||
|
<h2 className="text-2xl font-gaming font-bold mb-6 text-pixel-gold">
|
||||||
|
Gestion des Maisons
|
||||||
|
</h2>
|
||||||
|
<HouseManagement initialHouses={serializedHouses} />
|
||||||
|
</Card>
|
||||||
|
);
|
||||||
|
}
|
||||||
52
app/admin/layout.tsx
Normal file
52
app/admin/layout.tsx
Normal file
@@ -0,0 +1,52 @@
|
|||||||
|
import { redirect } from "next/navigation";
|
||||||
|
import { auth } from "@/lib/auth";
|
||||||
|
import { Role } from "@/prisma/generated/prisma/client";
|
||||||
|
import NavigationWrapper from "@/components/navigation/NavigationWrapper";
|
||||||
|
import AdminNavigation from "@/components/admin/AdminNavigation";
|
||||||
|
import { SectionTitle } from "@/components/ui";
|
||||||
|
|
||||||
|
export const dynamic = "force-dynamic";
|
||||||
|
|
||||||
|
export default async function AdminLayout({
|
||||||
|
children,
|
||||||
|
}: {
|
||||||
|
children: React.ReactNode;
|
||||||
|
}) {
|
||||||
|
const session = await auth();
|
||||||
|
|
||||||
|
if (!session?.user) {
|
||||||
|
redirect("/login");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (session.user.role !== Role.ADMIN) {
|
||||||
|
redirect("/");
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<main className="min-h-screen bg-black relative">
|
||||||
|
{/* Background Image */}
|
||||||
|
<div
|
||||||
|
className="fixed inset-0 bg-cover bg-center bg-no-repeat"
|
||||||
|
style={{
|
||||||
|
backgroundImage: `url('/got-light.jpg')`,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{/* Dark overlay for readability */}
|
||||||
|
<div className="absolute inset-0 bg-gradient-to-b from-black/70 via-black/60 to-black/80"></div>
|
||||||
|
</div>
|
||||||
|
<NavigationWrapper />
|
||||||
|
<section className="relative w-full min-h-screen flex flex-col items-center overflow-hidden pt-24 pb-16">
|
||||||
|
<div className="relative z-10 w-full max-w-6xl mx-auto px-8 py-16">
|
||||||
|
<SectionTitle variant="gradient" size="md" className="mb-16 text-center">
|
||||||
|
ADMIN
|
||||||
|
</SectionTitle>
|
||||||
|
|
||||||
|
<AdminNavigation />
|
||||||
|
|
||||||
|
{children}
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
</main>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
@@ -1,328 +1,7 @@
|
|||||||
"use client";
|
import { redirect } from "next/navigation";
|
||||||
|
|
||||||
import { useEffect, useState } from "react";
|
export const dynamic = "force-dynamic";
|
||||||
import { useSession } from "next-auth/react";
|
|
||||||
import { useRouter } from "next/navigation";
|
|
||||||
import Navigation from "@/components/Navigation";
|
|
||||||
import ImageSelector from "@/components/ImageSelector";
|
|
||||||
import UserManagement from "@/components/UserManagement";
|
|
||||||
import EventManagement from "@/components/EventManagement";
|
|
||||||
|
|
||||||
interface SitePreferences {
|
export default async function AdminPage() {
|
||||||
id: string;
|
redirect("/admin/preferences");
|
||||||
homeBackground: string | null;
|
|
||||||
eventsBackground: string | null;
|
|
||||||
leaderboardBackground: string | null;
|
|
||||||
}
|
|
||||||
|
|
||||||
type AdminSection = "preferences" | "users" | "events";
|
|
||||||
|
|
||||||
export default function AdminPage() {
|
|
||||||
const { data: session, status } = useSession();
|
|
||||||
const router = useRouter();
|
|
||||||
const [activeSection, setActiveSection] =
|
|
||||||
useState<AdminSection>("preferences");
|
|
||||||
const [preferences, setPreferences] = useState<SitePreferences | null>(null);
|
|
||||||
const [loading, setLoading] = useState(true);
|
|
||||||
const [isEditing, setIsEditing] = useState(false);
|
|
||||||
const [formData, setFormData] = useState({
|
|
||||||
homeBackground: "",
|
|
||||||
eventsBackground: "",
|
|
||||||
leaderboardBackground: "",
|
|
||||||
});
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (status === "unauthenticated") {
|
|
||||||
router.push("/login");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (status === "authenticated" && session?.user?.role !== "ADMIN") {
|
|
||||||
router.push("/");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (status === "authenticated" && session?.user?.role === "ADMIN") {
|
|
||||||
fetchPreferences();
|
|
||||||
}
|
|
||||||
}, [status, session, router]);
|
|
||||||
|
|
||||||
const fetchPreferences = async () => {
|
|
||||||
try {
|
|
||||||
const response = await fetch("/api/admin/preferences");
|
|
||||||
if (response.ok) {
|
|
||||||
const data = await response.json();
|
|
||||||
setPreferences(data);
|
|
||||||
setFormData({
|
|
||||||
homeBackground: data.homeBackground || "",
|
|
||||||
eventsBackground: data.eventsBackground || "",
|
|
||||||
leaderboardBackground: data.leaderboardBackground || "",
|
|
||||||
});
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
console.error("Error fetching preferences:", error);
|
|
||||||
} finally {
|
|
||||||
setLoading(false);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleEdit = () => {
|
|
||||||
setIsEditing(true);
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleSave = async () => {
|
|
||||||
try {
|
|
||||||
const response = await fetch("/api/admin/preferences", {
|
|
||||||
method: "PUT",
|
|
||||||
headers: {
|
|
||||||
"Content-Type": "application/json",
|
|
||||||
},
|
|
||||||
body: JSON.stringify(formData),
|
|
||||||
});
|
|
||||||
|
|
||||||
if (response.ok) {
|
|
||||||
await fetchPreferences();
|
|
||||||
setIsEditing(false);
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
console.error("Error updating preferences:", error);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleCancel = () => {
|
|
||||||
setIsEditing(false);
|
|
||||||
if (preferences) {
|
|
||||||
setFormData({
|
|
||||||
homeBackground: preferences.homeBackground || "",
|
|
||||||
eventsBackground: preferences.eventsBackground || "",
|
|
||||||
leaderboardBackground: preferences.leaderboardBackground || "",
|
|
||||||
});
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
if (status === "loading" || loading) {
|
|
||||||
return (
|
|
||||||
<main className="min-h-screen bg-black relative">
|
|
||||||
<Navigation />
|
|
||||||
<div className="flex items-center justify-center min-h-screen text-pixel-gold">
|
|
||||||
Chargement...
|
|
||||||
</div>
|
|
||||||
</main>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<main className="min-h-screen bg-black relative">
|
|
||||||
<Navigation />
|
|
||||||
<section className="relative w-full min-h-screen flex flex-col items-center overflow-hidden pt-24 pb-16">
|
|
||||||
<div className="relative z-10 w-full max-w-6xl mx-auto px-8 py-16">
|
|
||||||
<h1 className="text-4xl font-gaming font-black mb-8 text-center">
|
|
||||||
<span className="bg-gradient-to-r from-pixel-gold via-orange-400 to-pixel-gold bg-clip-text text-transparent">
|
|
||||||
ADMIN
|
|
||||||
</span>
|
|
||||||
</h1>
|
|
||||||
|
|
||||||
{/* Navigation Tabs */}
|
|
||||||
<div className="flex gap-4 mb-8 justify-center">
|
|
||||||
<button
|
|
||||||
onClick={() => setActiveSection("preferences")}
|
|
||||||
className={`px-6 py-3 border uppercase text-xs tracking-widest rounded transition ${
|
|
||||||
activeSection === "preferences"
|
|
||||||
? "border-pixel-gold bg-pixel-gold/10 text-pixel-gold"
|
|
||||||
: "border-pixel-gold/30 bg-black/60 text-gray-400 hover:border-pixel-gold/50"
|
|
||||||
}`}
|
|
||||||
>
|
|
||||||
Préférences UI
|
|
||||||
</button>
|
|
||||||
<button
|
|
||||||
onClick={() => setActiveSection("users")}
|
|
||||||
className={`px-6 py-3 border uppercase text-xs tracking-widest rounded transition ${
|
|
||||||
activeSection === "users"
|
|
||||||
? "border-pixel-gold bg-pixel-gold/10 text-pixel-gold"
|
|
||||||
: "border-pixel-gold/30 bg-black/60 text-gray-400 hover:border-pixel-gold/50"
|
|
||||||
}`}
|
|
||||||
>
|
|
||||||
Utilisateurs
|
|
||||||
</button>
|
|
||||||
<button
|
|
||||||
onClick={() => setActiveSection("events")}
|
|
||||||
className={`px-6 py-3 border uppercase text-xs tracking-widest rounded transition ${
|
|
||||||
activeSection === "events"
|
|
||||||
? "border-pixel-gold bg-pixel-gold/10 text-pixel-gold"
|
|
||||||
: "border-pixel-gold/30 bg-black/60 text-gray-400 hover:border-pixel-gold/50"
|
|
||||||
}`}
|
|
||||||
>
|
|
||||||
Événements
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{activeSection === "preferences" && (
|
|
||||||
<div className="bg-black/80 border border-pixel-gold/30 rounded-lg p-6 backdrop-blur-sm">
|
|
||||||
<h2 className="text-2xl font-gaming font-bold mb-6 text-pixel-gold">
|
|
||||||
Préférences UI Globales
|
|
||||||
</h2>
|
|
||||||
<div className="space-y-4">
|
|
||||||
<div className="bg-black/60 border border-pixel-gold/20 rounded p-4">
|
|
||||||
<div className="flex justify-between items-start mb-4">
|
|
||||||
<div>
|
|
||||||
<h3 className="text-pixel-gold font-bold text-lg">
|
|
||||||
Images de fond du site
|
|
||||||
</h3>
|
|
||||||
<p className="text-gray-400 text-sm">
|
|
||||||
Ces préférences s'appliquent à tous les utilisateurs
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
{!isEditing && (
|
|
||||||
<button
|
|
||||||
onClick={handleEdit}
|
|
||||||
className="px-4 py-2 border border-pixel-gold/50 bg-black/60 text-white uppercase text-xs tracking-widest rounded hover:bg-pixel-gold/10 transition"
|
|
||||||
>
|
|
||||||
Modifier
|
|
||||||
</button>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{isEditing ? (
|
|
||||||
<div className="space-y-6">
|
|
||||||
<ImageSelector
|
|
||||||
value={formData.homeBackground}
|
|
||||||
onChange={(url) =>
|
|
||||||
setFormData({
|
|
||||||
...formData,
|
|
||||||
homeBackground: url,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
label="Background Home"
|
|
||||||
/>
|
|
||||||
<ImageSelector
|
|
||||||
value={formData.eventsBackground}
|
|
||||||
onChange={(url) =>
|
|
||||||
setFormData({
|
|
||||||
...formData,
|
|
||||||
eventsBackground: url,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
label="Background Events"
|
|
||||||
/>
|
|
||||||
<ImageSelector
|
|
||||||
value={formData.leaderboardBackground}
|
|
||||||
onChange={(url) =>
|
|
||||||
setFormData({
|
|
||||||
...formData,
|
|
||||||
leaderboardBackground: url,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
label="Background Leaderboard"
|
|
||||||
/>
|
|
||||||
<div className="flex gap-2 pt-4">
|
|
||||||
<button
|
|
||||||
onClick={handleSave}
|
|
||||||
className="px-4 py-2 border border-green-500/50 bg-green-900/20 text-green-400 uppercase text-xs tracking-widest rounded hover:bg-green-900/30 transition"
|
|
||||||
>
|
|
||||||
Enregistrer
|
|
||||||
</button>
|
|
||||||
<button
|
|
||||||
onClick={handleCancel}
|
|
||||||
className="px-4 py-2 border border-gray-600/50 bg-gray-900/20 text-gray-400 uppercase text-xs tracking-widest rounded hover:bg-gray-900/30 transition"
|
|
||||||
>
|
|
||||||
Annuler
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
<div className="space-y-4">
|
|
||||||
<div className="flex items-center gap-4">
|
|
||||||
<span className="text-pixel-gold font-bold min-w-[120px]">
|
|
||||||
Home:
|
|
||||||
</span>
|
|
||||||
{preferences?.homeBackground ? (
|
|
||||||
<div className="flex items-center gap-3">
|
|
||||||
<img
|
|
||||||
src={preferences.homeBackground}
|
|
||||||
alt="Home background"
|
|
||||||
className="w-20 h-12 object-cover rounded border border-pixel-gold/30"
|
|
||||||
onError={(e) => {
|
|
||||||
e.currentTarget.src = "/got-2.jpg";
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
<span className="text-xs text-gray-400 truncate max-w-xs">
|
|
||||||
{preferences.homeBackground}
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
<span className="text-gray-400">Par défaut</span>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
<div className="flex items-center gap-4">
|
|
||||||
<span className="text-pixel-gold font-bold min-w-[120px]">
|
|
||||||
Events:
|
|
||||||
</span>
|
|
||||||
{preferences?.eventsBackground ? (
|
|
||||||
<div className="flex items-center gap-3">
|
|
||||||
<img
|
|
||||||
src={preferences.eventsBackground}
|
|
||||||
alt="Events background"
|
|
||||||
className="w-20 h-12 object-cover rounded border border-pixel-gold/30"
|
|
||||||
onError={(e) => {
|
|
||||||
e.currentTarget.src = "/got-2.jpg";
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
<span className="text-xs text-gray-400 truncate max-w-xs">
|
|
||||||
{preferences.eventsBackground}
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
<span className="text-gray-400">Par défaut</span>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
<div className="flex items-center gap-4">
|
|
||||||
<span className="text-pixel-gold font-bold min-w-[120px]">
|
|
||||||
Leaderboard:
|
|
||||||
</span>
|
|
||||||
{preferences?.leaderboardBackground ? (
|
|
||||||
<div className="flex items-center gap-3">
|
|
||||||
<img
|
|
||||||
src={preferences.leaderboardBackground}
|
|
||||||
alt="Leaderboard background"
|
|
||||||
className="w-20 h-12 object-cover rounded border border-pixel-gold/30"
|
|
||||||
onError={(e) => {
|
|
||||||
e.currentTarget.src = "/got-2.jpg";
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
<span className="text-xs text-gray-400 truncate max-w-xs">
|
|
||||||
{preferences.leaderboardBackground}
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
<span className="text-gray-400">Par défaut</span>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{activeSection === "users" && (
|
|
||||||
<div className="bg-black/80 border border-pixel-gold/30 rounded-lg p-6 backdrop-blur-sm">
|
|
||||||
<h2 className="text-2xl font-gaming font-bold mb-6 text-pixel-gold">
|
|
||||||
Gestion des Utilisateurs
|
|
||||||
</h2>
|
|
||||||
<UserManagement />
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{activeSection === "events" && (
|
|
||||||
<div className="bg-black/80 border border-pixel-gold/30 rounded-lg p-6 backdrop-blur-sm">
|
|
||||||
<h2 className="text-2xl font-gaming font-bold mb-6 text-pixel-gold">
|
|
||||||
Gestion des Événements
|
|
||||||
</h2>
|
|
||||||
<EventManagement />
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</section>
|
|
||||||
</main>
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|||||||
30
app/admin/preferences/page.tsx
Normal file
30
app/admin/preferences/page.tsx
Normal file
@@ -0,0 +1,30 @@
|
|||||||
|
import { sitePreferencesService } from "@/services/preferences/site-preferences.service";
|
||||||
|
import BackgroundPreferences from "@/components/admin/BackgroundPreferences";
|
||||||
|
import EventPointsPreferences from "@/components/admin/EventPointsPreferences";
|
||||||
|
import EventFeedbackPointsPreferences from "@/components/admin/EventFeedbackPointsPreferences";
|
||||||
|
import HousePointsPreferences from "@/components/admin/HousePointsPreferences";
|
||||||
|
import { Card } from "@/components/ui";
|
||||||
|
|
||||||
|
export const dynamic = "force-dynamic";
|
||||||
|
|
||||||
|
export default async function AdminPreferencesPage() {
|
||||||
|
const sitePreferences =
|
||||||
|
await sitePreferencesService.getOrCreateSitePreferences();
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Card variant="dark" className="p-4 sm:p-6">
|
||||||
|
<div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 mb-6">
|
||||||
|
<h2 className="text-xl sm:text-2xl font-gaming font-bold text-pixel-gold break-words">
|
||||||
|
Préférences UI Globales
|
||||||
|
</h2>
|
||||||
|
</div>
|
||||||
|
<div className="space-y-4">
|
||||||
|
<BackgroundPreferences initialPreferences={sitePreferences} />
|
||||||
|
<EventPointsPreferences initialPreferences={sitePreferences} />
|
||||||
|
<EventFeedbackPointsPreferences initialPreferences={sitePreferences} />
|
||||||
|
<HousePointsPreferences initialPreferences={sitePreferences} />
|
||||||
|
</div>
|
||||||
|
</Card>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
42
app/admin/users/page.tsx
Normal file
42
app/admin/users/page.tsx
Normal file
@@ -0,0 +1,42 @@
|
|||||||
|
import UserManagement from "@/components/admin/UserManagement";
|
||||||
|
import { Card } from "@/components/ui";
|
||||||
|
import { userService } from "@/services/users/user.service";
|
||||||
|
|
||||||
|
export const dynamic = "force-dynamic";
|
||||||
|
|
||||||
|
export default async function AdminUsersPage() {
|
||||||
|
const users = await userService.getAllUsers({
|
||||||
|
orderBy: {
|
||||||
|
score: "desc",
|
||||||
|
},
|
||||||
|
select: {
|
||||||
|
id: true,
|
||||||
|
username: true,
|
||||||
|
email: true,
|
||||||
|
role: true,
|
||||||
|
score: true,
|
||||||
|
level: true,
|
||||||
|
hp: true,
|
||||||
|
maxHp: true,
|
||||||
|
xp: true,
|
||||||
|
maxXp: true,
|
||||||
|
avatar: true,
|
||||||
|
createdAt: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
// Sérialiser les dates pour le client
|
||||||
|
const serializedUsers = users.map((user) => ({
|
||||||
|
...user,
|
||||||
|
createdAt: user.createdAt.toISOString(),
|
||||||
|
}));
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Card variant="dark" className="p-6">
|
||||||
|
<h2 className="text-2xl font-gaming font-bold mb-6 text-pixel-gold">
|
||||||
|
Gestion des Utilisateurs
|
||||||
|
</h2>
|
||||||
|
<UserManagement initialUsers={serializedUsers} />
|
||||||
|
</Card>
|
||||||
|
);
|
||||||
|
}
|
||||||
70
app/api/admin/avatars/upload/route.ts
Normal file
70
app/api/admin/avatars/upload/route.ts
Normal file
@@ -0,0 +1,70 @@
|
|||||||
|
import { NextResponse } from "next/server";
|
||||||
|
import { auth } from "@/lib/auth";
|
||||||
|
import { Role } from "@/prisma/generated/prisma/client";
|
||||||
|
import { writeFile, mkdir } from "fs/promises";
|
||||||
|
import { join } from "path";
|
||||||
|
import { existsSync } from "fs";
|
||||||
|
|
||||||
|
export async function POST(request: Request) {
|
||||||
|
try {
|
||||||
|
const session = await auth();
|
||||||
|
|
||||||
|
if (!session?.user || session.user.role !== Role.ADMIN) {
|
||||||
|
return NextResponse.json({ error: "Accès refusé" }, { status: 403 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const formData = await request.formData();
|
||||||
|
const file = formData.get("file") as File;
|
||||||
|
|
||||||
|
if (!file) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: "Aucun fichier fourni" },
|
||||||
|
{ status: 400 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Vérifier le type de fichier
|
||||||
|
if (!file.type.startsWith("image/")) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: "Le fichier doit être une image" },
|
||||||
|
{ status: 400 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Limiter la taille (par exemple 5MB)
|
||||||
|
const maxSize = 5 * 1024 * 1024; // 5MB
|
||||||
|
if (file.size > maxSize) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: "L'image est trop grande (max 5MB)" },
|
||||||
|
{ status: 400 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Créer le dossier uploads/avatars s'il n'existe pas
|
||||||
|
const uploadsDir = join(process.cwd(), "public", "uploads");
|
||||||
|
const avatarsDir = join(uploadsDir, "avatars");
|
||||||
|
if (!existsSync(avatarsDir)) {
|
||||||
|
await mkdir(avatarsDir, { recursive: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
// Générer un nom de fichier unique
|
||||||
|
const timestamp = Date.now();
|
||||||
|
const filename = `avatar-admin-${timestamp}-${file.name}`;
|
||||||
|
const filepath = join(avatarsDir, filename);
|
||||||
|
|
||||||
|
// Convertir le fichier en buffer et l'écrire
|
||||||
|
const bytes = await file.arrayBuffer();
|
||||||
|
const buffer = Buffer.from(bytes);
|
||||||
|
await writeFile(filepath, buffer);
|
||||||
|
|
||||||
|
// Retourner l'URL de l'image via l'API
|
||||||
|
const imageUrl = `/api/avatars/${filename}`;
|
||||||
|
return NextResponse.json({ url: imageUrl });
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error uploading avatar:", error);
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: "Erreur lors de l'upload de l'avatar" },
|
||||||
|
{ status: 500 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
25
app/api/admin/challenges/route.ts
Normal file
25
app/api/admin/challenges/route.ts
Normal file
@@ -0,0 +1,25 @@
|
|||||||
|
import { NextResponse } from "next/server";
|
||||||
|
import { auth } from "@/lib/auth";
|
||||||
|
import { challengeService } from "@/services/challenges/challenge.service";
|
||||||
|
import { Role } from "@/prisma/generated/prisma/client";
|
||||||
|
|
||||||
|
export async function GET() {
|
||||||
|
try {
|
||||||
|
const session = await auth();
|
||||||
|
|
||||||
|
if (!session?.user || session.user.role !== Role.ADMIN) {
|
||||||
|
return NextResponse.json({ error: "Accès refusé" }, { status: 403 });
|
||||||
|
}
|
||||||
|
|
||||||
|
// Récupérer tous les défis pour l'admin (PENDING, ACCEPTED, CANCELLED, COMPLETED, REJECTED)
|
||||||
|
const challenges = await challengeService.getAllChallenges();
|
||||||
|
|
||||||
|
return NextResponse.json(challenges);
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error fetching challenges:", error);
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: "Erreur lors de la récupération des défis" },
|
||||||
|
{ status: 500 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
31
app/api/admin/events/[id]/registrations/route.ts
Normal file
31
app/api/admin/events/[id]/registrations/route.ts
Normal file
@@ -0,0 +1,31 @@
|
|||||||
|
import { NextResponse } from "next/server";
|
||||||
|
import { auth } from "@/lib/auth";
|
||||||
|
import { eventRegistrationService } from "@/services/events/event-registration.service";
|
||||||
|
import { Role } from "@/prisma/generated/prisma/client";
|
||||||
|
|
||||||
|
export async function GET(
|
||||||
|
request: Request,
|
||||||
|
{ params }: { params: Promise<{ id: string }> }
|
||||||
|
) {
|
||||||
|
try {
|
||||||
|
const session = await auth();
|
||||||
|
|
||||||
|
if (!session?.user || session.user.role !== Role.ADMIN) {
|
||||||
|
return NextResponse.json({ error: "Accès refusé" }, { status: 403 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const { id: eventId } = await params;
|
||||||
|
const registrations = await eventRegistrationService.getEventRegistrations(
|
||||||
|
eventId
|
||||||
|
);
|
||||||
|
|
||||||
|
return NextResponse.json(registrations);
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error fetching event registrations:", error);
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: "Erreur lors de la récupération des inscrits" },
|
||||||
|
{ status: 500 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@@ -1,116 +0,0 @@
|
|||||||
import { NextResponse } from "next/server";
|
|
||||||
import { auth } from "@/lib/auth";
|
|
||||||
import { prisma } from "@/lib/prisma";
|
|
||||||
import { Role, EventType, EventStatus } from "@/prisma/generated/prisma/client";
|
|
||||||
|
|
||||||
export async function PUT(
|
|
||||||
request: Request,
|
|
||||||
{ params }: { params: Promise<{ id: string }> }
|
|
||||||
) {
|
|
||||||
try {
|
|
||||||
const session = await auth();
|
|
||||||
|
|
||||||
if (!session?.user || session.user.role !== Role.ADMIN) {
|
|
||||||
return NextResponse.json({ error: "Accès refusé" }, { status: 403 });
|
|
||||||
}
|
|
||||||
|
|
||||||
const { id } = await params;
|
|
||||||
const body = await request.json();
|
|
||||||
const { date, name, description, type, status } = body;
|
|
||||||
|
|
||||||
// Vérifier que l'événement existe
|
|
||||||
const existingEvent = await prisma.event.findUnique({
|
|
||||||
where: { id },
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!existingEvent) {
|
|
||||||
return NextResponse.json(
|
|
||||||
{ error: "Événement non trouvé" },
|
|
||||||
{ status: 404 }
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
const updateData: {
|
|
||||||
date?: string;
|
|
||||||
name?: string;
|
|
||||||
description?: string;
|
|
||||||
type?: EventType;
|
|
||||||
status?: EventStatus;
|
|
||||||
} = {};
|
|
||||||
|
|
||||||
if (date !== undefined) updateData.date = date;
|
|
||||||
if (name !== undefined) updateData.name = name;
|
|
||||||
if (description !== undefined) updateData.description = description;
|
|
||||||
if (type !== undefined) {
|
|
||||||
if (!Object.values(EventType).includes(type)) {
|
|
||||||
return NextResponse.json(
|
|
||||||
{ error: "Type d'événement invalide" },
|
|
||||||
{ status: 400 }
|
|
||||||
);
|
|
||||||
}
|
|
||||||
updateData.type = type as EventType;
|
|
||||||
}
|
|
||||||
if (status !== undefined) {
|
|
||||||
if (!Object.values(EventStatus).includes(status)) {
|
|
||||||
return NextResponse.json(
|
|
||||||
{ error: "Statut d'événement invalide" },
|
|
||||||
{ status: 400 }
|
|
||||||
);
|
|
||||||
}
|
|
||||||
updateData.status = status as EventStatus;
|
|
||||||
}
|
|
||||||
|
|
||||||
const event = await prisma.event.update({
|
|
||||||
where: { id },
|
|
||||||
data: updateData,
|
|
||||||
});
|
|
||||||
|
|
||||||
return NextResponse.json(event);
|
|
||||||
} catch (error) {
|
|
||||||
console.error("Error updating event:", error);
|
|
||||||
return NextResponse.json(
|
|
||||||
{ error: "Erreur lors de la mise à jour de l'événement" },
|
|
||||||
{ status: 500 }
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function DELETE(
|
|
||||||
request: Request,
|
|
||||||
{ params }: { params: Promise<{ id: string }> }
|
|
||||||
) {
|
|
||||||
try {
|
|
||||||
const session = await auth();
|
|
||||||
|
|
||||||
if (!session?.user || session.user.role !== Role.ADMIN) {
|
|
||||||
return NextResponse.json({ error: "Accès refusé" }, { status: 403 });
|
|
||||||
}
|
|
||||||
|
|
||||||
const { id } = await params;
|
|
||||||
|
|
||||||
// Vérifier que l'événement existe
|
|
||||||
const existingEvent = await prisma.event.findUnique({
|
|
||||||
where: { id },
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!existingEvent) {
|
|
||||||
return NextResponse.json(
|
|
||||||
{ error: "Événement non trouvé" },
|
|
||||||
{ status: 404 }
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
await prisma.event.delete({
|
|
||||||
where: { id },
|
|
||||||
});
|
|
||||||
|
|
||||||
return NextResponse.json({ success: true });
|
|
||||||
} catch (error) {
|
|
||||||
console.error("Error deleting event:", error);
|
|
||||||
return NextResponse.json(
|
|
||||||
{ error: "Erreur lors de la suppression de l'événement" },
|
|
||||||
{ status: 500 }
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
import { NextResponse } from "next/server";
|
import { NextResponse } from "next/server";
|
||||||
import { auth } from "@/lib/auth";
|
import { auth } from "@/lib/auth";
|
||||||
import { prisma } from "@/lib/prisma";
|
import { eventService } from "@/services/events/event.service";
|
||||||
import { Role, EventType, EventStatus } from "@/prisma/generated/prisma/client";
|
import { Role } from "@/prisma/generated/prisma/client";
|
||||||
|
|
||||||
export async function GET() {
|
export async function GET() {
|
||||||
try {
|
try {
|
||||||
@@ -11,13 +11,25 @@ export async function GET() {
|
|||||||
return NextResponse.json({ error: "Accès refusé" }, { status: 403 });
|
return NextResponse.json({ error: "Accès refusé" }, { status: 403 });
|
||||||
}
|
}
|
||||||
|
|
||||||
const events = await prisma.event.findMany({
|
const events = await eventService.getEventsWithStatus();
|
||||||
orderBy: {
|
|
||||||
date: "asc",
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
return NextResponse.json(events);
|
// Transformer les données pour la sérialisation
|
||||||
|
const eventsWithCount = events.map((event) => ({
|
||||||
|
id: event.id,
|
||||||
|
date: event.date.toISOString(),
|
||||||
|
name: event.name,
|
||||||
|
description: event.description,
|
||||||
|
type: event.type,
|
||||||
|
status: event.status,
|
||||||
|
room: event.room,
|
||||||
|
time: event.time,
|
||||||
|
maxPlaces: event.maxPlaces,
|
||||||
|
createdAt: event.createdAt.toISOString(),
|
||||||
|
updatedAt: event.updatedAt.toISOString(),
|
||||||
|
registrationsCount: event.registrationsCount,
|
||||||
|
}));
|
||||||
|
|
||||||
|
return NextResponse.json(eventsWithCount);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("Error fetching events:", error);
|
console.error("Error fetching events:", error);
|
||||||
return NextResponse.json(
|
return NextResponse.json(
|
||||||
@@ -26,57 +38,3 @@ export async function GET() {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function POST(request: Request) {
|
|
||||||
try {
|
|
||||||
const session = await auth();
|
|
||||||
|
|
||||||
if (!session?.user || session.user.role !== Role.ADMIN) {
|
|
||||||
return NextResponse.json({ error: "Accès refusé" }, { status: 403 });
|
|
||||||
}
|
|
||||||
|
|
||||||
const body = await request.json();
|
|
||||||
const { date, name, description, type, status } = body;
|
|
||||||
|
|
||||||
if (!date || !name || !description || !type || !status) {
|
|
||||||
return NextResponse.json(
|
|
||||||
{ error: "Tous les champs sont requis" },
|
|
||||||
{ status: 400 }
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Valider les enums
|
|
||||||
if (!Object.values(EventType).includes(type)) {
|
|
||||||
return NextResponse.json(
|
|
||||||
{ error: "Type d'événement invalide" },
|
|
||||||
{ status: 400 }
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!Object.values(EventStatus).includes(status)) {
|
|
||||||
return NextResponse.json(
|
|
||||||
{ error: "Statut d'événement invalide" },
|
|
||||||
{ status: 400 }
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
const event = await prisma.event.create({
|
|
||||||
data: {
|
|
||||||
date,
|
|
||||||
name,
|
|
||||||
description,
|
|
||||||
type: type as EventType,
|
|
||||||
status: status as EventStatus,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
return NextResponse.json(event);
|
|
||||||
} catch (error) {
|
|
||||||
console.error("Error creating event:", error);
|
|
||||||
return NextResponse.json(
|
|
||||||
{ error: "Erreur lors de la création de l'événement" },
|
|
||||||
{ status: 500 }
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|||||||
34
app/api/admin/feedback/route.ts
Normal file
34
app/api/admin/feedback/route.ts
Normal file
@@ -0,0 +1,34 @@
|
|||||||
|
import { NextResponse } from "next/server";
|
||||||
|
import { auth } from "@/lib/auth";
|
||||||
|
import { eventFeedbackService } from "@/services/events/event-feedback.service";
|
||||||
|
import { Role } from "@/prisma/generated/prisma/client";
|
||||||
|
|
||||||
|
export async function GET() {
|
||||||
|
try {
|
||||||
|
const session = await auth();
|
||||||
|
if (!session?.user?.id) {
|
||||||
|
return NextResponse.json({ error: "Non authentifié" }, { status: 401 });
|
||||||
|
}
|
||||||
|
|
||||||
|
if (session.user.role !== Role.ADMIN) {
|
||||||
|
return NextResponse.json({ error: "Accès refusé" }, { status: 403 });
|
||||||
|
}
|
||||||
|
|
||||||
|
// Récupérer tous les feedbacks avec les détails de l'événement et de l'utilisateur
|
||||||
|
const feedbacks = await eventFeedbackService.getAllFeedbacks();
|
||||||
|
|
||||||
|
// Calculer les statistiques par événement
|
||||||
|
const statistics = await eventFeedbackService.getFeedbackStatistics();
|
||||||
|
|
||||||
|
return NextResponse.json({
|
||||||
|
feedbacks,
|
||||||
|
statistics,
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error fetching feedbacks:", error);
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: "Erreur lors de la récupération des feedbacks" },
|
||||||
|
{ status: 500 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
99
app/api/admin/houses/route.ts
Normal file
99
app/api/admin/houses/route.ts
Normal file
@@ -0,0 +1,99 @@
|
|||||||
|
import { NextResponse } from "next/server";
|
||||||
|
import { auth } from "@/lib/auth";
|
||||||
|
import { houseService } from "@/services/houses/house.service";
|
||||||
|
import { Role, Prisma } from "@/prisma/generated/prisma/client";
|
||||||
|
|
||||||
|
export async function GET() {
|
||||||
|
try {
|
||||||
|
const session = await auth();
|
||||||
|
|
||||||
|
if (!session?.user || session.user.role !== Role.ADMIN) {
|
||||||
|
return NextResponse.json({ error: "Accès refusé" }, { status: 403 });
|
||||||
|
}
|
||||||
|
|
||||||
|
// Récupérer toutes les maisons avec leurs membres
|
||||||
|
type HouseWithIncludes = Prisma.HouseGetPayload<{
|
||||||
|
include: {
|
||||||
|
creator: {
|
||||||
|
select: {
|
||||||
|
id: true;
|
||||||
|
username: true;
|
||||||
|
avatar: true;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
memberships: {
|
||||||
|
include: {
|
||||||
|
user: {
|
||||||
|
select: {
|
||||||
|
id: true;
|
||||||
|
username: true;
|
||||||
|
avatar: true;
|
||||||
|
score: true;
|
||||||
|
level: true;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
};
|
||||||
|
};
|
||||||
|
};
|
||||||
|
}>;
|
||||||
|
|
||||||
|
const houses = (await houseService.getAllHouses({
|
||||||
|
include: {
|
||||||
|
creator: {
|
||||||
|
select: {
|
||||||
|
id: true,
|
||||||
|
username: true,
|
||||||
|
avatar: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
memberships: {
|
||||||
|
include: {
|
||||||
|
user: {
|
||||||
|
select: {
|
||||||
|
id: true,
|
||||||
|
username: true,
|
||||||
|
avatar: true,
|
||||||
|
score: true,
|
||||||
|
level: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
orderBy: [
|
||||||
|
{ role: "asc" }, // OWNER, ADMIN, MEMBER
|
||||||
|
{ joinedAt: "asc" },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
orderBy: {
|
||||||
|
createdAt: "desc",
|
||||||
|
},
|
||||||
|
})) as unknown as HouseWithIncludes[];
|
||||||
|
|
||||||
|
// Transformer les données pour la sérialisation
|
||||||
|
const housesWithData = houses.map((house) => ({
|
||||||
|
id: house.id,
|
||||||
|
name: house.name,
|
||||||
|
description: house.description,
|
||||||
|
creatorId: house.creatorId,
|
||||||
|
creator: house.creator,
|
||||||
|
createdAt: house.createdAt.toISOString(),
|
||||||
|
updatedAt: house.updatedAt.toISOString(),
|
||||||
|
membersCount: house.memberships?.length || 0,
|
||||||
|
memberships:
|
||||||
|
house.memberships?.map((membership) => ({
|
||||||
|
id: membership.id,
|
||||||
|
role: membership.role,
|
||||||
|
joinedAt: membership.joinedAt.toISOString(),
|
||||||
|
user: membership.user,
|
||||||
|
})) || [],
|
||||||
|
}));
|
||||||
|
|
||||||
|
return NextResponse.json(housesWithData);
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error fetching houses:", error);
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: "Erreur lors de la récupération des maisons" },
|
||||||
|
{ status: 500 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -15,25 +15,18 @@ export async function GET() {
|
|||||||
|
|
||||||
const images: string[] = [];
|
const images: string[] = [];
|
||||||
|
|
||||||
// Lister les images dans public/
|
// Lister uniquement les images dans public/uploads/backgrounds/
|
||||||
const publicDir = join(process.cwd(), "public");
|
const publicDir = join(process.cwd(), "public");
|
||||||
if (existsSync(publicDir)) {
|
const uploadsDir = join(publicDir, "uploads");
|
||||||
const files = await readdir(publicDir);
|
const backgroundsDir = join(uploadsDir, "backgrounds");
|
||||||
|
|
||||||
|
if (existsSync(backgroundsDir)) {
|
||||||
|
const files = await readdir(backgroundsDir);
|
||||||
const imageFiles = files.filter(
|
const imageFiles = files.filter(
|
||||||
(file) =>
|
(file) =>
|
||||||
file.match(/\.(jpg|jpeg|png|gif|webp|svg)$/i) && !file.startsWith(".")
|
file.match(/\.(jpg|jpeg|png|gif|webp|svg)$/i) && !file.startsWith(".")
|
||||||
);
|
);
|
||||||
images.push(...imageFiles.map((file) => `/${file}`));
|
images.push(...imageFiles.map((file) => `/api/backgrounds/${file}`));
|
||||||
}
|
|
||||||
|
|
||||||
// Lister les images dans public/uploads/
|
|
||||||
const uploadsDir = join(publicDir, "uploads");
|
|
||||||
if (existsSync(uploadsDir)) {
|
|
||||||
const uploadFiles = await readdir(uploadsDir);
|
|
||||||
const imageFiles = uploadFiles.filter((file) =>
|
|
||||||
file.match(/\.(jpg|jpeg|png|gif|webp|svg)$/i)
|
|
||||||
);
|
|
||||||
images.push(...imageFiles.map((file) => `/uploads/${file}`));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return NextResponse.json({ images });
|
return NextResponse.json({ images });
|
||||||
@@ -45,4 +38,3 @@ export async function GET() {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -17,7 +17,10 @@ export async function POST(request: Request) {
|
|||||||
const file = formData.get("file") as File;
|
const file = formData.get("file") as File;
|
||||||
|
|
||||||
if (!file) {
|
if (!file) {
|
||||||
return NextResponse.json({ error: "Aucun fichier fourni" }, { status: 400 });
|
return NextResponse.json(
|
||||||
|
{ error: "Aucun fichier fourni" },
|
||||||
|
{ status: 400 }
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Vérifier le type de fichier
|
// Vérifier le type de fichier
|
||||||
@@ -28,24 +31,25 @@ export async function POST(request: Request) {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Créer le dossier uploads s'il n'existe pas
|
// Créer le dossier uploads/backgrounds s'il n'existe pas
|
||||||
const uploadsDir = join(process.cwd(), "public", "uploads");
|
const uploadsDir = join(process.cwd(), "public", "uploads");
|
||||||
if (!existsSync(uploadsDir)) {
|
const backgroundsDir = join(uploadsDir, "backgrounds");
|
||||||
await mkdir(uploadsDir, { recursive: true });
|
if (!existsSync(backgroundsDir)) {
|
||||||
|
await mkdir(backgroundsDir, { recursive: true });
|
||||||
}
|
}
|
||||||
|
|
||||||
// Générer un nom de fichier unique
|
// Générer un nom de fichier unique
|
||||||
const timestamp = Date.now();
|
const timestamp = Date.now();
|
||||||
const filename = `${timestamp}-${file.name}`;
|
const filename = `${timestamp}-${file.name}`;
|
||||||
const filepath = join(uploadsDir, filename);
|
const filepath = join(backgroundsDir, filename);
|
||||||
|
|
||||||
// Convertir le fichier en buffer et l'écrire
|
// Convertir le fichier en buffer et l'écrire
|
||||||
const bytes = await file.arrayBuffer();
|
const bytes = await file.arrayBuffer();
|
||||||
const buffer = Buffer.from(bytes);
|
const buffer = Buffer.from(bytes);
|
||||||
await writeFile(filepath, buffer);
|
await writeFile(filepath, buffer);
|
||||||
|
|
||||||
// Retourner l'URL de l'image
|
// Retourner l'URL de l'image via l'API
|
||||||
const imageUrl = `/uploads/${filename}`;
|
const imageUrl = `/api/backgrounds/${filename}`;
|
||||||
return NextResponse.json({ url: imageUrl });
|
return NextResponse.json({ url: imageUrl });
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("Error uploading image:", error);
|
console.error("Error uploading image:", error);
|
||||||
@@ -55,4 +59,3 @@ export async function POST(request: Request) {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import { NextResponse } from "next/server";
|
import { NextResponse } from "next/server";
|
||||||
import { auth } from "@/lib/auth";
|
import { auth } from "@/lib/auth";
|
||||||
import { prisma } from "@/lib/prisma";
|
import { sitePreferencesService } from "@/services/preferences/site-preferences.service";
|
||||||
import { Role } from "@/prisma/generated/prisma/client";
|
import { Role } from "@/prisma/generated/prisma/client";
|
||||||
|
|
||||||
export async function GET() {
|
export async function GET() {
|
||||||
@@ -11,22 +11,9 @@ export async function GET() {
|
|||||||
return NextResponse.json({ error: "Accès refusé" }, { status: 403 });
|
return NextResponse.json({ error: "Accès refusé" }, { status: 403 });
|
||||||
}
|
}
|
||||||
|
|
||||||
// Récupérer les préférences globales du site
|
// Récupérer les préférences globales du site (ou créer si elles n'existent pas)
|
||||||
let sitePreferences = await prisma.sitePreferences.findUnique({
|
const sitePreferences =
|
||||||
where: { id: "global" },
|
await sitePreferencesService.getOrCreateSitePreferences();
|
||||||
});
|
|
||||||
|
|
||||||
// Si elles n'existent pas, créer une entrée par défaut
|
|
||||||
if (!sitePreferences) {
|
|
||||||
sitePreferences = await prisma.sitePreferences.create({
|
|
||||||
data: {
|
|
||||||
id: "global",
|
|
||||||
homeBackground: null,
|
|
||||||
eventsBackground: null,
|
|
||||||
leaderboardBackground: null,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
return NextResponse.json(sitePreferences);
|
return NextResponse.json(sitePreferences);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
@@ -37,46 +24,3 @@ export async function GET() {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function PUT(request: Request) {
|
|
||||||
try {
|
|
||||||
const session = await auth();
|
|
||||||
|
|
||||||
if (!session?.user || session.user.role !== Role.ADMIN) {
|
|
||||||
return NextResponse.json({ error: "Accès refusé" }, { status: 403 });
|
|
||||||
}
|
|
||||||
|
|
||||||
const body = await request.json();
|
|
||||||
const { homeBackground, eventsBackground, leaderboardBackground } = body;
|
|
||||||
|
|
||||||
const preferences = await prisma.sitePreferences.upsert({
|
|
||||||
where: { id: "global" },
|
|
||||||
update: {
|
|
||||||
homeBackground:
|
|
||||||
homeBackground === "" ? null : homeBackground ?? undefined,
|
|
||||||
eventsBackground:
|
|
||||||
eventsBackground === "" ? null : eventsBackground ?? undefined,
|
|
||||||
leaderboardBackground:
|
|
||||||
leaderboardBackground === ""
|
|
||||||
? null
|
|
||||||
: leaderboardBackground ?? undefined,
|
|
||||||
},
|
|
||||||
create: {
|
|
||||||
id: "global",
|
|
||||||
homeBackground: homeBackground === "" ? null : homeBackground ?? null,
|
|
||||||
eventsBackground:
|
|
||||||
eventsBackground === "" ? null : eventsBackground ?? null,
|
|
||||||
leaderboardBackground:
|
|
||||||
leaderboardBackground === "" ? null : leaderboardBackground ?? null,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
return NextResponse.json(preferences);
|
|
||||||
} catch (error) {
|
|
||||||
console.error("Error updating admin preferences:", error);
|
|
||||||
return NextResponse.json(
|
|
||||||
{ error: "Erreur lors de la mise à jour des préférences" },
|
|
||||||
{ status: 500 }
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,151 +0,0 @@
|
|||||||
import { NextResponse } from "next/server";
|
|
||||||
import { auth } from "@/lib/auth";
|
|
||||||
import { prisma } from "@/lib/prisma";
|
|
||||||
import { Role } from "@/prisma/generated/prisma/client";
|
|
||||||
|
|
||||||
export async function PUT(
|
|
||||||
request: Request,
|
|
||||||
{ params }: { params: Promise<{ id: string }> }
|
|
||||||
) {
|
|
||||||
try {
|
|
||||||
const session = await auth();
|
|
||||||
|
|
||||||
if (!session?.user || session.user.role !== Role.ADMIN) {
|
|
||||||
return NextResponse.json({ error: "Accès refusé" }, { status: 403 });
|
|
||||||
}
|
|
||||||
|
|
||||||
const { id } = await params;
|
|
||||||
const body = await request.json();
|
|
||||||
const { hpDelta, xpDelta, score, level, role } = body;
|
|
||||||
|
|
||||||
// Récupérer l'utilisateur actuel
|
|
||||||
const user = await prisma.user.findUnique({
|
|
||||||
where: { id },
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!user) {
|
|
||||||
return NextResponse.json(
|
|
||||||
{ error: "Utilisateur non trouvé" },
|
|
||||||
{ status: 404 }
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Calculer les nouvelles valeurs
|
|
||||||
let newHp = user.hp;
|
|
||||||
let newXp = user.xp;
|
|
||||||
let newLevel = user.level;
|
|
||||||
let newMaxXp = user.maxXp;
|
|
||||||
|
|
||||||
// Appliquer les changements de HP
|
|
||||||
if (hpDelta !== undefined) {
|
|
||||||
newHp = Math.max(0, Math.min(user.maxHp, user.hp + hpDelta));
|
|
||||||
}
|
|
||||||
|
|
||||||
// Appliquer les changements de XP
|
|
||||||
if (xpDelta !== undefined) {
|
|
||||||
newXp = user.xp + xpDelta;
|
|
||||||
newLevel = user.level;
|
|
||||||
newMaxXp = user.maxXp;
|
|
||||||
|
|
||||||
// Gérer le niveau up si nécessaire (quand on ajoute de l'XP)
|
|
||||||
if (newXp >= newMaxXp && newXp > 0) {
|
|
||||||
while (newXp >= newMaxXp) {
|
|
||||||
newXp -= newMaxXp;
|
|
||||||
newLevel += 1;
|
|
||||||
// Augmenter le maxXp pour le prochain niveau (formule simple)
|
|
||||||
newMaxXp = Math.floor(newMaxXp * 1.2);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Gérer le niveau down si nécessaire (quand on enlève de l'XP)
|
|
||||||
if (newXp < 0 && newLevel > 1) {
|
|
||||||
while (newXp < 0 && newLevel > 1) {
|
|
||||||
newLevel -= 1;
|
|
||||||
// Calculer le maxXp du niveau précédent
|
|
||||||
newMaxXp = Math.floor(newMaxXp / 1.2);
|
|
||||||
newXp += newMaxXp;
|
|
||||||
}
|
|
||||||
// S'assurer que l'XP ne peut pas être négative
|
|
||||||
newXp = Math.max(0, newXp);
|
|
||||||
}
|
|
||||||
|
|
||||||
// S'assurer que le niveau minimum est 1
|
|
||||||
if (newLevel < 1) {
|
|
||||||
newLevel = 1;
|
|
||||||
newXp = 0;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Appliquer les changements directs (score, level, role)
|
|
||||||
const updateData: {
|
|
||||||
hp: number;
|
|
||||||
xp: number;
|
|
||||||
level: number;
|
|
||||||
maxXp: number;
|
|
||||||
score?: number;
|
|
||||||
role?: Role;
|
|
||||||
} = {
|
|
||||||
hp: newHp,
|
|
||||||
xp: newXp,
|
|
||||||
level: newLevel,
|
|
||||||
maxXp: newMaxXp,
|
|
||||||
};
|
|
||||||
|
|
||||||
if (score !== undefined) {
|
|
||||||
updateData.score = Math.max(0, score);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (level !== undefined) {
|
|
||||||
// Si le niveau est modifié directement, utiliser cette valeur
|
|
||||||
const targetLevel = Math.max(1, level);
|
|
||||||
updateData.level = targetLevel;
|
|
||||||
|
|
||||||
// Recalculer le maxXp pour le nouveau niveau
|
|
||||||
// Formule: maxXp = 5000 * (1.2 ^ (level - 1))
|
|
||||||
let calculatedMaxXp = 5000;
|
|
||||||
for (let i = 1; i < targetLevel; i++) {
|
|
||||||
calculatedMaxXp = Math.floor(calculatedMaxXp * 1.2);
|
|
||||||
}
|
|
||||||
updateData.maxXp = calculatedMaxXp;
|
|
||||||
|
|
||||||
// Réinitialiser l'XP si le niveau change directement (sauf si on modifie aussi l'XP)
|
|
||||||
if (targetLevel !== user.level && xpDelta === undefined) {
|
|
||||||
updateData.xp = 0;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (role !== undefined) {
|
|
||||||
if (role === "ADMIN" || role === "USER") {
|
|
||||||
updateData.role = role as Role;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Mettre à jour l'utilisateur
|
|
||||||
const updatedUser = await prisma.user.update({
|
|
||||||
where: { id },
|
|
||||||
data: updateData,
|
|
||||||
select: {
|
|
||||||
id: true,
|
|
||||||
username: true,
|
|
||||||
email: true,
|
|
||||||
role: true,
|
|
||||||
score: true,
|
|
||||||
level: true,
|
|
||||||
hp: true,
|
|
||||||
maxHp: true,
|
|
||||||
xp: true,
|
|
||||||
maxXp: true,
|
|
||||||
avatar: true,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
return NextResponse.json(updatedUser);
|
|
||||||
} catch (error) {
|
|
||||||
console.error("Error updating user:", error);
|
|
||||||
return NextResponse.json(
|
|
||||||
{ error: "Erreur lors de la mise à jour de l'utilisateur" },
|
|
||||||
{ status: 500 }
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
import { NextResponse } from "next/server";
|
import { NextResponse } from "next/server";
|
||||||
import { auth } from "@/lib/auth";
|
import { auth } from "@/lib/auth";
|
||||||
import { prisma } from "@/lib/prisma";
|
import { userService } from "@/services/users/user.service";
|
||||||
import { Role } from "@/prisma/generated/prisma/client";
|
import { Role } from "@/prisma/generated/prisma/client";
|
||||||
|
|
||||||
export async function GET() {
|
export async function GET() {
|
||||||
@@ -12,7 +12,10 @@ export async function GET() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Récupérer tous les utilisateurs avec leurs stats
|
// Récupérer tous les utilisateurs avec leurs stats
|
||||||
const users = await prisma.user.findMany({
|
const users = await userService.getAllUsers({
|
||||||
|
orderBy: {
|
||||||
|
score: "desc",
|
||||||
|
},
|
||||||
select: {
|
select: {
|
||||||
id: true,
|
id: true,
|
||||||
username: true,
|
username: true,
|
||||||
@@ -27,9 +30,6 @@ export async function GET() {
|
|||||||
avatar: true,
|
avatar: true,
|
||||||
createdAt: true,
|
createdAt: true,
|
||||||
},
|
},
|
||||||
orderBy: {
|
|
||||||
score: "desc",
|
|
||||||
},
|
|
||||||
});
|
});
|
||||||
|
|
||||||
return NextResponse.json(users);
|
return NextResponse.json(users);
|
||||||
@@ -41,4 +41,3 @@ export async function GET() {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,3 @@
|
|||||||
import { handlers } from "@/lib/auth";
|
import { handlers } from "@/lib/auth";
|
||||||
|
|
||||||
export const { GET, POST } = handlers;
|
export const { GET, POST } = handlers;
|
||||||
|
|
||||||
|
|||||||
78
app/api/avatars/[filename]/route.ts
Normal file
78
app/api/avatars/[filename]/route.ts
Normal file
@@ -0,0 +1,78 @@
|
|||||||
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
|
import { readFile } from "fs/promises";
|
||||||
|
import { join } from "path";
|
||||||
|
import { existsSync } from "fs";
|
||||||
|
|
||||||
|
export async function GET(
|
||||||
|
request: NextRequest,
|
||||||
|
{ params }: { params: Promise<{ filename: string }> }
|
||||||
|
) {
|
||||||
|
try {
|
||||||
|
const { filename } = await params;
|
||||||
|
|
||||||
|
// Sécuriser le nom de fichier pour éviter les path traversal
|
||||||
|
if (
|
||||||
|
!filename ||
|
||||||
|
filename.includes("..") ||
|
||||||
|
filename.includes("/") ||
|
||||||
|
filename.includes("\\")
|
||||||
|
) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: "Nom de fichier invalide" },
|
||||||
|
{ status: 400 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Décoder le nom de fichier (au cas où il contient des caractères encodés)
|
||||||
|
const decodedFilename = decodeURIComponent(filename);
|
||||||
|
|
||||||
|
// Chemin vers le fichier avatar
|
||||||
|
const avatarsDir = join(process.cwd(), "public", "uploads", "avatars");
|
||||||
|
const filepath = join(avatarsDir, decodedFilename);
|
||||||
|
|
||||||
|
// Vérifier que le fichier existe
|
||||||
|
if (!existsSync(filepath)) {
|
||||||
|
return NextResponse.json({ error: "Avatar non trouvé" }, { status: 404 });
|
||||||
|
}
|
||||||
|
|
||||||
|
// Lire le fichier
|
||||||
|
const fileBuffer = await readFile(filepath);
|
||||||
|
|
||||||
|
// Déterminer le type MIME basé sur l'extension
|
||||||
|
const extension = decodedFilename.split(".").pop()?.toLowerCase();
|
||||||
|
let contentType = "image/jpeg"; // par défaut
|
||||||
|
|
||||||
|
switch (extension) {
|
||||||
|
case "png":
|
||||||
|
contentType = "image/png";
|
||||||
|
break;
|
||||||
|
case "gif":
|
||||||
|
contentType = "image/gif";
|
||||||
|
break;
|
||||||
|
case "webp":
|
||||||
|
contentType = "image/webp";
|
||||||
|
break;
|
||||||
|
case "svg":
|
||||||
|
contentType = "image/svg+xml";
|
||||||
|
break;
|
||||||
|
case "jpg":
|
||||||
|
case "jpeg":
|
||||||
|
default:
|
||||||
|
contentType = "image/jpeg";
|
||||||
|
}
|
||||||
|
|
||||||
|
// Retourner l'image avec les bons headers
|
||||||
|
return new NextResponse(fileBuffer, {
|
||||||
|
headers: {
|
||||||
|
"Content-Type": contentType,
|
||||||
|
"Cache-Control": "public, max-age=31536000, immutable",
|
||||||
|
},
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error serving avatar:", error);
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: "Erreur lors de la récupération de l'avatar" },
|
||||||
|
{ status: 500 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
86
app/api/backgrounds/[filename]/route.ts
Normal file
86
app/api/backgrounds/[filename]/route.ts
Normal file
@@ -0,0 +1,86 @@
|
|||||||
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
|
import { readFile } from "fs/promises";
|
||||||
|
import { join } from "path";
|
||||||
|
import { existsSync } from "fs";
|
||||||
|
|
||||||
|
export async function GET(
|
||||||
|
request: NextRequest,
|
||||||
|
{ params }: { params: Promise<{ filename: string }> }
|
||||||
|
) {
|
||||||
|
try {
|
||||||
|
const { filename } = await params;
|
||||||
|
|
||||||
|
// Sécuriser le nom de fichier pour éviter les path traversal
|
||||||
|
if (
|
||||||
|
!filename ||
|
||||||
|
filename.includes("..") ||
|
||||||
|
filename.includes("/") ||
|
||||||
|
filename.includes("\\")
|
||||||
|
) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: "Nom de fichier invalide" },
|
||||||
|
{ status: 400 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Décoder le nom de fichier (au cas où il contient des caractères encodés)
|
||||||
|
const decodedFilename = decodeURIComponent(filename);
|
||||||
|
|
||||||
|
// Chemin vers le fichier background
|
||||||
|
const backgroundsDir = join(
|
||||||
|
process.cwd(),
|
||||||
|
"public",
|
||||||
|
"uploads",
|
||||||
|
"backgrounds"
|
||||||
|
);
|
||||||
|
const filepath = join(backgroundsDir, decodedFilename);
|
||||||
|
|
||||||
|
// Vérifier que le fichier existe
|
||||||
|
if (!existsSync(filepath)) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: "Image de fond non trouvée" },
|
||||||
|
{ status: 404 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Lire le fichier
|
||||||
|
const fileBuffer = await readFile(filepath);
|
||||||
|
|
||||||
|
// Déterminer le type MIME basé sur l'extension
|
||||||
|
const extension = decodedFilename.split(".").pop()?.toLowerCase();
|
||||||
|
let contentType = "image/jpeg"; // par défaut
|
||||||
|
|
||||||
|
switch (extension) {
|
||||||
|
case "png":
|
||||||
|
contentType = "image/png";
|
||||||
|
break;
|
||||||
|
case "gif":
|
||||||
|
contentType = "image/gif";
|
||||||
|
break;
|
||||||
|
case "webp":
|
||||||
|
contentType = "image/webp";
|
||||||
|
break;
|
||||||
|
case "svg":
|
||||||
|
contentType = "image/svg+xml";
|
||||||
|
break;
|
||||||
|
case "jpg":
|
||||||
|
case "jpeg":
|
||||||
|
default:
|
||||||
|
contentType = "image/jpeg";
|
||||||
|
}
|
||||||
|
|
||||||
|
// Retourner l'image avec les bons headers
|
||||||
|
return new NextResponse(fileBuffer, {
|
||||||
|
headers: {
|
||||||
|
"Content-Type": contentType,
|
||||||
|
"Cache-Control": "public, max-age=31536000, immutable",
|
||||||
|
},
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error serving background:", error);
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: "Erreur lors de la récupération de l'image de fond" },
|
||||||
|
{ status: 500 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
23
app/api/challenges/active-count/route.ts
Normal file
23
app/api/challenges/active-count/route.ts
Normal file
@@ -0,0 +1,23 @@
|
|||||||
|
import { NextResponse } from "next/server";
|
||||||
|
import { auth } from "@/lib/auth";
|
||||||
|
import { challengeService } from "@/services/challenges/challenge.service";
|
||||||
|
|
||||||
|
export async function GET() {
|
||||||
|
try {
|
||||||
|
const session = await auth();
|
||||||
|
|
||||||
|
if (!session?.user?.id) {
|
||||||
|
return NextResponse.json({ count: 0 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const count = await challengeService.getActiveChallengesCount(
|
||||||
|
session.user.id
|
||||||
|
);
|
||||||
|
|
||||||
|
return NextResponse.json({ count });
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error fetching active challenges count:", error);
|
||||||
|
return NextResponse.json({ count: 0 });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
31
app/api/challenges/route.ts
Normal file
31
app/api/challenges/route.ts
Normal file
@@ -0,0 +1,31 @@
|
|||||||
|
import { NextResponse } from "next/server";
|
||||||
|
import { auth } from "@/lib/auth";
|
||||||
|
import { challengeService } from "@/services/challenges/challenge.service";
|
||||||
|
|
||||||
|
export async function GET() {
|
||||||
|
try {
|
||||||
|
const session = await auth();
|
||||||
|
|
||||||
|
if (!session?.user?.id) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: "Vous devez être connecté" },
|
||||||
|
{ status: 401 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Récupérer tous les défis de l'utilisateur
|
||||||
|
const challenges = await challengeService.getUserChallenges(
|
||||||
|
session.user.id
|
||||||
|
);
|
||||||
|
|
||||||
|
return NextResponse.json(challenges);
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error fetching challenges:", error);
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: "Erreur lors de la récupération des défis" },
|
||||||
|
{ status: 500 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
28
app/api/events/[id]/register/route.ts
Normal file
28
app/api/events/[id]/register/route.ts
Normal file
@@ -0,0 +1,28 @@
|
|||||||
|
import { NextResponse } from "next/server";
|
||||||
|
import { auth } from "@/lib/auth";
|
||||||
|
import { eventRegistrationService } from "@/services/events/event-registration.service";
|
||||||
|
|
||||||
|
export async function GET(
|
||||||
|
request: Request,
|
||||||
|
{ params }: { params: Promise<{ id: string }> }
|
||||||
|
) {
|
||||||
|
try {
|
||||||
|
const session = await auth();
|
||||||
|
|
||||||
|
if (!session?.user?.id) {
|
||||||
|
return NextResponse.json({ registered: false });
|
||||||
|
}
|
||||||
|
|
||||||
|
const { id: eventId } = await params;
|
||||||
|
|
||||||
|
const isRegistered = await eventRegistrationService.checkUserRegistration(
|
||||||
|
session.user.id,
|
||||||
|
eventId
|
||||||
|
);
|
||||||
|
|
||||||
|
return NextResponse.json({ registered: isRegistered });
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Check registration error:", error);
|
||||||
|
return NextResponse.json({ registered: false });
|
||||||
|
}
|
||||||
|
}
|
||||||
28
app/api/events/[id]/route.ts
Normal file
28
app/api/events/[id]/route.ts
Normal file
@@ -0,0 +1,28 @@
|
|||||||
|
import { NextResponse } from "next/server";
|
||||||
|
import { eventService } from "@/services/events/event.service";
|
||||||
|
|
||||||
|
export async function GET(
|
||||||
|
request: Request,
|
||||||
|
{ params }: { params: Promise<{ id: string }> }
|
||||||
|
) {
|
||||||
|
try {
|
||||||
|
const { id } = await params;
|
||||||
|
|
||||||
|
const event = await eventService.getEventById(id);
|
||||||
|
|
||||||
|
if (!event) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: "Événement introuvable" },
|
||||||
|
{ status: 404 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return NextResponse.json(event);
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error fetching event:", error);
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: "Erreur lors de la récupération de l'événement" },
|
||||||
|
{ status: 500 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,12 +1,10 @@
|
|||||||
import { NextResponse } from "next/server";
|
import { NextResponse } from "next/server";
|
||||||
import { prisma } from "@/lib/prisma";
|
import { eventService } from "@/services/events/event.service";
|
||||||
|
|
||||||
export async function GET() {
|
export async function GET() {
|
||||||
try {
|
try {
|
||||||
const events = await prisma.event.findMany({
|
const events = await eventService.getAllEvents({
|
||||||
orderBy: {
|
orderBy: { date: "asc" },
|
||||||
date: "asc",
|
|
||||||
},
|
|
||||||
});
|
});
|
||||||
|
|
||||||
return NextResponse.json(events);
|
return NextResponse.json(events);
|
||||||
@@ -18,4 +16,3 @@ export async function GET() {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
31
app/api/feedback/[eventId]/route.ts
Normal file
31
app/api/feedback/[eventId]/route.ts
Normal file
@@ -0,0 +1,31 @@
|
|||||||
|
import { NextResponse } from "next/server";
|
||||||
|
import { auth } from "@/lib/auth";
|
||||||
|
import { eventFeedbackService } from "@/services/events/event-feedback.service";
|
||||||
|
|
||||||
|
export async function GET(
|
||||||
|
request: Request,
|
||||||
|
{ params }: { params: Promise<{ eventId: string }> }
|
||||||
|
) {
|
||||||
|
try {
|
||||||
|
const session = await auth();
|
||||||
|
if (!session?.user?.id) {
|
||||||
|
return NextResponse.json({ error: "Non authentifié" }, { status: 401 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const { eventId } = await params;
|
||||||
|
|
||||||
|
// Récupérer le feedback de l'utilisateur pour cet événement
|
||||||
|
const feedback = await eventFeedbackService.getUserFeedback(
|
||||||
|
session.user.id,
|
||||||
|
eventId
|
||||||
|
);
|
||||||
|
|
||||||
|
return NextResponse.json({ feedback });
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error fetching feedback:", error);
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: "Erreur lors de la récupération du feedback" },
|
||||||
|
{ status: 500 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
5
app/api/health/route.ts
Normal file
5
app/api/health/route.ts
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
import { NextResponse } from "next/server";
|
||||||
|
|
||||||
|
export async function GET() {
|
||||||
|
return NextResponse.json({ status: "ok" });
|
||||||
|
}
|
||||||
51
app/api/houses/[houseId]/invitations/route.ts
Normal file
51
app/api/houses/[houseId]/invitations/route.ts
Normal file
@@ -0,0 +1,51 @@
|
|||||||
|
import { NextResponse } from "next/server";
|
||||||
|
import { auth } from "@/lib/auth";
|
||||||
|
import { houseService } from "@/services/houses/house.service";
|
||||||
|
|
||||||
|
export async function GET(
|
||||||
|
request: Request,
|
||||||
|
{ params }: { params: Promise<{ houseId: string }> }
|
||||||
|
) {
|
||||||
|
try {
|
||||||
|
const session = await auth();
|
||||||
|
|
||||||
|
if (!session?.user?.id) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: "Vous devez être connecté" },
|
||||||
|
{ status: 401 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const { houseId } = await params;
|
||||||
|
|
||||||
|
// Vérifier que l'utilisateur est membre de la maison
|
||||||
|
const isMember = await houseService.isUserMemberOfHouse(
|
||||||
|
session.user.id,
|
||||||
|
houseId
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!isMember) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: "Vous devez être membre de cette maison" },
|
||||||
|
{ status: 403 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const { searchParams } = new URL(request.url);
|
||||||
|
const status = searchParams.get("status") as "PENDING" | "ACCEPTED" | "REJECTED" | "CANCELLED" | null;
|
||||||
|
|
||||||
|
const invitations = await houseService.getHouseInvitations(
|
||||||
|
houseId,
|
||||||
|
status || undefined
|
||||||
|
);
|
||||||
|
|
||||||
|
return NextResponse.json(invitations);
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error fetching house invitations:", error);
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: "Erreur lors de la récupération des invitations" },
|
||||||
|
{ status: 500 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
48
app/api/houses/[houseId]/requests/route.ts
Normal file
48
app/api/houses/[houseId]/requests/route.ts
Normal file
@@ -0,0 +1,48 @@
|
|||||||
|
import { NextResponse } from "next/server";
|
||||||
|
import { auth } from "@/lib/auth";
|
||||||
|
import { houseService } from "@/services/houses/house.service";
|
||||||
|
|
||||||
|
export async function GET(
|
||||||
|
request: Request,
|
||||||
|
{ params }: { params: Promise<{ houseId: string }> }
|
||||||
|
) {
|
||||||
|
try {
|
||||||
|
const session = await auth();
|
||||||
|
|
||||||
|
if (!session?.user?.id) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: "Vous devez être connecté" },
|
||||||
|
{ status: 401 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const { houseId } = await params;
|
||||||
|
|
||||||
|
// Vérifier que l'utilisateur est propriétaire ou admin
|
||||||
|
const isAuthorized = await houseService.isUserOwnerOrAdmin(
|
||||||
|
session.user.id,
|
||||||
|
houseId
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!isAuthorized) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: "Vous n'avez pas les permissions pour voir les demandes" },
|
||||||
|
{ status: 403 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const { searchParams } = new URL(request.url);
|
||||||
|
const status = searchParams.get("status") as "PENDING" | "ACCEPTED" | "REJECTED" | "CANCELLED" | null;
|
||||||
|
|
||||||
|
const requests = await houseService.getHouseRequests(houseId, status || undefined);
|
||||||
|
|
||||||
|
return NextResponse.json(requests);
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error fetching house requests:", error);
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: "Erreur lors de la récupération des demandes" },
|
||||||
|
{ status: 500 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
59
app/api/houses/[houseId]/route.ts
Normal file
59
app/api/houses/[houseId]/route.ts
Normal file
@@ -0,0 +1,59 @@
|
|||||||
|
import { NextResponse } from "next/server";
|
||||||
|
import { auth } from "@/lib/auth";
|
||||||
|
import { houseService } from "@/services/houses/house.service";
|
||||||
|
|
||||||
|
export async function GET(
|
||||||
|
request: Request,
|
||||||
|
{ params }: { params: Promise<{ houseId: string }> }
|
||||||
|
) {
|
||||||
|
try {
|
||||||
|
const session = await auth();
|
||||||
|
|
||||||
|
if (!session?.user?.id) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: "Vous devez être connecté" },
|
||||||
|
{ status: 401 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const { houseId } = await params;
|
||||||
|
const house = await houseService.getHouseById(houseId, {
|
||||||
|
memberships: {
|
||||||
|
include: {
|
||||||
|
user: {
|
||||||
|
select: {
|
||||||
|
id: true,
|
||||||
|
username: true,
|
||||||
|
avatar: true,
|
||||||
|
score: true,
|
||||||
|
level: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
creator: {
|
||||||
|
select: {
|
||||||
|
id: true,
|
||||||
|
username: true,
|
||||||
|
avatar: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!house) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: "Maison non trouvée" },
|
||||||
|
{ status: 404 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return NextResponse.json(house);
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error fetching house:", error);
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: "Erreur lors de la récupération de la maison" },
|
||||||
|
{ status: 500 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
48
app/api/houses/my-house/route.ts
Normal file
48
app/api/houses/my-house/route.ts
Normal file
@@ -0,0 +1,48 @@
|
|||||||
|
import { NextResponse } from "next/server";
|
||||||
|
import { auth } from "@/lib/auth";
|
||||||
|
import { houseService } from "@/services/houses/house.service";
|
||||||
|
|
||||||
|
export async function GET() {
|
||||||
|
try {
|
||||||
|
const session = await auth();
|
||||||
|
|
||||||
|
if (!session?.user?.id) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: "Vous devez être connecté" },
|
||||||
|
{ status: 401 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const house = await houseService.getUserHouse(session.user.id, {
|
||||||
|
memberships: {
|
||||||
|
include: {
|
||||||
|
user: {
|
||||||
|
select: {
|
||||||
|
id: true,
|
||||||
|
username: true,
|
||||||
|
avatar: true,
|
||||||
|
score: true,
|
||||||
|
level: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
creator: {
|
||||||
|
select: {
|
||||||
|
id: true,
|
||||||
|
username: true,
|
||||||
|
avatar: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
return NextResponse.json(house);
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error fetching user house:", error);
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: "Erreur lors de la récupération de votre maison" },
|
||||||
|
{ status: 500 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
87
app/api/houses/route.ts
Normal file
87
app/api/houses/route.ts
Normal file
@@ -0,0 +1,87 @@
|
|||||||
|
import { NextResponse } from "next/server";
|
||||||
|
import { auth } from "@/lib/auth";
|
||||||
|
import { houseService } from "@/services/houses/house.service";
|
||||||
|
|
||||||
|
export async function GET(request: Request) {
|
||||||
|
try {
|
||||||
|
const session = await auth();
|
||||||
|
|
||||||
|
if (!session?.user?.id) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: "Vous devez être connecté" },
|
||||||
|
{ status: 401 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const { searchParams } = new URL(request.url);
|
||||||
|
const search = searchParams.get("search");
|
||||||
|
const include = searchParams.get("include")?.split(",") || [];
|
||||||
|
|
||||||
|
const includeOptions: {
|
||||||
|
memberships?: {
|
||||||
|
include: {
|
||||||
|
user: {
|
||||||
|
select: {
|
||||||
|
id: boolean;
|
||||||
|
username: boolean;
|
||||||
|
avatar: boolean;
|
||||||
|
score?: boolean;
|
||||||
|
level?: boolean;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
};
|
||||||
|
};
|
||||||
|
creator?: {
|
||||||
|
select: {
|
||||||
|
id: boolean;
|
||||||
|
username: boolean;
|
||||||
|
avatar: boolean;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
} = {};
|
||||||
|
if (include.includes("members")) {
|
||||||
|
includeOptions.memberships = {
|
||||||
|
include: {
|
||||||
|
user: {
|
||||||
|
select: {
|
||||||
|
id: true,
|
||||||
|
username: true,
|
||||||
|
avatar: true,
|
||||||
|
score: true,
|
||||||
|
level: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if (include.includes("creator")) {
|
||||||
|
includeOptions.creator = {
|
||||||
|
select: {
|
||||||
|
id: true,
|
||||||
|
username: true,
|
||||||
|
avatar: true,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
let houses;
|
||||||
|
if (search) {
|
||||||
|
houses = await houseService.searchHouses(search, {
|
||||||
|
include: includeOptions,
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
houses = await houseService.getAllHouses({
|
||||||
|
include: includeOptions,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return NextResponse.json(houses);
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error fetching houses:", error);
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: "Erreur lors de la récupération des maisons" },
|
||||||
|
{ status: 500 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
23
app/api/invitations/pending-count/route.ts
Normal file
23
app/api/invitations/pending-count/route.ts
Normal file
@@ -0,0 +1,23 @@
|
|||||||
|
import { NextResponse } from "next/server";
|
||||||
|
import { auth } from "@/lib/auth";
|
||||||
|
import { houseService } from "@/services/houses/house.service";
|
||||||
|
|
||||||
|
export async function GET() {
|
||||||
|
try {
|
||||||
|
const session = await auth();
|
||||||
|
|
||||||
|
if (!session?.user?.id) {
|
||||||
|
return NextResponse.json({ count: 0 });
|
||||||
|
}
|
||||||
|
|
||||||
|
// Compter les invitations ET les demandes d'adhésion en attente
|
||||||
|
const count = await houseService.getPendingHouseActionsCount(
|
||||||
|
session.user.id
|
||||||
|
);
|
||||||
|
|
||||||
|
return NextResponse.json({ count });
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error fetching pending house actions count:", error);
|
||||||
|
return NextResponse.json({ count: 0 });
|
||||||
|
}
|
||||||
|
}
|
||||||
36
app/api/invitations/route.ts
Normal file
36
app/api/invitations/route.ts
Normal file
@@ -0,0 +1,36 @@
|
|||||||
|
import { NextResponse } from "next/server";
|
||||||
|
import { auth } from "@/lib/auth";
|
||||||
|
import { houseService } from "@/services/houses/house.service";
|
||||||
|
|
||||||
|
export async function GET(request: Request) {
|
||||||
|
try {
|
||||||
|
const session = await auth();
|
||||||
|
|
||||||
|
if (!session?.user?.id) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: "Vous devez être connecté" },
|
||||||
|
{ status: 401 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const { searchParams } = new URL(request.url);
|
||||||
|
const statusParam = searchParams.get("status");
|
||||||
|
const status = statusParam && ["PENDING", "ACCEPTED", "REJECTED", "CANCELLED"].includes(statusParam)
|
||||||
|
? (statusParam as "PENDING" | "ACCEPTED" | "REJECTED" | "CANCELLED")
|
||||||
|
: undefined;
|
||||||
|
|
||||||
|
const invitations = await houseService.getUserInvitations(
|
||||||
|
session.user.id,
|
||||||
|
status
|
||||||
|
);
|
||||||
|
|
||||||
|
return NextResponse.json(invitations);
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error fetching invitations:", error);
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: "Erreur lors de la récupération des invitations" },
|
||||||
|
{ status: 500 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
17
app/api/leaderboard/houses/route.ts
Normal file
17
app/api/leaderboard/houses/route.ts
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
import { NextResponse } from "next/server";
|
||||||
|
import { userStatsService } from "@/services/users/user-stats.service";
|
||||||
|
|
||||||
|
export async function GET() {
|
||||||
|
try {
|
||||||
|
const leaderboard = await userStatsService.getHouseLeaderboard(10);
|
||||||
|
|
||||||
|
return NextResponse.json(leaderboard);
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error fetching house leaderboard:", error);
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: "Erreur lors de la récupération du leaderboard des maisons" },
|
||||||
|
{ status: 500 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@@ -1,29 +1,9 @@
|
|||||||
import { NextResponse } from "next/server";
|
import { NextResponse } from "next/server";
|
||||||
import { prisma } from "@/lib/prisma";
|
import { userStatsService } from "@/services/users/user-stats.service";
|
||||||
|
|
||||||
export async function GET() {
|
export async function GET() {
|
||||||
try {
|
try {
|
||||||
const users = await prisma.user.findMany({
|
const leaderboard = await userStatsService.getLeaderboard(10);
|
||||||
orderBy: {
|
|
||||||
score: "desc",
|
|
||||||
},
|
|
||||||
take: 10,
|
|
||||||
select: {
|
|
||||||
id: true,
|
|
||||||
username: true,
|
|
||||||
score: true,
|
|
||||||
level: true,
|
|
||||||
avatar: true,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
const leaderboard = users.map((user: { id: string; username: string; score: number; level: number; avatar: string | null }, index: number) => ({
|
|
||||||
rank: index + 1,
|
|
||||||
username: user.username,
|
|
||||||
score: user.score,
|
|
||||||
level: user.level,
|
|
||||||
avatar: user.avatar,
|
|
||||||
}));
|
|
||||||
|
|
||||||
return NextResponse.json(leaderboard);
|
return NextResponse.json(leaderboard);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
@@ -34,4 +14,3 @@ export async function GET() {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,12 +1,10 @@
|
|||||||
import { NextResponse } from "next/server";
|
import { NextResponse } from "next/server";
|
||||||
import { prisma } from "@/lib/prisma";
|
import { sitePreferencesService } from "@/services/preferences/site-preferences.service";
|
||||||
|
|
||||||
export async function GET() {
|
export async function GET() {
|
||||||
try {
|
try {
|
||||||
// Récupérer les préférences globales du site (pas besoin d'authentification)
|
// Récupérer les préférences globales du site (pas besoin d'authentification)
|
||||||
let sitePreferences = await prisma.sitePreferences.findUnique({
|
const sitePreferences = await sitePreferencesService.getSitePreferences();
|
||||||
where: { id: "global" },
|
|
||||||
});
|
|
||||||
|
|
||||||
// Si elles n'existent pas, retourner des valeurs par défaut
|
// Si elles n'existent pas, retourner des valeurs par défaut
|
||||||
if (!sitePreferences) {
|
if (!sitePreferences) {
|
||||||
@@ -14,6 +12,9 @@ export async function GET() {
|
|||||||
homeBackground: null,
|
homeBackground: null,
|
||||||
eventsBackground: null,
|
eventsBackground: null,
|
||||||
leaderboardBackground: null,
|
leaderboardBackground: null,
|
||||||
|
challengesBackground: null,
|
||||||
|
profileBackground: null,
|
||||||
|
houseBackground: null,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -21,6 +22,9 @@ export async function GET() {
|
|||||||
homeBackground: sitePreferences.homeBackground,
|
homeBackground: sitePreferences.homeBackground,
|
||||||
eventsBackground: sitePreferences.eventsBackground,
|
eventsBackground: sitePreferences.eventsBackground,
|
||||||
leaderboardBackground: sitePreferences.leaderboardBackground,
|
leaderboardBackground: sitePreferences.leaderboardBackground,
|
||||||
|
challengesBackground: sitePreferences.challengesBackground,
|
||||||
|
profileBackground: sitePreferences.profileBackground,
|
||||||
|
houseBackground: sitePreferences.houseBackground,
|
||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("Error fetching preferences:", error);
|
console.error("Error fetching preferences:", error);
|
||||||
@@ -29,6 +33,9 @@ export async function GET() {
|
|||||||
homeBackground: null,
|
homeBackground: null,
|
||||||
eventsBackground: null,
|
eventsBackground: null,
|
||||||
leaderboardBackground: null,
|
leaderboardBackground: null,
|
||||||
|
challengesBackground: null,
|
||||||
|
profileBackground: null,
|
||||||
|
houseBackground: null,
|
||||||
},
|
},
|
||||||
{ status: 200 }
|
{ status: 200 }
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -16,7 +16,10 @@ export async function POST(request: Request) {
|
|||||||
const file = formData.get("file") as File;
|
const file = formData.get("file") as File;
|
||||||
|
|
||||||
if (!file) {
|
if (!file) {
|
||||||
return NextResponse.json({ error: "Aucun fichier fourni" }, { status: 400 });
|
return NextResponse.json(
|
||||||
|
{ error: "Aucun fichier fourni" },
|
||||||
|
{ status: 400 }
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Vérifier le type de fichier
|
// Vérifier le type de fichier
|
||||||
@@ -36,24 +39,25 @@ export async function POST(request: Request) {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Créer le dossier uploads s'il n'existe pas
|
// Créer le dossier uploads/avatars s'il n'existe pas
|
||||||
const uploadsDir = join(process.cwd(), "public", "uploads");
|
const uploadsDir = join(process.cwd(), "public", "uploads");
|
||||||
if (!existsSync(uploadsDir)) {
|
const avatarsDir = join(uploadsDir, "avatars");
|
||||||
await mkdir(uploadsDir, { recursive: true });
|
if (!existsSync(avatarsDir)) {
|
||||||
|
await mkdir(avatarsDir, { recursive: true });
|
||||||
}
|
}
|
||||||
|
|
||||||
// Générer un nom de fichier unique avec l'ID utilisateur
|
// Générer un nom de fichier unique avec l'ID utilisateur
|
||||||
const timestamp = Date.now();
|
const timestamp = Date.now();
|
||||||
const filename = `avatar-${session.user.id}-${timestamp}-${file.name}`;
|
const filename = `avatar-${session.user.id}-${timestamp}-${file.name}`;
|
||||||
const filepath = join(uploadsDir, filename);
|
const filepath = join(avatarsDir, filename);
|
||||||
|
|
||||||
// Convertir le fichier en buffer et l'écrire
|
// Convertir le fichier en buffer et l'écrire
|
||||||
const bytes = await file.arrayBuffer();
|
const bytes = await file.arrayBuffer();
|
||||||
const buffer = Buffer.from(bytes);
|
const buffer = Buffer.from(bytes);
|
||||||
await writeFile(filepath, buffer);
|
await writeFile(filepath, buffer);
|
||||||
|
|
||||||
// Retourner l'URL de l'image
|
// Retourner l'URL de l'image via l'API
|
||||||
const imageUrl = `/uploads/${filename}`;
|
const imageUrl = `/api/avatars/${filename}`;
|
||||||
return NextResponse.json({ url: imageUrl });
|
return NextResponse.json({ url: imageUrl });
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("Error uploading avatar:", error);
|
console.error("Error uploading avatar:", error);
|
||||||
@@ -63,4 +67,3 @@ export async function POST(request: Request) {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,80 +0,0 @@
|
|||||||
import { NextResponse } from "next/server";
|
|
||||||
import { auth } from "@/lib/auth";
|
|
||||||
import { prisma } from "@/lib/prisma";
|
|
||||||
import bcrypt from "bcryptjs";
|
|
||||||
|
|
||||||
export async function PUT(request: Request) {
|
|
||||||
try {
|
|
||||||
const session = await auth();
|
|
||||||
|
|
||||||
if (!session?.user) {
|
|
||||||
return NextResponse.json({ error: "Non authentifié" }, { status: 401 });
|
|
||||||
}
|
|
||||||
|
|
||||||
const body = await request.json();
|
|
||||||
const { currentPassword, newPassword, confirmPassword } = body;
|
|
||||||
|
|
||||||
// Validation
|
|
||||||
if (!currentPassword || !newPassword || !confirmPassword) {
|
|
||||||
return NextResponse.json(
|
|
||||||
{ error: "Tous les champs sont requis" },
|
|
||||||
{ status: 400 }
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (newPassword.length < 6) {
|
|
||||||
return NextResponse.json(
|
|
||||||
{ error: "Le nouveau mot de passe doit contenir au moins 6 caractères" },
|
|
||||||
{ status: 400 }
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (newPassword !== confirmPassword) {
|
|
||||||
return NextResponse.json(
|
|
||||||
{ error: "Les mots de passe ne correspondent pas" },
|
|
||||||
{ status: 400 }
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Récupérer l'utilisateur avec le mot de passe
|
|
||||||
const user = await prisma.user.findUnique({
|
|
||||||
where: { id: session.user.id },
|
|
||||||
select: { password: true },
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!user) {
|
|
||||||
return NextResponse.json(
|
|
||||||
{ error: "Utilisateur non trouvé" },
|
|
||||||
{ status: 404 }
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Vérifier l'ancien mot de passe
|
|
||||||
const isPasswordValid = await bcrypt.compare(currentPassword, user.password);
|
|
||||||
|
|
||||||
if (!isPasswordValid) {
|
|
||||||
return NextResponse.json(
|
|
||||||
{ error: "Mot de passe actuel incorrect" },
|
|
||||||
{ status: 400 }
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Hasher le nouveau mot de passe
|
|
||||||
const hashedPassword = await bcrypt.hash(newPassword, 10);
|
|
||||||
|
|
||||||
// Mettre à jour le mot de passe
|
|
||||||
await prisma.user.update({
|
|
||||||
where: { id: session.user.id },
|
|
||||||
data: { password: hashedPassword },
|
|
||||||
});
|
|
||||||
|
|
||||||
return NextResponse.json({ message: "Mot de passe modifié avec succès" });
|
|
||||||
} catch (error) {
|
|
||||||
console.error("Error updating password:", error);
|
|
||||||
return NextResponse.json(
|
|
||||||
{ error: "Erreur lors de la modification du mot de passe" },
|
|
||||||
{ status: 500 }
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
import { NextResponse } from "next/server";
|
import { NextResponse } from "next/server";
|
||||||
import { auth } from "@/lib/auth";
|
import { auth } from "@/lib/auth";
|
||||||
import { prisma } from "@/lib/prisma";
|
import { userService } from "@/services/users/user.service";
|
||||||
|
|
||||||
export async function GET() {
|
export async function GET() {
|
||||||
try {
|
try {
|
||||||
@@ -10,25 +10,27 @@ export async function GET() {
|
|||||||
return NextResponse.json({ error: "Non authentifié" }, { status: 401 });
|
return NextResponse.json({ error: "Non authentifié" }, { status: 401 });
|
||||||
}
|
}
|
||||||
|
|
||||||
const user = await prisma.user.findUnique({
|
const user = await userService.getUserById(session.user.id, {
|
||||||
where: { id: session.user.id },
|
id: true,
|
||||||
select: {
|
email: true,
|
||||||
id: true,
|
username: true,
|
||||||
email: true,
|
avatar: true,
|
||||||
username: true,
|
bio: true,
|
||||||
avatar: true,
|
characterClass: true,
|
||||||
hp: true,
|
hp: true,
|
||||||
maxHp: true,
|
maxHp: true,
|
||||||
xp: true,
|
xp: true,
|
||||||
maxXp: true,
|
maxXp: true,
|
||||||
level: true,
|
level: true,
|
||||||
score: true,
|
score: true,
|
||||||
createdAt: true,
|
createdAt: true,
|
||||||
},
|
|
||||||
});
|
});
|
||||||
|
|
||||||
if (!user) {
|
if (!user) {
|
||||||
return NextResponse.json({ error: "Utilisateur non trouvé" }, { status: 404 });
|
return NextResponse.json(
|
||||||
|
{ error: "Utilisateur non trouvé" },
|
||||||
|
{ status: 404 }
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
return NextResponse.json(user);
|
return NextResponse.json(user);
|
||||||
@@ -40,83 +42,3 @@ export async function GET() {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function PUT(request: Request) {
|
|
||||||
try {
|
|
||||||
const session = await auth();
|
|
||||||
|
|
||||||
if (!session?.user) {
|
|
||||||
return NextResponse.json({ error: "Non authentifié" }, { status: 401 });
|
|
||||||
}
|
|
||||||
|
|
||||||
const body = await request.json();
|
|
||||||
const { username, avatar } = body;
|
|
||||||
|
|
||||||
// Validation
|
|
||||||
if (username !== undefined) {
|
|
||||||
if (typeof username !== "string" || username.trim().length === 0) {
|
|
||||||
return NextResponse.json(
|
|
||||||
{ error: "Le nom d'utilisateur ne peut pas être vide" },
|
|
||||||
{ status: 400 }
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (username.length < 3 || username.length > 20) {
|
|
||||||
return NextResponse.json(
|
|
||||||
{ error: "Le nom d'utilisateur doit contenir entre 3 et 20 caractères" },
|
|
||||||
{ status: 400 }
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Vérifier si le username est déjà pris par un autre utilisateur
|
|
||||||
const existingUser = await prisma.user.findFirst({
|
|
||||||
where: {
|
|
||||||
username: username.trim(),
|
|
||||||
NOT: { id: session.user.id },
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
if (existingUser) {
|
|
||||||
return NextResponse.json(
|
|
||||||
{ error: "Ce nom d'utilisateur est déjà pris" },
|
|
||||||
{ status: 400 }
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Mettre à jour l'utilisateur
|
|
||||||
const updateData: { username?: string; avatar?: string | null } = {};
|
|
||||||
if (username !== undefined) {
|
|
||||||
updateData.username = username.trim();
|
|
||||||
}
|
|
||||||
if (avatar !== undefined) {
|
|
||||||
updateData.avatar = avatar || null;
|
|
||||||
}
|
|
||||||
|
|
||||||
const updatedUser = await prisma.user.update({
|
|
||||||
where: { id: session.user.id },
|
|
||||||
data: updateData,
|
|
||||||
select: {
|
|
||||||
id: true,
|
|
||||||
email: true,
|
|
||||||
username: true,
|
|
||||||
avatar: true,
|
|
||||||
hp: true,
|
|
||||||
maxHp: true,
|
|
||||||
xp: true,
|
|
||||||
maxXp: true,
|
|
||||||
level: true,
|
|
||||||
score: true,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
return NextResponse.json(updatedUser);
|
|
||||||
} catch (error) {
|
|
||||||
console.error("Error updating profile:", error);
|
|
||||||
return NextResponse.json(
|
|
||||||
{ error: "Erreur lors de la mise à jour du profil" },
|
|
||||||
{ status: 500 }
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|||||||
63
app/api/register/avatar/route.ts
Normal file
63
app/api/register/avatar/route.ts
Normal file
@@ -0,0 +1,63 @@
|
|||||||
|
import { NextResponse } from "next/server";
|
||||||
|
import { writeFile, mkdir } from "fs/promises";
|
||||||
|
import { join } from "path";
|
||||||
|
import { existsSync } from "fs";
|
||||||
|
|
||||||
|
export async function POST(request: Request) {
|
||||||
|
try {
|
||||||
|
const formData = await request.formData();
|
||||||
|
const file = formData.get("file") as File;
|
||||||
|
|
||||||
|
if (!file) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: "Aucun fichier fourni" },
|
||||||
|
{ status: 400 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Vérifier le type de fichier
|
||||||
|
if (!file.type.startsWith("image/")) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: "Le fichier doit être une image" },
|
||||||
|
{ status: 400 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Limiter la taille (par exemple 5MB)
|
||||||
|
const maxSize = 5 * 1024 * 1024; // 5MB
|
||||||
|
if (file.size > maxSize) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: "L'image est trop grande (max 5MB)" },
|
||||||
|
{ status: 400 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Créer le dossier uploads/avatars s'il n'existe pas
|
||||||
|
const uploadsDir = join(process.cwd(), "public", "uploads");
|
||||||
|
const avatarsDir = join(uploadsDir, "avatars");
|
||||||
|
if (!existsSync(avatarsDir)) {
|
||||||
|
await mkdir(avatarsDir, { recursive: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
// Générer un nom de fichier unique avec timestamp
|
||||||
|
const timestamp = Date.now();
|
||||||
|
const randomId = Math.random().toString(36).substring(2, 9);
|
||||||
|
const filename = `avatar-register-${timestamp}-${randomId}-${file.name}`;
|
||||||
|
const filepath = join(avatarsDir, filename);
|
||||||
|
|
||||||
|
// Convertir le fichier en buffer et l'écrire
|
||||||
|
const bytes = await file.arrayBuffer();
|
||||||
|
const buffer = Buffer.from(bytes);
|
||||||
|
await writeFile(filepath, buffer);
|
||||||
|
|
||||||
|
// Retourner l'URL de l'image via l'API
|
||||||
|
const imageUrl = `/api/avatars/${filename}`;
|
||||||
|
return NextResponse.json({ url: imageUrl });
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error uploading avatar:", error);
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: "Erreur lors de l'upload de l'avatar" },
|
||||||
|
{ status: 500 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
47
app/api/register/complete/route.ts
Normal file
47
app/api/register/complete/route.ts
Normal file
@@ -0,0 +1,47 @@
|
|||||||
|
import { NextResponse } from "next/server";
|
||||||
|
import { userService } from "@/services/users/user.service";
|
||||||
|
import {
|
||||||
|
ValidationError,
|
||||||
|
NotFoundError,
|
||||||
|
ConflictError,
|
||||||
|
} from "@/services/errors";
|
||||||
|
|
||||||
|
export async function POST(request: Request) {
|
||||||
|
try {
|
||||||
|
const body = await request.json();
|
||||||
|
const { userId, username, avatar, bio, characterClass } = body;
|
||||||
|
|
||||||
|
if (!userId) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: "ID utilisateur requis" },
|
||||||
|
{ status: 400 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const updatedUser = await userService.validateAndCompleteRegistration(
|
||||||
|
userId,
|
||||||
|
{ username, avatar, bio, characterClass }
|
||||||
|
);
|
||||||
|
|
||||||
|
return NextResponse.json({
|
||||||
|
message: "Profil finalisé avec succès",
|
||||||
|
userId: updatedUser.id,
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error completing registration:", error);
|
||||||
|
|
||||||
|
if (error instanceof ValidationError || error instanceof ConflictError) {
|
||||||
|
return NextResponse.json({ error: error.message }, { status: 400 });
|
||||||
|
}
|
||||||
|
if (error instanceof NotFoundError) {
|
||||||
|
return NextResponse.json({ error: error.message }, { status: 404 });
|
||||||
|
}
|
||||||
|
|
||||||
|
return NextResponse.json(
|
||||||
|
{
|
||||||
|
error: `Erreur lors de la finalisation de l'inscription: ${error instanceof Error ? error.message : "Erreur inconnue"}`,
|
||||||
|
},
|
||||||
|
{ status: 500 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,50 +1,19 @@
|
|||||||
import { NextResponse } from "next/server";
|
import { NextResponse } from "next/server";
|
||||||
import { prisma } from "@/lib/prisma";
|
import { userService } from "@/services/users/user.service";
|
||||||
import bcrypt from "bcryptjs";
|
import { ValidationError, ConflictError } from "@/services/errors";
|
||||||
|
|
||||||
export async function POST(request: Request) {
|
export async function POST(request: Request) {
|
||||||
try {
|
try {
|
||||||
const body = await request.json();
|
const body = await request.json();
|
||||||
const { email, username, password } = body;
|
const { email, username, password, bio, characterClass, avatar } = body;
|
||||||
|
|
||||||
if (!email || !username || !password) {
|
const user = await userService.validateAndCreateUser({
|
||||||
return NextResponse.json(
|
email,
|
||||||
{ error: "Tous les champs sont requis" },
|
username,
|
||||||
{ status: 400 }
|
password,
|
||||||
);
|
bio,
|
||||||
}
|
characterClass,
|
||||||
|
avatar,
|
||||||
if (password.length < 6) {
|
|
||||||
return NextResponse.json(
|
|
||||||
{ error: "Le mot de passe doit contenir au moins 6 caractères" },
|
|
||||||
{ status: 400 }
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Vérifier si l'email existe déjà
|
|
||||||
const existingUser = await prisma.user.findFirst({
|
|
||||||
where: {
|
|
||||||
OR: [{ email }, { username }],
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
if (existingUser) {
|
|
||||||
return NextResponse.json(
|
|
||||||
{ error: "Cet email ou nom d'utilisateur est déjà utilisé" },
|
|
||||||
{ status: 400 }
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Hasher le mot de passe
|
|
||||||
const hashedPassword = await bcrypt.hash(password, 10);
|
|
||||||
|
|
||||||
// Créer l'utilisateur
|
|
||||||
const user = await prisma.user.create({
|
|
||||||
data: {
|
|
||||||
email,
|
|
||||||
username,
|
|
||||||
password: hashedPassword,
|
|
||||||
},
|
|
||||||
});
|
});
|
||||||
|
|
||||||
return NextResponse.json(
|
return NextResponse.json(
|
||||||
@@ -53,10 +22,14 @@ export async function POST(request: Request) {
|
|||||||
);
|
);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("Registration error:", error);
|
console.error("Registration error:", error);
|
||||||
|
|
||||||
|
if (error instanceof ValidationError || error instanceof ConflictError) {
|
||||||
|
return NextResponse.json({ error: error.message }, { status: 400 });
|
||||||
|
}
|
||||||
|
|
||||||
return NextResponse.json(
|
return NextResponse.json(
|
||||||
{ error: "Une erreur est survenue lors de l'inscription" },
|
{ error: "Une erreur est survenue lors de l'inscription" },
|
||||||
{ status: 500 }
|
{ status: 500 }
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import { NextResponse } from "next/server";
|
import { NextResponse } from "next/server";
|
||||||
import { auth } from "@/lib/auth";
|
import { auth } from "@/lib/auth";
|
||||||
import { prisma } from "@/lib/prisma";
|
import { userService } from "@/services/users/user.service";
|
||||||
|
|
||||||
export async function GET(
|
export async function GET(
|
||||||
request: Request,
|
request: Request,
|
||||||
@@ -19,23 +19,23 @@ export async function GET(
|
|||||||
return NextResponse.json({ error: "Accès refusé" }, { status: 403 });
|
return NextResponse.json({ error: "Accès refusé" }, { status: 403 });
|
||||||
}
|
}
|
||||||
|
|
||||||
const user = await prisma.user.findUnique({
|
const user = await userService.getUserById(id, {
|
||||||
where: { id },
|
id: true,
|
||||||
select: {
|
username: true,
|
||||||
id: true,
|
avatar: true,
|
||||||
username: true,
|
hp: true,
|
||||||
avatar: true,
|
maxHp: true,
|
||||||
hp: true,
|
xp: true,
|
||||||
maxHp: true,
|
maxXp: true,
|
||||||
xp: true,
|
level: true,
|
||||||
maxXp: true,
|
score: true,
|
||||||
level: true,
|
|
||||||
score: true,
|
|
||||||
},
|
|
||||||
});
|
});
|
||||||
|
|
||||||
if (!user) {
|
if (!user) {
|
||||||
return NextResponse.json({ error: "Utilisateur non trouvé" }, { status: 404 });
|
return NextResponse.json(
|
||||||
|
{ error: "Utilisateur non trouvé" },
|
||||||
|
{ status: 404 }
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
return NextResponse.json(user);
|
return NextResponse.json(user);
|
||||||
@@ -47,4 +47,3 @@ export async function GET(
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
43
app/api/users/route.ts
Normal file
43
app/api/users/route.ts
Normal file
@@ -0,0 +1,43 @@
|
|||||||
|
import { NextResponse } from "next/server";
|
||||||
|
import { auth } from "@/lib/auth";
|
||||||
|
import { userService } from "@/services/users/user.service";
|
||||||
|
|
||||||
|
export async function GET() {
|
||||||
|
try {
|
||||||
|
const session = await auth();
|
||||||
|
|
||||||
|
if (!session?.user?.id) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: "Vous devez être connecté" },
|
||||||
|
{ status: 401 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Récupérer tous les utilisateurs (pour sélectionner qui défier)
|
||||||
|
const users = await userService.getAllUsers({
|
||||||
|
orderBy: {
|
||||||
|
username: "asc",
|
||||||
|
},
|
||||||
|
select: {
|
||||||
|
id: true,
|
||||||
|
username: true,
|
||||||
|
avatar: true,
|
||||||
|
score: true,
|
||||||
|
level: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
// Filtrer l'utilisateur actuel
|
||||||
|
const otherUsers = users.filter((user) => user.id !== session.user.id);
|
||||||
|
|
||||||
|
return NextResponse.json(otherUsers);
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error fetching users:", error);
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: "Erreur lors de la récupération des utilisateurs" },
|
||||||
|
{ status: 500 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
55
app/challenges/page.tsx
Normal file
55
app/challenges/page.tsx
Normal file
@@ -0,0 +1,55 @@
|
|||||||
|
import { redirect } from "next/navigation";
|
||||||
|
import { auth } from "@/lib/auth";
|
||||||
|
import { getBackgroundImage } from "@/lib/preferences";
|
||||||
|
import NavigationWrapper from "@/components/navigation/NavigationWrapper";
|
||||||
|
import ChallengesSection from "@/components/challenges/ChallengesSection";
|
||||||
|
import { challengeService } from "@/services/challenges/challenge.service";
|
||||||
|
import { userService } from "@/services/users/user.service";
|
||||||
|
|
||||||
|
export const dynamic = "force-dynamic";
|
||||||
|
|
||||||
|
export default async function ChallengesPage() {
|
||||||
|
const session = await auth();
|
||||||
|
|
||||||
|
if (!session?.user) {
|
||||||
|
redirect("/login");
|
||||||
|
}
|
||||||
|
|
||||||
|
const [challengesRaw, users, backgroundImage] = await Promise.all([
|
||||||
|
challengeService.getUserChallenges(session.user.id),
|
||||||
|
userService
|
||||||
|
.getAllUsers({
|
||||||
|
orderBy: {
|
||||||
|
username: "asc",
|
||||||
|
},
|
||||||
|
select: {
|
||||||
|
id: true,
|
||||||
|
username: true,
|
||||||
|
avatar: true,
|
||||||
|
score: true,
|
||||||
|
level: true,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
.then((users) => users.filter((user) => user.id !== session.user.id)),
|
||||||
|
getBackgroundImage("challenges", "/got-2.jpg"),
|
||||||
|
]);
|
||||||
|
|
||||||
|
// Convertir les dates Date en string pour correspondre au type attendu par le composant
|
||||||
|
const challenges = challengesRaw.map((challenge) => ({
|
||||||
|
...challenge,
|
||||||
|
createdAt: challenge.createdAt.toISOString(),
|
||||||
|
acceptedAt: challenge.acceptedAt?.toISOString() ?? null,
|
||||||
|
completedAt: challenge.completedAt?.toISOString() ?? null,
|
||||||
|
}));
|
||||||
|
|
||||||
|
return (
|
||||||
|
<main className="min-h-screen bg-black relative">
|
||||||
|
<NavigationWrapper />
|
||||||
|
<ChallengesSection
|
||||||
|
initialChallenges={challenges}
|
||||||
|
initialUsers={users}
|
||||||
|
backgroundImage={backgroundImage}
|
||||||
|
/>
|
||||||
|
</main>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,12 +1,48 @@
|
|||||||
import Navigation from "@/components/Navigation";
|
import NavigationWrapper from "@/components/navigation/NavigationWrapper";
|
||||||
import EventsPageSection from "@/components/EventsPageSection";
|
import EventsPageSection from "@/components/events/EventsPageSection";
|
||||||
|
import { eventService } from "@/services/events/event.service";
|
||||||
|
import { eventRegistrationService } from "@/services/events/event-registration.service";
|
||||||
|
import { getBackgroundImage } from "@/lib/preferences";
|
||||||
|
import { auth } from "@/lib/auth";
|
||||||
|
|
||||||
|
export const dynamic = "force-dynamic";
|
||||||
|
|
||||||
|
export default async function EventsPage() {
|
||||||
|
// Paralléliser les appels indépendants
|
||||||
|
const session = await auth();
|
||||||
|
|
||||||
|
const [events, backgroundImage, allRegistrations] = await Promise.all([
|
||||||
|
eventService.getAllEvents({
|
||||||
|
orderBy: { date: "desc" },
|
||||||
|
}),
|
||||||
|
getBackgroundImage("events", "/got-2.jpg"),
|
||||||
|
session?.user?.id
|
||||||
|
? eventRegistrationService.getUserRegistrations(session.user.id)
|
||||||
|
: Promise.resolve([]),
|
||||||
|
]);
|
||||||
|
|
||||||
|
// Sérialiser les dates pour le client
|
||||||
|
const serializedEvents = events.map((event) => ({
|
||||||
|
...event,
|
||||||
|
date: event.date.toISOString(),
|
||||||
|
createdAt: event.createdAt.toISOString(),
|
||||||
|
updatedAt: event.updatedAt.toISOString(),
|
||||||
|
}));
|
||||||
|
|
||||||
|
// Construire le map des inscriptions
|
||||||
|
const initialRegistrations: Record<string, boolean> = {};
|
||||||
|
allRegistrations.forEach((reg) => {
|
||||||
|
initialRegistrations[reg.eventId] = true;
|
||||||
|
});
|
||||||
|
|
||||||
export default function EventsPage() {
|
|
||||||
return (
|
return (
|
||||||
<main className="min-h-screen bg-black relative">
|
<main className="min-h-screen bg-black relative">
|
||||||
<Navigation />
|
<NavigationWrapper />
|
||||||
<EventsPageSection />
|
<EventsPageSection
|
||||||
|
events={serializedEvents}
|
||||||
|
backgroundImage={backgroundImage}
|
||||||
|
initialRegistrations={initialRegistrations}
|
||||||
|
/>
|
||||||
</main>
|
</main>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
249
app/feedback/[eventId]/FeedbackPageClient.tsx
Normal file
249
app/feedback/[eventId]/FeedbackPageClient.tsx
Normal file
@@ -0,0 +1,249 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useState, useEffect, useTransition, type FormEvent } from "react";
|
||||||
|
import { useSession } from "next-auth/react";
|
||||||
|
import { useRouter, useParams } from "next/navigation";
|
||||||
|
import Navigation from "@/components/navigation/Navigation";
|
||||||
|
import { createFeedback } from "@/actions/events/feedback";
|
||||||
|
import {
|
||||||
|
StarRating,
|
||||||
|
Textarea,
|
||||||
|
Button,
|
||||||
|
Alert,
|
||||||
|
Card,
|
||||||
|
BackgroundSection,
|
||||||
|
SectionTitle,
|
||||||
|
} from "@/components/ui";
|
||||||
|
|
||||||
|
interface Event {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
date: string;
|
||||||
|
description: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface Feedback {
|
||||||
|
id: string;
|
||||||
|
rating: number;
|
||||||
|
comment: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface FeedbackPageClientProps {
|
||||||
|
backgroundImage: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function FeedbackPageClient({
|
||||||
|
backgroundImage,
|
||||||
|
}: FeedbackPageClientProps) {
|
||||||
|
const { status } = useSession();
|
||||||
|
const router = useRouter();
|
||||||
|
const params = useParams();
|
||||||
|
const eventId = params?.eventId as string;
|
||||||
|
|
||||||
|
const [event, setEvent] = useState<Event | null>(null);
|
||||||
|
const [existingFeedback, setExistingFeedback] = useState<Feedback | null>(
|
||||||
|
null
|
||||||
|
);
|
||||||
|
const [loading, setLoading] = useState(true);
|
||||||
|
const [submitting, setSubmitting] = useState(false);
|
||||||
|
const [error, setError] = useState("");
|
||||||
|
const [success, setSuccess] = useState(false);
|
||||||
|
const [, startTransition] = useTransition();
|
||||||
|
|
||||||
|
const [rating, setRating] = useState(0);
|
||||||
|
const [comment, setComment] = useState("");
|
||||||
|
|
||||||
|
const fetchEventAndFeedback = async () => {
|
||||||
|
try {
|
||||||
|
// Récupérer l'événement
|
||||||
|
const eventResponse = await fetch(`/api/events/${eventId}`);
|
||||||
|
if (!eventResponse.ok) {
|
||||||
|
setError("Événement introuvable");
|
||||||
|
setLoading(false);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const eventData = await eventResponse.json();
|
||||||
|
setEvent(eventData);
|
||||||
|
|
||||||
|
// Récupérer le feedback existant si disponible
|
||||||
|
const feedbackResponse = await fetch(`/api/feedback/${eventId}`);
|
||||||
|
if (feedbackResponse.ok) {
|
||||||
|
const feedbackData = await feedbackResponse.json();
|
||||||
|
if (feedbackData.feedback) {
|
||||||
|
setExistingFeedback(feedbackData.feedback);
|
||||||
|
setRating(feedbackData.feedback.rating);
|
||||||
|
setComment(feedbackData.feedback.comment || "");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
setError("Erreur lors du chargement des données");
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (status === "unauthenticated") {
|
||||||
|
router.push(`/login?redirect=/feedback/${eventId}`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (status === "authenticated" && eventId) {
|
||||||
|
fetchEventAndFeedback();
|
||||||
|
}
|
||||||
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
|
}, [status, eventId, router]);
|
||||||
|
|
||||||
|
const handleSubmit = async (e: FormEvent) => {
|
||||||
|
e.preventDefault();
|
||||||
|
setError("");
|
||||||
|
setSuccess(false);
|
||||||
|
|
||||||
|
if (rating === 0) {
|
||||||
|
setError("Veuillez sélectionner une note");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
setSubmitting(true);
|
||||||
|
|
||||||
|
startTransition(async () => {
|
||||||
|
try {
|
||||||
|
const result = await createFeedback(eventId, {
|
||||||
|
rating,
|
||||||
|
comment: comment.trim() || null,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!result.success) {
|
||||||
|
setError(result.error || "Erreur lors de l'enregistrement");
|
||||||
|
setSubmitting(false);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
setSuccess(true);
|
||||||
|
if (result.data) {
|
||||||
|
setExistingFeedback({
|
||||||
|
id: result.data.id,
|
||||||
|
rating: result.data.rating,
|
||||||
|
comment: result.data.comment,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Rafraîchir le score dans le header
|
||||||
|
window.dispatchEvent(new Event("refreshUserScore"));
|
||||||
|
|
||||||
|
// Rediriger après 2 secondes
|
||||||
|
setTimeout(() => {
|
||||||
|
router.push("/events");
|
||||||
|
}, 2000);
|
||||||
|
} catch {
|
||||||
|
setError("Erreur lors de l'enregistrement");
|
||||||
|
} finally {
|
||||||
|
setSubmitting(false);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
if (status === "loading" || loading) {
|
||||||
|
return (
|
||||||
|
<main className="min-h-screen bg-black relative">
|
||||||
|
<Navigation />
|
||||||
|
<section className="relative w-full min-h-screen flex flex-col items-center justify-center overflow-hidden pt-24">
|
||||||
|
<div className="text-white">Chargement...</div>
|
||||||
|
</section>
|
||||||
|
</main>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!event) {
|
||||||
|
return (
|
||||||
|
<main className="min-h-screen bg-black relative">
|
||||||
|
<Navigation />
|
||||||
|
<section className="relative w-full min-h-screen flex flex-col items-center justify-center overflow-hidden pt-24">
|
||||||
|
<div className="text-red-400">Événement introuvable</div>
|
||||||
|
</section>
|
||||||
|
</main>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<main className="min-h-screen bg-black relative">
|
||||||
|
<Navigation />
|
||||||
|
<BackgroundSection backgroundImage={backgroundImage} className="pt-24">
|
||||||
|
{/* Feedback Form */}
|
||||||
|
<div className="w-full max-w-2xl mx-auto px-8">
|
||||||
|
<Card variant="dark" className="p-8">
|
||||||
|
<SectionTitle
|
||||||
|
variant="gradient"
|
||||||
|
size="lg"
|
||||||
|
className="mb-2 text-center"
|
||||||
|
>
|
||||||
|
FEEDBACK
|
||||||
|
</SectionTitle>
|
||||||
|
<p className="text-gray-400 text-sm text-center mb-2">
|
||||||
|
{existingFeedback
|
||||||
|
? "Modifier votre feedback pour"
|
||||||
|
: "Donnez votre avis sur"}
|
||||||
|
</p>
|
||||||
|
<p className="text-pixel-gold text-lg font-semibold text-center mb-8">
|
||||||
|
{event.name}
|
||||||
|
</p>
|
||||||
|
|
||||||
|
{success && (
|
||||||
|
<Alert variant="success" className="mb-6">
|
||||||
|
Feedback enregistré avec succès ! Redirection...
|
||||||
|
</Alert>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{error && (
|
||||||
|
<Alert variant="error" className="mb-6">
|
||||||
|
{error}
|
||||||
|
</Alert>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<form onSubmit={handleSubmit} className="space-y-6">
|
||||||
|
{/* Rating */}
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm font-semibold text-gray-300 mb-4 uppercase tracking-wider">
|
||||||
|
Note
|
||||||
|
</label>
|
||||||
|
<StarRating
|
||||||
|
value={rating}
|
||||||
|
onChange={setRating}
|
||||||
|
size="lg"
|
||||||
|
showValue
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Comment */}
|
||||||
|
<Textarea
|
||||||
|
id="comment"
|
||||||
|
label="Commentaire (optionnel)"
|
||||||
|
value={comment}
|
||||||
|
onChange={(e) => setComment(e.target.value)}
|
||||||
|
rows={6}
|
||||||
|
maxLength={1000}
|
||||||
|
showCharCount
|
||||||
|
placeholder="Partagez votre expérience, vos suggestions..."
|
||||||
|
/>
|
||||||
|
|
||||||
|
{/* Submit Button */}
|
||||||
|
<Button
|
||||||
|
type="submit"
|
||||||
|
variant="primary"
|
||||||
|
size="lg"
|
||||||
|
disabled={submitting || rating === 0}
|
||||||
|
className="w-full"
|
||||||
|
>
|
||||||
|
{submitting
|
||||||
|
? "Enregistrement..."
|
||||||
|
: existingFeedback
|
||||||
|
? "Modifier le feedback"
|
||||||
|
: "Envoyer le feedback"}
|
||||||
|
</Button>
|
||||||
|
</form>
|
||||||
|
</Card>
|
||||||
|
</div>
|
||||||
|
</BackgroundSection>
|
||||||
|
</main>
|
||||||
|
);
|
||||||
|
}
|
||||||
17
app/feedback/[eventId]/page.tsx
Normal file
17
app/feedback/[eventId]/page.tsx
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
import FeedbackPageClient from "./FeedbackPageClient";
|
||||||
|
import { getBackgroundImage } from "@/lib/preferences";
|
||||||
|
|
||||||
|
export const dynamic = "force-dynamic";
|
||||||
|
|
||||||
|
interface FeedbackPageProps {
|
||||||
|
params: Promise<{
|
||||||
|
eventId: string;
|
||||||
|
}>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export default async function FeedbackPage({ params }: FeedbackPageProps) {
|
||||||
|
await params; // Ensure params are resolved (Next.js 15 requirement)
|
||||||
|
const backgroundImage = await getBackgroundImage("home", "/got-2.jpg");
|
||||||
|
|
||||||
|
return <FeedbackPageClient backgroundImage={backgroundImage} />;
|
||||||
|
}
|
||||||
5
app/feedback/layout.tsx
Normal file
5
app/feedback/layout.tsx
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
import type { ReactNode } from "react";
|
||||||
|
|
||||||
|
export default function FeedbackLayout({ children }: { children: ReactNode }) {
|
||||||
|
return <>{children}</>;
|
||||||
|
}
|
||||||
175
app/globals.css
175
app/globals.css
@@ -2,10 +2,111 @@
|
|||||||
@tailwind components;
|
@tailwind components;
|
||||||
@tailwind utilities;
|
@tailwind utilities;
|
||||||
|
|
||||||
|
:root {
|
||||||
|
/* Font variables - will be overridden by Next.js Font */
|
||||||
|
--font-orbitron: "Orbitron", sans-serif;
|
||||||
|
--font-rajdhani: "Rajdhani", sans-serif;
|
||||||
|
|
||||||
|
/* Dark cyan theme (default) */
|
||||||
|
--background: #001d2e;
|
||||||
|
--foreground: #ffffff;
|
||||||
|
--card: rgba(0, 29, 46, 0.6);
|
||||||
|
--card-hover: rgba(0, 29, 46, 0.8);
|
||||||
|
--card-column: rgba(0, 29, 46, 0.8);
|
||||||
|
--border: rgba(29, 254, 228, 0.3);
|
||||||
|
--input: rgba(0, 29, 46, 0.6);
|
||||||
|
--primary: #1dfee4;
|
||||||
|
--primary-foreground: #001d2e;
|
||||||
|
--muted: #9ca3af;
|
||||||
|
--muted-foreground: #9ca3af;
|
||||||
|
--gray-300: #d1d5db;
|
||||||
|
--gray-400: #9ca3af;
|
||||||
|
--gray-500: #6b7280;
|
||||||
|
--gray-600: #4b5563;
|
||||||
|
--gray-700: #374151;
|
||||||
|
--gray-800: #1f2937;
|
||||||
|
--gray-900: #111827;
|
||||||
|
--accent: #1dfee4;
|
||||||
|
--destructive: #ef4444;
|
||||||
|
--success: #10b981;
|
||||||
|
--purple: #8b5cf6;
|
||||||
|
--yellow: #eab308;
|
||||||
|
--green: #10b981;
|
||||||
|
--blue: #3b82f6;
|
||||||
|
--pixel-gold: #1dfee4;
|
||||||
|
--accent-color: #1dfee4;
|
||||||
|
}
|
||||||
|
|
||||||
|
.dark {
|
||||||
|
/* Dark gold theme (original) */
|
||||||
|
--background: #000000;
|
||||||
|
--foreground: #ffffff;
|
||||||
|
--card: rgba(0, 0, 0, 0.6);
|
||||||
|
--card-hover: rgba(0, 0, 0, 0.8);
|
||||||
|
--card-column: rgba(0, 0, 0, 0.8);
|
||||||
|
--border: rgba(218, 165, 32, 0.3);
|
||||||
|
--input: rgba(0, 0, 0, 0.6);
|
||||||
|
--primary: #06b6d4;
|
||||||
|
--primary-foreground: #ffffff;
|
||||||
|
--muted: #9ca3af;
|
||||||
|
--muted-foreground: #9ca3af;
|
||||||
|
--gray-300: #d1d5db;
|
||||||
|
--gray-400: #9ca3af;
|
||||||
|
--gray-500: #6b7280;
|
||||||
|
--gray-600: #4b5563;
|
||||||
|
--gray-700: #374151;
|
||||||
|
--gray-800: #1f2937;
|
||||||
|
--gray-900: #111827;
|
||||||
|
--accent: #ff8c00;
|
||||||
|
--destructive: #ef4444;
|
||||||
|
--success: #10b981;
|
||||||
|
--purple: #8b5cf6;
|
||||||
|
--yellow: #eab308;
|
||||||
|
--green: #10b981;
|
||||||
|
--blue: #3b82f6;
|
||||||
|
--pixel-gold: #daa520;
|
||||||
|
--accent-color: #daa520;
|
||||||
|
}
|
||||||
|
|
||||||
|
.dark-cyan {
|
||||||
|
/* Dark cyan theme (new) */
|
||||||
|
--background: #001d2e;
|
||||||
|
--foreground: #ffffff;
|
||||||
|
--card: rgba(0, 29, 46, 0.6);
|
||||||
|
--card-hover: rgba(0, 29, 46, 0.8);
|
||||||
|
--card-column: rgba(0, 29, 46, 0.8);
|
||||||
|
--border: rgba(29, 254, 228, 0.3);
|
||||||
|
--input: rgba(0, 29, 46, 0.6);
|
||||||
|
--primary: #1dfee4;
|
||||||
|
--primary-foreground: #001d2e;
|
||||||
|
--muted: #9ca3af;
|
||||||
|
--muted-foreground: #9ca3af;
|
||||||
|
--gray-300: #d1d5db;
|
||||||
|
--gray-400: #9ca3af;
|
||||||
|
--gray-500: #6b7280;
|
||||||
|
--gray-600: #4b5563;
|
||||||
|
--gray-700: #374151;
|
||||||
|
--gray-800: #1f2937;
|
||||||
|
--gray-900: #111827;
|
||||||
|
--accent: #1dfee4;
|
||||||
|
--destructive: #ef4444;
|
||||||
|
--success: #10b981;
|
||||||
|
--purple: #8b5cf6;
|
||||||
|
--yellow: #eab308;
|
||||||
|
--green: #10b981;
|
||||||
|
--blue: #3b82f6;
|
||||||
|
--pixel-gold: #1dfee4;
|
||||||
|
--accent-color: #1dfee4;
|
||||||
|
}
|
||||||
|
|
||||||
@layer base {
|
@layer base {
|
||||||
body {
|
body {
|
||||||
@apply bg-black text-white;
|
background-color: var(--background);
|
||||||
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif;
|
color: var(--foreground);
|
||||||
|
font-family:
|
||||||
|
-apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", "Oxygen",
|
||||||
|
"Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue",
|
||||||
|
sans-serif;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -18,9 +119,75 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
.text-pixel {
|
.text-pixel {
|
||||||
font-family: 'Courier New', monospace;
|
font-family: "Courier New", monospace;
|
||||||
text-shadow: 2px 2px 0px rgba(0, 0, 0, 0.8);
|
text-shadow: 2px 2px 0px rgba(0, 0, 0, 0.8);
|
||||||
letter-spacing: 1px;
|
letter-spacing: 1px;
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
|
.title-animated {
|
||||||
|
background-clip: text;
|
||||||
|
-webkit-background-clip: text;
|
||||||
|
-webkit-text-fill-color: transparent;
|
||||||
|
}
|
||||||
|
|
||||||
|
@keyframes shimmer {
|
||||||
|
0% {
|
||||||
|
transform: translateX(-100%);
|
||||||
|
}
|
||||||
|
100% {
|
||||||
|
transform: translateX(100%);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.animate-shimmer {
|
||||||
|
animation: shimmer 2s infinite;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Button hover states using CSS variables */
|
||||||
|
.btn-primary {
|
||||||
|
border-color: color-mix(in srgb, var(--accent-color) 50%, transparent);
|
||||||
|
background-color: color-mix(in srgb, var(--background) 60%, transparent);
|
||||||
|
color: var(--foreground);
|
||||||
|
}
|
||||||
|
.btn-primary:hover:not(:disabled) {
|
||||||
|
border-color: var(--accent-color);
|
||||||
|
background-color: color-mix(in srgb, var(--accent-color) 10%, transparent);
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-secondary {
|
||||||
|
border-color: rgba(107, 114, 128, 0.5);
|
||||||
|
background-color: rgba(31, 41, 55, 0.2);
|
||||||
|
color: var(--gray-400);
|
||||||
|
}
|
||||||
|
.btn-secondary:hover:not(:disabled) {
|
||||||
|
border-color: var(--gray-500);
|
||||||
|
background-color: rgba(31, 41, 55, 0.3);
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-success {
|
||||||
|
border-color: rgba(16, 185, 129, 0.5);
|
||||||
|
background-color: rgba(16, 185, 129, 0.2);
|
||||||
|
color: var(--success);
|
||||||
|
}
|
||||||
|
.btn-success:hover:not(:disabled) {
|
||||||
|
background-color: rgba(16, 185, 129, 0.3);
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-danger {
|
||||||
|
border-color: rgba(239, 68, 68, 0.5);
|
||||||
|
background-color: rgba(239, 68, 68, 0.2);
|
||||||
|
color: var(--destructive);
|
||||||
|
}
|
||||||
|
.btn-danger:hover:not(:disabled) {
|
||||||
|
background-color: rgba(239, 68, 68, 0.3);
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-ghost {
|
||||||
|
border-color: transparent;
|
||||||
|
background-color: transparent;
|
||||||
|
color: var(--foreground);
|
||||||
|
}
|
||||||
|
.btn-ghost:hover:not(:disabled) {
|
||||||
|
color: var(--accent-color);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
207
app/houses/page.tsx
Normal file
207
app/houses/page.tsx
Normal file
@@ -0,0 +1,207 @@
|
|||||||
|
import { redirect } from "next/navigation";
|
||||||
|
import { auth } from "@/lib/auth";
|
||||||
|
import { getBackgroundImage } from "@/lib/preferences";
|
||||||
|
import NavigationWrapper from "@/components/navigation/NavigationWrapper";
|
||||||
|
import HousesSection from "@/components/houses/HousesSection";
|
||||||
|
import { houseService } from "@/services/houses/house.service";
|
||||||
|
import { prisma } from "@/services/database";
|
||||||
|
import type {
|
||||||
|
House,
|
||||||
|
HouseMembership,
|
||||||
|
HouseInvitation,
|
||||||
|
} from "@/prisma/generated/prisma/client";
|
||||||
|
|
||||||
|
export const dynamic = "force-dynamic";
|
||||||
|
|
||||||
|
// Types pour les données sérialisées
|
||||||
|
type HouseWithRelations = House & {
|
||||||
|
creator?: {
|
||||||
|
id: string;
|
||||||
|
username: string;
|
||||||
|
avatar: string | null;
|
||||||
|
} | null;
|
||||||
|
creatorId?: string;
|
||||||
|
memberships?: Array<
|
||||||
|
HouseMembership & {
|
||||||
|
user: {
|
||||||
|
id: string;
|
||||||
|
username: string;
|
||||||
|
avatar: string | null;
|
||||||
|
score: number | null;
|
||||||
|
level: number | null;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
>;
|
||||||
|
};
|
||||||
|
|
||||||
|
type InvitationWithRelations = HouseInvitation & {
|
||||||
|
house: {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
};
|
||||||
|
inviter: {
|
||||||
|
id: string;
|
||||||
|
username: string;
|
||||||
|
avatar: string | null;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
export default async function HousesPage() {
|
||||||
|
const session = await auth();
|
||||||
|
|
||||||
|
if (!session?.user?.id) {
|
||||||
|
redirect("/login");
|
||||||
|
}
|
||||||
|
|
||||||
|
const [housesData, myHouseData, invitationsData, users, backgroundImage] =
|
||||||
|
await Promise.all([
|
||||||
|
// Récupérer les maisons
|
||||||
|
houseService.getAllHouses({
|
||||||
|
include: {
|
||||||
|
memberships: {
|
||||||
|
include: {
|
||||||
|
user: {
|
||||||
|
select: {
|
||||||
|
id: true,
|
||||||
|
username: true,
|
||||||
|
avatar: true,
|
||||||
|
score: true,
|
||||||
|
level: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
orderBy: [
|
||||||
|
{ role: "asc" }, // OWNER, ADMIN, MEMBER
|
||||||
|
{ user: { score: "desc" } }, // Puis par score décroissant
|
||||||
|
],
|
||||||
|
},
|
||||||
|
creator: {
|
||||||
|
select: {
|
||||||
|
id: true,
|
||||||
|
username: true,
|
||||||
|
avatar: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
// Récupérer la maison de l'utilisateur
|
||||||
|
houseService.getUserHouse(session.user.id, {
|
||||||
|
memberships: {
|
||||||
|
include: {
|
||||||
|
user: {
|
||||||
|
select: {
|
||||||
|
id: true,
|
||||||
|
username: true,
|
||||||
|
avatar: true,
|
||||||
|
score: true,
|
||||||
|
level: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
creator: {
|
||||||
|
select: {
|
||||||
|
id: true,
|
||||||
|
username: true,
|
||||||
|
avatar: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
// Récupérer les invitations de l'utilisateur
|
||||||
|
houseService.getUserInvitations(session.user.id, "PENDING"),
|
||||||
|
// Récupérer tous les utilisateurs sans maison pour les invitations
|
||||||
|
prisma.user.findMany({
|
||||||
|
where: {
|
||||||
|
houseMemberships: {
|
||||||
|
none: {},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
select: {
|
||||||
|
id: true,
|
||||||
|
username: true,
|
||||||
|
avatar: true,
|
||||||
|
},
|
||||||
|
orderBy: {
|
||||||
|
username: "asc",
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
getBackgroundImage("houses", "/got-2.jpg"),
|
||||||
|
]);
|
||||||
|
|
||||||
|
// Sérialiser les données pour le client
|
||||||
|
const houses = (housesData as HouseWithRelations[]).map(
|
||||||
|
(house: HouseWithRelations) => ({
|
||||||
|
id: house.id,
|
||||||
|
name: house.name,
|
||||||
|
description: house.description,
|
||||||
|
creator: house.creator || {
|
||||||
|
id: house.creatorId || "",
|
||||||
|
username: "Unknown",
|
||||||
|
avatar: null,
|
||||||
|
},
|
||||||
|
memberships: (house.memberships || []).map((m) => ({
|
||||||
|
id: m.id,
|
||||||
|
role: m.role,
|
||||||
|
user: {
|
||||||
|
id: m.user.id,
|
||||||
|
username: m.user.username,
|
||||||
|
avatar: m.user.avatar,
|
||||||
|
score: m.user.score ?? 0,
|
||||||
|
level: m.user.level ?? 1,
|
||||||
|
},
|
||||||
|
})),
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
|
const myHouse = myHouseData
|
||||||
|
? {
|
||||||
|
id: myHouseData.id,
|
||||||
|
name: myHouseData.name,
|
||||||
|
description: myHouseData.description,
|
||||||
|
creator: (myHouseData as HouseWithRelations).creator || {
|
||||||
|
id: (myHouseData as HouseWithRelations).creatorId || "",
|
||||||
|
username: "Unknown",
|
||||||
|
avatar: null,
|
||||||
|
},
|
||||||
|
memberships: (
|
||||||
|
(myHouseData as HouseWithRelations).memberships || []
|
||||||
|
).map((m) => ({
|
||||||
|
id: m.id,
|
||||||
|
role: m.role,
|
||||||
|
user: {
|
||||||
|
id: m.user.id,
|
||||||
|
username: m.user.username,
|
||||||
|
avatar: m.user.avatar,
|
||||||
|
score: m.user.score ?? 0,
|
||||||
|
level: m.user.level ?? 1,
|
||||||
|
},
|
||||||
|
})),
|
||||||
|
}
|
||||||
|
: null;
|
||||||
|
|
||||||
|
const invitations = (invitationsData as InvitationWithRelations[]).map(
|
||||||
|
(inv: InvitationWithRelations) => ({
|
||||||
|
id: inv.id,
|
||||||
|
house: {
|
||||||
|
id: inv.house.id,
|
||||||
|
name: inv.house.name,
|
||||||
|
},
|
||||||
|
inviter: inv.inviter,
|
||||||
|
status: inv.status,
|
||||||
|
createdAt: inv.createdAt.toISOString(),
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<main className="min-h-screen bg-black relative">
|
||||||
|
<NavigationWrapper />
|
||||||
|
<HousesSection
|
||||||
|
initialHouses={houses}
|
||||||
|
initialMyHouse={myHouse}
|
||||||
|
initialUsers={users}
|
||||||
|
initialInvitations={invitations}
|
||||||
|
backgroundImage={backgroundImage}
|
||||||
|
/>
|
||||||
|
</main>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,7 +1,10 @@
|
|||||||
import type { Metadata } from "next";
|
import type { Metadata } from "next";
|
||||||
|
import type { ReactNode } from "react";
|
||||||
import { Orbitron, Rajdhani } from "next/font/google";
|
import { Orbitron, Rajdhani } from "next/font/google";
|
||||||
import "./globals.css";
|
import "./globals.css";
|
||||||
import SessionProvider from "@/components/SessionProvider";
|
import SessionProvider from "@/components/layout/SessionProvider";
|
||||||
|
import { ThemeProvider } from "@/contexts/ThemeContext";
|
||||||
|
import Footer from "@/components/layout/Footer";
|
||||||
|
|
||||||
const orbitron = Orbitron({
|
const orbitron = Orbitron({
|
||||||
subsets: ["latin"],
|
subsets: ["latin"],
|
||||||
@@ -23,12 +26,20 @@ export const metadata: Metadata = {
|
|||||||
export default function RootLayout({
|
export default function RootLayout({
|
||||||
children,
|
children,
|
||||||
}: Readonly<{
|
}: Readonly<{
|
||||||
children: React.ReactNode;
|
children: ReactNode;
|
||||||
}>) {
|
}>) {
|
||||||
return (
|
return (
|
||||||
<html lang="fr" className={`${orbitron.variable} ${rajdhani.variable}`}>
|
<html
|
||||||
|
lang="fr"
|
||||||
|
className={`${orbitron.variable} ${rajdhani.variable} dark-cyan`}
|
||||||
|
>
|
||||||
<body className="antialiased">
|
<body className="antialiased">
|
||||||
<SessionProvider>{children}</SessionProvider>
|
<ThemeProvider>
|
||||||
|
<SessionProvider>
|
||||||
|
{children}
|
||||||
|
<Footer />
|
||||||
|
</SessionProvider>
|
||||||
|
</ThemeProvider>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -1,12 +1,26 @@
|
|||||||
import Navigation from "@/components/Navigation";
|
import NavigationWrapper from "@/components/navigation/NavigationWrapper";
|
||||||
import LeaderboardSection from "@/components/LeaderboardSection";
|
import LeaderboardSection from "@/components/leaderboard/LeaderboardSection";
|
||||||
|
import { userStatsService } from "@/services/users/user-stats.service";
|
||||||
|
import { getBackgroundImage } from "@/lib/preferences";
|
||||||
|
|
||||||
|
export const dynamic = "force-dynamic";
|
||||||
|
|
||||||
|
export default async function LeaderboardPage() {
|
||||||
|
// Paralléliser les appels DB
|
||||||
|
const [leaderboard, houseLeaderboard, backgroundImage] = await Promise.all([
|
||||||
|
userStatsService.getLeaderboard(10),
|
||||||
|
userStatsService.getHouseLeaderboard(10),
|
||||||
|
getBackgroundImage("leaderboard", "/leaderboard-bg.jpg"),
|
||||||
|
]);
|
||||||
|
|
||||||
export default function LeaderboardPage() {
|
|
||||||
return (
|
return (
|
||||||
<main className="min-h-screen bg-black relative">
|
<main className="min-h-screen bg-black relative">
|
||||||
<Navigation />
|
<NavigationWrapper />
|
||||||
<LeaderboardSection />
|
<LeaderboardSection
|
||||||
|
leaderboard={leaderboard}
|
||||||
|
houseLeaderboard={houseLeaderboard}
|
||||||
|
backgroundImage={backgroundImage}
|
||||||
|
/>
|
||||||
</main>
|
</main>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,10 +1,18 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { useState } from "react";
|
import { useState, type FormEvent } from "react";
|
||||||
import { signIn } from "next-auth/react";
|
import { signIn } from "next-auth/react";
|
||||||
import { useRouter } from "next/navigation";
|
import { useRouter } from "next/navigation";
|
||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
import Navigation from "@/components/Navigation";
|
import Navigation from "@/components/navigation/Navigation";
|
||||||
|
import {
|
||||||
|
Input,
|
||||||
|
Button,
|
||||||
|
Alert,
|
||||||
|
Card,
|
||||||
|
BackgroundSection,
|
||||||
|
SectionTitle,
|
||||||
|
} from "@/components/ui";
|
||||||
|
|
||||||
export default function LoginPage() {
|
export default function LoginPage() {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
@@ -13,7 +21,7 @@ export default function LoginPage() {
|
|||||||
const [error, setError] = useState("");
|
const [error, setError] = useState("");
|
||||||
const [loading, setLoading] = useState(false);
|
const [loading, setLoading] = useState(false);
|
||||||
|
|
||||||
const handleSubmit = async (e: React.FormEvent) => {
|
const handleSubmit = async (e: FormEvent) => {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
setError("");
|
setError("");
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
@@ -46,79 +54,53 @@ export default function LoginPage() {
|
|||||||
return (
|
return (
|
||||||
<main className="min-h-screen bg-black relative">
|
<main className="min-h-screen bg-black relative">
|
||||||
<Navigation />
|
<Navigation />
|
||||||
<section className="relative w-full min-h-screen flex flex-col items-center justify-center overflow-hidden pt-24">
|
<BackgroundSection backgroundImage="/got-2.jpg" className="pt-24">
|
||||||
{/* Background Image */}
|
|
||||||
<div
|
|
||||||
className="absolute inset-0 bg-cover bg-center bg-no-repeat"
|
|
||||||
style={{
|
|
||||||
backgroundImage: `url('/got-2.jpg')`,
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<div className="absolute inset-0 bg-gradient-to-b from-black/70 via-black/60 to-black/80"></div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Login Form */}
|
{/* Login Form */}
|
||||||
<div className="relative z-10 w-full max-w-md mx-auto px-8">
|
<div className="w-full max-w-md mx-auto px-8">
|
||||||
<div className="bg-black/80 border border-pixel-gold/30 rounded-lg p-8 backdrop-blur-sm">
|
<Card variant="dark" className="p-8">
|
||||||
<h1 className="text-4xl font-gaming font-black mb-2 text-center">
|
<SectionTitle
|
||||||
<span className="bg-gradient-to-r from-pixel-gold via-orange-400 to-pixel-gold bg-clip-text text-transparent">
|
variant="gradient"
|
||||||
CONNEXION
|
size="md"
|
||||||
</span>
|
className="mb-2 text-center"
|
||||||
</h1>
|
>
|
||||||
|
CONNEXION
|
||||||
|
</SectionTitle>
|
||||||
<p className="text-gray-400 text-sm text-center mb-8">
|
<p className="text-gray-400 text-sm text-center mb-8">
|
||||||
Connectez-vous à votre compte
|
Connectez-vous à votre compte
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
<form onSubmit={handleSubmit} className="space-y-6">
|
<form onSubmit={handleSubmit} className="space-y-6">
|
||||||
{error && (
|
{error && <Alert variant="error">{error}</Alert>}
|
||||||
<div className="bg-red-900/50 border border-red-500/50 text-red-400 px-4 py-3 rounded text-sm">
|
|
||||||
{error}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<div>
|
<Input
|
||||||
<label
|
id="email"
|
||||||
htmlFor="email"
|
type="email"
|
||||||
className="block text-sm font-semibold text-gray-300 mb-2 uppercase tracking-wider"
|
label="Email"
|
||||||
>
|
value={email}
|
||||||
Email
|
onChange={(e) => setEmail(e.target.value)}
|
||||||
</label>
|
required
|
||||||
<input
|
placeholder="votre@email.com"
|
||||||
id="email"
|
/>
|
||||||
type="email"
|
|
||||||
value={email}
|
|
||||||
onChange={(e) => setEmail(e.target.value)}
|
|
||||||
required
|
|
||||||
className="w-full px-4 py-3 bg-black/60 border border-pixel-gold/30 rounded text-white placeholder-gray-500 focus:outline-none focus:border-pixel-gold transition"
|
|
||||||
placeholder="votre@email.com"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div>
|
<Input
|
||||||
<label
|
id="password"
|
||||||
htmlFor="password"
|
type="password"
|
||||||
className="block text-sm font-semibold text-gray-300 mb-2 uppercase tracking-wider"
|
label="Mot de passe"
|
||||||
>
|
value={password}
|
||||||
Mot de passe
|
onChange={(e) => setPassword(e.target.value)}
|
||||||
</label>
|
required
|
||||||
<input
|
placeholder="••••••••"
|
||||||
id="password"
|
/>
|
||||||
type="password"
|
|
||||||
value={password}
|
|
||||||
onChange={(e) => setPassword(e.target.value)}
|
|
||||||
required
|
|
||||||
className="w-full px-4 py-3 bg-black/60 border border-pixel-gold/30 rounded text-white placeholder-gray-500 focus:outline-none focus:border-pixel-gold transition"
|
|
||||||
placeholder="••••••••"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<button
|
<Button
|
||||||
type="submit"
|
type="submit"
|
||||||
|
variant="primary"
|
||||||
|
size="lg"
|
||||||
disabled={loading}
|
disabled={loading}
|
||||||
className="w-full px-6 py-3 border border-pixel-gold/50 bg-black/60 text-white uppercase text-sm tracking-widest rounded hover:bg-pixel-gold/10 hover:border-pixel-gold transition disabled:opacity-50 disabled:cursor-not-allowed"
|
className="w-full"
|
||||||
>
|
>
|
||||||
{loading ? "Connexion..." : "Se connecter"}
|
{loading ? "Connexion..." : "Se connecter"}
|
||||||
</button>
|
</Button>
|
||||||
</form>
|
</form>
|
||||||
|
|
||||||
<div className="mt-6 text-center">
|
<div className="mt-6 text-center">
|
||||||
@@ -128,14 +110,13 @@ export default function LoginPage() {
|
|||||||
href="/register"
|
href="/register"
|
||||||
className="text-pixel-gold hover:text-orange-400 transition"
|
className="text-pixel-gold hover:text-orange-400 transition"
|
||||||
>
|
>
|
||||||
S'inscrire
|
S'inscrire
|
||||||
</Link>
|
</Link>
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</Card>
|
||||||
</div>
|
</div>
|
||||||
</section>
|
</BackgroundSection>
|
||||||
</main>
|
</main>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
32
app/page.tsx
32
app/page.tsx
@@ -1,13 +1,29 @@
|
|||||||
import Navigation from "@/components/Navigation";
|
import NavigationWrapper from "@/components/navigation/NavigationWrapper";
|
||||||
import HeroSection from "@/components/HeroSection";
|
import HeroSection from "@/components/layout/HeroSection";
|
||||||
import EventsSection from "@/components/EventsSection";
|
import EventsSection from "@/components/events/EventsSection";
|
||||||
|
import { eventService } from "@/services/events/event.service";
|
||||||
|
import { getBackgroundImage } from "@/lib/preferences";
|
||||||
|
|
||||||
|
export const dynamic = "force-dynamic";
|
||||||
|
|
||||||
|
export default async function Home() {
|
||||||
|
// Paralléliser les appels DB
|
||||||
|
const [events, backgroundImage] = await Promise.all([
|
||||||
|
eventService.getUpcomingEvents(3),
|
||||||
|
getBackgroundImage("home", "/got-2.jpg"),
|
||||||
|
]);
|
||||||
|
|
||||||
|
// Convert Date objects to strings for serialization
|
||||||
|
const serializedEvents = events.map((event) => ({
|
||||||
|
...event,
|
||||||
|
date: event.date.toISOString(),
|
||||||
|
}));
|
||||||
|
|
||||||
export default function Home() {
|
|
||||||
return (
|
return (
|
||||||
<main className="min-h-screen bg-black relative">
|
<main className="min-h-screen relative" style={{ backgroundColor: "var(--background)" }}>
|
||||||
<Navigation />
|
<NavigationWrapper />
|
||||||
<HeroSection />
|
<HeroSection backgroundImage={backgroundImage} />
|
||||||
<EventsSection />
|
<EventsSection events={serializedEvents} />
|
||||||
</main>
|
</main>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,499 +1,54 @@
|
|||||||
"use client";
|
import { redirect } from "next/navigation";
|
||||||
|
import { auth } from "@/lib/auth";
|
||||||
|
import { userService } from "@/services/users/user.service";
|
||||||
|
import { getBackgroundImage } from "@/lib/preferences";
|
||||||
|
import NavigationWrapper from "@/components/navigation/NavigationWrapper";
|
||||||
|
import ProfileForm from "@/components/profile/ProfileForm";
|
||||||
|
|
||||||
import { useEffect, useState, useRef } from "react";
|
export default async function ProfilePage() {
|
||||||
import { useSession } from "next-auth/react";
|
const session = await auth();
|
||||||
import { useRouter } from "next/navigation";
|
|
||||||
import Navigation from "@/components/Navigation";
|
|
||||||
import { useBackgroundImage } from "@/hooks/usePreferences";
|
|
||||||
|
|
||||||
interface UserProfile {
|
if (!session?.user) {
|
||||||
id: string;
|
redirect("/login");
|
||||||
email: string;
|
|
||||||
username: string;
|
|
||||||
avatar: string | null;
|
|
||||||
hp: number;
|
|
||||||
maxHp: number;
|
|
||||||
xp: number;
|
|
||||||
maxXp: number;
|
|
||||||
level: number;
|
|
||||||
score: number;
|
|
||||||
createdAt: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
const formatNumber = (num: number): string => {
|
|
||||||
return num.toLocaleString("en-US");
|
|
||||||
};
|
|
||||||
|
|
||||||
export default function ProfilePage() {
|
|
||||||
const { data: session, status } = useSession();
|
|
||||||
const router = useRouter();
|
|
||||||
const backgroundImage = useBackgroundImage("home", "/got-background.jpg");
|
|
||||||
const [profile, setProfile] = useState<UserProfile | null>(null);
|
|
||||||
const [loading, setLoading] = useState(true);
|
|
||||||
const [saving, setSaving] = useState(false);
|
|
||||||
const [error, setError] = useState<string | null>(null);
|
|
||||||
const [success, setSuccess] = useState<string | null>(null);
|
|
||||||
|
|
||||||
const [username, setUsername] = useState("");
|
|
||||||
const [avatar, setAvatar] = useState<string | null>(null);
|
|
||||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
|
||||||
const [uploadingAvatar, setUploadingAvatar] = useState(false);
|
|
||||||
|
|
||||||
// Password change form state
|
|
||||||
const [showPasswordForm, setShowPasswordForm] = useState(false);
|
|
||||||
const [currentPassword, setCurrentPassword] = useState("");
|
|
||||||
const [newPassword, setNewPassword] = useState("");
|
|
||||||
const [confirmPassword, setConfirmPassword] = useState("");
|
|
||||||
const [changingPassword, setChangingPassword] = useState(false);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (status === "unauthenticated") {
|
|
||||||
router.push("/login");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (status === "authenticated" && session?.user) {
|
|
||||||
fetchProfile();
|
|
||||||
}
|
|
||||||
}, [status, session, router]);
|
|
||||||
|
|
||||||
const fetchProfile = async () => {
|
|
||||||
try {
|
|
||||||
const response = await fetch("/api/profile");
|
|
||||||
if (response.ok) {
|
|
||||||
const data = await response.json();
|
|
||||||
setProfile(data);
|
|
||||||
setUsername(data.username);
|
|
||||||
setAvatar(data.avatar);
|
|
||||||
} else {
|
|
||||||
setError("Erreur lors du chargement du profil");
|
|
||||||
}
|
|
||||||
} catch (err) {
|
|
||||||
console.error("Error fetching profile:", err);
|
|
||||||
setError("Erreur lors du chargement du profil");
|
|
||||||
} finally {
|
|
||||||
setLoading(false);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleAvatarUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
|
|
||||||
const file = e.target.files?.[0];
|
|
||||||
if (!file) return;
|
|
||||||
|
|
||||||
setUploadingAvatar(true);
|
|
||||||
setError(null);
|
|
||||||
|
|
||||||
try {
|
|
||||||
const formData = new FormData();
|
|
||||||
formData.append("file", file);
|
|
||||||
|
|
||||||
const response = await fetch("/api/profile/avatar", {
|
|
||||||
method: "POST",
|
|
||||||
body: formData,
|
|
||||||
});
|
|
||||||
|
|
||||||
if (response.ok) {
|
|
||||||
const data = await response.json();
|
|
||||||
setAvatar(data.url);
|
|
||||||
setSuccess("Avatar mis à jour avec succès");
|
|
||||||
setTimeout(() => setSuccess(null), 3000);
|
|
||||||
} else {
|
|
||||||
const errorData = await response.json();
|
|
||||||
setError(errorData.error || "Erreur lors de l'upload de l'avatar");
|
|
||||||
}
|
|
||||||
} catch (err) {
|
|
||||||
console.error("Error uploading avatar:", err);
|
|
||||||
setError("Erreur lors de l'upload de l'avatar");
|
|
||||||
} finally {
|
|
||||||
setUploadingAvatar(false);
|
|
||||||
if (fileInputRef.current) {
|
|
||||||
fileInputRef.current.value = "";
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleSubmit = async (e: React.FormEvent) => {
|
|
||||||
e.preventDefault();
|
|
||||||
setSaving(true);
|
|
||||||
setError(null);
|
|
||||||
setSuccess(null);
|
|
||||||
|
|
||||||
try {
|
|
||||||
const response = await fetch("/api/profile", {
|
|
||||||
method: "PUT",
|
|
||||||
headers: {
|
|
||||||
"Content-Type": "application/json",
|
|
||||||
},
|
|
||||||
body: JSON.stringify({
|
|
||||||
username,
|
|
||||||
avatar,
|
|
||||||
}),
|
|
||||||
});
|
|
||||||
|
|
||||||
if (response.ok) {
|
|
||||||
const data = await response.json();
|
|
||||||
setProfile(data);
|
|
||||||
setSuccess("Profil mis à jour avec succès");
|
|
||||||
setTimeout(() => setSuccess(null), 3000);
|
|
||||||
} else {
|
|
||||||
const errorData = await response.json();
|
|
||||||
setError(errorData.error || "Erreur lors de la mise à jour");
|
|
||||||
}
|
|
||||||
} catch (err) {
|
|
||||||
console.error("Error updating profile:", err);
|
|
||||||
setError("Erreur lors de la mise à jour du profil");
|
|
||||||
} finally {
|
|
||||||
setSaving(false);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const handlePasswordChange = async (e: React.FormEvent) => {
|
|
||||||
e.preventDefault();
|
|
||||||
setChangingPassword(true);
|
|
||||||
setError(null);
|
|
||||||
setSuccess(null);
|
|
||||||
|
|
||||||
try {
|
|
||||||
const response = await fetch("/api/profile/password", {
|
|
||||||
method: "PUT",
|
|
||||||
headers: {
|
|
||||||
"Content-Type": "application/json",
|
|
||||||
},
|
|
||||||
body: JSON.stringify({
|
|
||||||
currentPassword,
|
|
||||||
newPassword,
|
|
||||||
confirmPassword,
|
|
||||||
}),
|
|
||||||
});
|
|
||||||
|
|
||||||
if (response.ok) {
|
|
||||||
setSuccess("Mot de passe modifié avec succès");
|
|
||||||
setCurrentPassword("");
|
|
||||||
setNewPassword("");
|
|
||||||
setConfirmPassword("");
|
|
||||||
setShowPasswordForm(false);
|
|
||||||
setTimeout(() => setSuccess(null), 3000);
|
|
||||||
} else {
|
|
||||||
const errorData = await response.json();
|
|
||||||
setError(errorData.error || "Erreur lors de la modification du mot de passe");
|
|
||||||
}
|
|
||||||
} catch (err) {
|
|
||||||
console.error("Error changing password:", err);
|
|
||||||
setError("Erreur lors de la modification du mot de passe");
|
|
||||||
} finally {
|
|
||||||
setChangingPassword(false);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
if (loading || status === "loading") {
|
|
||||||
return (
|
|
||||||
<main className="min-h-screen bg-black relative">
|
|
||||||
<Navigation />
|
|
||||||
<section className="relative w-full min-h-screen flex flex-col items-center justify-center overflow-hidden pt-24 pb-16">
|
|
||||||
<div className="text-pixel-gold text-xl">Chargement...</div>
|
|
||||||
</section>
|
|
||||||
</main>
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!profile) {
|
// Paralléliser les appels DB
|
||||||
return (
|
const [user, backgroundImage] = await Promise.all([
|
||||||
<main className="min-h-screen bg-black relative">
|
userService.getUserById(session.user.id, {
|
||||||
<Navigation />
|
id: true,
|
||||||
<section className="relative w-full min-h-screen flex flex-col items-center justify-center overflow-hidden pt-24 pb-16">
|
email: true,
|
||||||
<div className="text-red-400 text-xl">Erreur lors du chargement du profil</div>
|
username: true,
|
||||||
</section>
|
avatar: true,
|
||||||
</main>
|
bio: true,
|
||||||
);
|
characterClass: true,
|
||||||
|
hp: true,
|
||||||
|
maxHp: true,
|
||||||
|
xp: true,
|
||||||
|
maxXp: true,
|
||||||
|
level: true,
|
||||||
|
score: true,
|
||||||
|
createdAt: true,
|
||||||
|
}),
|
||||||
|
getBackgroundImage("profile", "/got-background.jpg"),
|
||||||
|
]);
|
||||||
|
|
||||||
|
if (!user) {
|
||||||
|
redirect("/login");
|
||||||
}
|
}
|
||||||
|
|
||||||
const hpPercentage = (profile.hp / profile.maxHp) * 100;
|
// Convert Date to string for the component
|
||||||
const xpPercentage = (profile.xp / profile.maxXp) * 100;
|
const userProfile = {
|
||||||
|
...user,
|
||||||
const hpColor =
|
createdAt: user.createdAt.toISOString(),
|
||||||
hpPercentage > 60
|
};
|
||||||
? "from-green-600 to-green-700"
|
|
||||||
: hpPercentage > 30
|
|
||||||
? "from-yellow-600 to-orange-700"
|
|
||||||
: "from-red-700 to-red-900";
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<main className="min-h-screen bg-black relative">
|
<main className="min-h-screen bg-black relative">
|
||||||
<Navigation />
|
<NavigationWrapper />
|
||||||
<section className="relative w-full min-h-screen flex flex-col items-center justify-center overflow-hidden pt-24 pb-16">
|
<ProfileForm
|
||||||
{/* Background Image */}
|
initialProfile={userProfile}
|
||||||
<div
|
backgroundImage={backgroundImage}
|
||||||
className="absolute inset-0 bg-cover bg-center bg-no-repeat"
|
/>
|
||||||
style={{
|
|
||||||
backgroundImage: `url('${backgroundImage}')`,
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
{/* Dark overlay for readability */}
|
|
||||||
<div className="absolute inset-0 bg-gradient-to-b from-black/70 via-black/60 to-black/80"></div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Content */}
|
|
||||||
<div className="relative z-10 w-full max-w-4xl mx-auto px-8 py-16">
|
|
||||||
{/* Title Section */}
|
|
||||||
<div className="text-center mb-12">
|
|
||||||
<h1 className="text-5xl md:text-7xl font-gaming font-black mb-4 tracking-tight">
|
|
||||||
<span
|
|
||||||
className="bg-gradient-to-r from-pixel-gold via-orange-400 to-pixel-gold bg-clip-text text-transparent"
|
|
||||||
style={{
|
|
||||||
textShadow: "0 0 30px rgba(218, 165, 32, 0.5)",
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
PROFIL
|
|
||||||
</span>
|
|
||||||
</h1>
|
|
||||||
<div className="text-pixel-gold text-lg md:text-xl font-gaming-subtitle font-semibold flex items-center justify-center gap-2 tracking-wide">
|
|
||||||
<span>✦</span>
|
|
||||||
<span>Gérez votre profil</span>
|
|
||||||
<span>✦</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Profile Card */}
|
|
||||||
<div className="bg-black/60 border border-pixel-gold/30 rounded-lg overflow-hidden backdrop-blur-sm">
|
|
||||||
<form onSubmit={handleSubmit} className="p-8 space-y-8">
|
|
||||||
{/* Messages */}
|
|
||||||
{error && (
|
|
||||||
<div className="bg-red-900/50 border border-red-500/50 text-red-400 px-4 py-3 rounded text-sm">
|
|
||||||
{error}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
{success && (
|
|
||||||
<div className="bg-green-900/50 border border-green-500/50 text-green-400 px-4 py-3 rounded text-sm">
|
|
||||||
{success}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* Avatar Section */}
|
|
||||||
<div className="flex flex-col items-center gap-4">
|
|
||||||
<div className="relative">
|
|
||||||
<div className="w-32 h-32 rounded-full border-4 border-pixel-gold/50 overflow-hidden bg-gray-900 flex items-center justify-center">
|
|
||||||
{avatar ? (
|
|
||||||
<img
|
|
||||||
src={avatar}
|
|
||||||
alt={username}
|
|
||||||
className="w-full h-full object-cover"
|
|
||||||
/>
|
|
||||||
) : (
|
|
||||||
<span className="text-pixel-gold text-4xl font-bold">
|
|
||||||
{username.charAt(0).toUpperCase()}
|
|
||||||
</span>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
{uploadingAvatar && (
|
|
||||||
<div className="absolute inset-0 bg-black/60 flex items-center justify-center rounded-full">
|
|
||||||
<div className="text-pixel-gold text-sm">Upload...</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<input
|
|
||||||
ref={fileInputRef}
|
|
||||||
type="file"
|
|
||||||
accept="image/*"
|
|
||||||
onChange={handleAvatarUpload}
|
|
||||||
className="hidden"
|
|
||||||
id="avatar-upload"
|
|
||||||
/>
|
|
||||||
<label
|
|
||||||
htmlFor="avatar-upload"
|
|
||||||
className="px-4 py-2 border border-pixel-gold/50 bg-black/40 text-white uppercase text-xs tracking-widest rounded hover:bg-pixel-gold/10 hover:border-pixel-gold transition cursor-pointer inline-block"
|
|
||||||
>
|
|
||||||
{uploadingAvatar ? "Upload en cours..." : "Changer l'avatar"}
|
|
||||||
</label>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Username Field */}
|
|
||||||
<div>
|
|
||||||
<label className="block text-pixel-gold text-sm uppercase tracking-widest mb-2">
|
|
||||||
Nom d'utilisateur
|
|
||||||
</label>
|
|
||||||
<input
|
|
||||||
type="text"
|
|
||||||
value={username}
|
|
||||||
onChange={(e) => setUsername(e.target.value)}
|
|
||||||
className="w-full px-4 py-3 bg-black/40 border border-pixel-gold/30 rounded text-white focus:outline-none focus:border-pixel-gold transition"
|
|
||||||
required
|
|
||||||
minLength={3}
|
|
||||||
maxLength={20}
|
|
||||||
/>
|
|
||||||
<p className="text-gray-500 text-xs mt-1">
|
|
||||||
3-20 caractères
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Stats Display */}
|
|
||||||
<div className="border-t border-pixel-gold/20 pt-6">
|
|
||||||
<h3 className="text-pixel-gold text-sm uppercase tracking-widest mb-4">
|
|
||||||
Statistiques
|
|
||||||
</h3>
|
|
||||||
|
|
||||||
<div className="grid grid-cols-2 gap-4 mb-4">
|
|
||||||
<div className="bg-black/40 border border-pixel-gold/20 rounded p-4">
|
|
||||||
<div className="text-gray-400 text-xs uppercase mb-1">Score</div>
|
|
||||||
<div className="text-pixel-gold text-xl font-bold">
|
|
||||||
{formatNumber(profile.score)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div className="bg-black/40 border border-pixel-gold/20 rounded p-4">
|
|
||||||
<div className="text-gray-400 text-xs uppercase mb-1">Niveau</div>
|
|
||||||
<div className="text-pixel-gold text-xl font-bold">
|
|
||||||
Lv.{profile.level}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* HP Bar */}
|
|
||||||
<div className="mb-4">
|
|
||||||
<div className="flex justify-between text-xs text-gray-400 mb-1">
|
|
||||||
<span>HP</span>
|
|
||||||
<span>{profile.hp} / {profile.maxHp}</span>
|
|
||||||
</div>
|
|
||||||
<div className="relative h-3 bg-gray-900 border border-gray-700 rounded overflow-hidden">
|
|
||||||
<div
|
|
||||||
className={`absolute inset-0 bg-gradient-to-r ${hpColor} transition-all duration-1000 ease-out`}
|
|
||||||
style={{ width: `${hpPercentage}%` }}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* XP Bar */}
|
|
||||||
<div>
|
|
||||||
<div className="flex justify-between text-xs text-gray-400 mb-1">
|
|
||||||
<span>XP</span>
|
|
||||||
<span>{formatNumber(profile.xp)} / {formatNumber(profile.maxXp)}</span>
|
|
||||||
</div>
|
|
||||||
<div className="relative h-3 bg-gray-900 border border-pixel-gold/30 rounded overflow-hidden">
|
|
||||||
<div
|
|
||||||
className="absolute inset-0 bg-gradient-to-r from-pixel-gold/80 via-pixel-gold/70 to-pixel-gold/80 transition-all duration-1000 ease-out"
|
|
||||||
style={{ width: `${xpPercentage}%` }}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Email (read-only) */}
|
|
||||||
<div>
|
|
||||||
<label className="block text-gray-500 text-sm uppercase tracking-widest mb-2">
|
|
||||||
Email
|
|
||||||
</label>
|
|
||||||
<input
|
|
||||||
type="email"
|
|
||||||
value={profile.email}
|
|
||||||
disabled
|
|
||||||
className="w-full px-4 py-3 bg-black/20 border border-gray-700/50 rounded text-gray-500 cursor-not-allowed"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Submit Button */}
|
|
||||||
<div className="flex justify-end gap-4 pt-4 border-t border-pixel-gold/20">
|
|
||||||
<button
|
|
||||||
type="submit"
|
|
||||||
disabled={saving}
|
|
||||||
className="px-6 py-2 border border-pixel-gold/50 bg-black/40 text-white uppercase text-xs tracking-widest rounded hover:bg-pixel-gold/10 hover:border-pixel-gold transition disabled:opacity-50 disabled:cursor-not-allowed"
|
|
||||||
>
|
|
||||||
{saving ? "Enregistrement..." : "Enregistrer les modifications"}
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</form>
|
|
||||||
|
|
||||||
{/* Password Change Section - Separate form */}
|
|
||||||
<div className="border-t border-pixel-gold/20 p-8">
|
|
||||||
<div className="flex items-center justify-between mb-4">
|
|
||||||
<h3 className="text-pixel-gold text-sm uppercase tracking-widest">
|
|
||||||
Mot de passe
|
|
||||||
</h3>
|
|
||||||
{!showPasswordForm && (
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
onClick={() => setShowPasswordForm(true)}
|
|
||||||
className="px-4 py-2 border border-pixel-gold/50 bg-black/40 text-white uppercase text-xs tracking-widest rounded hover:bg-pixel-gold/10 hover:border-pixel-gold transition"
|
|
||||||
>
|
|
||||||
Changer le mot de passe
|
|
||||||
</button>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{showPasswordForm && (
|
|
||||||
<form onSubmit={handlePasswordChange} className="space-y-4">
|
|
||||||
<div>
|
|
||||||
<label className="block text-pixel-gold text-sm uppercase tracking-widest mb-2">
|
|
||||||
Mot de passe actuel
|
|
||||||
</label>
|
|
||||||
<input
|
|
||||||
type="password"
|
|
||||||
value={currentPassword}
|
|
||||||
onChange={(e) => setCurrentPassword(e.target.value)}
|
|
||||||
className="w-full px-4 py-3 bg-black/40 border border-pixel-gold/30 rounded text-white focus:outline-none focus:border-pixel-gold transition"
|
|
||||||
required
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div>
|
|
||||||
<label className="block text-pixel-gold text-sm uppercase tracking-widest mb-2">
|
|
||||||
Nouveau mot de passe
|
|
||||||
</label>
|
|
||||||
<input
|
|
||||||
type="password"
|
|
||||||
value={newPassword}
|
|
||||||
onChange={(e) => setNewPassword(e.target.value)}
|
|
||||||
className="w-full px-4 py-3 bg-black/40 border border-pixel-gold/30 rounded text-white focus:outline-none focus:border-pixel-gold transition"
|
|
||||||
required
|
|
||||||
minLength={6}
|
|
||||||
/>
|
|
||||||
<p className="text-gray-500 text-xs mt-1">
|
|
||||||
Minimum 6 caractères
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div>
|
|
||||||
<label className="block text-pixel-gold text-sm uppercase tracking-widest mb-2">
|
|
||||||
Confirmer le nouveau mot de passe
|
|
||||||
</label>
|
|
||||||
<input
|
|
||||||
type="password"
|
|
||||||
value={confirmPassword}
|
|
||||||
onChange={(e) => setConfirmPassword(e.target.value)}
|
|
||||||
className="w-full px-4 py-3 bg-black/40 border border-pixel-gold/30 rounded text-white focus:outline-none focus:border-pixel-gold transition"
|
|
||||||
required
|
|
||||||
minLength={6}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="flex justify-end gap-4">
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
onClick={() => {
|
|
||||||
setShowPasswordForm(false);
|
|
||||||
setCurrentPassword("");
|
|
||||||
setNewPassword("");
|
|
||||||
setConfirmPassword("");
|
|
||||||
setError(null);
|
|
||||||
}}
|
|
||||||
className="px-4 py-2 border border-gray-600/50 bg-black/40 text-gray-400 uppercase text-xs tracking-widest rounded hover:bg-gray-900/40 hover:border-gray-500 transition"
|
|
||||||
>
|
|
||||||
Annuler
|
|
||||||
</button>
|
|
||||||
<button
|
|
||||||
type="submit"
|
|
||||||
disabled={changingPassword}
|
|
||||||
className="px-4 py-2 border border-pixel-gold/50 bg-black/40 text-white uppercase text-xs tracking-widest rounded hover:bg-pixel-gold/10 hover:border-pixel-gold transition disabled:opacity-50 disabled:cursor-not-allowed"
|
|
||||||
>
|
|
||||||
{changingPassword ? "Modification..." : "Modifier le mot de passe"}
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</form>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</section>
|
|
||||||
</main>
|
</main>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,9 +1,20 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { useState } from "react";
|
import { useState, useRef, type ChangeEvent, type FormEvent } from "react";
|
||||||
import { useRouter } from "next/navigation";
|
import { useRouter } from "next/navigation";
|
||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
import Navigation from "@/components/Navigation";
|
import Navigation from "@/components/navigation/Navigation";
|
||||||
|
import {
|
||||||
|
Avatar,
|
||||||
|
Input,
|
||||||
|
Textarea,
|
||||||
|
Button,
|
||||||
|
Alert,
|
||||||
|
Card,
|
||||||
|
BackgroundSection,
|
||||||
|
SectionTitle,
|
||||||
|
} from "@/components/ui";
|
||||||
|
import { CHARACTER_CLASSES } from "@/lib/character-classes";
|
||||||
|
|
||||||
export default function RegisterPage() {
|
export default function RegisterPage() {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
@@ -12,18 +23,64 @@ export default function RegisterPage() {
|
|||||||
username: "",
|
username: "",
|
||||||
password: "",
|
password: "",
|
||||||
confirmPassword: "",
|
confirmPassword: "",
|
||||||
|
bio: "",
|
||||||
|
characterClass: null as string | null,
|
||||||
|
avatar: null as string | null,
|
||||||
});
|
});
|
||||||
const [error, setError] = useState("");
|
const [error, setError] = useState("");
|
||||||
const [loading, setLoading] = useState(false);
|
const [loading, setLoading] = useState(false);
|
||||||
|
const [uploadingAvatar, setUploadingAvatar] = useState(false);
|
||||||
|
const [step, setStep] = useState(1);
|
||||||
|
const [userId, setUserId] = useState<string | null>(null);
|
||||||
|
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||||
|
|
||||||
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
const handleChange = (
|
||||||
|
e: ChangeEvent<HTMLInputElement | HTMLTextAreaElement>
|
||||||
|
) => {
|
||||||
setFormData({
|
setFormData({
|
||||||
...formData,
|
...formData,
|
||||||
[e.target.name]: e.target.value,
|
[e.target.name]: e.target.value,
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleSubmit = async (e: React.FormEvent) => {
|
const handleAvatarUpload = async (e: ChangeEvent<HTMLInputElement>) => {
|
||||||
|
const file = e.target.files?.[0];
|
||||||
|
if (!file) return;
|
||||||
|
|
||||||
|
setUploadingAvatar(true);
|
||||||
|
setError("");
|
||||||
|
|
||||||
|
try {
|
||||||
|
const formDataUpload = new FormData();
|
||||||
|
formDataUpload.append("file", file);
|
||||||
|
|
||||||
|
const response = await fetch("/api/register/avatar", {
|
||||||
|
method: "POST",
|
||||||
|
body: formDataUpload,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (response.ok) {
|
||||||
|
const data = await response.json();
|
||||||
|
setFormData({
|
||||||
|
...formData,
|
||||||
|
avatar: data.url,
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
const errorData = await response.json();
|
||||||
|
setError(errorData.error || "Erreur lors de l'upload de l'avatar");
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
console.error("Error uploading avatar:", err);
|
||||||
|
setError("Erreur lors de l'upload de l'avatar");
|
||||||
|
} finally {
|
||||||
|
setUploadingAvatar(false);
|
||||||
|
if (fileInputRef.current) {
|
||||||
|
fileInputRef.current.value = "";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleStep1Submit = async (e: React.FormEvent) => {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
setError("");
|
setError("");
|
||||||
|
|
||||||
@@ -49,6 +106,9 @@ export default function RegisterPage() {
|
|||||||
email: formData.email,
|
email: formData.email,
|
||||||
username: formData.username,
|
username: formData.username,
|
||||||
password: formData.password,
|
password: formData.password,
|
||||||
|
bio: null,
|
||||||
|
characterClass: null,
|
||||||
|
avatar: null,
|
||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -59,9 +119,51 @@ export default function RegisterPage() {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
setUserId(data.userId);
|
||||||
|
setStep(2);
|
||||||
|
} catch {
|
||||||
|
setError("Une erreur est survenue");
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleStep2Submit = async (e: FormEvent) => {
|
||||||
|
e.preventDefault();
|
||||||
|
setError("");
|
||||||
|
|
||||||
|
if (!userId) {
|
||||||
|
setError("Erreur: ID utilisateur manquant");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
setLoading(true);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await fetch("/api/register/complete", {
|
||||||
|
method: "POST",
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
},
|
||||||
|
body: JSON.stringify({
|
||||||
|
userId,
|
||||||
|
username: formData.username,
|
||||||
|
bio: formData.bio && formData.bio.trim() ? formData.bio.trim() : null,
|
||||||
|
characterClass: formData.characterClass || null,
|
||||||
|
avatar: formData.avatar || null,
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
const errorData = await response.json();
|
||||||
|
setError(errorData.error || "Une erreur est survenue");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
router.push("/login?registered=true");
|
router.push("/login?registered=true");
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
setError("Une erreur est survenue");
|
console.error("Registration completion error:", err);
|
||||||
|
setError(err instanceof Error ? err.message : "Une erreur est survenue");
|
||||||
} finally {
|
} finally {
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
}
|
}
|
||||||
@@ -70,120 +172,293 @@ export default function RegisterPage() {
|
|||||||
return (
|
return (
|
||||||
<main className="min-h-screen bg-black relative">
|
<main className="min-h-screen bg-black relative">
|
||||||
<Navigation />
|
<Navigation />
|
||||||
<section className="relative w-full min-h-screen flex flex-col items-center justify-center overflow-hidden pt-24">
|
<BackgroundSection backgroundImage="/got-2.jpg" className="pt-24">
|
||||||
{/* Background Image */}
|
|
||||||
<div
|
|
||||||
className="absolute inset-0 bg-cover bg-center bg-no-repeat"
|
|
||||||
style={{
|
|
||||||
backgroundImage: `url('/got-2.jpg')`,
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<div className="absolute inset-0 bg-gradient-to-b from-black/70 via-black/60 to-black/80"></div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Register Form */}
|
{/* Register Form */}
|
||||||
<div className="relative z-10 w-full max-w-md mx-auto px-8">
|
<div className="w-full max-w-4xl mx-auto px-8">
|
||||||
<div className="bg-black/80 border border-pixel-gold/30 rounded-lg p-8 backdrop-blur-sm">
|
<Card variant="dark" className="p-8">
|
||||||
<h1 className="text-4xl font-gaming font-black mb-2 text-center">
|
<SectionTitle
|
||||||
<span className="bg-gradient-to-r from-pixel-gold via-orange-400 to-pixel-gold bg-clip-text text-transparent">
|
variant="gradient"
|
||||||
INSCRIPTION
|
size="lg"
|
||||||
</span>
|
className="mb-2 text-center"
|
||||||
</h1>
|
>
|
||||||
<p className="text-gray-400 text-sm text-center mb-8">
|
INSCRIPTION
|
||||||
Créez votre compte pour commencer
|
</SectionTitle>
|
||||||
|
<p className="text-gray-400 text-sm text-center mb-4">
|
||||||
|
{step === 1
|
||||||
|
? "Créez votre compte pour commencer"
|
||||||
|
: "Personnalisez votre profil"}
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
<form onSubmit={handleSubmit} className="space-y-6">
|
{/* Step Indicator */}
|
||||||
{error && (
|
<div className="flex items-center justify-center gap-2 mb-8">
|
||||||
<div className="bg-red-900/50 border border-red-500/50 text-red-400 px-4 py-3 rounded text-sm">
|
<div
|
||||||
{error}
|
className={`w-8 h-8 rounded-full flex items-center justify-center text-xs font-bold transition ${
|
||||||
</div>
|
step >= 1
|
||||||
)}
|
? "bg-pixel-gold text-black"
|
||||||
|
: "bg-gray-700 text-gray-400"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
1
|
||||||
|
</div>
|
||||||
|
<div
|
||||||
|
className={`h-px w-12 transition ${
|
||||||
|
step >= 2 ? "bg-pixel-gold" : "bg-gray-700"
|
||||||
|
}`}
|
||||||
|
/>
|
||||||
|
<div
|
||||||
|
className={`w-8 h-8 rounded-full flex items-center justify-center text-xs font-bold transition ${
|
||||||
|
step >= 2
|
||||||
|
? "bg-pixel-gold text-black"
|
||||||
|
: "bg-gray-700 text-gray-400"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
2
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
<div>
|
{step === 1 ? (
|
||||||
<label
|
<form onSubmit={handleStep1Submit} className="space-y-6">
|
||||||
htmlFor="email"
|
{error && <Alert variant="error">{error}</Alert>}
|
||||||
className="block text-sm font-semibold text-gray-300 mb-2 uppercase tracking-wider"
|
|
||||||
>
|
<Input
|
||||||
Email
|
|
||||||
</label>
|
|
||||||
<input
|
|
||||||
id="email"
|
id="email"
|
||||||
name="email"
|
name="email"
|
||||||
type="email"
|
type="email"
|
||||||
|
label="Email"
|
||||||
value={formData.email}
|
value={formData.email}
|
||||||
onChange={handleChange}
|
onChange={handleChange}
|
||||||
required
|
required
|
||||||
className="w-full px-4 py-3 bg-black/60 border border-pixel-gold/30 rounded text-white placeholder-gray-500 focus:outline-none focus:border-pixel-gold transition"
|
|
||||||
placeholder="votre@email.com"
|
placeholder="votre@email.com"
|
||||||
/>
|
/>
|
||||||
</div>
|
|
||||||
|
|
||||||
<div>
|
<Input
|
||||||
<label
|
|
||||||
htmlFor="username"
|
|
||||||
className="block text-sm font-semibold text-gray-300 mb-2 uppercase tracking-wider"
|
|
||||||
>
|
|
||||||
Nom d'utilisateur
|
|
||||||
</label>
|
|
||||||
<input
|
|
||||||
id="username"
|
id="username"
|
||||||
name="username"
|
name="username"
|
||||||
type="text"
|
type="text"
|
||||||
|
label="Nom d'utilisateur"
|
||||||
value={formData.username}
|
value={formData.username}
|
||||||
onChange={handleChange}
|
onChange={handleChange}
|
||||||
required
|
required
|
||||||
className="w-full px-4 py-3 bg-black/60 border border-pixel-gold/30 rounded text-white placeholder-gray-500 focus:outline-none focus:border-pixel-gold transition"
|
|
||||||
placeholder="VotrePseudo"
|
placeholder="VotrePseudo"
|
||||||
/>
|
/>
|
||||||
</div>
|
|
||||||
|
|
||||||
<div>
|
<Input
|
||||||
<label
|
|
||||||
htmlFor="password"
|
|
||||||
className="block text-sm font-semibold text-gray-300 mb-2 uppercase tracking-wider"
|
|
||||||
>
|
|
||||||
Mot de passe
|
|
||||||
</label>
|
|
||||||
<input
|
|
||||||
id="password"
|
id="password"
|
||||||
name="password"
|
name="password"
|
||||||
type="password"
|
type="password"
|
||||||
|
label="Mot de passe"
|
||||||
value={formData.password}
|
value={formData.password}
|
||||||
onChange={handleChange}
|
onChange={handleChange}
|
||||||
required
|
required
|
||||||
className="w-full px-4 py-3 bg-black/60 border border-pixel-gold/30 rounded text-white placeholder-gray-500 focus:outline-none focus:border-pixel-gold transition"
|
|
||||||
placeholder="••••••••"
|
placeholder="••••••••"
|
||||||
/>
|
/>
|
||||||
</div>
|
|
||||||
|
|
||||||
<div>
|
<Input
|
||||||
<label
|
|
||||||
htmlFor="confirmPassword"
|
|
||||||
className="block text-sm font-semibold text-gray-300 mb-2 uppercase tracking-wider"
|
|
||||||
>
|
|
||||||
Confirmer le mot de passe
|
|
||||||
</label>
|
|
||||||
<input
|
|
||||||
id="confirmPassword"
|
id="confirmPassword"
|
||||||
name="confirmPassword"
|
name="confirmPassword"
|
||||||
type="password"
|
type="password"
|
||||||
|
label="Confirmer le mot de passe"
|
||||||
value={formData.confirmPassword}
|
value={formData.confirmPassword}
|
||||||
onChange={handleChange}
|
onChange={handleChange}
|
||||||
required
|
required
|
||||||
className="w-full px-4 py-3 bg-black/60 border border-pixel-gold/30 rounded text-white placeholder-gray-500 focus:outline-none focus:border-pixel-gold transition"
|
|
||||||
placeholder="••••••••"
|
placeholder="••••••••"
|
||||||
/>
|
/>
|
||||||
</div>
|
|
||||||
|
|
||||||
<button
|
<Button
|
||||||
type="submit"
|
type="submit"
|
||||||
disabled={loading}
|
variant="primary"
|
||||||
className="w-full px-6 py-3 border border-pixel-gold/50 bg-black/60 text-white uppercase text-sm tracking-widest rounded hover:bg-pixel-gold/10 hover:border-pixel-gold transition disabled:opacity-50 disabled:cursor-not-allowed"
|
size="lg"
|
||||||
>
|
disabled={loading}
|
||||||
{loading ? "Inscription..." : "S'inscrire"}
|
className="w-full"
|
||||||
</button>
|
>
|
||||||
</form>
|
{loading ? "Création..." : "Suivant"}
|
||||||
|
</Button>
|
||||||
|
</form>
|
||||||
|
) : (
|
||||||
|
<form onSubmit={handleStep2Submit} className="space-y-6">
|
||||||
|
{error && <Alert variant="error">{error}</Alert>}
|
||||||
|
|
||||||
|
{/* Avatar Selection */}
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm font-semibold text-gray-300 mb-3 uppercase tracking-wider">
|
||||||
|
Avatar (optionnel)
|
||||||
|
</label>
|
||||||
|
<div className="flex flex-col items-center gap-4">
|
||||||
|
{/* Preview */}
|
||||||
|
<div className="relative">
|
||||||
|
<Avatar
|
||||||
|
src={formData.avatar}
|
||||||
|
username={formData.username || "User"}
|
||||||
|
size="xl"
|
||||||
|
borderClassName="border-4 border-pixel-gold/50"
|
||||||
|
fallbackText={formData.username ? undefined : "?"}
|
||||||
|
/>
|
||||||
|
{uploadingAvatar && (
|
||||||
|
<div className="absolute inset-0 bg-black/60 flex items-center justify-center rounded-full">
|
||||||
|
<div className="text-pixel-gold text-xs">
|
||||||
|
Upload...
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Default Avatars */}
|
||||||
|
<div className="flex flex-col items-center gap-2 w-full">
|
||||||
|
<label className="text-pixel-gold text-xs uppercase tracking-widest">
|
||||||
|
Avatars par défaut
|
||||||
|
</label>
|
||||||
|
<div className="flex flex-wrap gap-2 justify-center">
|
||||||
|
{[
|
||||||
|
"/avatar-1.jpg",
|
||||||
|
"/avatar-2.jpg",
|
||||||
|
"/avatar-3.jpg",
|
||||||
|
"/avatar-4.jpg",
|
||||||
|
"/avatar-5.jpg",
|
||||||
|
"/avatar-6.jpg",
|
||||||
|
].map((defaultAvatar) => (
|
||||||
|
<button
|
||||||
|
key={defaultAvatar}
|
||||||
|
type="button"
|
||||||
|
onClick={() =>
|
||||||
|
setFormData({
|
||||||
|
...formData,
|
||||||
|
avatar: defaultAvatar,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
className={`w-16 h-16 rounded-full border-2 overflow-hidden transition ${
|
||||||
|
formData.avatar === defaultAvatar
|
||||||
|
? "border-pixel-gold scale-110"
|
||||||
|
: "border-pixel-gold/30 hover:border-pixel-gold/50"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<img
|
||||||
|
src={defaultAvatar}
|
||||||
|
alt="Avatar par défaut"
|
||||||
|
className="w-full h-full object-cover"
|
||||||
|
/>
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Custom Upload */}
|
||||||
|
<div>
|
||||||
|
<input
|
||||||
|
ref={fileInputRef}
|
||||||
|
type="file"
|
||||||
|
accept="image/*"
|
||||||
|
onChange={handleAvatarUpload}
|
||||||
|
className="hidden"
|
||||||
|
id="avatar-upload"
|
||||||
|
/>
|
||||||
|
<label htmlFor="avatar-upload">
|
||||||
|
<Button
|
||||||
|
variant="primary"
|
||||||
|
size="md"
|
||||||
|
as="span"
|
||||||
|
className="cursor-pointer"
|
||||||
|
>
|
||||||
|
{uploadingAvatar
|
||||||
|
? "Upload en cours..."
|
||||||
|
: "Upload un avatar custom"}
|
||||||
|
</Button>
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<Input
|
||||||
|
id="username-step2"
|
||||||
|
name="username"
|
||||||
|
type="text"
|
||||||
|
label="Nom d'utilisateur"
|
||||||
|
value={formData.username}
|
||||||
|
onChange={handleChange}
|
||||||
|
required
|
||||||
|
placeholder="VotrePseudo"
|
||||||
|
minLength={3}
|
||||||
|
maxLength={20}
|
||||||
|
/>
|
||||||
|
<p className="text-gray-500 text-xs mt-1">3-20 caractères</p>
|
||||||
|
|
||||||
|
<Textarea
|
||||||
|
id="bio"
|
||||||
|
name="bio"
|
||||||
|
label="Bio (optionnel)"
|
||||||
|
value={formData.bio}
|
||||||
|
onChange={handleChange}
|
||||||
|
rows={4}
|
||||||
|
maxLength={500}
|
||||||
|
showCharCount
|
||||||
|
placeholder="Parlez-nous de vous..."
|
||||||
|
/>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm font-semibold text-gray-300 mb-3 uppercase tracking-wider">
|
||||||
|
Classe de Personnage (optionnel)
|
||||||
|
</label>
|
||||||
|
<div className="grid grid-cols-2 md:grid-cols-3 gap-3">
|
||||||
|
{CHARACTER_CLASSES.map((cls) => (
|
||||||
|
<button
|
||||||
|
key={cls.value}
|
||||||
|
type="button"
|
||||||
|
onClick={() =>
|
||||||
|
setFormData({
|
||||||
|
...formData,
|
||||||
|
characterClass:
|
||||||
|
formData.characterClass === cls.value
|
||||||
|
? null
|
||||||
|
: cls.value,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
className={`p-4 border-2 rounded-lg text-left transition-all ${
|
||||||
|
formData.characterClass === cls.value
|
||||||
|
? "border-pixel-gold bg-pixel-gold/20 shadow-lg shadow-pixel-gold/30"
|
||||||
|
: "border-pixel-gold/30 bg-black/40 hover:border-pixel-gold/50 hover:bg-black/60"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<div className="flex items-center gap-2 mb-1">
|
||||||
|
<span className="text-2xl">{cls.icon}</span>
|
||||||
|
<span
|
||||||
|
className={`font-bold text-sm uppercase tracking-wider ${
|
||||||
|
formData.characterClass === cls.value
|
||||||
|
? "text-pixel-gold"
|
||||||
|
: "text-white"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{cls.name}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<p className="text-xs text-gray-400 leading-tight">
|
||||||
|
{cls.desc}
|
||||||
|
</p>
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex gap-4">
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="secondary"
|
||||||
|
size="lg"
|
||||||
|
onClick={() => setStep(1)}
|
||||||
|
className="flex-1"
|
||||||
|
>
|
||||||
|
Retour
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
type="submit"
|
||||||
|
variant="primary"
|
||||||
|
size="lg"
|
||||||
|
disabled={loading}
|
||||||
|
className="flex-1"
|
||||||
|
>
|
||||||
|
{loading ? "Finalisation..." : "Terminer"}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
)}
|
||||||
|
|
||||||
<div className="mt-6 text-center">
|
<div className="mt-6 text-center">
|
||||||
<p className="text-gray-400 text-sm">
|
<p className="text-gray-400 text-sm">
|
||||||
@@ -196,9 +471,9 @@ export default function RegisterPage() {
|
|||||||
</Link>
|
</Link>
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</Card>
|
||||||
</div>
|
</div>
|
||||||
</section>
|
</BackgroundSection>
|
||||||
</main>
|
</main>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
542
app/style-guide/page.tsx
Normal file
542
app/style-guide/page.tsx
Normal file
@@ -0,0 +1,542 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useState } from "react";
|
||||||
|
import Navigation from "@/components/navigation/Navigation";
|
||||||
|
import {
|
||||||
|
Button,
|
||||||
|
Input,
|
||||||
|
Textarea,
|
||||||
|
Select,
|
||||||
|
Card,
|
||||||
|
Badge,
|
||||||
|
Alert,
|
||||||
|
Modal,
|
||||||
|
ProgressBar,
|
||||||
|
StarRating,
|
||||||
|
Avatar,
|
||||||
|
SectionTitle,
|
||||||
|
BackgroundSection,
|
||||||
|
CloseButton,
|
||||||
|
} from "@/components/ui";
|
||||||
|
|
||||||
|
export default function StyleGuidePage() {
|
||||||
|
const [modalOpen, setModalOpen] = useState(false);
|
||||||
|
const [inputValue, setInputValue] = useState("");
|
||||||
|
const [textareaValue, setTextareaValue] = useState("");
|
||||||
|
const [selectValue, setSelectValue] = useState("");
|
||||||
|
const [rating, setRating] = useState(0);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<main className="min-h-screen bg-black relative">
|
||||||
|
<Navigation />
|
||||||
|
<BackgroundSection backgroundImage="/got-2.jpg" className="pt-24 pb-16">
|
||||||
|
<div className="w-full max-w-6xl mx-auto px-8">
|
||||||
|
<SectionTitle variant="gradient" size="xl" className="mb-16">
|
||||||
|
STYLE GUIDE
|
||||||
|
</SectionTitle>
|
||||||
|
<p className="text-gray-400 text-center mb-12 max-w-3xl mx-auto">
|
||||||
|
Guide de style complet avec tous les composants UI disponibles et
|
||||||
|
leurs variantes
|
||||||
|
</p>
|
||||||
|
|
||||||
|
{/* Buttons */}
|
||||||
|
<Card variant="dark" className="p-6 mb-8">
|
||||||
|
<h2 className="text-2xl font-bold text-pixel-gold mb-6">Buttons</h2>
|
||||||
|
<div className="space-y-6">
|
||||||
|
<div>
|
||||||
|
<h3 className="text-lg text-gray-300 mb-3">Variantes</h3>
|
||||||
|
<div className="flex flex-wrap gap-4">
|
||||||
|
<Button variant="primary">Primary</Button>
|
||||||
|
<Button variant="secondary">Secondary</Button>
|
||||||
|
<Button variant="success">Success</Button>
|
||||||
|
<Button variant="danger">Danger</Button>
|
||||||
|
<Button variant="ghost">Ghost</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<h3 className="text-lg text-gray-300 mb-3">Tailles</h3>
|
||||||
|
<div className="flex flex-wrap items-center gap-4">
|
||||||
|
<Button variant="primary" size="sm">
|
||||||
|
Small
|
||||||
|
</Button>
|
||||||
|
<Button variant="primary" size="md">
|
||||||
|
Medium
|
||||||
|
</Button>
|
||||||
|
<Button variant="primary" size="lg">
|
||||||
|
Large
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<h3 className="text-lg text-gray-300 mb-3">États</h3>
|
||||||
|
<div className="flex flex-wrap gap-4">
|
||||||
|
<Button variant="primary">Normal</Button>
|
||||||
|
<Button variant="primary" disabled>
|
||||||
|
Disabled
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
{/* Inputs */}
|
||||||
|
<Card variant="dark" className="p-6 mb-8">
|
||||||
|
<h2 className="text-2xl font-bold text-pixel-gold mb-6">Inputs</h2>
|
||||||
|
<div className="space-y-6">
|
||||||
|
<div>
|
||||||
|
<h3 className="text-lg text-gray-300 mb-3">Types</h3>
|
||||||
|
<div className="space-y-4 max-w-md">
|
||||||
|
<Input
|
||||||
|
label="Text Input"
|
||||||
|
type="text"
|
||||||
|
placeholder="Entrez du texte"
|
||||||
|
value={inputValue}
|
||||||
|
onChange={(e) => setInputValue(e.target.value)}
|
||||||
|
/>
|
||||||
|
<Input
|
||||||
|
label="Email Input"
|
||||||
|
type="email"
|
||||||
|
placeholder="email@example.com"
|
||||||
|
/>
|
||||||
|
<Input
|
||||||
|
label="Password Input"
|
||||||
|
type="password"
|
||||||
|
placeholder="••••••••"
|
||||||
|
/>
|
||||||
|
<Input label="Number Input" type="number" placeholder="123" />
|
||||||
|
<Input label="Date Input" type="date" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<h3 className="text-lg text-gray-300 mb-3">Avec erreur</h3>
|
||||||
|
<div className="max-w-md">
|
||||||
|
<Input
|
||||||
|
label="Input avec erreur"
|
||||||
|
type="text"
|
||||||
|
error="Ce champ est requis"
|
||||||
|
value={inputValue}
|
||||||
|
onChange={(e) => setInputValue(e.target.value)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
{/* Textarea */}
|
||||||
|
<Card variant="dark" className="p-6 mb-8">
|
||||||
|
<h2 className="text-2xl font-bold text-pixel-gold mb-6">
|
||||||
|
Textarea
|
||||||
|
</h2>
|
||||||
|
<div className="space-y-6">
|
||||||
|
<div>
|
||||||
|
<h3 className="text-lg text-gray-300 mb-3">Basique</h3>
|
||||||
|
<div className="max-w-md">
|
||||||
|
<Textarea
|
||||||
|
label="Commentaire"
|
||||||
|
placeholder="Écrivez votre commentaire..."
|
||||||
|
value={textareaValue}
|
||||||
|
onChange={(e) => setTextareaValue(e.target.value)}
|
||||||
|
rows={4}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<h3 className="text-lg text-gray-300 mb-3">
|
||||||
|
Avec compteur de caractères
|
||||||
|
</h3>
|
||||||
|
<div className="max-w-md">
|
||||||
|
<Textarea
|
||||||
|
label="Bio"
|
||||||
|
placeholder="Parlez-nous de vous..."
|
||||||
|
value={textareaValue}
|
||||||
|
onChange={(e) => setTextareaValue(e.target.value)}
|
||||||
|
rows={4}
|
||||||
|
maxLength={500}
|
||||||
|
showCharCount
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<h3 className="text-lg text-gray-300 mb-3">Avec erreur</h3>
|
||||||
|
<div className="max-w-md">
|
||||||
|
<Textarea
|
||||||
|
label="Textarea avec erreur"
|
||||||
|
placeholder="Écrivez quelque chose..."
|
||||||
|
error="Ce champ est requis"
|
||||||
|
value={textareaValue}
|
||||||
|
onChange={(e) => setTextareaValue(e.target.value)}
|
||||||
|
rows={4}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
{/* Select */}
|
||||||
|
<Card variant="dark" className="p-6 mb-8">
|
||||||
|
<h2 className="text-2xl font-bold text-pixel-gold mb-6">Select</h2>
|
||||||
|
<div className="space-y-6">
|
||||||
|
<div>
|
||||||
|
<h3 className="text-lg text-gray-300 mb-3">Basique</h3>
|
||||||
|
<div className="max-w-md">
|
||||||
|
<Select
|
||||||
|
label="Sélectionner une option"
|
||||||
|
value={selectValue}
|
||||||
|
onChange={(e) => setSelectValue(e.target.value)}
|
||||||
|
>
|
||||||
|
<option value="">Choisir...</option>
|
||||||
|
<option value="option1">Option 1</option>
|
||||||
|
<option value="option2">Option 2</option>
|
||||||
|
<option value="option3">Option 3</option>
|
||||||
|
</Select>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<h3 className="text-lg text-gray-300 mb-3">Sans label</h3>
|
||||||
|
<div className="max-w-md">
|
||||||
|
<Select
|
||||||
|
value={selectValue}
|
||||||
|
onChange={(e) => setSelectValue(e.target.value)}
|
||||||
|
>
|
||||||
|
<option value="">Choisir...</option>
|
||||||
|
<option value="option1">Option 1</option>
|
||||||
|
<option value="option2">Option 2</option>
|
||||||
|
<option value="option3">Option 3</option>
|
||||||
|
</Select>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<h3 className="text-lg text-gray-300 mb-3">Avec erreur</h3>
|
||||||
|
<div className="max-w-md">
|
||||||
|
<Select
|
||||||
|
label="Select avec erreur"
|
||||||
|
value={selectValue}
|
||||||
|
onChange={(e) => setSelectValue(e.target.value)}
|
||||||
|
error="Veuillez sélectionner une option"
|
||||||
|
>
|
||||||
|
<option value="">Choisir...</option>
|
||||||
|
<option value="option1">Option 1</option>
|
||||||
|
<option value="option2">Option 2</option>
|
||||||
|
<option value="option3">Option 3</option>
|
||||||
|
</Select>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<h3 className="text-lg text-gray-300 mb-3">Disabled</h3>
|
||||||
|
<div className="max-w-md">
|
||||||
|
<Select
|
||||||
|
label="Select désactivé"
|
||||||
|
value={selectValue}
|
||||||
|
onChange={(e) => setSelectValue(e.target.value)}
|
||||||
|
disabled
|
||||||
|
>
|
||||||
|
<option value="">Choisir...</option>
|
||||||
|
<option value="option1">Option 1</option>
|
||||||
|
<option value="option2">Option 2</option>
|
||||||
|
<option value="option3">Option 3</option>
|
||||||
|
</Select>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
{/* Badges */}
|
||||||
|
<Card variant="dark" className="p-6 mb-8">
|
||||||
|
<h2 className="text-2xl font-bold text-pixel-gold mb-6">Badges</h2>
|
||||||
|
<div className="space-y-6">
|
||||||
|
<div>
|
||||||
|
<h3 className="text-lg text-gray-300 mb-3">Variantes</h3>
|
||||||
|
<div className="flex flex-wrap gap-4">
|
||||||
|
<Badge variant="default">Default</Badge>
|
||||||
|
<Badge variant="success">Success</Badge>
|
||||||
|
<Badge variant="warning">Warning</Badge>
|
||||||
|
<Badge variant="danger">Danger</Badge>
|
||||||
|
<Badge variant="info">Info</Badge>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<h3 className="text-lg text-gray-300 mb-3">Tailles</h3>
|
||||||
|
<div className="flex flex-wrap items-center gap-4">
|
||||||
|
<Badge variant="default" size="xs">
|
||||||
|
Extra Small
|
||||||
|
</Badge>
|
||||||
|
<Badge variant="default" size="sm">
|
||||||
|
Small
|
||||||
|
</Badge>
|
||||||
|
<Badge variant="default" size="md">
|
||||||
|
Medium
|
||||||
|
</Badge>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
{/* Alerts */}
|
||||||
|
<Card variant="dark" className="p-6 mb-8">
|
||||||
|
<h2 className="text-2xl font-bold text-pixel-gold mb-6">Alerts</h2>
|
||||||
|
<div className="space-y-4 max-w-md">
|
||||||
|
<Alert variant="success">
|
||||||
|
Opération réussie ! Votre action a été effectuée avec succès.
|
||||||
|
</Alert>
|
||||||
|
<Alert variant="error">
|
||||||
|
Une erreur est survenue. Veuillez réessayer.
|
||||||
|
</Alert>
|
||||||
|
<Alert variant="warning">
|
||||||
|
Attention ! Cette action est irréversible.
|
||||||
|
</Alert>
|
||||||
|
<Alert variant="info">
|
||||||
|
Information : Voici quelques informations utiles.
|
||||||
|
</Alert>
|
||||||
|
</div>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
{/* Cards */}
|
||||||
|
<Card variant="dark" className="p-6 mb-8">
|
||||||
|
<h2 className="text-2xl font-bold text-pixel-gold mb-6">Cards</h2>
|
||||||
|
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||||
|
<Card variant="default" className="p-4">
|
||||||
|
<h3 className="text-lg font-bold text-pixel-gold mb-2">
|
||||||
|
Card Default
|
||||||
|
</h3>
|
||||||
|
<p className="text-gray-300 text-sm">
|
||||||
|
Contenu de la carte avec variant default
|
||||||
|
</p>
|
||||||
|
</Card>
|
||||||
|
<Card variant="dark" className="p-4">
|
||||||
|
<h3 className="text-lg font-bold text-pixel-gold mb-2">
|
||||||
|
Card Dark
|
||||||
|
</h3>
|
||||||
|
<p className="text-gray-300 text-sm">
|
||||||
|
Contenu de la carte avec variant dark
|
||||||
|
</p>
|
||||||
|
</Card>
|
||||||
|
</div>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
{/* Progress Bars */}
|
||||||
|
<Card variant="dark" className="p-6 mb-8">
|
||||||
|
<h2 className="text-2xl font-bold text-pixel-gold mb-6">
|
||||||
|
Progress Bars
|
||||||
|
</h2>
|
||||||
|
<div className="space-y-6 max-w-md">
|
||||||
|
<div>
|
||||||
|
<h3 className="text-lg text-gray-300 mb-3">HP Bar (High)</h3>
|
||||||
|
<ProgressBar
|
||||||
|
value={75}
|
||||||
|
max={100}
|
||||||
|
variant="hp"
|
||||||
|
showLabel
|
||||||
|
label="HP"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<h3 className="text-lg text-gray-300 mb-3">HP Bar (Medium)</h3>
|
||||||
|
<ProgressBar
|
||||||
|
value={45}
|
||||||
|
max={100}
|
||||||
|
variant="hp"
|
||||||
|
showLabel
|
||||||
|
label="HP"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<h3 className="text-lg text-gray-300 mb-3">HP Bar (Low)</h3>
|
||||||
|
<ProgressBar
|
||||||
|
value={20}
|
||||||
|
max={100}
|
||||||
|
variant="hp"
|
||||||
|
showLabel
|
||||||
|
label="HP"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<h3 className="text-lg text-gray-300 mb-3">XP Bar</h3>
|
||||||
|
<ProgressBar
|
||||||
|
value={60}
|
||||||
|
max={100}
|
||||||
|
variant="xp"
|
||||||
|
showLabel
|
||||||
|
label="XP"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<h3 className="text-lg text-gray-300 mb-3">Default</h3>
|
||||||
|
<ProgressBar
|
||||||
|
value={50}
|
||||||
|
max={100}
|
||||||
|
variant="default"
|
||||||
|
showLabel
|
||||||
|
label="Progress"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<h3 className="text-lg text-gray-300 mb-3">Sans label</h3>
|
||||||
|
<ProgressBar value={60} max={100} variant="default" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
{/* Star Rating */}
|
||||||
|
<Card variant="dark" className="p-6 mb-8">
|
||||||
|
<h2 className="text-2xl font-bold text-pixel-gold mb-6">
|
||||||
|
Star Rating
|
||||||
|
</h2>
|
||||||
|
<div className="space-y-6">
|
||||||
|
<div>
|
||||||
|
<h3 className="text-lg text-gray-300 mb-3">Interactif</h3>
|
||||||
|
<StarRating value={rating} onChange={setRating} showValue />
|
||||||
|
<p className="text-gray-400 text-sm mt-2">
|
||||||
|
Note sélectionnée : {rating}/5
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<h3 className="text-lg text-gray-300 mb-3">Tailles</h3>
|
||||||
|
<div className="space-y-4">
|
||||||
|
<div>
|
||||||
|
<p className="text-gray-400 text-sm mb-2">Small</p>
|
||||||
|
<StarRating value={4} size="sm" />
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<p className="text-gray-400 text-sm mb-2">Medium</p>
|
||||||
|
<StarRating value={4} size="md" />
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<p className="text-gray-400 text-sm mb-2">Large</p>
|
||||||
|
<StarRating value={4} size="lg" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
{/* Avatar */}
|
||||||
|
<Card variant="dark" className="p-6 mb-8">
|
||||||
|
<h2 className="text-2xl font-bold text-pixel-gold mb-6">Avatar</h2>
|
||||||
|
<div className="space-y-6">
|
||||||
|
<div>
|
||||||
|
<h3 className="text-lg text-gray-300 mb-3">Tailles</h3>
|
||||||
|
<div className="flex items-center gap-6">
|
||||||
|
<Avatar src="/avatar-1.jpg" username="User" size="sm" />
|
||||||
|
<Avatar src="/avatar-2.jpg" username="User" size="md" />
|
||||||
|
<Avatar src="/avatar-3.jpg" username="User" size="lg" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<h3 className="text-lg text-gray-300 mb-3">
|
||||||
|
Sans image (fallback)
|
||||||
|
</h3>
|
||||||
|
<Avatar src={null} username="John Doe" size="lg" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
{/* Section Title */}
|
||||||
|
<Card variant="dark" className="p-6 mb-8">
|
||||||
|
<h2 className="text-2xl font-bold text-pixel-gold mb-6">
|
||||||
|
Section Title
|
||||||
|
</h2>
|
||||||
|
<div className="space-y-8">
|
||||||
|
<div>
|
||||||
|
<h3 className="text-lg text-gray-300 mb-3">Variantes</h3>
|
||||||
|
<div className="space-y-4">
|
||||||
|
<SectionTitle variant="default" size="md">
|
||||||
|
Default Title
|
||||||
|
</SectionTitle>
|
||||||
|
<SectionTitle variant="gradient" size="md">
|
||||||
|
Gradient Title
|
||||||
|
</SectionTitle>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<h3 className="text-lg text-gray-300 mb-3">Tailles</h3>
|
||||||
|
<div className="space-y-4">
|
||||||
|
<SectionTitle variant="gradient" size="sm">
|
||||||
|
Small Title
|
||||||
|
</SectionTitle>
|
||||||
|
<SectionTitle variant="gradient" size="md">
|
||||||
|
Medium Title
|
||||||
|
</SectionTitle>
|
||||||
|
<SectionTitle variant="gradient" size="lg">
|
||||||
|
Large Title
|
||||||
|
</SectionTitle>
|
||||||
|
<SectionTitle variant="gradient" size="xl">
|
||||||
|
Extra Large Title
|
||||||
|
</SectionTitle>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<h3 className="text-lg text-gray-300 mb-3">Avec sous-titre</h3>
|
||||||
|
<SectionTitle
|
||||||
|
variant="gradient"
|
||||||
|
size="lg"
|
||||||
|
subtitle="Un sous-titre descriptif"
|
||||||
|
>
|
||||||
|
Title with Subtitle
|
||||||
|
</SectionTitle>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
{/* Modal */}
|
||||||
|
<Card variant="dark" className="p-6 mb-8">
|
||||||
|
<h2 className="text-2xl font-bold text-pixel-gold mb-6">Modal</h2>
|
||||||
|
<div className="space-y-6">
|
||||||
|
<div>
|
||||||
|
<h3 className="text-lg text-gray-300 mb-3">Tailles</h3>
|
||||||
|
<div className="flex flex-wrap gap-4">
|
||||||
|
<Button onClick={() => setModalOpen(true)}>
|
||||||
|
Ouvrir Modal
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
{/* Close Button */}
|
||||||
|
<Card variant="dark" className="p-6 mb-8">
|
||||||
|
<h2 className="text-2xl font-bold text-pixel-gold mb-6">
|
||||||
|
Close Button
|
||||||
|
</h2>
|
||||||
|
<div className="space-y-6">
|
||||||
|
<div>
|
||||||
|
<h3 className="text-lg text-gray-300 mb-3">Tailles</h3>
|
||||||
|
<div className="flex items-center gap-6">
|
||||||
|
<CloseButton onClick={() => {}} size="sm" />
|
||||||
|
<CloseButton onClick={() => {}} size="md" />
|
||||||
|
<CloseButton onClick={() => {}} size="lg" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<h3 className="text-lg text-gray-300 mb-3">Disabled</h3>
|
||||||
|
<CloseButton onClick={() => {}} disabled />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
{/* Modal Demo */}
|
||||||
|
<Modal
|
||||||
|
isOpen={modalOpen}
|
||||||
|
onClose={() => setModalOpen(false)}
|
||||||
|
size="md"
|
||||||
|
>
|
||||||
|
<div className="p-8">
|
||||||
|
<div className="flex items-center justify-between mb-6">
|
||||||
|
<h2 className="text-2xl font-bold text-pixel-gold">
|
||||||
|
Exemple de Modal
|
||||||
|
</h2>
|
||||||
|
<CloseButton onClick={() => setModalOpen(false)} />
|
||||||
|
</div>
|
||||||
|
<p className="text-gray-300 mb-6">
|
||||||
|
Ceci est un exemple de modal avec différentes tailles
|
||||||
|
disponibles.
|
||||||
|
</p>
|
||||||
|
<div className="flex gap-4">
|
||||||
|
<Button onClick={() => setModalOpen(false)}>Fermer</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</Modal>
|
||||||
|
</div>
|
||||||
|
</BackgroundSection>
|
||||||
|
</main>
|
||||||
|
);
|
||||||
|
}
|
||||||
75
components/Avatar.tsx
Normal file
75
components/Avatar.tsx
Normal file
@@ -0,0 +1,75 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useState, useEffect, useRef } from "react";
|
||||||
|
import { normalizeAvatarUrl } from "@/lib/avatars";
|
||||||
|
|
||||||
|
interface AvatarProps {
|
||||||
|
src: string | null | undefined;
|
||||||
|
username: string;
|
||||||
|
size?: "xs" | "sm" | "md" | "lg" | "xl" | "2xl";
|
||||||
|
className?: string;
|
||||||
|
borderClassName?: string;
|
||||||
|
fallbackText?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
const sizeClasses = {
|
||||||
|
xs: "w-6 h-6 text-[8px]",
|
||||||
|
sm: "w-8 h-8 text-[10px]",
|
||||||
|
md: "w-10 h-10 text-xs",
|
||||||
|
lg: "w-16 h-16 sm:w-20 sm:h-20 text-xl sm:text-2xl",
|
||||||
|
xl: "w-24 h-24 text-4xl",
|
||||||
|
"2xl": "w-32 h-32 text-4xl",
|
||||||
|
};
|
||||||
|
|
||||||
|
export default function Avatar({
|
||||||
|
src,
|
||||||
|
username,
|
||||||
|
size = "md",
|
||||||
|
className = "",
|
||||||
|
borderClassName = "",
|
||||||
|
fallbackText,
|
||||||
|
}: AvatarProps) {
|
||||||
|
const [avatarError, setAvatarError] = useState(false);
|
||||||
|
const prevSrcRef = useRef<string | null | undefined>(undefined);
|
||||||
|
|
||||||
|
// Reset error state when src changes
|
||||||
|
useEffect(() => {
|
||||||
|
if (src !== prevSrcRef.current) {
|
||||||
|
prevSrcRef.current = src;
|
||||||
|
// Reset error when src changes to allow retry
|
||||||
|
// eslint-disable-next-line react-hooks/set-state-in-effect
|
||||||
|
setAvatarError(false);
|
||||||
|
}
|
||||||
|
}, [src]);
|
||||||
|
|
||||||
|
const sizeClass = sizeClasses[size];
|
||||||
|
const normalizedSrc = normalizeAvatarUrl(src);
|
||||||
|
const displaySrc = normalizedSrc && !avatarError ? normalizedSrc : null;
|
||||||
|
const initial = fallbackText || username.charAt(0).toUpperCase();
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
className={`${sizeClass} rounded-full border overflow-hidden flex items-center justify-center relative ${className} ${borderClassName}`}
|
||||||
|
style={{
|
||||||
|
backgroundColor: "var(--card)",
|
||||||
|
borderColor: "var(--border)",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{displaySrc ? (
|
||||||
|
<img
|
||||||
|
key={displaySrc}
|
||||||
|
src={displaySrc}
|
||||||
|
alt={username}
|
||||||
|
className="w-full h-full object-cover absolute inset-0"
|
||||||
|
onError={() => setAvatarError(true)}
|
||||||
|
/>
|
||||||
|
) : null}
|
||||||
|
<span
|
||||||
|
className={`font-bold ${displaySrc ? "hidden" : ""}`}
|
||||||
|
style={{ color: "var(--accent-color)" }}
|
||||||
|
>
|
||||||
|
{initial}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,381 +0,0 @@
|
|||||||
"use client";
|
|
||||||
|
|
||||||
import { useState, useEffect } from "react";
|
|
||||||
|
|
||||||
interface Event {
|
|
||||||
id: string;
|
|
||||||
date: string;
|
|
||||||
name: string;
|
|
||||||
description: string;
|
|
||||||
type: "SUMMIT" | "LAUNCH" | "FESTIVAL" | "COMPETITION";
|
|
||||||
status: "UPCOMING" | "LIVE" | "PAST";
|
|
||||||
createdAt: string;
|
|
||||||
updatedAt: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface EventFormData {
|
|
||||||
date: string;
|
|
||||||
name: string;
|
|
||||||
description: string;
|
|
||||||
type: "SUMMIT" | "LAUNCH" | "FESTIVAL" | "COMPETITION";
|
|
||||||
status: "UPCOMING" | "LIVE" | "PAST";
|
|
||||||
}
|
|
||||||
|
|
||||||
const eventTypes: Event["type"][] = [
|
|
||||||
"SUMMIT",
|
|
||||||
"LAUNCH",
|
|
||||||
"FESTIVAL",
|
|
||||||
"COMPETITION",
|
|
||||||
];
|
|
||||||
const eventStatuses: Event["status"][] = ["UPCOMING", "LIVE", "PAST"];
|
|
||||||
|
|
||||||
const getEventTypeLabel = (type: Event["type"]) => {
|
|
||||||
switch (type) {
|
|
||||||
case "SUMMIT":
|
|
||||||
return "Sommet";
|
|
||||||
case "LAUNCH":
|
|
||||||
return "Lancement";
|
|
||||||
case "FESTIVAL":
|
|
||||||
return "Festival";
|
|
||||||
case "COMPETITION":
|
|
||||||
return "Compétition";
|
|
||||||
default:
|
|
||||||
return type;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const getStatusLabel = (status: Event["status"]) => {
|
|
||||||
switch (status) {
|
|
||||||
case "UPCOMING":
|
|
||||||
return "À venir";
|
|
||||||
case "LIVE":
|
|
||||||
return "En cours";
|
|
||||||
case "PAST":
|
|
||||||
return "Passé";
|
|
||||||
default:
|
|
||||||
return status;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
export default function EventManagement() {
|
|
||||||
const [events, setEvents] = useState<Event[]>([]);
|
|
||||||
const [loading, setLoading] = useState(true);
|
|
||||||
const [editingEvent, setEditingEvent] = useState<Event | null>(null);
|
|
||||||
const [isCreating, setIsCreating] = useState(false);
|
|
||||||
const [saving, setSaving] = useState(false);
|
|
||||||
const [formData, setFormData] = useState<EventFormData>({
|
|
||||||
date: "",
|
|
||||||
name: "",
|
|
||||||
description: "",
|
|
||||||
type: "SUMMIT",
|
|
||||||
status: "UPCOMING",
|
|
||||||
});
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
fetchEvents();
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
const fetchEvents = async () => {
|
|
||||||
try {
|
|
||||||
const response = await fetch("/api/admin/events");
|
|
||||||
if (response.ok) {
|
|
||||||
const data = await response.json();
|
|
||||||
setEvents(data);
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
console.error("Error fetching events:", error);
|
|
||||||
} finally {
|
|
||||||
setLoading(false);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleCreate = () => {
|
|
||||||
setIsCreating(true);
|
|
||||||
setEditingEvent(null);
|
|
||||||
setFormData({
|
|
||||||
date: "",
|
|
||||||
name: "",
|
|
||||||
description: "",
|
|
||||||
type: "SUMMIT",
|
|
||||||
status: "UPCOMING",
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleEdit = (event: Event) => {
|
|
||||||
setEditingEvent(event);
|
|
||||||
setIsCreating(false);
|
|
||||||
setFormData({
|
|
||||||
date: event.date,
|
|
||||||
name: event.name,
|
|
||||||
description: event.description,
|
|
||||||
type: event.type,
|
|
||||||
status: event.status,
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleSave = async () => {
|
|
||||||
setSaving(true);
|
|
||||||
try {
|
|
||||||
let response;
|
|
||||||
if (isCreating) {
|
|
||||||
response = await fetch("/api/admin/events", {
|
|
||||||
method: "POST",
|
|
||||||
headers: {
|
|
||||||
"Content-Type": "application/json",
|
|
||||||
},
|
|
||||||
body: JSON.stringify(formData),
|
|
||||||
});
|
|
||||||
} else if (editingEvent) {
|
|
||||||
response = await fetch(`/api/admin/events/${editingEvent.id}`, {
|
|
||||||
method: "PUT",
|
|
||||||
headers: {
|
|
||||||
"Content-Type": "application/json",
|
|
||||||
},
|
|
||||||
body: JSON.stringify(formData),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
if (response?.ok) {
|
|
||||||
await fetchEvents();
|
|
||||||
setEditingEvent(null);
|
|
||||||
setIsCreating(false);
|
|
||||||
setFormData({
|
|
||||||
date: "",
|
|
||||||
name: "",
|
|
||||||
description: "",
|
|
||||||
type: "SUMMIT",
|
|
||||||
status: "UPCOMING",
|
|
||||||
});
|
|
||||||
} else {
|
|
||||||
const error = await response?.json();
|
|
||||||
alert(error.error || "Erreur lors de la sauvegarde");
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
console.error("Error saving event:", error);
|
|
||||||
alert("Erreur lors de la sauvegarde");
|
|
||||||
} finally {
|
|
||||||
setSaving(false);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleDelete = async (eventId: string) => {
|
|
||||||
if (!confirm("Êtes-vous sûr de vouloir supprimer cet événement ?")) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
const response = await fetch(`/api/admin/events/${eventId}`, {
|
|
||||||
method: "DELETE",
|
|
||||||
});
|
|
||||||
|
|
||||||
if (response.ok) {
|
|
||||||
await fetchEvents();
|
|
||||||
} else {
|
|
||||||
const error = await response.json();
|
|
||||||
alert(error.error || "Erreur lors de la suppression");
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
console.error("Error deleting event:", error);
|
|
||||||
alert("Erreur lors de la suppression");
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleCancel = () => {
|
|
||||||
setEditingEvent(null);
|
|
||||||
setIsCreating(false);
|
|
||||||
setFormData({
|
|
||||||
date: "",
|
|
||||||
name: "",
|
|
||||||
description: "",
|
|
||||||
type: "SUMMIT",
|
|
||||||
status: "UPCOMING",
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
if (loading) {
|
|
||||||
return <div className="text-center text-gray-400 py-8">Chargement...</div>;
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="space-y-4">
|
|
||||||
<div className="flex justify-between items-center mb-4">
|
|
||||||
<h3 className="text-xl font-gaming font-bold text-pixel-gold">
|
|
||||||
Événements ({events.length})
|
|
||||||
</h3>
|
|
||||||
{!isCreating && !editingEvent && (
|
|
||||||
<button
|
|
||||||
onClick={handleCreate}
|
|
||||||
className="px-4 py-2 border border-green-500/50 bg-green-900/20 text-green-400 uppercase text-xs tracking-widest rounded hover:bg-green-900/30 transition"
|
|
||||||
>
|
|
||||||
+ Nouvel événement
|
|
||||||
</button>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{(isCreating || editingEvent) && (
|
|
||||||
<div className="bg-black/60 border border-pixel-gold/20 rounded p-4 mb-4">
|
|
||||||
<h4 className="text-pixel-gold font-bold mb-4">
|
|
||||||
{isCreating ? "Créer un événement" : "Modifier l'événement"}
|
|
||||||
</h4>
|
|
||||||
<div className="space-y-4">
|
|
||||||
<div>
|
|
||||||
<label className="block text-sm text-gray-300 mb-1">Date</label>
|
|
||||||
<input
|
|
||||||
type="date"
|
|
||||||
value={formData.date}
|
|
||||||
onChange={(e) =>
|
|
||||||
setFormData({ ...formData, date: e.target.value })
|
|
||||||
}
|
|
||||||
className="w-full px-3 py-2 bg-black/60 border border-pixel-gold/30 rounded text-white text-sm"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<label className="block text-sm text-gray-300 mb-1">Nom</label>
|
|
||||||
<input
|
|
||||||
type="text"
|
|
||||||
value={formData.name}
|
|
||||||
onChange={(e) =>
|
|
||||||
setFormData({ ...formData, name: e.target.value })
|
|
||||||
}
|
|
||||||
placeholder="Nom de l'événement"
|
|
||||||
className="w-full px-3 py-2 bg-black/60 border border-pixel-gold/30 rounded text-white text-sm"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<label className="block text-sm text-gray-300 mb-1">
|
|
||||||
Description
|
|
||||||
</label>
|
|
||||||
<textarea
|
|
||||||
value={formData.description}
|
|
||||||
onChange={(e) =>
|
|
||||||
setFormData({ ...formData, description: e.target.value })
|
|
||||||
}
|
|
||||||
placeholder="Description de l'événement"
|
|
||||||
rows={4}
|
|
||||||
className="w-full px-3 py-2 bg-black/60 border border-pixel-gold/30 rounded text-white text-sm"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<div className="grid grid-cols-2 gap-4">
|
|
||||||
<div>
|
|
||||||
<label className="block text-sm text-gray-300 mb-1">Type</label>
|
|
||||||
<select
|
|
||||||
value={formData.type}
|
|
||||||
onChange={(e) =>
|
|
||||||
setFormData({
|
|
||||||
...formData,
|
|
||||||
type: e.target.value as Event["type"],
|
|
||||||
})
|
|
||||||
}
|
|
||||||
className="w-full px-3 py-2 bg-black/60 border border-pixel-gold/30 rounded text-white text-sm"
|
|
||||||
>
|
|
||||||
{eventTypes.map((type) => (
|
|
||||||
<option key={type} value={type}>
|
|
||||||
{getEventTypeLabel(type)}
|
|
||||||
</option>
|
|
||||||
))}
|
|
||||||
</select>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<label className="block text-sm text-gray-300 mb-1">
|
|
||||||
Statut
|
|
||||||
</label>
|
|
||||||
<select
|
|
||||||
value={formData.status}
|
|
||||||
onChange={(e) =>
|
|
||||||
setFormData({
|
|
||||||
...formData,
|
|
||||||
status: e.target.value as Event["status"],
|
|
||||||
})
|
|
||||||
}
|
|
||||||
className="w-full px-3 py-2 bg-black/60 border border-pixel-gold/30 rounded text-white text-sm"
|
|
||||||
>
|
|
||||||
{eventStatuses.map((status) => (
|
|
||||||
<option key={status} value={status}>
|
|
||||||
{getStatusLabel(status)}
|
|
||||||
</option>
|
|
||||||
))}
|
|
||||||
</select>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div className="flex gap-2">
|
|
||||||
<button
|
|
||||||
onClick={handleSave}
|
|
||||||
disabled={saving}
|
|
||||||
className="px-4 py-2 border border-green-500/50 bg-green-900/20 text-green-400 uppercase text-xs tracking-widest rounded hover:bg-green-900/30 transition disabled:opacity-50"
|
|
||||||
>
|
|
||||||
{saving ? "Enregistrement..." : "Enregistrer"}
|
|
||||||
</button>
|
|
||||||
<button
|
|
||||||
onClick={handleCancel}
|
|
||||||
className="px-4 py-2 border border-gray-600/50 bg-gray-900/20 text-gray-400 uppercase text-xs tracking-widest rounded hover:bg-gray-900/30 transition"
|
|
||||||
>
|
|
||||||
Annuler
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{events.length === 0 ? (
|
|
||||||
<div className="text-center text-gray-400 py-8">
|
|
||||||
Aucun événement trouvé
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
<div className="space-y-3">
|
|
||||||
{events.map((event) => (
|
|
||||||
<div
|
|
||||||
key={event.id}
|
|
||||||
className="bg-black/60 border border-pixel-gold/20 rounded p-4"
|
|
||||||
>
|
|
||||||
<div className="flex justify-between items-start">
|
|
||||||
<div className="flex-1">
|
|
||||||
<div className="flex items-center gap-3 mb-2">
|
|
||||||
<h4 className="text-pixel-gold font-bold text-lg">
|
|
||||||
{event.name}
|
|
||||||
</h4>
|
|
||||||
<span className="px-2 py-1 bg-pixel-gold/20 border border-pixel-gold/50 text-pixel-gold text-xs uppercase rounded">
|
|
||||||
{getEventTypeLabel(event.type)}
|
|
||||||
</span>
|
|
||||||
<span
|
|
||||||
className={`px-2 py-1 text-xs uppercase rounded ${
|
|
||||||
event.status === "UPCOMING"
|
|
||||||
? "bg-green-900/50 border border-green-500/50 text-green-400"
|
|
||||||
: event.status === "LIVE"
|
|
||||||
? "bg-yellow-900/50 border border-yellow-500/50 text-yellow-400"
|
|
||||||
: "bg-gray-900/50 border border-gray-500/50 text-gray-400"
|
|
||||||
}`}
|
|
||||||
>
|
|
||||||
{getStatusLabel(event.status)}
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
<p className="text-gray-400 text-sm mb-2">
|
|
||||||
{event.description}
|
|
||||||
</p>
|
|
||||||
<p className="text-gray-500 text-xs">
|
|
||||||
Date: {new Date(event.date).toLocaleDateString("fr-FR")}
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
{!isCreating && !editingEvent && (
|
|
||||||
<div className="flex gap-2 ml-4">
|
|
||||||
<button
|
|
||||||
onClick={() => handleEdit(event)}
|
|
||||||
className="px-3 py-1 border border-pixel-gold/50 bg-black/60 text-white uppercase text-xs tracking-widest rounded hover:bg-pixel-gold/10 transition"
|
|
||||||
>
|
|
||||||
Modifier
|
|
||||||
</button>
|
|
||||||
<button
|
|
||||||
onClick={() => handleDelete(event.id)}
|
|
||||||
className="px-3 py-1 border border-red-500/50 bg-red-900/20 text-red-400 uppercase text-xs tracking-widest rounded hover:bg-red-900/30 transition"
|
|
||||||
>
|
|
||||||
Supprimer
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,200 +0,0 @@
|
|||||||
"use client";
|
|
||||||
|
|
||||||
import { useEffect, useState } from "react";
|
|
||||||
import { useBackgroundImage } from "@/hooks/usePreferences";
|
|
||||||
|
|
||||||
interface Event {
|
|
||||||
id: string;
|
|
||||||
date: string;
|
|
||||||
name: string;
|
|
||||||
description: string;
|
|
||||||
type: "SUMMIT" | "LAUNCH" | "FESTIVAL" | "COMPETITION";
|
|
||||||
status: "UPCOMING" | "LIVE" | "PAST";
|
|
||||||
}
|
|
||||||
|
|
||||||
const getEventTypeColor = (type: Event["type"]) => {
|
|
||||||
switch (type) {
|
|
||||||
case "SUMMIT":
|
|
||||||
return "from-blue-600 to-cyan-500";
|
|
||||||
case "LAUNCH":
|
|
||||||
return "from-purple-600 to-pink-500";
|
|
||||||
case "FESTIVAL":
|
|
||||||
return "from-pixel-gold to-orange-500";
|
|
||||||
case "COMPETITION":
|
|
||||||
return "from-red-600 to-orange-500";
|
|
||||||
default:
|
|
||||||
return "from-gray-600 to-gray-500";
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const getEventTypeLabel = (type: Event["type"]) => {
|
|
||||||
switch (type) {
|
|
||||||
case "SUMMIT":
|
|
||||||
return "Sommet";
|
|
||||||
case "LAUNCH":
|
|
||||||
return "Lancement";
|
|
||||||
case "FESTIVAL":
|
|
||||||
return "Festival";
|
|
||||||
case "COMPETITION":
|
|
||||||
return "Compétition";
|
|
||||||
default:
|
|
||||||
return type;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const getStatusBadge = (status: Event["status"]) => {
|
|
||||||
switch (status) {
|
|
||||||
case "UPCOMING":
|
|
||||||
return (
|
|
||||||
<span className="px-3 py-1 bg-green-900/50 border border-green-500/50 text-green-400 text-xs uppercase tracking-widest rounded">
|
|
||||||
À venir
|
|
||||||
</span>
|
|
||||||
);
|
|
||||||
case "LIVE":
|
|
||||||
return (
|
|
||||||
<span className="px-3 py-1 bg-red-900/50 border border-red-500/50 text-red-400 text-xs uppercase tracking-widest rounded animate-pulse">
|
|
||||||
En direct
|
|
||||||
</span>
|
|
||||||
);
|
|
||||||
case "PAST":
|
|
||||||
return (
|
|
||||||
<span className="px-3 py-1 bg-gray-800/50 border border-gray-600/50 text-gray-400 text-xs uppercase tracking-widest rounded">
|
|
||||||
Passé
|
|
||||||
</span>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
export default function EventsPageSection() {
|
|
||||||
const [events, setEvents] = useState<Event[]>([]);
|
|
||||||
const [loading, setLoading] = useState(true);
|
|
||||||
const backgroundImage = useBackgroundImage("events", "/got-2.jpg");
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
fetch("/api/events")
|
|
||||||
.then((res) => res.json())
|
|
||||||
.then((data) => {
|
|
||||||
setEvents(data);
|
|
||||||
setLoading(false);
|
|
||||||
})
|
|
||||||
.catch((err) => {
|
|
||||||
console.error("Error fetching events:", err);
|
|
||||||
setLoading(false);
|
|
||||||
});
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
if (loading) {
|
|
||||||
return (
|
|
||||||
<section className="relative w-full min-h-screen flex flex-col items-center justify-center overflow-hidden pt-24 pb-16">
|
|
||||||
<div className="text-pixel-gold text-xl">Chargement...</div>
|
|
||||||
</section>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
return (
|
|
||||||
<section className="relative w-full min-h-screen flex flex-col items-center justify-center overflow-hidden pt-24 pb-16">
|
|
||||||
{/* Background Image */}
|
|
||||||
<div
|
|
||||||
className="absolute inset-0 bg-cover bg-center bg-no-repeat"
|
|
||||||
style={{
|
|
||||||
backgroundImage: `url('${backgroundImage}')`,
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
{/* Dark overlay for readability */}
|
|
||||||
<div className="absolute inset-0 bg-gradient-to-b from-black/70 via-black/60 to-black/80"></div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Content */}
|
|
||||||
<div className="relative z-10 w-full max-w-6xl mx-auto px-8 py-16">
|
|
||||||
{/* Title Section */}
|
|
||||||
<div className="text-center mb-16">
|
|
||||||
<h1 className="text-5xl md:text-7xl font-gaming font-black mb-4 tracking-tight">
|
|
||||||
<span
|
|
||||||
className="bg-gradient-to-r from-pixel-gold via-orange-400 to-pixel-gold bg-clip-text text-transparent"
|
|
||||||
style={{
|
|
||||||
textShadow: "0 0 30px rgba(218, 165, 32, 0.5)",
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
EVENTS
|
|
||||||
</span>
|
|
||||||
</h1>
|
|
||||||
<div className="text-pixel-gold text-lg md:text-xl font-gaming-subtitle font-semibold flex items-center justify-center gap-2 mb-6 tracking-wide">
|
|
||||||
<span>✦</span>
|
|
||||||
<span>Événements à venir et passés</span>
|
|
||||||
<span>✦</span>
|
|
||||||
</div>
|
|
||||||
<p className="text-gray-400 text-sm max-w-2xl mx-auto">
|
|
||||||
Rejoignez-nous pour des événements tech passionnants, des
|
|
||||||
compétitions et des célébrations tout au long de l'année
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Events Grid */}
|
|
||||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
|
|
||||||
{events.map((event) => (
|
|
||||||
<div
|
|
||||||
key={event.id}
|
|
||||||
className="bg-black/60 border border-pixel-gold/30 rounded-lg overflow-hidden backdrop-blur-sm hover:border-pixel-gold/50 transition group"
|
|
||||||
>
|
|
||||||
{/* Event Header */}
|
|
||||||
<div
|
|
||||||
className={`h-2 bg-gradient-to-r ${getEventTypeColor(
|
|
||||||
event.type
|
|
||||||
)}`}
|
|
||||||
></div>
|
|
||||||
|
|
||||||
{/* Event Content */}
|
|
||||||
<div className="p-6">
|
|
||||||
{/* Status Badge */}
|
|
||||||
<div className="flex justify-between items-start mb-4">
|
|
||||||
{getStatusBadge(event.status)}
|
|
||||||
<span className="text-pixel-gold text-xs uppercase tracking-widest">
|
|
||||||
{getEventTypeLabel(event.type)}
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Date */}
|
|
||||||
<div className="text-white text-sm font-bold uppercase tracking-widest mb-3">
|
|
||||||
{event.date}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Event Name */}
|
|
||||||
<h3 className="text-xl font-bold text-white mb-3 group-hover:text-pixel-gold transition">
|
|
||||||
{event.name}
|
|
||||||
</h3>
|
|
||||||
|
|
||||||
{/* Description */}
|
|
||||||
<p className="text-gray-400 text-sm leading-relaxed mb-4">
|
|
||||||
{event.description}
|
|
||||||
</p>
|
|
||||||
|
|
||||||
{/* Action Button */}
|
|
||||||
{event.status === "UPCOMING" && (
|
|
||||||
<button className="w-full px-4 py-2 border border-pixel-gold/50 bg-black/40 text-white uppercase text-xs tracking-widest rounded hover:bg-pixel-gold/10 hover:border-pixel-gold transition">
|
|
||||||
S'inscrire maintenant
|
|
||||||
</button>
|
|
||||||
)}
|
|
||||||
{event.status === "LIVE" && (
|
|
||||||
<button className="w-full px-4 py-2 border border-red-500/50 bg-red-900/20 text-red-400 uppercase text-xs tracking-widest rounded hover:bg-red-900/30 transition animate-pulse">
|
|
||||||
Rejoindre en direct
|
|
||||||
</button>
|
|
||||||
)}
|
|
||||||
{event.status === "PAST" && (
|
|
||||||
<button className="w-full px-4 py-2 border border-gray-600/50 bg-gray-900/20 text-gray-500 uppercase text-xs tracking-widest rounded cursor-not-allowed">
|
|
||||||
Événement terminé
|
|
||||||
</button>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Footer Info */}
|
|
||||||
<div className="mt-12 text-center">
|
|
||||||
<p className="text-gray-500 text-sm">
|
|
||||||
Restez informé de nos derniers événements et annonces
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</section>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,66 +0,0 @@
|
|||||||
"use client";
|
|
||||||
|
|
||||||
import { useEffect, useState } from "react";
|
|
||||||
|
|
||||||
interface Event {
|
|
||||||
id: string;
|
|
||||||
date: string;
|
|
||||||
name: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export default function EventsSection() {
|
|
||||||
const [events, setEvents] = useState<Event[]>([]);
|
|
||||||
const [loading, setLoading] = useState(true);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
fetch("/api/events")
|
|
||||||
.then((res) => res.json())
|
|
||||||
.then((data) => {
|
|
||||||
// Prendre seulement les 3 premiers événements pour la section d'accueil
|
|
||||||
setEvents(data.slice(0, 3));
|
|
||||||
setLoading(false);
|
|
||||||
})
|
|
||||||
.catch((err) => {
|
|
||||||
console.error("Error fetching events:", err);
|
|
||||||
setLoading(false);
|
|
||||||
});
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
if (loading) {
|
|
||||||
return (
|
|
||||||
<section className="w-full bg-gray-950 border-t border-pixel-gold/30 py-16">
|
|
||||||
<div className="max-w-7xl mx-auto px-8 text-center text-pixel-gold">
|
|
||||||
Chargement...
|
|
||||||
</div>
|
|
||||||
</section>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (events.length === 0) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
return (
|
|
||||||
<section className="w-full bg-gray-950 border-t border-pixel-gold/30 py-16">
|
|
||||||
<div className="max-w-7xl mx-auto px-8">
|
|
||||||
<div className="flex flex-col md:flex-row items-center justify-around gap-8">
|
|
||||||
{events.map((event, index) => (
|
|
||||||
<div key={index} className="flex flex-col items-center">
|
|
||||||
<div className="flex flex-col items-center mb-4">
|
|
||||||
<span className="text-pixel-gold text-xs uppercase tracking-widest mb-2">
|
|
||||||
Événement
|
|
||||||
</span>
|
|
||||||
<div className="w-16 h-px bg-pixel-gold"></div>
|
|
||||||
</div>
|
|
||||||
<div className="text-white text-lg font-bold mb-2 uppercase tracking-wide">
|
|
||||||
{event.date}
|
|
||||||
</div>
|
|
||||||
<div className="text-white text-base text-center">
|
|
||||||
{event.name}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</section>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user