ehsan-dashboards/dashboards/old_hermes/integrate_social_utms_and_rials.py

604 lines
51 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import json
import re
print("Integrating Top 10 Social Click Champions, VIP/Package Filters, Recent Posts, and Rial Currency into Dashboard...")
with open('/workspace/master_social_analyzed_utms.json', 'r', encoding='utf-8') as f:
social_data = json.load(f)
with open('/workspace/live_marketing_index.html', 'r', encoding='utf-8') as f:
html = f.read()
# Build the enhanced Javascript engine with Top 10, VIP/Package tab, Recent Posts tab, and Rial format
enhanced_engine = f"""
// ================= MASTER SOCIAL UTM ANALYTICS & RIAL SALES ENGINE =================
const ALL_SOCIAL_UTMS_MASTER = {json.dumps(social_data['all_social_utms'][:150], ensure_ascii=False)};
const TOP_10_SOCIAL_UTMS = {json.dumps(social_data['top_10_social'], ensure_ascii=False)};
const VIP_PACKAGE_UTMS = {json.dumps(social_data['vip_package_utms'], ensure_ascii=False)};
const RECENT_POSTS_UTMS = {json.dumps(social_data['recent_posts_utms'][:50], ensure_ascii=False)};
let customUtmList = JSON.parse(localStorage.getItem('ekeepa_custom_utms_v3') || 'null');
if (!customUtmList || customUtmList.length === 0) {{
customUtmList = ALL_SOCIAL_UTMS_MASTER;
localStorage.setItem('ekeepa_custom_utms_v3', JSON.stringify(customUtmList));
}}
let utmDynamicRules = JSON.parse(localStorage.getItem('ekeepa_utm_dynamic_rules_v1') || '[]');
let utmSearchQuery = '';
let utmActiveTabFilter = 'all'; // 'all' | 'top10' | 'vip_package' | 'recent_posts'
function renderGoogleAdsB2BView() {{
const pane = document.getElementById('tabPaneGoogleAdsB2B');
if (!pane) return;
const data = GOOGLE_ADS_B2B_MASTER;
const s = data.summary;
let criticalCount = data.vip_rooms.filter(r => r.status === 'critical').length;
let warningCount = data.vip_rooms.filter(r => r.status === 'warning').length;
// Base Dataset depending on view tab
let sourcePool = customUtmList;
if (utmActiveTabFilter === 'top10') {{
sourcePool = TOP_10_SOCIAL_UTMS;
}} else if (utmActiveTabFilter === 'vip_package') {{
sourcePool = customUtmList.filter(u => u.is_vip_or_package);
}} else if (utmActiveTabFilter === 'recent_posts') {{
sourcePool = customUtmList.filter(u => u.is_recent_post);
}}
// Filter UTMs dynamically
let filteredUtms = sourcePool.filter(item => {{
// 1. Full-text instant search (Ctrl + F search box)
const q = utmSearchQuery.toLowerCase().trim();
if (q) {{
const matchSearch = (
(item.title && item.title.toLowerCase().includes(q)) ||
(item.campaign && item.campaign.toLowerCase().includes(q)) ||
(item.gen && item.gen.toLowerCase().includes(q)) ||
(item.landing_decoded && item.landing_decoded.toLowerCase().includes(q)) ||
(item.landing && item.landing.toLowerCase().includes(q)) ||
(item.source && item.source.toLowerCase().includes(q)) ||
(item.medium && item.medium.toLowerCase().includes(q)) ||
(item.tag && item.tag.toLowerCase().includes(q)) ||
(item.content && item.content.toLowerCase().includes(q)) ||
(item.term && item.term.toLowerCase().includes(q))
);
if (!matchSearch) return false;
}}
// 2. Evaluate Dynamic User-defined Rules (AND logic)
for (let rule of utmDynamicRules) {{
const val = String(rule.value || '').toLowerCase().trim();
if (!val) continue;
let fieldVal = '';
let numFieldVal = 0;
if (rule.field === 'title') fieldVal = (item.title || '').toLowerCase();
else if (rule.field === 'gen') fieldVal = (item.gen || '').toLowerCase();
else if (rule.field === 'source') fieldVal = (item.source || '').toLowerCase();
else if (rule.field === 'medium') fieldVal = (item.medium || '').toLowerCase();
else if (rule.field === 'campaign') fieldVal = (item.campaign || '').toLowerCase();
else if (rule.field === 'landing') fieldVal = (item.landing_decoded || item.landing || '').toLowerCase();
else if (rule.field === 'tag') fieldVal = (item.tag || '').toLowerCase();
else if (rule.field === 'clicks') numFieldVal = item.clicks || 0;
else if (rule.field === 'sales') numFieldVal = item.sales_count || 0;
else if (rule.field === 'cr') numFieldVal = item.conversion_rate || (item.clicks > 0 ? ((item.sales_count / item.clicks) * 100) : 0);
else if (rule.field === 'revenue') numFieldVal = item.revenue_rial || 0;
// Numeric comparisons
if (['clicks', 'sales', 'cr', 'revenue'].includes(rule.field)) {{
const targetNum = parseFloat(val) || 0;
if (rule.operator === 'gte' && !(numFieldVal >= targetNum)) return false;
if (rule.operator === 'lte' && !(numFieldVal <= targetNum)) return false;
if (rule.operator === 'equals' && !(numFieldVal === targetNum)) return false;
}} else {{
// String comparisons
if (rule.operator === 'contains' && !fieldVal.includes(val)) return false;
if (rule.operator === 'equals' && fieldVal !== val) return false;
if (rule.operator === 'not_contains' && fieldVal.includes(val)) return false;
if (rule.operator === 'starts_with' && !fieldVal.startsWith(val)) return false;
}}
}}
return true;
}});
// Calculate aggregated UTM stats (In Rials)
const totalUtmClicks = filteredUtms.reduce((sum, it) => sum + (it.clicks || 0), 0);
const totalUtmLeads = filteredUtms.reduce((sum, it) => sum + (it.leads || 0), 0);
const totalUtmSales = filteredUtms.reduce((sum, it) => sum + (it.sales_count || 0), 0);
const totalUtmRevenueRial = filteredUtms.reduce((sum, it) => sum + (it.revenue_rial || ((it.revenue || 0) * 10)), 0);
const avgConversionRate = totalUtmClicks > 0 ? ((totalUtmSales / totalUtmClicks) * 100).toFixed(1) : '0';
// Format Rial numbers clearly with Persian text
function formatRials(val) {{
if (val >= 10000000000) {{
return (val / 10000000000).toLocaleString('fa-IR', {{maximumFractionDigits: 1}}) + ' میلیارد ریال';
}} else if (val >= 10000000) {{
return (val / 10000000).toLocaleString('fa-IR', {{maximumFractionDigits: 1}}) + ' میلیون ریال';
}} else {{
return val.toLocaleString('fa-IR') + ' ریال';
}}
}}
let html = `
<div style="margin-bottom: 24px;">
<!-- ALERT BANNER: END OF MONTH REMINDER -->
<div style="background: linear-gradient(135deg, #FFF1F2 0%, #FFE4E6 100%); border: 1.5px solid #FDA4AF; border-radius: 16px; padding: 18px 24px; margin-bottom: 24px; display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 16px; box-shadow: 0 4px 15px rgba(225, 29, 72, 0.08);">
<div style="display: flex; align-items: center; gap: 16px;">
<div style="width: 46px; height: 46px; border-radius: 12px; background: #E11D48; color: #fff; display: flex; align-items: center; justify-content: center; font-size: 1.4rem; flex-shrink: 0;">
⏰
</div>
<div>
<div style="font-size: 1.05rem; font-weight: 800; color: #9F1239; margin-bottom: 4px;">
هشدار اتمام دوره ماهانه: تنها ${{s.days_left_in_month}} روز تا پایان ماه باقی مانده است!
</div>
<div style="font-size: 0.85rem; color: #BE123C; line-height: 1.5;">
تعداد <strong>${{criticalCount}} پکیج VIP بحرانی</strong> و <strong>${{warningCount}} پکیج نیازمند توجه</strong> به تارگت فروش ماهانه نرسیده‌اند. کمپین‌های UTM متصل به ریلز و استوری را فعال کنید.
</div>
</div>
</div>
<div style="display: flex; gap: 10px;">
<button onclick="scrollToVipAlerts()" style="background: #E11D48; color: #fff; border: none; padding: 10px 18px; border-radius: 10px; font-weight: 800; font-size: 0.85rem; cursor: pointer; display: flex; align-items: center; gap: 6px; box-shadow: 0 4px 12px rgba(225, 29, 72, 0.3);">
<span>مشاهده پکیج‌های جا مانده از تارگت</span>
<span>↓</span>
</button>
</div>
</div>
<!-- TOP KPI STRIP (IN RIALS) -->
<div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(230px, 1fr)); gap: 16px; margin-bottom: 24px;">
<div style="background: var(--bg-card); border: 1px solid var(--border-color); border-radius: 14px; padding: 16px 18px; box-shadow: 0 2px 8px rgba(0,0,0,0.03);">
<div style="font-size: 0.78rem; font-weight: 700; color: var(--text-muted); margin-bottom: 6px;">بودجه تبلیغات و ادز (ریال)</div>
<div style="font-size: 1.35rem; font-weight: 900; color: var(--text-main); font-feature-settings: 'tnum';">${{((s.total_ad_spend_toman * 10) / 1000000000).toLocaleString('fa-IR', {{maximumFractionDigits: 1}})}} میلیارد ریال</div>
<div style="font-size: 0.76rem; color: #059669; margin-top: 4px; font-weight: 600;">CPC میانگین: ${{((s.avg_cpc_toman * 10)).toLocaleString('fa-IR')}} ریال</div>
</div>
<div style="background: var(--bg-card); border: 1px solid var(--border-color); border-radius: 14px; padding: 16px 18px; box-shadow: 0 2px 8px rgba(0,0,0,0.03);">
<div style="font-size: 0.78rem; font-weight: 700; color: var(--text-muted); margin-bottom: 6px;">فروش کل پکیج‌ها و UTMها (ریال)</div>
<div style="font-size: 1.35rem; font-weight: 900; color: var(--primary); font-feature-settings: 'tnum';">${{formatRials(totalUtmRevenueRial + (s.b2b_revenue_toman * 10))}}</div>
<div style="font-size: 0.76rem; color: var(--primary); margin-top: 4px; font-weight: 600;">بازگشت سرمایه (ROAS): ${{s.ad_roas}}x</div>
</div>
<div style="background: var(--bg-card); border: 1px solid var(--border-color); border-radius: 14px; padding: 16px 18px; box-shadow: 0 2px 8px rgba(0,0,0,0.03);">
<div style="font-size: 0.78rem; font-weight: 700; color: var(--text-muted); margin-bottom: 6px;">کلیک و ترافیک سوشال رهگیری‌شده</div>
<div style="font-size: 1.35rem; font-weight: 900; color: #2563EB; font-feature-settings: 'tnum';">${{totalUtmClicks.toLocaleString('fa-IR')}} کلیک</div>
<div style="font-size: 0.76rem; color: #2563EB; margin-top: 4px; font-weight: 600;">لیدهای ثبت‌شده: ${{totalUtmLeads.toLocaleString('fa-IR')}} نفر</div>
</div>
<div style="background: var(--bg-card); border: 1px solid var(--border-color); border-radius: 14px; padding: 16px 18px; box-shadow: 0 2px 8px rgba(0,0,0,0.03);">
<div style="font-size: 0.78rem; font-weight: 700; color: var(--text-muted); margin-bottom: 6px;">بلیت‌های فروخته‌شده از UTM</div>
<div style="font-size: 1.35rem; font-weight: 900; color: #0d9488; font-feature-settings: 'tnum';">${{totalUtmSales.toLocaleString('fa-IR')}} سانس</div>
<div style="font-size: 0.76rem; color: #0d9488; margin-top: 4px; font-weight: 700;">نرخ تبدیل فروش: ${{avgConversionRate}}%</div>
</div>
</div>
<!-- ================= DYNAMIC UTM SEARCH & FILTER BUILDER BOX ================= -->
<div style="background: var(--bg-card); border: 1.5px solid var(--border-color); border-radius: 16px; padding: 22px; margin-bottom: 28px; box-shadow: 0 4px 15px rgba(0,0,0,0.04);">
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 18px; flex-wrap: wrap; gap: 12px; border-bottom: 1px solid var(--border-color); padding-bottom: 14px;">
<div>
<div style="display: flex; align-items: center; gap: 8px;">
<span style="font-size: 1.3rem;">🎯</span>
<h3 style="margin: 0; font-size: 1.15rem; font-weight: 800; color: var(--text-main);">رصدخانه و تحلیلگر پیشرفته UTMهای سوشال (اینستاگرام، تلگرام، بله، لینکدین)</h3>
</div>
<div style="font-size: 0.8rem; color: var(--text-muted); margin-top: 4px;">
تحلیل ۱۰ لینک پربازدید، پکیج‌ها و کلیدواژه‌های VIP، پست‌های اخیر و محاسبه در لحظه مبالغ به ریال
</div>
</div>
<div style="display: flex; gap: 8px; flex-wrap: wrap;">
<a href="https://docs.google.com/spreadsheets/d/1mY1-XPfRAO-tDkNyDOf1G2Krb7o9OOcvoEmFqricK1o/edit?gid=1693824302#gid=1693824302" target="_blank" class="date-btn" style="padding: 8px 14px; font-size: 0.8rem; display: inline-flex; align-items: center; gap: 6px; text-decoration: none; color: var(--text-main);">
<span>📊 گوگل شیت آنلاین</span>
</a>
<button onclick="openAddUtmModal()" class="date-btn active" style="background: var(--primary); color: #fff; padding: 8px 16px; font-size: 0.82rem; font-weight: 800; display: inline-flex; align-items: center; gap: 6px;">
<span>➕ ست کردن UTM جدید</span>
</button>
</div>
</div>
<!-- VIEW TABS: ALL / TOP 10 / VIP & PACKAGE / RECENT POSTS -->
<div style="display: flex; gap: 8px; margin-bottom: 18px; border-bottom: 2px solid var(--border-color); padding-bottom: 12px; flex-wrap: wrap;">
<button onclick="setUtmActiveTab('all')" class="date-btn ${{utmActiveTabFilter === 'all' ? 'active' : ''}}" style="padding: 8px 18px; font-size: 0.84rem; font-weight: 800;">
<span>🌐 همه لینک‌های سوشال</span>
</button>
<button onclick="setUtmActiveTab('top10')" class="date-btn ${{utmActiveTabFilter === 'top10' ? 'active' : ''}}" style="padding: 8px 18px; font-size: 0.84rem; font-weight: 800; color: #2563EB; border-color: #93C5FD; background: ${{utmActiveTabFilter === 'top10' ? '#2563EB' : 'transparent'}}; color: ${{utmActiveTabFilter === 'top10' ? '#fff' : '#2563EB'}};">
<span>🏆 ۱۰ نرخ کلیک برتر سوشال</span>
</button>
<button onclick="setUtmActiveTab('vip_package')" class="date-btn ${{utmActiveTabFilter === 'vip_package' ? 'active' : ''}}" style="padding: 8px 18px; font-size: 0.84rem; font-weight: 800; color: #D97706; border-color: #FCD34D; background: ${{utmActiveTabFilter === 'vip_package' ? '#D97706' : 'transparent'}}; color: ${{utmActiveTabFilter === 'vip_package' ? '#fff' : '#D97706'}};">
<span>👑 پکیج‌ها و کلیدواژه‌های VIP</span>
</button>
<button onclick="setUtmActiveTab('recent_posts')" class="date-btn ${{utmActiveTabFilter === 'recent_posts' ? 'active' : ''}}" style="padding: 8px 18px; font-size: 0.84rem; font-weight: 800; color: #059669; border-color: #6EE7B7; background: ${{utmActiveTabFilter === 'recent_posts' ? '#059669' : 'transparent'}}; color: ${{utmActiveTabFilter === 'recent_posts' ? '#fff' : '#059669'}};">
<span>📢 پست‌ها و ریلزهای اخیر</span>
</button>
</div>
<!-- UTM Quick Aggregate Highlights (In Rials) -->
<div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(160px, 1fr)); gap: 12px; margin-bottom: 18px;">
<div style="background: var(--bg-body); border: 1px solid var(--border-color); padding: 12px 14px; border-radius: 10px; text-align: center;">
<div style="font-size: 0.74rem; color: var(--text-muted); font-weight: 700;">کمپین‌های این تب</div>
<div style="font-size: 1.2rem; font-weight: 900; color: var(--text-main); margin-top: 4px;">${{filteredUtms.length.toLocaleString('fa-IR')}} لینک</div>
</div>
<div style="background: var(--bg-body); border: 1px solid var(--border-color); padding: 12px 14px; border-radius: 10px; text-align: center;">
<div style="font-size: 0.74rem; color: var(--text-muted); font-weight: 700;">مجموع کلیک‌های فعال</div>
<div style="font-size: 1.2rem; font-weight: 900; color: #2563EB; margin-top: 4px;">${{totalUtmClicks.toLocaleString('fa-IR')}}</div>
</div>
<div style="background: var(--bg-body); border: 1px solid var(--border-color); padding: 12px 14px; border-radius: 10px; text-align: center;">
<div style="font-size: 0.74rem; color: var(--text-muted); font-weight: 700;">فروش بلیت / سانس</div>
<div style="font-size: 1.2rem; font-weight: 900; color: #059669; margin-top: 4px;">${{totalUtmSales.toLocaleString('fa-IR')}} سانس</div>
</div>
<div style="background: var(--bg-body); border: 1px solid var(--border-color); padding: 12px 14px; border-radius: 10px; text-align: center;">
<div style="font-size: 0.74rem; color: var(--text-muted); font-weight: 700;">فروش کل این بخش (ریال)</div>
<div style="font-size: 1.15rem; font-weight: 900; color: var(--primary); margin-top: 4px;">${{formatRials(totalUtmRevenueRial)}}</div>
</div>
</div>
<!-- ================= ULTRA-CLEAN SMART SEARCH & DYNAMIC FILTER BUILDER ================= -->
<div style="background: var(--bg-card); border: 2px solid var(--primary); border-radius: 16px; padding: 20px; margin-bottom: 22px; box-shadow: 0 4px 20px rgba(124, 58, 237, 0.08);">
<!-- 1. Universal Search Bar (Ctrl + F) -->
<div style="display: flex; gap: 12px; align-items: center; margin-bottom: 16px;">
<div style="position: relative; flex: 1;">
<span style="position: absolute; right: 16px; top: 50%; transform: translateY(-50%); font-size: 1.25rem; color: var(--primary); pointer-events: none;">🔍</span>
<input type="text" id="utmCtrlFSearchInput" value="${{utmSearchQuery}}" oninput="handleUtmSearch(this.value)" placeholder="جستجوی هوشمند در تمام پارامترها (نام اتاق فرار، VIP، پکیج، gen، کمپین، لندینگ، منبع، تگ)..." style="width: 100%; padding: 13px 48px 13px 105px; border-radius: 12px; border: 1.5px solid var(--border-color); background: var(--bg-body); color: var(--text-main); font-size: 0.95rem; font-weight: 600; box-shadow: inset 0 2px 4px rgba(0,0,0,0.02); transition: all 0.2s;">
<div style="position: absolute; left: 14px; top: 50%; transform: translateY(-50%); display: flex; align-items: center; gap: 4px;">
<kbd style="background: var(--bg-card); border: 1px solid var(--border-color); padding: 3px 8px; border-radius: 6px; font-size: 0.72rem; color: var(--primary); font-family: monospace; font-weight: 800; box-shadow: 0 1px 2px rgba(0,0,0,0.05);">Ctrl + F</kbd>
</div>
</div>
${{utmSearchQuery ? `
<button onclick="clearUtmSearch()" class="date-btn" style="padding: 12px 18px; font-size: 0.85rem; font-weight: 700; color: #EF4444; border-color: #FCA5A5; background: #FEF2F2; border-radius: 10px; cursor: pointer;">
✕ پاکسازی جستجو
</button>
` : ''}}
</div>
<!-- 2. Dynamic Rule Builder Controls -->
<div style="background: var(--bg-body); border: 1px solid var(--border-color); border-radius: 12px; padding: 14px 16px;">
<div style="display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 12px;">
<!-- Left / Inputs side -->
<div style="display: flex; align-items: center; gap: 10px; flex-wrap: wrap; flex: 1;">
<div style="display: flex; align-items: center; gap: 6px; font-weight: 800; font-size: 0.85rem; color: var(--primary);">
<span style="font-size: 1.1rem;">⚙️</span>
<span>فیلترساز دلخواه:</span>
</div>
<!-- Field -->
<select id="builderRuleField" onchange="handleBuilderFieldChange()" style="padding: 8px 12px; border-radius: 8px; border: 1.5px solid var(--border-color); background: var(--bg-card); color: var(--text-main); font-size: 0.82rem; font-weight: 700; cursor: pointer;">
<option value="gen">شناسه رهگیری (gen)</option>
<option value="title">عنوان / نام اتاق فرار</option>
<option value="source">منبع (utm_source)</option>
<option value="medium">مدیوم (utm_medium)</option>
<option value="campaign">کمپین (utm_campaign)</option>
<option value="landing">آدرس لندینگ (Landing Page)</option>
<option value="tag">دسته‌بندی / تگ</option>
<option value="clicks">حداقل کلیک (Clicks >=)</option>
<option value="sales">حداقل فروش بلیت (Sales >=)</option>
<option value="cr">نرخ تبدیل (CR% >=)</option>
<option value="revenue">حداقل درآمد (ریال >=)</option>
</select>
<!-- Operator -->
<select id="builderRuleOp" style="padding: 8px 12px; border-radius: 8px; border: 1.5px solid var(--border-color); background: var(--bg-card); color: var(--text-main); font-size: 0.82rem; cursor: pointer;">
<option value="contains">شامل باشد (contains)</option>
<option value="equals">دقیقاً برابر باشد (=)</option>
<option value="not_contains">شامل نباشد (not contains)</option>
<option value="starts_with">شروع شود با (starts with)</option>
<option value="gte">بزرگتر یا مساوی (>=)</option>
<option value="lte">کوچکتر یا مساوی (<=)</option>
</select>
<!-- Value Input -->
<div id="builderValueContainer" style="display: inline-flex; align-items: center; gap: 6px;">
<input type="text" id="builderRuleValue" onkeypress="if(event.key==='Enter') addDynamicFilterRule()" placeholder="مقدار مورد نظر (مثلاً: story، VIP، مشهد، 50)..." style="padding: 8px 14px; border-radius: 8px; border: 1.5px solid var(--border-color); background: var(--bg-card); color: var(--text-main); font-size: 0.85rem; min-width: 230px;">
</div>
<button onclick="addDynamicFilterRule()" class="date-btn active" style="padding: 8px 18px; font-size: 0.82rem; font-weight: 800; background: var(--primary); color: #fff; border-radius: 8px; display: inline-flex; align-items: center; gap: 6px; box-shadow: 0 2px 8px rgba(124, 58, 237, 0.25);">
<span>➕ افزودن این فیلتر</span>
</button>
</div>
<!-- Right / Quick Helpers -->
<div style="display: flex; align-items: center; gap: 6px; flex-wrap: wrap;">
<span style="font-size: 0.74rem; color: var(--text-muted); font-weight: 700;">فیلتر سریع:</span>
<button onclick="applyQuickPreset('vip')" class="date-btn" style="padding: 4px 10px; font-size: 0.75rem; border-radius: 6px; color: #D97706; border-color: #FCD34D; font-weight: 700;">👑 فقط VIP</button>
<button onclick="applyQuickPreset('pakeg')" class="date-btn" style="padding: 4px 10px; font-size: 0.75rem; border-radius: 6px; color: #7C3AED; border-color: #DDD6FE; font-weight: 700;">📦 پکیج‌ها</button>
<button onclick="applyQuickPreset('story')" class="date-btn" style="padding: 4px 10px; font-size: 0.75rem; border-radius: 6px;">📱 استوری‌ها</button>
<button onclick="applyQuickPreset('reel')" class="date-btn" style="padding: 4px 10px; font-size: 0.75rem; border-radius: 6px;">🎬 ریلزها</button>
<button onclick="applyQuickPreset('high_sales')" class="date-btn" style="padding: 4px 10px; font-size: 0.75rem; color: #059669; border-color: #6EE7B7; border-radius: 6px; font-weight: 700;">🔥 پرفروش‌ها (>=100)</button>
</div>
</div>
<!-- 3. Active Filters Chips (Tags) -->
${{utmDynamicRules.length > 0 ? `
<div style="display: flex; align-items: center; gap: 8px; flex-wrap: wrap; margin-top: 14px; padding-top: 12px; border-top: 1px dashed var(--border-color);">
<span style="font-size: 0.78rem; font-weight: 800; color: var(--text-main);">فیلترهای اعمال‌شده (${{utmDynamicRules.length}}):</span>
${{utmDynamicRules.map((rule, idx) => {{
const fieldLabels = {{
'gen': 'شناسه gen',
'title': 'عنوان',
'source': 'منبع',
'medium': 'مدیوم',
'campaign': 'کمپین',
'landing': 'لندینگ',
'tag': 'تگ',
'clicks': 'کلیک',
'sales': 'فروش',
'cr': 'نرخ تبدیل',
'revenue': 'درآمد (ریال)'
}};
const opLabels = {{
'contains': 'شامل',
'equals': '=',
'not_contains': 'به جز',
'starts_with': 'شروع با',
'gte': '>=',
'lte': '<='
}};
return `
<span style="display: inline-flex; align-items: center; gap: 8px; padding: 5px 12px; border-radius: 8px; background: rgba(124, 58, 237, 0.12); border: 1.5px solid var(--primary); color: var(--primary); font-size: 0.78rem; font-weight: 800;">
<span>${{fieldLabels[rule.field] || rule.field}} ${{opLabels[rule.operator] || rule.operator}} <strong>«${{rule.value}}»</strong></span>
<button onclick="removeDynamicFilterRule(${{idx}})" title="حذف این فیلتر" style="background: none; border: none; cursor: pointer; color: var(--primary); font-size: 1.1rem; font-weight: 900; line-height: 1; padding: 0 2px;">&times;</button>
</span>
`;
}}).join('')}}
<button onclick="clearAllDynamicFilters()" class="date-btn" style="padding: 4px 10px; font-size: 0.74rem; color: #EF4444; border-color: #FCA5A5; background: #FEF2F2; border-radius: 6px; font-weight: 700;">
🗑️ پاکسازی همه فیلترها
</button>
</div>
` : ''}}
</div>
</div>
<!-- UTM Data Table Matching Google Sheet Exactly (With Rials) -->
<div style="overflow-x: auto; width: 100%;">
<table class="data-table" style="width: 100%; border-collapse: collapse; font-size: 0.78rem;">
<thead>
<tr style="background: var(--bg-body); border-bottom: 2px solid var(--border-color); text-align: right;">
<th style="padding: 10px 10px; font-weight: 800; width: 40px; text-align: center;">رتبه</th>
<th style="padding: 10px 10px; font-weight: 800;">عنوان / محتوای سوشال</th>
<th style="padding: 10px 10px; font-weight: 800;">شناسه رهگیری (gen)</th>
<th style="padding: 10px 10px; font-weight: 800;">منبع و مدیوم</th>
<th style="padding: 10px 10px; font-weight: 800;">کمپین</th>
<th style="padding: 10px 10px; font-weight: 800;">لندینگ پیج (Landing)</th>
<th style="padding: 10px 10px; font-weight: 800; text-align: center;">کلیک‌ها</th>
<th style="padding: 10px 10px; font-weight: 800; text-align: center;">لید</th>
<th style="padding: 10px 10px; font-weight: 800; text-align: center;">خرید موفق</th>
<th style="padding: 10px 10px; font-weight: 800; text-align: center;">نرخ تبدیل</th>
<th style="padding: 10px 10px; font-weight: 800; text-align: left;">فروش نهایی (ریال)</th>
<th style="padding: 10px 8px; font-weight: 800; text-align: center;">عملیات</th>
</tr>
</thead>
<tbody>
${{filteredUtms.length === 0 ? `
<tr>
<td colspan="12" style="padding: 35px; text-align: center; color: var(--text-muted);">
<div style="font-size: 1.8rem; margin-bottom: 8px;">🔍</div>
<div style="font-size: 0.9rem; font-weight: 700;">هیچ لینک یا کمپینی با شرایط فیلتر و جستجوی فعلی یافت نشد.</div>
<div style="font-size: 0.76rem; margin-top: 4px;">می‌توانید فیلترها را حذف کرده یا عبارت جستجو را تغییر دهید.</div>
<button onclick="clearAllDynamicFilters()" class="date-btn active" style="margin-top: 12px; padding: 6px 14px; font-size: 0.78rem;">پاکسازی تمام فیلترها</button>
</td>
</tr>
` : filteredUtms.map((it, idx) => {{
const cr = it.conversion_rate !== undefined ? it.conversion_rate : (it.clicks > 0 ? ((it.sales_count / it.clicks) * 100).toFixed(1) : 0);
const revRial = it.revenue_rial || ((it.revenue || 0) * 10);
const isTopRank = idx < 3 && utmActiveTabFilter === 'top10';
const rankBadge = isTopRank ? ['🥇', '🥈', '🥉'][idx] : (idx + 1).toLocaleString('fa-IR');
return `
<tr style="border-bottom: 1px solid var(--border-color); transition: background 0.15s; background: ${{isTopRank ? 'rgba(124, 58, 237, 0.04)' : 'transparent'}};">
<td style="padding: 9px 6px; text-align: center; font-weight: 900; font-size: ${{isTopRank ? '1.1rem' : '0.8rem'}}; color: var(--text-muted);">
${{rankBadge}}
</td>
<td style="padding: 9px 10px; font-weight: 800; color: var(--text-main);">
<div style="display: flex; align-items: center; gap: 6px;">
<span>${{it.title}}</span>
${{it.is_vip_or_package ? '<span style="font-size: 0.68rem; background: #FEF3C7; color: #B45309; padding: 1px 5px; border-radius: 4px; font-weight: 800;">👑 VIP/پکیج</span>' : ''}}
</div>
<div style="font-size: 0.68rem; color: var(--text-muted); font-weight: 400;">${{it.date_created || ''}} | ${{it.tag || 'سوشال مارکتینگ'}}</div>
</td>
<td style="padding: 9px 10px;">
<span style="font-family: monospace; font-size: 0.72rem; font-weight: 800; background: rgba(124, 58, 237, 0.1); color: var(--primary); padding: 2px 6px; border-radius: 6px;">${{it.gen || '-'}}</span>
</td>
<td style="padding: 9px 10px;">
<span style="display: inline-block; padding: 2px 6px; border-radius: 6px; background: rgba(59, 130, 246, 0.1); color: #2563EB; font-size: 0.7rem; font-weight: 700; font-family: monospace;">${{it.source}} / ${{it.medium}}</span>
</td>
<td style="padding: 9px 10px; font-family: monospace; font-weight: 700; color: var(--text-main); font-size: 0.72rem;">${{it.campaign}}</td>
<td style="padding: 9px 10px; max-width: 170px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">
<a href="${{it.final_url || it.landing}}" target="_blank" title="${{it.landing_decoded || it.landing}}" style="color: var(--primary); text-decoration: none; font-size: 0.72rem; font-family: monospace; direction: ltr; display: inline-block;">${{it.landing ? it.landing.replace('https://ekeepa.co', '') : '-'}}</a>
</td>
<td style="padding: 9px 10px; text-align: center; font-weight: 900; color: #2563EB; font-feature-settings: 'tnum'; font-size: 0.84rem;">${{(it.clicks || 0).toLocaleString('fa-IR')}}</td>
<td style="padding: 9px 10px; text-align: center; font-feature-settings: 'tnum'; color: var(--text-muted); font-weight: 700;">${{(it.leads || 0).toLocaleString('fa-IR')}}</td>
<td style="padding: 9px 10px; text-align: center; font-weight: 900; color: #059669; font-feature-settings: 'tnum'; font-size: 0.84rem;">${{(it.sales_count || 0).toLocaleString('fa-IR')}}</td>
<td style="padding: 9px 10px; text-align: center; font-weight: 800; color: ${{cr >= 4 ? '#059669' : '#D97706'}}; font-feature-settings: 'tnum';">${{cr}}%</td>
<td style="padding: 9px 10px; text-align: left; font-weight: 900; color: var(--primary); font-feature-settings: 'tnum'; font-size: 0.82rem; white-space: nowrap;">
<div>${{revRial.toLocaleString('fa-IR')}} ریال</div>
<div style="font-size: 0.65rem; color: var(--text-muted); font-weight: 400;">(${{formatRials(revRial)}})</div>
</td>
<td style="padding: 9px 8px; text-align: center;">
<div style="display: flex; gap: 5px; justify-content: center; align-items: center;">
<button onclick="copyDirectUtmUrl('${{it.final_url ? it.final_url.replace(/'/g, "\\\\'") : ''}}')" title="کپی لینک مستقیم UTM" class="date-btn" style="padding: 3px 8px; font-size: 0.72rem; display: inline-flex; align-items: center; gap: 3px; background: rgba(124, 58, 237, 0.1); border-color: var(--primary); color: var(--primary); font-weight: 800;">
<span>🔗</span>
<span>کپی</span>
</button>
<button onclick="editUtmRecord('${{it.id}}')" title="ویرایش آمار فروش و کلیک" class="date-btn" style="padding: 3px 6px; font-size: 0.72rem; color: #D97706; border-color: #FCD34D;">
<span>✏️</span>
</button>
<button onclick="deleteUtmRecord('${{it.id}}')" title="حذف رکورد" class="date-btn" style="padding: 3px 6px; font-size: 0.72rem; color: #EF4444; border-color: #FCA5A5;">
<span>🗑️</span>
</button>
</div>
</td>
</tr>
`;
}}).join('')}}
</tbody>
</table>
</div>
</div>
<!-- SECTION 1: VIP ROOMS SALES WARNING & RESCUE ENGINE (IN RIALS) -->
<div id="vipAlertsSection" style="background: var(--bg-card); border: 1px solid var(--border-color); border-radius: 16px; padding: 22px; margin-bottom: 28px; box-shadow: 0 2px 12px rgba(0,0,0,0.04);">
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 18px; flex-wrap: wrap; gap: 12px;">
<div>
<div style="display: flex; align-items: center; gap: 8px;">
<span style="font-size: 1.3rem;">🚨</span>
<h3 style="margin: 0; font-size: 1.15rem; font-weight: 800; color: #9F1239;">اتاق‌های VIP و سینماهای بحرانی (نیازمند پوشش سناریو در سوشال)</h3>
</div>
<div style="font-size: 0.8rem; color: var(--text-muted); margin-top: 4px;">
اتاق‌ها و سانس‌های با نرخ تکمیل کمتر از ۷۰٪ در پایان ماه — محتوای فوری برای پر کردن سانس‌ها تولید شود
</div>
</div>
</div>
<div style="display: grid; grid-template-columns: repeat(auto-fill, minmax(320px, 1fr)); gap: 16px;">
${{data.vip_rooms.map(room => {{
let isCrit = room.status === 'critical';
let isWarn = room.status === 'warning';
let badgeBg = isCrit ? '#FFE4E6' : (isWarn ? '#FEF3C7' : '#DCFCE7');
let badgeColor = isCrit ? '#9F1239' : (isWarn ? '#92400E' : '#166534');
let badgeText = isCrit ? '⚠️ بحرانی (فاصله زیاد از تارگت)' : (isWarn ? '⚡ نیازمند توجه' : '✅ در مسیر تارگت');
const rName = room.name || room.room_name || 'اتاق VIP';
const rCat = room.category || room.genre || 'سینما فرار / ترس';
const rBooked = room.booked !== undefined ? room.booked : (room.booked_slots || 0);
const rTarget = room.monthly_target !== undefined ? room.monthly_target : (room.target_slots || 0);
const rPct = room.achievement_pct !== undefined ? room.achievement_pct : (room.completion_pct || 0);
const rPriceRial = room.ticket_price_toman ? ((room.ticket_price_toman * 10)).toLocaleString('fa-IR') + ' ریال' : '۱۶,۰۰۰,۰۰۰ ریال';
const rAction = room.suggested_action || room.suggested_rescue_action || 'اجرای سناریو و ریلز تبلیغاتی';
return `
<div style="border: 1.5px solid ${{isCrit ? '#FDA4AF' : (isWarn ? '#FDE68A' : '#BBF7D0')}}; background: var(--bg-card); border-radius: 14px; padding: 16px; box-shadow: 0 2px 8px rgba(0,0,0,0.02);">
<div style="display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 10px;">
<div>
<div style="font-weight: 800; font-size: 0.95rem; color: var(--text-main);">${{rName}}</div>
<div style="font-size: 0.75rem; color: var(--text-muted);">${{rCat}}</div>
</div>
<span style="background: ${{badgeBg}}; color: ${{badgeColor}}; font-size: 0.72rem; font-weight: 800; padding: 3px 8px; border-radius: 6px;">${{badgeText}}</span>
</div>
<div style="display: flex; justify-content: space-between; margin-bottom: 6px; font-size: 0.78rem;">
<span style="color: var(--text-muted);">رزرو شده: <strong>${{rBooked}}</strong> از ${{rTarget}} سانس</span>
<span style="font-weight: 800; color: ${{isCrit ? '#E11D48' : '#059669'}}; font-feature-settings: 'tnum';">${{rPct}}%</span>
</div>
<div style="height: 7px; background: var(--bg-body); border-radius: 4px; overflow: hidden; margin-bottom: 12px;">
<div style="height: 100%; width: ${{Math.min(rPct, 100)}}%; background: ${{isCrit ? '#E11D48' : (isWarn ? '#F59E0B' : '#10B981')}}; border-radius: 4px;"></div>
</div>
<div style="background: var(--bg-body); padding: 8px 10px; border-radius: 8px; font-size: 0.75rem; line-height: 1.5; color: var(--text-body); margin-bottom: 12px;">
💡 <strong>اکشن فوری سوشال:</strong> ${{rAction}}
</div>
<div style="display: flex; justify-content: space-between; align-items: center; border-top: 1px solid var(--border-color); padding-top: 10px;">
<span style="font-size: 0.75rem; font-weight: 700; color: var(--primary);">قیمت هر سانس: ${{rPriceRial}}</span>
<button onclick="createScenarioForRescue('${{rName.replace(/'/g, "\\\\\\'")}}', '${{rAction.replace(/'/g, "\\\\\\'")}}')" class="date-btn active" style="padding: 4px 10px; font-size: 0.72rem; background: var(--primary); color: #fff;">
➕ ایجاد سناریو در شیت
</button>
</div>
</div>
`;
}}).join('')}}
</div>
</div>
<!-- SECTION 2: AD CAMPAIGNS & CHANNELS (IN RIALS) -->
<div style="background: var(--bg-card); border: 1px solid var(--border-color); border-radius: 16px; padding: 22px; margin-bottom: 28px; box-shadow: 0 2px 12px rgba(0,0,0,0.04);">
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 18px; flex-wrap: wrap; gap: 12px;">
<div>
<div style="display: flex; align-items: center; gap: 8px;">
<span style="font-size: 1.3rem;">💼</span>
<h3 style="margin: 0; font-size: 1.15rem; font-weight: 800; color: var(--text-main);">پکیج‌ها و کمپین‌های تبلیغاتی فعال</h3>
</div>
<div style="font-size: 0.8rem; color: var(--text-muted); margin-top: 4px;">
عملکرد لیدهای گوگل ادز و پکیج‌های تبلیغاتی در کانال‌های مختلف
</div>
</div>
</div>
<div style="display: grid; grid-template-columns: repeat(auto-fill, minmax(320px, 1fr)); gap: 16px;">
${{(data.campaigns || []).map(pkg => `
<div style="border: 1px solid var(--border-color); background: var(--bg-card); border-radius: 14px; padding: 16px;">
<div style="display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 8px;">
<div>
<div style="font-weight: 800; font-size: 0.95rem; color: var(--text-main);">${{pkg.name || pkg.title || 'کمپین تبلیغاتی'}}</div>
<div style="font-size: 0.74rem; color: var(--text-muted);">${{pkg.source}} / ${{pkg.medium}} | CR: ${{pkg.cr_pct || '۲.۴%'}}</div>
</div>
<span style="background: rgba(124, 58, 237, 0.1); color: var(--primary); font-size: 0.74rem; font-weight: 800; padding: 3px 8px; border-radius: 6px;">ROAS: ${{pkg.roas || '10x'}}</span>
</div>
<div style="display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 8px; background: var(--bg-body); padding: 10px; border-radius: 8px; margin-bottom: 10px; text-align: center;">
<div>
<div style="font-size: 0.7rem; color: var(--text-muted);">کلیک ادز</div>
<div style="font-size: 0.95rem; font-weight: 800; color: #2563EB; font-feature-settings: 'tnum';">${{(pkg.clicks || 0).toLocaleString('fa-IR')}}</div>
</div>
<div>
<div style="font-size: 0.7rem; color: var(--text-muted);">خرید نهایی</div>
<div style="font-size: 0.95rem; font-weight: 800; color: #059669; font-feature-settings: 'tnum';">${{(pkg.purchases || 0).toLocaleString('fa-IR')}}</div>
</div>
<div>
<div style="font-size: 0.7rem; color: var(--text-muted);">درآمد حاصله</div>
<div style="font-size: 0.88rem; font-weight: 800; color: var(--primary); font-feature-settings: 'tnum';">${{((pkg.revenue_toman || 0) * 10 / 10000000).toLocaleString('fa-IR')}} م ریال</div>
</div>
</div>
<div style="font-size: 0.75rem; color: var(--text-muted); line-height: 1.5;">
🎯 <strong>کد ردیابی کمپین:</strong> <code style="font-family: monospace; color: var(--primary);">${{pkg.campaign}}</code>
</div>
</div>
`).join('')}}
</div>
</div>
</div>
`;
pane.innerHTML = html;
}}
function setUtmActiveTab(tab) {{
utmActiveTabFilter = tab;
renderGoogleAdsB2BView();
}}
function applyQuickPreset(preset) {{
if (preset === 'vip') {{
utmDynamicRules = [{{ field: 'title', operator: 'contains', value: 'vip' }}];
}} else if (preset === 'pakeg') {{
utmDynamicRules = [{{ field: 'title', operator: 'contains', value: 'پکیج' }}];
}} else if (preset === 'story') {{
utmDynamicRules = [{{ field: 'gen', operator: 'contains', value: 'story' }}];
}} else if (preset === 'reel') {{
utmDynamicRules = [{{ field: 'gen', operator: 'contains', value: 'reel' }}];
}} else if (preset === 'direct') {{
utmDynamicRules = [{{ field: 'gen', operator: 'contains', value: 'direct' }}];
}} else if (preset === 'high_sales') {{
utmDynamicRules = [{{ field: 'sales', operator: 'gte', value: '100' }}];
}}
localStorage.setItem('ekeepa_utm_dynamic_rules_v1', JSON.stringify(utmDynamicRules));
renderGoogleAdsB2BView();
showToast('فیلتر سریع «' + preset + '» اعمال شد 🎯✅');
}}
window.setUtmActiveTab = setUtmActiveTab;
window.applyQuickPreset = applyQuickPreset;
"""
# Replace in live_marketing_index.html
start_block = html.find('// ================= MASTER SOCIAL UTM ANALYTICS')
if start_block == -1:
start_block = html.find('// ================= DYNAMIC QUERY & FILTER BUILDER ENGINE =================')
if start_block != -1:
start_block = html.rfind('const OFFICIAL_SHEET_UTMS =', 0, start_block)
else:
start_block = html.find('const OFFICIAL_SHEET_UTMS =')
end_block = html.find('function copyDirectUtmUrl', start_block)
if start_block != -1 and end_block != -1:
html = html[:start_block] + enhanced_engine.strip() + '\n\n ' + html[end_block:]
print("Successfully replaced with Master Social UTM Analytics & Rial Engine!")
with open('/workspace/live_marketing_index.html', 'w', encoding='utf-8') as f:
f.write(html)
print("Saved updated live_marketing_index.html!")