diff --git a/package.json b/package.json index fc23268..25af99d 100644 --- a/package.json +++ b/package.json @@ -10,7 +10,8 @@ "clean": "rm -rf dist", "lint": "tsc --noEmit", "db:sync": "tsx scripts/sync-db-local.ts", - "sync-registry": "tsx scripts/import-registry.ts" + "sync-registry": "tsx scripts/import-registry.ts", + "test": "node --experimental-strip-types --no-warnings --test tests/*.test.ts" }, "dependencies": { "@google/genai": "^1.29.0", diff --git a/src/lib/attribution.ts b/src/lib/attribution.ts new file mode 100644 index 0000000..c2fc630 --- /dev/null +++ b/src/lib/attribution.ts @@ -0,0 +1,100 @@ +/** + * 문의 유입 기록(UTM). + * + * webforai.kr·company·region(webforai-landing 저장소 site/assets/attr.js)과 같은 규칙·같은 쿠키(wfa_attr, Domain=.webforai.kr)를 쓴다. + * 그래서 네이버 블로그 → infinith.webforai.kr → webforai.kr 처럼 서브도메인을 옮겨 다녀도 같은 기록이 남는다. + * + * 규칙: 마지막으로 들어온 '직접 방문이 아닌' 경로를 30일 기억(last non-direct touch). + * - 주소에 utm_* 가 있으면 덮어쓴다 + * - utm 없이 외부 사이트(또는 광고 클릭 ID)로 왔으면, 살아 있는 utm 기록이 없을 때만 ref 로 남긴다 + * - 직접 방문·같은 사이트 안 이동은 기록을 바꾸지 않는다 + * 문의 함수로 보내는 source 뒤에 붙는다. 예: footer | utm:naver_blog/organic/2611_webforai_hospital | land:infinith.webforai.kr/ + */ + +export const ATTR_KEY = 'wfa_attr'; +export const ATTR_TTL_MS = 30 * 24 * 60 * 60 * 1000; +const UTM_KEYS = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_content', 'utm_term'] as const; +const CLICK_IDS = ['fbclid', 'gclid', 'NaPm'] as const; + +export interface Attribution { + utm?: Partial>; + click?: string; + ref?: string; + land: string; + at: number; +} + +const clean = (s: string) => s.replace(/[|\s]+/g, ' ').trim().slice(0, 60); +const baseDomain = (h: string) => h.split('.').slice(-2).join('.'); + +export function nextAttribution( + prev: Attribution | null, + search: string, + referrer: string, + host: string, + land: string, + now: number, +): Attribution | null { + const q = new URLSearchParams(search); + const utm: NonNullable = {}; + for (const k of UTM_KEYS) { + const v = q.get(k); + if (v) utm[k] = clean(v); + } + const click = CLICK_IDS.find((k) => q.has(k)); + const alive = prev && now - prev.at < ATTR_TTL_MS ? prev : null; + if (Object.keys(utm).length) return { utm, click, land, at: now }; + + let refHost = ''; + try { + refHost = referrer ? new URL(referrer).hostname : ''; + } catch { + refHost = ''; + } + const external = !!refHost && refHost !== host && baseDomain(refHost) !== baseDomain(host); + if (alive?.utm) return null; + if (click) return { click, ref: refHost || undefined, land, at: now }; + if (external) return { ref: refHost, land, at: now }; + return null; +} + +export function attributionSuffix(a: Attribution | null, now: number): string { + if (!a || now - a.at >= ATTR_TTL_MS) return ''; + const parts: string[] = []; + if (a.utm) { + const u = a.utm; + parts.push('utm:' + [u.utm_source ?? '-', u.utm_medium ?? '-', u.utm_campaign ?? '-'].join('/')); + if (u.utm_content) parts.push('content:' + u.utm_content); + if (u.utm_term) parts.push('term:' + u.utm_term); + } + if (a.click) parts.push('click:' + a.click); + if (a.ref) parts.push('ref:' + a.ref); + parts.push('land:' + a.land.slice(0, 80)); + return ' | ' + parts.join(' | '); +} + +function read(): Attribution | null { + const m = document.cookie.match(new RegExp('(?:^|; )' + ATTR_KEY + '=([^;]*)')); + if (!m) return null; + try { + return JSON.parse(decodeURIComponent(m[1])) as Attribution; + } catch (e) { + console.warn('[attribution] 유입 기록을 읽지 못했습니다', e); + return null; + } +} + +/** 앱 시작 때 한 번 부른다(main.tsx). SPA 라 첫 진입 주소에 utm 이 있다. */ +export function captureAttribution(): void { + const host = location.hostname; + const rec = nextAttribution(read(), location.search, document.referrer, host, host + location.pathname, Date.now()); + if (!rec) return; + const domain = /(^|\.)webforai\.kr$/.test(host) ? '; Domain=.webforai.kr' : ''; + const secure = location.protocol === 'https:' ? '; Secure' : ''; + document.cookie = `${ATTR_KEY}=${encodeURIComponent(JSON.stringify(rec))}; Max-Age=${ATTR_TTL_MS / 1000}; Path=/${domain}; SameSite=Lax${secure}`; +} + +/** 문의 source 에 붙일 꼬리. */ +export function currentAttributionSuffix(): string { + return attributionSuffix(read(), Date.now()); +} diff --git a/src/lib/submitLead.ts b/src/lib/submitLead.ts index 5f62d64..2a8d876 100644 --- a/src/lib/submitLead.ts +++ b/src/lib/submitLead.ts @@ -24,6 +24,8 @@ export interface LeadInput { website: string; } +import { currentAttributionSuffix } from './attribution'; + export type LeadResult = { ok: true } | { ok: false; reason: 'failed' }; export async function submitLead(input: LeadInput): Promise { @@ -31,7 +33,8 @@ export async function submitLead(input: LeadInput): Promise { const res = await fetch('/api/lead', { method: 'POST', headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify(input), + // 유입 경로(UTM 등)를 source 뒤에 붙인다. 화면 분석 이벤트에는 붙이지 않는다(ContactModal 은 원래 source 만 보냄) + body: JSON.stringify({ ...input, source: input.source + currentAttributionSuffix() }), }); const data = await res.json().catch(() => null); // 성공했다고 말할 근거가 없으면 실패로 둔다. 화면은 메일 폴백을 보여준다. diff --git a/src/main.tsx b/src/main.tsx index d190a97..902f46f 100644 --- a/src/main.tsx +++ b/src/main.tsx @@ -25,8 +25,11 @@ import PrivacyPage from './pages/PrivacyPage.tsx'; import TermsPage from './pages/TermsPage.tsx'; import SampleReportPage from './pages/SampleReportPage.tsx'; import { DISCOVERY_SITE, SHOW_PRICING, SHOW_SAMPLE_REPORT } from './lib/site'; +import { captureAttribution } from './lib/attribution'; import './index.css'; +captureAttribution(); + createRoot(document.getElementById('root')!).render( diff --git a/tests/attribution.test.ts b/tests/attribution.test.ts new file mode 100644 index 0000000..6b442f8 --- /dev/null +++ b/tests/attribution.test.ts @@ -0,0 +1,21 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { nextAttribution, attributionSuffix, ATTR_TTL_MS } from '../src/lib/attribution.ts'; + +const NOW = 1_800_000_000_000; +const H = 'infinith.webforai.kr'; + +test('utm 기록과 꼬리', () => { + const a = nextAttribution(null, '?utm_source=naver_blog&utm_medium=organic&utm_campaign=2611_h', '', H, H + '/', NOW); + assert.equal(attributionSuffix(a, NOW), ' | utm:naver_blog/organic/2611_h | land:infinith.webforai.kr/'); +}); +test('webforai.kr 에서 넘어온 것은 같은 사이트', () => { + assert.equal(nextAttribution(null, '', 'https://webforai.kr/', H, H + '/', NOW), null); +}); +test('외부 유입은 살아 있는 utm 을 덮지 않고, 없으면 ref', () => { + const u = nextAttribution(null, '?utm_source=facebook', '', H, H + '/', NOW); + assert.equal(nextAttribution(u, '', 'https://blog.naver.com/x', H, H + '/', NOW + 1), null); + const r = nextAttribution(null, '', 'https://blog.naver.com/x', H, H + '/', NOW); + assert.equal(attributionSuffix(r, NOW), ' | ref:blog.naver.com | land:infinith.webforai.kr/'); + assert.equal(attributionSuffix(r, NOW + ATTR_TTL_MS), ''); +});