All files / src/components/Automation AutomationPanel.tsx

0% Statements 0/331
0% Branches 0/1
0% Functions 0/1
0% Lines 0/331

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 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               
/**
 * AutomationPanel - Unified Automation Entry Point
 *
 * Combines Pipelines, Hands and Workflows into a single unified view,
 * with category filtering, batch operations, and scheduling.
 *
 * @module components/Automation/AutomationPanel
 */
 
import { useState, useEffect, useCallback, useMemo } from 'react';
import { useHandStore } from '../../store/handStore';
import { useWorkflowStore } from '../../store/workflowStore';
import {
  type AutomationItem,
  type CategoryType,
  type CategoryStats,
  adaptToAutomationItems,
  calculateCategoryStats,
  filterByCategory,
  searchAutomationItems,
} from '../../types/automation';
import { AutomationCard } from './AutomationCard';
import { AutomationFilters } from './AutomationFilters';
import { BatchActionBar } from './BatchActionBar';
import { PipelinesPanel } from '../PipelinesPanel';
import {
  Zap,
  RefreshCw,
  Plus,
  Calendar,
  Search,
  X,
  Package,
  Bot,
  Workflow,
} from 'lucide-react';
import { useToast } from '../ui/Toast';
 
// === View Mode ===
 
type ViewMode = 'grid' | 'list';
 
// === Tab Type ===
 
type AutomationTab = 'pipelines' | 'hands' | 'workflows';
 
// === Component Props ===
 
interface AutomationPanelProps {
  initialCategory?: CategoryType;
  initialTab?: AutomationTab;
  onSelect?: (item: AutomationItem) => void;
  showBatchActions?: boolean;
}
 
// === Tab Configuration ===
 
const TAB_CONFIG: { key: AutomationTab; label: string; icon: React.ComponentType<{ className?: string }> }[] = [
  { key: 'pipelines', label: 'Pipelines', icon: Package },
  { key: 'hands', label: 'Hands', icon: Bot },
  { key: 'workflows', label: 'Workflows', icon: Workflow },
];
 
// === Main Component ===
 
