All files / apps/web/src/backoffice/pages Jobs.jsx

0% Statements 0/73
0% Branches 0/61
0% Functions 0/26
0% Lines 0/71

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     
import { useState } from 'react';
import { useSearchParams } from 'react-router-dom';
import { useQuery, useMutation } from '@tanstack/react-query';
import {
  Search,
  Filter,
  Square,
  RefreshCw,
  Eye,
  Clock,
  CheckCircle,
  XCircle,
  AlertCircle,
  Wand2,
} from 'lucide-react';
import api from '../../services/api';
import toast from 'react-hot-toast';
import JobResultsModal from '../components/JobResultsModal';
import { useOrganizationStore } from '../../store/organizationStore';
import { PHASE_COLORS, PHASE_LABELS } from '../../constants/phases';
 
const StatusBadge = ({ status }) => {
  const config = {
    pending: { color: 'bg-blue-100 text-blue-800', icon: Clock },
    running: { color: 'bg-yellow-100 text-yellow-800', icon: RefreshCw },
    completed: { color: 'bg-green-100 text-green-800', icon: CheckCircle },
    failed: { color: 'bg-red-100 text-red-800', icon: XCircle },
    cancelled: { color: 'bg-gray-100 text-gray-800', icon: AlertCircle },
    terminated: { color: 'bg-purple-100 text-purple-800', icon: AlertCircle }
  };
 
  const normalizedStatus = status?.toLowerCase() || 'pending';
  const { color, icon: Icon } = config[normalizedStatus] || config.pending;
 
  return (
    <span className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${color}`}>
      <Icon className="w-3 h-3 mr-1" />
      {status}
    </span>
  );
};
 
export default function JobsManagement() {
  const { currentOrganization } = useOrganizationStore();
  const organizationId = currentOrganization?.id;
  const [searchParams] = useSearchParams();
  const filterScheduleId = searchParams.get('scheduleId');
  const [searchTerm, setSearchTerm] = useState('');
  const [statusFilter, setStatusFilter] = useState(filterScheduleId ? 'all' : 'all');
  const [jobType, setJobType] = useState('all');
  const [showCleanupModal, setShowCleanupModal] = useState(false);
  const [cleanupForm, setCleanupForm] = useState({ taskQueue: '', olderThanHours: 24 });
  
  // View modal state
  const [selectedJob, setSelectedJob] = useState(null);
  const [showViewModal, setShowViewModal] = useState(false);
  const [viewJobResults, setViewJobResults] = useState(null);
 
  // Fetch all jobs from job-manager
  const { data: allJobs, isLoading, refetch, error } = useQuery({
    queryKey: ['jobs', organizationId, filterScheduleId],
    queryFn: async () => {
      const params = new URLSearchParams({ limit: '100' });
      if (filterScheduleId) params.set('scheduleId', filterScheduleId);
      const response = await api.get(`/${organizationId}/jobs?${params.toString()}`);
      return response.data.data?.jobs || [];
    }
  });
 
  // Cancel job mutation
  const cancelJob = useMutation({
    mutationFn: async ({ workflowId, type }) => {
      toast.error('Annulation via Temporal UI ou API requise');
    },
    onSuccess: () => {
    }
  });
 
  // Cleanup old jobs mutation
  const cleanupJobs = useMutation({
    mutationFn: async ({ taskQueue, olderThanHours }) => {
      const response = await api.post(`/${organizationId}/jobs/cleanup`, { taskQueue, olderThanHours });
      return response.data.data;
    },
    onSuccess: (data) => {
      refetch();
      const total = (data.deletedRedisCrawler || 0) + (data.deletedRedisWorkflow || 0) + (data.deletedMongoCrawljobs || 0) + (data.deletedMongoJobs || 0);
      toast.success(`${total} jobs nettoyés`);
    },
    onError: (error) => {
      toast.error(`Erreur cleanup: ${error.message}`);
    }
  });
 
  // Fetch job results for view modal
  const fetchJobResults = async (job) => {
    if (!job?.workflowId) return;
    
    setSelectedJob(job);
    
    try {
      const response = await api.get(`/jobs/${job.workflowId}/results`);
      // API returns data directly at response.data (not response.data.data)
      const data = response.data?.data || response.data || {};
      setViewJobResults({
        ...job,
        ...data
      });
      setShowViewModal(true);
    } catch (error) {
      console.error('Error fetching job results:', error);
      toast.error('Erreur lors du chargement des résultats');
    }
  };
 
  // Handle view action
  const handleView = (job) => {
    fetchJobResults(job);
  };
 
  // Filter jobs
  const filteredJobs = allJobs?.filter(job => {
    const matchesSearch = 
      job.workflowId?.toLowerCase().includes(searchTerm.toLowerCase()) ||
      job.type?.toLowerCase().includes(searchTerm.toLowerCase());
    
    const matchesStatus = statusFilter === 'all' || job.status?.toLowerCase() === statusFilter;
    const matchesType = jobType === 'all' || job.type === jobType;
    
    return matchesSearch && matchesStatus && matchesType;
  });
 
  if (isLoading) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-indigo-600"></div>
      </div>
    );
  }
 
  if (error) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="text-center text-red-600">
          <p>Erreur de chargement des jobs</p>
          <p className="text-sm">{error.message}</p>
        </div>
      </div>
    );
  }
 
  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-2xl font-bold text-gray-900">Gestion des Jobs</h2>
          <p className="text-gray-600">{allJobs?.length || 0} jobs au total</p>
        </div>
        <div className="flex gap-2">
          <button
            onClick={() => refetch()}
            className="flex items-center px-4 py-2 bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200"
          >
            <RefreshCw className="w-5 h-5 mr-2" />
            Actualiser
          </button>
          <button
            onClick={() => setShowCleanupModal(true)}
            className="flex items-center px-4 py-2 bg-orange-100 text-orange-700 rounded-lg hover:bg-orange-200"
          >
            <Wand2 className="w-5 h-5 mr-2" />
            Nettoyer
          </button>
        </div>
      </div>
 
      {/* Cleanup Modal */}
      {showCleanupModal && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
          <div className="bg-white rounded-lg p-6 w-full max-w-md">
            <h3 className="text-lg font-semibold mb-4">Nettoyer les jobs fermés</h3>
            <div className="space-y-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Type de job</label>
                <select
                  value={cleanupForm.taskQueue}
                  onChange={(e) => setCleanupForm({ ...cleanupForm, taskQueue: e.target.value })}
                  className="w-full border border-gray-300 rounded-lg px-3 py-2"
                >
                  <option value="">Tous les types</option>
                  <option value="crawler">Crawler</option>
                  <option value="workflow">Workflow</option>
                </select>
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Jobs fermés depuis plus de (heures)</label>
                <input
                  type="number"
                  min="0"
                  max="720"
                  value={cleanupForm.olderThanHours}
                  onChange={(e) => setCleanupForm({ ...cleanupForm, olderThanHours: parseInt(e.target.value) || 0 })}
                  className="w-full border border-gray-300 rounded-lg px-3 py-2"
                />
                <p className="text-xs text-gray-500 mt-1">0 = supprime tous les jobs fermés</p>
              </div>
            </div>
            <div className="flex justify-end gap-3 mt-6">
              <button
                onClick={() => setShowCleanupModal(false)}
                className="px-4 py-2 text-gray-700 bg-gray-100 rounded-lg hover:bg-gray-200"
              >
                Annuler
              </button>
              <button
                onClick={() => {
                  cleanupJobs.mutate(cleanupForm);
                  setShowCleanupModal(false);
                }}
                disabled={cleanupJobs.isPending}
                className="px-4 py-2 bg-orange-600 text-white rounded-lg hover:bg-orange-700 disabled:opacity-50"
              >
                {cleanupJobs.isPending ? 'Nettoyage...' : 'Nettoyer'}
              </button>
            </div>
          </div>
        </div>
      )}
 
      {/* View Results Modal - Unified for all job types */}
      {showViewModal && viewJobResults && (
        <JobResultsModal
          isOpen={showViewModal}
          onClose={() => {
            setShowViewModal(false);
            setSelectedJob(null);
            setViewJobResults(null);
          }}
          job={viewJobResults}
        />
      )}
 
      {/* Filters */}
      <div className="flex flex-col sm:flex-row gap-4">
        <div className="relative flex-1">
          <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-5 h-5" />
          <input
            type="text"
            placeholder="Rechercher un job..."
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
            className="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-transparent"
          />
        </div>
        <div className="flex items-center space-x-2">
          <Filter className="w-5 h-5 text-gray-400" />
          <select
            value={jobType}
            onChange={(e) => setJobType(e.target.value)}
            className="border border-gray-300 rounded-lg px-4 py-2 focus:ring-2 focus:ring-indigo-500 focus:border-transparent"
          >
            <option value="all">Tous les types</option>
            <option value="crawler">Crawler</option>
            <option value="workflow">Workflow</option>
          </select>
          <select
            value={statusFilter}
            onChange={(e) => setStatusFilter(e.target.value)}
            className="border border-gray-300 rounded-lg px-4 py-2 focus:ring-2 focus:ring-indigo-500 focus:border-transparent"
          >
            <option value="all">Tous les statuts</option>
            <option value="running">En cours</option>
            <option value="pending">En attente</option>
            <option value="completed">Terminés</option>
            <option value="failed">Échoués</option>
            <option value="cancelled">Annulés</option>
          </select>
        </div>
      </div>
 
      {/* Jobs Table */}
      <div className="bg-white rounded-lg shadow overflow-hidden">
        <div className="overflow-x-auto">
          <table className="min-w-full divide-y divide-gray-200">
            <thead className="bg-gray-50">
              <tr>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  Workflow ID
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  Type
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  Statut
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  Activités
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  Start
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  Closed
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  Actions
                </th>
              </tr>
            </thead>
            <tbody className="bg-white divide-y divide-gray-200">
              {filteredJobs?.map((job) => (
                <tr key={job.workflowId} className="hover:bg-gray-50">
                  <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">
                    {job.workflowId?.substring(0, 12)}...
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                    <span className={`px-2 py-1 rounded text-xs ${
                      job.taskQueue === 'crawler-workflows' ? 'bg-blue-100 text-blue-800' : 'bg-green-100 text-green-800'
                    }`}>
                      {job.taskQueue === 'crawler-workflows' ? 'Crawler' : 'Workflow'}
                    </span>
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap">
                    <StatusBadge status={job.status?.toLowerCase()} />
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap">
                    <div className="flex items-center gap-1.5">
                      {job.phases?.filter(p => PHASE_COLORS[p]).map((phase) => (
                        <span
                          key={phase}
                          className={`inline-block w-2.5 h-2.5 rounded-full ${PHASE_COLORS[phase]} cursor-help`}
                          title={PHASE_LABELS[phase] || phase}
                        />
                      ))}
                    </div>
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                    {job.startTime ? new Date(job.startTime).toLocaleString() : '-'}
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                    {job.closeTime ? new Date(job.closeTime).toLocaleString() : '-'}
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap text-sm font-medium">
                    <div className="flex items-center space-x-2">
                      <button
                        onClick={() => handleView(job)}
                        className="text-indigo-600 hover:text-indigo-900 p-1"
                        title="Voir les détails"
                      >
                        <Eye className="w-4 h-4" />
                      </button>
                      {job.status === 'Running' && (
                        <button
                          onClick={() => cancelJob.mutate({ workflowId: job.workflowId, type: job.type })}
                          className="text-yellow-600 hover:text-yellow-900 p-1"
                          title="Arrêter"
                        >
                          <Square className="w-4 h-4" />
                        </button>
                      )}
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
 
      {/* Empty state */}
      {filteredJobs?.length === 0 && (
        <div className="text-center py-12 bg-gray-50 rounded-lg">
          <p className="text-gray-500">Aucun job trouvé</p>
        </div>
      )}
    </div>
  );
}