import { Inject, Injectable } from '@nestjs/common'; import { PG } from '../db/db.module'; import { Sql, toVector } from '../db/db'; import { KeywordRepository } from '../keywords/keyword.repository'; import { normalizeKeyword } from '../keywords/normalize'; import { EmbeddingProvider } from '../embedding/types'; import { MerchantsService, MerchantWithTaxonomy } from '../merchants/merchants.service'; export interface SeoPayload { merchant: { id: string; externalId: string; name: string; siteUrl: string | null }; title: string; description: string; keywords: string[]; tags: Array<{ keyword: string; intent: string; relevance: number; aliases: string[] }>; generatedAt: string | null; } export interface AeoPayload { merchant: { id: string; externalId: string; name: string }; topics: string[]; faqs: Array<{ question: string; answer: string }>; /** JSON-LD 는 후속 단계에서 이 payload 를 그대로 매핑해 생성한다 */ structuredDataHints: { type: 'LocalBusiness'; name: string; description: string; areaServed: string | null; category: string | null; }; } @Injectable() export class ServingService { constructor( @Inject(PG) private readonly sql: Sql, private readonly merchants: MerchantsService, private readonly keywords: KeywordRepository, private readonly embedder: EmbeddingProvider, ) {} async seo(idOrExternalId: string, limit: number): Promise { const m = await this.merchants.findWithTaxonomy(idOrExternalId); const rows = await this.sql< Array<{ canonical: string; intent: string; relevance: number; aliases: string[] }> >` SELECT k.canonical, k.intent, mk.relevance, k.aliases FROM merchant_keyword mk JOIN keyword k ON k.id = mk.keyword_id WHERE mk.merchant_id = ${m.id} AND mk.status = 'active' ORDER BY mk.relevance DESC, k.usage_count ASC LIMIT ${limit}`; const kws = rows.map((r) => r.canonical); const locality = [m.region_name, m.industry_name].filter(Boolean).join(' '); return { merchant: { id: m.id, externalId: m.external_id, name: m.name, siteUrl: m.site_url }, title: locality ? `${m.name} | ${locality}` : m.name, description: buildDescription(m.name, m.description, kws), keywords: kws, tags: rows.map((r) => ({ keyword: r.canonical, intent: r.intent, relevance: Number(r.relevance), aliases: r.aliases ?? [], })), generatedAt: m.last_generated_at ? new Date(m.last_generated_at).toISOString() : null, }; } async aeo(idOrExternalId: string, limit: number): Promise { const m = await this.merchants.findWithTaxonomy(idOrExternalId); const faqs = await this.sql>` SELECT question, answer FROM qa_pair WHERE merchant_id = ${m.id} AND status = 'active' ORDER BY created_at ASC LIMIT ${limit}`; const topics = await this.sql>` SELECT k.canonical FROM merchant_keyword mk JOIN keyword k ON k.id = mk.keyword_id WHERE mk.merchant_id = ${m.id} AND mk.status = 'active' AND k.intent IN ('informational', 'local') ORDER BY mk.relevance DESC LIMIT ${limit}`; return { merchant: { id: m.id, externalId: m.external_id, name: m.name }, topics: topics.map((t) => t.canonical), faqs, structuredDataHints: { type: 'LocalBusiness', name: m.name, description: m.description, areaServed: m.region_name, category: m.industry_name, }, }; } /** 자유 입력(업체명 또는 문장) → 적재된 키워드 사전에서 잘 맞는 것을 골라준다. */ async match(rawQuery: string, limit: number) { const query = rawQuery.trim(); const merchant = await this.resolveMerchant(query); const queryText = merchant ? [ merchant.name, merchant.region_name, merchant.industry_name, merchant.description, ...toStrings(merchant.profile?.['services']), ...toStrings(merchant.profile?.['features']), ...toStrings(merchant.profile?.['audiences']), ...toStrings(merchant.profile?.['nearby']), ].filter(Boolean).join(' ') : query; const [embedding] = await this.embedder.embed([queryText], 'query'); const rows = await this.sql>` SELECT k.id, k.canonical, k.intent, k.kind, k.category, k.aliases, k.usage_count, 1 - (k.embedding <=> ${toVector(embedding)}::vector) AS score, (mk.merchant_id IS NOT NULL) AS linked FROM keyword k LEFT JOIN merchant_keyword mk ON mk.keyword_id = k.id AND mk.merchant_id = ${merchant?.id ?? null} WHERE k.embedding IS NOT NULL ORDER BY k.embedding <=> ${toVector(embedding)}::vector LIMIT ${limit}`; return { mode: 'single' as const, input: query, resolved: merchant ? { id: merchant.id, externalId: merchant.external_id, name: merchant.name, region: merchant.region_name, industry: merchant.industry_name, description: merchant.description, siteUrl: merchant.site_url, profile: merchant.profile ?? {}, } : null, queryText, embeddingProvider: this.embedder.name, total: await this.dictionarySize(), matches: rows.map((r) => ({ ...r, score: Number(r.score) })), }; } /** 상호는 띄어쓰기가 흔들린다 — 정규화 일치 → trigram 순으로 해석 */ private async resolveMerchant(query: string) { const norm = normalizeKeyword(query); if (!norm) return null; const rows = await this.sql>` SELECT m.*, i.name AS industry_name, i.path::text AS industry_path, r.name AS region_name, r.path::text AS region_path, similarity(regexp_replace(lower(m.name), '\\s', '', 'g'), ${norm}) AS sim FROM merchant m LEFT JOIN industry i ON i.id = m.industry_id LEFT JOIN region r ON r.id = m.region_id WHERE regexp_replace(lower(m.name), '\\s', '', 'g') = ${norm} OR m.external_id = ${query} OR similarity(regexp_replace(lower(m.name), '\\s', '', 'g'), ${norm}) >= 0.45 ORDER BY sim DESC NULLS LAST LIMIT 1`; return rows[0] ?? null; } async dictionarySize() { const [row] = await this.sql>` SELECT count(*)::int AS n FROM keyword WHERE embedding IS NOT NULL`; return row?.n ?? 0; } async searchKeywords(query: string, limit: number) { const [embedding] = await this.embedder.embed([query], 'query'); return this.keywords.searchByVector(embedding, 'ko-KR', limit); } /** Search Console / 유입 로그 피드백 → 저성과 키워드 강등 */ async applyPerformance( idOrExternalId: string, items: Array<{ keyword: string; impressions: number; clicks: number }>, ) { const m = await this.merchants.findWithTaxonomy(idOrExternalId); let updated = 0; for (const it of items) { const rows = await this.sql>` UPDATE merchant_keyword mk SET impressions = mk.impressions + ${it.impressions}, clicks = mk.clicks + ${it.clicks}, ctr = CASE WHEN (mk.impressions + ${it.impressions}) > 0 THEN (mk.clicks + ${it.clicks})::real / (mk.impressions + ${it.impressions}) ELSE 0 END, updated_at = now() FROM keyword k WHERE k.id = mk.keyword_id AND mk.merchant_id = ${m.id} AND (k.canonical = ${it.keyword} OR ${it.keyword} = ANY(k.aliases)) RETURNING mk.keyword_id`; updated += rows.length; } // 노출은 충분한데 클릭이 없는 키워드는 강등 → 다음 생성 사이클에서 대체 const demoted = await this.sql>` UPDATE merchant_keyword SET status = 'demoted', updated_at = now() WHERE merchant_id = ${m.id} AND status = 'active' AND impressions >= 100 AND ctr < 0.002 RETURNING keyword_id`; return { matched: updated, demoted: demoted.length }; } } function toStrings(v: unknown): string[] { return Array.isArray(v) ? v.filter((x): x is string => typeof x === 'string') : []; } function buildDescription(name: string, desc: string, keywords: string[]): string { const base = desc?.trim() || `${name} 안내`; const tail = keywords.slice(0, 3).join(', '); const full = tail ? `${base} ${tail} 정보를 확인하세요.` : base; return full.length > 155 ? `${full.slice(0, 152)}...` : full; }