feat: refactor TFS integration structure and add scheduler functionality

- Updated TFS service imports to a new directory structure for better organization.
- Introduced new API routes for TFS scheduler configuration and status retrieval.
- Implemented TFS scheduler logic to manage automatic synchronization based on user preferences.
- Added components for TFS configuration and scheduler management, enhancing user interaction with TFS settings.
- Removed deprecated TfsSync component, consolidating functionality into the new structure.
This commit is contained in:
Julien Froidefond
2025-10-03 08:15:12 +02:00
parent f4c6b1181f
commit a1f82a4c9b
17 changed files with 975 additions and 223 deletions

View File

@@ -2,7 +2,7 @@
import { userPreferencesService } from '@/services/core/user-preferences';
import { revalidatePath } from 'next/cache';
import { tfsService, TfsConfig } from '@/services/integrations/tfs';
import { tfsService, TfsConfig } from '@/services/integrations/tfs/tfs';
import { getServerSession } from 'next-auth';
import { authOptions } from '@/lib/auth';

View File

@@ -1,5 +1,5 @@
import { NextResponse } from 'next/server';
import { tfsService } from '@/services/integrations/tfs';
import { tfsService } from '@/services/integrations/tfs/tfs';
/**
* Supprime toutes les tâches TFS de la base de données locale

View File

@@ -0,0 +1,85 @@
import { NextRequest, NextResponse } from 'next/server';
import { getServerSession } from 'next-auth';
import { authOptions } from '@/lib/auth';
import { userPreferencesService } from '@/services/core/user-preferences';
import { tfsScheduler } from '@/services/integrations/tfs/scheduler';
/**
* GET /api/tfs/scheduler-config
* Récupère la configuration du scheduler TFS
*/
export async function GET() {
try {
const session = await getServerSession(authOptions);
if (!session?.user?.id) {
return NextResponse.json({ success: false, error: 'Non authentifié' }, { status: 401 });
}
const schedulerConfig = await userPreferencesService.getTfsSchedulerConfig(session.user.id);
return NextResponse.json({
success: true,
data: schedulerConfig
});
} catch (error) {
console.error('Erreur récupération config scheduler TFS:', error);
return NextResponse.json({
success: false,
error: error instanceof Error ? error.message : 'Erreur lors de la récupération'
}, { status: 500 });
}
}
/**
* POST /api/tfs/scheduler-config
* Sauvegarde la configuration du scheduler TFS
*/
export async function POST(request: NextRequest) {
try {
const session = await getServerSession(authOptions);
if (!session?.user?.id) {
return NextResponse.json({ success: false, error: 'Non authentifié' }, { status: 401 });
}
const body = await request.json();
const { tfsAutoSync, tfsSyncInterval } = body;
if (typeof tfsAutoSync !== 'boolean') {
return NextResponse.json({
success: false,
error: 'tfsAutoSync doit être un booléen'
}, { status: 400 });
}
if (!['hourly', 'daily', 'weekly'].includes(tfsSyncInterval)) {
return NextResponse.json({
success: false,
error: 'tfsSyncInterval doit être hourly, daily ou weekly'
}, { status: 400 });
}
await userPreferencesService.saveTfsSchedulerConfig(
session.user.id,
tfsAutoSync,
tfsSyncInterval
);
// Redémarrer le scheduler avec la nouvelle configuration
await tfsScheduler.restart(session.user.id);
// Récupérer le statut mis à jour
const status = await tfsScheduler.getStatus(session.user.id);
return NextResponse.json({
success: true,
message: 'Configuration scheduler TFS mise à jour',
data: status
});
} catch (error) {
console.error('Erreur sauvegarde config scheduler TFS:', error);
return NextResponse.json({
success: false,
error: error instanceof Error ? error.message : 'Erreur lors de la sauvegarde'
}, { status: 500 });
}
}

View File

@@ -0,0 +1,30 @@
import { NextResponse } from 'next/server';
import { getServerSession } from 'next-auth';
import { authOptions } from '@/lib/auth';
import { tfsScheduler } from '@/services/integrations/tfs/scheduler';
/**
* GET /api/tfs/scheduler-status
* Récupère le statut du scheduler TFS
*/
export async function GET() {
try {
const session = await getServerSession(authOptions);
if (!session?.user?.id) {
return NextResponse.json({ success: false, error: 'Non authentifié' }, { status: 401 });
}
const status = await tfsScheduler.getStatus(session.user.id);
return NextResponse.json({
success: true,
data: status
});
} catch (error) {
console.error('Erreur récupération statut scheduler TFS:', error);
return NextResponse.json({
success: false,
error: error instanceof Error ? error.message : 'Erreur lors de la récupération'
}, { status: 500 });
}
}

View File

@@ -1,5 +1,5 @@
import { NextResponse } from 'next/server';
import { tfsService } from '@/services/integrations/tfs';
import { tfsService } from '@/services/integrations/tfs/tfs';
import { getServerSession } from 'next-auth';
import { authOptions } from '@/lib/auth';

View File

@@ -1,5 +1,5 @@
import { NextResponse } from 'next/server';
import { tfsService } from '@/services/integrations/tfs';
import { tfsService } from '@/services/integrations/tfs/tfs';
import { getServerSession } from 'next-auth';
import { authOptions } from '@/lib/auth';

View File

