feat: enhance Jira scheduler with user-specific handling
- Updated `jiraScheduler` methods to accept a `userId` parameter, allowing for user-specific configurations and status retrieval. - Modified the `POST` and `GET` routes to pass the current user's ID, ensuring accurate scheduler status and actions based on the logged-in user. - Adjusted the `JiraSchedulerConfig` component to reflect changes in scheduler activation logic from `isEnabled` to `isRunning`, improving clarity in the UI. - Enhanced synchronization response structure to provide detailed task statistics for better client-side handling.
This commit is contained in:
@@ -29,13 +29,13 @@ export async function POST(request: Request) {
|
||||
switch (action) {
|
||||
case 'scheduler':
|
||||
if (params.enabled) {
|
||||
await jiraScheduler.start();
|
||||
await jiraScheduler.start(session.user.id);
|
||||
} else {
|
||||
jiraScheduler.stop();
|
||||
}
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
data: await jiraScheduler.getStatus()
|
||||
data: await jiraScheduler.getStatus(session.user.id)
|
||||
});
|
||||
|
||||
case 'config':
|
||||
@@ -45,11 +45,11 @@ export async function POST(request: Request) {
|
||||
params.jiraSyncInterval
|
||||
);
|
||||
// Redémarrer le scheduler si la config a changé
|
||||
await jiraScheduler.restart();
|
||||
await jiraScheduler.restart(session.user.id);
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
message: 'Configuration scheduler mise à jour',
|
||||
data: await jiraScheduler.getStatus()
|
||||
data: await jiraScheduler.getStatus(session.user.id)
|
||||
});
|
||||
|
||||
default:
|
||||
@@ -99,18 +99,36 @@ export async function POST(request: Request) {
|
||||
}
|
||||
|
||||
// Effectuer la synchronisation
|
||||
const result = await jiraService.syncTasks();
|
||||
const syncResult = await jiraService.syncTasks();
|
||||
|
||||
if (result.success) {
|
||||
// Convertir SyncResult en JiraSyncResult pour le client
|
||||
const jiraSyncResult = {
|
||||
success: syncResult.success,
|
||||
tasksFound: syncResult.totalItems,
|
||||
tasksCreated: syncResult.stats.created,
|
||||
tasksUpdated: syncResult.stats.updated,
|
||||
tasksSkipped: syncResult.stats.skipped,
|
||||
tasksDeleted: syncResult.stats.deleted,
|
||||
errors: syncResult.errors,
|
||||
actions: syncResult.actions.map(action => ({
|
||||
type: action.type as 'created' | 'updated' | 'skipped' | 'deleted',
|
||||
taskKey: action.itemId.toString(),
|
||||
taskTitle: action.title,
|
||||
reason: action.message,
|
||||
changes: action.message ? [action.message] : undefined
|
||||
}))
|
||||
};
|
||||
|
||||
if (syncResult.success) {
|
||||
return NextResponse.json({
|
||||
message: 'Synchronisation Jira terminée avec succès',
|
||||
data: result
|
||||
data: jiraSyncResult
|
||||
});
|
||||
} else {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: 'Synchronisation Jira terminée avec des erreurs',
|
||||
data: result
|
||||
data: jiraSyncResult
|
||||
},
|
||||
{ status: 207 } // Multi-Status
|
||||
);
|
||||
@@ -180,8 +198,8 @@ export async function GET() {
|
||||
projectValidation = await jiraService.validateProject(jiraConfig.projectKey);
|
||||
}
|
||||
|
||||
// Récupérer aussi le statut du scheduler
|
||||
const schedulerStatus = await jiraScheduler.getStatus();
|
||||
// Récupérer aussi le statut du scheduler avec l'utilisateur connecté
|
||||
const schedulerStatus = await jiraScheduler.getStatus(session.user.id);
|
||||
|
||||
return NextResponse.json({
|
||||
connected,
|
||||
|
||||
@@ -39,8 +39,8 @@ export function JiraSchedulerConfig({ className = "" }: JiraSchedulerConfigProps
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
// Utiliser isEnabled au lieu de isRunning pour l'activation
|
||||
const newStatus = await jiraClient.updateSchedulerConfig(!schedulerStatus.isEnabled, schedulerStatus.interval);
|
||||
// Utiliser isRunning au lieu de isEnabled pour l'activation
|
||||
const newStatus = await jiraClient.updateSchedulerConfig(!schedulerStatus.isRunning, schedulerStatus.interval);
|
||||
setSchedulerStatus(newStatus);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Erreur lors du toggle scheduler');
|
||||
@@ -104,8 +104,8 @@ export function JiraSchedulerConfig({ className = "" }: JiraSchedulerConfigProps
|
||||
|
||||
const getIntervalText = (interval: string) => {
|
||||
switch (interval) {
|
||||
case 'hourly': return 'Toutes les heures';
|
||||
case 'daily': return 'Quotidienne';
|
||||
case 'hourly': return 'Horaire';
|
||||
case 'daily': return 'Quotidien';
|
||||
case 'weekly': return 'Hebdomadaire';
|
||||
default: return interval;
|
||||
}
|
||||
@@ -165,12 +165,12 @@ export function JiraSchedulerConfig({ className = "" }: JiraSchedulerConfigProps
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-sm font-medium">Synchronisation automatique</span>
|
||||
<Button
|
||||
variant={schedulerStatus.isEnabled ? "danger" : "primary"}
|
||||
variant={schedulerStatus.isRunning ? "danger" : "primary"}
|
||||
size="sm"
|
||||
onClick={toggleScheduler}
|
||||
disabled={isLoading || !schedulerStatus.jiraConfigured}
|
||||
>
|
||||
{schedulerStatus.isEnabled ? 'Désactiver' : 'Activer'}
|
||||
{schedulerStatus.isRunning ? 'Désactiver' : 'Activer'}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -10,17 +10,19 @@ export interface JiraSchedulerConfig {
|
||||
export class JiraScheduler {
|
||||
private timer: NodeJS.Timeout | null = null;
|
||||
private isRunning = false;
|
||||
private currentUserId: string | null = null;
|
||||
|
||||
/**
|
||||
* Démarre le planificateur de synchronisation Jira automatique
|
||||
*/
|
||||
async start(): Promise<void> {
|
||||
async start(userId?: string): Promise<void> {
|
||||
if (this.isRunning) {
|
||||
console.log('⚠️ Jira scheduler is already running');
|
||||
return;
|
||||
}
|
||||
|
||||
const config = await this.getConfig();
|
||||
const targetUserId = userId || 'default';
|
||||
const config = await this.getConfig(targetUserId);
|
||||
|
||||
if (!config.enabled) {
|
||||
console.log('📋 Automatic Jira sync is disabled');
|
||||
@@ -28,8 +30,7 @@ export class JiraScheduler {
|
||||
}
|
||||
|
||||
// Vérifier que Jira est configuré
|
||||
// Pour les services système, on utilise un userId par défaut
|
||||
const jiraConfig = await userPreferencesService.getJiraConfig('default');
|
||||
const jiraConfig = await userPreferencesService.getJiraConfig(targetUserId);
|
||||
if (!jiraConfig.enabled || !jiraConfig.baseUrl || !jiraConfig.email || !jiraConfig.apiToken) {
|
||||
console.log('⚠️ Jira not configured, scheduler cannot start');
|
||||
return;
|
||||
@@ -42,11 +43,12 @@ export class JiraScheduler {
|
||||
|
||||
// Planifier les synchronisations suivantes
|
||||
this.timer = setInterval(() => {
|
||||
this.performScheduledSync();
|
||||
this.performScheduledSync(targetUserId);
|
||||
}, intervalMs);
|
||||
|
||||
this.isRunning = true;
|
||||
console.log(`✅ Jira scheduler started with ${config.interval} interval`);
|
||||
this.currentUserId = targetUserId;
|
||||
console.log(`✅ Jira scheduler started with ${config.interval} interval for user ${targetUserId}`);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -59,15 +61,16 @@ export class JiraScheduler {
|
||||
}
|
||||
|
||||
this.isRunning = false;
|
||||
this.currentUserId = null;
|
||||
console.log('🛑 Jira scheduler stopped');
|
||||
}
|
||||
|
||||
/**
|
||||
* Redémarre le planificateur (utile lors des changements de config)
|
||||
*/
|
||||
async restart(): Promise<void> {
|
||||
async restart(userId?: string): Promise<void> {
|
||||
this.stop();
|
||||
await this.start();
|
||||
await this.start(userId);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -80,12 +83,12 @@ export class JiraScheduler {
|
||||
/**
|
||||
* Effectue une synchronisation planifiée
|
||||
*/
|
||||
private async performScheduledSync(): Promise<void> {
|
||||
private async performScheduledSync(userId: string = 'default'): Promise<void> {
|
||||
try {
|
||||
console.log('🔄 Starting scheduled Jira sync...');
|
||||
|
||||
// Récupérer la config Jira
|
||||
const jiraConfig = await userPreferencesService.getJiraConfig('default');
|
||||
const jiraConfig = await userPreferencesService.getJiraConfig(userId);
|
||||
|
||||
if (!jiraConfig.enabled || !jiraConfig.baseUrl || !jiraConfig.email || !jiraConfig.apiToken) {
|
||||
console.log('⚠️ Jira config incomplete, skipping scheduled sync');
|
||||
@@ -152,11 +155,11 @@ export class JiraScheduler {
|
||||
/**
|
||||
* Récupère la configuration du scheduler depuis les user preferences
|
||||
*/
|
||||
private async getConfig(): Promise<JiraSchedulerConfig> {
|
||||
private async getConfig(userId: string = 'default'): Promise<JiraSchedulerConfig> {
|
||||
try {
|
||||
const [jiraConfig, schedulerConfig] = await Promise.all([
|
||||
userPreferencesService.getJiraConfig('default'),
|
||||
userPreferencesService.getJiraSchedulerConfig('default')
|
||||
userPreferencesService.getJiraConfig(userId),
|
||||
userPreferencesService.getJiraSchedulerConfig(userId)
|
||||
]);
|
||||
|
||||
return {
|
||||
@@ -179,9 +182,10 @@ export class JiraScheduler {
|
||||
/**
|
||||
* Obtient les stats du planificateur
|
||||
*/
|
||||
async getStatus() {
|
||||
const config = await this.getConfig();
|
||||
const jiraConfig = await userPreferencesService.getJiraConfig('default');
|
||||
async getStatus(userId?: string) {
|
||||
const targetUserId = userId || 'default';
|
||||
const config = await this.getConfig(targetUserId);
|
||||
const jiraConfig = await userPreferencesService.getJiraConfig(targetUserId);
|
||||
|
||||
return {
|
||||
isRunning: this.isRunning,
|
||||
|
||||
Reference in New Issue
Block a user