export function AutomationPanel({
  initialCategory = 'all',
  initialTab = 'pipelines',
  onSelect,
  showBatchActions = true,
}: AutomationPanelProps) {
  // Store state - use domain stores
  const hands = useHandStore((s) => s.hands);
  const workflows = useWorkflowStore((s) => s.workflows);
  const handLoading = useHandStore((s) => s.isLoading);
  const workflowLoading = useWorkflowStore((s) => s.isLoading);
  const isLoading = handLoading || workflowLoading;
  const loadHands = useHandStore((s) => s.loadHands);
  const loadWorkflows = useWorkflowStore((s) => s.loadWorkflows);
  const triggerHand = useHandStore((s) => s.triggerHand);
  const triggerWorkflow = useWorkflowStore((s) => s.triggerWorkflow);
 
  // UI state
  const [activeTab, setActiveTab] = useState<AutomationTab>(initialTab);
  const [selectedCategory, setSelectedCategory] = useState<CategoryType>(initialCategory);
  const [searchQuery, setSearchQuery] = useState('');
  const [viewMode, setViewMode] = useState<ViewMode>('grid');
  const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set());
  const [executingIds, setExecutingIds] = useState<Set<string>>(new Set());
  const [showWorkflowDialog, setShowWorkflowDialog] = useState(false);
  const [showSchedulerDialog, setShowSchedulerDialog] = useState(false);
 
  const { toast } = useToast();
 
  // Load data on mount
  useEffect(() => {
    loadHands();
    loadWorkflows();
  }, [loadHands, loadWorkflows]);
 
  // Adapt hands and workflows to automation items
  const automationItems = useMemo<AutomationItem[]>(() => {
    return adaptToAutomationItems(hands, workflows);
  }, [hands, workflows]);
 
  // Calculate category stats
  const categoryStats = useMemo<CategoryStats>(() => {
    return calculateCategoryStats(automationItems);
  }, [automationItems]);
 
  // Filter and search items
  const filteredItems = useMemo<AutomationItem[]>(() => {
    let items = filterByCategory(automationItems, selectedCategory);
    if (searchQuery.trim()) {
      items = searchAutomationItems(items, searchQuery);
    }
    // Filter by tab
    if (activeTab === 'hands') {
      items = items.filter(item => item.type === 'hand');
    } else if (activeTab === 'workflows') {
      items = items.filter(item => item.type === 'workflow');
    }
    return items;
  }, [automationItems, selectedCategory, searchQuery, activeTab]);
 
  // Selection handlers
  const handleSelect = useCallback((id: string, selected: boolean) => {
    setSelectedIds(prev => {
      const next = new Set(prev);
      if (selected) {
        next.add(id);
      } else {
        next.delete(id);
      }
      return next;
    });
  }, []);
 
  const handleSelectAll = useCallback(() => {
    setSelectedIds(new Set(filteredItems.map(item => item.id)));
  }, [filteredItems]);
 
  const handleDeselectAll = useCallback(() => {
    setSelectedIds(new Set());
  }, []);
 
  // Workflow dialog handlers
  const handleCreateWorkflow = useCallback(() => {
    setShowWorkflowDialog(true);
  }, []);
 
  const handleSchedulerManage = useCallback(() => {
    setShowSchedulerDialog(true);
  }, []);
 
  // Execute handler
  const handleExecute = useCallback(async (item: AutomationItem, params?: Record<string, unknown>) => {
    setExecutingIds(prev => new Set(prev).add(item.id));
 
    try {
      if (item.type === 'hand') {
        await triggerHand(item.id, params);
      } else {
        await triggerWorkflow(item.id, params);
      }
      toast(`${item.name} 执行成功`, 'success');
    } catch (err) {
      const errorMsg = err instanceof Error ? err.message : String(err);
      toast(`${item.name} 执行失败: ${errorMsg}`, 'error');
    } finally {
      setExecutingIds(prev => {
        const next = new Set(prev);
        next.delete(item.id);
        return next;
      });
    }
  }, [triggerHand, triggerWorkflow, toast]);
 
  // Batch execute
  const handleBatchExecute = useCallback(async () => {
    const itemsToExecute = filteredItems.filter(item => selectedIds.has(item.id));
    let successCount = 0;
    let failCount = 0;
 
    for (const item of itemsToExecute) {
      try {
        if (item.type === 'hand') {
          await triggerHand(item.id);
        } else {
          await triggerWorkflow(item.id);
        }
        successCount++;
      } catch {
        failCount++;
      }
    }
 
    if (successCount > 0) {
      toast(`成功执行 ${successCount} 个项目`, 'success');
    }
    if (failCount > 0) {
      toast(`${failCount} 个项目执行失败`, 'error');
    }
 
    setSelectedIds(new Set());
  }, [filteredItems, selectedIds, triggerHand, triggerWorkflow, toast]);
 
  // Refresh handler
  const handleRefresh = useCallback(async () => {
    await Promise.all([loadHands(), loadWorkflows()]);
    toast('数据已刷新', 'success');
  }, [loadHands, loadWorkflows, toast]);
 
  // If Pipelines tab is active, show PipelinesPanel directly
  if (activeTab === 'pipelines') {
    return (
      <div className="flex flex-col h-full">
        {/* Header with Tabs */}
        <div className="flex items-center justify-between px-4 py-3 border-b border-gray-200 dark:border-gray-700">
          <div className="flex items-center gap-2">
            <Package className="w-5 h-5 text-blue-500" />
            <h2 className="text-lg font-semibold text-gray-900 dark:text-white">
              自动化
            </h2>
          </div>
          {/* Tab Switcher */}
          <div className="flex items-center bg-gray-100 dark:bg-gray-800 rounded-lg p-1">
            {TAB_CONFIG.map(({ key, label, icon: Icon }) => (
              <button
                key={key}
                onClick={() => setActiveTab(key)}
                className={`flex items-center gap-1.5 px-3 py-1.5 text-sm font-medium rounded-md transition-colors ${
                  activeTab === key
                    ? 'bg-white dark:bg-gray-700 text-gray-900 dark:text-white shadow-sm'
                    : 'text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-200'
                }`}
              >
                <Icon className="w-4 h-4" />
                {label}
              </button>
            ))}
          </div>
        </div>
 
        {/* Pipelines Panel */}
        <div className="flex-1 overflow-hidden">
          <PipelinesPanel />
        </div>
      </div>
    );
  }
 
  // Hands and Workflows tabs
  return (
    <div className="flex flex-col h-full">
      {/* Header */}
      <div className="flex items-center justify-between px-4 py-3 border-b border-gray-200 dark:border-gray-700">
        <div className="flex items-center gap-2">
          <Zap className="w-5 h-5 text-orange-500" />
          <h2 className="text-lg font-semibold text-gray-900 dark:text-white">
            自动化
          </h2>
          <span className="text-sm text-gray-500 dark:text-gray-400">
            ({automationItems.length})
          </span>
        </div>
        <div className="flex items-center gap-2">
          {/* Tab Switcher */}
          <div className="flex items-center bg-gray-100 dark:bg-gray-800 rounded-lg p-1 mr-2">
            {TAB_CONFIG.map(({ key, label, icon: Icon }) => (
              <button
                key={key}
                onClick={() => setActiveTab(key)}
                className={`flex items-center gap-1.5 px-3 py-1.5 text-sm font-medium rounded-md transition-colors ${
                  activeTab === key
                    ? 'bg-white dark:bg-gray-700 text-gray-900 dark:text-white shadow-sm'
                    : 'text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-200'
                }`}
              >
                <Icon className="w-4 h-4" />
                {label}
              </button>
            ))}
          </div>
          <button
            onClick={handleRefresh}
            disabled={isLoading}
            className="p-2 text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-300 disabled:opacity-50"
            title="刷新"
          >
            <RefreshCw className={`w-4 h-4 ${isLoading ? 'animate-spin' : ''}`} />
          </button>
          <button
            onClick={handleCreateWorkflow}
            className="p-2 text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-300"
            title="新建工作流"
          >
            <Plus className="w-4 h-4" />
          </button>
          <button
            onClick={handleSchedulerManage}
            className="p-2 text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-300"
            title="调度管理"
          >
            <Calendar className="w-4 h-4" />
          </button>
        </div>
      </div>
 
      {/* Filters */}
      <AutomationFilters
        selectedCategory={selectedCategory}
        onCategoryChange={setSelectedCategory}
        searchQuery={searchQuery}
        onSearchChange={setSearchQuery}
        viewMode={viewMode}
        onViewModeChange={setViewMode}
        categoryStats={categoryStats}
      />
 
      {/* Content */}
      <div className="flex-1 overflow-y-auto p-4">
        {isLoading && automationItems.length === 0 ? (
          <div className="flex items-center justify-center h-32">
            <RefreshCw className="w-6 h-6 animate-spin text-gray-400" />
          </div>
        ) : filteredItems.length === 0 ? (
          <div className="flex flex-col items-center justify-center h-32 text-center">
            <Search className="w-8 h-8 text-gray-400 mb-2" />
            <p className="text-sm text-gray-500 dark:text-gray-400">
              {searchQuery ? '没有找到匹配的项目' : '暂无自动化项目'}
            </p>
          </div>
        ) : (
          <div className={
            viewMode === 'grid'
              ? 'grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4'
              : 'flex flex-col gap-2'
          }>
            {filteredItems.map(item => (
              <AutomationCard
                key={item.id}
                item={item}
                viewMode={viewMode}
                isSelected={selectedIds.has(item.id)}
                isExecuting={executingIds.has(item.id)}
                onSelect={(selected) => handleSelect(item.id, selected)}
                onExecute={(params) => handleExecute(item, params)}
                onClick={() => onSelect?.(item)}
              />
            ))}
          </div>
        )}
      </div>
 
      {/* Batch Actions */}
      {showBatchActions && selectedIds.size > 0 && (
        <BatchActionBar
          selectedCount={selectedIds.size}
          totalCount={filteredItems.length}
          onSelectAll={handleSelectAll}
          onDeselectAll={handleDeselectAll}
          onBatchExecute={handleBatchExecute}
          onBatchSchedule={() => {
            toast('批量调度功能开发中', 'info');
          }}
        />
      )}
 
      {/* Create Workflow Dialog */}
      {showWorkflowDialog && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
          <div className="bg-white dark:bg-gray-800 rounded-lg shadow-xl w-full max-w-md mx-4">
            <div className="flex items-center justify-between p-4 border-b border-gray-200 dark:border-gray-700">
              <h3 className="text-lg font-semibold text-gray-900 dark:text-white">新建工作流</h3>
              <button
                onClick={() => setShowWorkflowDialog(false)}
                className="p-1 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300"
              >
                <X className="w-5 h-5" />
              </button>
            </div>
            <div className="p-4">
              <div className="space-y-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                    工作流名称
                  </label>
                  <input
                    type="text"
                    placeholder="输入工作流名称..."
                    className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:outline-none focus:ring-2 focus:ring-gray-400"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                    描述
                  </label>
                  <textarea
                    placeholder="描述这个工作流的用途..."
                    rows={3}
                    className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:outline-none focus:ring-2 focus:ring-gray-400 resize-none"
                  />
                </div>
              </div>
            </div>
            <div className="flex justify-end gap-2 p-4 border-t border-gray-200 dark:border-gray-700">
              <button
                onClick={() => setShowWorkflowDialog(false)}
                className="px-4 py-2 text-sm text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg"
              >
                取消
              </button>
              <button
                onClick={() => {
                  toast('工作流创建功能开发中', 'info');
                  setShowWorkflowDialog(false);
                }}
                className="px-4 py-2 text-sm bg-gray-700 dark:bg-gray-600 text-white rounded-lg hover:bg-gray-800 dark:hover:bg-gray-500"
              >
                创建
              </button>
            </div>
          </div>
        </div>
      )}
 
      {/* Scheduler Dialog */}
      {showSchedulerDialog && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
          <div className="bg-white dark:bg-gray-800 rounded-lg shadow-xl w-full max-w-lg mx-4">
            <div className="flex items-center justify-between p-4 border-b border-gray-200 dark:border-gray-700">
              <h3 className="text-lg font-semibold text-gray-900 dark:text-white">调度管理</h3>
              <button
                onClick={() => setShowSchedulerDialog(false)}
                className="p-1 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300"
              >
                <X className="w-5 h-5" />
              </button>
            </div>
            <div className="p-4">
              <div className="text-center py-8 text-gray-500 dark:text-gray-400">
                <Calendar className="w-12 h-12 mx-auto mb-3 opacity-50" />
                <p>调度管理功能开发中</p>
                <p className="text-sm mt-1">将支持定时执行、Cron 表达式配置等</p>
              </div>
            </div>
            <div className="flex justify-end p-4 border-t border-gray-200 dark:border-gray-700">
              <button
                onClick={() => setShowSchedulerDialog(false)}
                className="px-4 py-2 text-sm text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg"
              >
                关闭
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
 
export default AutomationPanel;