@@ -2,7 +2,7 @@
import { Badge } from '@/components/ui/Badge';
import { Task } from '@/lib/types';
import { TfsConfig } from '@/services/integrations/tfs';
import { TfsConfig } from '@/services/integrations/tfs/tfs';
import { useUserPreferences } from '@/contexts/UserPreferencesContext';
interface TaskTfsInfoProps {

View File

@@ -1,15 +1,16 @@
'use client';
import { JiraConfig } from '@/lib/types';
import { TfsConfig } from '@/services/integrations/tfs';
import { TfsConfig } from '@/services/integrations/tfs/tfs';
import { Header } from '@/components/ui/Header';
import { Card, CardHeader, CardContent } from '@/components/ui/Card';
import { JiraConfigForm } from '@/components/settings/JiraConfigForm';
import { JiraConfigForm } from './jira/JiraConfigForm';
import { JiraSync } from '@/components/jira/JiraSync';
import { JiraLogs } from '@/components/jira/JiraLogs';
import { JiraSchedulerConfig } from '@/components/jira/JiraSchedulerConfig';
import { TfsConfigForm } from '@/components/settings/TfsConfigForm';
import { TfsSync } from '@/components/tfs/TfsSync';
import { TfsConfigForm } from './tfs/TfsConfigForm';
import { TfsSync } from './tfs/TfsSync';
import { TfsSchedulerConfig } from './tfs/TfsSchedulerConfig';
import Link from 'next/link';
interface IntegrationsSettingsPageClientProps {
@@ -154,7 +155,10 @@ export function IntegrationsSettingsPageClient({
{/* Actions TFS */}
<div className="space-y-4">
{initialTfsConfig?.enabled ? (
<TfsSync />
<>
<TfsSchedulerConfig />
<TfsSync />
</>
) : (
<Card>
<CardContent className="p-4">

View File

@@ -1,7 +1,7 @@
'use client';
import { useState, useEffect, useTransition } from 'react';
import { TfsConfig } from '@/services/integrations/tfs';
import { TfsConfig } from '@/services/integrations/tfs/tfs';
import { getTfsConfig, saveTfsConfig, deleteAllTfsTasks } from '@/actions/tfs';
import { Button } from '@/components/ui/Button';
import { Badge } from '@/components/ui/Badge';
@@ -21,7 +21,6 @@ export function TfsConfigForm() {
type: 'success' | 'error';
text: string;
} | null>(null);
const [testingConnection, setTestingConnection] = useState(false);
const [showForm, setShowForm] = useState(false);
const [isLoading, setIsLoading] = useState(true);
const [deletingTasks, setDeletingTasks] = useState(false);
@@ -119,59 +118,6 @@ export function TfsConfigForm() {
});
};
const testConnection = async () => {
try {
setTestingConnection(true);
setMessage(null);
// Sauvegarder d'abord la config
const saveResult = await saveTfsConfig(config);
if (!saveResult.success) {
setMessage({
type: 'error',
text: saveResult.error || 'Erreur lors de la sauvegarde',
});
return;
}
// Attendre un peu que la configuration soit prise en compte
await new Promise((resolve) => setTimeout(resolve, 1000));
// Tester la connexion avec la route dédiée
const response = await fetch('/api/tfs/test', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
});
const result = await response.json();
console.log('Test TFS - Réponse:', { status: response.status, result });
if (response.ok && result.connected) {
setMessage({
type: 'success',
text: `Connexion Azure DevOps réussie ! ${result.message || ''}`,
});
} else {
const errorMessage =
result.error || result.details || 'Erreur de connexion inconnue';
setMessage({
type: 'error',
text: `Connexion échouée: ${errorMessage}`,
});
console.error('Test TFS échoué:', result);
}
} catch (error) {
console.error('Erreur test connexion TFS:', error);
setMessage({
type: 'error',
text: `Erreur réseau: ${error instanceof Error ? error.message : 'Erreur inconnue'}`,
});
} finally {
setTestingConnection(false);
}
};
const handleDeleteAllTasks = async () => {
setShowDeleteTasksConfirm(true);
@@ -365,6 +311,7 @@ export function TfsConfigForm() {
</div>
)}
{/* Formulaire de configuration */}
{showForm && (
<form
@@ -538,20 +485,6 @@ export function TfsConfigForm() {
: 'Sauvegarder la configuration'}
</Button>
<Button
type="button"
variant="secondary"
onClick={testConnection}
disabled={
testingConnection ||
!config.organizationUrl ||
!config.personalAccessToken
}
className="px-6"
>
{testingConnection ? 'Test...' : 'Tester'}
</Button>
{isTfsConfigured && (
<Button
type="button"

View File

@@ -0,0 +1,246 @@
'use client';
import { useState, useEffect } from 'react';
import { Button } from '@/components/ui/Button';
import { Card, CardHeader, CardContent } from '@/components/ui/Card';
import { Badge } from '@/components/ui/Badge';
import { parseDate, getToday } from '@/lib/date-utils';
interface TfsSchedulerStatus {
isRunning: boolean;
isEnabled: boolean;
interval: 'hourly' | 'daily' | 'weekly';
nextSync: Date | null;
tfsConfigured: boolean;
}
interface TfsSchedulerConfigProps {
className?: string;
}
export function TfsSchedulerConfig({ className = "" }: TfsSchedulerConfigProps) {
const [schedulerStatus, setSchedulerStatus] = useState<TfsSchedulerStatus | null>(null);
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
// Charger le statut initial
useEffect(() => {
loadSchedulerStatus();
}, []);
const loadSchedulerStatus = async () => {
try {
const response = await fetch('/api/tfs/scheduler-status');
if (response.ok) {
const status = await response.json();
setSchedulerStatus(status.data);
}
} catch (err) {
console.error('Erreur lors du chargement du statut scheduler:', err);
}
};
const toggleScheduler = async () => {
if (!schedulerStatus) return;
setIsLoading(true);
setError(null);
try {
const response = await fetch('/api/tfs/scheduler-config', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
tfsAutoSync: !schedulerStatus.isRunning,
tfsSyncInterval: schedulerStatus.interval
})
});
if (response.ok) {
const result = await response.json();
setSchedulerStatus(result.data);
} else {
const error = await response.json();
setError(error.error || 'Erreur lors du toggle scheduler');
}
} catch (err) {
setError(err instanceof Error ? err.message : 'Erreur lors du toggle scheduler');
} finally {
setIsLoading(false);
}
};
const updateInterval = async (interval: 'hourly' | 'daily' | 'weekly') => {
if (!schedulerStatus) return;
setIsLoading(true);
setError(null);
try {
const response = await fetch('/api/tfs/scheduler-config', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
tfsAutoSync: true,
tfsSyncInterval: interval
})
});
if (response.ok) {
const result = await response.json();
setSchedulerStatus(result.data);
} else {
const error = await response.json();
setError(error.error || 'Erreur lors de la mise à jour');
}
} catch (err) {
setError(err instanceof Error ? err.message : 'Erreur lors de la mise à jour');
} finally {
setIsLoading(false);
}
};
const getStatusBadge = () => {
if (!schedulerStatus) return null;
if (!schedulerStatus.tfsConfigured) {
return <Badge variant="warning" size="sm"> TFS non configuré</Badge>;
}
if (!schedulerStatus.isEnabled) {
return <Badge variant="default" size="sm"> Désactivé</Badge>;
}
return schedulerStatus.isRunning ? (
<Badge variant="success" size="sm"> Actif</Badge>
) : (
<Badge variant="danger" size="sm"> Arrêté</Badge>
);
};
const getNextSyncText = () => {
if (!schedulerStatus?.nextSync) return 'Aucune synchronisation planifiée';
const nextSync = typeof schedulerStatus.nextSync === 'string'
? parseDate(schedulerStatus.nextSync)
: schedulerStatus.nextSync;
const now = getToday();
const diffMs = nextSync.getTime() - now.getTime();
if (diffMs <= 0) return 'Synchronisation en cours...';
const diffHours = Math.floor(diffMs / (1000 * 60 * 60));
const diffMinutes = Math.floor((diffMs % (1000 * 60 * 60)) / (1000 * 60));
if (diffHours > 0) {
return `Dans ${diffHours}h ${diffMinutes}min`;
} else {
return `Dans ${diffMinutes}min`;
}
};
const getIntervalText = (interval: string) => {
switch (interval) {
case 'hourly': return 'Horaire';
case 'daily': return 'Quotidien';
case 'weekly': return 'Hebdomadaire';
default: return interval;
}
};
if (!schedulerStatus) {
return (
<Card className={className}>
<CardHeader>
<h3 className="text-lg font-semibold"> Synchronisation automatique</h3>
</CardHeader>
<CardContent>
<p className="text-gray-500">Chargement...</p>
</CardContent>
</Card>
);
}
return (
<Card className={className}>
<CardHeader>
<div className="flex items-center justify-between gap-3">
<h3 className="text-base sm:text-lg font-semibold flex-1 min-w-0 truncate"> Synchronisation automatique</h3>
<div className="flex-shrink-0">
{getStatusBadge()}
</div>
</div>
</CardHeader>
<CardContent className="space-y-4">
{error && (
<div className="p-3 bg-red-50 border border-red-200 rounded-md">
<p className="text-red-700 text-sm">{error}</p>
</div>
)}
{/* Statut actuel */}
<div className="grid grid-cols-2 gap-4 text-sm">
<div>
<span className="font-medium text-gray-600">Statut:</span>
<p className="mt-1">
{schedulerStatus.isEnabled && schedulerStatus.isRunning ? '🟢 Actif' : '🔴 Arrêté'}
</p>
</div>
<div>
<span className="font-medium text-gray-600">Fréquence:</span>
<p className="mt-1">{getIntervalText(schedulerStatus.interval)}</p>
</div>
<div className="col-span-2">
<span className="font-medium text-gray-600">Prochaine synchronisation:</span>
<p className="mt-1">{getNextSyncText()}</p>
</div>
</div>
{/* Contrôles */}
<div className="flex flex-col gap-3">
{/* Toggle scheduler */}
<div className="flex items-center justify-between">
<span className="text-sm font-medium">Synchronisation automatique</span>
<Button
variant={schedulerStatus.isRunning ? "danger" : "primary"}
size="sm"
onClick={toggleScheduler}
disabled={isLoading || !schedulerStatus.tfsConfigured}
>
{schedulerStatus.isRunning ? 'Désactiver' : 'Activer'}
</Button>
</div>
{/* Sélecteur d'intervalle */}
{schedulerStatus.isEnabled && (
<div>
<span className="text-sm font-medium text-gray-600 block mb-2">Fréquence de synchronisation</span>
<div className="flex gap-2">
{(['hourly', 'daily', 'weekly'] as const).map((interval) => (
<Button
key={interval}
variant={schedulerStatus.interval === interval ? "primary" : "secondary"}
size="sm"
onClick={() => updateInterval(interval)}
disabled={isLoading}
>
{getIntervalText(interval)}
</Button>
))}
</div>
</div>
)}
</div>
{/* Avertissement si TFS non configuré */}
{!schedulerStatus.tfsConfigured && (
<div className="p-3 bg-yellow-50 border border-yellow-200 rounded-md">
<p className="text-yellow-700 text-sm">
Configurez d&apos;abord votre connexion TFS pour activer la synchronisation automatique.
</p>
</div>
)}
</CardContent>
</Card>
);
}

View File

@@ -0,0 +1,370 @@
'use client';
import { useState } from 'react';
import { Button } from '@/components/ui/Button';
import { Card, CardHeader, CardContent } from '@/components/ui/Card';
import { Badge } from '@/components/ui/Badge';
import { getToday } from '@/lib/date-utils';
import { Modal } from '@/components/ui/Modal';
import { TfsSyncResult, TfsSyncAction } from '@/services/integrations/tfs/tfs';
interface TfsSyncProps {
onSyncComplete?: () => void;
className?: string;
}
export function TfsSync({ onSyncComplete, className = "" }: TfsSyncProps) {
const [isConnected, setIsConnected] = useState<boolean | null>(null);
const [isLoading, setIsLoading] = useState(false);
const [isSyncing, setIsSyncing] = useState(false);
const [lastSyncResult, setLastSyncResult] = useState<TfsSyncResult | null>(null);
const [error, setError] = useState<string | null>(null);
const [showDetails, setShowDetails] = useState(false);
const testConnection = async () => {
setIsLoading(true);
setError(null);
try {
const response = await fetch('/api/tfs/test');
const result = await response.json();
setIsConnected(result.connected);
if (!result.connected) {
setError(result.error || result.message);
}
} catch (err) {
setIsConnected(false);
setError(err instanceof Error ? err.message : 'Erreur de connexion');
} finally {
setIsLoading(false);
}
};
const startSync = async () => {
setIsSyncing(true);
setError(null);
try {
const response = await fetch('/api/tfs/sync', { method: 'POST' });
const result = await response.json();
console.log('TFS Sync API Response:', result);
// L'API retourne { message: '...', data: result } ou { error: '...', data: result }
const syncResult = result.data || result;
console.log('TFS Sync Result:', syncResult);
setLastSyncResult(syncResult);
// Considérer comme succès si on a une réponse (même avec status 207)
if (response.ok || response.status === 207) {
onSyncComplete?.();
}
} catch (err) {
console.error('TFS Sync Error:', err);
setError(err instanceof Error ? err.message : 'Erreur de synchronisation');
} finally {
setIsSyncing(false);
}
};
const getConnectionStatus = () => {
if (isConnected === null) return null;
return isConnected ? (
<Badge variant="success" size="sm"> Connecté</Badge>
) : (
<Badge variant="danger" size="sm"> Déconnecté</Badge>
);
};
const getSyncStatus = () => {
if (!lastSyncResult) return null;
const {
success,
totalPullRequests = 0,
pullRequestsCreated = 0,
pullRequestsUpdated = 0,
pullRequestsSkipped = 0,
pullRequestsDeleted = 0,
errors = [],
actions = []
} = lastSyncResult;
return (
<div className="space-y-3 text-sm">
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
<Badge variant={
success ? "success" :
(errors.length > 0 ? "danger" :
(totalPullRequests > 0 ? "warning" : "success"))
} size="sm">
{success ? "✓ Succès" :
(errors.length > 0 ? "⚠ Erreurs" :
(totalPullRequests > 0 ? "✓ À jour" : "✓ Synchronisé"))}
</Badge>
<span className="text-[var(--muted-foreground)] text-xs">
{getToday().toLocaleTimeString()}
</span>
</div>
<div className="text-xs text-[var(--muted-foreground)]">
{totalPullRequests > 0
? `${totalPullRequests} PR${totalPullRequests > 1 ? 's' : ''} trouvée${totalPullRequests > 1 ? 's' : ''}`
: 'Aucune PR trouvée'
}
</div>
</div>
<div className="grid grid-cols-2 gap-2 text-xs">
<div className="text-center p-2 bg-[var(--card)] rounded">
<div className="font-mono font-bold text-emerald-400">{pullRequestsCreated}</div>
<div className="text-[var(--muted-foreground)]">Créées</div>
</div>
<div className="text-center p-2 bg-[var(--card)] rounded">
<div className="font-mono font-bold text-blue-400">{pullRequestsUpdated}</div>
<div className="text-[var(--muted-foreground)]">Mises à jour</div>
</div>
<div className="text-center p-2 bg-[var(--card)] rounded">
<div className="font-mono font-bold text-orange-400">{pullRequestsSkipped}</div>
<div className="text-[var(--muted-foreground)]">Ignorées</div>
</div>
<div className="text-center p-2 bg-[var(--card)] rounded">
<div className="font-mono font-bold text-red-400">{pullRequestsDeleted}</div>
<div className="text-[var(--muted-foreground)]">Supprimées</div>
</div>
</div>
{/* Résumé textuel avec bouton détails */}
<div className="p-2 bg-[var(--muted)]/5 rounded text-xs">
<div className="flex items-center justify-between mb-1">
<div className="font-medium text-[var(--muted-foreground)]">Résumé:</div>
{actions && actions.length > 0 && (
<Button
onClick={() => setShowDetails(true)}
variant="secondary"
size="sm"
className="text-xs px-2 py-1 h-auto"
>
Voir détails ({actions.length})
</Button>
)}
</div>
<div className="text-[var(--muted-foreground)]">
{pullRequestsCreated > 0 && `${pullRequestsCreated} nouvelle${pullRequestsCreated > 1 ? 's' : ''}`}
{pullRequestsUpdated > 0 && `${pullRequestsUpdated} mise${pullRequestsUpdated > 1 ? 's' : ''} à jour • `}
{pullRequestsDeleted > 0 && `${pullRequestsDeleted} supprimée${pullRequestsDeleted > 1 ? 's' : ''} (fermées) • `}
{pullRequestsSkipped > 0 && `${pullRequestsSkipped} déjà synchronisée${pullRequestsSkipped > 1 ? 's' : ''}`}
{(pullRequestsCreated + pullRequestsUpdated + pullRequestsDeleted + pullRequestsSkipped) === 0 && 'Aucune PR trouvée'}
</div>
</div>
{errors && errors.length > 0 && (
<div className="p-2 bg-[var(--destructive)]/10 border border-[var(--destructive)]/20 rounded text-xs">
<div className="font-semibold text-[var(--destructive)] mb-1">Erreurs ({errors.length}):</div>
<div className="space-y-1 max-h-20 overflow-y-auto">
{errors.map((err, i) => (
<div key={i} className="text-[var(--destructive)] font-mono text-xs">{err}</div>
))}
</div>
</div>
)}
</div>
);
};
return (
<Card className={`${className}`}>
<CardHeader className="pb-4">
<div className="flex items-center justify-between">
<div className="flex items-center gap-3">
<div className="w-2 h-2 rounded-full animate-pulse" style={{ backgroundColor: 'var(--purple)' }}></div>
<h3 className="font-mono text-sm font-bold text-purple-400 uppercase tracking-wider">
TFS SYNC
</h3>
</div>
{getConnectionStatus()}
</div>
</CardHeader>
<CardContent className="space-y-4">
{/* Test de connexion */}
<div className="flex gap-2">
<Button
onClick={testConnection}
disabled={isLoading}
variant="secondary"
size="sm"
className="flex-1"
>
{isLoading ? (
<div className="flex items-center gap-2">
<div className="w-3 h-3 border border-[var(--muted-foreground)] border-t-transparent rounded-full animate-spin"></div>
Test...
</div>
) : (
'Tester connexion'
)}
</Button>
<Button
onClick={startSync}
disabled={isSyncing || isConnected === false}
variant="primary"
size="sm"
className="flex-1"
>
{isSyncing ? (
<div className="flex items-center gap-2">
<div className="w-3 h-3 border border-white border-t-transparent rounded-full animate-spin"></div>
Sync...
</div>
) : (
'🔄 Synchroniser'
)}
</Button>
</div>
{/* Messages d'erreur */}
{error && (
<div className="p-3 bg-[var(--destructive)]/10 border border-[var(--destructive)]/20 rounded text-sm text-[var(--destructive)]">
{error}
</div>
)}
{/* Résultats de sync */}
{getSyncStatus()}
{/* Info */}
<div className="text-xs text-[var(--muted-foreground)] space-y-1">
<div> Synchronisation unidirectionnelle (TFS TowerControl)</div>
<div> Les modifications locales sont préservées</div>
<div> Seules les Pull Requests assignées sont synchronisées</div>
<div> Les PRs fermées sont automatiquement supprimées</div>
</div>
</CardContent>
{/* Modal détails de synchronisation */}
{lastSyncResult && (
<Modal
isOpen={showDetails}
onClose={() => setShowDetails(false)}
title="📋 DÉTAILS DE SYNCHRONISATION"
size="xl"
>
<div className="space-y-4">
<p className="text-sm text-[var(--muted-foreground)]">
{(lastSyncResult.actions || []).length} action{(lastSyncResult.actions || []).length > 1 ? 's' : ''} effectuée{(lastSyncResult.actions || []).length > 1 ? 's' : ''}
</p>
<div className="max-h-[60vh] overflow-y-auto">
{(lastSyncResult.actions || []).length > 0 ? (
<SyncActionsList actions={lastSyncResult.actions || []} />
) : (
<div className="text-center py-8 text-[var(--muted-foreground)]">
<div className="text-2xl mb-2">📝</div>
<div>Aucun détail disponible pour cette synchronisation</div>
<div className="text-sm mt-1">Les détails sont disponibles pour les nouvelles synchronisations</div>
</div>
)}
</div>
</div>
</Modal>
)}
</Card>
);
}
// Composant pour afficher la liste des actions
function SyncActionsList({ actions }: { actions: TfsSyncAction[] }) {
const getActionIcon = (type: TfsSyncAction['type']) => {
switch (type) {
case 'created': return '';
case 'updated': return '🔄';
case 'skipped': return '⏭️';
case 'deleted': return '🗑️';
default: return '❓';
}
};
const getActionColor = (type: TfsSyncAction['type']) => {
switch (type) {
case 'created': return 'text-emerald-400';
case 'updated': return 'text-blue-400';
case 'skipped': return 'text-orange-400';
case 'deleted': return 'text-red-400';
default: return 'text-gray-400';
}
};
const getActionLabel = (type: TfsSyncAction['type']) => {
switch (type) {
case 'created': return 'Créée';
case 'updated': return 'Mise à jour';
case 'skipped': return 'Ignorée';
case 'deleted': return 'Supprimée';
default: return 'Inconnue';
}
};
// Grouper les actions par type
const groupedActions = actions.reduce((acc, action) => {
if (!acc[action.type]) acc[action.type] = [];
acc[action.type].push(action);
return acc;
}, {} as Record<string, TfsSyncAction[]>);
return (
<div className="space-y-6">
{Object.entries(groupedActions).map(([type, typeActions]) => (
<div key={type} className="space-y-3">
<h4 className={`font-bold text-sm flex items-center gap-2 ${getActionColor(type as TfsSyncAction['type'])}`}>
{getActionIcon(type as TfsSyncAction['type'])}
{getActionLabel(type as TfsSyncAction['type'])} ({typeActions.length})
</h4>
<div className="space-y-2">
{typeActions.map((action, index) => (
<div key={index} className="p-2 bg-[var(--muted)]/10 rounded border border-[var(--border)]">
<div className="flex items-start justify-between gap-3">
<div className="flex-1 min-w-0">
<div className="flex items-baseline gap-2">
<span className="font-mono text-sm font-bold text-[var(--foreground)] shrink-0">
PR #{action.pullRequestId}
</span>
<span className="text-sm text-[var(--muted-foreground)] truncate">
{action.prTitle}
</span>
</div>
</div>
<Badge variant="outline" size="sm" className="shrink-0">
{getActionLabel(action.type)}
</Badge>
</div>
{action.reason && (
<div className="mt-1 text-xs text-[var(--muted-foreground)] italic">
💡 {action.reason}
</div>
)}
{action.changes && action.changes.length > 0 && (
<div className="mt-1 space-y-0.5">
<div className="text-xs font-medium text-[var(--muted-foreground)]">
Modifications:
</div>
{action.changes.map((change, changeIndex) => (
<div key={changeIndex} className="text-xs font-mono text-[var(--foreground)] pl-2 border-l-2 border-purple-400/30">
{change}
</div>
))}
</div>
)}
</div>
))}
</div>
</div>
))}
</div>
);
}

View File

@@ -1,100 +0,0 @@
'use client';
import { useState, useTransition } from 'react';
import { Card, CardHeader, CardContent } from '@/components/ui/Card';
import { syncTfsPullRequests } from '@/actions/tfs';
export function TfsSync() {
const [isPending, startTransition] = useTransition();
const [lastSync, setLastSync] = useState<{
success: boolean;
message: string;
stats?: {
created: number;
updated: number;
skipped: number;
deleted: number;
}
} | null>(null);
const handleSync = () => {
startTransition(async () => {
setLastSync(null);
const result = await syncTfsPullRequests();
if (result.success) {
setLastSync({
success: true,
message: result.message || 'Synchronisation réussie',
stats: result.data ? {
created: result.data.pullRequestsCreated,
updated: result.data.pullRequestsUpdated,
skipped: result.data.pullRequestsSkipped,
deleted: result.data.pullRequestsDeleted
} : undefined
});
} else {
setLastSync({
success: false,
message: result.error || 'Erreur lors de la synchronisation'
});
}
});
};
return (
<Card>
<CardHeader>
<h3 className="text-lg font-semibold flex items-center gap-2">
<span className="text-blue-600">🔄</span>
Synchronisation TFS
</h3>
</CardHeader>
<CardContent className="space-y-4">
<p className="text-sm text-[var(--muted-foreground)]">
Synchronise manuellement les Pull Requests depuis Azure DevOps
</p>
{/* Résultat de la dernière synchronisation */}
{lastSync && (
<div className={`p-3 rounded-lg text-sm ${
lastSync.success
? 'bg-green-50 text-green-800 border border-green-200'
: 'bg-red-50 text-red-800 border border-red-200'
}`}>
<div className="font-medium mb-1">
{lastSync.success ? '✅' : '❌'} {lastSync.message}
</div>
{lastSync.stats && (
<div className="text-xs opacity-80">
Créées: {lastSync.stats.created} |
Mises à jour: {lastSync.stats.updated} |
Ignorées: {lastSync.stats.skipped} |
Supprimées: {lastSync.stats.deleted}
</div>
)}
</div>
)}
<button
onClick={handleSync}
disabled={isPending}
className="w-full px-4 py-2 bg-[var(--primary)] text-[var(--primary-foreground)] rounded-lg hover:bg-[var(--primary)]/90 transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2"
>
{isPending && (
<svg className="animate-spin h-4 w-4" viewBox="0 0 24 24">
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" fill="none" />
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 0 1 8-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 0 1 4 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z" />
</svg>
)}
{isPending ? 'Synchronisation en cours...' : 'Synchroniser maintenant'}
</button>
<div className="text-xs text-[var(--muted-foreground)] text-center">
Les Pull Requests seront importées comme tâches dans le tableau Kanban
</div>
</CardContent>
</Card>
);
}

View File

@@ -1,4 +1,4 @@
import { TfsConfig } from '@/services/integrations/tfs';
import { TfsConfig } from '@/services/integrations/tfs/tfs';
import { Theme } from './theme-config';
// Réexporter Theme pour les autres modules

View File

@@ -7,7 +7,7 @@ import {
JiraConfig,
Theme,
} from '@/lib/types';
import { TfsConfig } from '@/services/integrations/tfs';
import { TfsConfig } from '@/services/integrations/tfs/tfs';
import { prisma } from './database';
import { getConfig } from '@/lib/config';
@@ -94,6 +94,7 @@ class UserPreferencesService {
// S'assurer que les nouveaux champs existent (migration douce)
await this.ensureJiraSchedulerFields(userId);
await this.ensureTfsSchedulerFields(userId);
return userPrefs;
}
@@ -115,6 +116,23 @@ class UserPreferencesService {
}
}
/**
* S'assure que les champs tfsAutoSync et tfsSyncInterval existent
*/
private async ensureTfsSchedulerFields(userId: string): Promise<void> {
try {
await prisma.$executeRaw`
UPDATE user_preferences
SET tfsAutoSync = COALESCE(tfsAutoSync, ${DEFAULT_PREFERENCES.tfsAutoSync}),
tfsSyncInterval = COALESCE(tfsSyncInterval, ${DEFAULT_PREFERENCES.tfsSyncInterval})
WHERE userId = ${userId}
`;
} catch (error) {
// Ignorer les erreurs si les colonnes n'existent pas encore
console.debug('Migration douce des champs scheduler TFS:', error);
}
}
// === FILTRES KANBAN ===
/**

View File

@@ -0,0 +1,208 @@
import { userPreferencesService } from '@/services/core/user-preferences';
import { TfsService } from './tfs';
import { addMinutes, getToday } from '@/lib/date-utils';
export interface TfsSchedulerConfig {
enabled: boolean;
interval: 'hourly' | 'daily' | 'weekly';
}
export class TfsScheduler {
private timer: NodeJS.Timeout | null = null;
private isRunning = false;
private currentUserId: string | null = null;
/**
* Démarre le planificateur de synchronisation TFS automatique
*/
async start(userId?: string): Promise<void> {
if (this.isRunning) {
console.log('⚠️ TFS scheduler is already running');
return;
}
const targetUserId = userId || 'default';
const config = await this.getConfig(targetUserId);
if (!config.enabled) {
console.log('📋 Automatic TFS sync is disabled');
return;
}
// Vérifier que TFS est configuré
const tfsConfig = await userPreferencesService.getTfsConfig(targetUserId);
if (!tfsConfig.enabled || !tfsConfig.organizationUrl || !tfsConfig.personalAccessToken) {
console.log('⚠️ TFS not configured, scheduler cannot start');
return;
}
const intervalMs = this.getIntervalMs(config.interval);
// Première synchronisation immédiate (optionnelle)
// this.performScheduledSync();
// Planifier les synchronisations suivantes
this.timer = setInterval(() => {
this.performScheduledSync(targetUserId);
}, intervalMs);
this.isRunning = true;
this.currentUserId = targetUserId;
console.log(`✅ TFS scheduler started with ${config.interval} interval for user ${targetUserId}`);
}
/**
* Arrête le planificateur
*/
stop(): void {
if (this.timer) {
clearInterval(this.timer);
this.timer = null;
}
this.isRunning = false;
this.currentUserId = null;
console.log('🛑 TFS scheduler stopped');
}
/**
* Redémarre le planificateur (utile lors des changements de config)
*/
async restart(userId?: string): Promise<void> {
this.stop();
await this.start(userId);
}
/**
* Vérifie si le planificateur fonctionne
*/
isActive(): boolean {
return this.isRunning && this.timer !== null;
}
/**
* Effectue une synchronisation planifiée
*/
private async performScheduledSync(userId: string = 'default'): Promise<void> {
try {
console.log('🔄 Starting scheduled TFS sync...');
// Récupérer la config TFS
const tfsConfig = await userPreferencesService.getTfsConfig(userId);
if (!tfsConfig.enabled || !tfsConfig.organizationUrl || !tfsConfig.personalAccessToken) {
console.log('⚠️ TFS config incomplete, skipping scheduled sync');
return;
}
// Créer le service TFS
const tfsService = new TfsService({
enabled: tfsConfig.enabled,
organizationUrl: tfsConfig.organizationUrl,
projectName: tfsConfig.projectName,
personalAccessToken: tfsConfig.personalAccessToken,
repositories: tfsConfig.repositories || [],
ignoredRepositories: tfsConfig.ignoredRepositories || []
});
// Tester la connexion d'abord
const connectionOk = await tfsService.testConnection();
if (!connectionOk) {
console.error('❌ Scheduled TFS sync failed: connection error');
return;
}
// Effectuer la synchronisation
const result = await tfsService.syncTasks();
if (result.success) {
console.log(`✅ Scheduled TFS sync completed: ${result.pullRequestsCreated} created, ${result.pullRequestsUpdated} updated, ${result.pullRequestsSkipped} skipped`);
} else {
console.error(`❌ Scheduled TFS sync failed: ${result.errors.join(', ')}`);
}
} catch (error) {
console.error('❌ Scheduled TFS sync error:', error);
}
}
/**
* Convertit l'intervalle en millisecondes
*/
private getIntervalMs(interval: TfsSchedulerConfig['interval']): number {
const intervals = {
hourly: 60 * 60 * 1000, // 1 heure
daily: 24 * 60 * 60 * 1000, // 24 heures
weekly: 7 * 24 * 60 * 60 * 1000, // 7 jours
};
return intervals[interval];
}
/**
* Obtient le prochain moment de synchronisation
*/
async getNextSyncTime(): Promise<Date | null> {
if (!this.isRunning || !this.timer) {
return null;
}
const config = await this.getConfig();
const intervalMs = this.getIntervalMs(config.interval);
return addMinutes(getToday(), Math.floor(intervalMs / (1000 * 60)));
}
/**
* Récupère la configuration du scheduler depuis les user preferences
*/
private async getConfig(userId: string = 'default'): Promise<TfsSchedulerConfig> {
try {
const [tfsConfig, schedulerConfig] = await Promise.all([
userPreferencesService.getTfsConfig(userId),
userPreferencesService.getTfsSchedulerConfig(userId)
]);
return {
enabled: schedulerConfig.tfsAutoSync &&
tfsConfig.enabled &&
!!tfsConfig.organizationUrl &&
!!tfsConfig.personalAccessToken,
interval: schedulerConfig.tfsSyncInterval
};
} catch (error) {
console.error('Error getting TFS scheduler config:', error);
return {
enabled: false,
interval: 'daily'
};
}
}
/**
* Obtient les stats du planificateur
*/
async getStatus(userId?: string) {
const targetUserId = userId || 'default';
const config = await this.getConfig(targetUserId);
const tfsConfig = await userPreferencesService.getTfsConfig(targetUserId);
return {
isRunning: this.isRunning,
isEnabled: config.enabled,
interval: config.interval,
nextSync: await this.getNextSyncTime(),
tfsConfigured: !!(tfsConfig.organizationUrl && tfsConfig.personalAccessToken),
};
}
}
// Instance singleton
export const tfsScheduler = new TfsScheduler();
// Auto-start du scheduler
// Démarrer avec un délai pour laisser l'app s'initialiser
setTimeout(() => {
console.log('🚀 Auto-starting TFS scheduler...');
tfsScheduler.start();
}, 8000); // 8 secondes, après le Jira scheduler

