ehsan-dashboards/dashboards/old_hermes/integrate_official_sheet_utms.py

656 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 Official Google Sheet UTM Engine & Builder into live dashboard...")
with open('/workspace/master_google_sheet_utms.json', 'r', encoding='utf-8') as f:
sheet_utms = json.load(f)
with open('/workspace/live_marketing_index.html', 'r', encoding='utf-8') as f:
html = f.read()
# Update master UTM Javascript Engine
utm_engine_js = f"""
// ================= MASTER GOOGLE SHEET UTM TRACKER ENGINE =================
const OFFICIAL_SHEET_UTMS = {json.dumps(sheet_utms, ensure_ascii=False)};
let customUtmList = JSON.parse(localStorage.getItem('ekeepa_custom_utms_v2') || 'null');
if (!customUtmList || customUtmList.length === 0) {{
customUtmList = OFFICIAL_SHEET_UTMS;
localStorage.setItem('ekeepa_custom_utms_v2', JSON.stringify(customUtmList));
}}
let utmFilterSource = 'all';
let utmFilterGen = 'all';
let utmFilterCampaign = 'all';
let utmSearchQuery = '';
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;
// Filter UTMs
let filteredUtms = customUtmList.filter(item => {{
const matchSrc = (utmFilterSource === 'all') || (item.source === utmFilterSource);
const matchGen = (utmFilterGen === 'all') || ((item.gen || '').includes(utmFilterGen));
const matchCamp = (utmFilterCampaign === 'all') || (item.campaign === utmFilterCampaign);
const q = utmSearchQuery.toLowerCase().trim();
const matchSearch = !q || (
(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.source && item.source.toLowerCase().includes(q)) ||
(item.medium && item.medium.toLowerCase().includes(q)) ||
(item.tag && item.tag.toLowerCase().includes(q))
);
return matchSrc && matchGen && matchCamp && matchSearch;
}});
// Calculate aggregated UTM stats
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 totalUtmRevenue = filteredUtms.reduce((sum, it) => sum + (it.revenue || 0), 0);
const avgConversionRate = totalUtmClicks > 0 ? ((totalUtmSales / totalUtmClicks) * 100).toFixed(1) : '0';
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 -->
<div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(220px, 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 / 1000000).toLocaleString('fa-IR')}} م تومان</div>
<div style="font-size: 0.76rem; color: #059669; margin-top: 4px; font-weight: 600;">CPC میانگین: ${{s.avg_cpc_toman.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';">${{((s.b2b_revenue_toman + totalUtmRevenue) / 1000000).toLocaleString('fa-IR')}} م تومان</div>
<div style="font-size: 0.76rem; color: var(--primary); margin-top: 4px; font-weight: 600;">بازگشت سرمایه (ROAS): ${{s.ad_roas}}</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>
<!-- ================= NEW SECTION: UTM ANALYTICS & GOOGLE SHEET SYNC TRACKER ================= -->
<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;">
ساخت خودکار لینک نهایی، کد رهگیری gen، پیگیری کلیک، لید، رزرو سانس و فروش هر اتاق فرار / ورکشاپ
</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>
<!-- UTM Quick Aggregate Highlights -->
<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.2rem; font-weight: 900; color: var(--primary); margin-top: 4px;">${{(totalUtmRevenue / 1000000).toLocaleString('fa-IR')}} م تومان</div>
</div>
</div>
<!-- UTM Search & Filters Bar (Source, Gen, Campaign) -->
<div style="display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 10px; margin-bottom: 14px; background: var(--bg-body); padding: 10px 14px; border-radius: 10px; border: 1px solid var(--border-color);">
<div style="display: flex; align-items: center; gap: 8px; flex-wrap: wrap;">
<span style="font-size: 0.78rem; font-weight: 700; color: var(--text-muted);">منبع:</span>
<div style="display: flex; gap: 4px;">
<button onclick="setUtmSourceFilter('all')" class="date-btn ${{utmFilterSource === 'all' ? 'active' : ''}}" style="padding: 4px 10px; font-size: 0.74rem;">همه</button>
<button onclick="setUtmSourceFilter('instagram')" class="date-btn ${{utmFilterSource === 'instagram' ? 'active' : ''}}" style="padding: 4px 10px; font-size: 0.74rem;">📸 اینستاگرام</button>
<button onclick="setUtmSourceFilter('telegram')" class="date-btn ${{utmFilterSource === 'telegram' ? 'active' : ''}}" style="padding: 4px 10px; font-size: 0.74rem;">✈️ تلگرام</button>
</div>
<span style="font-size: 0.78rem; font-weight: 700; color: var(--text-muted); margin-right: 8px;">فرمت (Gen):</span>
<div style="display: flex; gap: 4px;">
<button onclick="setUtmGenFilter('all')" class="date-btn ${{utmFilterGen === 'all' ? 'active' : ''}}" style="padding: 4px 8px; font-size: 0.74rem;">همه</button>
<button onclick="setUtmGenFilter('story')" class="date-btn ${{utmFilterGen === 'story' ? 'active' : ''}}" style="padding: 4px 8px; font-size: 0.74rem;">📱 استوری</button>
<button onclick="setUtmGenFilter('reel')" class="date-btn ${{utmFilterGen === 'reel' ? 'active' : ''}}" style="padding: 4px 8px; font-size: 0.74rem;">🎬 ریلز</button>
<button onclick="setUtmGenFilter('direct')" class="date-btn ${{utmFilterGen === 'direct' ? 'active' : ''}}" style="padding: 4px 8px; font-size: 0.74rem;">💬 دایرکت</button>
<button onclick="setUtmGenFilter('post')" class="date-btn ${{utmFilterGen === 'post' ? 'active' : ''}}" style="padding: 4px 8px; font-size: 0.74rem;">📢 پست</button>
</div>
<span style="font-size: 0.78rem; font-weight: 700; color: var(--text-muted); margin-right: 8px;">کمپین:</span>
<div style="display: flex; gap: 4px;">
<button onclick="setUtmCampaignFilter('all')" class="date-btn ${{utmFilterCampaign === 'all' ? 'active' : ''}}" style="padding: 4px 8px; font-size: 0.74rem;">همه</button>
<button onclick="setUtmCampaignFilter('ekp-list')" class="date-btn ${{utmFilterCampaign === 'ekp-list' ? 'active' : ''}}" style="padding: 4px 8px; font-size: 0.74rem;">🎭 اکیپا</button>
<button onclick="setUtmCampaignFilter('art-list')" class="date-btn ${{utmFilterCampaign === 'art-list' ? 'active' : ''}}" style="padding: 4px 8px; font-size: 0.74rem;">🎨 آرت</button>
<button onclick="setUtmCampaignFilter('ads-list')" class="date-btn ${{utmFilterCampaign === 'ads-list' ? 'active' : ''}}" style="padding: 4px 8px; font-size: 0.74rem;">📢 ادز</button>
</div>
</div>
<div style="display: flex; align-items: center; gap: 10px;">
<input type="text" id="utmLiveSearchInput" value="${{utmSearchQuery}}" oninput="handleUtmSearch(this.value)" placeholder="جستجو در نام اتاق، gen، لندینگ..." style="padding: 6px 12px; border-radius: 8px; border: 1px solid var(--border-color); background: var(--bg-card); color: var(--text-main); font-size: 0.78rem; width: 220px;">
</div>
</div>
<!-- UTM Data Table Matching Google Sheet Exactly -->
<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;">عنوان / اتاق فرار</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 10px; font-weight: 800; text-align: center;">عملیات</th>
</tr>
</thead>
<tbody>
${{filteredUtms.length === 0 ? `
<tr>
<td colspan="11" style="padding: 30px; text-align: center; color: var(--text-muted);">هیچ لینک UTM با این فیلتر یافت نشد.</td>
</tr>
` : filteredUtms.map((it, idx) => {{
const cr = it.clicks > 0 ? ((it.sales_count / it.clicks) * 100).toFixed(1) : 0;
return `
<tr style="border-bottom: 1px solid var(--border-color); transition: background 0.15s;">
<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>
</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: 800; font-feature-settings: 'tnum';">${{(it.clicks || 0).toLocaleString('fa-IR')}}</td>
<td style="padding: 9px 10px; text-align: center; font-feature-settings: 'tnum'; color: #2563EB; 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';">${{(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';">${{((it.revenue || 0)).toLocaleString('fa-IR')}} ت</td>
<td style="padding: 9px 10px; text-align: center;">
<div style="display: flex; gap: 4px; justify-content: center;">
<button onclick="copyDirectUtmUrl('${{it.final_url ? it.final_url.replace(/'/g, "\\\\'") : ''}}')" title="کپی لینک نهایی UTM" style="background: none; border: none; cursor: pointer; font-size: 0.88rem;">🔗</button>
<button onclick="editUtmRecord('${{it.id}}')" title="ویرایش آمار فروش و کلیک" style="background: none; border: none; cursor: pointer; font-size: 0.88rem;">✏️</button>
<button onclick="deleteUtmRecord('${{it.id}}')" title="حذف" style="background: none; border: none; cursor: pointer; font-size: 0.88rem; color: #EF4444;">🗑️</button>
</div>
</td>
</tr>
`;
}}).join('')}}
</tbody>
</table>
</div>
</div>
<!-- SECTION 1: VIP ROOMS SALES WARNING & RESCUE ENGINE -->
<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 rPrice = room.price_per_slot || (room.ticket_price_toman ? room.ticket_price_toman.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);">قیمت هر سانس: ${{rPrice}}</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 -->
<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.95rem; font-weight: 800; color: var(--primary); font-feature-settings: 'tnum';">${{((pkg.revenue_toman || 0) / 1000000).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;
}}
// ================= UTM FILTER CONTROLLERS =================
function setUtmSourceFilter(src) {{
utmFilterSource = src;
renderGoogleAdsB2BView();
}}
function setUtmGenFilter(gen) {{
utmFilterGen = gen;
renderGoogleAdsB2BView();
}}
function setUtmCampaignFilter(camp) {{
utmFilterCampaign = camp;
renderGoogleAdsB2BView();
}}
function handleUtmSearch(query) {{
utmSearchQuery = query;
renderGoogleAdsB2BView();
}}
function copyDirectUtmUrl(url) {{
if (!url) {{
showToast('آدرس URL یافت نشد');
return;
}}
navigator.clipboard.writeText(url).then(() => {{
showToast('لینک نهایی UTM با موفقیت در کلیپ‌بورد کپی شد 🔗✅');
}}).catch(() => {{
prompt('لینک UTM:', url);
}});
}}
// Auto-generate UTM Generator in modal
function updateUtmGeneratorPreview() {{
const landing = document.getElementById('newUtmLanding').value.trim() || 'https://ekeepa.co/room/1013111/dark-forest';
const source = document.getElementById('newUtmSource').value;
const medium = document.getElementById('newUtmMedium').value;
const campaign = document.getElementById('newUtmCampaign').value.trim() || 'ekp-list';
const gen = document.getElementById('newUtmGen').value.trim() || 'i-story-14050701';
const content = document.getElementById('newUtmContent').value.trim();
const term = document.getElementById('newUtmTerm').value.trim();
let finalUrl = `${{landing}}?utm_source=${{source}}&utm_medium=${{medium}}&utm_campaign=${{campaign}}&gen=${{gen}}`;
if (content) finalUrl += `&utm_content=${{encodeURIComponent(content)}}`;
if (term) finalUrl += `&utm_term=${{encodeURIComponent(term)}}`;
const preview = document.getElementById('newUtmFinalPreview');
if (preview) preview.value = finalUrl;
}}
function openAddUtmModal() {{
const modal = document.getElementById('addUtmModal');
if (modal) {{
modal.style.display = 'flex';
updateUtmGeneratorPreview();
}}
}}
function closeAddUtmModal() {{
const modal = document.getElementById('addUtmModal');
if (modal) {{
modal.style.display = 'none';
}}
}}
function handleAddUtmSubmit(event) {{
event.preventDefault();
const title = document.getElementById('newUtmTitle').value.trim();
const landing = document.getElementById('newUtmLanding').value.trim();
const gen = document.getElementById('newUtmGen').value.trim();
const source = document.getElementById('newUtmSource').value;
const medium = document.getElementById('newUtmMedium').value;
const campaign = document.getElementById('newUtmCampaign').value.trim();
const content = document.getElementById('newUtmContent').value.trim();
const term = document.getElementById('newUtmTerm').value.trim();
const final_url = document.getElementById('newUtmFinalPreview').value;
const clicks = parseInt(document.getElementById('newUtmClicks').value) || 0;
const leads = parseInt(document.getElementById('newUtmLeads').value) || 0;
const sales = parseInt(document.getElementById('newUtmSales').value) || 0;
const revenue = parseInt(document.getElementById('newUtmRevenue').value) || 0;
const newItem = {{
id: 'utm_custom_' + Date.now(),
title: title || 'کمپین جدید',
date_created: '8/31/2026',
landing,
landing_decoded: decodeURIComponent(landing),
gen,
source,
medium,
campaign,
content,
term,
final_url,
tag: medium.includes('art') ? 'ورکشاپ و آرت' : 'اتاق فرار',
clicks,
leads,
sales_count: sales,
revenue
}};
customUtmList.unshift(newItem);
localStorage.setItem('ekeepa_custom_utms_v2', JSON.stringify(customUtmList));
closeAddUtmModal();
renderGoogleAdsB2BView();
showToast('لینک UTM با موفقیت ثبت و به لیست ردیابی اضافه شد 🎯✅');
}}
function deleteUtmRecord(id) {{
if (confirm('آیا از حذف این رکورد UTM اطمینان دارید؟')) {{
customUtmList = customUtmList.filter(it => it.id !== id);
localStorage.setItem('ekeepa_custom_utms_v2', JSON.stringify(customUtmList));
renderGoogleAdsB2BView();
showToast('کمپین UTM حذف شد 🗑️');
}}
}}
function editUtmRecord(id) {{
const item = customUtmList.find(it => it.id === id);
if (!item) return;
const clicksStr = prompt('تعداد کلیک جدید:', item.clicks);
if (clicksStr === null) return;
const salesStr = prompt('تعداد بلیت / خرید موفق جدید:', item.sales_count);
if (salesStr === null) return;
const revStr = prompt('مبلغ فروش (تومان):', item.revenue);
if (revStr === null) return;
item.clicks = parseInt(clicksStr) || 0;
item.sales_count = parseInt(salesStr) || 0;
item.revenue = parseInt(revStr) || 0;
localStorage.setItem('ekeepa_custom_utms_v2', JSON.stringify(customUtmList));
renderGoogleAdsB2BView();
showToast('آمار UTM با موفقیت به‌روزرسانی شد 📊✅');
}}
window.renderGoogleAdsB2BView = renderGoogleAdsB2BView;
window.setUtmSourceFilter = setUtmSourceFilter;
window.setUtmGenFilter = setUtmGenFilter;
window.setUtmCampaignFilter = setUtmCampaignFilter;
window.handleUtmSearch = handleUtmSearch;
window.copyDirectUtmUrl = copyDirectUtmUrl;
window.updateUtmGeneratorPreview = updateUtmGeneratorPreview;
window.openAddUtmModal = openAddUtmModal;
window.closeAddUtmModal = closeAddUtmModal;
window.handleAddUtmSubmit = handleAddUtmSubmit;
window.deleteUtmRecord = deleteUtmRecord;
window.editUtmRecord = editUtmRecord;
"""
# Replace in html
s_idx = html.find('// ================= MASTER PACKAGES & ADS + UTM TRACKER ENGINE =================')
if s_idx != -1:
e_idx = html.find('function scrollToVipAlerts()', s_idx)
if e_idx != -1:
html = html[:s_idx] + utm_engine_js.strip() + '\n\n ' + html[e_idx:]
print("Replaced UTM Engine in live_marketing_index.html!")
# Update Add UTM Modal HTML with exact Google Sheet Fields (gen, Landing, Campaign, Medium, Source, Content, Term, Final UTM)
new_modal_html = """
<!-- ================= 5. ADD UTM CAMPAIGN MODAL (EXACT GOOGLE SHEET SPEC) ================= -->
<div id="addUtmModal" style="display: none; position: fixed; inset: 0; background: rgba(15, 23, 42, 0.65); backdrop-filter: blur(5px); z-index: 10000; align-items: center; justify-content: center; padding: 1rem;">
<div style="background: var(--bg-card); border: 1px solid var(--border-color); border-radius: 16px; width: 100%; max-width: 620px; max-height: 90vh; overflow-y: auto; box-shadow: 0 25px 50px -12px rgba(0,0,0,0.25); padding: 1.5rem;">
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 1.25rem; border-bottom: 1px solid var(--border-color); padding-bottom: 0.75rem;">
<div style="display: flex; align-items: center; gap: 8px;">
<span style="font-size: 1.3rem;">🎯</span>
<h3 style="margin: 0; font-size: 1.1rem; font-weight: 800; color: var(--text-main);">ساخت و ثبت UTM جدید (مطابق ساختار گوگل شیت)</h3>
</div>
<button type="button" onclick="closeAddUtmModal()" style="background: none; border: none; font-size: 1.3rem; cursor: pointer; color: var(--text-muted);">&times;</button>
</div>
<form onsubmit="handleAddUtmSubmit(event)">
<div style="margin-bottom: 12px;">
<label style="display: block; font-size: 0.78rem; font-weight: 700; color: var(--text-muted); margin-bottom: 4px;">عنوان سناریو / نام محتوا *:</label>
<input type="text" id="newUtmTitle" required placeholder="مثال: استوری اینستا زاده شیطان / ریلز معرفی آرت" style="width: 100%; padding: 8px 12px; border-radius: 8px; border: 1px solid var(--border-color); background: var(--bg-body); color: var(--text-main); font-size: 0.82rem;">
</div>
<div style="margin-bottom: 12px;">
<label style="display: block; font-size: 0.78rem; font-weight: 700; color: var(--text-muted); margin-bottom: 4px;">آدرس لندینگ پیج (Landing Page) *:</label>
<input type="text" id="newUtmLanding" required oninput="updateUtmGeneratorPreview()" placeholder="https://ekeepa.co/room/3050011/زاده-شیطان" style="width: 100%; padding: 8px 12px; border-radius: 8px; border: 1px solid var(--border-color); background: var(--bg-body); color: var(--text-main); font-family: monospace; font-size: 0.8rem; direction: ltr;">
</div>
<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 12px; margin-bottom: 12px;">
<div>
<label style="display: block; font-size: 0.78rem; font-weight: 700; color: var(--text-muted); margin-bottom: 4px;">شناسه رهگیری اختصاصی (gen) *:</label>
<input type="text" id="newUtmGen" required oninput="updateUtmGeneratorPreview()" placeholder="i-story-14050701" style="width: 100%; padding: 8px 12px; border-radius: 8px; border: 1px solid var(--border-color); background: var(--bg-body); color: var(--primary); font-family: monospace; font-weight: 800; font-size: 0.82rem; direction: ltr;">
</div>
<div>
<label style="display: block; font-size: 0.78rem; font-weight: 700; color: var(--text-muted); margin-bottom: 4px;">کمپین (utm_campaign):</label>
<select id="newUtmCampaign" onchange="updateUtmGeneratorPreview()" style="width: 100%; padding: 8px; border-radius: 8px; border: 1px solid var(--border-color); background: var(--bg-body); color: var(--text-main); font-size: 0.8rem;">
<option value="ekp-list">🎭 ekp-list (اتاق فرار اکیپا)</option>
<option value="art-list">🎨 art-list (ورکشاپ‌های آرت)</option>
<option value="ads-list">📢 ads-list (تبلیغات ادز)</option>
<option value="story-list">📱 story-list (استوری‌ها)</option>
<option value="reel-list">🎬 reel-list (ریلز)</option>
<option value="pro-list">⚡ pro-list (پروموشن)</option>
</select>
</div>
</div>
<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 12px; margin-bottom: 12px;">
<div>
<label style="display: block; font-size: 0.78rem; font-weight: 700; color: var(--text-muted); margin-bottom: 4px;">منبع (utm_source):</label>
<select id="newUtmSource" onchange="updateUtmGeneratorPreview()" style="width: 100%; padding: 8px; border-radius: 8px; border: 1px solid var(--border-color); background: var(--bg-body); color: var(--text-main); font-size: 0.8rem;">
<option value="instagram">📸 اینستاگرام (instagram)</option>
<option value="telegram">✈️ تلگرام (telegram)</option>
<option value="google">🔍 گوگل ادز (google)</option>
<option value="linkedin">💼 لینکدین (linkedin)</option>
<option value="bale">💬 بله (bale)</option>
</select>
</div>
<div>
<label style="display: block; font-size: 0.78rem; font-weight: 700; color: var(--text-muted); margin-bottom: 4px;">مدیوم (utm_medium):</label>
<select id="newUtmMedium" onchange="updateUtmGeneratorPreview()" style="width: 100%; padding: 8px; border-radius: 8px; border: 1px solid var(--border-color); background: var(--bg-body); color: var(--text-main); font-size: 0.8rem;">
<option value="social_organic_ekp">social_organic_ekp (سوشال اکیپا)</option>
<option value="social_organic_art">social_organic_art (سوشال آرت)</option>
<option value="cpc">cpc (تبلیغ کلیکی)</option>
<option value="channel_post">channel_post (پست کانال)</option>
<option value="direct_dm">direct_dm (دایرکت)</option>
</select>
</div>
</div>
<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 12px; margin-bottom: 12px;">
<div>
<label style="display: block; font-size: 0.78rem; font-weight: 700; color: var(--text-muted); margin-bottom: 4px;">محتوای UTM اختیاری (utm_content):</label>
<input type="text" id="newUtmContent" oninput="updateUtmGeneratorPreview()" placeholder="story_sticker_20" style="width: 100%; padding: 8px 12px; border-radius: 8px; border: 1px solid var(--border-color); background: var(--bg-body); color: var(--text-main); font-family: monospace; font-size: 0.8rem; direction: ltr;">
</div>
<div>
<label style="display: block; font-size: 0.78rem; font-weight: 700; color: var(--text-muted); margin-bottom: 4px;">کلمه کلیدی اختیاری (utm_term):</label>
<input type="text" id="newUtmTerm" oninput="updateUtmGeneratorPreview()" placeholder="escape_room_tehran" style="width: 100%; padding: 8px 12px; border-radius: 8px; border: 1px solid var(--border-color); background: var(--bg-body); color: var(--text-main); font-family: monospace; font-size: 0.8rem; direction: ltr;">
</div>
</div>
<!-- Final Generated URL Preview -->
<div style="margin-bottom: 14px; background: var(--bg-body); padding: 10px 12px; border-radius: 10px; border: 1px solid var(--border-color);">
<label style="display: block; font-size: 0.75rem; font-weight: 800; color: var(--primary); margin-bottom: 4px;">🔗 پیش‌نمایش لینک نهایی تولیدشده (Final UTM URL):</label>
<textarea id="newUtmFinalPreview" rows="2" readonly style="width: 100%; padding: 8px 10px; border-radius: 6px; border: 1px solid var(--border-color); background: var(--bg-card); color: var(--text-main); font-family: monospace; font-size: 0.74rem; direction: ltr; resize: none;"></textarea>
</div>
<!-- Performance Initial Counters -->
<div style="display: grid; grid-template-columns: 1fr 1fr 1fr 1fr; gap: 8px; margin-bottom: 16px; background: var(--bg-body); padding: 10px; border-radius: 10px; border: 1px solid var(--border-color);">
<div>
<label style="display: block; font-size: 0.7rem; font-weight: 700; color: var(--text-muted); margin-bottom: 2px;">کلیک اولیه:</label>
<input type="number" id="newUtmClicks" value="0" style="width: 100%; padding: 6px; border-radius: 6px; border: 1px solid var(--border-color); background: var(--bg-card); color: var(--text-main); font-size: 0.78rem;">
</div>
<div>
<label style="display: block; font-size: 0.7rem; font-weight: 700; color: var(--text-muted); margin-bottom: 2px;">لید / تماس:</label>
<input type="number" id="newUtmLeads" value="0" style="width: 100%; padding: 6px; border-radius: 6px; border: 1px solid var(--border-color); background: var(--bg-card); color: var(--text-main); font-size: 0.78rem;">
</div>
<div>
<label style="display: block; font-size: 0.7rem; font-weight: 700; color: var(--text-muted); margin-bottom: 2px;">خرید موفق:</label>
<input type="number" id="newUtmSales" value="0" style="width: 100%; padding: 6px; border-radius: 6px; border: 1px solid var(--border-color); background: var(--bg-card); color: var(--text-main); font-size: 0.78rem;">
</div>
<div>
<label style="display: block; font-size: 0.7rem; font-weight: 700; color: var(--text-muted); margin-bottom: 2px;">درآمد (تومان):</label>
<input type="number" id="newUtmRevenue" value="0" style="width: 100%; padding: 6px; border-radius: 6px; border: 1px solid var(--border-color); background: var(--bg-card); color: var(--text-main); font-size: 0.78rem;">
</div>
</div>
<div style="display: flex; justify-content: flex-end; gap: 8px; border-top: 1px solid var(--border-color); padding-top: 1rem;">
<button type="button" onclick="closeAddUtmModal()" class="date-btn" style="padding: 8px 16px; font-size: 0.8rem;">انصراف</button>
<button type="submit" class="date-btn active" style="padding: 8px 20px; font-size: 0.82rem; font-weight: 800; background: var(--primary); color: #fff;">💾 ثبت و فعال‌سازی در شیت و ردیاب</button>
</div>
</form>
</div>
</div>
"""
# Replace modal in HTML
if '<div id="addUtmModal"' in html:
start_m = html.find('<!-- ================= 5. ADD UTM CAMPAIGN MODAL')
if start_m == -1:
start_m = html.find('<div id="addUtmModal"')
end_m = html.find('</body>', start_m)
html = html[:start_m] + new_modal_html.strip() + '\n\n' + html[end_m:]
else:
html = html.replace('</body>', new_modal_html + '\n</body>')
with open('/workspace/live_marketing_index.html', 'w', encoding='utf-8') as f:
f.write(html)
print("Saved updated live_marketing_index.html with full Google Sheet UTM integration!")