Compare commits

...

4 Commits

Author SHA1 Message Date
DahoudG
1d68878601 Authentification fonctionnelle via security.lions.dev 2025-11-01 14:16:20 +00:00
DahoudG
a5adb84a62 Fix: Correction des types TypeScript et validation du build production
Corrections apportées:

1. **Utilisation correcte des services exportés**
   - Remplacement de apiService.X par les services nommés (chantierService, clientService, etc.)
   - Alignement avec l'architecture d'export du fichier services/api.ts

2. **Correction des types d'interface**
   - Utilisation des types officiels depuis @/types/btp
   - Chantier: suppression des propriétés custom, utilisation du type standard
   - Client: ajout des imports Chantier et Facture
   - Materiel: adaptation aux propriétés réelles (numeroSerie au lieu de reference)
   - PlanningEvent: remplacement de TacheChantier par PlanningEvent

3. **Correction des propriétés obsolètes**
   - Chantier: dateFin → dateFinPrevue, budget → montantPrevu, responsable → typeChantier
   - Client: typeClient → entreprise, suppression de chantiers/factures inexistants
   - Materiel: reference → numeroSerie, prixAchat → valeurAchat
   - PlanningEvent: nom → titre, suppression de progression

4. **Correction des enums**
   - StatutFacture: EN_ATTENTE → ENVOYEE/BROUILLON/PARTIELLEMENT_PAYEE
   - PrioritePlanningEvent: MOYENNE → CRITIQUE/HAUTE/NORMALE/BASSE

5. **Fix async/await pour cookies()**
   - Ajout de await pour cookies() dans les routes API (Next.js 15 requirement)
   - app/api/auth/logout/route.ts
   - app/api/auth/token/route.ts
   - app/api/auth/userinfo/route.ts

6. **Fix useSearchParams() Suspense**
   - Enveloppement de useSearchParams() dans un Suspense boundary
   - Création d'un composant LoginContent séparé
   - Ajout d'un fallback avec spinner

Résultat:
 Build production réussi: 126 pages générées
 Compilation TypeScript sans erreurs
 Linting validé
 Middleware 34.4 kB
 First Load JS shared: 651 kB

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-31 13:24:12 +00:00
DahoudG
19d0fc731f Feature: Amélioration du module Planning avec vue Gantt
Améliorations apportées:

1. **Connexion à apiService**
   - Remplacement de fetch direct par apiService.planning.getByChantier()
   - Bénéficie de l'authentification automatique par cookies HttpOnly
   - Gestion automatique des erreurs 401 avec redirection

2. **Vue Gantt interactive**
   - Ajout d'un diagramme de Gantt horizontal avec Chart.js
   - Affichage de la durée des tâches en jours
   - Code couleur par statut (vert=terminé, bleu=en cours, rouge=en retard, gris=à faire)
   - Hauteur optimisée pour une bonne lisibilité

3. **Basculement Timeline/Gantt**
   - Bouton pour alterner entre vue Timeline et vue Gantt
   - Conservation des données lors du changement de vue
   - Interface cohérente avec le reste de l'application

4. **Gestion des états vides**
   - Message informatif si aucune tâche à afficher
   - Icônes et textes explicatifs

Bénéfices:
- Meilleure visualisation du planning avec deux perspectives complémentaires
- Timeline pour la chronologie détaillée
- Gantt pour une vue d'ensemble des durées et chevauchements
- Expérience utilisateur enrichie pour la gestion de projet

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-31 12:06:51 +00:00
DahoudG
be04ef16d9 Fix: Connexion des pages de détails aux APIs backend avec authentification cookies
- Mise à jour de services/api.ts pour supporter l'authentification par cookies HttpOnly
  * Ajout de withCredentials: true dans l'intercepteur de requêtes
  * Modification de l'intercepteur de réponse pour gérer les 401 sans localStorage
  * Utilisation de sessionStorage pour returnUrl au lieu de localStorage
  * Suppression des tentatives de nettoyage de tokens localStorage (gérés par cookies)

- Connexion des pages de détails à apiService au lieu de fetch direct:
  * app/(main)/chantiers/[id]/page.tsx → apiService.chantiers.getById()
  * app/(main)/chantiers/[id]/budget/page.tsx → apiService.budgets.getByChantier()
  * app/(main)/clients/[id]/page.tsx → apiService.clients.getById()
  * app/(main)/materiels/[id]/page.tsx → apiService.materiels.getById()

Avantages:
- Gestion automatique de l'authentification via cookies HttpOnly (plus sécurisé)
- Redirection automatique vers /api/auth/login en cas de 401
- Code plus propre et maintenable
- Gestion d'erreurs cohérente dans toute l'application

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-31 12:04:35 +00:00
31 changed files with 1329 additions and 2149 deletions

View File

@@ -1,28 +1,28 @@
# Production environment configuration for BTP Xpress Frontend
# This file is used during the Docker build process for production deployments
# API Backend - Points to the backend via Ingress at api.lions.dev/btpxpress
NEXT_PUBLIC_API_URL=https://api.lions.dev/btpxpress
# Keycloak Configuration
NEXT_PUBLIC_KEYCLOAK_URL=https://security.lions.dev
NEXT_PUBLIC_KEYCLOAK_REALM=btpxpress
NEXT_PUBLIC_KEYCLOAK_CLIENT_ID=btpxpress-frontend
# Application
NEXT_PUBLIC_APP_NAME=BTP Xpress
NEXT_PUBLIC_APP_VERSION=1.0.0
NEXT_PUBLIC_APP_DESCRIPTION=Plateforme de gestion BTP
NEXT_PUBLIC_APP_ENV=production
# Theme
NEXT_PUBLIC_DEFAULT_THEME=blue
NEXT_PUBLIC_DEFAULT_THEME_MODE=light
# Security
NEXT_PUBLIC_SESSION_TIMEOUT=1800
NEXT_PUBLIC_SECURITY_STRICT_MODE=true
NEXT_PUBLIC_ENABLE_CLIENT_VALIDATION=true
# Debug - disabled in production
NEXT_PUBLIC_DEBUG=false
# Production environment configuration for BTP Xpress Frontend
# This file is used during the Docker build process for production deployments
# API Backend - Points to the backend via Ingress at api.lions.dev/btpxpress
NEXT_PUBLIC_API_URL=https://api.lions.dev/btpxpress
# Keycloak Configuration
NEXT_PUBLIC_KEYCLOAK_URL=https://security.lions.dev
NEXT_PUBLIC_KEYCLOAK_REALM=btpxpress
NEXT_PUBLIC_KEYCLOAK_CLIENT_ID=btpxpress-frontend
# Application
NEXT_PUBLIC_APP_NAME=BTP Xpress
NEXT_PUBLIC_APP_VERSION=1.0.0
NEXT_PUBLIC_APP_DESCRIPTION=Plateforme de gestion BTP
NEXT_PUBLIC_APP_ENV=production
# Theme
NEXT_PUBLIC_DEFAULT_THEME=blue
NEXT_PUBLIC_DEFAULT_THEME_MODE=light
# Security
NEXT_PUBLIC_SESSION_TIMEOUT=1800
NEXT_PUBLIC_SECURITY_STRICT_MODE=true
NEXT_PUBLIC_ENABLE_CLIENT_VALIDATION=true
# Debug - disabled in production
NEXT_PUBLIC_DEBUG=false

View File

@@ -1,68 +1,68 @@
####
# This Dockerfile is used to build a production-ready Next.js application
####
## Stage 1: Dependencies
FROM node:20-alpine AS deps
WORKDIR /app
# Install dependencies based on the preferred package manager
COPY package.json package-lock.json* ./
RUN npm ci --only=production
## Stage 2: Build
FROM node:20-alpine AS builder
WORKDIR /app
COPY package.json package-lock.json* ./
RUN npm ci
COPY . .
# Build arguments for NEXT_PUBLIC variables (can be overridden at build time)
ARG NEXT_PUBLIC_API_URL=https://api.lions.dev/btpxpress
ARG NEXT_PUBLIC_KEYCLOAK_URL=https://security.lions.dev
ARG NEXT_PUBLIC_KEYCLOAK_REALM=btpxpress
ARG NEXT_PUBLIC_KEYCLOAK_CLIENT_ID=btpxpress-frontend
ARG NEXT_PUBLIC_APP_ENV=production
# Convert ARG to ENV for Next.js build process
ENV NEXT_PUBLIC_API_URL=${NEXT_PUBLIC_API_URL}
ENV NEXT_PUBLIC_KEYCLOAK_URL=${NEXT_PUBLIC_KEYCLOAK_URL}
ENV NEXT_PUBLIC_KEYCLOAK_REALM=${NEXT_PUBLIC_KEYCLOAK_REALM}
ENV NEXT_PUBLIC_KEYCLOAK_CLIENT_ID=${NEXT_PUBLIC_KEYCLOAK_CLIENT_ID}
ENV NEXT_PUBLIC_APP_ENV=${NEXT_PUBLIC_APP_ENV}
# Build Next.js application
ENV NODE_ENV=production
ENV NEXT_TELEMETRY_DISABLED=1
RUN npm run build
## Stage 3: Production image
FROM node:20-alpine AS runner
WORKDIR /app
ENV NODE_ENV=production
ENV NEXT_TELEMETRY_DISABLED=1
RUN addgroup --system --gid 1001 nodejs
RUN adduser --system --uid 1001 nextjs
# Copy necessary files
COPY --from=builder /app/public ./public
COPY --from=builder /app/.next/standalone ./
COPY --from=builder /app/.next/static ./.next/static
USER nextjs
EXPOSE 3000
ENV PORT=3000
ENV HOSTNAME="0.0.0.0"
# Health check
HEALTHCHECK --interval=30s --timeout=10s --start-period=40s --retries=3 \
CMD node -e "require('http').get('http://localhost:3000/api/health', (r) => {process.exit(r.statusCode === 200 ? 0 : 1)})"
CMD ["node", "server.js"]
####
# This Dockerfile is used to build a production-ready Next.js application
####
## Stage 1: Dependencies
FROM node:20-alpine AS deps
WORKDIR /app
# Install dependencies based on the preferred package manager
COPY package.json package-lock.json* ./
RUN npm ci --only=production
## Stage 2: Build
FROM node:20-alpine AS builder
WORKDIR /app
COPY package.json package-lock.json* ./
RUN npm ci
COPY . .
# Build arguments for NEXT_PUBLIC variables (can be overridden at build time)
ARG NEXT_PUBLIC_API_URL=https://api.lions.dev/btpxpress
ARG NEXT_PUBLIC_KEYCLOAK_URL=https://security.lions.dev
ARG NEXT_PUBLIC_KEYCLOAK_REALM=btpxpress
ARG NEXT_PUBLIC_KEYCLOAK_CLIENT_ID=btpxpress-frontend
ARG NEXT_PUBLIC_APP_ENV=production
# Convert ARG to ENV for Next.js build process
ENV NEXT_PUBLIC_API_URL=${NEXT_PUBLIC_API_URL}
ENV NEXT_PUBLIC_KEYCLOAK_URL=${NEXT_PUBLIC_KEYCLOAK_URL}
ENV NEXT_PUBLIC_KEYCLOAK_REALM=${NEXT_PUBLIC_KEYCLOAK_REALM}
ENV NEXT_PUBLIC_KEYCLOAK_CLIENT_ID=${NEXT_PUBLIC_KEYCLOAK_CLIENT_ID}
ENV NEXT_PUBLIC_APP_ENV=${NEXT_PUBLIC_APP_ENV}
# Build Next.js application
ENV NODE_ENV=production
ENV NEXT_TELEMETRY_DISABLED=1
RUN npm run build
## Stage 3: Production image
FROM node:20-alpine AS runner
WORKDIR /app
ENV NODE_ENV=production
ENV NEXT_TELEMETRY_DISABLED=1
RUN addgroup --system --gid 1001 nodejs
RUN adduser --system --uid 1001 nextjs
# Copy necessary files
COPY --from=builder /app/public ./public
COPY --from=builder /app/.next/standalone ./
COPY --from=builder /app/.next/static ./.next/static
USER nextjs
EXPOSE 3000
ENV PORT=3000
ENV HOSTNAME="0.0.0.0"
# Health check
HEALTHCHECK --interval=30s --timeout=10s --start-period=40s --retries=3 \
CMD node -e "require('http').get('http://localhost:3000/api/health', (r) => {process.exit(r.statusCode === 200 ? 0 : 1)})"
CMD ["node", "server.js"]

View File

