/* global React, Panel, KPI, fmtN, fmtEurM, fmtEur, MONTHS, MONTHS_FULL */ /* Kampanya Yönetimi — the action side of the CRM (14_fs/docs/2026-10-13-crm-revenue-loop-design.md, WP5). Audience (CRM segment / fill opportunity / guests handed over by Misafir 360) → package → channel → message → schedule → simulated send. Seeded campaign results come from crm.json (window.loadCrm); campaigns created here are demo simulations kept in this browser (localStorage fs_campaigns_v1) and nothing is ever sent. Agency-owned guests are always reached through their agency, never directly. Message previews are per-language CONTENT (guests get Russian; TR/EN are previews for the desk), so the template copy below is written per language instead of going through window.t. */ (() => { const h = React.createElement; const { useState, useEffect, useMemo } = React; const CP_STORE_KEY = 'fs_campaigns_v1'; const CP_MAX_IDS = 500; const CP_TIMEOUT_MS = 25000; const CP_LANGS = ['ru', 'tr', 'en']; const CP_LIMIT = { sms: 160, telegram: 350 }; const CP_CONTACT_RANK = { booked: 0, clicked: 1, opened: 2, sent: 3 }; // Module-level store: survives the remount a language switch causes (app.jsx keys pages by LANG), // and AI replies that arrive after such a remount still land in the current draft. const cpStore = { view: 'list', draft: null, openId: null, toast: null, saved: null, subs: new Set() }; const cpSet = (patch) => { Object.assign(cpStore, typeof patch === 'function' ? patch(cpStore) : patch); cpStore.subs.forEach(f => f()); }; const cpSetDraft = (fn) => cpSet(s => ({ draft: s.draft ? fn(s.draft) : s.draft })); // ---------- i18n: templates with {placeholders} + plural variants (en_1, ru_1, ru_2) ---------- const cpRuForm = (n) => { const a = Math.abs(n) % 100, b = a % 10; if (a > 10 && a < 20) return ''; return b === 1 ? 'ru_1' : (b >= 2 && b <= 4) ? 'ru_2' : ''; }; const cpTx = (key, vars) => { let s = window.t(key); const e = window.I18N_DICT && window.I18N_DICT[key]; const n = vars && vars.n; if (e && typeof n === 'number') { if (window.LANG === 'en' && n === 1 && e.en_1) s = e.en_1; if (window.LANG === 'ru') { const f = cpRuForm(n); if (f && e[f]) s = e[f]; } } return String(s == null ? '' : s).replace(/\{(\w+)\}/g, (m, k) => { const v = vars ? vars[k] : null; return v == null ? '' : typeof v === 'number' ? fmtN(v) : v; }); }; // {tr, en, ru} of a dictionary key — for stored names that must read in every language later. const cpL3 = (key) => { const e = (window.I18N_DICT && window.I18N_DICT[key]) || {}; return { tr: key, en: e.en || key, ru: e.ru || key }; }; // ---------- formatting ---------- const cpDec = (v, d) => { if (v == null || isNaN(v)) return '—'; const s = Number(v).toFixed(d); return window.LANG === 'en' ? s : s.replace('.', ','); }; const cpPct = (v, d = 1) => (v == null || isNaN(v) ? '—' : window.LANG === 'tr' ? '%' + cpDec(v, d) : cpDec(v, d) + '%'); const cpShare = (a, b) => (b ? (a || 0) / b * 100 : null); const cpCount = (v) => (v == null || isNaN(v) ? '—' : Math.abs(v - Math.round(v)) < 1e-9 ? fmtN(Math.round(v)) : cpDec(v, 1)); // Projected counts are expected values: whole numbers from 10 up, one decimal below, "<0,1" for a trace. const cpProjCount = (v) => (v == null || isNaN(v) ? '—' : v >= 10 ? fmtN(Math.round(v)) : v >= 0.05 ? cpDec(v, 1) : v > 0 ? '<' + cpDec(0.1, 1) : '0'); const cpEur = (v) => (v == null || isNaN(v) ? '—' : Math.abs(v) >= 1e5 ? fmtEurM(v) : fmtEur(Math.round(v))); const cpDate = (iso) => { const p = String(iso || '').split('-').map(Number); if (!p[0] || !p[1]) return '—'; return p[2] ? p[2] + ' ' + window.t(MONTHS[p[1]]) + ' ' + p[0] : window.t(MONTHS_FULL[p[1]]) + ' ' + p[0]; }; const cpAddDays = (iso, n) => { const p = String(iso || '').split('-').map(Number); return new Date(Date.UTC(p[0], (p[1] || 1) - 1, (p[2] || 1) + n)).toISOString().slice(0, 10); }; const cpGuestName = (g) => (g ? (window.LANG === 'ru' && g.name_cyr ? g.name_cyr : g.name) || g.id : '—'); const cpParty = (p) => cpTx('{n} yetişkin', { n: (p && p.adults) || 0 }) + (p && p.children ? ' + ' + cpTx('{n} çocuk', { n: p.children }) : ''); // "AZURE BY YELKEN HOTEL (EX.GRAND PARK BODRUM)" → "Azure by Yelken Hotel" (for messages + names) const cpHotel = (name) => { if (!name) return ''; let s = String(name).replace(/\s*\(\s*EX\.?[^)]*\)\s*/gi, ' ').replace(/\s+/g, ' ').trim(); if (!/[a-zçğıöşü]/.test(s)) { s = s.replace(/İ/g, 'I').toLowerCase() .replace(/(^|[\s&/-])(\S)/g, (m, a, b) => a + b.toUpperCase()) .replace(/ (By|And|Of|The) /g, (m, w) => ' ' + w.toLowerCase() + ' '); } return s; }; // ---------- labels ---------- const cpChannelName = (c) => (c === 'email' ? window.t('E-posta') : c === 'sms' ? window.t('SMS') : c === 'telegram' ? window.t('Telegram') : c === 'agency' ? window.t('Acente bülteni') : String(c || '—')); const cpStatus = (s) => (s === 'done' ? [window.t('Tamamlandı'), 'pill-info'] : s === 'running' ? [window.t('Devam ediyor'), 'pill-pos'] : s === 'scheduled' ? [window.t('Planlandı'), 'pill-warn'] : [String(s || '—'), 'pill-outline']); // Same contact-status words as the Misafir 360 contact history. const cpContactStatus = (s) => (s === 'booked' ? [window.t('Rezervasyon yaptı'), 'pill-pos'] : s === 'clicked' ? [window.t('Tıklandı'), 'pill-warn'] : s === 'opened' ? [window.t('Açıldı'), 'pill-info'] : [window.t('Gönderildi'), 'pill-outline']); const cpStepLabel = (n) => (n === 1 ? window.t('Hedef kitle') : n === 2 ? window.t('Paket') : n === 3 ? window.t('Kanal') : n === 4 ? window.t('Mesaj') : window.t('Zamanlama')); const cpOppKind = (o) => (o && o.kind === 'flight' ? window.t('Uçuş doluluğu') : window.t('Otel kontenjanı')); // ---------- storage (demo-created campaigns; every access guarded) ---------- const cpLoadSaved = () => { try { const a = JSON.parse(window.localStorage.getItem(CP_STORE_KEY) || '[]'); return Array.isArray(a) ? a.filter(c => c && typeof c.id === 'string' && c.demo && c.audience) : []; } catch (e) { return []; } }; const cpWriteSaved = (list) => { try { window.localStorage.setItem(CP_STORE_KEY, JSON.stringify(list)); return true; } catch (e) { return false; } }; // ---------- CRM derived (once per crm.json) ---------- const cpChannelRates = (campaigns) => { const blank = () => ({ sent: 0, opened: 0, clicked: 0, booked: 0 }); const by = {}, all = blank(); campaigns.forEach(c => { if (!c || c.demo || !c.sent) return; const a = by[c.channel] = by[c.channel] || blank(); [a, all].forEach(x => { x.sent += c.sent || 0; x.opened += c.opened || 0; x.clicked += c.clicked || 0; x.booked += c.booked || 0; }); }); const fin = x => Object.assign(x, { open: x.sent ? x.opened / x.sent : 0, click: x.sent ? x.clicked / x.sent : 0, book: x.sent ? x.booked / x.sent : 0 }); Object.keys(by).forEach(k => fin(by[k])); fin(all); return { by, all }; }; const cpRateFor = (rates, ch) => (rates.by[ch] && rates.by[ch].sent ? rates.by[ch] : rates.all); const cpDerivedCache = new WeakMap(); const cpDerived = (crm) => { if (cpDerivedCache.has(crm)) return cpDerivedCache.get(crm); const contacts = {}, eligible = {}, oppById = {}, offers = []; (crm.guests || []).forEach(g => { (g.contacts || []).forEach(c => { (contacts[c.campaign_id] = contacts[c.campaign_id] || []).push({ g, c }); }); if (g.offer) { offers.push([g, g.offer]); (eligible[g.segment] = eligible[g.segment] || []).push(g.id); } }); (crm.opportunities || []).forEach(o => { if (o && o.id) oppById[o.id] = o; }); const d = { contacts, eligible, oppById, offers, rates: cpChannelRates(crm.campaigns || []) }; cpDerivedCache.set(crm, d); return d; }; // ---------- audience ---------- // Segment audiences are the guests with an open CRM offer (same "eligible" set Misafir 360 hands over). const cpAudienceGuests = (crm, aud) => { if (!aud) return []; const D = cpDerived(crm); let ids = aud.guestIds && aud.guestIds.length ? aud.guestIds : null; if (!ids && aud.type === 'segment') ids = D.eligible[aud.id] || []; if (!ids && aud.type === 'opportunity') ids = (D.oppById[aud.id] && D.oppById[aud.id].guest_ids) || []; return (ids || []).map(id => crm.byId[id]).filter(Boolean); }; const cpAudienceLabel = (crm, aud) => { if (!aud) return '—'; if (aud.type === 'segment' && crm.segById[aud.id]) return window.crmLabel(crm.segById[aud.id].name); const o = aud.type === 'opportunity' ? cpDerived(crm).oppById[aud.id] : null; if (o) return window.crmLabel(o.title); return aud.label ? window.crmLabel(aud.label) : window.t('Seçili misafirler'); }; const cpStats = (guests) => { const direct = guests.filter(g => g.owner !== 'agency'), agency = guests.filter(g => g.owner === 'agency'); const reach = {}; ['email', 'sms', 'telegram'].forEach(ch => { reach[ch] = direct.filter(g => g.consent && g.consent[ch]).length; }); return { size: guests.length, direct: direct.length, agency: agency.length, agencies: new Set(agency.map(g => g.agency || '—')).size, reach }; }; const cpReach = (stats, ch) => (ch === 'agency' ? stats.agency : stats.reach[ch] || 0); const cpDefaultChannel = (stats) => { const best = ['email', 'telegram', 'sms'].filter(ch => stats.reach[ch] > 0) .sort((a, b) => stats.reach[b] - stats.reach[a])[0]; return best || (stats.agency ? 'agency' : 'email'); }; // Agency-owned guests always go through their agency; direct guests need consent for the channel. const cpRoute = (stats, ch) => (ch === 'agency' ? { channel: ch, direct: 0, agency: stats.agency, excluded: stats.direct, noConsent: 0 } : { channel: ch, direct: stats.reach[ch] || 0, agency: stats.agency, excluded: 0, noConsent: stats.direct - (stats.reach[ch] || 0) }); // ---------- package defaults + price ---------- const cpMode = (arr) => { const c = new Map(); let best = null, bc = 0; arr.forEach(v => { if (v == null || v === '') return; const n = (c.get(v) || 0) + 1; c.set(v, n); if (n > bc || (n === bc && String(v) < String(best))) { best = v; bc = n; } }); return best; }; const cpMedian = (a) => { const s = a.filter(v => isFinite(v) && v > 0).sort((x, y) => x - y); if (!s.length) return null; const m = s.length >> 1; return s.length % 2 ? s[m] : (s[m - 1] + s[m]) / 2; }; const cpPax = (g) => Math.max(1, ((g && g.party && g.party.adults) || 0) + ((g && g.party && g.party.children) || 0)); // Offer prices are net of the offer's discount for the guest's whole party → gross price per person-night. const cpGross = ([g, o]) => (o.price_eur || 0) / (1 - Math.min(90, Math.max(0, o.discount_pct || 0)) / 100) / (cpPax(g) * Math.max(1, o.nights || 1)); const cpPriceOf = (pkg) => (!pkg || pkg.ppn == null ? null : Math.round(pkg.ppn * (pkg.party.adults + pkg.party.children) * pkg.nights * (1 - pkg.discount_pct / 100) / 10) * 10); const cpRouteDest = (route) => { const p = String(route || '').split('→'); return p.length > 1 ? p[p.length - 1].trim() : null; }; const cpYm = (iso) => String(iso || '').slice(0, 7) || null; const cpDefaultPackage = (crm, aud, guests) => { const D = cpDerived(crm); const pairs = guests.filter(g => g.offer).map(g => [g, g.offer]); const opp = aud.type === 'opportunity' ? D.oppById[aud.id] : null; const single = guests.length === 1 ? guests[0] : null; const pkg = { hotel: null, sub_region: null, room: null, check_in: null, flight_no: null, route: null, nights: 7, discount_pct: 0, party: { adults: 2, children: 0 }, ppn: null, basis: 'segment', basisN: null, opp: opp || null }; let rel = pairs; if (single) { const o = single.offer; pkg.basis = 'guest'; pkg.party = { adults: (single.party && single.party.adults) || 2, children: (single.party && single.party.children) || 0 }; if (o) { Object.assign(pkg, { hotel: o.hotel || null, sub_region: o.sub_region || null, room: o.room || null, check_in: o.check_in || null, flight_no: (o.flight && o.flight.no) || null, nights: o.nights || 7, discount_pct: o.discount_pct || 0 }); rel = [[single, o]]; } else { const p = single.prefs || {}; Object.assign(pkg, { sub_region: p.sub_region || null, room: p.room || null, nights: p.nights || 7, check_in: cpYm(single.next_window && single.next_window.start) }); rel = []; } } else if (opp) { pkg.check_in = opp.date || null; if (opp.kind === 'flight') { Object.assign(pkg, { basis: 'flight', flight_no: opp.flight_no || null, route: opp.route || null, sub_region: cpRouteDest(opp.route) || cpMode(pairs.map(([, o]) => o.sub_region)) }); } else { Object.assign(pkg, { basis: 'allotment', hotel: opp.hotel || null, room: opp.room || null, sub_region: cpMode(pairs.map(([, o]) => o.sub_region)) || String(opp.route || '').replace(/\s*\(.*\)\s*$/, '') || null }); rel = pairs.filter(([, o]) => o.hotel === opp.hotel); } } else if (pairs.length) { // the audience's most common offer month → sub-region → hotel const ym = cpMode(pairs.map(([, o]) => cpYm(o.check_in))); const pm = pairs.filter(([, o]) => cpYm(o.check_in) === ym); const sub = cpMode(pm.map(([, o]) => o.sub_region)); const p = pm.filter(([, o]) => o.sub_region === sub); const hotel = cpMode(p.map(([, o]) => o.hotel)); const ph = p.filter(([, o]) => o.hotel === hotel); Object.assign(pkg, { hotel, sub_region: sub, room: cpMode(ph.map(([, o]) => o.room)), check_in: ym, basisN: { month: pm.length, sub: p.length, hotel: ph.length } }); rel = ph.length ? ph : p; } else { Object.assign(pkg, { sub_region: cpMode(guests.map(g => g.prefs && g.prefs.sub_region)), check_in: cpMode(guests.map(g => cpYm(g.next_window && g.next_window.start))) }); } if (!(single && single.offer)) { const src = rel.length ? rel : pairs; pkg.nights = cpMode(src.map(([, o]) => o.nights)) || 7; pkg.discount_pct = cpMode(src.map(([, o]) => o.discount_pct)) || 0; } const ppn = (list) => cpMedian(list.map(cpGross)); pkg.ppn = ppn(rel) || (pkg.hotel && ppn(D.offers.filter(([, o]) => o.hotel === pkg.hotel))) || (pkg.sub_region && ppn(D.offers.filter(([, o]) => o.sub_region === pkg.sub_region))) || ppn(D.offers) || null; return pkg; }; const cpPackageWhy = (crm, aud, pkg, guests) => { if (pkg.basis === 'guest') { const o = guests[0] && guests[0].offer; return o && o.why && o.why.length ? o.why.map(w => window.crmLabel(w)).filter(Boolean) : [window.t('Misafirin tercihlerinden (açık CRM teklifi yok)')]; } if (pkg.opp) return [window.crmLabel(pkg.opp.title)].concat((pkg.opp.why || []).map(w => window.crmLabel(w))).filter(Boolean); const n = pkg.basisN; if (pkg.hotel && n) { return [cpTx('En sık teklif ayı: {m} · {n} teklif', { m: cpDate(pkg.check_in), n: n.month }), cpTx('O ayın en sık bölgesi: {s} · {n} teklif', { s: pkg.sub_region || '—', n: n.sub }), cpTx('Bölgenin en sık oteli: {h} · {n} teklif', { h: pkg.hotel, n: n.hotel })]; } return [window.t('Misafirlerin tercih ettiği bölge ve aydan')]; }; // ---------- message templates (per-language content, see the header) ---------- const CP_PLACE = { ru: { Bodrum: 'Бодрум', Belek: 'Белек', Kemer: 'Кемер', Istanbul: 'Стамбул', Alanya: 'Аланья', Antalya: 'Анталья', Side: 'Сиде', Marmaris: 'Мармарис', Fethiye: 'Фетхие', Lara: 'Лара', Moskova: 'Москва', 'St. Petersburg': 'Санкт-Петербург', 'Nizhniy Novgorod': 'Нижний Новгород', Yekaterinburg: 'Екатеринбург', Kazan: 'Казань', Novosibirsk: 'Новосибирск', Chelyabinsk: 'Челябинск', Samara: 'Самара', 'Rostov-na-Donu': 'Ростов-на-Дону', Omsk: 'Омск', Ufa: 'Уфа', Krasnoyarsk: 'Красноярск', Voronezh: 'Воронеж' }, tr: { Istanbul: 'İstanbul' }, en: { Moskova: 'Moscow' }, }; const cpPlace = (name, lang) => (name && CP_PLACE[lang] && CP_PLACE[lang][name]) || name || ''; const CP_MON = { ru: { gen: ['января', 'февраля', 'марта', 'апреля', 'мая', 'июня', 'июля', 'августа', 'сентября', 'октября', 'ноября', 'декабря'], nom: ['январь', 'февраль', 'март', 'апрель', 'май', 'июнь', 'июль', 'август', 'сентябрь', 'октябрь', 'ноябрь', 'декабрь'], prep: ['январе', 'феврале', 'марте', 'апреле', 'мае', 'июне', 'июле', 'августе', 'сентябре', 'октябре', 'ноябре', 'декабре'], short: ['янв', 'фев', 'мар', 'апр', 'мая', 'июн', 'июл', 'авг', 'сен', 'окт', 'ноя', 'дек'] }, tr: ['Ocak', 'Şubat', 'Mart', 'Nisan', 'Mayıs', 'Haziran', 'Temmuz', 'Ağustos', 'Eylül', 'Ekim', 'Kasım', 'Aralık'], en: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'], }; const cpRuPl = (n, one, few, many) => { const a = Math.abs(n) % 100, b = a % 10; return a > 10 && a < 20 ? many : b === 1 ? one : b >= 2 && b <= 4 ? few : many; }; const cpMoney = (v, lang) => { try { return new Intl.NumberFormat(lang === 'ru' ? 'ru-RU' : lang === 'tr' ? 'tr-TR' : 'en-GB', { style: 'currency', currency: 'EUR', maximumFractionDigits: 0 }).format(v); } catch (e) { return '€' + Math.round(v); } }; const cpWhen = (ci, lang) => { const p = String(ci || '').split('-').map(Number); if (!p[0] || !p[1]) return { short: '', phrase: '', tiny: '' }; const m = p[1] - 1, y = p[0], d = p[2]; if (lang === 'ru') { const R = CP_MON.ru; return d ? { short: `${d} ${R.gen[m]} ${y}`, phrase: `заезд ${d} ${R.gen[m]} ${y}`, tiny: `${d} ${R.short[m]}` } : { short: `${R.nom[m]} ${y}`, phrase: `заезд в ${R.prep[m]} ${y}`, tiny: `${R.short[m]} ${y}` }; } const M = CP_MON[lang === 'tr' ? 'tr' : 'en']; const tiny = d ? `${d} ${M[m].slice(0, 3)}` : `${M[m].slice(0, 3)} ${y}`; if (lang === 'tr') return d ? { short: `${d} ${M[m]} ${y}`, phrase: `giriş ${d} ${M[m]} ${y}`, tiny } : { short: `${M[m]} ${y}`, phrase: `giriş ${M[m]} ${y}`, tiny }; return d ? { short: `${d} ${M[m]} ${y}`, phrase: `check-in ${d} ${M[m]} ${y}`, tiny } : { short: `${M[m]} ${y}`, phrase: `check-in in ${M[m]} ${y}`, tiny }; }; const CP_COPY = { ru: { nights: n => `${n} ${cpRuPl(n, 'ночь', 'ночи', 'ночей')}`, party: p => (p.adults === 2 && !p.children ? 'за двоих' : `за ${p.adults} взр.${p.children ? ` + ${p.children} реб.` : ''}`), what: x => (x.hotel ? `${x.hotel} (${x.place})` : `отдых в регионе ${x.place}`), hello: x => (x.name ? `${x.name}, здравствуйте!` : 'Здравствуйте!'), intro: x => (x.single ? 'Мы подобрали для вас отдых' : 'Специальное предложение для вас'), price: (x, C) => (x.price == null ? '' : `${x.single ? 'Стоимость' : 'Цена'} ${C.party(x.party)}: ${x.single ? '' : 'от '}${x.money}` + `${x.disc ? `, скидка ${x.disc}% уже учтена` : ''}.`), flight: x => (x.flight ? `Перелёт рейсом ${x.flight}${x.route ? ` (${x.route})` : ''} включён.` : ''), cta: { email: 'Ответьте на это письмо — и мы всё забронируем.', telegram: 'Напишите нам здесь — и мы всё оформим.', sms: 'Ответьте на SMS для брони.' }, subject: x => (x.single ? `${x.name ? x.name + ', ' : ''}${x.place} ждёт вас: ${x.when.short}` : `${x.place} · ${x.when.short}: предложение для вас${x.disc ? `, −${x.disc}%` : ''}`), sms: (x, C) => `Fun & Sun: ${x.short || x.place}, ${x.when.short}, ${C.nights(x.nights)}` + `${x.price != null ? ` — ${x.single ? '' : 'от '}${x.money} ${C.party(x.party)}` : ''}${x.disc ? ` (−${x.disc}%)` : ''}.`, agencyHello: 'Уважаемые партнёры!', agencyIntro: x => (x.single && x.fullName ? `Предложение для вашего клиента ${x.fullName}` : 'Предложение для ваших клиентов'), agencyNote: x => (x.single ? 'Подобрано по истории поездок клиента. Будем рады бронированию.' : 'Подобрано по истории поездок ваших клиентов. Будем рады вашим бронированиям.'), agencySubject: x => `Fun & Sun · ${x.place} · ${x.when.short}: предложение для ваших клиентов`, }, tr: { nights: n => `${n} gece`, party: p => (p.adults === 2 && !p.children ? '2 kişi için' : `${p.adults} yetişkin${p.children ? ` + ${p.children} çocuk` : ''} için`), what: x => (x.hotel ? `${x.hotel} (${x.place})` : `${x.place} bölgesinde tatil`), hello: x => (x.name ? `Merhaba ${x.name},` : 'Merhaba,'), intro: x => (x.single ? 'Sizin için seçtiğimiz tatil' : 'Size özel teklif'), price: (x, C) => (x.price == null ? '' : `${C.party(x.party)} ${x.single ? 'fiyat' : 'başlangıç fiyatı'}: ${x.money}` + `${x.disc ? `, %${x.disc} indirim dahil` : ''}.`), flight: x => (x.flight ? `${x.flight} uçuşu${x.route ? ` (${x.route})` : ''} dahil.` : ''), cta: { email: 'Rezervasyon için bu e-postayı yanıtlamanız yeterli.', telegram: 'Buradan yazmanız yeterli, rezervasyonu hemen yapalım.', sms: 'Rezervasyon için yanıtlayın.' }, subject: x => (x.single ? `${x.name ? x.name + ', ' : ''}${x.place} sizi bekliyor: ${x.when.short}` : `${x.place} · ${x.when.short}: size özel teklif${x.disc ? `, %${x.disc} indirim` : ''}`), sms: (x, C) => `Fun & Sun: ${x.short || x.place}, ${x.when.short}, ${C.nights(x.nights)}` + `${x.price != null ? ` — ${C.party(x.party)} ${x.money}` : ''}${x.disc ? ` (%${x.disc} indirimli)` : ''}.`, agencyHello: 'Değerli iş ortağımız,', agencyIntro: x => (x.single && x.fullName ? `Müşteriniz ${x.fullName} için teklifimiz` : 'Müşterileriniz için teklifimiz'), agencyNote: x => (x.single ? 'Teklif, müşterinizin seyahat geçmişine göre hazırlandı. Rezervasyonunuzu bekliyoruz.' : 'Teklif, müşterilerinizin seyahat geçmişine göre hazırlandı. Rezervasyonlarınızı bekliyoruz.'), agencySubject: x => `Fun & Sun · ${x.place} · ${x.when.short}: müşterileriniz için teklif`, }, en: { nights: n => `${n} night${n === 1 ? '' : 's'}`, party: p => (p.adults === 2 && !p.children ? 'for two' : `for ${p.adults} adult${p.adults === 1 ? '' : 's'}${p.children ? ` + ${p.children} ${p.children === 1 ? 'child' : 'children'}` : ''}`), what: x => (x.hotel ? `${x.hotel} (${x.place})` : `a holiday in the ${x.place} region`), hello: x => (x.name ? `Hello ${x.name},` : 'Hello,'), intro: x => (x.single ? 'We have picked a holiday for you' : 'A special offer for you'), price: (x, C) => (x.price == null ? '' : `Price ${C.party(x.party)}${x.single ? ':' : ' from'} ${x.money}` + `${x.disc ? `, ${x.disc}% discount included` : ''}.`), flight: x => (x.flight ? `Flight ${x.flight}${x.route ? ` (${x.route})` : ''} included.` : ''), cta: { email: 'Just reply to this email and we will book it for you.', telegram: 'Write to us here and we will book it right away.', sms: 'Reply to book.' }, subject: x => (x.single ? `${x.name ? x.name + ', ' : ''}${x.place} is waiting for you: ${x.when.short}` : `${x.place} · ${x.when.short}: an offer for you${x.disc ? `, ${x.disc}% off` : ''}`), sms: (x, C) => `Fun & Sun: ${x.short || x.place}, ${x.when.short}, ${C.nights(x.nights)}` + `${x.price != null ? ` — ${x.single ? '' : 'from '}${x.money} ${C.party(x.party)}` : ''}${x.disc ? ` (${x.disc}% off)` : ''}.`, agencyHello: 'Dear partner,', agencyIntro: x => (x.single && x.fullName ? `Our offer for your client ${x.fullName}` : 'Our offer for your clients'), agencyNote: x => (x.single ? "Selected from your client's travel history. We look forward to the booking." : "Selected from your clients' travel history. We look forward to your bookings."), agencySubject: x => `Fun & Sun · ${x.place} · ${x.when.short}: an offer for your clients`, }, }; const cpTplContext = (guests, pkg, price, lang) => { const g = guests.length === 1 ? guests[0] : null; const full = g ? ((lang === 'ru' && g.name_cyr) || g.name || '') : ''; return { single: !!g, name: full.split(' ')[0] || '', fullName: full, hotel: cpHotel(pkg.hotel), short: cpHotel(pkg.hotel), place: cpPlace(pkg.sub_region, lang) || cpPlace(cpRouteDest(pkg.route), lang), route: pkg.route ? pkg.route.split('→').map(s => cpPlace(s.trim(), lang)).join(' → ') : null, when: cpWhen(pkg.check_in, lang), nights: pkg.nights, party: pkg.party, price, money: price == null ? '' : cpMoney(price, lang), disc: pkg.discount_pct || 0, flight: pkg.flight_no, }; }; const cpTemplate = (lang, channel, x) => { const C = CP_COPY[lang] || CP_COPY.ru; const line = `${C.intro(x)}: ${C.what(x)}, ${x.when.phrase}, ${C.nights(x.nights)}.`; const price = C.price(x, C), flight = C.flight(x); if (channel === 'sms') { const tries = [C.sms(x, C) + ' ' + C.cta.sms, C.sms(Object.assign({}, x, { short: null }), C) + ' ' + C.cta.sms, C.sms(Object.assign({}, x, { short: null }), C)]; const ok = tries.find(s => s.length <= CP_LIMIT.sms); return { subject: null, body: ok || tries[2].slice(0, CP_LIMIT.sms - 1) + '…' }; } if (channel === 'telegram') { const full = [C.hello(x), line, [price, flight].filter(Boolean).join(' '), C.cta.telegram, 'Fun & Sun'].filter(Boolean).join('\n'); const lean = [C.hello(x), line, price, C.cta.telegram, 'Fun & Sun'].filter(Boolean).join('\n'); return { subject: null, body: full.length <= CP_LIMIT.telegram ? full : lean }; } if (channel === 'agency') { const intro = `${C.agencyIntro(x)}: ${C.what(x)}, ${x.when.phrase}, ${C.nights(x.nights)}.`; return { subject: C.agencySubject(x), body: [C.agencyHello, intro, [price, flight].filter(Boolean).join(' '), C.agencyNote(x)].filter(Boolean).join('\n') + '\n\nFun & Sun' }; } return { subject: C.subject(x), body: [C.hello(x), line, [price, flight].filter(Boolean).join(' '), C.cta.email].filter(Boolean).join('\n') + '\n\nFun & Sun' }; }; // ---------- projection (simulated sends) ---------- // CRM model, same numbers as Misafir 360 / Doluluk Fırsatları: every reached guest books with their offer // propensity at their own package price (their CRM offer; nights / discount edits re-price it, propensity stays). // Reached = direct guests with consent for the channel + agency-owned guests (always via their agency). // Comparison: the seeded campaigns' booking rate on that channel (agency bulletin rate for agency-routed guests) // at the same prices. const cpR3 = (v) => Math.round(v * 1000) / 1000; const cpGuestValue = (g, pkg, edits) => { const o = g.offer, p = g.propensity || 0; if (o && edits.nights == null && edits.discount_pct == null) { // untouched: exactly the CRM's expected revenue return { p, price: o.price_eur || 0, exp: o.expected_rev_eur != null ? o.expected_rev_eur : Math.round((o.price_eur || 0) * p) }; } const nights = edits.nights != null ? edits.nights : o ? o.nights || pkg.nights : pkg.nights; const disc = edits.discount_pct != null ? edits.discount_pct : o ? o.discount_pct || 0 : pkg.discount_pct; const ppn = o ? cpGross([g, o]) : pkg.ppn; const price = ppn ? Math.round(ppn * cpPax(g) * nights * (1 - disc / 100) / 10) * 10 : 0; return { p, price, exp: Math.round(price * p) }; }; const cpProject = (rates, guests, channel, pkg, edits) => { const rd = cpRateFor(rates, channel).book, ra = cpRateFor(rates, 'agency').book; const t = { sent: 0, booked: 0, rev: 0, bBooked: 0, bRev: 0 }, ag = {}; guests.forEach(g => { const viaAgency = g.owner === 'agency'; if (!viaAgency && (channel === 'agency' || !(g.consent && g.consent[channel]))) return; // not reached const v = cpGuestValue(g, pkg, edits), r = viaAgency ? ra : rd; t.sent += 1; t.booked += v.p; t.rev += v.exp; t.bBooked += r; t.bRev += r * v.price; if (viaAgency) { const k = g.agency || '—', a = ag[k] = ag[k] || { agency: k, sent: 0, booked: 0, revenue_eur: 0 }; a.sent += 1; a.booked += v.p; a.revenue_eur += v.exp; } }); return { sent: t.sent, opened: null, clicked: null, booked: cpR3(t.booked), revenue_eur: t.rev, blast: { booked: cpR3(t.bBooked), revenue_eur: Math.round(t.bRev) }, by_agency: Object.keys(ag).sort().map(k => Object.assign(ag[k], { booked: cpR3(ag[k].booked) })) }; }; // ---------- names stored on a simulated campaign ({tr, en, ru}, readable in every UI language) ---------- const cpCampaignName = (crm, aud, pkg) => { const D = cpDerived(crm); const out = {}; CP_LANGS.forEach(l => { const where = cpHotel(pkg.hotel) || cpPlace(pkg.sub_region, l); const when = cpWhen(pkg.check_in, l).tiny; let head; if (aud.type === 'segment' && crm.segById[aud.id]) head = crm.segById[aud.id].name[l] || crm.segById[aud.id].name.tr; else if (aud.type === 'opportunity' && D.oppById[aud.id]) { const o = D.oppById[aud.id]; head = cpL3(o.kind === 'flight' ? 'Uçuş doluluğu' : 'Otel kontenjanı')[l]; out[l] = [head, o.kind === 'flight' ? (o.flight_no || where) : where, when].filter(Boolean).join(' · '); return; } else head = aud.label ? window.crmLabel(aud.label) : cpL3('Seçili misafirler')[l]; out[l] = [head, where, when].filter(Boolean).join(' · '); }); return out; }; const cpPackageLabel = (pkg) => { const out = {}; CP_LANGS.forEach(l => { const C = CP_COPY[l]; out[l] = [cpHotel(pkg.hotel) || cpPlace(pkg.sub_region, l), cpWhen(pkg.check_in, l).tiny, C.nights(pkg.nights), pkg.discount_pct ? (l === 'tr' ? '%' + pkg.discount_pct : '−' + pkg.discount_pct + '%') : null].filter(Boolean).join(' · '); }); return out; }; const cpNextId = (saved) => { const n = (saved || []).reduce((m, c) => Math.max(m, parseInt(String(c.id).replace(/\D/g, ''), 10) || 0), 0) + 1; return 'SIM-' + String(n).padStart(3, '0'); }; // ---------- AI message endpoint ---------- const cpAskAi = (payload) => { const ctrl = typeof AbortController !== 'undefined' ? new AbortController() : null; const timer = setTimeout(() => { if (ctrl) ctrl.abort(); }, CP_TIMEOUT_MS); return fetch(((typeof window !== 'undefined' && window.API_BASE_URL) || '') + '/api/crm/message', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload), signal: ctrl ? ctrl.signal : undefined, }) .then(r => (r.ok ? r.json() : Promise.reject(new Error('HTTP ' + r.status)))) .then(j => (j && j.configured === false ? { state: 'off' } : j && !j.error && j.body ? { state: 'ok', subject: j.subject || null, body: String(j.body) } : { state: 'error' })) .catch(() => ({ state: 'down' })) .finally(() => clearTimeout(timer)); }; const cpAiSummary = (draft, key, kinds) => { if (!draft.aiKey || draft.aiKey !== key) return null; const states = []; kinds.forEach(k => CP_LANGS.forEach(l => { const a = draft.ai[k + '|' + l]; if (a) states.push(a.state); })); if (!states.length) return null; if (states.includes('loading')) return 'loading'; if (states.every(s => s === 'ok')) return 'ok'; if (states.includes('ok')) return 'partial'; if (states.includes('error')) return 'error'; return states.includes('off') ? 'off' : 'down'; }; // ---------- start / prefill ---------- const cpNewDraft = (crm, aud) => ({ step: 1, maxStep: aud ? 2 : 1, src: aud ? aud.type : 'segment', aud: aud || null, prefill: aud && aud.type === 'guests' ? aud : null, edits: {}, channel: null, ai: {}, aiKey: null, msgLang: 'ru', when: 'now', date: cpAddDays(crm.as_of, 7) }); const cpStartNew = (crm, aud) => { cpSet({ view: 'new', openId: null, draft: cpNewDraft(crm, aud) }); const c = document.querySelector('.content'); if (c && c.scrollTo) c.scrollTo(0, 0); }; const cpAudFromPrefill = (crm, a) => { const type = ['segment', 'opportunity', 'guests'].indexOf(a.type) >= 0 ? a.type : 'guests'; const ids = Array.isArray(a.guest_ids) ? Array.from(new Set(a.guest_ids.filter(id => crm.byId[id]))) : []; return { type, id: type === 'guests' ? null : (a.id || null), guestIds: ids.length ? ids : null, label: a.label || null }; }; // ============================================================ shared blocks const CpFunnel = ({ c, projected }) => { const steps = [['sent', window.t('Gönderim')], ['opened', window.t('Açılma')], ['clicked', window.t('Tıklama')], ['booked', window.t('Rezervasyon')]]; const max = Math.max(1, c.sent || 0); return h('div', { className: 'cp-funnel' + (projected ? ' cp-projected' : '') }, steps.map((st, i) => st.concat(i)) .filter(([k]) => c[k] != null).map(([k, label, i]) => { const v = c[k] || 0; return h('div', { key: k, className: 'cp-funnel-row' }, h('div', { className: 'cp-funnel-l' }, label), h('div', { className: 'cp-funnel-track' }, h('span', { className: 'cp-funnel-bar cp-f' + i, style: { width: (v ? Math.max(1.2, v / max * 100) : 0) + '%' } })), h('div', { className: 'cp-funnel-v mono' }, projected && i ? '≈ ' + cpProjCount(v) : cpCount(v)), h('div', { className: 'cp-funnel-r mono' }, i ? cpPct(cpShare(v, c.sent)) : '')); })); }; // CRM projection + the bulk-send comparison at the same prices (step 5 and a simulated campaign's detail). const CpProjection = ({ c, channel, direct, agency }) => { const k = c.blast && c.blast.booked > 0 ? c.booked / c.blast.booked : null; const via = channel === 'agency' || !direct ? cpChannelName('agency') : agency ? cpChannelName(channel) + ' / ' + cpChannelName('agency') : cpChannelName(channel); return h('div', { className: 'cp-projection' }, h(CpFunnel, { c, projected: true }), h('div', { className: 'cp-revline' }, h('span', null, window.t('Tahmini gelir') + ': '), h('strong', { 'data-eur': c.revenue_eur }, '≈ ' + cpEur(c.revenue_eur))), c.blast && h('div', { className: 'cp-compare' }, cpTx('Toplu gönderim oranıyla: ~{n} rezervasyon · {v}', { n: cpProjCount(c.blast.booked), v: cpEur(c.blast.revenue_eur) }) .replace('~<', '<'), // a trace value already reads as approximate k != null && h('strong', null, ' · ' + (k >= 1 ? cpTx('CRM hedefleme ≈ {k}× daha verimli', { k: cpDec(k, 1) }) : cpTx('CRM tahmini toplu oranın altında ({k}×)', { k: cpDec(k, 1) })))), c.blast && h('div', { className: 'cp-hint' }, cpTx('Tahmin: ulaşılan her misafirin CRM teklif olasılığı × misafirin paket fiyatı. Karşılaştırma: geçmiş {c} kampanyalarının rezervasyon oranı, aynı fiyatlarla.', { c: via }))); }; const CpMsgCard = ({ channel, title, subject, body, loading }) => h('div', { className: 'cp-msg cp-msg-' + channel + (loading ? ' cp-msg-loading' : '') }, h('div', { className: 'cp-msg-top' }, h('span', { className: 'cp-msg-ch' }, title || cpChannelName(channel)), loading && h('span', { className: 'insight-shimmer' }), CP_LIMIT[channel] && h('span', { className: 'cp-msg-count mono' }, cpTx('{n} / {max} karakter', { n: (body || '').length, max: CP_LIMIT[channel] }))), subject && h('div', { className: 'cp-msg-subject' }, h('span', null, window.t('Konu') + ': '), subject), h('div', { className: 'cp-msg-body' }, body || '—')); const CpLangChips = ({ lang, onLang }) => h('div', { className: 'cp-langs', role: 'tablist', 'aria-label': window.t('Mesaj dili') }, CP_LANGS.map(l => h('button', { key: l, type: 'button', role: 'tab', 'aria-selected': l === lang, className: 'filter-chip' + (l === lang ? ' active' : ''), onClick: () => onLang(l) }, l.toUpperCase()))); const CpShowAll = ({ n, shown, onAll }) => (n > shown ? h('button', { type: 'button', className: 'btn btn-sm btn-ghost cp-more', onClick: onAll }, cpTx('Tümünü göster ({n})', { n })) : null); // ============================================================ list view const CpKpis = ({ crm, list }) => { const seeded = (crm.campaigns || []).filter(c => c && !c.demo); const since = cpAddDays(crm.as_of, -90); const recent = seeded.filter(c => String(c.start_date || '') >= since); const sum = (a, k) => a.reduce((s, c) => s + (c[k] || 0), 0); const active = list.filter(c => c.status === 'running' || c.status === 'scheduled'); const running = active.filter(c => c.status === 'running').length; const direct = seeded.filter(c => c.channel !== 'agency'), agency = seeded.filter(c => c.channel === 'agency'); const sent = sum(seeded, 'sent'), booked = sum(seeded, 'booked'), rev = sum(seeded, 'revenue_eur'); return h('div', { className: 'grid grid-5 gap-3 cp-kpis' }, h(KPI, { label: window.t('Aktif kampanya'), value: fmtN(active.length), sub: cpTx('{a} devam ediyor · {b} planlandı', { a: running, b: active.length - running }) }), h(KPI, { label: window.t('Gönderim · son 90 gün'), value: fmtN(sum(recent, 'sent')), sub: cpTx('{n} kampanya', { n: recent.length }) }), h(KPI, { label: window.t('Açılma oranı'), value: cpPct(cpShare(sum(seeded, 'opened'), sent)), sub: window.t('doğrudan') + ' ' + cpPct(cpShare(sum(direct, 'opened'), sum(direct, 'sent'))) + ' · ' + window.t('acente') + ' ' + cpPct(cpShare(sum(agency, 'opened'), sum(agency, 'sent'))) }), h(KPI, { label: window.t('Rezervasyonlar'), value: fmtN(booked), sub: cpTx('dönüşüm {p} · simülasyonlar hariç', { p: cpPct(cpShare(booked, sent)) }) }), h(KPI, { label: window.t('Kampanya geliri'), value: cpEur(rev), sub: cpTx('rezervasyon başına {v}', { v: cpEur(booked ? rev / booked : null) }) })); }; const cpChannelCell = (c) => cpChannelName(c.channel) + (c.channel !== 'agency' && c.split && c.split.agency ? ' + ' + window.t('acente') : ''); const CpTable = ({ crm, list, selId }) => { const num = (c, k) => h('td', { className: 'num mono cp-n' }, h('div', null, c[k] == null ? '—' : c.projected && k !== 'sent' ? '≈ ' + cpProjCount(c[k]) : cpCount(c[k])), k !== 'sent' && c[k] != null && h('div', { className: 'cp-rate' }, cpPct(cpShare(c[k], c.sent)))); return h(Panel, { title: window.t('Kampanyalar'), flush: true, sub: window.t('Satıra tıklayın: huni, mesaj ve misafirler') + ' · ' + window.t('simülasyonlar bu tarayıcıda saklanır') }, h('table', { className: 'tbl cp-table' }, h('thead', null, h('tr', null, h('th', null, window.t('Kampanya')), h('th', null, window.t('Durum')), h('th', null, window.t('Kitle')), h('th', null, window.t('Kanal')), h('th', null, window.t('Başlangıç')), h('th', { className: 'num' }, window.t('Gönderim')), h('th', { className: 'num' }, window.t('Açılma')), h('th', { className: 'num' }, window.t('Tıklama')), h('th', { className: 'num' }, window.t('Rez.')), h('th', { className: 'num' }, window.t('Gelir')))), h('tbody', null, list.map(c => { const st = cpStatus(c.status); return h('tr', { key: c.id, className: 'clickable' + (c.id === selId ? ' selected' : '') + (c.demo ? ' cp-row-sim' : ''), tabIndex: 0, onClick: () => cpSet({ openId: c.id }), onKeyDown: e => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); cpSet({ openId: c.id }); } } }, h('td', { className: 'cp-name-cell' }, h('div', { className: 'cp-name' }, window.crmLabel(c.name) || c.id), h('div', { className: 'cp-sub' }, c.id, c.demo && h('span', { className: 'cp-sim' }, window.t('Simülasyon')))), h('td', null, h('span', { className: 'pill ' + st[1] }, st[0])), h('td', { className: 'cp-aud-cell' }, h('div', { className: 'cp-aud' }, cpAudienceLabel(crm, c.audience)), h('div', { className: 'cp-sub' }, cpTx('{n} misafir', { n: (c.audience && c.audience.size) || c.sent || 0 }))), h('td', null, cpChannelCell(c)), h('td', { className: 'mono cp-date-cell' }, cpDate(c.start_date)), num(c, 'sent'), num(c, 'opened'), num(c, 'clicked'), num(c, 'booked'), h('td', { className: 'num mono cp-rev' }, (c.projected ? '≈ ' : '') + cpEur(c.revenue_eur))); })))); }; // ---------- campaign detail drawer ---------- const CpDrawer = ({ crm, c }) => { const [lang, setLang] = useState('ru'); const [allGuests, setAllGuests] = useState(false); const [allAgencies, setAllAgencies] = useState(false); const close = () => cpSet({ openId: null }); useEffect(() => { const k = e => { if (e.key === 'Escape') close(); }; window.addEventListener('keydown', k); return () => window.removeEventListener('keydown', k); }, []); const D = cpDerived(crm); const st = cpStatus(c.status); const rate = cpRateFor(D.rates, c.channel); const pk = c.package || {}; const aud = c.audience ? { type: c.audience.type, id: c.audience.id, guestIds: c.audience.guest_ids || null, label: c.audience.label } : null; const rows = c.demo ? cpAudienceGuests(crm, aud).map(g => ({ g, route: g.owner === 'agency' ? 'agency' : c.channel !== 'agency' && g.consent && g.consent[c.channel] ? c.channel : 'none' })) : (D.contacts[c.id] || []).slice().sort((a, b) => ((CP_CONTACT_RANK[a.c.status] ?? 9) - (CP_CONTACT_RANK[b.c.status] ?? 9)) || ((b.c.revenue_eur || 0) - (a.c.revenue_eur || 0)) || String(a.g.name).localeCompare(String(b.g.name))); const shownRows = allGuests ? rows : rows.slice(0, 12); const agencies = (c.by_agency || []).slice().sort((a, b) => (b.revenue_eur || 0) - (a.revenue_eur || 0) || (b.booked || 0) - (a.booked || 0) || (b.sent || 0) - (a.sent || 0) || String(a.agency).localeCompare(String(b.agency))); const shownAgencies = allAgencies ? agencies : agencies.slice(0, 8); const agFunnel = agencies.some(a => a.opened != null); // seeded results; projections carry bookings only const pick = (o) => (o ? o[lang] || o.ru || o.tr || '' : ''); const msg = typeof c.message === 'string' ? c.message : pick(c.message); const agMsg = c.agency_message ? pick(c.agency_message) : null; const remove = () => cpSet(s => { const saved = (s.saved || []).filter(x => x.id !== c.id); cpWriteSaved(saved); return { saved, openId: null }; }); const meta = (k, v) => h('div', { className: 'cp-meta-item' }, h('div', { className: 'cp-meta-k' }, k), h('div', { className: 'cp-meta-v' }, v)); const numCell = (v, proj) => h('td', { className: 'num mono' }, proj ? '≈ ' + cpProjCount(v) : cpCount(v)); const name = window.crmLabel(c.name) || c.id; return h('div', { className: 'cp-drawer-backdrop', onClick: close }, h('aside', { className: 'cp-drawer', role: 'dialog', 'aria-modal': 'true', 'aria-label': name, onClick: e => e.stopPropagation() }, h('div', { className: 'cp-drawer-head' }, h('div', { className: 'cp-drawer-kicker' }, h('span', { className: 'pill ' + st[1] }, st[0]), h('span', { className: 'mono' }, c.id), c.demo && h('span', { className: 'cp-sim' }, window.t('Simülasyon'))), h('button', { type: 'button', className: 'cp-close', onClick: close, 'aria-label': window.t('Kapat') }, '×'), h('h2', { className: 'cp-drawer-title' }, name)), h('div', { className: 'cp-drawer-body' }, h('div', { className: 'cp-meta' }, meta(window.t('Kitle'), cpAudienceLabel(crm, c.audience) + ' · ' + cpTx('{n} misafir', { n: (c.audience && c.audience.size) || c.sent || 0 })), meta(window.t('Kanal'), cpChannelCell(c) + (c.split && c.split.agency ? ' · ' + cpTx('{n} acente üzerinden', { n: c.split.agency }) : '')), meta(window.t('Başlangıç'), cpDate(c.start_date)), meta(window.t('Paket'), [window.crmLabel(pk.label), pk.price_eur != null || pk.price_from_eur != null ? fmtEur(pk.price_eur != null ? pk.price_eur : pk.price_from_eur) : null, pk.price_eur != null || pk.price_from_eur != null ? cpParty(pk.party || { adults: 2, children: 0 }) : null] .filter(Boolean).join(' · '))), h('section', { className: 'cp-sec' }, h('div', { className: 'cp-sec-head' }, h('div', { className: 'cp-sec-l' }, c.projected ? window.t('Tahmini huni') : window.t('Huni')), h('div', { className: 'cp-sec-r' }, c.projected ? window.t('CRM teklif olasılıklarından · gerçek gönderim yok') : cpTx('{c} ortalaması: açılma {o} · rezervasyon {b}', { c: cpChannelName(c.channel), o: cpPct(rate.open * 100), b: cpPct(rate.book * 100) }))), c.projected ? h(CpProjection, { c, channel: c.channel, direct: c.split && c.split.direct, agency: c.split && c.split.agency }) : h(React.Fragment, null, h(CpFunnel, { c }), h('div', { className: 'cp-revline' }, h('span', null, window.t('Gelir') + ': '), h('strong', null, cpEur(c.revenue_eur)), c.booked ? h('span', { className: 'cp-muted' }, ' · ' + cpTx('rezervasyon başına {v}', { v: cpEur(c.revenue_eur / c.booked) })) : null))), h('section', { className: 'cp-sec' }, h('div', { className: 'cp-sec-head' }, h('div', { className: 'cp-sec-l' }, window.t('Mesaj')), h(CpLangChips, { lang, onLang: setLang })), h('div', { className: 'cp-msgs' + (agMsg ? ' two' : '') }, h(CpMsgCard, { channel: c.channel, subject: c.subject ? pick(c.subject) : null, body: msg }), agMsg && h(CpMsgCard, { channel: 'agency', title: window.t('Acente notu'), subject: c.agency_subject ? pick(c.agency_subject) : null, body: agMsg })), c.demo && h('div', { className: 'cp-ai-note' }, c.message_source === 'ai' ? window.t('AI mesajı · yalnızca paket ve CRM bilgileriyle yazıldı') : window.t('Şablon mesaj · paket bilgilerinden'))), agencies.length > 0 && h('section', { className: 'cp-sec' }, h('div', { className: 'cp-sec-head' }, h('div', { className: 'cp-sec-l' }, window.t('Acente kırılımı')), h('div', { className: 'cp-sec-r' }, cpTx('{n} acente', { n: agencies.length }))), h('table', { className: 'tbl cp-mini' }, h('thead', null, h('tr', null, h('th', null, window.t('Acente')), h('th', { className: 'num' }, window.t('Gönderim')), agFunnel && h('th', { className: 'num' }, window.t('Açılma')), agFunnel && h('th', { className: 'num' }, window.t('Tıklama')), h('th', { className: 'num' }, window.t('Rez.')), h('th', { className: 'num' }, window.t('Gelir')))), h('tbody', null, shownAgencies.map(a => h('tr', { key: a.agency }, h('td', { style: { fontWeight: 500 } }, a.agency), numCell(a.sent), agFunnel && numCell(a.opened, c.projected), agFunnel && numCell(a.clicked, c.projected), numCell(a.booked, c.projected), h('td', { className: 'num mono' }, (c.projected ? '≈ ' : '') + cpEur(a.revenue_eur)))))), h(CpShowAll, { n: agencies.length, shown: shownAgencies.length, onAll: () => setAllAgencies(true) })), h('section', { className: 'cp-sec' }, h('div', { className: 'cp-sec-head' }, h('div', { className: 'cp-sec-l' }, c.demo ? window.t('Hedeflenen misafirler') : window.t('Temas edilen misafirler')), h('div', { className: 'cp-sec-r' }, cpTx('{n} misafir', { n: rows.length }))), rows.length === 0 ? h('div', { className: 'cp-muted' }, window.t('Bu kampanyada misafir kaydı yok.')) : h('table', { className: 'tbl cp-mini cp-guests' }, h('thead', null, h('tr', null, h('th', null, window.t('Misafir')), h('th', null, window.t('Şehir')), h('th', null, window.t('Sahiplik')), h('th', null, c.demo ? window.t('Rota') : window.t('Durum')), !c.demo && h('th', { className: 'num' }, window.t('Gelir')))), h('tbody', null, shownRows.map(r => { const g = r.g; const owner = g.owner === 'agency' ? (g.agency || window.t('Acente')) : window.t('Doğrudan'); let status; if (c.demo) { status = r.route === 'agency' ? h('span', { className: 'pill pill-info' }, window.t('Acente üzerinden')) : r.route === 'none' ? h('span', { className: 'pill pill-outline' }, window.t('İzin yok')) : h('span', { className: 'pill pill-pos' }, cpChannelName(r.route)); } else { const cs = cpContactStatus(r.c.status); status = h('span', { className: 'pill ' + cs[1] }, cs[0]); } return h('tr', { key: g.id }, h('td', { style: { fontWeight: 500 } }, cpGuestName(g)), h('td', null, g.city || '—'), h('td', null, owner), h('td', null, status), !c.demo && h('td', { className: 'num mono' }, r.c.revenue_eur ? cpEur(r.c.revenue_eur) : '—')); }))), h(CpShowAll, { n: rows.length, shown: shownRows.length, onAll: () => setAllGuests(true) })), c.demo && h('div', { className: 'cp-drawer-foot' }, h('button', { type: 'button', className: 'btn btn-sm btn-ghost', onClick: remove }, window.t('Simülasyonu kaldır')))))); }; // ============================================================ new-campaign flow const CpSteps = ({ step, maxStep }) => h('ol', { className: 'cp-steps' }, [1, 2, 3, 4, 5].map(n => h('li', { key: n }, h('button', { type: 'button', disabled: n > maxStep, 'aria-current': n === step ? 'step' : undefined, className: 'cp-step' + (n === step ? ' active' : '') + (n < step ? ' done' : ''), onClick: () => cpSetDraft(d => Object.assign({}, d, { step: n })) }, h('span', { className: 'cp-step-n mono' }, String(n).padStart(2, '0')), h('span', { className: 'cp-step-l' }, cpStepLabel(n)))))); const CpStat = ({ k, v, sub }) => h('div', { className: 'cp-stat' }, h('div', { className: 'cp-stat-k' }, k), h('div', { className: 'cp-stat-v' }, v), sub ? h('div', { className: 'cp-stat-sub' }, sub) : null); const CpStepAudience = ({ crm, draft, stats, guests }) => { const D = cpDerived(crm); const aud = draft.aud; const pick = (a) => cpSetDraft(d => Object.assign({}, d, { aud: a, edits: {}, channel: null, ai: {}, aiKey: null, maxStep: Math.max(d.maxStep, 2) })); const tabs = [['segment', window.t('Segment')], ['opportunity', window.t('Doluluk fırsatı')]]; if (draft.prefill) tabs.push(['guests', window.t('Seçili misafirler')]); const src = draft.src; let body; if (src === 'opportunity') { const opps = (crm.opportunities || []).slice().sort((a, b) => String(a.date || '').localeCompare(String(b.date || ''))); body = h('div', { className: 'cp-cards cp-opps' }, opps.map(o => { const sel = aud && aud.type === 'opportunity' && aud.id === o.id; return h('button', { key: o.id, type: 'button', className: 'cp-card' + (sel ? ' sel' : ''), 'aria-pressed': sel, onClick: () => pick({ type: 'opportunity', id: o.id, guestIds: null, label: null }) }, h('div', { className: 'cp-card-kicker' }, h('span', { className: 'pill ' + (o.kind === 'flight' ? 'pill-brand' : 'pill-warn') }, cpOppKind(o)), h('span', { className: 'mono' }, cpDate(o.date))), h('div', { className: 'cp-card-title' }, window.crmLabel(o.title)), h('ul', { className: 'cp-card-why' }, (o.why || []).slice(0, 2).map((w, i) => h('li', { key: i }, window.crmLabel(w)))), h('div', { className: 'cp-card-foot' }, h('span', null, cpTx('{n} eşleşen misafir', { n: (o.guest_ids || []).length })), h('span', { className: 'mono' }, cpTx('beklenen {v}', { v: cpEur(o.expected_rev_eur) })))); })); } else if (src === 'guests' && draft.prefill) { const p = draft.prefill; const pg = cpAudienceGuests(crm, p); const sel = aud && aud.type === 'guests'; body = h('div', { className: 'cp-cards' }, h('button', { type: 'button', className: 'cp-card cp-card-wide' + (sel ? ' sel' : ''), 'aria-pressed': sel, onClick: () => pick(p) }, h('div', { className: 'cp-card-kicker' }, h('span', { className: 'pill pill-info' }, window.t('Misafir 360\'tan')), h('span', { className: 'mono' }, cpTx('{n} misafir', { n: pg.length }))), h('div', { className: 'cp-card-title' }, cpAudienceLabel(crm, p)), h('div', { className: 'cp-card-names' }, pg.slice(0, 8).map(cpGuestName).join(' · ') + (pg.length > 8 ? ' …' : '')))); } else { body = h('div', { className: 'cp-cards cp-segs' }, (crm.segments || []).map(s => { const sel = aud && aud.type === 'segment' && aud.id === s.id; const n = (D.eligible[s.id] || []).length; return h('button', { key: s.id, type: 'button', className: 'cp-card' + (sel ? ' sel' : ''), 'aria-pressed': sel, disabled: !n, onClick: () => pick({ type: 'segment', id: s.id, guestIds: null, label: null }) }, h('div', { className: 'cp-card-title' }, window.crmLabel(s.name)), h('div', { className: 'cp-card-desc' }, window.crmLabel(s.desc)), h('div', { className: 'cp-card-foot' }, h('span', null, cpTx('{n} açık teklif', { n })), h('span', { className: 'mono' }, cpTx('{p} doğrudan', { p: cpPct((s.share_direct || 0) * 100, 0) })))); })); } return h('div', { className: 'cp-step-body' }, h('div', { className: 'cp-src' }, tabs.map(([k, label]) => h('button', { key: k, type: 'button', className: 'filter-chip' + (src === k ? ' active' : ''), onClick: () => cpSetDraft(d => Object.assign({}, d, { src: k })) }, label))), body, aud && h('div', { className: 'cp-aud-sum' }, h('div', { className: 'cp-aud-sum-head' }, h('span', { className: 'cp-sec-l' }, window.t('Seçili kitle')), h('span', { className: 'cp-aud-sum-name' }, cpAudienceLabel(crm, aud))), guests.length === 0 ? h('div', { className: 'cp-route-warn' }, window.t('Bu kitlede kampanyaya uygun misafir yok.')) : h('div', { className: 'cp-stats' }, h(CpStat, { k: window.t('Kitle büyüklüğü'), v: fmtN(stats.size) }), h(CpStat, { k: window.t('Doğrudan'), v: fmtN(stats.direct), sub: cpPct(cpShare(stats.direct, stats.size), 0) }), h(CpStat, { k: window.t('Acente üzerinden'), v: fmtN(stats.agency), sub: cpTx('{n} acente', { n: stats.agencies }) }), h(CpStat, { k: window.t('E-posta izni'), v: fmtN(stats.reach.email) }), h(CpStat, { k: window.t('SMS izni'), v: fmtN(stats.reach.sms) }), h(CpStat, { k: window.t('Telegram izni'), v: fmtN(stats.reach.telegram) })), h('div', { className: 'cp-hint' }, window.t('İzinler doğrudan misafirler içindir; acente misafirlerine her zaman kendi acentesi ulaşır.')))); }; const CpStepper = ({ label, value, unit, min, max, onChange }) => h('div', { className: 'cp-field cp-field-edit' }, h('div', { className: 'cp-field-k' }, label), h('div', { className: 'cp-stepper' }, h('button', { type: 'button', className: 'btn btn-sm', disabled: value <= min, 'aria-label': label + ' −', onClick: () => onChange(Math.max(min, value - 1)) }, '−'), h('span', { className: 'cp-stepper-v mono' }, unit(value)), h('button', { type: 'button', className: 'btn btn-sm', disabled: value >= max, 'aria-label': label + ' +', onClick: () => onChange(Math.min(max, value + 1)) }, '+'))); const CpStepPackage = ({ crm, draft, base, pkg, price, guests }) => { const set = (k, v) => cpSetDraft(d => { const edits = Object.assign({}, d.edits, { [k]: v }); if (v === base[k]) delete edits[k]; // back to the default = the guests' own CRM offers return Object.assign({}, d, { edits }); }); const why = cpPackageWhy(crm, draft.aud, pkg, guests); const pax = pkg.party.adults + pkg.party.children; const gross = pkg.ppn != null ? Math.round(pkg.ppn * pax * pkg.nights / 10) * 10 : null; const field = (k, v) => h('div', { className: 'cp-field' }, h('div', { className: 'cp-field-k' }, k), h('div', { className: 'cp-field-v' }, v)); return h('div', { className: 'cp-step-body' }, why.length > 0 && h('div', { className: 'cp-why' }, h('div', { className: 'cp-sec-l' }, window.t('Neden bu paket')), h('ul', null, why.map((w, i) => h('li', { key: i }, w)))), h('div', { className: 'cp-pkg' }, h('div', { className: 'cp-form' }, field(window.t('Otel'), pkg.hotel || window.t('Bölgedeki oteller · misafire göre')), field(window.t('Bölge'), pkg.sub_region || '—'), field(window.t('Oda'), pkg.room ? window.crmRoom(pkg.room) : window.t('Misafire göre')), field(window.t('Giriş'), cpDate(pkg.check_in)), field(window.t('Uçuş'), pkg.flight_no ? pkg.flight_no + (pkg.route ? ' · ' + pkg.route : '') : window.t('Misafirin şehrinden')), field(window.t('Fiyat temeli'), cpParty(pkg.party)), h(CpStepper, { label: window.t('Gece'), value: pkg.nights, min: 3, max: 21, unit: v => cpTx('{n} gece', { n: v }), onChange: v => set('nights', v) }), h(CpStepper, { label: window.t('İndirim'), value: pkg.discount_pct, min: 0, max: 40, unit: v => cpPct(v, 0), onChange: v => set('discount_pct', v) })), h('div', { className: 'cp-price' }, h('div', { className: 'cp-field-k' }, window.t('Paket fiyatı')), h('div', { className: 'cp-price-v' }, price != null ? fmtEur(price) : '—'), h('div', { className: 'cp-price-sub' }, cpParty(pkg.party) + ' · ' + cpTx('{n} gece', { n: pkg.nights })), pkg.discount_pct > 0 && gross != null && h('div', { className: 'cp-price-sub' }, cpTx('indirimsiz {v}', { v: fmtEur(gross) })), h('div', { className: 'cp-hint' }, window.t('CRM tekliflerinin kişi-gece fiyatından hesaplanır; mesajlarda yalnızca bu fiyat yer alır.'))))); }; const CpRouteLine = ({ route, stats }) => h('div', { className: 'cp-route' }, h('div', { className: 'cp-route-main' }, h('strong', null, fmtN(route.direct)), ' ' + window.t('doğrudan') + (route.channel !== 'agency' ? ' (' + cpChannelName(route.channel) + ')' : ''), h('span', { className: 'cp-dot' }, ' · '), h('strong', null, fmtN(route.agency)), ' ' + window.t('acente üzerinden') + (route.agency ? ' (' + cpTx('{n} acente', { n: stats.agencies }) + ')' : ''), route.agency > 0 && h('span', { className: 'cp-route-why' }, ' — ' + window.t('acente misafirleri, satışı yapan acentenin müşterisidir; teklif misafire değil acentesine gider.'))), route.noConsent > 0 && h('div', { className: 'cp-route-warn' }, cpTx('{n} doğrudan misafirin bu kanal için izni yok; gönderime dahil edilmez.', { n: route.noConsent })), route.excluded > 0 && h('div', { className: 'cp-route-warn' }, cpTx('{n} doğrudan misafir acente bülteninde yer almaz; onlar için doğrudan bir kanal seçin.', { n: route.excluded }))); const CpStepChannel = ({ crm, stats, channel, route }) => { const D = cpDerived(crm); return h('div', { className: 'cp-step-body' }, h('div', { className: 'cp-channels' }, ['email', 'sms', 'telegram', 'agency'].map(ch => { const reach = cpReach(stats, ch), r = D.rates.by[ch]; const sel = ch === channel; return h('button', { key: ch, type: 'button', className: 'cp-channel' + (sel ? ' sel' : ''), disabled: !reach, 'aria-pressed': sel, onClick: () => cpSetDraft(d => Object.assign({}, d, { channel: ch })) }, h('div', { className: 'cp-channel-name' }, cpChannelName(ch)), h('div', { className: 'cp-channel-reach' }, ch === 'agency' ? cpTx('{n} misafir · {k} acente', { n: reach, k: stats.agencies }) : cpTx('{n} izinli doğrudan misafir', { n: reach })), h('div', { className: 'cp-channel-hist' }, r && r.sent ? cpTx('Geçmiş: açılma {o} · rezervasyon {b}', { o: cpPct(r.open * 100), b: cpPct(r.book * 100) }) : window.t('Bu kanalda geçmiş kampanya yok')), !reach && h('div', { className: 'cp-channel-off' }, window.t('Bu kitlede ulaşılabilir misafir yok'))); })), h(CpRouteLine, { route, stats })); }; const CpAiNote = ({ state }) => { if (state === 'loading') { return h('div', { className: 'insight-loading cp-ai-note' }, h('span', { className: 'insight-shimmer' }), window.t('AI mesajı yazıyor…')); } const text = state === 'ok' ? window.t('AI mesajı · yalnızca paket ve CRM bilgileriyle yazıldı') : state === 'partial' ? window.t('AI mesajı bazı dillerde yazılamadı; o dillerde şablon mesaj kullanılıyor.') : state === 'error' ? window.t('AI mesajı şu anda yazılamadı — paket bilgilerinden şablon mesaj kullanılıyor.') : state === 'off' || state === 'down' ? window.t('AI servisi şu anda bağlı değil — paket bilgilerinden şablon mesaj kullanılıyor.') : window.t('Şablon mesaj · paket bilgilerinden. Kişiselleştirmek için “AI ile yaz”.'); return h('div', { className: 'cp-ai-note' + (state === 'ok' ? ' ok' : '') }, text); }; const CpStepMessage = ({ draft, kinds, channel, msgFor, aiState, onWrite }) => { const lang = draft.msgLang || 'ru'; return h('div', { className: 'cp-step-body' }, h('div', { className: 'cp-msg-bar' }, h(CpLangChips, { lang, onLang: l => cpSetDraft(d => Object.assign({}, d, { msgLang: l })) }), h('span', { className: 'cp-hint cp-msg-hint' }, window.t('Misafirlere Rusça gider; TR ve EN masa için önizlemedir.')), h('button', { type: 'button', className: 'btn btn-accent cp-ai-btn', disabled: aiState === 'loading', onClick: onWrite }, aiState === 'ok' || aiState === 'partial' ? window.t('Yeniden yaz') : window.t('AI ile yaz'))), h('div', { className: 'cp-msgs' + (kinds.length > 1 ? ' two' : '') }, kinds.map(kind => { const m = msgFor(kind, lang); return h(CpMsgCard, { key: kind, channel: kind === 'agency' ? 'agency' : channel, title: kind === 'agency' && channel !== 'agency' ? window.t('Acente notu') : null, subject: m.subject, body: m.body, loading: m.state === 'loading' }); })), h(CpAiNote, { state: aiState })); }; const CpStepSchedule = ({ crm, draft, route, proj, minDate, dateOk, onSend }) => { const later = draft.when === 'later'; const opt = (k, title, sub, extra) => h('div', { className: 'cp-when-opt' + (draft.when === k ? ' sel' : ''), role: 'radio', 'aria-checked': draft.when === k, tabIndex: 0, onClick: () => cpSetDraft(d => Object.assign({}, d, { when: k })), onKeyDown: e => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); cpSetDraft(d => Object.assign({}, d, { when: k })); } } }, h('span', { className: 'cp-radio', 'aria-hidden': true }), h('div', null, h('div', { className: 'cp-when-t' }, title), h('div', { className: 'cp-when-s' }, sub), extra || null)); return h('div', { className: 'cp-step-body' }, h('div', { className: 'cp-when', role: 'radiogroup', 'aria-label': window.t('Zamanlama') }, opt('now', window.t('Hemen gönder'), cpTx('Bugün, {d} · durum: Devam ediyor', { d: cpDate(crm.as_of) })), opt('later', window.t('İleri bir tarihte'), window.t('durum: Planlandı'), h('input', { type: 'date', className: 'input cp-date', min: minDate, value: draft.date || '', 'aria-label': window.t('Gönderim tarihi'), onClick: e => e.stopPropagation(), onFocus: () => cpSetDraft(d => Object.assign({}, d, { when: 'later' })), onChange: e => { const v = e.target.value; cpSetDraft(d => Object.assign({}, d, { when: 'later', date: v })); } }))), later && !dateOk && h('div', { className: 'cp-route-warn' }, cpTx('Tarih {d} veya sonrası olmalı.', { d: cpDate(minDate) })), h('div', { className: 'cp-proj-block' }, h('div', { className: 'cp-sec-head' }, h('div', { className: 'cp-sec-l' }, window.t('Tahmini sonuç')), h('div', { className: 'cp-sec-r' }, cpTx('{n} alıcı', { n: proj.sent }))), h(CpProjection, { c: proj, channel: route.channel, direct: route.direct, agency: route.agency })), h('div', { className: 'cp-send' }, h('button', { type: 'button', className: 'btn btn-accent cp-send-btn', disabled: !dateOk || !proj.sent, onClick: onSend }, window.t('Simüle et ve gönder')), h('span', { className: 'cp-hint' }, window.t('Demo modu: gerçek mesaj gönderilmez.')))); }; const CpSummary = ({ crm, draft, stats, pkg, price, channel, route, proj, aiState }) => { const row = (k, v) => h('div', { className: 'cp-sum-row' }, h('div', { className: 'cp-sum-k' }, k), h('div', { className: 'cp-sum-v' }, v)); const aud = draft.aud; return h('aside', { className: 'panel cp-summary' }, h('div', { className: 'panel-head' }, h('div', null, h('div', { className: 'panel-head-title' }, window.t('Kampanya özeti')), h('div', { className: 'panel-head-sub' }, window.t('Demo modu: gönderim simüle edilir')))), h('div', { className: 'panel-body' }, row(window.t('Kitle'), aud ? cpAudienceLabel(crm, aud) + ' · ' + cpTx('{n} misafir', { n: stats.size }) : '—'), row(window.t('Paket'), pkg ? [pkg.hotel || pkg.sub_region, cpDate(pkg.check_in), cpTx('{n} gece', { n: pkg.nights }), price != null ? fmtEur(price) : null, pkg.discount_pct ? cpPct(pkg.discount_pct, 0) : null].filter(Boolean).join(' · ') : '—'), row(window.t('Kanal'), aud && draft.maxStep >= 3 ? cpChannelName(channel) + ' · ' + fmtN(route.direct) + ' ' + window.t('doğrudan') + ' · ' + fmtN(route.agency) + ' ' + window.t('acente üzerinden') : '—'), row(window.t('Mesaj'), draft.maxStep >= 4 ? (aiState === 'ok' || aiState === 'partial' ? window.t('AI') : aiState === 'loading' ? window.t('AI yazıyor…') : window.t('Şablon')) : '—'), row(window.t('Zamanlama'), draft.maxStep >= 5 ? (draft.when === 'later' ? cpDate(draft.date) : window.t('Hemen')) : '—'), aud && draft.maxStep >= 3 && h('div', { className: 'cp-sum-proj' }, h('div', { className: 'cp-sum-k' }, window.t('Tahmin')), h('div', { className: 'cp-sum-proj-v mono' }, fmtN(proj.sent) + ' → ' + cpProjCount(proj.booked) + ' ' + window.t('rez.') + ' · ≈ ' + cpEur(proj.revenue_eur))))); }; const CpFlow = ({ crm, draft }) => { const D = cpDerived(crm); const aud = draft.aud; const audKey = aud ? [aud.type, aud.id || '', (aud.guestIds || []).join(',')].join('|') : ''; const guests = useMemo(() => cpAudienceGuests(crm, aud), [audKey]); const stats = useMemo(() => cpStats(guests), [audKey]); const base = useMemo(() => (aud ? cpDefaultPackage(crm, aud, guests) : null), [audKey]); const pkg = base && Object.assign({}, base, { nights: draft.edits.nights != null ? draft.edits.nights : base.nights, discount_pct: draft.edits.discount_pct != null ? draft.edits.discount_pct : base.discount_pct }); const price = cpPriceOf(pkg); const channel = draft.channel && cpReach(stats, draft.channel) > 0 ? draft.channel : cpDefaultChannel(stats); const route = cpRoute(stats, channel); const kinds = channel === 'agency' || !stats.agency ? ['main'] : ['main', 'agency']; const factsKey = JSON.stringify([audKey, pkg && [pkg.hotel, pkg.sub_region, pkg.check_in, pkg.nights, pkg.discount_pct, price], channel]); const aiState = cpAiSummary(draft, factsKey, kinds); const proj = cpProject(D.rates, guests, channel, pkg, draft.edits); const minDate = cpAddDays(crm.as_of, 1); const dateOk = draft.when !== 'later' || (!!draft.date && draft.date >= minDate); const msgFor = (kind, lang) => { const ch = kind === 'agency' ? 'agency' : channel; const tpl = cpTemplate(lang, ch, cpTplContext(guests, pkg, price, lang)); const ai = draft.aiKey === factsKey ? draft.ai[kind + '|' + lang] : null; if (ai && ai.state === 'ok') return { subject: ai.subject || tpl.subject, body: ai.body, source: 'ai', state: 'ok' }; return { subject: tpl.subject, body: tpl.body, source: 'template', state: ai ? ai.state : null }; }; const pkgOut = pkg && { hotel: cpHotel(pkg.hotel) || null, sub_region: pkg.sub_region || null, room: pkg.room || null, check_in: pkg.check_in || null, nights: pkg.nights, price_eur: price, discount_pct: pkg.discount_pct, flight_no: pkg.flight_no || null, party: pkg.party }; const write = () => { const key = factsKey; const jobs = []; kinds.forEach(kind => CP_LANGS.forEach(lang => jobs.push([kind, lang]))); cpSetDraft(d => Object.assign({}, d, { aiKey: key, ai: jobs.reduce((o, [k, l]) => Object.assign(o, { [k + '|' + l]: { state: 'loading' } }), {}) })); jobs.forEach(([kind, lang]) => { const asGuests = aud.type === 'guests' || !aud.id; // a handed-over list without an id goes as guest ids cpAskAi({ audience: { type: asGuests ? 'guests' : aud.type, id: asGuests ? null : aud.id, guest_ids: asGuests ? guests.map(g => g.id).slice(0, CP_MAX_IDS) : [] }, package: pkgOut, channel: kind === 'agency' ? 'agency' : channel, lang, }).then(res => cpSetDraft(d => (d.aiKey === key ? Object.assign({}, d, { ai: Object.assign({}, d.ai, { [kind + '|' + lang]: res }) }) : d))); }); }; const send = () => { const now = draft.when !== 'later'; const L3 = (fn) => ({ tr: fn('tr'), en: fn('en'), ru: fn('ru') }); const main = L3(l => msgFor('main', l)), ag = kinds.length > 1 ? L3(l => msgFor('agency', l)) : null; const saved = cpStore.saved || []; const rec = Object.assign({ id: cpNextId(saved), demo: true, projected: true, created_at: new Date().toISOString(), name: cpCampaignName(crm, aud, pkg), status: now ? 'running' : 'scheduled', audience: { type: aud.type, id: aud.type === 'guests' ? null : aud.id, size: stats.size, label: aud.label || null, guest_ids: aud.type === 'guests' || (aud.guestIds && aud.guestIds.length) ? guests.map(g => g.id).slice(0, CP_MAX_IDS) : null }, channel, lang: 'ru', package: { label: cpPackageLabel(pkg), hotel: pkg.hotel, sub_region: pkg.sub_region, room: pkg.room, check_in: pkg.check_in, nights: pkg.nights, discount_pct: pkg.discount_pct, price_eur: price, flight_no: pkg.flight_no, party: pkg.party }, start_date: now ? crm.as_of : draft.date, split: { direct: route.direct, agency: route.agency, agencies: stats.agencies, excluded: route.excluded, no_consent: route.noConsent }, message: { tr: main.tr.body, en: main.en.body, ru: main.ru.body }, subject: main.ru.subject ? { tr: main.tr.subject, en: main.en.subject, ru: main.ru.subject } : null, agency_message: ag ? { tr: ag.tr.body, en: ag.en.body, ru: ag.ru.body } : null, agency_subject: ag ? { tr: ag.tr.subject, en: ag.en.subject, ru: ag.ru.subject } : null, message_source: main.ru.source, }, proj, { by_agency: proj.by_agency.length ? proj.by_agency : null }); const list = [rec].concat(saved); const ok = cpWriteSaved(list); const toast = { id: rec.id, warn: !ok }; cpSet({ saved: list, view: 'list', draft: null, openId: rec.id, toast }); setTimeout(() => cpSet(s => (s.toast === toast ? { toast: null } : {})), 6000); }; const step = draft.step; const canNext = step === 1 ? guests.length > 0 : step === 2 ? !!pkg : step === 3 ? cpReach(stats, channel) > 0 : true; const go = (n) => { cpSetDraft(d => Object.assign({}, d, { step: n, maxStep: Math.max(d.maxStep, n), channel: n >= 3 && !d.channel ? channel : d.channel })); const c = document.querySelector('.content'); if (c && c.scrollTo) c.scrollTo(0, 0); }; const subs = { 1: window.t('Segment, doluluk fırsatı veya Misafir 360\'tan gelen misafirler'), 2: window.t('Kitleden önerilen varsayılan · gece ve indirim düzenlenebilir'), 3: window.t('Doğrudan misafirler izin verdikleri kanaldan; acente misafirleri her zaman acentesi üzerinden'), 4: window.t('Paket ve CRM bilgileriyle tek bir kısa mesaj · fiyat ve indirim pakettekiyle aynı'), 5: window.t('Hemen veya ileri bir tarihte · gönderim simüle edilir'), }; let content = null; if (step === 1) content = h(CpStepAudience, { crm, draft, stats, guests }); else if (!aud || !pkg) content = h('div', { className: 'cp-muted' }, window.t('Önce bir hedef kitle seçin.')); else if (step === 2) content = h(CpStepPackage, { crm, draft, base, pkg, price, guests }); else if (step === 3) content = h(CpStepChannel, { crm, stats, channel, route }); else if (step === 4) content = h(CpStepMessage, { draft, kinds, channel, msgFor, aiState, onWrite: write }); else content = h(CpStepSchedule, { crm, draft, route, proj, minDate, dateOk, onSend: send }); return h('div', { className: 'cp-flow' }, h('div', { className: 'cp-flow-head' }, h('button', { type: 'button', className: 'btn btn-sm btn-ghost cp-back', onClick: () => cpSet({ view: 'list', draft: null }) }, '← ' + window.t('Kampanyalar')), h('div', { className: 'eyebrow' }, window.t('Yeni kampanya') + ' · ' + window.t('Demo modu')), h('h1', { className: 'headline cp-headline' }, window.t('Yeni kampanya'))), h(CpSteps, { step, maxStep: draft.maxStep }), h('div', { className: 'cp-flow-grid' }, h('div', { className: 'panel cp-flow-main' }, h('div', { className: 'panel-head' }, h('div', null, h('div', { className: 'panel-head-title' }, String(step).padStart(2, '0') + ' · ' + cpStepLabel(step)), h('div', { className: 'panel-head-sub' }, subs[step]))), h('div', { className: 'panel-body' }, content, h('div', { className: 'cp-nav' }, step > 1 ? h('button', { type: 'button', className: 'btn', onClick: () => go(step - 1) }, '← ' + window.t('Geri')) : h('button', { type: 'button', className: 'btn btn-ghost', onClick: () => cpSet({ view: 'list', draft: null }) }, window.t('Vazgeç')), step < 5 && h('button', { type: 'button', className: 'btn btn-primary cp-next', disabled: !canNext, onClick: () => go(step + 1) }, window.t('Devam') + ' →')))), h(CpSummary, { crm, draft, stats, pkg, price, channel, route, proj, aiState }))); }; // ============================================================ page const CpToast = ({ toast }) => (toast ? h('div', { className: 'cp-toast', role: 'status' }, h('div', null, window.t('Demo modu — gönderim simüle edildi, gerçek mesaj gönderilmedi')), toast.warn && h('div', { className: 'cp-toast-sub' }, window.t('Tarayıcı depolaması kapalı: simülasyon yalnızca bu oturumda görünür.'))) : null); const CampaignsPage = () => { const [, bump] = useState(0); const [crm, setCrm] = useState(window.CRM || null); const [err, setErr] = useState(false); useEffect(() => { const f = () => bump(n => n + 1); cpStore.subs.add(f); return () => { cpStore.subs.delete(f); }; }, []); const load = () => { setErr(false); if (!window.loadCrm) { setErr(true); return; } window.loadCrm().then(d => setCrm(d)).catch(() => setErr(true)); }; useEffect(() => { if (!crm) load(); }, []); // Misafir 360 / Doluluk Fırsatları hand over an audience in window.__campaignPrefill, then navigate here. useEffect(() => { if (!crm) return undefined; const take = () => { const p = window.__campaignPrefill; if (!p || !p.audience) return; try { delete window.__campaignPrefill; } catch (e) { window.__campaignPrefill = undefined; } cpStartNew(crm, cpAudFromPrefill(crm, p.audience)); }; take(); const onNav = (e) => { if (e.detail && e.detail.page === 'campaigns') setTimeout(take, 0); }; window.addEventListener('navigate', onNav); return () => window.removeEventListener('navigate', onNav); }, [crm]); if (cpStore.saved == null) cpStore.saved = cpLoadSaved(); if (err) { return h('div', { className: 'cp-page' }, h('div', { className: 'cp-state' }, h('div', { className: 'cp-state-t' }, window.t('Kampanya verisi yüklenemedi.')), h('div', { className: 'cp-muted' }, window.t('Bağlantıyı kontrol edip yeniden deneyin; panonun geri kalanı çalışmaya devam ediyor.')), h('button', { type: 'button', className: 'btn btn-primary', onClick: load }, window.t('Yeniden dene')))); } if (!crm) { return h('div', { className: 'cp-page' }, h('div', { className: 'insight-loading cp-state' }, h('span', { className: 'insight-shimmer' }), window.t('Kampanya verisi yükleniyor…'))); } const view = cpStore.view === 'new' && cpStore.draft ? 'new' : 'list'; const list = (cpStore.saved || []).concat((crm.campaigns || []).filter(c => c && c.id)) .sort((a, b) => String(b.start_date || '').localeCompare(String(a.start_date || '')) || String(b.created_at || '').localeCompare(String(a.created_at || ''))); const open = view === 'list' && cpStore.openId ? list.find(c => c.id === cpStore.openId) : null; return h('div', { className: 'cp-page' }, view === 'new' ? h(CpFlow, { crm, draft: cpStore.draft }) : h(React.Fragment, null, h('div', { className: 'cp-head' }, h('div', { className: 'cp-head-text' }, h('div', { className: 'eyebrow', style: { marginBottom: 6 } }, window.t("Kampanya Yönetimi · CRM'den aksiyona")), h('h1', { className: 'headline cp-headline' }, window.t('Doğru kitle, doğru paket, '), h('em', null, window.t('doğru kanal.'))), h('div', { className: 'cp-lede' }, window.t('Boş koltuk ve satılmamış odayı doğru misafire bağlayan kampanyalar: kitle CRM\'den, mesaj AI\'dan, sonuç huniden.'))), h('button', { type: 'button', className: 'btn btn-accent cp-new', onClick: () => cpStartNew(crm, null) }, '+ ' + window.t('Yeni kampanya'))), h('div', { className: 'byline cp-byline' }, h('strong', null, window.t('Örnek veri')), h('span', null, window.t('sentetik misafir kayıtları')), h('span', { className: 'sep' }, '·'), h('span', null, cpTx('Bugün: {d}', { d: cpDate(crm.as_of) })), h('span', { className: 'sep' }, '·'), h('span', null, window.t('Demo modu: gönderimler simüle edilir, gerçek mesaj gönderilmez.'))), h(CpKpis, { crm, list }), h(CpTable, { crm, list, selId: cpStore.openId })), open && h(CpDrawer, { key: open.id, crm, c: open }), h(CpToast, { toast: cpStore.toast })); }; window.CampaignsPage = CampaignsPage; })();