Files
o2o-site-AEO/ontology/src/merchants/merchants.service.ts
T
HyeongBaeYangandClaude Opus 5.5 847943a8bc [feat] ontology: 새 숙소 키워드를 OpenAI 로 쌓고 매칭에 쓴다 — 호텔 업종 · 숙소 검색 정정
사전이 고정 데이터셋뿐이라 사전에 없는 숙소는 새 단어를 받지 못했고, 생성분은 MATCH_SOURCES 가
llm 을 빼서 만들어도 추천에 안 나왔다. 숙소 검색은 가까운 키워드를 사전 전체(7천)에서 뽑아
상위가 아무 숙소에도 안 붙은 단어로 차서 `선유도 독채` 가 0건이었다.

- merchants.controller: 처음 보는 업체·기한 지난 업체만 생성, sync 는 처음 보는 업체만 기다림 —
  재빌드마다 불리는 창구라 조건이 없으면 저장마다 요금. 동기 생성 실패는 200 + generation.failed
- generation·dedup·keyword.repository: mock 생성분은 source='mock' — compose 기본이 mock 이라
  키 없는 환경의 가짜 단어가 매칭 후보가 되지 않게
- match.service: llm 출처를 후보에 넣음(brand 는 그 업체 것만), 업종은 뿌리(stay)로 좁힘 —
  새 호텔은 호텔 사전이 비어 잎으로 좁히면 후보 0건
- openai.provider: 미확인 시설·다른 숙박 유형어·가격 주장 금지
- drizzle/0002 · seed: stay.hotel — 시드만 두면 떠 있는 DB 에서 외래키 위반 500
- serving.service: 숙소에 연결된 키워드만 비교, 검색어가 지역을 말하면 그 지역 숙소만 —
  e5-small 은 지역이 틀려도 0.85(`여수 호텔` → 군산 호텔 0.848)라 임계값으로는 못 가른다

tsc 통과. 로컬 :3101 + 실 OpenAI(가짜 숙소 2곳): 첫 발행 7초 · 키워드 12 생성 · 재발행 fresh,
검색 7건(`은파호수공원 근처 호텔`·`선유도 독채`·`군산시내호텔` 적중, `여수 호텔` 0건) 확인 후 테스트 데이터 삭제

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-01 13:49:37 +09:00

99 lines
3.6 KiB
TypeScript

import { Inject, Injectable, NotFoundException } from '@nestjs/common';
import { PG } from '../db/db.module';
import { asJson, Sql } from '../db/db';
export interface MerchantRow {
id: string;
external_id: string;
name: string;
industry_id: string | null;
region_id: string | null;
description: string;
profile: Record<string, unknown>;
site_url: string | null;
last_generated_at: Date | null;
}
export interface MerchantWithTaxonomy extends MerchantRow {
industry_name: string | null;
industry_path: string | null;
region_name: string | null;
region_path: string | null;
}
export interface UpsertMerchantDto {
externalId: string;
name: string;
industryId?: string | null;
regionId?: string | null;
description?: string;
profile?: Record<string, unknown>;
siteUrl?: string | null;
}
@Injectable()
export class MerchantsService {
constructor(@Inject(PG) private readonly sql: Sql) {}
/** o2o-site-AEO 가 사이트를 발행할 때 호출하는 진입점 */
async upsert(dto: UpsertMerchantDto): Promise<MerchantRow> {
const rows = await this.sql<MerchantRow[]>`
INSERT INTO merchant (external_id, name, industry_id, region_id, description, profile, site_url)
VALUES (${dto.externalId}, ${dto.name}, ${dto.industryId ?? null}, ${dto.regionId ?? null},
${dto.description ?? ''}, ${this.sql.json(asJson(dto.profile ?? {}))}, ${dto.siteUrl ?? null})
ON CONFLICT (external_id) DO UPDATE SET
name = EXCLUDED.name,
industry_id = EXCLUDED.industry_id,
region_id = EXCLUDED.region_id,
description = EXCLUDED.description,
profile = EXCLUDED.profile,
site_url = EXCLUDED.site_url,
updated_at = now()
RETURNING *`;
return rows[0];
}
async findWithTaxonomy(idOrExternalId: string): Promise<MerchantWithTaxonomy> {
const rows = await this.sql<MerchantWithTaxonomy[]>`
SELECT m.*,
i.name AS industry_name, i.path::text AS industry_path,
r.name AS region_name, r.path::text AS region_path
FROM merchant m
LEFT JOIN industry i ON i.id = m.industry_id
LEFT JOIN region r ON r.id = m.region_id
WHERE m.external_id = ${idOrExternalId}
OR (${isUuid(idOrExternalId)} AND m.id::text = ${idOrExternalId})
LIMIT 1`;
if (!rows[0]) throw new NotFoundException(`merchant not found: ${idOrExternalId}`);
return rows[0];
}
async list(limit = 50) {
return this.sql<MerchantRow[]>`
SELECT * FROM merchant ORDER BY created_at DESC LIMIT ${limit}`;
}
/** 주기 리프레시 대상: 한 번도 생성 안 됐거나 N일 지난 업체 */
async findStale(intervalDays: number, limit: number) {
return this.sql<Array<{ id: string; external_id: string }>>`
SELECT id, external_id FROM merchant
WHERE last_generated_at IS NULL
OR last_generated_at < now() - (${intervalDays} || ' days')::interval
ORDER BY last_generated_at NULLS FIRST
LIMIT ${limit}`;
}
/** findStale 과 같은 기준을 행 하나에 — publish 가 생성 여부를 정할 때 쓴다 */
isStale(merchant: Pick<MerchantRow, 'last_generated_at'>, intervalDays: number): boolean {
if (!merchant.last_generated_at) return true;
return Date.now() - new Date(merchant.last_generated_at).getTime() > intervalDays * 86_400_000;
}
async markGenerated(merchantId: string) {
await this.sql`UPDATE merchant SET last_generated_at = now() WHERE id = ${merchantId}`;
}
}
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
const isUuid = (v: string) => UUID_RE.test(v);