Files
exodevices/fitnes/legacy/Fitnes v3/attribution.js
T
yuriy.pandClaude Opus 5.5 a61d53962a Add after-hours callbacks and persistent ad attribution to all four landings
- The callback dialog switches its copy outside business hours
  (shared/business-hours.ts); such leads get a "нерабочее время" tag,
  a marker in the deal name and a line in the note in amoCRM.
- utm_*, yclid and gclid are read on page load and kept for 30 days
  (src/lib/attribution.ts), last tagged visit wins, and are sent with
  every lead.
- The callback dialog is rebuilt: focus trap, focus return, phone
  masking and a full-number check.
- fitnes drops the floating MobileCta; header and mobile bars follow
  the new dialog state in the other three.
- Add the latest design mockups under legacy/.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-23 20:53:40 +06:00

172 lines
6.4 KiB
JavaScript

/*
* EXO — рекламные метки для всех лид-форм, v1.
* Загружать до script.js. Без внешних библиотек и cookies.
* Политика: последний переход с метками, хранение 30 дней с момента перехода.
* Новый размеченный переход заменяет весь набор: кампании и click ID не смешиваются.
* localStorage — основное хранилище, sessionStorage — резерв, память — последний резерв.
* Между разными доменами/поддоменами этот модуль метки НЕ переносит.
*/
(function (window, document) {
'use strict';
if (window.EXOAttribution) return;
var KEYS = Object.freeze([
'utm_source', 'utm_medium', 'utm_campaign', 'utm_content', 'utm_term',
'yclid', 'gclid'
]);
var STORAGE_KEY = 'exo_attribution_v1';
var TTL_DAYS = 30; // Срок можно изменить здесь до публикации.
var TTL_MS = TTL_DAYS * 24 * 60 * 60 * 1000;
var FORM_SELECTOR = '#leadForm, #exoCallbackForm, form[data-exo-attribution]';
var state = null;
var lastUrlSignature = null;
function emptyValues() {
var values = {};
KEYS.forEach(function (key) { values[key] = ''; });
return values;
}
function cleanValue(value) {
// Передаём как строку, не вставляем в HTML. Ограничиваем размер входных данных.
return typeof value === 'string' ? value.trim().slice(0, 2048) : '';
}
function hasValues(values) {
return KEYS.some(function (key) { return Boolean(values[key]); });
}
function fromUrl() {
var values = emptyValues();
try {
var params = new URLSearchParams(window.location.search);
KEYS.forEach(function (key) { values[key] = cleanValue(params.get(key)); });
} catch (_) { /* Некорректный URL не должен ломать форму. */ }
return values;
}
function isFresh(record) {
if (!record || record.version !== 1 || !record.values) return false;
var age = Date.now() - record.captured_at;
return Number.isFinite(record.captured_at) && age >= 0 && age < TTL_MS;
}
function removeStored(storageName) {
try { window[storageName].removeItem(STORAGE_KEY); } catch (_) {}
}
function readStored(storageName) {
try {
var raw = window[storageName].getItem(STORAGE_KEY);
if (!raw) return null;
var record = JSON.parse(raw);
if (!isFresh(record)) {
removeStored(storageName);
return null;
}
var values = emptyValues();
KEYS.forEach(function (key) { values[key] = cleanValue(record.values[key]); });
if (!hasValues(values)) {
removeStored(storageName);
return null;
}
return {version: 1, captured_at: record.captured_at, values: values};
} catch (_) {
// SecurityError, повреждённый JSON, недоступное хранилище.
removeStored(storageName);
return null;
}
}
function persist(record) {
var json = JSON.stringify(record);
['localStorage', 'sessionStorage'].forEach(function (storageName) {
try { window[storageName].setItem(STORAGE_KEY, json); } catch (_) {}
});
}
function refresh() {
var incoming = fromUrl();
var signature = JSON.stringify(incoming);
// Пустой URL не затирает сохранённый источник. Новые метки заменяют ВЕСЬ набор.
if (hasValues(incoming) && (signature !== lastUrlSignature || !isFresh(state))) {
state = {version: 1, captured_at: Date.now(), values: incoming};
persist(state);
}
lastUrlSignature = signature;
if (state && !isFresh(state)) {
state = null;
removeStored('localStorage');
removeStored('sessionStorage');
}
// Все семь ключей присутствуют; пустая строка означает «метки нет».
// Это также исключает устаревшие значения из ранее заполненных hidden-полей.
return Object.assign(emptyValues(), state ? state.values : {});
}
function syncForm(form, values) {
KEYS.forEach(function (key) {
var fields = form.querySelectorAll('input[type="hidden"][name="' + key + '"]');
if (!fields.length) {
var field = document.createElement('input');
field.type = 'hidden';
field.name = key;
field.setAttribute('data-exo-attribution-field', '');
form.appendChild(field);
fields = [field];
}
Array.prototype.forEach.call(fields, function (field) {
field.value = values[key] || '';
});
});
}
function syncForms() {
var values = refresh();
document.querySelectorAll(FORM_SELECTOR).forEach(function (form) {
syncForm(form, values);
});
return values;
}
var localRecord = readStored('localStorage');
var sessionRecord = readStored('sessionStorage');
state = localRecord;
if (sessionRecord && (!state || sessionRecord.captured_at > state.captured_at)) {
state = sessionRecord;
}
window.EXOAttribution = Object.freeze({
keys: KEYS,
storageKey: STORAGE_KEY,
ttlDays: TTL_DAYS,
collect: refresh,
syncForms: syncForms
});
window.collectAttribution = function collectAttribution() {
return refresh();
};
// Захват при загрузке, а не только в момент отправки заявки.
refresh();
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', syncForms, {once: true});
} else {
syncForms();
}
// Capture-фаза: обновление hidden-полей до чтения FormData основным обработчиком.
document.addEventListener('submit', function (event) {
if (event.target.matches && event.target.matches(FORM_SELECTOR)) {
syncForm(event.target, refresh());
}
}, true);
document.addEventListener('reset', function (event) {
if (event.target.matches && event.target.matches(FORM_SELECTOR)) {
// После form.reset() возвращаем метки для повторной заявки.
window.setTimeout(syncForms, 0);
}
}, true);
window.addEventListener('popstate', syncForms);
window.addEventListener('pageshow', syncForms);
})(window, document);