View File

@@ -205,19 +205,12 @@ export class TfsService {
*/
async getMyPullRequests(): Promise<TfsPullRequest[]> {
try {
console.log("🔍 Récupération des PRs créées par l'utilisateur...");
// Uniquement les PRs créées par l'utilisateur (simplifié)
const createdPrs = await this.getPullRequestsByCreator();
console.log(`👤 ${createdPrs.length} PR(s) créées par l'utilisateur`);
// Filtrer les PRs selon la configuration
const filteredPrs = this.filterPullRequests(createdPrs);
console.log(
`🎫 ${filteredPrs.length} PR(s) après filtrage de configuration`
);
return filteredPrs;
} catch (error) {
console.error('❗️ Erreur récupération PRs utilisateur:', error);
@@ -264,7 +257,6 @@ export class TfsService {
const data = await response.json();
const prs = data.value || [];
console.log(`🚀 ${prs.length} PR(s) créée(s) par l'utilisateur`);
return prs;
} catch (error) {
console.error('❗️ Erreur récupération PRs créateur:', error);
@@ -426,30 +418,18 @@ export class TfsService {
if (pr.closedDate) {
const closedDate = parseDate(pr.closedDate);
const isRecent = closedDate >= thirtyDaysAgo;
console.log(
`📅 PR ${pr.pullRequestId} (${pr.title}): Completed ${formatDateForDisplay(closedDate)} - ${isRecent ? 'INCLUSE (récente)' : 'EXCLUE (âgée)'}`
);
return isRecent;
} else {
// Si pas de date de fermeture, on l'inclut par sécurité
console.log(
`❓ PR ${pr.pullRequestId} (${pr.title}): Completed sans date - INCLUSE`
);
return true;
}
case 'abandoned':
// PRs abandonnées ne sont pas pertinentes
console.log(
`❌ PR ${pr.pullRequestId} (${pr.title}): Abandoned - EXCLUE`
);
return false;
default:
// Statut inconnu, on l'inclut par précaution
console.log(
`❓ PR ${pr.pullRequestId} (${pr.title}): Statut inconnu "${pr.status}" - INCLUSE`
);
return true;
}
});
@@ -555,10 +535,7 @@ export class TfsService {
const allPullRequests = await this.getMyPullRequests();
result.totalPullRequests = allPullRequests.length;
console.log(`📋 ${allPullRequests.length} Pull Requests trouvées`);
if (allPullRequests.length === 0) {
console.log(' Aucune PR assignée trouvée');
return result;
}
@@ -637,8 +614,6 @@ export class TfsService {
// Assigner le tag TFS
await this.assignTfsTag(newTask.id);
console.log(`➡️ Nouvelle tâche créée: PR-${pullRequestId}`);
return {
type: 'created',
pullRequestId,
@@ -662,8 +637,6 @@ export class TfsService {
}
if (changes.length === 0) {
console.log(`⏭️ Aucun changement pour PR-${pullRequestId}`);
// S'assurer que le tag TFS est assigné (pour les anciennes tâches)
await this.assignTfsTag(existingTask.id);
@@ -684,8 +657,6 @@ export class TfsService {
},
});
console.log(`🔄 Tâche mise à jour: PR-${pullRequestId} (${changes.length} changements)`);
return {
type: 'updated',
pullRequestId,
@@ -891,25 +862,17 @@ export class TfsService {
},
});
console.log(`📋 ${existingTfsTasks.length} tâches TFS existantes`);
// Identifier les tâches à supprimer
const tasksToDelete = existingTfsTasks.filter((task) => {
const prId = task.tfsPullRequestId;
if (!prId) {
console.log(`🤷 Tâche ${task.id} sans PR ID - à supprimer`);
return true;
}
const shouldKeep = currentPrIds.has(prId);
if (!shouldKeep) {
console.log(`❌ PR ${prId} plus active - à supprimer`);
}
return !shouldKeep;
});
console.log(`🗑️ ${tasksToDelete.length} tâches à supprimer`);
// Supprimer les tâches obsolètes
for (const task of tasksToDelete) {
try {
@@ -922,7 +885,6 @@ export class TfsService {
reason: 'Pull Request plus active ou supprimée',
});
console.log(`🗑️ Supprimé: ${task.title}`);
} catch (error) {
console.error(`❌ Erreur suppression tâche ${task.id}:`, error);
// Continue avec les autres tâches
@@ -948,16 +910,12 @@ export class TfsService {
error?: string;
}> {
try {
console.log('🗑️ Début suppression de toutes les tâches TFS...');
// Récupérer toutes les tâches TFS
const tfsTasks = await prisma.task.findMany({
where: { source: 'tfs' },
select: { id: true, title: true },
});
console.log(`📋 ${tfsTasks.length} tâches TFS trouvées`);
if (tfsTasks.length === 0) {
return {
success: true,