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) {
|
switch (action) {
|
||||||
case 'scheduler':
|
case 'scheduler':
|
||||||
if (params.enabled) {
|
if (params.enabled) {
|
||||||
await jiraScheduler.start();
|
await jiraScheduler.start(session.user.id);
|
||||||
} else {
|
} else {
|
||||||
jiraScheduler.stop();
|
jiraScheduler.stop();
|
||||||
}
|
}
|
||||||
return NextResponse.json({
|
return NextResponse.json({
|
||||||
success: true,
|
success: true,
|
||||||
data: await jiraScheduler.getStatus()
|
data: await jiraScheduler.getStatus(session.user.id)
|
||||||
});
|
});
|
||||||
|
|
||||||
case 'config':
|
case 'config':
|
||||||
@@ -45,11 +45,11 @@ export async function POST(request: Request) {
|
|||||||
params.jiraSyncInterval
|
params.jiraSyncInterval
|
||||||
);
|
);
|
||||||
// Redémarrer le scheduler si la config a changé
|
// Redémarrer le scheduler si la config a changé
|
||||||
await jiraScheduler.restart();
|
await jiraScheduler.restart(session.user.id);
|
||||||
return NextResponse.json({
|
return NextResponse.json({
|
||||||
success: true,
|
success: true,
|
||||||
message: 'Configuration scheduler mise à jour',
|
message: 'Configuration scheduler mise à jour',
|
||||||
data: await jiraScheduler.getStatus()
|
data: await jiraScheduler.getStatus(session.user.id)
|
||||||
});
|
});
|
||||||
|
|
||||||
default:
|
default:
|
||||||
@@ -99,18 +99,36 @@ export async function POST(request: Request) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Effectuer la synchronisation
|
// 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({
|
return NextResponse.json({
|
||||||
message: 'Synchronisation Jira terminée avec succès',
|
message: 'Synchronisation Jira terminée avec succès',
|
||||||
data: result
|
data: jiraSyncResult
|
||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
return NextResponse.json(
|
return NextResponse.json(
|
||||||
{
|
{
|
||||||
error: 'Synchronisation Jira terminée avec des erreurs',
|
error: 'Synchronisation Jira terminée avec des erreurs',
|
||||||
data: result
|
data: jiraSyncResult
|
||||||
},
|
},
|
||||||
{ status: 207 } // Multi-Status
|
{ status: 207 } // Multi-Status
|
||||||
);
|
);
|
||||||
@@ -180,8 +198,8 @@ export async function GET() {
|
|||||||
projectValidation = await jiraService.validateProject(jiraConfig.projectKey);
|
projectValidation = await jiraService.validateProject(jiraConfig.projectKey);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Récupérer aussi le statut du scheduler
|
// Récupérer aussi le statut du scheduler avec l'utilisateur connecté
|
||||||
const schedulerStatus = await jiraScheduler.getStatus();
|
const schedulerStatus = await jiraScheduler.getStatus(session.user.id);
|
||||||
|
|
||||||
return NextResponse.json({
|
return NextResponse.json({
|
||||||
connected,
|
connected,
|
||||||
|
|||||||
@@ -39,8 +39,8 @@ export function JiraSchedulerConfig({ className = "" }: JiraSchedulerConfigProps
|
|||||||
setError(null);
|
setError(null);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// Utiliser isEnabled au lieu de isRunning pour l'activation
|
// Utiliser isRunning au lieu de isEnabled pour l'activation
|
||||||
const newStatus = await jiraClient.updateSchedulerConfig(!schedulerStatus.isEnabled, schedulerStatus.interval);
|
const newStatus = await jiraClient.updateSchedulerConfig(!schedulerStatus.isRunning, schedulerStatus.interval);
|
||||||
setSchedulerStatus(newStatus);
|
setSchedulerStatus(newStatus);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
setError(err instanceof Error ? err.message : 'Erreur lors du toggle scheduler');
|
setError(err instanceof Error ? err.message : 'Erreur lors du toggle scheduler');
|
||||||
@@ -104,8 +104,8 @@ export function JiraSchedulerConfig({ className = "" }: JiraSchedulerConfigProps
|
|||||||
|
|
||||||
const getIntervalText = (interval: string) => {
|
const getIntervalText = (interval: string) => {
|
||||||
switch (interval) {
|
switch (interval) {
|
||||||
case 'hourly': return 'Toutes les heures';
|
case 'hourly': return 'Horaire';
|
||||||
case 'daily': return 'Quotidienne';
|
case 'daily': return 'Quotidien';
|
||||||
case 'weekly': return 'Hebdomadaire';
|
case 'weekly': return 'Hebdomadaire';
|
||||||
default: return interval;
|
default: return interval;
|
||||||
}
|
}
|
||||||
@@ -165,12 +165,12 @@ export function JiraSchedulerConfig({ className = "" }: JiraSchedulerConfigProps
|
|||||||
<div className="flex items-center justify-between">
|
<div className="flex items-center justify-between">
|
||||||
<span className="text-sm font-medium">Synchronisation automatique</span>
|
<span className="text-sm font-medium">Synchronisation automatique</span>
|
||||||
<Button
|
<Button
|
||||||
variant={schedulerStatus.isEnabled ? "danger" : "primary"}
|
variant={schedulerStatus.isRunning ? "danger" : "primary"}
|
||||||
size="sm"
|
size="sm"
|
||||||
onClick={toggleScheduler}
|
onClick={toggleScheduler}
|
||||||
disabled={isLoading || !schedulerStatus.jiraConfigured}
|
disabled={isLoading || !schedulerStatus.jiraConfigured}
|
||||||
>
|
>
|
||||||
{schedulerStatus.isEnabled ? 'Désactiver' : 'Activer'}
|
{schedulerStatus.isRunning ? 'Désactiver' : 'Activer'}
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|||||||
@@ -10,17 +10,19 @@ export interface JiraSchedulerConfig {
|
|||||||
export class JiraScheduler {
|
export class JiraScheduler {
|
||||||
private timer: NodeJS.Timeout | null = null;
|
private timer: NodeJS.Timeout | null = null;
|
||||||
private isRunning = false;
|
private isRunning = false;
|
||||||
|
private currentUserId: string | null = null;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Démarre le planificateur de synchronisation Jira automatique
|
* Démarre le planificateur de synchronisation Jira automatique
|
||||||
*/
|
*/
|
||||||
async start(): Promise<void> {
|
async start(userId?: string): Promise<void> {
|
||||||
if (this.isRunning) {
|
if (this.isRunning) {
|
||||||
console.log('⚠️ Jira scheduler is already running');
|
console.log('⚠️ Jira scheduler is already running');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const config = await this.getConfig();
|
const targetUserId = userId || 'default';
|
||||||
|
const config = await this.getConfig(targetUserId);
|
||||||
|
|
||||||
if (!config.enabled) {
|
if (!config.enabled) {
|
||||||
console.log('📋 Automatic Jira sync is disabled');
|
console.log('📋 Automatic Jira sync is disabled');
|
||||||
@@ -28,8 +30,7 @@ export class JiraScheduler {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Vérifier que Jira est configuré
|
// Vérifier que Jira est configuré
|
||||||
// Pour les services système, on utilise un userId par défaut
|
const jiraConfig = await userPreferencesService.getJiraConfig(targetUserId);
|
||||||
const jiraConfig = await userPreferencesService.getJiraConfig('default');
|
|
||||||
if (!jiraConfig.enabled || !jiraConfig.baseUrl || !jiraConfig.email || !jiraConfig.apiToken) {
|
if (!jiraConfig.enabled || !jiraConfig.baseUrl || !jiraConfig.email || !jiraConfig.apiToken) {
|
||||||
console.log('⚠️ Jira not configured, scheduler cannot start');
|
console.log('⚠️ Jira not configured, scheduler cannot start');
|
||||||
return;
|
return;
|
||||||
@@ -42,11 +43,12 @@ export class JiraScheduler {
|
|||||||
|
|
||||||
// Planifier les synchronisations suivantes
|
// Planifier les synchronisations suivantes
|
||||||
this.timer = setInterval(() => {
|
this.timer = setInterval(() => {
|
||||||
this.performScheduledSync();
|
this.performScheduledSync(targetUserId);
|
||||||
}, intervalMs);
|
}, intervalMs);
|
||||||
|
|
||||||
this.isRunning = true;
|
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.isRunning = false;
|
||||||
|
this.currentUserId = null;
|
||||||
console.log('🛑 Jira scheduler stopped');
|
console.log('🛑 Jira scheduler stopped');
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Redémarre le planificateur (utile lors des changements de config)
|
* Redémarre le planificateur (utile lors des changements de config)
|
||||||
*/
|
*/
|
||||||
async restart(): Promise<void> {
|
async restart(userId?: string): Promise<void> {
|
||||||
this.stop();
|
this.stop();
|
||||||
await this.start();
|
await this.start(userId);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -80,12 +83,12 @@ export class JiraScheduler {
|
|||||||
/**
|
/**
|
||||||
* Effectue une synchronisation planifiée
|
* Effectue une synchronisation planifiée
|
||||||
*/
|
*/
|
||||||
private async performScheduledSync(): Promise<void> {
|
private async performScheduledSync(userId: string = 'default'): Promise<void> {
|
||||||
try {
|
try {
|
||||||
console.log('🔄 Starting scheduled Jira sync...');
|
console.log('🔄 Starting scheduled Jira sync...');
|
||||||
|
|
||||||
// Récupérer la config Jira
|
// 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) {
|
if (!jiraConfig.enabled || !jiraConfig.baseUrl || !jiraConfig.email || !jiraConfig.apiToken) {
|
||||||
console.log('⚠️ Jira config incomplete, skipping scheduled sync');
|
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
|
* 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 {
|
try {
|
||||||
const [jiraConfig, schedulerConfig] = await Promise.all([
|
const [jiraConfig, schedulerConfig] = await Promise.all([
|
||||||
userPreferencesService.getJiraConfig('default'),
|
userPreferencesService.getJiraConfig(userId),
|
||||||
userPreferencesService.getJiraSchedulerConfig('default')
|
userPreferencesService.getJiraSchedulerConfig(userId)
|
||||||
]);
|
]);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
@@ -179,9 +182,10 @@ export class JiraScheduler {
|
|||||||
/**
|
/**
|
||||||
* Obtient les stats du planificateur
|
* Obtient les stats du planificateur
|
||||||
*/
|
*/
|
||||||
async getStatus() {
|
async getStatus(userId?: string) {
|
||||||
const config = await this.getConfig();
|
const targetUserId = userId || 'default';
|
||||||
const jiraConfig = await userPreferencesService.getJiraConfig('default');
|
const config = await this.getConfig(targetUserId);
|
||||||
|
const jiraConfig = await userPreferencesService.getJiraConfig(targetUserId);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
isRunning: this.isRunning,
|
isRunning: this.isRunning,
|
||||||
|
|||||||
Reference in New Issue
Block a user