Files
canina/frontend/admin-panel/src/pages/ApprovalsPage.tsx
T

1047 lines
51 KiB
TypeScript
Executable File

import React, { useState, useEffect, useMemo } from 'react';
import {
CheckCircle2,
XCircle,
Play,
AlertTriangle,
RefreshCw,
DollarSign,
ShoppingCart,
Send,
Sliders,
Check,
X,
MessageSquare,
FileText,
Search,
ArrowUpDown,
ArrowUpRight,
Briefcase,
Filter,
CheckCheck,
Building2,
TrendingUp,
Server,
Copy,
ExternalLink,
ChevronDown,
ChevronUp,
Sparkles,
ShieldAlert,
ShieldCheck,
Stethoscope,
Cpu,
Headphones,
MessageCircle,
BarChart3,
AlertCircle,
Info,
Tag,
Layers,
Clock
} from 'lucide-react';
import toast from 'react-hot-toast';
import api from '../services/api';
interface ApprovalItem {
id: string;
department: string;
category: string;
title: string;
payload: any;
testContext?: any;
status: 'PENDING' | 'APPROVED' | 'REJECTED';
ceoNotes?: string;
createdAt: string;
executedAt?: string;
}
// Format numbers with Persian/locale separators
function formatNumber(num: number | string | undefined | null): string {
if (num === undefined || num === null || num === '') return '-';
const n = Number(num);
if (isNaN(n)) return String(num);
return n.toLocaleString('fa-IR');
}
// Convert Rial to Toman if number looks like Rial (> 100,000)
function formatMoney(amount: number | string | undefined | null): string {
if (amount === undefined || amount === null || amount === '') return '-';
const n = Number(amount);
if (isNaN(n)) return String(amount);
if (n >= 100000 && n % 10 === 0) {
const toman = Math.floor(n / 10);
return `${toman.toLocaleString('fa-IR')} تومان`;
}
return `${n.toLocaleString('fa-IR')} تومان`;
}
// Copy helper
function copyToClipboard(text: string, label = 'متن') {
navigator.clipboard.writeText(text);
toast.success(`${label} در کلیپ‌بورد کپی شد`);
}
// Smart Payload Visualizer
function StructuredPayloadViewer({ payload }: { payload: any }) {
const [showRawJson, setShowRawJson] = useState(false);
if (!payload || typeof payload !== 'object') {
return (
<div className="p-3 bg-gray-50 rounded-xl text-xs text-gray-700 font-mono">
{String(payload || 'داده‌ای ثبت نشده است')}
</div>
);
}
// 1. Detect Strategic 5-Part Proposal Pattern (e.g. 1_مسئله_و_شکاف_بازار, etc.)
const hasFivePart = Object.keys(payload).some(k =>
k.includes('مسئله') || k.includes('راه‌حل') || k.includes('اقدام') || k.includes('معیار')
);
// 2. Detect Pricing Pattern
const hasPricing = ('current_price' in payload || 'currentPrice' in payload || 'suggested_price' in payload || 'newPrice' in payload);
// 3. Detect SMS Campaign Pattern
const hasSms = ('sms_pattern' in payload || 'message_template' in payload || 'target_audience_count' in payload || 'target_count' in payload);
// 4. Detect B2B Offline Action / QA Defect Strategy Pattern
const hasQaDefects = ('qa_defects' in payload || 'qa_feedback' in payload || 'source_task_code' in payload);
// 5. Detect Production Release Pattern
const hasRelease = ('stage_qa_score' in payload || 'stage_qa_feedback' in payload || 'deliverable_url' in payload);
// 6. Detect Competitor Intelligence / Benchmark Pattern
const hasCompetitorBenchmark = ('key_findings' in payload || 'scraped_sources' in payload);
// 7. Detect B2B Clinical Targets Pattern
const hasB2BTargets = ('top_tier_targets' in payload || 'target_clinics_identified' in payload);
return (
<div className="space-y-3 font-vazir">
{/* 1. Five-Part Strategic Opportunity Proposal */}
{hasFivePart && (
<div className="space-y-2.5">
{/* Issue & Gap */}
{(payload['1_مسئله_و_شکاف_بازار'] || payload['مسئله_و_شکاف_بازار'] || payload['مسئله']) && (
<div className="p-3.5 bg-rose-50/70 border border-rose-200/80 rounded-xl">
<div className="flex items-center gap-2 text-rose-800 text-xs font-black mb-1.5">
<AlertCircle className="w-4 h-4 text-rose-600 shrink-0" />
<span>مسئله و شکاف شناسایی‌شده در بازار:</span>
</div>
<p className="text-xs text-gray-800 leading-relaxed font-medium">
{payload['1_مسئله_و_شکاف_بازار'] || payload['مسئله_و_شکاف_بازار'] || payload['مسئله']}
</p>
</div>
)}
{/* Solution & Canina Advantage */}
{(payload['2_راه‌حل_و_مزیت_کنینا'] || payload['راه‌حل_و_مزیت_کنینا'] || payload['راه‌حل']) && (
<div className="p-3.5 bg-emerald-50/70 border border-emerald-200/80 rounded-xl">
<div className="flex items-center gap-2 text-emerald-800 text-xs font-black mb-1.5">
<Sparkles className="w-4 h-4 text-emerald-600 shrink-0" />
<span>راه‌حل، محصول و مزیت رقابتی کنینا:</span>
</div>
<p className="text-xs text-gray-800 leading-relaxed font-medium">
{payload['2_راه‌حل_و_مزیت_کنینا'] || payload['راه‌حل_و_مزیت_کنینا'] || payload['راه‌حل']}
</p>
</div>
)}
{/* Operational Plan */}
{(payload['3_طرح_اقدام_عملیاتی'] || payload['طرح_اقدام_عملیاتی'] || payload['طرح_اقدام']) && (
<div className="p-3.5 bg-blue-50/70 border border-blue-200/80 rounded-xl">
<div className="flex items-center gap-2 text-blue-800 text-xs font-black mb-1.5">
<Layers className="w-4 h-4 text-blue-600 shrink-0" />
<span>طرح اقدام عملیاتی و همکاری بین‌بخشی:</span>
</div>
<p className="text-xs text-gray-800 leading-relaxed font-medium">
{payload['3_طرح_اقدام_عملیاتی'] || payload['طرح_اقدام_عملیاتی'] || payload['طرح_اقدام']}
</p>
</div>
)}
{/* Departments & Acceptance Criteria Row */}
<div className="grid grid-cols-1 md:grid-cols-2 gap-2.5">
{(payload['4_دپارتمان‌های_مسئول'] || payload['دپارتمان‌های_مسئول']) && (
<div className="p-3 bg-purple-50/60 border border-purple-200/70 rounded-xl flex items-center gap-2">
<UsersIcon className="w-4 h-4 text-purple-600 shrink-0" />
<span className="text-xs font-black text-purple-900 shrink-0">دپارتمان‌های مجری:</span>
<span className="text-xs font-bold text-purple-700 bg-white px-2 py-0.5 rounded-md border border-purple-200">
{payload['4_دپارتمان‌های_مسئول'] || payload['دپارتمان‌های_مسئول']}
</span>
</div>
)}
{(payload['5_معیار_پذیرش_و_تکمیل'] || payload['معیار_پذیرش_و_تکمیل']) && (
<div className="p-3 bg-amber-50/60 border border-amber-200/70 rounded-xl flex items-start gap-2">
<CheckCheck className="w-4 h-4 text-amber-600 shrink-0 mt-0.5" />
<div>
<span className="text-xs font-black text-amber-900 block mb-0.5">معیار پذیرش نهایی (QA Gate):</span>
<p className="text-xs text-gray-700 font-medium">
{payload['5_معیار_پذیرش_و_تکمیل'] || payload['معیار_پذیرش_و_تکمیل']}
</p>
</div>
</div>
)}
</div>
</div>
)}
{/* 2. Pricing & Torob Margin Comparison */}
{hasPricing && (
<div className="p-4 bg-gradient-to-br from-amber-50/60 to-orange-50/40 border border-amber-200/80 rounded-2xl space-y-3">
<div className="flex items-center justify-between border-b border-amber-200/60 pb-2">
<div className="flex items-center gap-2">
<DollarSign className="w-4 h-4 text-amber-600" />
<span className="text-xs font-black text-amber-900">محاسبه قیمت‌گذاری و سود ناخالص:</span>
</div>
{payload.product_name && (
<span className="text-xs font-bold text-gray-800 bg-white px-2.5 py-0.5 rounded-lg border border-amber-200">
{payload.product_name}
</span>
)}
</div>
<div className="grid grid-cols-2 sm:grid-cols-4 gap-2.5 text-center">
<div className="p-2.5 bg-white rounded-xl border border-gray-200/80 shadow-xs">
<span className="block text-[11px] text-gray-500 font-bold mb-1">قیمت فعلی سایت</span>
<span className="text-xs font-black text-gray-900 font-mono">
{formatMoney(payload.current_price || payload.currentPrice)}
</span>
</div>
<div className="p-2.5 bg-white rounded-xl border border-emerald-200 shadow-xs">
<span className="block text-[11px] text-emerald-700 font-bold mb-1">قیمت پیشنهادی جدید</span>
<span className="text-xs font-black text-emerald-700 font-mono">
{formatMoney(payload.suggested_price || payload.newPrice)}
</span>
</div>
<div className="p-2.5 bg-white rounded-xl border border-blue-200 shadow-xs">
<span className="block text-[11px] text-blue-700 font-bold mb-1">حاشیه سود تخمینی</span>
<span className="text-xs font-black text-blue-700 font-mono">
{payload.margin_percent ? `${payload.margin_percent}٪` : '-'}
</span>
</div>
<div className="p-2.5 bg-white rounded-xl border border-purple-200 shadow-xs">
<span className="block text-[11px] text-purple-700 font-bold mb-1">کف قیمت ترب</span>
<span className="text-xs font-black text-purple-700 font-mono">
{formatMoney(payload.competitor_min_torob)}
</span>
</div>
</div>
{payload.reason && (
<div className="text-xs text-gray-700 bg-white/80 p-2.5 rounded-xl border border-amber-100 flex items-start gap-1.5">
<Info className="w-3.5 h-3.5 text-amber-600 shrink-0 mt-0.5" />
<span><strong>استدلال بازرگانی:</strong> {payload.reason}</span>
</div>
)}
</div>
)}
{/* 3. SMS Campaign Preview */}
{hasSms && (
<div className="p-4 bg-gradient-to-br from-purple-50/60 to-indigo-50/40 border border-purple-200/80 rounded-2xl space-y-3">
<div className="flex items-center justify-between border-b border-purple-200/60 pb-2">
<div className="flex items-center gap-2">
<MessageCircle className="w-4 h-4 text-purple-600" />
<span className="text-xs font-black text-purple-900">پیش‌نمایش کمپین پیامکی CRM:</span>
</div>
{payload.campaign_name && (
<span className="text-xs font-bold text-purple-800 bg-white px-2.5 py-0.5 rounded-lg border border-purple-200">
{payload.campaign_name}
</span>
)}
</div>
{/* SMS Bubble */}
{(payload.message_template || payload.sms_pattern) && (
<div className="relative bg-white p-3.5 rounded-2xl border border-purple-200/90 shadow-sm max-w-xl mx-auto">
<div className="flex items-center justify-between text-[11px] text-gray-400 border-b border-gray-100 pb-1.5 mb-2 font-mono">
<span>الگوی متن پیامک با متغیرها</span>
<button
type="button"
onClick={() => copyToClipboard(payload.message_template || payload.sms_pattern, 'متن پیامک')}
className="flex items-center gap-1 text-purple-600 hover:text-purple-700 font-bold cursor-pointer"
>
<Copy className="w-3 h-3" />
<span>کپی متن</span>
</button>
</div>
<p className="text-xs text-gray-900 leading-relaxed font-bold font-vazir whitespace-pre-wrap">
{payload.message_template || payload.sms_pattern}
</p>
</div>
)}
{/* Campaign Metrics */}
<div className="grid grid-cols-2 sm:grid-cols-4 gap-2 text-center text-xs">
<div className="p-2 bg-white rounded-xl border border-gray-200">
<span className="block text-[10px] text-gray-500 font-bold">تعداد گیرندگان</span>
<span className="text-xs font-black text-gray-900 font-mono">
{formatNumber(payload.target_audience_count || payload.target_count)} کاربر
</span>
</div>
<div className="p-2 bg-white rounded-xl border border-gray-200">
<span className="block text-[10px] text-gray-500 font-bold">هزینه ارسال</span>
<span className="text-xs font-black text-rose-600 font-mono">
{formatMoney(payload.estimated_sms_cost_irr || payload.estimated_cost_irr)}
</span>
</div>
<div className="p-2 bg-white rounded-xl border border-gray-200">
<span className="block text-[10px] text-gray-500 font-bold">فروش پیش‌بینی‌شده</span>
<span className="text-xs font-black text-emerald-600 font-mono">
{formatMoney(payload.forecasted_revenue_irr || payload.expected_revenue_irr)}
</span>
</div>
<div className="p-2 bg-white rounded-xl border border-gray-200">
<span className="block text-[10px] text-gray-500 font-bold">نرخ تبدیل</span>
<span className="text-xs font-black text-purple-700 font-mono">
{payload.forecasted_conversion || payload.expected_conversion_rate || '-'}
</span>
</div>
</div>
</div>
)}
{/* 4. Production Release & QA Stage Gate Review */}
{hasRelease && (
<div className="p-4 bg-emerald-50/70 border border-emerald-200 rounded-2xl space-y-3">
<div className="flex items-center justify-between border-b border-emerald-200 pb-2">
<div className="flex items-center gap-2">
<Server className="w-4 h-4 text-emerald-600" />
<span className="text-xs font-black text-emerald-950">گواهی تست آزمون استیجینگ و تاییدیه QA:</span>
</div>
{payload.stage_qa_score !== undefined && (
<span className="px-3 py-1 rounded-full text-xs font-black bg-emerald-600 text-white shadow-xs">
نمره قبولی استیج: {payload.stage_qa_score} از ۱۰۰
</span>
)}
</div>
{payload.stage_qa_feedback && (
<div className="text-xs text-gray-800 bg-white p-3 rounded-xl border border-emerald-100">
<strong>نظر کارشناسی تضمین کیفیت:</strong> {payload.stage_qa_feedback}
</div>
)}
{payload.deliverable_url && (
<div className="flex items-center justify-between text-xs p-2.5 bg-white rounded-xl border border-emerald-100">
<span className="font-bold text-gray-600">آدرس خروجی استقراریافته:</span>
<a
href={payload.deliverable_url}
target="_blank"
rel="noreferrer"
className="font-mono text-purple-700 hover:underline flex items-center gap-1 font-bold"
>
<span>{payload.deliverable_url}</span>
<ExternalLink className="w-3.5 h-3.5" />
</a>
</div>
)}
</div>
)}
{/* 5. QA Defect Details & Offline Action Needed */}
{hasQaDefects && (
<div className="p-4 bg-rose-50/60 border border-rose-200 rounded-2xl space-y-2.5">
<div className="flex items-center gap-2 text-rose-800 text-xs font-black border-b border-rose-200 pb-2">
<ShieldAlert className="w-4 h-4 text-rose-600" />
<span>نواقص ممیزی‌شده توسط واحد QA (نیاز به اقدام/امضای انسانی):</span>
</div>
{payload.reason && (
<p className="text-xs text-gray-800 font-bold bg-white p-2.5 rounded-xl border border-rose-100">
{payload.reason}
</p>
)}
{Array.isArray(payload.qa_defects) && payload.qa_defects.length > 0 && (
<ul className="space-y-1.5 text-xs text-rose-900 pr-1">
{payload.qa_defects.map((defect: string, i: number) => (
<li key={i} className="flex items-start gap-2 bg-white/80 p-2 rounded-lg border border-rose-100">
<XCircle className="w-3.5 h-3.5 text-rose-600 shrink-0 mt-0.5" />
<span className="font-medium text-gray-800">{defect}</span>
</li>
))}
</ul>
)}
{payload.qa_feedback && (
<div className="text-xs text-gray-700 bg-white p-2.5 rounded-xl border border-rose-100">
<strong>توضیحات تکمیلی ارزیاب کیفی:</strong> {payload.qa_feedback}
</div>
)}
</div>
)}
{/* 6. Competitor Benchmark Findings */}
{hasCompetitorBenchmark && Array.isArray(payload.key_findings) && (
<div className="p-3.5 bg-gray-50 border border-gray-200 rounded-2xl space-y-2.5">
<div className="flex items-center gap-2 text-gray-900 text-xs font-black border-b border-gray-200 pb-1.5">
<BarChart3 className="w-4 h-4 text-blue-600" />
<span>یافته‌های تحلیلی رصد بازار رقبا:</span>
</div>
<div className="grid grid-cols-1 md:grid-cols-3 gap-2">
{payload.key_findings.map((f: any, i: number) => (
<div key={i} className="bg-white p-2.5 rounded-xl border border-gray-200 text-xs space-y-1">
<span className="font-black text-gray-900 block truncate">{f.product}</span>
<span className="text-[11px] text-purple-700 font-bold block">{f.advantage || f.status}</span>
{f.our_price && (
<div className="text-[10px] text-gray-500 font-mono">
قیمت ما: {formatMoney(f.our_price)} | رقیب: {formatMoney(f.competitor_min)}
</div>
)}
</div>
))}
</div>
</div>
)}
{/* 7. Generic Key-Value Renderer for any remaining unmapped properties */}
{!hasFivePart && !hasPricing && !hasSms && !hasQaDefects && !hasRelease && !hasCompetitorBenchmark && (
<div className="p-3 bg-gray-50 border border-gray-200 rounded-2xl space-y-2">
<div className="text-xs font-black text-gray-700">پارامترهای فنی پیشنهاد:</div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-2 text-xs">
{Object.entries(payload).map(([k, v]) => {
if (typeof v === 'object' && v !== null) return null;
return (
<div key={k} className="p-2 bg-white rounded-xl border border-gray-100 flex items-center justify-between">
<span className="text-gray-500 font-bold">{k}:</span>
<span className="font-bold text-gray-900 max-w-[60%] truncate dir-ltr">{String(v)}</span>
</div>
);
})}
</div>
</div>
)}
{/* Raw JSON toggle button for engineers/inspectors */}
<div className="pt-1 flex items-center justify-between">
<button
type="button"
onClick={() => setShowRawJson(!showRawJson)}
className="text-[11px] font-bold text-gray-500 hover:text-purple-600 transition-colors flex items-center gap-1 cursor-pointer"
>
{showRawJson ? <ChevronUp className="w-3.5 h-3.5" /> : <ChevronDown className="w-3.5 h-3.5" />}
<span>{showRawJson ? 'بستن ساختار خام JSON' : 'مشاهده دیتای خام سیستمی (JSON)'}</span>
</button>
{showRawJson && (
<button
type="button"
onClick={() => copyToClipboard(JSON.stringify(payload, null, 2), 'JSON داده‌ها')}
className="text-[11px] font-bold text-purple-600 hover:text-purple-700 flex items-center gap-1 cursor-pointer"
>
<Copy className="w-3 h-3" />
<span>کپی JSON</span>
</button>
)}
</div>
{showRawJson && (
<pre className="p-3 bg-gray-900 text-purple-200 text-[11px] font-mono rounded-xl border border-gray-800 overflow-x-auto whitespace-pre-wrap dir-ltr max-h-60 overflow-y-auto">
{JSON.stringify(payload, null, 2)}
</pre>
)}
</div>
);
}
function UsersIcon(props: any) {
return (
<svg {...props} fill="none" viewBox="0 0 24 24" strokeWidth="2" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" d="M15 19.128a9.38 9.38 0 002.625.372 9.337 9.337 0 004.121-.952 4.125 4.125 0 00-7.533-2.493M15 19.128v-.003c0-1.113-.285-2.16-.786-3.07M15 19.128v.106A12.318 12.318 0 018.624 21c-2.331 0-4.512-.645-6.374-1.766l-.001-.109a6.375 6.375 0 0111.964-3.07M12 6.375a3.375 3.375 0 11-6.75 0 3.375 3.375 0 016.75 0zm8.25 2.25a2.625 2.625 0 11-5.25 0 2.625 2.625 0 015.25 0z" />
</svg>
);
}
export default function ApprovalsPage() {
const [items, setItems] = useState<ApprovalItem[]>([]);
const [loading, setLoading] = useState(true);
const [activeTab, setActiveTab] = useState<string>('ALL');
const [searchQuery, setSearchQuery] = useState<string>('');
const [sortOrder, setSortOrder] = useState<'newest' | 'oldest'>('newest');
const [statusFilter, setStatusFilter] = useState<'ALL' | 'PENDING' | 'APPROVED' | 'REJECTED'>('ALL');
const [categoryFilter, setCategoryFilter] = useState<string>('ALL');
const [testingId, setTestingId] = useState<string | null>(null);
const [testResults, setTestResults] = useState<Record<string, any>>({});
const [notes, setNotes] = useState<Record<string, string>>({});
const [actionLoading, setActionLoading] = useState<string | null>(null);
const [pendingCount, setPendingCount] = useState(0);
const fetchApprovals = async () => {
setLoading(true);
try {
const res = await api.get('/admin/approvals?limit=100');
if (res.data?.success) {
const authorizations = (res.data.data as ApprovalItem[]).filter(item => item.category !== 'B2B_SUPPLIER_STRATEGY');
setItems(authorizations);
setPendingCount(authorizations.filter(item => item.status === 'PENDING').length);
const initialNotes: Record<string, string> = {};
res.data.data.forEach((item: ApprovalItem) => {
if (item.ceoNotes) initialNotes[item.id] = item.ceoNotes;
});
setNotes(initialNotes);
}
} catch (err) {
console.error('Error fetching approvals', err);
toast.error('خطا در دریافت لیست کارتابل تاییدات');
} finally {
setLoading(false);
}
};
useEffect(() => {
fetchApprovals();
}, []);
const handleRunTest = async (id: string) => {
setTestingId(id);
try {
const res = await api.post(`/admin/approvals/${id}/test`);
if (res.data?.success) {
setTestResults((prev) => ({ ...prev, [id]: res.data.testResult }));
toast.success('شبیه‌سازی اثر و تست سلامت با موفقیت انجام شد');
}
} catch (err) {
console.error('Test simulation failed', err);
toast.error('خطا در اجرای تست شبیه‌سازی');
} finally {
setTestingId(null);
}
};
const handleDecision = async (id: string, decision: 'APPROVED' | 'REJECTED') => {
setActionLoading(id);
try {
const res = await api.put(`/admin/approvals/${id}/decide`, {
decision,
ceoNotes: notes[id] || '',
});
if (res.data?.success) {
toast.success(
decision === 'APPROVED'
? 'مجوز تایید شد؛ نتیجه اجرا جداگانه پیگیری شود'
: 'درخواست رد شد'
);
await fetchApprovals();
}
} catch (err) {
console.error('Decision update failed', err);
toast.error('خطا در ثبت تصمیم مدیرعامل');
} finally {
setActionLoading(null);
}
};
const setPresetNote = (id: string, text: string) => {
setNotes((prev) => ({ ...prev, [id]: text }));
};
const getCategoryBadge = (category: string) => {
const map: Record<string, { label: string; icon: any; color: string }> = {
PRICING: { label: 'قیمت‌گذاری و مارجین', icon: DollarSign, color: 'bg-amber-50 text-amber-800 border-amber-200' },
PRICE_CHANGE: { label: 'اصلاح قیمت ترب', icon: DollarSign, color: 'bg-amber-50 text-amber-800 border-amber-200' },
PURCHASE_ORDER: { label: 'سفارش خرید و انبار', icon: ShoppingCart, color: 'bg-blue-50 text-blue-800 border-blue-200' },
CAMPAIGN: { label: 'کمپین تجاری و مارکتینگ', icon: Send, color: 'bg-purple-50 text-purple-800 border-purple-200' },
SMS_CAMPAIGN: { label: 'کمپین پیامکی مشتریان', icon: MessageCircle, color: 'bg-purple-50 text-purple-800 border-purple-200' },
B2B_SUPPLIER_STRATEGY: { label: 'طرح استراتژیک تامین‌کننده', icon: Building2, color: 'bg-indigo-50 text-indigo-800 border-indigo-200' },
PRODUCTION_RELEASE: { label: 'مجوز استقرار پروداکشن', icon: Server, color: 'bg-emerald-50 text-emerald-800 border-emerald-200' },
CLINICAL: { label: 'پروتکل بالینی و دارویی', icon: Stethoscope, color: 'bg-teal-50 text-teal-800 border-teal-200' },
PARTNERSHIP: { label: 'همکاری کلینیکی B2B', icon: Building2, color: 'bg-sky-50 text-sky-800 border-sky-200' },
SEO: { label: 'سئو و کلمات کلیدی', icon: Search, color: 'bg-blue-50 text-blue-800 border-blue-200' },
CONTENT_PUBLISH: { label: 'انتشار مقاله و محتوا', icon: FileText, color: 'bg-purple-50 text-purple-800 border-purple-200' },
COMPETITOR_BENCHMARK: { label: 'تحلیل قیمت رقبا', icon: TrendingUp, color: 'bg-amber-50 text-amber-800 border-amber-200' },
INFRASTRUCTURE_UPDATE: { label: 'به‌روزرسانی سرور و سیستم', icon: Cpu, color: 'bg-rose-50 text-rose-800 border-rose-200' },
};
const cfg = map[category] || { label: category, icon: Sliders, color: 'bg-gray-100 text-gray-800 border-gray-200' };
const IconComponent = cfg.icon;
return (
<span className={`inline-flex items-center gap-1 px-2.5 py-1 rounded-xl text-[11px] font-black border ${cfg.color}`}>
<IconComponent className="w-3.5 h-3.5 shrink-0" />
<span>{cfg.label}</span>
</span>
);
};
const getStatusBadge = (status: string) => {
switch (status) {
case 'PENDING':
return (
<span className="inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-xs font-black bg-amber-50 text-amber-800 border border-amber-300 shadow-xs animate-pulse">
<Clock className="w-3.5 h-3.5" />
<span>در انتظار تصمیم شما</span>
</span>
);
case 'APPROVED':
return (
<span className="inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-xs font-black bg-emerald-50 text-emerald-800 border border-emerald-200">
<CheckCircle2 className="w-3.5 h-3.5 text-emerald-600" />
<span>مجوز تایید شد</span>
</span>
);
case 'REJECTED':
return (
<span className="inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-xs font-black bg-rose-50 text-rose-800 border border-rose-200">
<XCircle className="w-3.5 h-3.5 text-rose-600" />
<span>رد شده توسط مدیرعامل</span>
</span>
);
default:
return <span>{status}</span>;
}
};
// Filter and sort items
const filteredAndSortedItems = useMemo(() => {
return items
.filter((item) => {
// Tab filter (department)
if (activeTab !== 'ALL') {
if (activeTab === 'PENDING') {
if (item.status !== 'PENDING') return false;
} else if (item.department.toUpperCase() !== activeTab.toUpperCase()) {
return false;
}
}
// Status dropdown filter
if (statusFilter !== 'ALL' && item.status !== statusFilter) {
return false;
}
// Category filter
if (categoryFilter !== 'ALL' && item.category !== categoryFilter) {
return false;
}
// Search filter
if (searchQuery.trim()) {
const q = searchQuery.toLowerCase().trim();
const matchTitle = item.title?.toLowerCase().includes(q);
const matchDept = item.department?.toLowerCase().includes(q);
const matchCat = item.category?.toLowerCase().includes(q);
const matchNotes = item.ceoNotes?.toLowerCase().includes(q);
const matchPayload = JSON.stringify(item.payload || {}).toLowerCase().includes(q);
if (!matchTitle && !matchDept && !matchCat && !matchNotes && !matchPayload) {
return false;
}
}
return true;
})
.sort((a, b) => {
const timeA = new Date(a.createdAt).getTime();
const timeB = new Date(b.createdAt).getTime();
return sortOrder === 'newest' ? timeB - timeA : timeA - timeB;
});
}, [items, activeTab, statusFilter, categoryFilter, searchQuery, sortOrder]);
const totalCount = items.length;
const approvedCount = items.filter((i) => i.status === 'APPROVED').length;
const rejectedCount = items.filter((i) => i.status === 'REJECTED').length;
return (
<div className="space-y-6 max-w-7xl mx-auto p-4 md:p-6 font-vazir text-gray-900 bg-gray-50 min-h-screen" dir="rtl">
{/* Sleek Executive Header */}
<div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-4 bg-white p-6 rounded-3xl border border-gray-200/80 shadow-xs">
<div>
<div className="flex items-center gap-3">
<div className="w-10 h-10 rounded-2xl bg-purple-100 flex items-center justify-center text-purple-700 shadow-xs">
<ShieldCheck className="w-6 h-6" />
</div>
<div>
<h1 className="text-xl md:text-2xl font-black text-gray-900 tracking-tight">
کارتابل حاکمیت سازمانی و تاییدات مدیرعامل (CEO Approvals Gate)
</h1>
<p className="text-xs text-gray-500 font-medium mt-1 leading-relaxed">
هیچ اقدام حساسی اعم از قیمت‌گذاری، کمپین‌ها، سفارشات تامین و استقرار پروداکشن بدون تایید شما اجرا نخواهد شد.
</p>
</div>
</div>
</div>
<div className="flex items-center gap-3">
{pendingCount > 0 ? (
<span className="px-3.5 py-1.5 rounded-2xl text-xs font-black bg-amber-100 text-amber-900 border border-amber-300 flex items-center gap-1.5 shadow-xs">
<span className="w-2 h-2 rounded-full bg-amber-500 animate-ping" />
<span>{pendingCount} پیشنهاد منتظر تصمیم شما</span>
</span>
) : (
<span className="px-3.5 py-1.5 rounded-2xl text-xs font-black bg-emerald-100 text-emerald-900 border border-emerald-300 flex items-center gap-1.5 shadow-xs">
<CheckCheck className="w-4 h-4 text-emerald-700" />
<span>تمام موارد تعیین تکلیف شده‌اند</span>
</span>
)}
<button
type="button"
onClick={fetchApprovals}
disabled={loading}
className="inline-flex items-center gap-2 px-3.5 py-2 rounded-2xl bg-gray-100 hover:bg-gray-200 text-gray-700 text-xs font-bold transition-all border border-gray-200 cursor-pointer disabled:opacity-50"
title="به‌روزرسانی کارتابل"
>
<RefreshCw className={`w-4 h-4 ${loading ? 'animate-spin' : ''}`} />
<span className="hidden sm:inline">تازه‌سازی</span>
</button>
</div>
</div>
{/* Separation Banner */}
<div className="bg-indigo-50/80 border border-indigo-200 p-4 rounded-2xl flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3 shadow-xs">
<div className="flex items-center gap-2.5 text-xs text-indigo-950 font-medium">
<Briefcase className="w-4 h-4 text-indigo-600 shrink-0" />
<span>
اقدامات مدیریتی، توسعه سازمانی و استراتژی تامین‌کنندگان به بخش مستقل <strong>«اقدامات مدیریتی و همکاری‌ها»</strong> تفکیک شده‌اند.
</span>
</div>
<a
href="/manager-actions"
className="inline-flex items-center gap-1.5 px-3.5 py-1.5 bg-indigo-600 hover:bg-indigo-700 text-white rounded-xl text-xs font-bold shrink-0 transition-all shadow-2xs"
>
<span>مشاهده اقدامات مدیریتی</span>
<ArrowUpRight className="w-3.5 h-3.5" />
</a>
</div>
{/* Summary KPI Cards */}
<div className="grid grid-cols-2 sm:grid-cols-4 gap-3.5">
<div className="bg-white p-4 rounded-2xl border border-gray-200/80 shadow-xs flex items-center justify-between">
<div>
<p className="text-[11px] font-bold text-gray-500">کل موارد کارتابل</p>
<p className="text-2xl font-black text-gray-900 mt-1 font-mono">{totalCount}</p>
</div>
<div className="w-10 h-10 rounded-xl bg-purple-50 text-purple-700 flex items-center justify-center font-bold">
<Layers className="w-5 h-5" />
</div>
</div>
<div className="bg-white p-4 rounded-2xl border border-amber-300 shadow-xs flex items-center justify-between ring-1 ring-amber-400/20">
<div>
<p className="text-[11px] font-bold text-amber-700">در انتظار تایید شما</p>
<p className="text-2xl font-black text-amber-700 mt-1 font-mono">{pendingCount}</p>
</div>
<div className="w-10 h-10 rounded-xl bg-amber-50 text-amber-700 flex items-center justify-center font-bold">
<Clock className="w-5 h-5" />
</div>
</div>
<div className="bg-white p-4 rounded-2xl border border-emerald-200 shadow-xs flex items-center justify-between">
<div>
<p className="text-[11px] font-bold text-emerald-700">مجوزهای تاییدشده</p>
<p className="text-2xl font-black text-emerald-700 mt-1 font-mono">{approvedCount}</p>
</div>
<div className="w-10 h-10 rounded-xl bg-emerald-50 text-emerald-700 flex items-center justify-center font-bold">
<Check className="w-5 h-5" />
</div>
</div>
<div className="bg-white p-4 rounded-2xl border border-rose-200 shadow-xs flex items-center justify-between">
<div>
<p className="text-[11px] font-bold text-rose-700">رد شده توسط مدیرعامل</p>
<p className="text-2xl font-black text-rose-700 mt-1 font-mono">{rejectedCount}</p>
</div>
<div className="w-10 h-10 rounded-xl bg-rose-50 text-rose-700 flex items-center justify-center font-bold">
<X className="w-5 h-5" />
</div>
</div>
</div>
{/* Search, Filter & Controls Bar */}
<div className="bg-white p-4 rounded-3xl border border-gray-200/80 shadow-xs space-y-3.5">
<div className="grid grid-cols-1 md:grid-cols-12 gap-3 items-center">
{/* Search Box */}
<div className="md:col-span-5 relative">
<Search className="w-4 h-4 text-gray-400 absolute right-3.5 top-1/2 -translate-y-1/2" />
<input
type="text"
placeholder="جستجو در عنوان، دپارتمان، شکاف بازار، کد..."
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
className="w-full pr-10 pl-4 py-2 text-xs bg-gray-50 border border-gray-200 rounded-xl focus:bg-white focus:outline-none focus:border-purple-500 font-medium text-gray-900 transition-colors"
/>
{searchQuery && (
<button
type="button"
onClick={() => setSearchQuery('')}
className="absolute left-3 top-1/2 -translate-y-1/2 text-[10px] text-gray-400 hover:text-gray-600 cursor-pointer font-bold"
>
پاک کردن
</button>
)}
</div>
{/* Status Select */}
<div className="md:col-span-2">
<select
value={statusFilter}
onChange={(e: any) => setStatusFilter(e.target.value)}
className="w-full px-3 py-2 text-xs bg-gray-50 border border-gray-200 rounded-xl focus:bg-white focus:outline-none focus:border-purple-500 font-bold text-gray-700 cursor-pointer"
>
<option value="ALL">همه وضعیت‌ها</option>
<option value="PENDING">فقط در انتظار تایید ({pendingCount})</option>
<option value="APPROVED">تایید شده‌ها ({approvedCount})</option>
<option value="REJECTED">رد شده‌ها ({rejectedCount})</option>
</select>
</div>
{/* Category Select */}
<div className="md:col-span-3">
<select
value={categoryFilter}
onChange={(e) => setCategoryFilter(e.target.value)}
className="w-full px-3 py-2 text-xs bg-gray-50 border border-gray-200 rounded-xl focus:bg-white focus:outline-none focus:border-purple-500 font-bold text-gray-700 cursor-pointer"
>
<option value="ALL">همه دسته‌بندی‌ها</option>
<option value="B2B_SUPPLIER_STRATEGY">طرح استراتژیک تامین‌کننده</option>
<option value="PRODUCTION_RELEASE">مجوز انتشار پروداکشن</option>
<option value="PRICING">قیمت‌گذاری و مارجین</option>
<option value="CAMPAIGN">کمپین‌های تجاری</option>
<option value="SMS_CAMPAIGN">کمپین‌های پیامکی</option>
<option value="PARTNERSHIP">همکاری کلینیکی B2B</option>
<option value="CONTENT_PUBLISH">انتشار محتوا</option>
</select>
</div>
{/* Sort Order */}
<div className="md:col-span-2">
<select
value={sortOrder}
onChange={(e: any) => setSortOrder(e.target.value)}
className="w-full px-3 py-2 text-xs bg-gray-50 border border-gray-200 rounded-xl focus:bg-white focus:outline-none focus:border-purple-500 font-bold text-gray-700 cursor-pointer"
>
<option value="newest">جدیدترین به قدیمی‌ترین</option>
<option value="oldest">قدیمی‌ترین به جدیدترین</option>
</select>
</div>
</div>
{/* Department Quick Filter Pills */}
<div className="flex flex-wrap gap-1.5 pt-2 border-t border-gray-100">
{[
{ id: 'ALL', label: `همه (${totalCount})` },
{ id: 'PENDING', label: `در انتظار (${pendingCount})` },
{ id: 'CONTENT', label: 'محتوا و وبلاگ' },
{ id: 'CLINICAL_RD', label: 'تحقیق و توسعه بالینی' },
{ id: 'B2B', label: 'بازرگانی و کلینیک‌ها' },
{ id: 'DEV', label: 'مهندسی و توسعه' },
{ id: 'DEVOPS', label: 'زیرساخت و سرور' },
{ id: 'SEO', label: 'سئو و مارکت‌پلیس' },
{ id: 'MARKETING', label: 'مارکتینگ و پیامک' },
{ id: 'PRICING', label: 'قیمت‌گذاری' },
].map((tab) => (
<button
key={tab.id}
type="button"
onClick={() => setActiveTab(tab.id)}
className={`px-3 py-1 rounded-xl text-[11px] font-bold transition-all cursor-pointer ${
activeTab === tab.id
? 'bg-purple-600 text-white shadow-xs'
: 'bg-gray-100 text-gray-600 hover:bg-gray-200'
}`}
>
{tab.label}
</button>
))}
</div>
</div>
{/* Results Header Counter */}
<div className="flex justify-between items-center text-xs text-gray-500 px-1">
<span>
نمایش <strong>{filteredAndSortedItems.length}</strong> مورد از مجموع <strong>{totalCount}</strong> مورد کارتابل
</span>
{(searchQuery || statusFilter !== 'ALL' || categoryFilter !== 'ALL' || activeTab !== 'ALL') && (
<button
type="button"
onClick={() => {
setSearchQuery('');
setStatusFilter('ALL');
setCategoryFilter('ALL');
setActiveTab('ALL');
}}
className="text-purple-600 hover:underline font-bold cursor-pointer"
>
پاک کردن همه فیلترها
</button>
)}
</div>
{/* Main Content List */}
{loading ? (
<div className="py-24 flex flex-col justify-center items-center gap-3">
<RefreshCw className="w-8 h-8 text-purple-600 animate-spin" />
<span className="text-xs font-bold text-gray-500">در حال دریافت داده‌های کارتابل تاییدات...</span>
</div>
) : filteredAndSortedItems.length === 0 ? (
<div className="bg-white p-12 text-center rounded-3xl border border-gray-200/80 shadow-xs space-y-2">
<CheckCircle2 className="w-12 h-12 text-emerald-500 mx-auto mb-2" />
<h3 className="text-base font-black text-gray-900">هیچ موردی با این فیلترها یافت نشد</h3>
<p className="text-xs text-gray-500">می‌توانید فیلترها یا عبارت جستجو را تغییر دهید.</p>
</div>
) : (
<div className="grid gap-5">
{filteredAndSortedItems.map((item) => (
<div
key={item.id}
className={`bg-white rounded-3xl border transition-all overflow-hidden ${
item.status === 'PENDING'
? 'border-amber-300 shadow-md ring-2 ring-amber-400/20'
: 'border-gray-200/90 opacity-95'
}`}
>
{/* Card Header Bar */}
<div className="p-5 border-b border-gray-100 flex flex-col md:flex-row justify-between items-start md:items-center gap-3 bg-gray-50/60">
<div className="flex items-start md:items-center gap-3">
<div className="mt-0.5 md:mt-0">
{getCategoryBadge(item.category)}
</div>
<div>
<h3 className="font-black text-gray-900 text-sm md:text-base leading-snug">
{item.title}
</h3>
<div className="flex flex-wrap items-center gap-2 mt-1 text-[11px] text-gray-500 font-medium">
<span>دپارتمان: <strong className="text-gray-800">{item.department}</strong></span>
<span>•</span>
<span>
تاریخ ثبت: {new Intl.DateTimeFormat('fa-IR', { year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit' }).format(new Date(item.createdAt))}
</span>
{item.executedAt && (
<>
<span>•</span>
<span className="text-emerald-700 font-bold">
تاریخ اعمال: {new Intl.DateTimeFormat('fa-IR', { year: 'numeric', month: '2-digit', day: '2-digit' }).format(new Date(item.executedAt))}
</span>
</>
)}
</div>
</div>
</div>
<div className="shrink-0">
{getStatusBadge(item.status)}
</div>
</div>
{/* Card Body */}
<div className="p-5 space-y-4">
{/* Clean, Mapped Payload Visualizer */}
<StructuredPayloadViewer payload={item.payload} />
{/* Pre-Execution Simulation Test */}
<div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3 p-3 bg-purple-50/50 rounded-2xl border border-purple-100">
<div className="text-xs text-purple-900">
<strong>شبیه‌سازی اثر و اعتبارسنجی خودکار:</strong> بررسی پیش‌شرط‌های امنیتی قبل از تایید قطعی
</div>
<button
type="button"
onClick={() => handleRunTest(item.id)}
disabled={testingId === item.id}
className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-xl bg-white hover:bg-purple-100 text-purple-700 text-xs font-bold transition-all border border-purple-200 shadow-2xs cursor-pointer disabled:opacity-50"
>
<Play className={`w-3.5 h-3.5 ${testingId === item.id ? 'animate-spin' : ''}`} />
<span>{testingId === item.id ? 'در حال شبیه‌سازی...' : 'اجرای تست و شبیه‌سازی'}</span>
</button>
</div>
{/* Test Result Display */}
{testResults[item.id] && (
<div className="p-3 bg-emerald-50 border border-emerald-200 rounded-2xl text-xs text-emerald-900 space-y-1">
<strong>نتیجه تست سلامت و شبیه‌سازی:</strong>
<div className="font-mono text-[11px] bg-white p-2.5 rounded-xl border border-emerald-200 whitespace-pre-wrap dir-ltr">
{JSON.stringify(testResults[item.id], null, 2)}
</div>
</div>
)}
{/* CEO Directives & Quick Chips */}
{item.status === 'PENDING' && (
<div className="space-y-2 pt-2 border-t border-gray-100">
<div className="flex items-center justify-between">
<label className="text-xs font-bold text-gray-700 flex items-center gap-1.5">
<MessageSquare className="w-3.5 h-3.5 text-purple-600" />
<span>دستور یا یادداشت مدیرعامل برای ابلاغ:</span>
</label>
<span className="text-[10px] text-gray-400 font-medium">پاسخ‌های آماده جهت درج سریع:</span>
</div>
{/* Quick Preset Chips */}
<div className="flex flex-wrap gap-1.5">
{[
'تایید شد، در اولویت اجرا قرار گیرد',
'تایید مشروط به بررسی استیجینگ',
'قیمت‌گذاری مجدداً با ترب مقایسه شود',
'فاقد توجیه اقتصادی، رد شود'
].map((preset) => (
<button
key={preset}
type="button"
onClick={() => setPresetNote(item.id, preset)}
className="text-[10px] font-bold px-2 py-0.5 rounded-lg bg-gray-100 hover:bg-purple-50 hover:text-purple-700 text-gray-600 transition-colors border border-gray-200 cursor-pointer"
>
+ {preset}
</button>
))}
</div>
<textarea
rows={2}
value={notes[item.id] || ''}
onChange={(e) =>
setNotes((prev) => ({ ...prev, [item.id]: e.target.value }))
}
placeholder="دستور اختصاصی، شروط تایید یا علت رد درخواست را اینجا بنویسید..."
disabled={actionLoading === item.id}
className="w-full text-xs p-3 rounded-2xl border border-gray-200 bg-gray-50 focus:bg-white focus:border-purple-500 focus:outline-none font-medium text-gray-900 transition-colors"
/>
</div>
)}
{/* Log of CEO note when already decided */}
{item.status !== 'PENDING' && item.ceoNotes && (
<div className="p-3 bg-gray-50 rounded-2xl text-xs text-gray-700 border border-gray-200 flex items-start gap-2">
<MessageSquare className="w-4 h-4 text-purple-600 shrink-0 mt-0.5" />
<div>
<strong className="text-gray-900 block mb-0.5">یادداشت ثبت‌شده مدیرعامل:</strong>
<span>{item.ceoNotes}</span>
</div>
</div>
)}
{/* Primary Decision Action Buttons */}
{item.status === 'PENDING' && (
<div className="flex flex-wrap items-center justify-end gap-3 pt-3 border-t border-gray-100">
<button
type="button"
onClick={() => handleDecision(item.id, 'REJECTED')}
disabled={actionLoading === item.id}
className="inline-flex items-center gap-1.5 px-4 py-2.5 rounded-2xl bg-rose-50 hover:bg-rose-100 text-rose-700 text-xs font-bold transition-all border border-rose-200 shadow-2xs cursor-pointer disabled:opacity-50"
>
<X className="w-4 h-4 text-rose-600" />
<span>رد این درخواست</span>
</button>
<button
type="button"
onClick={() => handleDecision(item.id, 'APPROVED')}
disabled={actionLoading === item.id}
className="inline-flex items-center gap-2 px-5 py-2.5 rounded-2xl bg-emerald-600 hover:bg-emerald-700 text-white text-xs font-black transition-all shadow-md shadow-emerald-600/20 cursor-pointer disabled:opacity-50"
>
<Check className="w-4 h-4" />
<span>تایید و صدور مجوز اجرا در پروداکشن</span>
</button>
</div>
)}
</div>
</div>
))}
</div>
)}
</div>
);
}