/* global React, ReactDOM, DATA, KPI, Panel, Stars, fmtEurM, fmtEur, fmtN, MONTHS */ /* Misafir 360 — the revenue-aware CRM over crm.json (lazy: window.loadCrm). Synthetic guests ("Örnek veri"). Every "contact this guest" suggestion carries its why: guest fit AND where the desk needs demand (low-LF flights, unsold allotment). Agency-owned guests are never contacted directly: their offer goes via the agency that sold the trip. The shared kit (guest card drawer, badges, selection, campaign handoff) is exposed as window.CrmKit / window.CrmGuestCard for Doluluk Fırsatları (page-fill.jsx). */ (() => { const h = React.createElement; const { useState, useEffect, useMemo, useRef } = React; const T = (s) => window.t(s); const L = (o) => window.crmLabel(o); // ---------- i18n: templates + plurals ---------- // tx('{n} gece', { n: 7 }) → window.t(template) with placeholders filled (numbers via fmtN). Plural // variants sit next to the translation in i18n-crm.js: en_1 (n = 1), ru_1 (1, 21…), ru_2 (2–4, 22…). const ruForm = (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 tx = (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 = ruForm(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; }); }; // ---------- formatting ---------- const p100 = (v) => (v == null || isNaN(v) ? null : v * 100); const pct = (v) => (v == null || isNaN(v) ? '—' : window.LANG === 'tr' ? '%' + Math.round(v) : Math.round(v) + '%'); const eur = (v) => (v == null || isNaN(v) ? '—' : Math.abs(v) >= 1e6 ? fmtEurM(v) : fmtEur(v)); // one guest / offer const eurK = (v) => (v == null || isNaN(v) ? '—' : fmtEurM(v)); // aggregates: €840K, €2.1M const utc = (s) => { const p = String(s || '').split('-'); return Date.UTC(+p[0], (+p[1] || 1) - 1, +p[2] || 1); }; const dayDiff = (a, b) => Math.round((utc(b) - utc(a)) / 864e5); const addDays = (s, n) => new Date(utc(s) + n * 864e5).toISOString().slice(0, 10); const asOf = () => (window.CRM && window.CRM.as_of) || ''; const fmtDay = (s, withYear) => { if (!s) return '—'; const p = String(s).split('-'); const y = withYear || p[0] !== asOf().slice(0, 4) ? ' ' + p[0] : ''; return +p[2] + ' ' + T(MONTHS[+p[1]] || '') + y; }; const fmtRange = (a, b) => { if (!a || !b) return '—'; return a.slice(0, 7) === b.slice(0, 7) ? +a.slice(8) + '–' + fmtDay(b) : fmtDay(a) + ' – ' + fmtDay(b); }; const norm = (s) => String(s || '').normalize('NFD').replace(/[̀-ͯ]/g, '').toLowerCase(); // ---------- guest helpers ---------- const gName = (g) => (window.LANG === 'ru' && g.name_cyr ? g.name_cyr : g.name) || g.id; const gAltName = (g) => (window.LANG === 'ru' ? (g.name_cyr ? g.name : null) : g.name_cyr) || null; const isDetractor = (g) => !!(g && g.survey && g.survey.nps != null && g.survey.nps <= 6); const CH_LABEL = { email: 'E-posta', sms: 'SMS', telegram: 'Telegram' }; const VIA_NOTE = 'Acente misafirine doğrudan yazılmaz; teklif, tatili satan acente üzerinden gider (kanal çatışması yok).'; const STATUS = { sent: 'Gönderildi', opened: 'Açıldı', clicked: 'Tıklandı', booked: 'Rezervasyon yaptı' }; const TRIP_CH = { 'B2B Agency': 'B2B acente', 'B2C Web': 'Web sitesi', 'Call Center': 'Çağrı merkezi', 'Mobile App': 'Mobil uygulama', 'Corporate': 'Kurumsal' }; // Offer flights: show "market → destination", never the origin airport code (it doesn't match the market city). const DEST = { AYT: 'Antalya', BJV: 'Bodrum', DLM: 'Dalaman', IST: 'Istanbul', SAW: 'Istanbul', ADB: 'Izmir', GZP: 'Gazipaşa' }; const flightRoute = (g, o) => (g.market || g.city || '—') + ' → ' + ((o.flight && DEST[o.flight.dest]) || o.sub_region || '—'); const partyTxt = (a, c) => (a ? tx('{n} yetişkin', { n: a }) : '') + (c ? ' + ' + tx('{n} çocuk', { n: c }) : ''); const offerLine = (o) => [o.hotel, window.crmRoom(o.room), fmtDay(o.check_in), o.nights ? tx('{n} gece', { n: o.nights }) : null] .filter(Boolean).join(' · '); let _hotels = null; const hotelRec = (name) => { if (!_hotels) { _hotels = {}; ((window.DATA && DATA.hotel_index) || []).forEach(x => { _hotels[x.HotelName] = x; }); } return name ? _hotels[name] : null; }; const HotelName = ({ name, stars }) => { const rec = hotelRec(name); const kids = [name || '—', stars ? ' ' : null, stars ? h(Stars, { key: 's', n: stars }) : null]; return rec ? h('button', { type: 'button', className: 'crm-hotel', title: T('Otel detayını aç'), onClick: (e) => { e.stopPropagation(); window.dispatchEvent(new CustomEvent('open-hotel', { detail: rec })); } }, ...kids) : h('span', { className: 'crm-hotel crm-hotel-plain' }, ...kids); }; const ChannelBadge = ({ channel, agency }) => channel === 'agency' ? h('span', { className: 'crm-ch crm-ch-agency', title: T(VIA_NOTE) }, agency ? tx('Acente üzerinden: {a}', { a: agency }) : T('Acente üzerinden')) : h('span', { className: 'crm-ch crm-ch-' + (channel || 'none') }, T(CH_LABEL[channel] || String(channel || '—'))); const segIdx = (crm, id) => (crm.segments || []).findIndex(s => s.id === id); const SegChip = ({ crm, id }) => { const s = crm.segById ? crm.segById[id] : null; const i = segIdx(crm, id); return h('span', { className: 'crm-seg', style: { '--seg': 'var(--seg-' + (i >= 0 ? i % 8 : 7) + ')' } }, s ? L(s.name) : (id || '—')); }; const NpsBadge = ({ g }) => isDetractor(g) ? h('span', { className: 'crm-npsb', title: T('Telafi önceliği') }, 'NPS ' + g.survey.nps) : null; // ---------- data loading ---------- const useCrm = () => { const [st, setSt] = useState(() => ({ crm: window.CRM || null, err: null })); const load = () => { setSt({ crm: null, err: null }); if (typeof window.loadCrm !== 'function') { setSt({ crm: null, err: new Error('crm-data.js') }); return; } window.loadCrm().then( (crm) => setSt(crm && Array.isArray(crm.guests) ? { crm, err: null } : { crm: null, err: new Error('crm.json') }), (err) => setSt({ crm: null, err })); }; useEffect(() => { if (!st.crm) load(); }, []); return [st, load]; }; const Loading = () => h('div', { className: 'panel crm-state' }, h('div', { className: 'insight-loading' }, h('span', { className: 'insight-shimmer' }), T('Misafir kayıtları yükleniyor…'))); const LoadError = ({ onRetry }) => h('div', { className: 'panel crm-state crm-state-err', role: 'alert' }, h('div', { className: 'crm-state-t' }, T('Misafir verisi yüklenemedi.')), h('div', { className: 'crm-state-s' }, T('Bağlantıyı kontrol edip yeniden deneyin; panonun geri kalanı çalışmaya devam ediyor.')), h('button', { className: 'btn btn-sm btn-primary', onClick: onRetry }, T('Yeniden dene'))); // Page header shared by both CRM pages (eyebrow, headline, lede, sample-data byline). const PageHead = ({ eyebrow, title, em, lede, crm, extra }) => h('div', { className: 'crm-head' }, h('div', { className: 'eyebrow', style: { marginBottom: 6 } }, eyebrow), h('h1', { className: 'headline crm-headline' }, title, em ? h('em', null, em) : null), h('div', { className: 'crm-lede' }, lede), h('div', { className: 'byline crm-byline' }, h('strong', null, T('Örnek veri')), h('span', null, T('sentetik misafir kayıtları')), crm ? h('span', { className: 'sep' }, '·') : null, crm ? h('span', null, tx('Bugün: {d}', { d: fmtDay(crm.as_of, true) })) : null, extra || null)); // ---------- derived data (once per crm.json) ---------- let _d = null; const derive = (crm) => { if (_d && _d.crm === crm) return _d; const a = crm.as_of; const weeks = []; for (let i = 0; i < 8; i++) { weeks.push({ i, start: addDays(a, i * 7), end: addDays(a, i * 7 + 6), guests: [], exp: 0, linked: 0, ch: {} }); } const segs = {}; (crm.segments || []).forEach(s => { segs[s.id] = { eligible: [], booked: 0, pipe: 0, due30: 0 }; }); const markets = {}; let due30 = 0, det = 0; const rows = (crm.guests || []).map(g => { const o = g.offer; const dd = o && o.contact_date ? Math.max(0, dayDiff(a, o.contact_date)) : null; // contact dates are clamped ≥ today if (dd != null && dd < 56) { const w = weeks[Math.floor(dd / 7)]; w.guests.push(g); w.exp += o.expected_rev_eur || 0; if (o.opportunity_id) w.linked++; w.ch[o.channel] = (w.ch[o.channel] || 0) + 1; } if (dd != null && dd < 30) due30++; const s = segs[g.segment]; if (s) { if (o) { s.eligible.push(g.id); s.pipe += o.expected_rev_eur || 0; if (dd != null && dd < 30) s.due30++; } else s.booked++; } const m = g.market || g.city; if (m) markets[m] = (markets[m] || 0) + 1; const d = isDetractor(g); if (d) det++; const q = norm([g.name, g.name_cyr, g.id, g.city, g.market, g.agency, o && o.hotel] .concat((g.trips || []).map(t => t.hotel)).filter(Boolean).join(' ')); return { g, dd, det: d, q }; }); weeks.forEach(w => w.guests.sort((x, y) => (y.offer.expected_rev_eur || 0) - (x.offer.expected_rev_eur || 0))); const camp = {}, opp = {}; (crm.campaigns || []).forEach(c => { camp[c.id] = c; }); (crm.opportunities || []).forEach(o => { opp[o.id] = o; }); _d = { crm, weeks, segs, rows, camp, opp, due30, det, markets: Object.keys(markets).sort((x, y) => markets[y] - markets[x]) }; return _d; }; // ---------- campaign selection + handoff (contract shared with Kampanya Yönetimi) ---------- const sel = { ids: [], subs: new Set() }; const selEmit = () => sel.subs.forEach(f => f()); const selToggle = (id) => { sel.ids = sel.ids.includes(id) ? sel.ids.filter(x => x !== id) : sel.ids.concat(id); selEmit(); }; const selClear = () => { sel.ids = []; selEmit(); }; const useSel = () => { const [, bump] = useState(0); useEffect(() => { const f = () => bump(n => n + 1); sel.subs.add(f); return () => { sel.subs.delete(f); }; }, []); return sel.ids; }; const toCampaign = (type, id, guestIds, label) => { window.__campaignPrefill = { audience: { type, id: id == null ? null : id, guest_ids: (guestIds || []).slice(), label: label || '' } }; window.dispatchEvent(new CustomEvent('navigate', { detail: { page: 'campaigns' } })); }; const goFill = (oppId) => { window.__fillFocus = oppId; window.dispatchEvent(new CustomEvent('navigate', { detail: { page: 'fill' } })); }; const AddButton = ({ id }) => { const ids = useSel(); const on = ids.includes(id); return h('button', { type: 'button', className: 'btn btn-sm crm-add' + (on ? ' on' : ''), 'aria-pressed': on, onClick: (e) => { e.stopPropagation(); selToggle(id); } }, on ? '✓ ' + T('Eklendi') : '+ ' + T('Kampanyaya ekle')); }; const SelectionBar = () => { const ids = useSel(); const crm = window.CRM; if (!ids.length || !crm) return null; const exp = ids.reduce((s, id) => s + ((crm.byId[id] && crm.byId[id].offer && crm.byId[id].offer.expected_rev_eur) || 0), 0); return h('div', { className: 'crm-selbar', role: 'region', 'aria-label': T('Seçili misafirler') }, h('span', { className: 'crm-selbar-n' }, tx('{n} misafir seçildi', { n: ids.length })), h('span', { className: 'crm-selbar-e' }, tx('beklenen {v}', { v: eur(exp) })), h('button', { type: 'button', className: 'btn btn-sm crm-selbar-x', onClick: selClear }, T('Temizle')), h('button', { type: 'button', className: 'btn btn-sm btn-accent', onClick: () => { const list = ids.slice(); selClear(); toCampaign('guests', null, list, tx('Seçili {n} misafir', { n: list.length })); } }, T('Kampanya oluştur') + ' →')); }; // Drawer state survives the remount a language switch causes (app.jsx keys pages by LANG) — but not navigation. const useDrawer = (store) => { const [id, setId] = useState(() => { const o = store.open; store.open = null; return o && o.lang !== window.LANG ? o.id : null; }); useEffect(() => { store.open = id ? { id, lang: window.LANG } : null; }, [id]); return [id, setId]; }; // ---------- guest card (side drawer; Esc closes) ---------- const Stat = ({ k, v, s }) => h('div', { className: 'crm-stat' }, h('div', { className: 'crm-stat-k' }, k), h('div', { className: 'crm-stat-v' }, v), s ? h('div', { className: 'crm-stat-s' }, s) : null); const LfBar = ({ lf }) => h('span', { className: 'crm-lf', 'aria-hidden': true }, h('span', { style: { width: Math.max(0, Math.min(100, lf || 0)) + '%' } })); const OfferCard = ({ crm, g, onOpp }) => { const o = g.offer; const D = derive(crm); if (!o) { const yr = asOf().slice(0, 4); const bk = (g.trips || []).filter(t => String(t.check_in || '') >= yr).sort((x, y) => String(y.check_in).localeCompare(String(x.check_in)))[0]; return h('section', { className: 'crm-offer crm-offer-booked' }, h('div', { className: 'crm-sec-t' }, T('2026 rezervasyonu var')), bk ? h('div', { className: 'crm-offer-hotel' }, h(HotelName, { name: bk.hotel, stars: bk.stars })) : null, bk ? h('div', { className: 'crm-offer-sub' }, [fmtDay(bk.check_in, true), bk.nights ? tx('{n} gece', { n: bk.nights }) : null, bk.sub_region, window.crmRoom(bk.room), bk.amount_eur ? eur(bk.amount_eur) : null].filter(Boolean).join(' · ')) : null, h('div', { className: 'crm-note' }, T('Bu sezon için teklif üretilmez: misafir zaten rezervasyonlu, indirim boşa harcanmaz.'))); } const opp = o.opportunity_id ? D.opp[o.opportunity_id] : null; return h('section', { className: 'crm-offer' }, h('div', { className: 'crm-offer-head' }, h('div', { className: 'crm-sec-t' }, T('Sıradaki en iyi teklif')), opp ? h('button', { type: 'button', className: 'crm-oppl', title: L(opp.title), onClick: () => (onOpp ? onOpp(opp.id) : goFill(opp.id)) }, '● ' + T('Doluluk fırsatı') + ' →') : null), h('div', { className: 'crm-offer-main' }, h('div', { className: 'crm-offer-l' }, h('div', { className: 'crm-offer-hotel' }, h(HotelName, { name: o.hotel, stars: o.stars })), h('div', { className: 'crm-offer-sub' }, [o.sub_region, o.concept, window.crmRoom(o.room)].filter(Boolean).join(' · ')), h('div', { className: 'crm-offer-dates' }, [ o.check_in ? fmtDay(o.check_in, true) + (o.nights ? ' – ' + fmtDay(addDays(o.check_in, o.nights), true) : '') : null, o.nights ? tx('{n} gece', { n: o.nights }) : null, g.party ? partyTxt(g.party.adults, g.party.children) : null].filter(Boolean).join(' · ')), o.flight ? h('div', { className: 'crm-offer-flight' }, h('span', { className: 'crm-fl' }, '✈'), h('span', null, flightRoute(g, o)), o.flight.no ? h('span', { className: 'mono' }, o.flight.no) : null, o.flight.lf != null ? h('span', { className: 'crm-offer-lf' }, 'LF ' + pct(o.flight.lf), h(LfBar, { lf: o.flight.lf })) : null) : null), h('div', { className: 'crm-offer-r' }, h('div', { className: 'crm-offer-exp' }, eur(o.expected_rev_eur)), h('div', { className: 'crm-offer-expl' }, T('beklenen gelir')), h('div', { className: 'crm-offer-calc mono', title: T('Beklenen gelir = paket fiyatı × eğilim') }, eur(o.price_eur) + (g.propensity != null ? ' × ' + pct(p100(g.propensity)) : '')), o.discount_pct ? h('div', { className: 'crm-offer-disc' }, tx('{p} indirim dahil', { p: pct(o.discount_pct) })) : null)), h('div', { className: 'crm-offer-contact' }, h('span', { className: 'crm-k' }, T('Temas')), h('span', null, fmtDay(o.contact_date, true)), h(ChannelBadge, { channel: o.channel, agency: g.agency })), (o.why || []).length ? h('div', { className: 'crm-sec-k' }, T('Neden bu misafir, neden şimdi?')) : null, (o.why || []).length ? h('ul', { className: 'crm-why crm-why-lg' }, o.why.map((w, i) => h('li', { key: i }, L(w)))) : null, h('div', { className: 'crm-offer-act' }, h(AddButton, { id: g.id }), h('button', { type: 'button', className: 'btn btn-sm btn-primary', onClick: () => toCampaign('guests', null, [g.id], gName(g)) }, T('Bu misafire kampanya') + ' →'))); }; const GuestCard = ({ id, onClose, onOpp }) => { const crm = window.CRM; const g = crm && crm.byId ? crm.byId[id] : null; const ref = useRef(null); useEffect(() => { // Esc closes the drawer — unless a dialog above it (hotel modal, palette) is open: that one closes first. const onKey = (e) => { if (e.key === 'Escape' && !document.querySelector('.modal-backdrop')) onClose(); }; window.addEventListener('keydown', onKey); return () => window.removeEventListener('keydown', onKey); }, [onClose]); useEffect(() => { if (ref.current) { ref.current.scrollTop = 0; ref.current.focus({ preventScroll: true }); } }, [id]); if (!g) return null; const D = derive(crm); const det = isDetractor(g); const agency = g.owner === 'agency'; const alt = gAltName(g); const trips = (g.trips || []).slice().sort((x, y) => String(y.check_in || '').localeCompare(String(x.check_in || ''))); const contacts = (g.contacts || []).slice().sort((x, y) => String(y.date || '').localeCompare(String(x.date || ''))); const sv = g.survey && (g.survey.nps != null || g.survey.comment) ? g.survey : null; const years = g.first_trip ? String(g.first_trip).slice(0, 4) + (g.last_trip && String(g.last_trip).slice(0, 4) !== String(g.first_trip).slice(0, 4) ? '–' + String(g.last_trip).slice(0, 4) : '') : null; const consent = g.consent || {}; const nw = g.next_window; const win = nw && nw.start ? fmtRange(nw.start, nw.end || nw.start) + (nw.start.slice(0, 4) !== asOf().slice(0, 4) ? '' : ' ' + nw.start.slice(0, 4)) : null; const body = h('aside', { className: 'crm-drawer', ref, tabIndex: -1, role: 'dialog', 'aria-modal': 'true', 'aria-label': gName(g), onClick: (e) => e.stopPropagation() }, h('header', { className: 'crm-dr-head' }, h('div', { className: 'crm-dr-top' }, h('div', { className: 'eyebrow' }, T('Misafir kartı') + ' · ' + g.id), h('button', { type: 'button', className: 'btn btn-sm btn-ghost crm-dr-x', onClick: onClose, 'aria-label': T('Kartı kapat') }, '✕')), h('h2', { className: 'crm-dr-name' }, gName(g), alt ? h('span', { className: 'crm-dr-alt' }, alt) : null), h('div', { className: 'crm-dr-chips' }, h('span', { className: 'crm-dr-sub' }, [g.city, L(g.party_label)].filter(Boolean).join(' · ')), h(SegChip, { crm, id: g.segment }), det ? h('span', { className: 'crm-rec' }, T('Telafi önceliği')) : null, !g.offer ? h('span', { className: 'crm-booked' }, T('2026 rezervasyonu var')) : null)), h('div', { className: 'crm-dr-body' }, h('section', { className: 'crm-owner' + (agency ? ' agency' : '') }, h('div', { className: 'crm-owner-t' }, agency ? tx('Acente misafiri · {a}', { a: g.agency || '—' }) : T('Doğrudan misafir')), h('div', { className: 'crm-owner-s' }, agency ? T(VIA_NOTE) : tx('Tercih edilen kanal: {c}', { c: T(CH_LABEL[g.channel_pref] || String(g.channel_pref || '—')) })), h('div', { className: 'crm-consent' }, h('span', { className: 'crm-k' }, T('İletişim izni')), ['email', 'sms', 'telegram'].map(c => h('span', { key: c, className: 'crm-cons ' + (consent[c] ? 'on' : 'off') }, (consent[c] ? '✓ ' : '✕ ') + T(CH_LABEL[c]))))), h('div', { className: 'crm-stats' }, h(Stat, { k: T('LTV'), v: eur(g.ltv_eur), s: T('tüm tatillerin toplamı') }), h(Stat, { k: T('Tatil'), v: fmtN(g.trips_count), s: years }), h(Stat, { k: T('Eğilim'), v: pct(p100(g.propensity)), s: T('teklife dönüş olasılığı') }), h(Stat, { k: T('Kayıp riski'), v: pct(p100(g.churn_risk)), s: g.churn_risk == null ? null : T(g.churn_risk >= 0.6 ? 'risk yüksek' : g.churn_risk >= 0.3 ? 'risk orta' : 'risk düşük') })), (g.patterns || []).length || win ? h('section', { className: 'crm-sec' }, h('div', { className: 'crm-sec-t' }, T('Örüntüler')), win ? h('div', { className: 'crm-window' }, h('span', { className: 'crm-k' }, T('Sıradaki tatil penceresi')), win) : null, h('div', { className: 'crm-pats' }, (g.patterns || []).map((p, i) => h('span', { key: i, className: 'crm-pat crm-pat-' + p.key + (p.key === 'nps' && sv ? (det ? ' neg' : sv.nps >= 9 ? ' pos' : '') : '') }, L(p.label))))) : null, h(OfferCard, { crm, g, onOpp }), h('section', { className: 'crm-sec' }, h('div', { className: 'crm-sec-t' }, T('Tatil geçmişi'), h('span', { className: 'crm-sec-n' }, trips.length)), trips.length ? h('ol', { className: 'crm-tl' }, trips.map((t, i) => { const up = String(t.check_in || '') > asOf(); return h('li', { key: i, className: 'crm-tl-i' + (up ? ' up' : '') }, h('div', { className: 'crm-tl-y mono' }, String(t.check_in || '').slice(0, 4) || '—'), h('div', { className: 'crm-tl-b' }, h('div', { className: 'crm-tl-top' }, h(HotelName, { name: t.hotel, stars: t.stars }), up ? h('span', { className: 'crm-up' }, T('Yaklaşan')) : null, h('span', { className: 'crm-tl-amt mono' }, eur(t.amount_eur))), h('div', { className: 'crm-tl-s' }, [fmtDay(t.check_in, true), t.nights ? tx('{n} gece', { n: t.nights }) : null, t.sub_region, t.concept, window.crmRoom(t.room), partyTxt(t.adults, t.children)].filter(Boolean).join(' · ')), h('div', { className: 'crm-tl-s2' }, h('span', null, [t.agency ? tx('Acente: {a}', { a: t.agency }) : (TRIP_CH[t.channel] ? T(TRIP_CH[t.channel]) : t.channel), t.lead_days != null ? tx('{n} gün önceden', { n: t.lead_days }) : null].filter(Boolean).join(' · ')), t.pnr ? h('span', { className: 'crm-pnr mono' }, 'PNR ' + t.pnr) : null))); })) : h('div', { className: 'crm-empty' }, T('Kayıtlı tatil yok.'))), h('section', { className: 'crm-sec' }, h('div', { className: 'crm-sec-t' }, T('Temas geçmişi'), h('span', { className: 'crm-sec-n' }, contacts.length)), contacts.length ? h('ul', { className: 'crm-contacts' }, contacts.map((c, i) => { const cp = c.campaign_id ? D.camp[c.campaign_id] : null; return h('li', { key: i }, h('span', { className: 'crm-c-date mono' }, fmtDay(c.date, true)), h('span', { className: 'crm-c-name' }, cp ? L(cp.name) : (c.campaign_id || '—')), h(ChannelBadge, { channel: c.channel, agency: g.agency }), h('span', { className: 'crm-st crm-st-' + c.status }, T(STATUS[c.status] || String(c.status || '—'))), c.status === 'booked' && c.revenue_eur ? h('span', { className: 'crm-c-rev mono' }, eur(c.revenue_eur)) : null); })) : h('div', { className: 'crm-empty' }, T('Henüz kampanya teması yok.'))), sv ? h('section', { className: 'crm-sec crm-sv' + (det ? ' det' : '') }, h('div', { className: 'crm-sec-t' }, T('Son anket'), sv.date ? h('span', { className: 'crm-sec-n' }, fmtDay(sv.date, true)) : null), h('div', { className: 'crm-sv-row' }, h('div', { className: 'crm-sv-nps ' + (sv.nps == null ? '' : sv.nps >= 9 ? 'pos' : sv.nps >= 7 ? 'mid' : 'neg') }, sv.nps != null ? sv.nps : '—'), h('div', { className: 'crm-sv-meta' }, h('div', { className: 'crm-sv-k' }, 'NPS' + (sv.nps == null ? '' : ' · ' + T(sv.nps >= 9 ? 'Promoter (9–10)' : sv.nps >= 7 ? 'Pasif (7–8)' : 'Detractor (0–6)'))), det ? h('span', { className: 'crm-rec' }, T('Telafi önceliği')) : null, det ? h('div', { className: 'crm-sv-hint' }, T('Yeni teklif öncesi hizmet telafisi önerilir.')) : null)), sv.comment ? h('blockquote', { className: 'crm-sv-q' }, '“' + sv.comment + '”') : null, sv.comment_tr ? h('div', { className: 'crm-sv-tr' }, h('span', { className: 'crm-k' }, T('Çeviri (TR)')), sv.comment_tr) : null) : null)); return ReactDOM.createPortal(h('div', { className: 'crm-drawer-bg', onClick: onClose }, body), document.body); }; // ---------- view 1: Temas Takvimi ---------- const CalendarView = ({ crm, D, ui, upd, onOpen }) => { const wk = D.weeks[ui.week] || D.weeks[0]; const maxExp = Math.max(1, ...D.weeks.map(w => w.exp)); const list = wk.guests.slice(0, ui.shown); const wkName = (w) => (w.i === 0 ? T('Bu hafta') : tx('Hafta {n}', { n: w.i + 1 })); const via = wk.ch.agency || 0; return h(React.Fragment, null, h(Panel, { title: T('Önümüzdeki 8 hafta'), flush: true, sub: T('Temas günü = tatil penceresi − misafirin tipik rezervasyon süresi − 14 gün · haftaya tıklayın') }, h('div', { className: 'crm-weeks' }, D.weeks.map(w => h('button', { key: w.i, type: 'button', className: 'crm-week' + (w.i === wk.i ? ' active' : ''), 'aria-pressed': w.i === wk.i, onClick: () => upd({ week: w.i, shown: 20 }) }, h('div', { className: 'crm-week-k' }, wkName(w)), h('div', { className: 'crm-week-d' }, fmtRange(w.start, w.end)), h('div', { className: 'crm-week-n' }, fmtN(w.guests.length), h('span', null, ' ' + tx('temas', { n: w.guests.length }))), h('div', { className: 'crm-week-e mono' }, eurK(w.exp)), h('div', { className: 'crm-week-bar' }, h('span', { style: { width: (w.exp / maxExp * 100).toFixed(1) + '%' } })), h('div', { className: 'crm-week-o' }, w.linked ? tx('{n} fırsata bağlı', { n: w.linked }) : ' '))))), h(Panel, { flush: true, title: wkName(wk) + ' · ' + fmtRange(wk.start, wk.end), sub: tx('{n} temas', { n: wk.guests.length }) + ' · ' + tx('beklenen {v}', { v: eurK(wk.exp) }) + ' · ' + T('beklenen gelire göre sıralı'), actions: h('button', { type: 'button', className: 'btn btn-accent crm-cta-week', disabled: !wk.guests.length, onClick: () => toCampaign('guests', null, wk.guests.map(g => g.id), tx('Temas takvimi · {d} · {n} misafir', { d: fmtRange(wk.start, wk.end), n: wk.guests.length })) }, T('Bu haftaya kampanya oluştur') + ' →') }, wk.guests.length ? h('div', { className: 'crm-mix' }, h('span', { className: 'crm-k' }, T('Kanal')), ['email', 'sms', 'telegram', 'agency'].filter(c => wk.ch[c]).map(c => h('span', { key: c, className: 'crm-mix-i' }, h(ChannelBadge, { channel: c }), h('span', { className: 'mono' }, fmtN(wk.ch[c])))), wk.linked ? h('button', { type: 'button', className: 'crm-mix-opp', onClick: () => window.dispatchEvent( new CustomEvent('navigate', { detail: { page: 'fill' } })) }, '● ' + tx('{n} temas bir doluluk fırsatına bağlı', { n: wk.linked }) + ' — ' + T('Doluluk Fırsatları') + ' →') : null) : null, via ? h('div', { className: 'crm-note crm-note-bar' }, T(VIA_NOTE)) : null, wk.guests.length === 0 ? h('div', { className: 'crm-empty crm-empty-pad' }, T('Bu hafta planlanmış temas yok.')) : h('div', { className: 'crm-list' }, list.map((g, i) => { const o = g.offer; const opp = o.opportunity_id ? D.opp[o.opportunity_id] : null; return h('div', { key: g.id, className: 'crm-row', onClick: () => onOpen(g.id) }, h('div', { className: 'crm-row-rank mono' }, i + 1), h('div', { className: 'crm-row-who' }, h('button', { type: 'button', className: 'crm-name', onClick: (e) => { e.stopPropagation(); onOpen(g.id); } }, gName(g)), h(NpsBadge, { g }), h('div', { className: 'crm-row-meta' }, h(SegChip, { crm, id: g.segment }), h('span', null, [g.city, g.trips_count ? tx('{n} tatil', { n: g.trips_count }) : null].filter(Boolean).join(' · ')))), h('div', { className: 'crm-row-offer' }, h('div', { className: 'crm-row-line' }, offerLine(o)), opp ? h('div', { className: 'crm-row-opp' }, '● ' + T('Doluluk fırsatı') + ': ' + (L(opp.title) || opp.route || opp.id)) : null, (o.why || []).length ? h('ul', { className: 'crm-why' }, o.why.map((w, k) => h('li', { key: k }, L(w)))) : null), h('div', { className: 'crm-row-ch' }, h(ChannelBadge, { channel: o.channel, agency: g.agency }), h('div', { className: 'crm-row-date' }, tx('Temas: {d}', { d: fmtDay(o.contact_date) }))), h('div', { className: 'crm-row-exp' }, h('div', { className: 'crm-row-eur' }, eur(o.expected_rev_eur)), h('div', { className: 'crm-row-eurl' }, T('beklenen'))), h('div', { className: 'crm-row-act' }, h(AddButton, { id: g.id }))); })), wk.guests.length > list.length ? h('div', { className: 'crm-more' }, h('button', { type: 'button', className: 'btn btn-sm', onClick: () => upd({ shown: ui.shown + 25 }) }, tx('Daha fazla göster · {n} misafir kaldı', { n: wk.guests.length - list.length }))) : null)); }; // ---------- view 2: Misafirler ---------- const PAGE = 50; const SORTS = { ltv: 'LTV', prop: 'Eğilim', contact: 'Temas tarihi' }; const GuestsView = ({ crm, D, ui, upd, onOpen }) => { const res = useMemo(() => { const toks = norm(ui.q).split(/\s+/).filter(Boolean); const key = ui.sort === 'prop' ? (x) => -(x.g.propensity || 0) : ui.sort === 'contact' ? (x) => (x.dd == null ? 1e9 : x.dd) : (x) => -(x.g.ltv_eur || 0); return D.rows.filter(x => { const g = x.g; if (ui.seg && g.segment !== ui.seg) return false; if (ui.city && (g.market || g.city) !== ui.city) return false; if (ui.owner && g.owner !== ui.owner) return false; if (ui.ch && g.channel_pref !== ui.ch) return false; if (ui.due && !(x.dd != null && x.dd < 30)) return false; if (ui.det && !x.det) return false; for (let i = 0; i < toks.length; i++) if (x.q.indexOf(toks[i]) < 0) return false; return true; }).sort((a, b) => key(a) - key(b) || (b.g.ltv_eur || 0) - (a.g.ltv_eur || 0)); }, [D, ui.q, ui.seg, ui.city, ui.owner, ui.ch, ui.due, ui.det, ui.sort]); const pages = Math.max(1, Math.ceil(res.length / PAGE)); const page = Math.min(ui.page, pages - 1); const rows = res.slice(page * PAGE, page * PAGE + PAGE); const set = (p) => upd(Object.assign({ page: 0 }, p)); const select = (val, onChange, label, opts) => h('select', { className: 'input crm-select', value: val, 'aria-label': label, onChange: (e) => onChange(e.target.value) }, opts.map(o => h('option', { key: o[0], value: o[0] }, o[1]))); const filtered = ui.q || ui.seg || ui.city || ui.owner || ui.ch || ui.due || ui.det; const th = (k, label, cls) => h('th', { className: (cls || '') + (SORTS[k] ? ' crm-th-sort' + (ui.sort === k ? ' on' : '') : ''), onClick: SORTS[k] ? () => set({ sort: k }) : undefined, 'aria-sort': ui.sort === k ? (k === 'contact' ? 'ascending' : 'descending') : undefined }, label, ui.sort === k ? (k === 'contact' ? ' ↑' : ' ↓') : ''); const pgBtns = []; for (let p = Math.max(0, page - 2); p <= Math.min(pages - 1, page + 2); p++) pgBtns.push(p); return h(Panel, { flush: true, className: 'crm-gpanel' }, h('div', { className: 'crm-filters' }, h('div', { className: 'crm-frow' }, h('input', { className: 'input crm-search', type: 'search', value: ui.q, placeholder: T('İsim, şehir, otel veya acente…'), 'aria-label': T('Misafir ara'), onChange: (e) => set({ q: e.target.value }) }), select(ui.seg, (v) => set({ seg: v }), T('Segment'), [['', T('Tüm segmentler')]].concat((crm.segments || []).map(s => [s.id, L(s.name)]))), select(ui.city, (v) => set({ city: v }), T('Şehir / pazar'), [['', T('Tüm şehirler')]].concat(D.markets.map(m => [m, m]))), select(ui.owner, (v) => set({ owner: v }), T('Sahiplik'), [['', T('Tüm sahiplik')], ['direct', T('Doğrudan')], ['agency', T('Acente')]]), select(ui.ch, (v) => set({ ch: v }), T('Kanal'), [['', T('Tüm kanallar')], ['email', T('E-posta')], ['sms', T('SMS')], ['telegram', T('Telegram')], ['agency', T('Acente üzerinden')]])), h('div', { className: 'crm-frow' }, h('button', { type: 'button', className: 'filter-chip' + (ui.due ? ' active' : ''), 'aria-pressed': ui.due, onClick: () => set({ due: !ui.due }) }, T('Teması yaklaşanlar (30 gün)'), h('span', { className: 'crm-chip-n' }, fmtN(D.due30))), h('button', { type: 'button', className: 'filter-chip' + (ui.det ? ' active' : ''), 'aria-pressed': ui.det, onClick: () => set({ det: !ui.det }) }, T('Detractor (NPS ≤ 6)'), h('span', { className: 'crm-chip-n' }, fmtN(D.det))), h('span', { className: 'crm-flabel' }, T('Sırala')), Object.keys(SORTS).map(k => h('button', { key: k, type: 'button', className: 'filter-chip' + (ui.sort === k ? ' active' : ''), 'aria-pressed': ui.sort === k, onClick: () => set({ sort: k }) }, T(SORTS[k]))), h('span', { className: 'crm-count' }, tx('{n} misafir', { n: res.length }), filtered ? h('button', { type: 'button', className: 'crm-link', onClick: () => set({ q: '', seg: '', city: '', owner: '', ch: '', due: false, det: false }) }, T('Filtreleri temizle')) : null))), res.length === 0 ? h('div', { className: 'crm-empty crm-empty-pad' }, T('Bu filtrelerle eşleşen misafir yok.')) : h('table', { className: 'tbl crm-tbl' }, h('thead', null, h('tr', null, th('', T('Misafir')), th('', T('Segment')), th('', T('Kanal')), th('ltv', T('LTV'), 'num'), th('', T('Tatil'), 'num'), th('prop', T('Eğilim'), 'num'), th('contact', T('Sıradaki temas')), th('', T('Beklenen'), 'num'))), h('tbody', null, rows.map(x => { const g = x.g, o = g.offer; return h('tr', { key: g.id, className: 'clickable', onClick: () => onOpen(g.id) }, h('td', { className: 'crm-td-who' }, h('button', { type: 'button', className: 'crm-name', onClick: (e) => { e.stopPropagation(); onOpen(g.id); } }, gName(g)), h(NpsBadge, { g }), h('div', { className: 'crm-td-sub' }, [g.city, g.id].filter(Boolean).join(' · '))), h('td', null, h(SegChip, { crm, id: g.segment })), h('td', null, h(ChannelBadge, { channel: g.channel_pref, agency: g.agency })), h('td', { className: 'num mono' }, eur(g.ltv_eur)), h('td', { className: 'num mono' }, fmtN(g.trips_count)), h('td', { className: 'num mono' }, pct(p100(g.propensity))), h('td', null, o ? h('span', { className: x.dd != null && x.dd < 7 ? 'crm-soon' : '' }, fmtDay(o.contact_date) + (x.dd != null && x.dd < 7 ? ' · ' + T('bu hafta') : '')) : h('span', { className: 'crm-booked-t' }, T('2026 rezervasyonu var'))), h('td', { className: 'num mono' }, o ? eur(o.expected_rev_eur) : '—')); }))), res.length > PAGE ? h('nav', { className: 'crm-pager', 'aria-label': T('Sayfalar') }, h('button', { type: 'button', className: 'btn btn-sm', disabled: page === 0, onClick: () => upd({ page: page - 1 }) }, '‹ ' + T('Önceki')), pgBtns[0] > 0 ? h('button', { type: 'button', className: 'btn btn-sm crm-pg', onClick: () => upd({ page: 0 }) }, '1') : null, pgBtns[0] > 1 ? h('span', { className: 'crm-pg-gap' }, '…') : null, pgBtns.map(p => h('button', { key: p, type: 'button', className: 'btn btn-sm crm-pg' + (p === page ? ' on' : ''), 'aria-current': p === page ? 'page' : undefined, onClick: () => upd({ page: p }) }, String(p + 1))), pgBtns[pgBtns.length - 1] < pages - 2 ? h('span', { className: 'crm-pg-gap' }, '…') : null, pgBtns[pgBtns.length - 1] < pages - 1 ? h('button', { type: 'button', className: 'btn btn-sm crm-pg', onClick: () => upd({ page: pages - 1 }) }, String(pages)) : null, h('button', { type: 'button', className: 'btn btn-sm', disabled: page >= pages - 1, onClick: () => upd({ page: page + 1 }) }, T('Sonraki') + ' ›'), h('span', { className: 'crm-pager-info' }, fmtN(page * PAGE + 1) + '–' + fmtN(page * PAGE + rows.length) + ' / ' + fmtN(res.length))) : null); }; // ---------- view 3: Segmentler ---------- const SegmentsView = ({ crm, D, upd }) => h('div', { className: 'crm-segs' }, (crm.segments || []).map((s, i) => { const x = D.segs[s.id] || { eligible: [], booked: 0, pipe: 0, due30: 0 }; return h('article', { key: s.id, className: 'panel crm-segcard', style: { '--seg': 'var(--seg-' + (i % 8) + ')' } }, h('div', { className: 'crm-segcard-name' }, L(s.name)), h('div', { className: 'crm-segcard-desc' }, L(s.desc)), h('div', { className: 'crm-segstats' }, h(Stat, { k: T('Misafirler'), v: fmtN(s.count) }), h(Stat, { k: T('Ort. LTV'), v: eur(s.ltv_eur) }), h(Stat, { k: T('Ort. tatil'), v: s.avg_trips != null ? Number(s.avg_trips).toFixed(1) : '—' }), h(Stat, { k: T('Doğrudan pay'), v: pct(p100(s.share_direct)), s: h('span', { className: 'crm-share' }, h('span', { style: { width: (p100(s.share_direct) || 0) + '%' } })) })), h('div', { className: 'crm-segcard-pipe' }, h('div', null, h('span', { className: 'crm-k' }, T('Teklif pipeline\'ı')), h('strong', { className: 'mono' }, eurK(x.pipe))), h('div', null, h('span', { className: 'crm-k' }, T('30 günde temas')), h('strong', { className: 'mono' }, fmtN(x.due30)))), h('div', { className: 'crm-segcard-foot' }, tx('Kampanyaya uygun: {n} misafir', { n: x.eligible.length }), x.booked ? ' · ' + tx('{n} misafirin 2026 rezervasyonu var', { n: x.booked }) : ''), h('div', { className: 'crm-segcard-act' }, h('button', { type: 'button', className: 'btn btn-sm', onClick: () => upd({ tab: 'guests', seg: s.id, page: 0 }) }, T('Misafirleri gör')), h('button', { type: 'button', className: 'btn btn-sm btn-primary', disabled: !x.eligible.length, onClick: () => toCampaign('segment', s.id, x.eligible, L(s.name)) }, T('Bu segmente kampanya') + ' →'))); })); // ---------- page ---------- const store = { ui: { tab: 'calendar', week: 0, shown: 20, q: '', seg: '', city: '', owner: '', ch: '', due: false, det: false, sort: 'ltv', page: 0 }, open: null }; const CrmPage = () => { const [{ crm, err }, reload] = useCrm(); const [ui, setUi] = useState(store.ui); const upd = (p) => setUi(u => (store.ui = Object.assign({}, u, p))); const [openId, setOpenId] = useDrawer(store); const head = h(PageHead, { crm, eyebrow: T('Misafir 360 · Gelir odaklı CRM'), title: T('Kimi, ne zaman, '), em: T('hangi teklifle?'), lede: T('Her temas önerisi iki sinyalden doğar: misafirin tatil alışkanlığı ve masanın doldurması gereken koltuk ve odalar. Teklif, beklenen gelir ve gerekçesiyle gelir.') }); if (err) return h('div', { className: 'crm-page' }, head, h(LoadError, { onRetry: reload })); if (!crm) return h('div', { className: 'crm-page' }, head, h(Loading)); const D = derive(crm); const S = crm.summary || {}; const tabs = [['calendar', T('Temas Takvimi')], ['guests', T('Misafirler'), (crm.guests || []).length], ['segments', T('Segmentler'), (crm.segments || []).length]]; return h('div', { className: 'crm-page' }, head, h('div', { className: 'grid grid-5 gap-3 crm-kpis' }, h(KPI, { label: T('Misafirler'), value: fmtN(S.guests), sub: S.active_12m != null ? tx('{n} aktif (son 12 ay)', { n: S.active_12m }) : null }), h(KPI, { label: T('Tekrar oranı'), value: pct(p100(S.repeat_rate)), sub: S.avg_ltv_eur != null ? tx('ort. LTV {v}', { v: eur(S.avg_ltv_eur) }) : null }), h(KPI, { label: T('Doğrudan pay'), value: pct(p100(S.direct_share)), sub: S.direct_share != null ? tx('{p} acente üzerinden', { p: pct(100 - p100(S.direct_share)) }) : null }), h(KPI, { label: T('Bu hafta temas'), value: fmtN(S.contacts_due_7d), sub: S.contacts_due_30d != null ? tx('30 günde {n} temas', { n: S.contacts_due_30d }) : null }), h(KPI, { label: T('Teklif pipeline\'ı'), value: eurK(S.pipeline_eur), sub: T('beklenen gelir · tüm açık teklifler') })), h('div', { className: 'panel crm-tabs' }, h('div', { className: 'tabs', role: 'tablist' }, tabs.map(t => h('button', { key: t[0], type: 'button', role: 'tab', 'aria-selected': ui.tab === t[0], className: 'tab' + (ui.tab === t[0] ? ' active' : ''), onClick: () => upd({ tab: t[0] }) }, t[1], t[2] != null ? h('span', { className: 'crm-tab-n' }, fmtN(t[2])) : null)))), ui.tab === 'calendar' ? h(CalendarView, { crm, D, ui, upd, onOpen: setOpenId }) : null, ui.tab === 'guests' ? h(GuestsView, { crm, D, ui, upd, onOpen: setOpenId }) : null, ui.tab === 'segments' ? h(SegmentsView, { crm, D, upd }) : null, h(SelectionBar), openId ? h(GuestCard, { id: openId, onClose: () => setOpenId(null) }) : null); }; window.CrmPage = CrmPage; window.CrmGuestCard = GuestCard; window.CrmKit = { h, T, L, tx, pct, p100, eur, eurK, fmtDay, fmtRange, dayDiff, addDays, gName, isDetractor, useCrm, useDrawer, derive, Loading, LoadError, PageHead, ChannelBadge, SegChip, NpsBadge, HotelName, SelectionBar, AddButton, toCampaign, GuestCard }; })();