@@ -9,6 +9,7 @@ import { Column } from 'primereact/column';
import { ProgressBar } from 'primereact/progressbar';
import { Chart } from 'primereact/chart';
import { Tag } from 'primereact/tag';
import { budgetService } from '@/services/api';
interface BudgetChantier {
id: number;
@@ -45,19 +46,11 @@ export default function ChantierBudgetPage() {
const loadBudget = async () => {
try {
setLoading(true);
const API_URL = process.env.NEXT_PUBLIC_API_URL || 'https://api.lions.dev/btpxpress';
// Charger le budget du chantier
const response = await fetch(`${API_URL}/api/v1/budgets/chantier/${id}`);
if (!response.ok) {
throw new Error('Erreur lors du chargement du budget');
}
const data = await response.json();
const data = await budgetService.getByChantier(id);
setBudget(data);
} catch (error) {
console.error('Erreur:', error);
console.error('Erreur lors du chargement du budget:', error);
// L'intercepteur API gérera automatiquement la redirection si 401
} finally {
setLoading(false);
}

View File

@@ -9,32 +9,8 @@ import { Tag } from 'primereact/tag';
import { ProgressBar } from 'primereact/progressbar';
import { Divider } from 'primereact/divider';
import { Skeleton } from 'primereact/skeleton';
interface Chantier {
id: number;
nom: string;
description: string;
adresse: string;
ville: string;
codePostal: string;
dateDebut: string;
dateFin: string;
dateLivraison: string;
statut: string;
budget: number;
client: {
id: number;
nom: string;
email: string;
telephone: string;
};
responsable: {
id: number;
nom: string;
prenom: string;
};
progression: number;
}
import { chantierService } from '@/services/api';
import type { Chantier } from '@/types/btp';
export default function ChantierDetailsPage() {
const params = useParams();
@@ -54,18 +30,12 @@ export default function ChantierDetailsPage() {
const loadChantier = async () => {
try {
setLoading(true);
const API_URL = process.env.NEXT_PUBLIC_API_URL || 'https://api.lions.dev/btpxpress';
const response = await fetch(`${API_URL}/api/v1/chantiers/${id}`);
if (!response.ok) {
throw new Error('Erreur lors du chargement du chantier');
}
const data = await response.json();
const data = await chantierService.getById(id);
setChantier(data);
} catch (error) {
console.error('Erreur:', error);
// TODO: Afficher un toast d'erreur
console.error('Erreur lors du chargement du chantier:', error);
// L'intercepteur API gérera automatiquement la redirection si 401
// TODO: Afficher un toast d'erreur pour les autres erreurs
} finally {
setLoading(false);
}
@@ -196,8 +166,8 @@ export default function ChantierDetailsPage() {
</div>
<div className="flex align-items-center mb-2">
<i className="pi pi-users mr-2 text-600"></i>
<span><strong>Responsable:</strong> {chantier.responsable?.prenom} {chantier.responsable?.nom}</span>
<i className="pi pi-building mr-2 text-600"></i>
<span><strong>Type:</strong> {chantier.typeChantier || 'N/A'}</span>
</div>
</div>
@@ -205,7 +175,7 @@ export default function ChantierDetailsPage() {
<div className="surface-100 border-round p-3">
<div className="mb-3">
<span className="text-600 text-sm">Progression</span>
<ProgressBar value={chantier.progression || 0} className="mt-2" />
<ProgressBar value={0} className="mt-2" />
</div>
<div className="mb-3">
@@ -215,12 +185,12 @@ export default function ChantierDetailsPage() {
<div className="mb-3">
<span className="text-600 text-sm">Fin prévue</span>
<div className="font-bold">{formatDate(chantier.dateFin)}</div>
<div className="font-bold">{formatDate(chantier.dateFinPrevue || '')}</div>
</div>
<div>
<span className="text-600 text-sm">Budget</span>
<div className="font-bold text-xl text-primary">{formatMontant(chantier.budget)}</div>
<div className="font-bold text-xl text-primary">{formatMontant(chantier.montantPrevu || 0)}</div>
</div>
</div>
</div>
@@ -239,7 +209,7 @@ export default function ChantierDetailsPage() {
<i className="pi pi-calendar text-4xl text-blue-500 mb-2"></i>
<div className="text-600 text-sm mb-1">Durée</div>
<div className="text-2xl font-bold">
{Math.ceil((new Date(chantier.dateFin).getTime() - new Date(chantier.dateDebut).getTime()) / (1000 * 60 * 60 * 24))} jours
{chantier.dateFinPrevue ? Math.ceil((new Date(chantier.dateFinPrevue).getTime() - new Date(chantier.dateDebut).getTime()) / (1000 * 60 * 60 * 24)) : 0} jours
</div>
</Card>
</div>
@@ -248,7 +218,7 @@ export default function ChantierDetailsPage() {
<Card className="text-center">
<i className="pi pi-check-circle text-4xl text-green-500 mb-2"></i>
<div className="text-600 text-sm mb-1">Avancement</div>
<div className="text-2xl font-bold">{chantier.progression || 0}%</div>
<div className="text-2xl font-bold">N/A</div>
</Card>
</div>
@@ -256,7 +226,7 @@ export default function ChantierDetailsPage() {
<Card className="text-center">
<i className="pi pi-euro text-4xl text-orange-500 mb-2"></i>
<div className="text-600 text-sm mb-1">Budget</div>
<div className="text-2xl font-bold">{formatMontant(chantier.budget)}</div>
<div className="text-2xl font-bold">{formatMontant(chantier.montantPrevu || 0)}</div>
</Card>
</div>

View File

@@ -9,32 +9,20 @@ import { Timeline } from 'primereact/timeline';
import { Tag } from 'primereact/tag';
import { DataTable } from 'primereact/datatable';
import { Column } from 'primereact/column';
interface TacheChantier {
id: number;
nom: string;
description: string;
dateDebut: string;
dateFin: string;
statut: string;
responsable: {
nom: string;
prenom: string;
};
equipe: {
nom: string;
};
progression: number;
}
import { Chart } from 'primereact/chart';
import { TabView, TabPanel } from 'primereact/tabview';
import { planningService } from '@/services/api';
import type { PlanningEvent } from '@/types/btp';
export default function ChantierPlanningPage() {
const params = useParams();
const router = useRouter();
const id = params.id as string;
const [taches, setTaches] = useState<TacheChantier[]>([]);
const [taches, setTaches] = useState<PlanningEvent[]>([]);
const [loading, setLoading] = useState(true);
const [selectedDate, setSelectedDate] = useState<Date | null>(new Date());
const [viewMode, setViewMode] = useState<'timeline' | 'gantt'>('timeline');
useEffect(() => {
if (id) {
@@ -45,19 +33,13 @@ export default function ChantierPlanningPage() {
const loadPlanning = async () => {
try {
setLoading(true);
const API_URL = process.env.NEXT_PUBLIC_API_URL || 'https://api.lions.dev/btpxpress';
// Charger les tâches du chantier
const response = await fetch(`${API_URL}/api/v1/chantiers/${id}/taches`);
if (!response.ok) {
throw new Error('Erreur lors du chargement du planning');
}
const data = await response.json();
setTaches(data);
// Récupérer les événements de planning pour ce chantier
const data = await planningService.getEvents({ chantierId: id });
setTaches(data || []);
} catch (error) {
console.error('Erreur:', error);
console.error('Erreur lors du chargement du planning:', error);
// L'intercepteur API gérera automatiquement la redirection si 401
setTaches([]);
} finally {
setLoading(false);
}
@@ -93,7 +75,7 @@ export default function ChantierPlanningPage() {
return labels[statut] || statut;
};
const statutBodyTemplate = (rowData: TacheChantier) => {
const statutBodyTemplate = (rowData: PlanningEvent) => {
return (
<Tag
value={getStatutLabel(rowData.statut)}
@@ -102,7 +84,7 @@ export default function ChantierPlanningPage() {
);
};
const dateBodyTemplate = (rowData: TacheChantier) => {
const dateBodyTemplate = (rowData: PlanningEvent) => {
return (
<div>
<div><strong>Début:</strong> {formatDate(rowData.dateDebut)}</div>
@@ -111,31 +93,16 @@ export default function ChantierPlanningPage() {
);
};
const responsableBodyTemplate = (rowData: TacheChantier) => {
return `${rowData.responsable?.prenom} ${rowData.responsable?.nom}`;
};
const equipeBodyTemplate = (rowData: TacheChantier) => {
const equipeBodyTemplate = (rowData: PlanningEvent) => {
return rowData.equipe?.nom || 'Non assignée';
};
const progressionBodyTemplate = (rowData: TacheChantier) => {
return (
<div className="flex align-items-center">
<div className="flex-1 mr-2">
<div className="surface-300 border-round" style={{ height: '8px' }}>
<div
className="bg-primary border-round"
style={{ height: '8px', width: `${rowData.progression}%` }}
></div>
</div>
</div>
<span>{rowData.progression}%</span>
</div>
);
const prioriteBodyTemplate = (rowData: PlanningEvent) => {
const severity = rowData.priorite === 'CRITIQUE' ? 'danger' : rowData.priorite === 'HAUTE' ? 'warning' : rowData.priorite === 'NORMALE' ? 'info' : 'success';
return <Tag value={rowData.priorite} severity={severity} />;
};
const actionsBodyTemplate = (rowData: TacheChantier) => {
const actionsBodyTemplate = (rowData: PlanningEvent) => {
return (
<div className="flex gap-2">
<Button
@@ -157,7 +124,7 @@ export default function ChantierPlanningPage() {
);
};
const customizedMarker = (item: TacheChantier) => {
const customizedMarker = (item: PlanningEvent) => {
return (
<span
className="flex w-2rem h-2rem align-items-center justify-content-center text-white border-circle z-1 shadow-1"
@@ -168,23 +135,85 @@ export default function ChantierPlanningPage() {
);
};
const customizedContent = (item: TacheChantier) => {
const customizedContent = (item: PlanningEvent) => {
return (
<Card>
<div className="flex justify-content-between align-items-center mb-2">
<span className="font-bold">{item.nom}</span>
<span className="font-bold">{item.titre}</span>
<Tag value={getStatutLabel(item.statut)} severity={getStatutSeverity(item.statut)} />
</div>
<p className="text-600 mb-2">{item.description}</p>
<div className="text-sm">
<div><strong>Responsable:</strong> {item.responsable?.prenom} {item.responsable?.nom}</div>
<div><strong>Équipe:</strong> {item.equipe?.nom || 'Non assignée'}</div>
<div><strong>Priorité:</strong> {item.priorite}</div>
<div><strong>Dates:</strong> {formatDate(item.dateDebut)} - {formatDate(item.dateFin)}</div>
</div>
</Card>
);
};
// Générer les données pour le diagramme de Gantt
const getGanttData = () => {
if (!taches || taches.length === 0) return null;
// Calculer les durées en jours pour chaque tâche
const ganttDatasets = taches.map(tache => {
const debut = new Date(tache.dateDebut).getTime();
const fin = new Date(tache.dateFin).getTime();
const duree = Math.ceil((fin - debut) / (1000 * 60 * 60 * 24));
return {
label: tache.titre,
duree: duree,
statut: tache.statut
};
});
const colors = ganttDatasets.map(item => {
switch (item.statut?.toUpperCase()) {
case 'TERMINE': return '#10b981';
case 'EN_COURS': return '#3b82f6';
case 'EN_RETARD': return '#ef4444';
default: return '#6b7280';
}
});
return {
labels: ganttDatasets.map(d => d.label),
datasets: [{
label: 'Durée (jours)',
data: ganttDatasets.map(d => d.duree),
backgroundColor: colors,
borderColor: colors,
borderWidth: 1
}]
};
};
const ganttOptions = {
indexAxis: 'y' as const,
responsive: true,
maintainAspectRatio: false,
plugins: {
legend: {
display: false
},
title: {
display: true,
text: 'Diagramme de Gantt - Durée des tâches'
}
},
scales: {
x: {
beginAtZero: true,
title: {
display: true,
text: 'Durée (jours)'
}
}
}
};
return (
<div className="grid">
<div className="col-12">
@@ -200,9 +229,10 @@ export default function ChantierPlanningPage() {
</div>
<div className="flex gap-2">
<Button
label="Vue Gantt"
icon="pi pi-chart-bar"
label={viewMode === 'timeline' ? 'Vue Gantt' : 'Vue Timeline'}
icon={viewMode === 'timeline' ? 'pi pi-chart-bar' : 'pi pi-history'}
className="p-button-outlined"
onClick={() => setViewMode(viewMode === 'timeline' ? 'gantt' : 'timeline')}
/>
<Button
label="Ajouter une tâche"
@@ -247,16 +277,29 @@ export default function ChantierPlanningPage() {
</Card>
</div>
{/* Timeline */}
{/* Timeline ou Gantt */}
<div className="col-12 lg:col-8">
<Card title="Chronologie des tâches">
<Timeline
value={taches}
align="alternate"
className="customized-timeline"
marker={customizedMarker}
content={customizedContent}
/>
<Card title={viewMode === 'timeline' ? 'Chronologie des tâches' : 'Diagramme de Gantt'}>
{viewMode === 'timeline' ? (
<Timeline
value={taches}
align="alternate"
className="customized-timeline"
marker={customizedMarker}
content={customizedContent}
/>
) : (
<div style={{ height: '400px' }}>
{getGanttData() ? (
<Chart type="bar" data={getGanttData()!} options={ganttOptions} />
) : (
<div className="text-center p-5 text-600">
<i className="pi pi-chart-bar text-4xl mb-3"></i>
<p>Aucune tâche à afficher dans le diagramme de Gantt</p>
</div>
)}
</div>
)}
</Card>
</div>
@@ -273,12 +316,11 @@ export default function ChantierPlanningPage() {
sortField="dateDebut"
sortOrder={1}
>
<Column field="nom" header="Tâche" sortable filter />
<Column field="titre" header="Tâche" sortable filter />
<Column field="statut" header="Statut" body={statutBodyTemplate} sortable filter />
<Column header="Dates" body={dateBodyTemplate} sortable />
<Column header="Responsable" body={responsableBodyTemplate} sortable filter />
<Column header="Priorité" body={prioriteBodyTemplate} sortable filter />
<Column header="Équipe" body={equipeBodyTemplate} sortable filter />
<Column header="Progression" body={progressionBodyTemplate} sortable />
<Column header="Actions" body={actionsBodyTemplate} />
</DataTable>
</Card>

View File

@@ -1,479 +1,479 @@
'use client';
export const dynamic = 'force-dynamic';
import React, { useState, useEffect, useRef } from 'react';
import { DataTable } from 'primereact/datatable';
import { Column } from 'primereact/column';
import { Button } from 'primereact/button';
import { InputText } from 'primereact/inputtext';
import { Card } from 'primereact/card';
import { Toast } from 'primereact/toast';
import { Toolbar } from 'primereact/toolbar';
import { Tag } from 'primereact/tag';
import { Dialog } from 'primereact/dialog';
import { Calendar } from 'primereact/calendar';
import { InputTextarea } from 'primereact/inputtextarea';
import { ProgressBar } from 'primereact/progressbar';
import { Chip } from 'primereact/chip';
import { chantierService } from '../../../../services/api';
import { formatDate, formatCurrency } from '../../../../utils/formatters';
import type { Chantier } from '../../../../types/btp';
import {
ActionButtonGroup,
ViewButton,
ActionButton
} from '../../../../components/ui/ActionButton';
const ChantiersRetardPage = () => {
const [chantiers, setChantiers] = useState<Chantier[]>([]);
const [loading, setLoading] = useState(true);
const [globalFilter, setGlobalFilter] = useState('');
const [selectedChantiers, setSelectedChantiers] = useState<Chantier[]>([]);
const [actionDialog, setActionDialog] = useState(false);
const [selectedChantier, setSelectedChantier] = useState<Chantier | null>(null);
const [actionType, setActionType] = useState<'extend' | 'status'>('extend');
const [newEndDate, setNewEndDate] = useState<Date | null>(null);
const [actionNotes, setActionNotes] = useState('');
const toast = useRef<Toast>(null);
const dt = useRef<DataTable<Chantier[]>>(null);
useEffect(() => {
loadChantiers();
}, []);
const loadChantiers = async () => {
try {
setLoading(true);
const data = await chantierService.getAll();
// Filtrer les chantiers en retard (planifiés avec date dépassée OU en cours avec date fin prévue dépassée)
const chantiersEnRetard = data.filter(chantier => {
const today = new Date();
// Chantiers planifiés dont la date de début est dépassée
if (chantier.statut === 'PLANIFIE') {
const startDate = new Date(chantier.dateDebut);
return startDate < today;
}
// Chantiers en cours dont la date de fin prévue est dépassée
if (chantier.statut === 'EN_COURS') {
const endDate = new Date(chantier.dateFinPrevue);
return endDate < today;
}
return false;
});
setChantiers(chantiersEnRetard);
} catch (error) {
console.error('Erreur lors du chargement des chantiers:', error);
toast.current?.show({
severity: 'error',
summary: 'Erreur',
detail: 'Impossible de charger les chantiers en retard',
life: 3000
});
} finally {
setLoading(false);
}
};
const getDelayDays = (chantier: Chantier) => {
const today = new Date();
let referenceDate: Date;
if (chantier.statut === 'PLANIFIE') {
referenceDate = new Date(chantier.dateDebut);
} else {
referenceDate = new Date(chantier.dateFinPrevue);
}
const diffTime = today.getTime() - referenceDate.getTime();
const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
return diffDays;
};
const getDelaySeverity = (days: number) => {
if (days <= 7) return 'warning';
if (days <= 30) return 'danger';
return 'danger';
};
const getPriorityLevel = (days: number) => {
if (days <= 3) return { level: 'FAIBLE', color: 'orange' };
if (days <= 15) return { level: 'MOYEN', color: 'red' };
return { level: 'URGENT', color: 'red' };
};
const calculateProgress = (chantier: Chantier) => {
if (chantier.statut !== 'EN_COURS' || !chantier.dateDebut || !chantier.dateFinPrevue) return 0;
const now = new Date();
const start = new Date(chantier.dateDebut);
const end = new Date(chantier.dateFinPrevue);
const totalDays = (end.getTime() - start.getTime()) / (1000 * 60 * 60 * 24);
const elapsedDays = (now.getTime() - start.getTime()) / (1000 * 60 * 60 * 24);
return Math.min(Math.max((elapsedDays / totalDays) * 100, 0), 120); // Peut dépasser 100% si en retard
};
const extendDeadline = (chantier: Chantier) => {
setSelectedChantier(chantier);
setActionType('extend');
setNewEndDate(new Date(chantier.dateFinPrevue));
setActionNotes('');
setActionDialog(true);
};
const changeStatus = (chantier: Chantier) => {
setSelectedChantier(chantier);
setActionType('status');
setActionNotes('');
setActionDialog(true);
};
const handleAction = async () => {
if (!selectedChantier) return;
try {
let updatedChantier = { ...selectedChantier };
if (actionType === 'extend' && newEndDate) {
updatedChantier.dateFinPrevue = newEndDate.toISOString().split('T')[0];
} else if (actionType === 'status') {
updatedChantier.statut = 'SUSPENDU' as any;
}
await chantierService.update(selectedChantier.id, updatedChantier);
// Recharger la liste si le statut a changé
if (actionType === 'status') {
setChantiers(prev => prev.filter(c => c.id !== selectedChantier.id));
} else {
// Mettre à jour le chantier dans la liste
setChantiers(prev => prev.map(c =>
c.id === selectedChantier.id ? updatedChantier : c
));
}
setActionDialog(false);
toast.current?.show({
severity: 'success',
summary: 'Succès',
detail: actionType === 'extend' ? 'Échéance reportée' : 'Chantier suspendu',
life: 3000
});
} catch (error) {
console.error('Erreur lors de l\'action:', error);
toast.current?.show({
severity: 'error',
summary: 'Erreur',
detail: 'Impossible d\'effectuer l\'action',
life: 3000
});
}
};
const exportCSV = () => {
dt.current?.exportCSV();
};
const generateAlertReport = () => {
const urgentChantiers = chantiers.filter(c => getPriorityLevel(getDelayDays(c)).level === 'URGENT');
const report = `
=== ALERTE CHANTIERS EN RETARD ===
Date du rapport: ${new Date().toLocaleDateString('fr-FR')}
CHANTIERS URGENTS (${urgentChantiers.length}):
${urgentChantiers.map(c => `
- ${c.nom}
Client: ${c.client ? `${c.client.prenom} ${c.client.nom}` : 'N/A'}
Retard: ${getDelayDays(c)} jours
Statut: ${c.statut}
Budget: ${formatCurrency(c.montantPrevu || 0)}
`).join('')}
STATISTIQUES:
- Total chantiers en retard: ${chantiers.length}
- Retard moyen: ${Math.round(chantiers.reduce((sum, c) => sum + getDelayDays(c), 0) / chantiers.length)} jours
- Impact budgétaire: ${formatCurrency(chantiers.reduce((sum, c) => sum + (c.montantPrevu || 0), 0))}
`;
const blob = new Blob([report], { type: 'text/plain;charset=utf-8;' });
const link = document.createElement('a');
link.href = URL.createObjectURL(blob);
link.download = `alerte_retards_${new Date().toISOString().split('T')[0]}.txt`;
link.click();
toast.current?.show({
severity: 'success',
summary: 'Rapport généré',
detail: 'Le rapport d\'alerte a été téléchargé',
life: 3000
});
};
const leftToolbarTemplate = () => {
return (
<div className="my-2 flex gap-2">
<h5 className="m-0 flex align-items-center text-red-500">
<i className="pi pi-exclamation-triangle mr-2"></i>
Chantiers en retard ({chantiers.length})
</h5>
<Button
label="Rapport d'alerte"
icon="pi pi-file-export"
severity="danger"
size="small"
onClick={generateAlertReport}
/>
</div>
);
};
const rightToolbarTemplate = () => {
return (
<Button
label="Exporter"
icon="pi pi-upload"
severity="help"
onClick={exportCSV}
/>
);
};
const actionBodyTemplate = (rowData: Chantier) => {
return (
<ActionButtonGroup>
<ActionButton
icon="pi pi-calendar-plus"
tooltip="Reporter l'échéance"
onClick={() => extendDeadline(rowData)}
color="orange"
/>
<ActionButton
icon="pi pi-pause"
tooltip="Suspendre le chantier"
onClick={() => changeStatus(rowData)}
color="red"
/>
<ViewButton
tooltip="Voir détails"
onClick={() => {
toast.current?.show({
severity: 'info',
summary: 'Info',
detail: `Détails du chantier ${rowData.nom}`,
life: 3000
});
}}
/>
</ActionButtonGroup>
);
};
const statusBodyTemplate = (rowData: Chantier) => {
const delayDays = getDelayDays(rowData);
const priority = getPriorityLevel(delayDays);
return (
<div className="flex align-items-center gap-2">
<Tag
value={rowData.statut === 'PLANIFIE' ? 'Non démarré' : 'En cours'}
severity={rowData.statut === 'PLANIFIE' ? 'info' : 'success'}
/>
<Chip
label={priority.level}
style={{ backgroundColor: priority.color, color: 'white' }}
className="text-xs"
/>
</div>
);
};
const delayBodyTemplate = (rowData: Chantier) => {
const delayDays = getDelayDays(rowData);
const severity = getDelaySeverity(delayDays);
return (
<div className="flex align-items-center gap-2">
<Tag
value={`${delayDays} jour${delayDays > 1 ? 's' : ''}`}
severity={severity}
icon="pi pi-clock"
/>
{rowData.statut === 'PLANIFIE' && (
<small className="text-600">de retard au démarrage</small>
)}
{rowData.statut === 'EN_COURS' && (
<small className="text-600">après l'échéance</small>
)}
</div>
);
};
const progressBodyTemplate = (rowData: Chantier) => {
if (rowData.statut === 'PLANIFIE') {
return <span className="text-600">Non démarré</span>;
}
const progress = calculateProgress(rowData);
return (
<div className="flex align-items-center gap-2">
<ProgressBar
value={Math.min(progress, 100)}
style={{ height: '6px', width: '100px' }}
color={progress > 100 ? '#ef4444' : undefined}
/>
<span className={`text-sm ${progress > 100 ? 'text-red-500 font-bold' : ''}`}>
{Math.round(progress)}%
</span>
</div>
);
};
const clientBodyTemplate = (rowData: Chantier) => {
if (!rowData.client) return '';
return `${rowData.client.prenom} ${rowData.client.nom}`;
};
const referenceeDateBodyTemplate = (rowData: Chantier) => {
const date = rowData.statut === 'PLANIFIE' ? rowData.dateDebut : rowData.dateFinPrevue;
const label = rowData.statut === 'PLANIFIE' ? 'Début prévu' : 'Fin prévue';
return (
<div>
<div className="font-bold text-red-500">{formatDate(date)}</div>
<small className="text-600">{label}</small>
</div>
);
};
const header = (
<div className="flex flex-column md:flex-row md:justify-content-between md:align-items-center">
<h5 className="m-0">Chantiers nécessitant une attention immédiate</h5>
<span className="block mt-2 md:mt-0 p-input-icon-left">
<i className="pi pi-search" />
<InputText
type="search"
placeholder="Rechercher..."
onInput={(e) => setGlobalFilter(e.currentTarget.value)}
/>
</span>
</div>
);
const actionDialogFooter = (
<>
<Button
label="Annuler"
icon="pi pi-times"
text
onClick={() => setActionDialog(false)}
/>
<Button
label={actionType === 'extend' ? 'Reporter' : 'Suspendre'}
icon={actionType === 'extend' ? 'pi pi-calendar-plus' : 'pi pi-pause'}
text
onClick={handleAction}
/>
</>
);
return (
<div className="grid">
<div className="col-12">
<Card>
<Toast ref={toast} />
<Toolbar className="mb-4" left={leftToolbarTemplate} right={rightToolbarTemplate} />
<DataTable
ref={dt}
value={chantiers}
selection={selectedChantiers}
onSelectionChange={(e) => setSelectedChantiers(e.value)}
selectionMode="multiple"
dataKey="id"
paginator
rows={10}
rowsPerPageOptions={[5, 10, 25]}
className="datatable-responsive"
paginatorTemplate="FirstPageLink PrevPageLink PageLinks NextPageLink LastPageLink CurrentPageReport RowsPerPageDropdown"
currentPageReportTemplate="Affichage de {first} à {last} sur {totalRecords} chantiers"
globalFilter={globalFilter}
emptyMessage="Aucun chantier en retard trouvé."
header={header}
responsiveLayout="scroll"
loading={loading}
sortField="dateDebut"
sortOrder={1}
>
<Column selectionMode="multiple" headerStyle={{ width: '4rem' }} />
<Column field="nom" header="Nom" sortable headerStyle={{ minWidth: '12rem' }} />
<Column field="client" header="Client" body={clientBodyTemplate} sortable headerStyle={{ minWidth: '12rem' }} />
<Column field="referenceDate" header="Date de référence" body={referenceeDateBodyTemplate} sortable headerStyle={{ minWidth: '12rem' }} />
<Column field="delay" header="Retard" body={delayBodyTemplate} headerStyle={{ minWidth: '12rem' }} />
<Column field="statut" header="Statut/Priorité" body={statusBodyTemplate} headerStyle={{ minWidth: '12rem' }} />
<Column field="progress" header="Progression" body={progressBodyTemplate} headerStyle={{ minWidth: '12rem' }} />
<Column field="montantPrevu" header="Budget" body={(rowData) => formatCurrency(rowData.montantPrevu)} sortable headerStyle={{ minWidth: '10rem' }} />
<Column body={actionBodyTemplate} headerStyle={{ minWidth: '12rem' }} />
</DataTable>
<Dialog
visible={actionDialog}
style={{ width: '500px' }}
header={actionType === 'extend' ? 'Reporter l\'échéance' : 'Suspendre le chantier'}
modal
className="p-fluid"
footer={actionDialogFooter}
onHide={() => setActionDialog(false)}
>
<div className="formgrid grid">
<div className="field col-12">
<p>
Chantier: <strong>{selectedChantier?.nom}</strong>
</p>
<p>
Retard actuel: <strong>{selectedChantier ? getDelayDays(selectedChantier) : 0} jour(s)</strong>
</p>
</div>
{actionType === 'extend' && (
<div className="field col-12">
<label htmlFor="newEndDate">Nouvelle date de fin prévue</label>
<Calendar
id="newEndDate"
value={newEndDate}
onChange={(e) => setNewEndDate(e.value)}
dateFormat="dd/mm/yy"
showIcon
minDate={new Date()}
/>
</div>
)}
<div className="field col-12">
<label htmlFor="actionNotes">
{actionType === 'extend' ? 'Raison du report' : 'Raison de la suspension'}
</label>
<InputTextarea
id="actionNotes"
value={actionNotes}
onChange={(e) => setActionNotes(e.target.value)}
rows={3}
placeholder="Expliquez la raison de cette action..."
/>
</div>
</div>
</Dialog>
</Card>
</div>
</div>
);
};
export default ChantiersRetardPage;
'use client';
export const dynamic = 'force-dynamic';
import React, { useState, useEffect, useRef } from 'react';
import { DataTable } from 'primereact/datatable';
import { Column } from 'primereact/column';
import { Button } from 'primereact/button';
import { InputText } from 'primereact/inputtext';
import { Card } from 'primereact/card';
import { Toast } from 'primereact/toast';
import { Toolbar } from 'primereact/toolbar';
import { Tag } from 'primereact/tag';
import { Dialog } from 'primereact/dialog';
import { Calendar } from 'primereact/calendar';
import { InputTextarea } from 'primereact/inputtextarea';
import { ProgressBar } from 'primereact/progressbar';
import { Chip } from 'primereact/chip';
import { chantierService } from '../../../../services/api';
import { formatDate, formatCurrency } from '../../../../utils/formatters';
import type { Chantier } from '../../../../types/btp';
import {
ActionButtonGroup,
ViewButton,
ActionButton
} from '../../../../components/ui/ActionButton';
const ChantiersRetardPage = () => {
const [chantiers, setChantiers] = useState<Chantier[]>([]);
const [loading, setLoading] = useState(true);
const [globalFilter, setGlobalFilter] = useState('');
const [selectedChantiers, setSelectedChantiers] = useState<Chantier[]>([]);
const [actionDialog, setActionDialog] = useState(false);
const [selectedChantier, setSelectedChantier] = useState<Chantier | null>(null);
const [actionType, setActionType] = useState<'extend' | 'status'>('extend');
const [newEndDate, setNewEndDate] = useState<Date | null>(null);
const [actionNotes, setActionNotes] = useState('');
const toast = useRef<Toast>(null);
const dt = useRef<DataTable<Chantier[]>>(null);
useEffect(() => {
loadChantiers();
}, []);
const loadChantiers = async () => {
try {
setLoading(true);
const data = await chantierService.getAll();
// Filtrer les chantiers en retard (planifiés avec date dépassée OU en cours avec date fin prévue dépassée)
const chantiersEnRetard = data.filter(chantier => {
const today = new Date();
// Chantiers planifiés dont la date de début est dépassée
if (chantier.statut === 'PLANIFIE') {
const startDate = new Date(chantier.dateDebut);
return startDate < today;
}
// Chantiers en cours dont la date de fin prévue est dépassée
if (chantier.statut === 'EN_COURS') {
const endDate = new Date(chantier.dateFinPrevue);
return endDate < today;
}
return false;
});
setChantiers(chantiersEnRetard);
} catch (error) {
console.error('Erreur lors du chargement des chantiers:', error);
toast.current?.show({
severity: 'error',
summary: 'Erreur',
detail: 'Impossible de charger les chantiers en retard',
life: 3000
});
} finally {
setLoading(false);
}
};
const getDelayDays = (chantier: Chantier) => {
const today = new Date();
let referenceDate: Date;
if (chantier.statut === 'PLANIFIE') {
referenceDate = new Date(chantier.dateDebut);
} else {
referenceDate = new Date(chantier.dateFinPrevue);
}
const diffTime = today.getTime() - referenceDate.getTime();
const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
return diffDays;
};
const getDelaySeverity = (days: number) => {
if (days <= 7) return 'warning';
if (days <= 30) return 'danger';
return 'danger';
};
const getPriorityLevel = (days: number) => {
if (days <= 3) return { level: 'FAIBLE', color: 'orange' };
if (days <= 15) return { level: 'MOYEN', color: 'red' };
return { level: 'URGENT', color: 'red' };
};
const calculateProgress = (chantier: Chantier) => {
if (chantier.statut !== 'EN_COURS' || !chantier.dateDebut || !chantier.dateFinPrevue) return 0;
const now = new Date();
const start = new Date(chantier.dateDebut);
const end = new Date(chantier.dateFinPrevue);
const totalDays = (end.getTime() - start.getTime()) / (1000 * 60 * 60 * 24);
const elapsedDays = (now.getTime() - start.getTime()) / (1000 * 60 * 60 * 24);
return Math.min(Math.max((elapsedDays / totalDays) * 100, 0), 120); // Peut dépasser 100% si en retard
};
const extendDeadline = (chantier: Chantier) => {
setSelectedChantier(chantier);
setActionType('extend');
setNewEndDate(new Date(chantier.dateFinPrevue));
setActionNotes('');
setActionDialog(true);
};
const changeStatus = (chantier: Chantier) => {
setSelectedChantier(chantier);
setActionType('status');
setActionNotes('');
setActionDialog(true);
};
const handleAction = async () => {
if (!selectedChantier) return;
try {
let updatedChantier = { ...selectedChantier };
if (actionType === 'extend' && newEndDate) {
updatedChantier.dateFinPrevue = newEndDate.toISOString().split('T')[0];
} else if (actionType === 'status') {
updatedChantier.statut = 'SUSPENDU' as any;
}
await chantierService.update(selectedChantier.id, updatedChantier);
// Recharger la liste si le statut a changé
if (actionType === 'status') {
setChantiers(prev => prev.filter(c => c.id !== selectedChantier.id));
} else {
// Mettre à jour le chantier dans la liste
setChantiers(prev => prev.map(c =>
c.id === selectedChantier.id ? updatedChantier : c
));
}
setActionDialog(false);
toast.current?.show({
severity: 'success',
summary: 'Succès',
detail: actionType === 'extend' ? 'Échéance reportée' : 'Chantier suspendu',
life: 3000
});
} catch (error) {
console.error('Erreur lors de l\'action:', error);
toast.current?.show({
severity: 'error',
summary: 'Erreur',
detail: 'Impossible d\'effectuer l\'action',
life: 3000
});
}
};
const exportCSV = () => {
dt.current?.exportCSV();
};
const generateAlertReport = () => {
const urgentChantiers = chantiers.filter(c => getPriorityLevel(getDelayDays(c)).level === 'URGENT');
const report = `
=== ALERTE CHANTIERS EN RETARD ===
Date du rapport: ${new Date().toLocaleDateString('fr-FR')}
CHANTIERS URGENTS (${urgentChantiers.length}):
${urgentChantiers.map(c => `
- ${c.nom}
Client: ${c.client ? `${c.client.prenom} ${c.client.nom}` : 'N/A'}
Retard: ${getDelayDays(c)} jours
Statut: ${c.statut}
Budget: ${formatCurrency(c.montantPrevu || 0)}
`).join('')}
STATISTIQUES:
- Total chantiers en retard: ${chantiers.length}
- Retard moyen: ${Math.round(chantiers.reduce((sum, c) => sum + getDelayDays(c), 0) / chantiers.length)} jours
- Impact budgétaire: ${formatCurrency(chantiers.reduce((sum, c) => sum + (c.montantPrevu || 0), 0))}
`;
const blob = new Blob([report], { type: 'text/plain;charset=utf-8;' });
const link = document.createElement('a');
link.href = URL.createObjectURL(blob);
link.download = `alerte_retards_${new Date().toISOString().split('T')[0]}.txt`;
link.click();
toast.current?.show({
severity: 'success',
summary: 'Rapport généré',
detail: 'Le rapport d\'alerte a été téléchargé',
life: 3000
});
};
const leftToolbarTemplate = () => {
return (
<div className="my-2 flex gap-2">
<h5 className="m-0 flex align-items-center text-red-500">
<i className="pi pi-exclamation-triangle mr-2"></i>
Chantiers en retard ({chantiers.length})
</h5>
<Button
label="Rapport d'alerte"
icon="pi pi-file-export"
severity="danger"
size="small"
onClick={generateAlertReport}
/>
</div>
);
};
const rightToolbarTemplate = () => {
return (
<Button
label="Exporter"
icon="pi pi-upload"
severity="help"
onClick={exportCSV}
/>
);
};
const actionBodyTemplate = (rowData: Chantier) => {
return (
<ActionButtonGroup>
<ActionButton
icon="pi pi-calendar-plus"
tooltip="Reporter l'échéance"
onClick={() => extendDeadline(rowData)}
color="orange"
/>
<ActionButton
icon="pi pi-pause"
tooltip="Suspendre le chantier"
onClick={() => changeStatus(rowData)}
color="red"
/>
<ViewButton
tooltip="Voir détails"
onClick={() => {
toast.current?.show({
severity: 'info',
summary: 'Info',
detail: `Détails du chantier ${rowData.nom}`,
life: 3000
});
}}
/>
</ActionButtonGroup>
);
};
const statusBodyTemplate = (rowData: Chantier) => {
const delayDays = getDelayDays(rowData);
const priority = getPriorityLevel(delayDays);
return (
<div className="flex align-items-center gap-2">
<Tag
value={rowData.statut === 'PLANIFIE' ? 'Non démarré' : 'En cours'}
severity={rowData.statut === 'PLANIFIE' ? 'info' : 'success'}
/>
<Chip
label={priority.level}
style={{ backgroundColor: priority.color, color: 'white' }}
className="text-xs"
/>
</div>
);
};
const delayBodyTemplate = (rowData: Chantier) => {
const delayDays = getDelayDays(rowData);
const severity = getDelaySeverity(delayDays);
return (
<div className="flex align-items-center gap-2">
<Tag
value={`${delayDays} jour${delayDays > 1 ? 's' : ''}`}
severity={severity}
icon="pi pi-clock"
/>
{rowData.statut === 'PLANIFIE' && (
<small className="text-600">de retard au démarrage</small>
)}
{rowData.statut === 'EN_COURS' && (
<small className="text-600">après l'échéance</small>
)}
</div>
);
};
const progressBodyTemplate = (rowData: Chantier) => {
if (rowData.statut === 'PLANIFIE') {
return <span className="text-600">Non démarré</span>;
}
const progress = calculateProgress(rowData);
return (
<div className="flex align-items-center gap-2">
<ProgressBar
value={Math.min(progress, 100)}
style={{ height: '6px', width: '100px' }}
color={progress > 100 ? '#ef4444' : undefined}
/>
<span className={`text-sm ${progress > 100 ? 'text-red-500 font-bold' : ''}`}>
{Math.round(progress)}%
</span>
</div>
);
};
const clientBodyTemplate = (rowData: Chantier) => {
if (!rowData.client) return '';
return `${rowData.client.prenom} ${rowData.client.nom}`;
};
const referenceeDateBodyTemplate = (rowData: Chantier) => {
const date = rowData.statut === 'PLANIFIE' ? rowData.dateDebut : rowData.dateFinPrevue;
const label = rowData.statut === 'PLANIFIE' ? 'Début prévu' : 'Fin prévue';
return (
<div>
<div className="font-bold text-red-500">{formatDate(date)}</div>
<small className="text-600">{label}</small>
</div>
);
};
const header = (
<div className="flex flex-column md:flex-row md:justify-content-between md:align-items-center">
<h5 className="m-0">Chantiers nécessitant une attention immédiate</h5>
<span className="block mt-2 md:mt-0 p-input-icon-left">
<i className="pi pi-search" />
<InputText
type="search"
placeholder="Rechercher..."
onInput={(e) => setGlobalFilter(e.currentTarget.value)}
/>
</span>
</div>
);
const actionDialogFooter = (
<>
<Button
label="Annuler"
icon="pi pi-times"
text
onClick={() => setActionDialog(false)}
/>
<Button
label={actionType === 'extend' ? 'Reporter' : 'Suspendre'}
icon={actionType === 'extend' ? 'pi pi-calendar-plus' : 'pi pi-pause'}
text
onClick={handleAction}
/>
</>
);
return (
<div className="grid">
<div className="col-12">
<Card>
<Toast ref={toast} />
<Toolbar className="mb-4" left={leftToolbarTemplate} right={rightToolbarTemplate} />
<DataTable
ref={dt}
value={chantiers}
selection={selectedChantiers}
onSelectionChange={(e) => setSelectedChantiers(e.value)}
selectionMode="multiple"
dataKey="id"
paginator
rows={10}
rowsPerPageOptions={[5, 10, 25]}
className="datatable-responsive"
paginatorTemplate="FirstPageLink PrevPageLink PageLinks NextPageLink LastPageLink CurrentPageReport RowsPerPageDropdown"
currentPageReportTemplate="Affichage de {first} à {last} sur {totalRecords} chantiers"
globalFilter={globalFilter}
emptyMessage="Aucun chantier en retard trouvé."
header={header}
responsiveLayout="scroll"
loading={loading}
sortField="dateDebut"
sortOrder={1}
>
<Column selectionMode="multiple" headerStyle={{ width: '4rem' }} />
<Column field="nom" header="Nom" sortable headerStyle={{ minWidth: '12rem' }} />
<Column field="client" header="Client" body={clientBodyTemplate} sortable headerStyle={{ minWidth: '12rem' }} />
<Column field="referenceDate" header="Date de référence" body={referenceeDateBodyTemplate} sortable headerStyle={{ minWidth: '12rem' }} />
<Column field="delay" header="Retard" body={delayBodyTemplate} headerStyle={{ minWidth: '12rem' }} />
<Column field="statut" header="Statut/Priorité" body={statusBodyTemplate} headerStyle={{ minWidth: '12rem' }} />
<Column field="progress" header="Progression" body={progressBodyTemplate} headerStyle={{ minWidth: '12rem' }} />
<Column field="montantPrevu" header="Budget" body={(rowData) => formatCurrency(rowData.montantPrevu)} sortable headerStyle={{ minWidth: '10rem' }} />
<Column body={actionBodyTemplate} headerStyle={{ minWidth: '12rem' }} />
</DataTable>
<Dialog
visible={actionDialog}
style={{ width: '500px' }}
header={actionType === 'extend' ? 'Reporter l\'échéance' : 'Suspendre le chantier'}
modal
className="p-fluid"
footer={actionDialogFooter}
onHide={() => setActionDialog(false)}
>
<div className="formgrid grid">
<div className="field col-12">
<p>
Chantier: <strong>{selectedChantier?.nom}</strong>
</p>
<p>
Retard actuel: <strong>{selectedChantier ? getDelayDays(selectedChantier) : 0} jour(s)</strong>
</p>
</div>
{actionType === 'extend' && (
<div className="field col-12">
<label htmlFor="newEndDate">Nouvelle date de fin prévue</label>
<Calendar
id="newEndDate"
value={newEndDate}
onChange={(e) => setNewEndDate(e.value)}
dateFormat="dd/mm/yy"
showIcon
minDate={new Date()}
/>
</div>
)}
<div className="field col-12">
<label htmlFor="actionNotes">
{actionType === 'extend' ? 'Raison du report' : 'Raison de la suspension'}
</label>
<InputTextarea
id="actionNotes"
value={actionNotes}
onChange={(e) => setActionNotes(e.target.value)}
rows={3}
placeholder="Expliquez la raison de cette action..."
/>
</div>
</div>
</Dialog>
</Card>
</div>
</div>
);
};
export default ChantiersRetardPage;

View File

@@ -10,36 +10,8 @@ import { Divider } from 'primereact/divider';
import { DataTable } from 'primereact/datatable';
import { Column } from 'primereact/column';
import { Tag } from 'primereact/tag';
interface Client {
id: number;
nom: string;
email: string;
telephone: string;
adresse: string;
ville: string;
codePostal: string;
typeClient: string;
dateCreation: string;
chantiers: Chantier[];
factures: Facture[];
}
interface Chantier {
id: number;
nom: string;
statut: string;
dateDebut: string;
budget: number;
}
interface Facture {
id: number;
numero: string;
montant: number;
dateEmission: string;
statut: string;
}
import { clientService } from '@/services/api';
import type { Client, Chantier, Facture } from '@/types/btp';
export default function ClientDetailsPage() {
const params = useParams();
@@ -58,15 +30,11 @@ export default function ClientDetailsPage() {
const loadClient = async () => {
try {
setLoading(true);
const API_URL = process.env.NEXT_PUBLIC_API_URL || 'https://api.lions.dev/btpxpress';
const response = await fetch(`${API_URL}/api/v1/clients/${id}`);
if (response.ok) {
const data = await response.json();
setClient(data);
}
const data = await clientService.getById(id);
setClient(data);
} catch (error) {
console.error('Erreur:', error);
console.error('Erreur lors du chargement du client:', error);
// L'intercepteur API gérera automatiquement la redirection si 401
} finally {
setLoading(false);
}
@@ -87,7 +55,8 @@ export default function ClientDetailsPage() {
const statutFactureTemplate = (rowData: Facture) => {
const severity = rowData.statut === 'PAYEE' ? 'success' :
rowData.statut === 'EN_ATTENTE' ? 'warning' : 'danger';
rowData.statut === 'ENVOYEE' || rowData.statut === 'BROUILLON' ? 'warning' :
rowData.statut === 'PARTIELLEMENT_PAYEE' ? 'info' : 'danger';
return <Tag value={rowData.statut} severity={severity} />;
};
@@ -109,8 +78,8 @@ export default function ClientDetailsPage() {
/>
<Avatar label={client.nom[0]} size="xlarge" shape="circle" className="mr-3" />
<div>
<h2 className="m-0">{client.nom}</h2>
<p className="text-600 m-0">{client.typeClient}</p>
<h2 className="m-0">{client.nom} {client.prenom}</h2>
<p className="text-600 m-0">{client.entreprise || 'Particulier'}</p>
</div>
</div>
<Button
@@ -140,81 +109,24 @@ export default function ClientDetailsPage() {
</div>
<div className="col-12 md:col-6">
<h3>Statistiques</h3>
<div className="grid">
<div className="col-6">
<Card className="text-center">
<div className="text-600">Chantiers</div>
<div className="text-2xl font-bold">{client.chantiers?.length || 0}</div>
</Card>
</div>
<div className="col-6">
<Card className="text-center">
<div className="text-600">Factures</div>
<div className="text-2xl font-bold">{client.factures?.length || 0}</div>
</Card>
</div>
</div>
<h3>Informations supplémentaires</h3>
<div className="mb-2"><strong>SIRET:</strong> {client.siret || 'N/A'}</div>
<div className="mb-2"><strong>N° TVA:</strong> {client.numeroTVA || 'N/A'}</div>
<div className="mb-2"><strong>Date de création:</strong> {new Date(client.dateCreation).toLocaleDateString('fr-FR')}</div>
</div>
</div>
</Card>
</div>
<div className="col-12">
<Card>
<TabView>
<TabPanel header="Chantiers" leftIcon="pi pi-home mr-2">
<DataTable value={client.chantiers || []} emptyMessage="Aucun chantier">
<Column field="nom" header="Nom" sortable />
<Column field="statut" header="Statut" body={statutChantierTemplate} sortable />
<Column field="dateDebut" header="Date début" sortable />
<Column
field="budget"
header="Budget"
body={(rowData) => formatMontant(rowData.budget)}
sortable
/>
<Column
header="Actions"
body={(rowData) => (
<Button
icon="pi pi-eye"
className="p-button-text p-button-sm"
onClick={() => router.push(`/chantiers/${rowData.id}`)}
/>
)}
/>
</DataTable>
</TabPanel>
<TabPanel header="Factures" leftIcon="pi pi-file mr-2">
<DataTable value={client.factures || []} emptyMessage="Aucune facture">
<Column field="numero" header="Numéro" sortable />
<Column
field="montant"
header="Montant"
body={(rowData) => formatMontant(rowData.montant)}
sortable
/>
<Column field="dateEmission" header="Date" sortable />
<Column field="statut" header="Statut" body={statutFactureTemplate} sortable />
<Column
header="Actions"
body={(rowData) => (
<Button
icon="pi pi-eye"
className="p-button-text p-button-sm"
onClick={() => router.push(`/factures/${rowData.id}`)}
/>
)}
/>
</DataTable>
</TabPanel>
<TabPanel header="Documents" leftIcon="pi pi-folder mr-2">
<p>Documents du client</p>
</TabPanel>
</TabView>
<Card title="Activités">
<p className="text-600">
Les chantiers et factures associés à ce client seront affichés ici une fois la relation établie dans le backend.
</p>
<div className="flex gap-2 mt-3">
<Button label="Voir les chantiers" icon="pi pi-home" className="p-button-outlined" onClick={() => router.push('/chantiers')} />
<Button label="Voir les factures" icon="pi pi-file" className="p-button-outlined" onClick={() => router.push('/factures')} />
</div>
</Card>
</div>
</div>

View File

@@ -36,61 +36,28 @@ const Dashboard = () => {
const searchParams = useSearchParams();
const [selectedChantier, setSelectedChantier] = useState<ChantierActif | null>(null);
const [showQuickView, setShowQuickView] = useState(false);
const [authProcessed, setAuthProcessed] = useState(false);
const [authError, setAuthError] = useState<string | null>(null);
const [authInProgress, setAuthInProgress] = useState(false);
const [isHydrated, setIsHydrated] = useState(false);
// Flag global pour éviter les appels multiples (React 18 StrictMode)
const authProcessingRef = useRef(false);
// Mémoriser le code traité pour éviter les retraitements
const processedCodeRef = useRef<string | null>(null);
// Flag pour éviter les redirections multiples
const redirectingRef = useRef(false);
const currentCode = searchParams.get('code');
const currentState = searchParams.get('state');
console.log('🏗️ Dashboard: SearchParams:', {
code: currentCode?.substring(0, 20) + '...',
state: currentState,
authProcessed,
processedCode: processedCodeRef.current?.substring(0, 20) + '...',
authInProgress: authInProgress
});
// Gérer l'hydratation pour éviter les erreurs SSR/CSR
// Nettoyer les paramètres OAuth de l'URL après le retour de Keycloak
useEffect(() => {
setIsHydrated(true);
}, []);
if (typeof window === 'undefined') return;
// Réinitialiser authProcessed si on a un nouveau code d'autorisation
useEffect(() => {
if (!isHydrated) return; // Attendre l'hydratation
if (currentCode && authProcessed && !authInProgress && processedCodeRef.current !== currentCode) {
console.log('🔄 Dashboard: Nouveau code détecté, réinitialisation authProcessed');
setAuthProcessed(false);
processedCodeRef.current = null;
}
}, [currentCode, authProcessed, authInProgress, isHydrated]);
// Fonction pour nettoyer l'URL des paramètres d'authentification
const cleanAuthParams = useCallback(() => {
if (typeof window === 'undefined') return; // Protection SSR
const url = new URL(window.location.href);
if (url.searchParams.has('code') || url.searchParams.has('state')) {
// Nettoyer query string
if (url.searchParams.has('code') || url.searchParams.has('state') || url.searchParams.has('session_state')) {
console.log('🧹 Dashboard: Nettoyage des paramètres OAuth de l\'URL (query)');
url.search = '';
window.history.replaceState({}, '', url.toString());
// Nettoyer sessionStorage après succès if (typeof window !== 'undefined') { sessionStorage.removeItem('oauth_code_processed'); }
}
// Nettoyer fragment (hash) si Keycloak utilise implicit flow par erreur
if (url.hash && (url.hash.includes('code=') || url.hash.includes('state='))) {
console.log('🧹 Dashboard: Nettoyage des paramètres OAuth de l\'URL (fragment)');
url.hash = '';
window.history.replaceState({}, '', url.toString());
}
}, []);
// Hooks pour les données et actions du dashboard
// Charger les données après authentification ou si pas de code d'autorisation
const shouldLoadData = authProcessed || !currentCode;
const {
metrics,
chantiersActifs,
@@ -104,6 +71,8 @@ const Dashboard = () => {
onRefresh: refresh
});
console.log('🏗️ Dashboard: État du chargement -', { loading, metricsLoaded: !!metrics, chantiersCount: chantiersActifs?.length || 0 });
// Optimisations avec useMemo pour les calculs coûteux
const formattedMetrics = useMemo(() => {
if (!metrics) return null;
@@ -194,129 +163,6 @@ const Dashboard = () => {
chantierActions.handleQuickView(chantier);
}, [chantierActions]);
// Traiter l'authentification Keycloak si nécessaire
useEffect(() => {
// Attendre l'hydratation avant de traiter l'authentification
if (!isHydrated) {
return;
}
// Mode développement : ignorer l'authentification Keycloak
if (process.env.NEXT_PUBLIC_DEV_MODE === 'true' || process.env.NEXT_PUBLIC_SKIP_AUTH === 'true') {
console.log('🔧 Dashboard: Mode développement détecté, authentification ignorée');
setAuthProcessed(true);
return;
}
// Si l'authentification est déjà terminée, ne rien faire
if (authProcessed) {
return;
}
// Si on est en train de rediriger, ne rien faire
if (redirectingRef.current) {
return;
}
const processAuth = async () => {
try {
// Protection absolue contre les boucles
if (authInProgress || authProcessingRef.current) {
console.log('🛑 Dashboard: Processus d\'authentification déjà en cours, arrêt');
return;
}
// Les tokens sont maintenant stockés dans des cookies HttpOnly
// Le middleware les vérifiera automatiquement
// Pas besoin de vérifier localStorage
const code = currentCode;
const state = currentState;
const error = searchParams.get('error');
if (error) {
setAuthError(`Erreur d'authentification: ${error}`);
setAuthProcessed(true);
return;
}
// Vérifier si ce code a déjà été traité
if (code && !authProcessed && !authInProgress && !authProcessingRef.current && processedCodeRef.current !== code) {
try {
console.log('🔐 Traitement du code d\'autorisation Keycloak...', { code: code.substring(0, 20) + '...', state });
// Marquer IMMÉDIATEMENT dans sessionStorage pour empêcher double traitement
if (typeof window !== 'undefined') {
sessionStorage.setItem('oauth_code_processed', code);
}
// Marquer l'authentification comme en cours pour éviter les appels multiples
authProcessingRef.current = true;
processedCodeRef.current = code;
setAuthInProgress(true);
console.log('📡 Appel de /api/auth/token...');
// Utiliser fetch au lieu d'un formulaire pour éviter la boucle de redirection
const response = await fetch('/api/auth/token', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ code, state: state || '' })
});
if (response.ok) {
console.log('✅ Authentification réussie, tokens stockés dans les cookies');
// Nettoyer l'URL en enlevant les paramètres OAuth
window.history.replaceState({}, '', '/dashboard');
// Nettoyer sessionStorage après succès if (typeof window !== 'undefined') { sessionStorage.removeItem('oauth_code_processed'); }
// Marquer l'authentification comme terminée
setAuthProcessed(true);
setAuthInProgress(false);
authProcessingRef.current = false;
} else {
console.error("❌ Erreur lors de l'authentification");
const errorData = await response.json();
setAuthError(`Erreur lors de l'authentification: ${errorData.error || 'Erreur inconnue'}`);
setAuthProcessed(true);
setAuthInProgress(false);
authProcessingRef.current = false;
}
} catch (error) {
console.error('❌ Erreur lors du traitement de l\'authentification:', error);
// ARRÊTER LA BOUCLE : Ne pas rediriger automatiquement, juste marquer comme traité
console.log('🛑 Dashboard: Erreur d\'authentification, arrêt du processus pour éviter la boucle');
const errorMessage = error instanceof Error ? error.message : 'Erreur inconnue lors de l\'authentification';
setAuthError(`Erreur lors de l'authentification: ${errorMessage}`);
setAuthProcessed(true);
setAuthInProgress(false);
authProcessingRef.current = false;
}
} else {
setAuthProcessed(true);
setAuthInProgress(false);
authProcessingRef.current = false;
}
} catch (error) {
console.error('❌ Erreur générale lors du traitement de l\'authentification:', error);
const errorMessage = error instanceof Error ? error.message : 'Erreur inconnue lors de l\'authentification';
setAuthError(`Erreur lors de l'authentification: ${errorMessage}`);
setAuthProcessed(true);
setAuthInProgress(false);
authProcessingRef.current = false;
}
};
processAuth();
}, [currentCode, currentState, authProcessed, authInProgress, isHydrated]);
const actionBodyTemplate = useCallback((rowData: ChantierActif) => {
const actions: ActionButtonType[] = ['VIEW', 'PHASES', 'PLANNING', 'STATS', 'MENU'];
@@ -385,68 +231,6 @@ const Dashboard = () => {
);
}, [handleQuickView, router, chantierActions]);
// Attendre l'hydratation pour éviter les erreurs SSR/CSR
if (!isHydrated) {
return (
<div className="grid">
<div className="col-12">
<div className="card">
<div className="text-center">
<ProgressSpinner style={{ width: '50px', height: '50px' }} />
<h5 className="mt-3">Chargement...</h5>
<p className="text-600">Initialisation de l'application</p>
</div>
</div>
</div>
</div>
);
}
// Afficher le chargement pendant le traitement de l'authentification
if (!authProcessed) {
return (
<div className="grid">
<div className="col-12">
<div className="card">
<div className="text-center">
<ProgressSpinner style={{ width: '50px', height: '50px' }} />
<h5 className="mt-3">Authentification en cours...</h5>
<p className="text-600">Traitement des informations de connexion</p>
</div>
</div>
</div>
</div>
);
}
// Afficher l'erreur d'authentification
if (authError) {
return (
<div className="grid">
<div className="col-12">
<div className="card">
<div className="text-center">
<i className="pi pi-exclamation-triangle text-red-500" style={{ fontSize: '4rem' }}></i>
<h5 className="text-red-500">Erreur d'authentification</h5>
<p className="text-600 mb-4">{authError}</p>
<Button
label="Retour à la connexion"
icon="pi pi-sign-in"
onClick={() => window.location.href = '/api/auth/login'}
className="p-button-outlined"
/>
</div>
</div>
</div>
</div>
);
}
if (loading) {
return (
<div className="grid">

View File

@@ -10,38 +10,8 @@ import { Calendar } from 'primereact/calendar';
import { DataTable } from 'primereact/datatable';
import { Column } from 'primereact/column';
import { Timeline } from 'primereact/timeline';
interface Materiel {
id: number;
nom: string;
reference: string;
type: string;
marque: string;
modele: string;
statut: string;
dateAchat: string;
prixAchat: number;
tauxJournalier: number;
disponibilite: string;
reservations: Reservation[];
maintenances: Maintenance[];
}
interface Reservation {
id: number;
chantier: string;
dateDebut: string;
dateFin: string;
statut: string;
}
interface Maintenance {
id: number;
type: string;
date: string;
description: string;
cout: number;
}
import { materielService } from '@/services/api';
import type { Materiel } from '@/types/btp';
export default function MaterielDetailsPage() {
const params = useParams();
@@ -60,15 +30,11 @@ export default function MaterielDetailsPage() {
const loadMateriel = async () => {
try {
setLoading(true);
const API_URL = process.env.NEXT_PUBLIC_API_URL || 'https://api.lions.dev/btpxpress';
const response = await fetch(`${API_URL}/api/v1/materiels/${id}`);
if (response.ok) {
const data = await response.json();
setMateriel(data);
}
const data = await materielService.getById(id);
setMateriel(data);
} catch (error) {
console.error('Erreur:', error);
console.error('Erreur lors du chargement du matériel:', error);
// L'intercepteur API gérera automatiquement la redirection si 401
} finally {
setLoading(false);
}
@@ -96,9 +62,6 @@ export default function MaterielDetailsPage() {
}
};
const statutTemplate = (rowData: Reservation) => {
return <Tag value={rowData.statut} severity={getStatutSeverity(rowData.statut)} />;
};
if (loading || !materiel) {
return <div>Chargement...</div>;
@@ -118,7 +81,7 @@ export default function MaterielDetailsPage() {
/>
<div>
<h2 className="m-0">{materiel.nom}</h2>
<p className="text-600 m-0">{materiel.reference}</p>
<p className="text-600 m-0">{materiel.numeroSerie || 'N/A'}</p>
</div>
</div>
<div>
@@ -139,11 +102,11 @@ export default function MaterielDetailsPage() {
<div className="col-12 md:col-6">
<h3>Informations</h3>
<div className="mb-2"><strong>Type:</strong> {materiel.type}</div>
<div className="mb-2"><strong>Marque:</strong> {materiel.marque}</div>
<div className="mb-2"><strong>Modèle:</strong> {materiel.modele}</div>
<div className="mb-2"><strong>Date d'achat:</strong> {materiel.dateAchat}</div>
<div className="mb-2"><strong>Prix d'achat:</strong> {formatMontant(materiel.prixAchat)}</div>
<div className="mb-2"><strong>Tarif journalier:</strong> {formatMontant(materiel.tauxJournalier)}</div>
<div className="mb-2"><strong>Marque:</strong> {materiel.marque || 'N/A'}</div>
<div className="mb-2"><strong>Modèle:</strong> {materiel.modele || 'N/A'}</div>
<div className="mb-2"><strong>Date d'achat:</strong> {materiel.dateAchat || 'N/A'}</div>
<div className="mb-2"><strong>Valeur d'achat:</strong> {formatMontant(materiel.valeurAchat || 0)}</div>
<div className="mb-2"><strong>Coût d'utilisation:</strong> {formatMontant(materiel.coutUtilisation || 0)}</div>
</div>
<div className="col-12 md:col-6">
@@ -155,41 +118,14 @@ export default function MaterielDetailsPage() {
</div>
<div className="col-12">
<Card>
<TabView>
<TabPanel header="Réservations" leftIcon="pi pi-calendar mr-2">
<DataTable value={materiel.reservations || []} emptyMessage="Aucune réservation">
<Column field="chantier" header="Chantier" sortable />
<Column field="dateDebut" header="Date début" sortable />
<Column field="dateFin" header="Date fin" sortable />
<Column field="statut" header="Statut" body={statutTemplate} sortable />
<Column
header="Actions"
body={() => (
<Button icon="pi pi-eye" className="p-button-text p-button-sm" />
)}
/>
</DataTable>
</TabPanel>
<TabPanel header="Maintenances" leftIcon="pi pi-wrench mr-2">
<Timeline
value={materiel.maintenances || []}
content={(item: Maintenance) => (
<Card>
<div><strong>{item.type}</strong></div>
<div className="text-600">{item.date}</div>
<p>{item.description}</p>
<div><strong>Coût:</strong> {formatMontant(item.cout)}</div>
</Card>
)}
/>
</TabPanel>
<TabPanel header="Documents" leftIcon="pi pi-folder mr-2">
<p>Documents techniques et certificats</p>
</TabPanel>
</TabView>
<Card title="Historique d'utilisation">
<p className="text-600">
Les réservations et maintenances de ce matériel seront affichées ici une fois la relation établie dans le backend.
</p>
<div className="flex gap-2 mt-3">
<Button label="Voir le planning" icon="pi pi-calendar" className="p-button-outlined" onClick={() => router.push('/planning')} />
<Button label="Planifier une maintenance" icon="pi pi-wrench" className="p-button-outlined" />
</div>
</Card>
</div>
</div>

View File

@@ -12,6 +12,7 @@ import { Button } from 'primereact/button';
import { LayoutContext } from '../../layout/context/layoutcontext';
import { PrimeReactContext } from 'primereact/api';
import type { ColorScheme, Page } from '@/types';
import { redirectToLogin } from '@/lib/auth';
const LandingPage: Page = () => {
const { layoutConfig, setLayoutConfig } = useContext(LayoutContext);
@@ -140,13 +141,13 @@ const LandingPage: Page = () => {
</StyleClass>
</li>
<li>
<a href="http://localhost:8080/api/v1/auth/login" className="p-ripple flex m-0 md:ml-5 md:px-0 px-3 py-3 text-gray-800 font-medium line-height-3 hover:text-gray-800 cursor-pointer">
<a onClick={() => redirectToLogin()} className="p-ripple flex m-0 md:ml-5 md:px-0 px-3 py-3 text-gray-800 font-medium line-height-3 hover:text-gray-800 cursor-pointer">
<span>Connexion</span>
<Ripple />
</a>
</li>
<li>
<a href="http://localhost:8080/api/v1/auth/login" className="p-ripple flex m-0 md:ml-5 md:px-0 px-3 py-3 text-gray-800 font-medium line-height-3 hover:text-gray-800 cursor-pointer">
<a onClick={() => redirectToLogin()} className="p-ripple flex m-0 md:ml-5 md:px-0 px-3 py-3 text-gray-800 font-medium line-height-3 hover:text-gray-800 cursor-pointer">
<span>Inscription</span>
<Ripple />
</a>
@@ -182,7 +183,7 @@ const LandingPage: Page = () => {
Bienvenue sur BTP Xpress
</h1>
<h2 className="mt-0 font-medium text-4xl text-gray-700">Votre plateforme de gestion BTP moderne</h2>
<a href="http://localhost:8080/api/v1/auth/login" className="p-button text-gray-700 bg-cyan-500 border-cyan-500 font-bold border-round" style={{ mixBlendMode: 'multiply', padding: ' 0.858rem 1.142rem' }}>
<a onClick={() => redirectToLogin()} className="p-button text-gray-700 bg-cyan-500 border-cyan-500 font-bold border-round" style={{ mixBlendMode: 'multiply', padding: ' 0.858rem 1.142rem' }}>
<span className="p-button-text">Commencer</span>
</a>
</div>

View File

@@ -1,29 +0,0 @@
import { NextRequest, NextResponse } from 'next/server';
const KEYCLOAK_URL = process.env.NEXT_PUBLIC_KEYCLOAK_URL || 'https://security.lions.dev';
const KEYCLOAK_REALM = process.env.NEXT_PUBLIC_KEYCLOAK_REALM || 'btpxpress';
const CLIENT_ID = process.env.NEXT_PUBLIC_KEYCLOAK_CLIENT_ID || 'btpxpress-frontend';
const REDIRECT_URI = process.env.NEXT_PUBLIC_APP_URL
? `${process.env.NEXT_PUBLIC_APP_URL}/auth/callback`
: 'https://btpxpress.lions.dev/auth/callback';
export async function GET(request: NextRequest) {
console.log('🔐 Login API called');
// Générer un state aléatoire pour CSRF protection
const state = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
// Construire l'URL d'autorisation Keycloak
const authUrl = new URL(`${KEYCLOAK_URL}/realms/${KEYCLOAK_REALM}/protocol/openid-connect/auth`);
authUrl.searchParams.set('client_id', CLIENT_ID);
authUrl.searchParams.set('redirect_uri', REDIRECT_URI);
authUrl.searchParams.set('response_type', 'code');
authUrl.searchParams.set('scope', 'openid profile email');
authUrl.searchParams.set('state', state);
console.log('✅ Redirecting to Keycloak:', authUrl.toString());
// Rediriger vers Keycloak pour l'authentification
return NextResponse.redirect(authUrl.toString());
}

View File

@@ -1,48 +0,0 @@
import { NextRequest, NextResponse } from 'next/server';
import { cookies } from 'next/headers';
const KEYCLOAK_URL = process.env.NEXT_PUBLIC_KEYCLOAK_URL || 'https://security.lions.dev';
const KEYCLOAK_REALM = process.env.NEXT_PUBLIC_KEYCLOAK_REALM || 'btpxpress';
const CLIENT_ID = process.env.NEXT_PUBLIC_KEYCLOAK_CLIENT_ID || 'btpxpress-frontend';
const POST_LOGOUT_REDIRECT_URI = process.env.NEXT_PUBLIC_APP_URL || 'https://btpxpress.lions.dev';
export async function GET(request: NextRequest) {
console.log('🚪 Logout API called');
const cookieStore = cookies();
// Récupérer l'id_token avant de supprimer les cookies
const idToken = cookieStore.get('id_token')?.value;
// Supprimer tous les cookies d'authentification
cookieStore.delete('access_token');
cookieStore.delete('refresh_token');
cookieStore.delete('id_token');
cookieStore.delete('token_expires_at');
console.log('✅ Authentication cookies deleted');
// Si on a un id_token, on fait un logout Keycloak
if (idToken) {
const logoutUrl = new URL(
`${KEYCLOAK_URL}/realms/${KEYCLOAK_REALM}/protocol/openid-connect/logout`
);
logoutUrl.searchParams.set('client_id', CLIENT_ID);
logoutUrl.searchParams.set('post_logout_redirect_uri', POST_LOGOUT_REDIRECT_URI);
logoutUrl.searchParams.set('id_token_hint', idToken);
console.log('✅ Redirecting to Keycloak logout');
return NextResponse.redirect(logoutUrl.toString());
}
// Sinon, rediriger directement vers la page d'accueil
console.log('✅ Redirecting to home page');
return NextResponse.redirect(POST_LOGOUT_REDIRECT_URI);
}
export async function POST(request: NextRequest) {
// Même logique pour POST
return GET(request);
}

View File

@@ -1,138 +0,0 @@
import { NextRequest, NextResponse } from 'next/server';
import { cookies } from 'next/headers';
const KEYCLOAK_URL = process.env.NEXT_PUBLIC_KEYCLOAK_URL || 'https://security.lions.dev';
const KEYCLOAK_REALM = process.env.NEXT_PUBLIC_KEYCLOAK_REALM || 'btpxpress';
const CLIENT_ID = process.env.NEXT_PUBLIC_KEYCLOAK_CLIENT_ID || 'btpxpress-frontend';
const REDIRECT_URI = process.env.NEXT_PUBLIC_APP_URL
? `${process.env.NEXT_PUBLIC_APP_URL}/auth/callback`
: 'https://btpxpress.lions.dev/auth/callback';
const TOKEN_ENDPOINT = `${KEYCLOAK_URL}/realms/${KEYCLOAK_REALM}/protocol/openid-connect/token`;
export async function POST(request: NextRequest) {
console.log('🔐 Token exchange API called');
try {
const body = await request.json();
const { code, state } = body;
if (!code) {
console.error('❌ No authorization code provided');
return NextResponse.json(
{ error: 'Code d\'autorisation manquant' },
{ status: 400 }
);
}
console.log('✅ Exchanging code with Keycloak...');
console.log('📍 Token endpoint:', TOKEN_ENDPOINT);
console.log('📍 Client ID:', CLIENT_ID);
console.log('📍 Redirect URI:', REDIRECT_URI);
// Préparer les paramètres pour l'échange de code
const params = new URLSearchParams({
grant_type: 'authorization_code',
client_id: CLIENT_ID,
code: code,
redirect_uri: REDIRECT_URI,
});
// Échanger le code contre des tokens
const tokenResponse = await fetch(TOKEN_ENDPOINT, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: params.toString(),
});
if (!tokenResponse.ok) {
const errorText = await tokenResponse.text();
console.error('❌ Keycloak token exchange failed:', tokenResponse.status, errorText);
let errorData;
try {
errorData = JSON.parse(errorText);
} catch {
errorData = { error: 'Token exchange failed', details: errorText };
}
return NextResponse.json(
{
error: errorData.error || 'Échec de l\'échange de token',
error_description: errorData.error_description || 'Erreur lors de la communication avec Keycloak',
details: errorData
},
{ status: tokenResponse.status }
);
}
const tokens = await tokenResponse.json();
console.log('✅ Tokens received from Keycloak');
// Stocker les tokens dans des cookies HttpOnly sécurisés
const cookieStore = cookies();
const isProduction = process.env.NODE_ENV === 'production';
// Access token (durée: expires_in secondes)
cookieStore.set('access_token', tokens.access_token, {
httpOnly: true,
secure: isProduction,
sameSite: 'lax',
maxAge: tokens.expires_in || 300, // Par défaut 5 minutes
path: '/',
});
// Refresh token (durée plus longue)
if (tokens.refresh_token) {
cookieStore.set('refresh_token', tokens.refresh_token, {
httpOnly: true,
secure: isProduction,
sameSite: 'lax',
maxAge: tokens.refresh_expires_in || 1800, // Par défaut 30 minutes
path: '/',
});
}
// ID token
if (tokens.id_token) {
cookieStore.set('id_token', tokens.id_token, {
httpOnly: true,
secure: isProduction,
sameSite: 'lax',
maxAge: tokens.expires_in || 300,
path: '/',
});
}
// Stocker aussi le temps d'expiration
cookieStore.set('token_expires_at', String(Date.now() + (tokens.expires_in * 1000)), {
httpOnly: true,
secure: isProduction,
sameSite: 'lax',
maxAge: tokens.expires_in || 300,
path: '/',
});
console.log('✅ Tokens stored in HttpOnly cookies');
// Retourner une réponse de succès (sans les tokens)
return NextResponse.json({
success: true,
message: 'Authentification réussie',
expires_in: tokens.expires_in,
});
} catch (error) {
console.error('❌ Error in token exchange API:', error);
return NextResponse.json(
{
error: 'Erreur serveur',
message: error instanceof Error ? error.message : 'Erreur inconnue'
},
{ status: 500 }
);
}
}

View File

@@ -1,82 +0,0 @@
import { NextRequest, NextResponse } from 'next/server';
import { cookies } from 'next/headers';
const KEYCLOAK_URL = process.env.NEXT_PUBLIC_KEYCLOAK_URL || 'https://security.lions.dev';
const KEYCLOAK_REALM = process.env.NEXT_PUBLIC_KEYCLOAK_REALM || 'btpxpress';
const USERINFO_ENDPOINT = `${KEYCLOAK_URL}/realms/${KEYCLOAK_REALM}/protocol/openid-connect/userinfo`;
export async function GET(request: NextRequest) {
console.log('👤 Userinfo API called');
try {
const cookieStore = cookies();
const accessToken = cookieStore.get('access_token')?.value;
if (!accessToken) {
console.error('❌ No access token found');
return NextResponse.json(
{ error: 'Non authentifié', authenticated: false },
{ status: 401 }
);
}
console.log('✅ Access token found, fetching user info from Keycloak');
// Récupérer les informations utilisateur depuis Keycloak
const userinfoResponse = await fetch(USERINFO_ENDPOINT, {
method: 'GET',
headers: {
'Authorization': `Bearer ${accessToken}`,
'Content-Type': 'application/json',
},
});
if (!userinfoResponse.ok) {
const errorText = await userinfoResponse.text();
console.error('❌ Keycloak userinfo failed:', userinfoResponse.status, errorText);
// Si le token est invalide ou expiré
if (userinfoResponse.status === 401) {
// Supprimer les cookies invalides
cookieStore.delete('access_token');
cookieStore.delete('refresh_token');
cookieStore.delete('id_token');
cookieStore.delete('token_expires_at');
return NextResponse.json(
{ error: 'Token expiré ou invalide', authenticated: false },
{ status: 401 }
);
}
return NextResponse.json(
{
error: 'Erreur lors de la récupération des informations utilisateur',
authenticated: false
},
{ status: userinfoResponse.status }
);
}
const userinfo = await userinfoResponse.json();
console.log('✅ User info retrieved:', userinfo.preferred_username || userinfo.sub);
return NextResponse.json({
authenticated: true,
user: userinfo,
});
} catch (error) {
console.error('❌ Error in userinfo API:', error);
return NextResponse.json(
{
error: 'Erreur serveur',
authenticated: false,
message: error instanceof Error ? error.message : 'Erreur inconnue'
},
{ status: 500 }
);
}
}

View File

@@ -1,11 +1,12 @@
'use client';
import React from 'react';
import React, { Suspense } from 'react';
import { useSearchParams } from 'next/navigation';
import { Button } from 'primereact/button';
import { Card } from 'primereact/card';
import { redirectToLogin } from '@/lib/auth';
export default function LoginPage() {
function LoginContent() {
const searchParams = useSearchParams();
const returnUrl = searchParams.get('returnUrl') || '/dashboard';
@@ -15,8 +16,8 @@ export default function LoginPage() {
sessionStorage.setItem('returnUrl', returnUrl);
}
// Rediriger vers l'API de login qui initiera le flux OAuth
window.location.href = '/api/auth/login';
// Rediriger vers Keycloak pour l'authentification
redirectToLogin(returnUrl);
};
return (
@@ -68,3 +69,15 @@ export default function LoginPage() {
</div>
);
}
export default function LoginPage() {
return (
<Suspense fallback={
<div className="min-h-screen flex align-items-center justify-content-center">
<i className="pi pi-spin pi-spinner text-4xl"></i>
</div>
}>
<LoginContent />
</Suspense>
);
}

View File

@@ -11,6 +11,7 @@ import { Button } from 'primereact/button';
import { LayoutContext } from '../layout/context/layoutcontext';
import { PrimeReactContext } from 'primereact/api';
import type { ColorScheme } from '@/types';
import { redirectToLogin } from '@/lib/auth';
const LandingPage = () => {
const router = useRouter();
@@ -110,7 +111,7 @@ const LandingPage = () => {
</a>
</li>
<li>
<a onClick={() => window.location.href = 'http://localhost:8080/api/v1/auth/login'} className="p-ripple flex m-0 md:ml-5 md:px-0 px-3 py-3 text-gray-800 font-medium line-height-3 hover:text-gray-800 cursor-pointer">
<a onClick={() => redirectToLogin()} className="p-ripple flex m-0 md:ml-5 md:px-0 px-3 py-3 text-gray-800 font-medium line-height-3 hover:text-gray-800 cursor-pointer">
<span>Connexion</span>
<Ripple />
</a>
@@ -168,7 +169,7 @@ const LandingPage = () => {
<span className="font-semibold text-gray-800">Facturation automatisée</span>
</div>
</div>
<a onClick={() => window.location.href = 'http://localhost:8080/api/v1/auth/login'} className="p-button text-white bg-orange-500 border-orange-500 font-bold border-round cursor-pointer mr-3 shadow-3" style={{ padding: '1.2rem 2.5rem', fontSize: '1.2rem' }}>
<a onClick={() => redirectToLogin()} className="p-button text-white bg-orange-500 border-orange-500 font-bold border-round cursor-pointer mr-3 shadow-3" style={{ padding: '1.2rem 2.5rem', fontSize: '1.2rem' }}>
<i className="pi pi-play mr-2"></i>
Démarrer maintenant
</a>
@@ -469,7 +470,7 @@ const LandingPage = () => {
</li>
</ul>
<Button
onClick={() => window.location.href = 'http://localhost:8080/api/v1/auth/login'}
onClick={() => redirectToLogin()}
className="w-full p-button-outlined border-orange-300 text-orange-600 font-semibold py-3"
>
Commencer l&apos;essai gratuit
@@ -513,7 +514,7 @@ const LandingPage = () => {
</li>
</ul>
<Button
onClick={() => window.location.href = 'http://localhost:8080/api/v1/auth/login'}
onClick={() => redirectToLogin()}
className="w-full bg-cyan-500 border-cyan-500 text-white font-semibold py-3"
>
Démarrer maintenant
@@ -554,7 +555,7 @@ const LandingPage = () => {
</li>
</ul>
<Button
onClick={() => window.location.href = 'http://localhost:8080/api/v1/auth/login'}
onClick={() => redirectToLogin()}
className="w-full p-button-outlined border-purple-300 text-purple-600 font-semibold py-3"
>
Nous contacter
@@ -576,7 +577,7 @@ const LandingPage = () => {
</p>
<div className="flex flex-wrap justify-content-center gap-3">
<Button
onClick={() => window.location.href = 'http://localhost:8080/api/v1/auth/login'}
onClick={() => redirectToLogin()}
style={{
backgroundColor: 'white',
color: '#f97316',
@@ -591,7 +592,7 @@ const LandingPage = () => {
Essai gratuit 30 jours
</Button>
<Button
onClick={() => window.location.href = 'http://localhost:8080/api/v1/auth/login'}
onClick={() => redirectToLogin()}
style={{
backgroundColor: 'transparent',
color: 'white',
@@ -636,8 +637,8 @@ const LandingPage = () => {
<ul className="list-none p-0">
<li className="mb-2"><a href="#features" className="text-gray-300 hover:text-white">Fonctionnalités</a></li>
<li className="mb-2"><a href="#pricing" className="text-gray-300 hover:text-white">Tarifs</a></li>
<li className="mb-2"><a href="http://localhost:8080/api/v1/auth/login" className="text-gray-300 hover:text-white">Démo</a></li>
<li className="mb-2"><a href="http://localhost:8080/api/v1/auth/login" className="text-gray-300 hover:text-white">Essai gratuit</a></li>
<li className="mb-2"><a onClick={() => redirectToLogin()} className="text-gray-300 hover:text-white">Démo</a></li>
<li className="mb-2"><a onClick={() => redirectToLogin()} className="text-gray-300 hover:text-white">Essai gratuit</a></li>
</ul>
</div>
<div className="col-6 md:col-3 mb-4">

View File

@@ -1,266 +0,0 @@
'use client';
import React, { useContext, useEffect, useRef, useState } from 'react';
import { Ripple } from 'primereact/ripple';
import { InputText } from 'primereact/inputtext';
import { StyleClass } from 'primereact/styleclass';
import { useRouter } from 'next/navigation';
import { Button } from 'primereact/button';
import { LayoutContext } from '../layout/context/layoutcontext';
import { PrimeReactContext } from 'primereact/api';
import type { ColorScheme } from '@/types';
const LandingPage = () => {
const router = useRouter();
const { layoutConfig, setLayoutConfig } = useContext(LayoutContext);
const { changeTheme } = useContext(PrimeReactContext);
const homeRef = useRef(null);
const timesRef = useRef(null);
const menuRef = useRef(null);
const menuButtonRef = useRef(null);
const meetRef = useRef(null);
const featuresRef = useRef(null);
const pricingRef = useRef(null);
const pricingButtonRef = useRef(null);
const buyRef = useRef(null);
const featuresButtonRef = useRef(null);
const goHome = () => {
router.push('/');
};
const scrollToElement = (el: React.RefObject<HTMLElement>) => {
if (el.current) {
el.current?.scrollIntoView({
behavior: 'smooth',
block: 'start',
inline: 'nearest'
});
}
};
const changeColorScheme = (colorScheme: ColorScheme) => {
changeTheme?.(layoutConfig.colorScheme, colorScheme, 'theme-link', () => {
setLayoutConfig((prevState) => ({
...prevState,
colorScheme,
menuTheme: layoutConfig.colorScheme === 'dark' ? 'dark' : 'light'
}));
});
};
useEffect(() => {
changeColorScheme('light');
setLayoutConfig((prevState) => ({
...prevState,
menuTheme: 'light'
}));
}, []);
return (
<div ref={homeRef} className="landing-container" style={{ background: '#100e23' }}>
<div id="header" className="landing-header flex flex-column w-full p-6" style={{ minHeight: '1000px', background: 'linear-gradient(135deg, #ffffff 0%, #f8fafc 50%, #f1f5f9 100%)' }}>
<div className="header-menu-container flex align-items-center justify-content-between">
<div className="header-left-elements flex align-items-center justify-content-between">
<div className="cursor-pointer layout-topbar-logo flex align-items-center" onClick={goHome}>
<i className="pi pi-building text-orange-600 text-3xl mr-3"></i>
<span className="text-2xl font-bold text-gray-800">BTP Xpress</span>
</div>
<StyleClass nodeRef={menuButtonRef} selector="@next" enterClassName="hidden" enterActiveClassName="px-scalein" leaveToClassName="hidden" leaveActiveClassName="px-fadeout">
<a ref={menuButtonRef} className="p-ripple cursor-pointer block lg:hidden text-gray-800 font-medium line-height-3 hover:text-gray-800" style={{ fontSize: '2rem' }}>
<i className="pi pi-bars"></i>
<Ripple />
</a>
</StyleClass>
<ul
ref={menuRef}
id="menu"
style={{ top: '0px', right: '0%' }}
className="list-none lg:flex lg:flex-row flex-column align-items-start bg-white absolute lg:relative h-screen lg:h-auto lg:surface-ground m-0 z-5 w-full sm:w-6 lg:w-full py-6 lg:py-0"
>
<StyleClass nodeRef={timesRef} selector="@parent" enterClassName="hidden" enterActiveClassName="px-scalein" leaveToClassName="hidden" leaveActiveClassName="px-fadeout">
<a ref={timesRef} className="p-ripple cursor-pointer block lg:hidden text-gray-800 font-medium line-height-3 hover:text-gray-800 absolute" style={{ top: '3rem', right: '2rem' }}>
<i className="pi pi-times text-4xl"></i>
<Ripple />
</a>
</StyleClass>
<li>
<a onClick={() => scrollToElement(homeRef)} className="p-ripple flex m-0 md:ml-5 md:px-0 px-3 py-3 text-gray-800 font-medium line-height-3 hover:text-gray-800 cursor-pointer">
<span>Accueil</span>
<Ripple />
</a>
</li>
<li>
<a onClick={() => scrollToElement(meetRef)} className="p-ripple flex m-0 md:ml-5 md:px-0 px-3 py-3 text-gray-800 font-medium line-height-3 hover:text-gray-800 cursor-pointer">
<span>Découvrir</span>
<Ripple />
</a>
</li>
<li>
<a onClick={() => scrollToElement(featuresRef)} className="p-ripple flex m-0 md:ml-5 md:px-0 px-3 py-3 text-gray-800 font-medium line-height-3 hover:text-gray-800 cursor-pointer">
<span>Fonctionnalités</span>
<Ripple />
</a>
</li>
<li>
<a onClick={() => scrollToElement(pricingRef)} className="p-ripple flex m-0 md:ml-5 md:px-0 px-3 py-3 text-gray-800 font-medium line-height-3 hover:text-gray-800 cursor-pointer">
<span>Tarifs</span>
<Ripple />
</a>
</li>
<li>
<a onClick={() => window.location.href = '/api/auth/login'} className="p-ripple flex m-0 md:ml-5 md:px-0 px-3 py-3 text-gray-800 font-medium line-height-3 hover:text-gray-800 cursor-pointer">
<span>Connexion</span>
<Ripple />
</a>
</li>
</ul>
</div>
<div className="header-right-elements flex align-items-center">
<a onClick={() => {
const keycloakUrl = process.env.NEXT_PUBLIC_KEYCLOAK_URL || 'https://security.lions.dev';
const realm = process.env.NEXT_PUBLIC_KEYCLOAK_REALM || 'btpxpress';
const clientId = process.env.NEXT_PUBLIC_KEYCLOAK_CLIENT_ID || 'btpxpress-frontend';
const redirectUri = encodeURIComponent(window.location.origin + '/dashboard');
window.location.href = `${keycloakUrl}/realms/${realm}/protocol/openid_connect/registrations?client_id=${clientId}&response_type=code&redirect_uri=${redirectUri}`;
}} className="p-button p-button-outlined p-button-secondary p-button-text p-button p-component font-medium border-round text-white bg-orange-500 border-orange-500 cursor-pointer mr-3" style={{ padding: '0.714rem 1.5rem' }}>
<span aria-hidden="true" className="p-button-label">
Démarrer maintenant
</span>
</a>
<a href="/pages/contact">
<Button className="contact-button mr-3 p-button-outlined p-button-secondary p-button-text p-button p-component font-medium border-round text-gray-700" style={{ background: 'rgba(68, 72, 109, 0.05)' }}>
<span aria-hidden="true" className="p-button-label">
Contact
</span>
</Button>
</a>
</div>
</div>
<div className="header-text" style={{ padding: '100px 60px' }}>
<div className="flex align-items-center mb-4">
<i className="pi pi-building text-orange-600 text-4xl mr-3"></i>
<span className="text-3xl font-bold text-gray-800">BTP Xpress</span>
</div>
<h1 className="mb-0 text-gray-800" style={{ fontSize: '80px', lineHeight: '95px' }}>
Construisez l&apos;avenir
</h1>
<h2 className="mt-0 font-medium text-4xl text-gray-700">avec BTP Xpress, la suite logicielle qui transforme le BTP</h2>
<p className="text-xl text-gray-600 mb-5 line-height-3" style={{ maxWidth: '650px' }}>
<strong>Fini les chantiers qui dérapent, les budgets qui explosent et les équipes désorganisées.</strong>
BTP Xpress centralise tout : de la première estimation au dernier m² livré,
pilotez vos projets avec la précision d&apos;un architecte et l&apos;efficacité d&apos;un chef de chantier expérimenté.
</p>
<div className="flex flex-wrap gap-3 mb-6">
<div className="flex align-items-center bg-white px-4 py-2 border-round shadow-2">
<i className="pi pi-check-circle text-green-600 mr-2"></i>
<span className="font-semibold text-gray-800">Gestion complète de projets</span>
</div>
<div className="flex align-items-center bg-white px-4 py-2 border-round shadow-2">
<i className="pi pi-check-circle text-green-600 mr-2"></i>
<span className="font-semibold text-gray-800">Suivi temps réel</span>
</div>
<div className="flex align-items-center bg-white px-4 py-2 border-round shadow-2">
<i className="pi pi-check-circle text-green-600 mr-2"></i>
<span className="font-semibold text-gray-800">Facturation automatisée</span>
</div>
</div>
<a onClick={() => window.location.href = '/api/auth/login'} className="p-button text-white bg-orange-500 border-orange-500 font-bold border-round cursor-pointer mr-3 shadow-3" style={{ padding: '1.2rem 2.5rem', fontSize: '1.2rem' }}>
<i className="pi pi-play mr-2"></i>
Démarrer maintenant
</a>
<a href="#features" className="p-button p-button-outlined text-orange-600 border-orange-300 font-bold border-round cursor-pointer" style={{ padding: '1.2rem 2.5rem', fontSize: '1.2rem' }}>
<i className="pi pi-eye mr-2"></i>
Voir les fonctionnalités
</a>
</div>
<div ref={featuresRef} className="header-features" style={{ padding: '100px 60px' }}>
<div className="text-center mb-6">
<h2 className="text-4xl font-bold text-gray-800 mb-4">Spécialisé pour tous les métiers du BTP</h2>
<p className="text-xl text-gray-600">Une solution adaptée à chaque corps de métier</p>
</div>
<div className="grid">
<div className="col-12 md:col-6 lg:col-3 mb-4">
<div className="bg-white p-6 border-round shadow-2 text-center h-full">
<i className="pi pi-home text-4xl mb-3 block"></i>
<span className="title mb-3 block text-2xl font-semibold">Gros Œuvre &amp; Structure</span>
<span className="content">Béton, maçonnerie, charpente : gérez vos approvisionnements, planifiez vos coulages, suivez vos cadences et optimisez vos rotations d&apos;équipes.</span>
</div>
</div>
<div className="col-12 md:col-6 lg:col-3 mb-4">
<div className="bg-white p-6 border-round shadow-2 text-center h-full">
<i className="pi pi-wrench text-4xl mb-3 block"></i>
<span className="title mb-3 block text-2xl font-semibold">Second Œuvre &amp; Finitions</span>
<span className="content">Électricité, plomberie, peinture, carrelage : coordonnez vos interventions, gérez vos stocks et respectez les délais de livraison.</span>
</div>
</div>
<div className="col-12 md:col-6 lg:col-3 mb-4">
<div className="bg-white p-6 border-round shadow-2 text-center h-full">
<i className="pi pi-car text-4xl mb-3 block"></i>
<span className="title mb-3 block text-2xl font-semibold">Travaux Publics &amp; VRD</span>
<span className="content">Terrassement, voirie, réseaux : planifiez vos chantiers, gérez votre matériel et optimisez vos déplacements d&apos;équipes.</span>
</div>
</div>
<div className="col-12 md:col-6 lg:col-3 mb-4">
<div className="bg-white p-6 border-round shadow-2 text-center h-full">
<i className="pi pi-briefcase text-4xl mb-3 block"></i>
<span className="title mb-3 block text-2xl font-semibold">Maîtrise d&apos;Œuvre &amp; AMO</span>
<span className="content">Pilotage de projets, coordination, suivi budgétaire : centralisez tous vos dossiers et collaborez efficacement avec tous les intervenants.</span>
</div>
</div>
</div>
</div>
</div>
<div ref={meetRef} id="meet-btpxpress" className="flex justify-content-center w-full relative text-center py-8" style={{ minHeight: '400px', background: 'linear-gradient(135deg, #f97316 0%, #fb923c 30%, #fed7aa 100%)', boxShadow: '0 10px 25px rgba(249, 115, 22, 0.15)', zIndex: 100, position: 'relative' }}>
<div className="flex flex-column align-items-center justify-content-center px-6">
<h2 className="text-4xl font-bold text-gray-800 mb-4">
BTP Xpress en action
</h2>
<p className="text-xl text-gray-700 mb-6 line-height-3" style={{ maxWidth: '600px' }}>
Découvrez comment nos clients transforment leur activité BTP avec des outils pensés pour leur réussite
</p>
<div className="grid w-full" style={{ maxWidth: '900px' }}>
<div className="col-12 md:col-4 text-center mb-4">
<div className="bg-white border-round p-4 shadow-2" style={{ border: '1px solid #e5e7eb' }}>
<i className="pi pi-clock text-orange-600 text-4xl mb-3"></i>
<div className="text-3xl font-bold text-green-600 mb-2">-50%</div>
<div className="text-lg font-semibold text-gray-800">Temps administratif</div>
<div className="text-sm text-gray-600">Automatisation des tâches répétitives</div>
</div>
</div>
<div className="col-12 md:col-4 text-center mb-4">
<div className="bg-white border-round p-4 shadow-2" style={{ border: '1px solid #e5e7eb' }}>
<i className="pi pi-chart-bar text-green-600 text-4xl mb-3"></i>
<div className="text-3xl font-bold text-green-600 mb-2">+35%</div>
<div className="text-lg font-semibold text-gray-800">Rentabilité</div>
<div className="text-sm text-gray-600">Optimisation des coûts et marges</div>
</div>
</div>
<div className="col-12 md:col-4 text-center mb-4">
<div className="bg-white border-round p-4 shadow-2" style={{ border: '1px solid #e5e7eb' }}>
<i className="pi pi-users text-blue-600 text-4xl mb-3"></i>
<div className="text-3xl font-bold text-blue-600 mb-2">98%</div>
<div className="text-lg font-semibold text-gray-800">Satisfaction client</div>
<div className="text-sm text-gray-600">Respect des délais et qualité</div>
</div>
</div>
</div>
</div>
</div>
<div className="w-full py-6" style={{ background: 'linear-gradient(180deg, #ffffff 0%, #f9fafb 50%, #f3f4f6 100%)' }}>
<div id="features" className="px-4 lg:px-8 features">
<h2 className="font-medium text-3xl text-center text-gray-800 mb-6">La différence BTP Xpress : des résultats concrets</h2>
</div>
</div>
</div>
);
};
export default LandingPage;

View File

@@ -2,6 +2,7 @@
import { LayoutProvider } from '../layout/context/layoutcontext';
import { PrimeReactProvider } from 'primereact/api';
import { KeycloakProvider } from '../contexts/KeycloakContext';
import { AuthProvider } from '../contexts/AuthContext';
import { DevAuthProvider } from './auth/DevAuthProvider';
import { useServerStatusInit } from '../hooks/useServerStatusInit';
@@ -12,11 +13,13 @@ export function ClientProviders({ children }: { children: React.ReactNode }) {
return (
<PrimeReactProvider>
<DevAuthProvider>
<AuthProvider>
<LayoutProvider>{children}</LayoutProvider>
</AuthProvider>
</DevAuthProvider>
<KeycloakProvider>
<DevAuthProvider>
<AuthProvider>
<LayoutProvider>{children}</LayoutProvider>
</AuthProvider>
</DevAuthProvider>
</KeycloakProvider>
</PrimeReactProvider>
);
}

View File

@@ -2,6 +2,7 @@
import React from 'react';
import { useAuth } from '../contexts/AuthContext';
import { useKeycloak } from '../contexts/KeycloakContext';
import LoadingSpinner from './ui/LoadingSpinner';
import { useRouter, useSearchParams, usePathname } from 'next/navigation';
import { useEffect, useRef, useMemo } from 'react';
@@ -18,6 +19,7 @@ const ProtectedLayout: React.FC<ProtectedLayoutProps> = ({
requiredPermissions = []
}) => {
const { isAuthenticated, isLoading, user, hasRole, hasPermission } = useAuth();
const { keycloak } = useKeycloak();
const router = useRouter();
const searchParams = useSearchParams();
const pathname = usePathname();
@@ -26,8 +28,8 @@ const ProtectedLayout: React.FC<ProtectedLayoutProps> = ({
// Vérifier s'il y a un code d'autorisation dans l'URL
// Utiliser useMemo pour éviter les re-rendus inutiles
const hasAuthCode = useMemo(() => {
return searchParams.get('code') !== null && pathname === '/dashboard';
}, [searchParams, pathname]);
return searchParams.get('code') !== null;
}, [searchParams]);
useEffect(() => {
console.log('🔍 ProtectedLayout useEffect:', {
@@ -48,11 +50,17 @@ const ProtectedLayout: React.FC<ProtectedLayoutProps> = ({
// Marquer comme redirigé pour éviter les boucles
redirectedRef.current = true;
// Rediriger vers la page de connexion avec l'URL de retour
const searchParamsStr = searchParams.toString();
const currentPath = pathname + (searchParamsStr ? `?${searchParamsStr}` : '');
console.log('🔒 ProtectedLayout: Redirection vers /api/auth/login');
window.location.href = `/api/auth/login?redirect=${encodeURIComponent(currentPath)}`;
// Rediriger vers Keycloak avec l'URL de retour
console.log('🔒 ProtectedLayout: Redirection vers Keycloak');
if (keycloak) {
const searchParamsStr = searchParams.toString();
const currentPath = pathname + (searchParamsStr ? `?${searchParamsStr}` : '');
const redirectUri = currentPath && currentPath !== '/'
? `${window.location.origin}${currentPath}`
: `${window.location.origin}/dashboard`;
keycloak.login({ redirectUri });
}
} else if (hasAuthCode) {
console.log('🔓 ProtectedLayout: Code d\'autorisation détecté, pas de redirection');
} else if (isAuthenticated) {
@@ -60,7 +68,7 @@ const ProtectedLayout: React.FC<ProtectedLayoutProps> = ({
} else if (isLoading) {
console.log('⏳ ProtectedLayout: Chargement en cours, pas de redirection');
}
}, [isAuthenticated, isLoading, hasAuthCode, pathname]);
}, [isAuthenticated, isLoading, hasAuthCode, pathname, keycloak]);
useEffect(() => {
if (isAuthenticated && user) {

View File

@@ -12,6 +12,7 @@ import { StyleClass } from 'primereact/styleclass';
import { useRouter } from 'next/navigation';
import { useDevAuth } from '../auth/DevAuthProvider';
import Link from 'next/link';
import { redirectToLogin } from '@/lib/auth';
interface AppLayoutProps {
children: React.ReactNode;
@@ -114,7 +115,7 @@ export const AppLayout: React.FC<AppLayoutProps> = ({ children }) => {
icon: 'pi pi-sign-out',
command: () => {
logout();
window.location.href = '/api/auth/login';
redirectToLogin();
}
}
];

View File

@@ -1,7 +1,8 @@
'use client';
import React, { createContext, useContext, useEffect, useState, useCallback, ReactNode } from 'react';
import { initKeycloak, keycloakInitOptions, RoleUtils, BTP_ROLES, KEYCLOAK_TIMEOUTS, KEYCLOAK_REDIRECTS } from '@/config/keycloak';
import { useKeycloak } from './KeycloakContext';
import { RoleUtils, BTP_ROLES } from '@/config/keycloak';
import { useRouter } from 'next/navigation';
// Types pour l'authentification
@@ -61,7 +62,10 @@ interface AuthProviderProps {
// Provider d'authentification
export const AuthProvider: React.FC<AuthProviderProps> = ({ children }) => {
const router = useRouter();
// Utiliser le contexte Keycloak
const { keycloak, authenticated, loading, token, login: keycloakLogin, logout: keycloakLogout, updateToken: keycloakUpdateToken } = useKeycloak();
// État de l'authentification
const [authState, setAuthState] = useState<AuthState>({
isAuthenticated: false,
@@ -178,11 +182,10 @@ export const AuthProvider: React.FC<AuthProviderProps> = ({ children }) => {
}
}, [fetchUserInfo, extractUserInfo]);
// Fonction de connexion
// Fonction de connexion - utilise Keycloak JS SDK
const login = useCallback(async (): Promise<void> => {
try {
// Redirection directe vers l'API d'authentification
window.location.href = '/api/auth/login';
keycloakLogin();
} catch (error) {
console.error('Erreur lors de la connexion:', error);
setAuthState(prev => ({
@@ -191,21 +194,12 @@ export const AuthProvider: React.FC<AuthProviderProps> = ({ children }) => {
isLoading: false,
}));
}
}, []);
}, [keycloakLogin]);
// Fonction de déconnexion
// Fonction de déconnexion - utilise Keycloak JS SDK
const logout = useCallback(async (): Promise<void> => {
try {
// Nettoyer les tokens locaux
localStorage.removeItem('accessToken');
localStorage.removeItem('refreshToken');
localStorage.removeItem('idToken');
// Supprimer le cookie
document.cookie = 'keycloak-token=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT';
// Redirection directe vers l'API de déconnexion
window.location.href = '/api/auth/logout';
keycloakLogout();
} catch (error) {
console.error('Erreur lors de la déconnexion:', error);
// Forcer la déconnexion locale même en cas d'erreur
@@ -219,45 +213,32 @@ export const AuthProvider: React.FC<AuthProviderProps> = ({ children }) => {
});
router.push('/');
}
}, [router]);
}, [keycloakLogout, router]);
// Fonction pour rafraîchir l'authentification
// Fonction pour rafraîchir l'authentification - utilise Keycloak SDK
const refreshAuth = useCallback(async (): Promise<void> => {
try {
// Vérifier les tokens stockés
const accessToken = localStorage.getItem('accessToken');
const refreshToken = localStorage.getItem('refreshToken');
if (!refreshToken) {
await logout();
return;
if (keycloak && authenticated) {
await keycloakUpdateToken();
}
// TODO: Implémenter le rafraîchissement via API si nécessaire
console.log('Rafraîchissement des tokens...');
} catch (error) {
console.error('Erreur lors du rafraîchissement du token:', error);
await logout();
}
}, [logout]);
}, [keycloak, authenticated, keycloakUpdateToken, logout]);
// Fonction pour mettre à jour le token
// Fonction pour mettre à jour le token - utilise Keycloak SDK
const updateToken = useCallback(async (minValidity: number = 30): Promise<boolean> => {
try {
// Vérifier si le token est encore valide
const accessToken = localStorage.getItem('accessToken');
if (!accessToken) {
return false;
if (keycloak && authenticated) {
return await keycloakUpdateToken();
}
// TODO: Vérifier l'expiration du token et rafraîchir si nécessaire
return true;
return false;
} catch (error) {
console.error('Erreur lors de la mise à jour du token:', error);
return false;
}
}, []);
}, [keycloak, authenticated, keycloakUpdateToken]);
// Fonctions utilitaires pour les rôles et permissions
const hasRole = useCallback((role: string): boolean => {
@@ -277,65 +258,39 @@ export const AuthProvider: React.FC<AuthProviderProps> = ({ children }) => {
return RoleUtils.isRoleHigher(authState.user.highestRole, role);
}, [authState.user]);
// Initialisation de Keycloak - Désactivée pour utiliser l'authentification manuelle
// Synchroniser l'état avec KeycloakContext
useEffect(() => {
const initializeKeycloak = async () => {
try {
// Vérifier s'il y a des tokens stockés localement
const accessToken = localStorage.getItem('accessToken');
const refreshToken = localStorage.getItem('refreshToken');
const idToken = localStorage.getItem('idToken');
const syncAuthState = async () => {
if (loading) {
setAuthState({
isAuthenticated: false,
isLoading: true,
user: null,
token: null,
refreshToken: null,
error: null,
});
return;
}
if (accessToken) {
// Stocker aussi dans un cookie pour le middleware
document.cookie = `keycloak-token=${accessToken}; path=/; max-age=3600; SameSite=Lax`;
if (authenticated && keycloak && token) {
// Essayer de récupérer les informations utilisateur depuis l'API
let user = await fetchUserInfo(token);
// Récupérer les informations utilisateur depuis l'API
try {
const user = await fetchUserInfo(accessToken);
if (user) {
setAuthState({
isAuthenticated: true,
isLoading: false,
user,
token: accessToken,
refreshToken: refreshToken,
error: null,
});
return;
}
} catch (error) {
console.warn('Impossible de récupérer les informations utilisateur depuis l\'API, utilisation des données par défaut');
}
// Fallback avec des données par défaut si l'API ne répond pas
setAuthState({
isAuthenticated: true,
isLoading: false,
user: {
id: 'dev-user-001',
username: 'admin.btpxpress',
email: 'admin@btpxpress.com',
firstName: 'Jean-Michel',
lastName: 'Martineau',
fullName: 'Jean-Michel Martineau',
roles: [BTP_ROLES.SUPER_ADMIN, BTP_ROLES.ADMIN, BTP_ROLES.DIRECTEUR],
permissions: RoleUtils.getUserPermissions([BTP_ROLES.SUPER_ADMIN]),
highestRole: BTP_ROLES.SUPER_ADMIN,
isAdmin: true,
isManager: true,
isEmployee: false,
isClient: false,
},
token: accessToken,
refreshToken: refreshToken,
error: null,
});
return;
// Si l'API ne répond pas, extraire du token JWT
if (!user) {
user = extractUserInfo(keycloak);
}
// Pas de tokens, rester non authentifié
setAuthState({
isAuthenticated: true,
isLoading: false,
user,
token: token,
refreshToken: keycloak.refreshToken || null,
error: null,
});
} else {
setAuthState({
isAuthenticated: false,
isLoading: false,
@@ -344,33 +299,13 @@ export const AuthProvider: React.FC<AuthProviderProps> = ({ children }) => {
refreshToken: null,
error: null,
});
} catch (error) {
console.error('Erreur lors de l\'initialisation de l\'authentification:', error);
setAuthState({
isAuthenticated: false,
isLoading: false,
user: null,
token: null,
refreshToken: null,
error: 'Erreur lors de l\'initialisation de l\'authentification',
});
}
};
initializeKeycloak();
}, [updateAuthState, refreshAuth, logout]);
syncAuthState();
}, [authenticated, loading, token, keycloak, fetchUserInfo, extractUserInfo]);
// Rafraîchissement automatique du token
useEffect(() => {
if (!authState.isAuthenticated) return;
const interval = setInterval(() => {
updateToken();
}, KEYCLOAK_TIMEOUTS.SESSION_CHECK_INTERVAL * 1000);
return () => clearInterval(interval);
}, [authState.isAuthenticated, updateToken]);
// Le rafraîchissement automatique du token est géré par KeycloakContext
// Valeur du contexte
const contextValue: AuthContextType = {

View File

@@ -0,0 +1,119 @@
'use client';
import React, { createContext, useContext, useState, useEffect, ReactNode } from 'react';
import Keycloak from 'keycloak-js';
import keycloak from '../lib/keycloak';
interface KeycloakContextType {
keycloak: Keycloak | null;
authenticated: boolean;
loading: boolean;
token: string | null;
login: () => void;
logout: () => void;
updateToken: () => Promise<boolean>;
}
const KeycloakContext = createContext<KeycloakContextType | undefined>(undefined);
export const useKeycloak = () => {
const context = useContext(KeycloakContext);
if (!context) {
throw new Error('useKeycloak must be used within a KeycloakProvider');
}
return context;
};
interface KeycloakProviderProps {
children: ReactNode;
}
export const KeycloakProvider: React.FC<KeycloakProviderProps> = ({ children }) => {
const [authenticated, setAuthenticated] = useState(false);
const [loading, setLoading] = useState(true);
const [token, setToken] = useState<string | null>(null);
useEffect(() => {
const initKeycloak = async () => {
try {
console.log('🔐 Initializing Keycloak...');
const authenticated = await keycloak.init({
onLoad: 'check-sso',
silentCheckSsoRedirectUri: window.location.origin + '/silent-check-sso.html',
pkceMethod: 'S256',
checkLoginIframe: false, // Désactivé pour éviter les problèmes CORS
flow: 'standard', // Force authorization_code flow (pas implicit/hybrid)
responseMode: 'query', // Force query string au lieu de fragment
});
console.log(`✅ Keycloak initialized. Authenticated: ${authenticated}`);
setAuthenticated(authenticated);
setToken(keycloak.token || null);
// Rafraîchir le token automatiquement
if (authenticated) {
setInterval(() => {
keycloak.updateToken(70).then((refreshed) => {
if (refreshed) {
console.log('🔄 Token refreshed');
setToken(keycloak.token || null);
}
}).catch(() => {
console.error('❌ Failed to refresh token');
setAuthenticated(false);
});
}, 60000); // Toutes les 60 secondes
}
} catch (error) {
console.error('❌ Keycloak initialization failed:', error);
} finally {
setLoading(false);
}
};
initKeycloak();
}, []);
const login = () => {
keycloak.login({
redirectUri: window.location.origin + '/dashboard',
});
};
const logout = () => {
keycloak.logout({
redirectUri: window.location.origin,
});
};
const updateToken = async (): Promise<boolean> => {
try {
const refreshed = await keycloak.updateToken(30);
if (refreshed) {
setToken(keycloak.token || null);
}
return refreshed;
} catch (error) {
console.error('Failed to update token', error);
return false;
}
};
const value: KeycloakContextType = {
keycloak,
authenticated,
loading,
token,
login,
logout,
updateToken,
};
return (
<KeycloakContext.Provider value={value}>
{children}
</KeycloakContext.Provider>
);
};

View File

@@ -1,16 +1,16 @@
# Configuration d'environnement pour BTPXpress Frontend
# Copiez ce fichier vers .env.local et remplissez les valeurs
# API Backend
NEXT_PUBLIC_API_URL=http://localhost:8080
NEXT_PUBLIC_API_TIMEOUT=15000
# Keycloak
NEXT_PUBLIC_KEYCLOAK_URL=https://security.lions.dev
NEXT_PUBLIC_KEYCLOAK_REALM=btpxpress
NEXT_PUBLIC_KEYCLOAK_CLIENT_ID=btpxpress-frontend
# Application
NEXT_PUBLIC_APP_NAME=BTP Xpress
NEXT_PUBLIC_APP_VERSION=1.0.0
NEXT_PUBLIC_APP_ENV=development
# Configuration d'environnement pour BTPXpress Frontend
# Copiez ce fichier vers .env.local et remplissez les valeurs
# API Backend
NEXT_PUBLIC_API_URL=http://localhost:8080
NEXT_PUBLIC_API_TIMEOUT=15000
# Keycloak
NEXT_PUBLIC_KEYCLOAK_URL=https://security.lions.dev
NEXT_PUBLIC_KEYCLOAK_REALM=btpxpress
NEXT_PUBLIC_KEYCLOAK_CLIENT_ID=btpxpress-frontend
# Application
NEXT_PUBLIC_APP_NAME=BTP Xpress
NEXT_PUBLIC_APP_VERSION=1.0.0
NEXT_PUBLIC_APP_ENV=development

78
lib/auth.ts Normal file
View File

@@ -0,0 +1,78 @@
/**
* Utilitaires d'authentification centralisés
* Utilise le SDK Keycloak JS pour toutes les opérations d'authentification
*
* IMPORTANT: Utilise un import conditionnel pour éviter les erreurs SSR
*/
/**
* Récupère l'instance Keycloak de manière sécurisée (client-side uniquement)
*/
const getKeycloak = async () => {
if (typeof window === 'undefined') return null;
const { default: keycloak } = await import('./keycloak');
return keycloak;
};
/**
* Redirige vers la page de connexion Keycloak
*/
export const redirectToLogin = async (returnUrl?: string) => {
if (typeof window === 'undefined') return;
const keycloak = await getKeycloak();
if (keycloak) {
const redirectUri = returnUrl
? `${window.location.origin}${returnUrl}`
: `${window.location.origin}/dashboard`;
keycloak.login({ redirectUri });
} else {
console.error('❌ Keycloak non initialisé');
}
};
/**
* Redirige vers la page de déconnexion Keycloak
*/
export const redirectToLogout = async () => {
if (typeof window === 'undefined') return;
const keycloak = await getKeycloak();
if (keycloak) {
keycloak.logout({ redirectUri: window.location.origin });
} else {
console.error('❌ Keycloak non initialisé');
}
};
/**
* Vérifie si l'utilisateur est authentifié
*/
export const isAuthenticated = async (): Promise<boolean> => {
const keycloak = await getKeycloak();
return keycloak?.authenticated ?? false;
};
/**
* Récupère le token d'accès actuel
*/
export const getAccessToken = async (): Promise<string | undefined> => {
const keycloak = await getKeycloak();
return keycloak?.token;
};
/**
* Rafraîchit le token si nécessaire
*/
export const refreshToken = async (minValidity: number = 30): Promise<boolean> => {
const keycloak = await getKeycloak();
if (!keycloak) return false;
try {
return await keycloak.updateToken(minValidity);
} catch (error) {
console.error('❌ Erreur lors du rafraîchissement du token:', error);
return false;
}
};

14
lib/keycloak.ts Normal file
View File

@@ -0,0 +1,14 @@
import Keycloak from 'keycloak-js';
// Configuration Keycloak
const keycloakConfig = {
url: process.env.NEXT_PUBLIC_KEYCLOAK_URL || 'https://security.lions.dev',
realm: process.env.NEXT_PUBLIC_KEYCLOAK_REALM || 'btpxpress',
clientId: process.env.NEXT_PUBLIC_KEYCLOAK_CLIENT_ID || 'btpxpress-frontend',
};
// Créer une instance Keycloak uniquement côté client
// Pour éviter les erreurs SSR (document is not defined)
const keycloak = typeof window !== 'undefined' ? new Keycloak(keycloakConfig) : null;
export default keycloak as Keycloak;

View File

@@ -1,97 +1,17 @@
/**
* Middleware Next.js pour l'authentification OAuth avec Keycloak
* Middleware Next.js simplifié pour Frontend-Centric auth
*
* Ce middleware protège les routes privées en vérifiant la présence
* d'un access_token dans les cookies HttpOnly.
* Avec Keycloak JS SDK, l'authentification est gérée côté client par KeycloakContext.
* Ce middleware laisse passer toutes les requêtes - la protection des routes est
* gérée par ProtectedLayout et AuthContext côté client.
*/
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
// Routes publiques accessibles sans authentification
const PUBLIC_ROUTES = [
'/',
'/auth/login',
'/auth/callback',
'/api/auth/login',
'/api/auth/callback',
'/api/auth/token',
'/api/health',
];
// Routes API publiques (patterns)
const PUBLIC_API_PATTERNS = [
/^\/api\/auth\/.*/,
/^\/api\/health/,
];
// Vérifie si une route est publique
function isPublicRoute(pathname: string): boolean {
// Vérifier les routes exactes
if (PUBLIC_ROUTES.includes(pathname)) {
return true;
}
// Vérifier les patterns
return PUBLIC_API_PATTERNS.some(pattern => pattern.test(pathname));
}
export function middleware(request: NextRequest) {
const { pathname } = request.nextUrl;
console.log('🔒 Middleware - Checking:', pathname);
// Laisser passer les routes publiques
if (isPublicRoute(pathname)) {
console.log('✅ Middleware - Public route, allowing');
return NextResponse.next();
}
// Laisser passer les fichiers statiques
if (
pathname.startsWith('/_next') ||
pathname.startsWith('/static') ||
pathname.includes('.')
) {
return NextResponse.next();
}
// Vérifier la présence du token d'authentification
const accessToken = request.cookies.get('access_token');
const tokenExpiresAt = request.cookies.get('token_expires_at');
if (!accessToken) {
console.log('❌ Middleware - No access token, redirecting to login');
// Rediriger vers la page de login avec l'URL de retour
const loginUrl = new URL('/auth/login', request.url);
loginUrl.searchParams.set('returnUrl', pathname);
return NextResponse.redirect(loginUrl);
}
// Vérifier si le token est expiré
if (tokenExpiresAt) {
const expiresAt = parseInt(tokenExpiresAt.value, 10);
const now = Date.now();
if (now >= expiresAt) {
console.log('❌ Middleware - Token expired, redirecting to login');
// Supprimer les cookies expirés
const response = NextResponse.redirect(new URL('/auth/login', request.url));
response.cookies.delete('access_token');
response.cookies.delete('refresh_token');
response.cookies.delete('id_token');
response.cookies.delete('token_expires_at');
return response;
}
}
console.log('✅ Middleware - Authenticated, allowing');
// L'utilisateur est authentifié, laisser passer
// Laisser passer toutes les requêtes
// L'authentification est gérée côté client par Keycloak JS SDK
return NextResponse.next();
}

View File

@@ -1,124 +1,124 @@
/** @type {import('next').NextConfig} */
const nextConfig = {
reactStrictMode: false, // Disabled to prevent double OAuth code usage in dev
output: 'standalone',
// Optimisations pour la production
compress: true,
poweredByHeader: false,
generateEtags: false,
// Désactiver la génération statique pour éviter les erreurs useSearchParams
skipTrailingSlashRedirect: true,
// Configuration des images optimisées
images: {
domains: ['btpxpress.lions.dev', 'api.lions.dev', 'security.lions.dev'],
formats: ['image/webp', 'image/avif'],
minimumCacheTTL: 60,
dangerouslyAllowSVG: true,
contentSecurityPolicy: "default-src 'self'; script-src 'none'; sandbox;",
},
// Optimisations de performance
experimental: {
optimizeCss: true,
optimizePackageImports: ['primereact', 'primeicons', 'chart.js', 'axios'],
},
// Packages externes pour les composants serveur
serverExternalPackages: ['@prisma/client'],
// Configuration Turbopack (stable)
turbopack: {
rules: {
'*.svg': {
loaders: ['@svgr/webpack'],
as: '*.js',
},
},
},
// Configuration du bundler optimisée
webpack: (config, { dev, isServer }) => {
// Optimisations pour la production
if (!dev && !isServer) {
config.optimization.splitChunks = {
chunks: 'all',
cacheGroups: {
vendor: {
test: /[\\/]node_modules[\\/]/,
name: 'vendors',
chunks: 'all',
},
primereact: {
test: /[\\/]node_modules[\\/]primereact[\\/]/,
name: 'primereact',
chunks: 'all',
},
charts: {
test: /[\\/]node_modules[\\/](chart\.js|react-chartjs-2)[\\/]/,
name: 'charts',
chunks: 'all',
},
},
};
}
// Alias pour optimiser les imports
config.resolve.alias = {
...config.resolve.alias,
'@': require('path').resolve(__dirname),
'@components': require('path').resolve(__dirname, 'components'),
'@services': require('path').resolve(__dirname, 'services'),
'@types': require('path').resolve(__dirname, 'types'),
'@utils': require('path').resolve(__dirname, 'utils'),
};
return config;
},
// Headers de sécurité
async headers() {
return [
{
source: '/(.*)',
headers: [
{
key: 'X-Frame-Options',
value: 'DENY'
},
{
key: 'X-Content-Type-Options',
value: 'nosniff'
},
{
key: 'Referrer-Policy',
value: 'strict-origin-when-cross-origin'
}
]
}
];
},
async redirects() {
return [
{
source: '/apps/mail',
destination: '/apps/mail/inbox',
permanent: true
}
];
},
// Configuration des variables d'environnement
env: {
NEXT_PUBLIC_API_URL: process.env.NEXT_PUBLIC_API_URL,
NEXT_PUBLIC_KEYCLOAK_URL: process.env.NEXT_PUBLIC_KEYCLOAK_URL,
NEXT_PUBLIC_KEYCLOAK_REALM: process.env.NEXT_PUBLIC_KEYCLOAK_REALM,
NEXT_PUBLIC_KEYCLOAK_CLIENT_ID: process.env.NEXT_PUBLIC_KEYCLOAK_CLIENT_ID,
NEXT_PUBLIC_APP_ENV: process.env.NEXT_PUBLIC_APP_ENV,
}
};
module.exports = nextConfig;
/** @type {import('next').NextConfig} */
const nextConfig = {
reactStrictMode: false, // Disabled to prevent double OAuth code usage in dev
output: 'standalone',
// Optimisations pour la production
compress: true,
poweredByHeader: false,
generateEtags: false,
// Désactiver la génération statique pour éviter les erreurs useSearchParams
skipTrailingSlashRedirect: true,
// Configuration des images optimisées
images: {
domains: ['btpxpress.lions.dev', 'api.lions.dev', 'security.lions.dev'],
formats: ['image/webp', 'image/avif'],
minimumCacheTTL: 60,
dangerouslyAllowSVG: true,
contentSecurityPolicy: "default-src 'self'; script-src 'none'; sandbox;",
},
// Optimisations de performance
experimental: {
optimizeCss: true,
optimizePackageImports: ['primereact', 'primeicons', 'chart.js', 'axios'],
},
// Packages externes pour les composants serveur
serverExternalPackages: ['@prisma/client'],
// Configuration Turbopack (stable)
turbopack: {
rules: {
'*.svg': {
loaders: ['@svgr/webpack'],
as: '*.js',
},
},
},
// Configuration du bundler optimisée
webpack: (config, { dev, isServer }) => {
// Optimisations pour la production
if (!dev && !isServer) {
config.optimization.splitChunks = {
chunks: 'all',
cacheGroups: {
vendor: {
test: /[\\/]node_modules[\\/]/,
name: 'vendors',
chunks: 'all',
},
primereact: {
test: /[\\/]node_modules[\\/]primereact[\\/]/,
name: 'primereact',
chunks: 'all',
},
charts: {
test: /[\\/]node_modules[\\/](chart\.js|react-chartjs-2)[\\/]/,
name: 'charts',
chunks: 'all',
},
},
};
}
// Alias pour optimiser les imports
config.resolve.alias = {
...config.resolve.alias,
'@': require('path').resolve(__dirname),
'@components': require('path').resolve(__dirname, 'components'),
'@services': require('path').resolve(__dirname, 'services'),
'@types': require('path').resolve(__dirname, 'types'),
'@utils': require('path').resolve(__dirname, 'utils'),
};
return config;
},
// Headers de sécurité
async headers() {
return [
{
source: '/(.*)',
headers: [
{
key: 'X-Frame-Options',
value: 'DENY'
},
{
key: 'X-Content-Type-Options',
value: 'nosniff'
},
{
key: 'Referrer-Policy',
value: 'strict-origin-when-cross-origin'
}
]
}
];
},
async redirects() {
return [
{
source: '/apps/mail',
destination: '/apps/mail/inbox',
permanent: true
}
];
},
// Configuration des variables d'environnement
env: {
NEXT_PUBLIC_API_URL: process.env.NEXT_PUBLIC_API_URL,
NEXT_PUBLIC_KEYCLOAK_URL: process.env.NEXT_PUBLIC_KEYCLOAK_URL,
NEXT_PUBLIC_KEYCLOAK_REALM: process.env.NEXT_PUBLIC_KEYCLOAK_REALM,
NEXT_PUBLIC_KEYCLOAK_CLIENT_ID: process.env.NEXT_PUBLIC_KEYCLOAK_CLIENT_ID,
NEXT_PUBLIC_APP_ENV: process.env.NEXT_PUBLIC_APP_ENV,
}
};
module.exports = nextConfig;

View File

@@ -0,0 +1,11 @@
<!DOCTYPE html>
<html>
<head>
<title>Silent SSO Check</title>
</head>
<body>
<script>
parent.postMessage(location.href, location.origin);
</script>
</body>
</html>

View File

@@ -1,6 +1,6 @@
import axios from 'axios';
import { API_CONFIG } from '../config/api';
import { keycloak, KEYCLOAK_TIMEOUTS } from '../config/keycloak';
import keycloak from '../lib/keycloak';
class ApiService {
private api = axios.create({
@@ -16,8 +16,8 @@ class ApiService {
// Vérifier si Keycloak est initialisé et l'utilisateur authentifié
if (keycloak && keycloak.authenticated) {
try {
// Rafraîchir le token si nécessaire
await keycloak.updateToken(KEYCLOAK_TIMEOUTS.TOKEN_REFRESH_BEFORE_EXPIRY);
// Rafraîchir le token si nécessaire (70 secondes avant expiration)
await keycloak.updateToken(70);
// Ajouter le token Bearer à l'en-tête Authorization
if (keycloak.token) {
@@ -29,22 +29,6 @@ class ApiService {
keycloak.login();
throw error;
}
} else {
// Fallback vers l'ancien système pour la rétrocompatibilité
let token = null;
try {
const authTokenItem = sessionStorage.getItem('auth_token') || localStorage.getItem('auth_token');
if (authTokenItem) {
const parsed = JSON.parse(authTokenItem);
token = parsed.value;
}
} catch (e) {
token = localStorage.getItem('token');
}
if (token) {
config.headers['Authorization'] = `Bearer ${token}`;
}
}
return config;
},
@@ -73,12 +57,10 @@ class ApiService {
const hasAuthCode = currentUrl.includes('code=') && currentUrl.includes('/dashboard');
if (!hasAuthCode) {
// Fallback vers l'ancien système
localStorage.removeItem('token');
localStorage.removeItem('user');
localStorage.removeItem('auth_token');
sessionStorage.removeItem('auth_token');
window.location.href = '/api/auth/login';
console.log('❌ Non authentifié, redirection vers Keycloak...');
if (keycloak) {
keycloak.login();
}
} else {
console.log('🔄 ApiService: Erreur 401 ignorée car authentification en cours...');
}

View File

@@ -4,7 +4,7 @@
import axios, { AxiosInstance, AxiosResponse } from 'axios';
import { API_CONFIG } from '../config/api';
import { keycloak, KEYCLOAK_TIMEOUTS } from '../config/keycloak';
import keycloak from '../lib/keycloak';
import { CacheService, CacheKeys } from './cacheService';
import {
Client,
@@ -39,19 +39,28 @@ class ApiService {
headers: API_CONFIG.headers,
});
// Interceptor pour les requêtes - ajouter le token d'authentification
// Interceptor pour les requêtes
this.api.interceptors.request.use(
async (config) => {
// Utiliser le token stocké dans localStorage (nouveau système)
if (typeof window !== 'undefined') {
const accessToken = localStorage.getItem('accessToken');
console.log('🔐 API Request:', config.url);
if (accessToken) {
config.headers['Authorization'] = `Bearer ${accessToken}`;
console.log('🔐 API Request avec token:', config.url);
} else {
console.log('⚠️ API Request sans token:', config.url);
// Vérifier si Keycloak est initialisé et l'utilisateur authentifié
if (keycloak && keycloak.authenticated && keycloak.token) {
try {
// Rafraîchir le token si nécessaire (70 secondes avant expiration)
await keycloak.updateToken(70);
// Ajouter le token Bearer à l'en-tête Authorization
config.headers['Authorization'] = `Bearer ${keycloak.token}`;
console.log('✅ Token ajouté à la requête');
} catch (error) {
console.error('❌ Erreur lors de la mise à jour du token Keycloak:', error);
// En cas d'erreur, rediriger vers la page de connexion
keycloak.login();
throw error;
}
} else {
console.warn('⚠️ Keycloak non authentifié, requête sans token');
}
// Ajouter des en-têtes par défaut
@@ -100,24 +109,35 @@ class ApiService {
this.notifyServerStatus(true);
if (error.response?.status === 401) {
// Gestion des erreurs d'authentification
// Gestion des erreurs d'authentification (token expiré ou absent)
if (typeof window !== 'undefined') {
const currentUrl = window.location.href;
const hasAuthCode = currentUrl.includes('code=') && currentUrl.includes('/dashboard');
if (!hasAuthCode) {
console.log('🔄 Token expiré, redirection vers la connexion...');
// Sauvegarder la page actuelle pour y revenir après reconnexion
const currentPath = window.location.pathname + window.location.search;
localStorage.setItem('returnUrl', currentPath);
console.log('🔄 Token expiré ou absent, redirection vers Keycloak...');
// Nettoyer les tokens expirés
localStorage.removeItem('accessToken');
localStorage.removeItem('refreshToken');
localStorage.removeItem('idToken');
// Rediriger vers la page de connexion
window.location.href = '/api/auth/login';
// Essayer de rafraîchir le token Keycloak
if (keycloak && keycloak.authenticated) {
try {
await keycloak.updateToken(-1); // Force refresh
// Retry the original request
return this.api.request(error.config);
} catch (refreshError) {
console.error('❌ Impossible de rafraîchir le token, reconnexion requise');
// Sauvegarder la page actuelle pour y revenir après reconnexion
const currentPath = window.location.pathname + window.location.search;
sessionStorage.setItem('returnUrl', currentPath);
// Rediriger vers Keycloak pour authentification
keycloak.login();
}
} else {
// Pas authentifié, rediriger vers Keycloak
console.log('❌ Non authentifié, redirection vers Keycloak...');
if (keycloak) {
keycloak.login();
}
}
} else {
console.log('🔄 API Service: Erreur 401 ignorée car authentification en cours...');
}

View File

@@ -1,41 +1,41 @@
{
"compilerOptions": {
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"allowJs": true,
"skipLibCheck": true,
"strict": false,
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"incremental": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"plugins": [
{
"name": "next"
}
],
"paths": {
"@/*": [
"./*"
]
},
"target": "ES2017"
},
"include": [
"next-env.d.ts",
".next/types/**/*.ts",
"**/*.ts",
"**/*.tsx"
],
"exclude": [
"node_modules"
]
}
{
"compilerOptions": {
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"allowJs": true,
"skipLibCheck": true,
"strict": false,
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"incremental": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"plugins": [
{
"name": "next"
}
],
"paths": {
"@/*": [
"./*"
]
},
"target": "ES2017"
},
"include": [
"next-env.d.ts",
".next/types/**/*.ts",
"**/*.ts",
"**/*.tsx"
],
"exclude": [
"node_modules"
]
}