최상단을 프로젝트 단위로 평평하게 둔다 — o2o-negosium 과 같은 규약이고, 이 레포만
다르게 갈 이유가 없다. negodata/{backend,front} 가 프로젝트 안에서 f/b 를 가르는 선례,
lps-admin/ 이 백엔드 없이 프론트만 가진 최상단 폴더의 선례다.
backend/ frontend/{admin,site,shared} → solution/{backend,front,site,shared} + admin/
## 왜
내부 라우트(/local-content, /places/:id/seo)의 이름과 화면 코드가 사장님 번들에
그대로 실려 나가고 있었다. UserRole.DEVELOPER 주석의 "고객사에 존재를 노출하지 않는다"를
번들이 깨고 있었다 — 라우트 가드는 화면을 가리지 번들은 못 가린다.
번들을 갈라 확인했다: 사장님 dist 에서 local-content · /places · SeoAudit 이 전부 0건이다.
그 과정에서 두 곳이 더 새고 있었다.
- AppShell 의 NAV 배열이 내부 메뉴를 하드코딩하고 있었다. 앱을 가른 뒤에도 dist 에
local-content 가 남아서 찾았다. 메뉴는 이제 앱이 prop 으로 들고 온다.
- EditorHeader·BuilderPage·LoginPage 가 /places 로 링크하고 있었다. 그 화면이 admin 으로
나갔으니 사장님 앱에서는 404 다. 링크를 걷어내고 LoginPage 기본 도착지는 '/' 로 바꿨다
(앱마다 홈이 다르고 각 라우터의 '/' 가 이미 그걸 안다).
## admin 에 백엔드를 두지 않았다
내부 화면이 부르는 훅이 전부 router/v1/{place,fact,local,validator} 에 이미 있다.
자체 백엔드를 두면 place·fact·link 를 같은 DB 에 대고 두 번 구현하게 된다.
대가는 solution/backend 가 죽으면 admin 도 멈추는 것 — 내부 도구라 감수한다.
## admin 의 `@` 는 solution/front/src 를 가리킨다
내부 화면이 쓰는 API 클라이언트·UI·수집 배선이 solution 에 한 벌만 있고 그 파일들끼리도
`@/...` 로 서로를 부른다. admin 에서 `@` 를 자기 src 로 잡으면 그 참조가 전부 깨진다
(실측 TS2307 14건). 복제하는 길도 있지만 RecollectPanel 주석이 금지한다 —
"수집 경로를 두 벌 만들면 확정 게이트"가 갈라진다.
admin 자기 파일만 `@admin` 이고, 의존 방향은 admin → solution 한 쪽뿐이다.
admin 이 여는 빌더는 다른 오리진이라 절대 URL + 새 탭이다(admin/src/lib/solutionUrl.ts).
react-router Link 로 두면 admin 안에서 라우트를 찾다 404 다.
## 그 밖
- npm 워크스페이스 루트를 레포 루트로 올렸다(admin 이 solution 밖이라).
- docker-compose 를 255→174줄로 줄이고 admin(:3002) 서비스를 넣었다. ADMIN_BIND 기본값은
127.0.0.1 — 0.0.0.0 으로 열면 앱을 가른 의미가 없다.
- 발행 호스트를 프론트 .env 에 따로 적지 않는다. compose 가 루트의 SITE_PUBLIC_HOST 를
VITE_PUBLISH_HOST 로 흘려보낸다 — 두 곳에 적으면 canonical 과 화면 주소가 조용히 갈라진다.
- nginx/site.conf 를 git 에서 빼고 .example 만 남겼다(.env·*.toml 과 같은 규약).
compose 가 bind mount 하므로 클론 직후 복사해야 한다 — 없으면 Docker 가 그 자리에
디렉토리를 만들어 nginx 가 설정 없이 뜬다.
- config.test.toml.example 을 추가했다. 없으면 클론한 사람이 pytest 를 아예 못 돌린다
(conftest import 단계에서 죽는다). 외부 API 키는 전부 빈값이다 —
APP_ENV=test 가 .env 를 안 읽는 이유를 여기서 우회하면 안 된다.
- 경로가 한 칸 깊어져 test_schema_ddl(parents[2]→[3]) 과 test_site_theme 을 고쳤다.
검증: front·admin·site 전부 lint 0 / build 0. 백엔드 514 passed.
남은 4건(test_build_publish 3 · test_snapshot 1)은 이 변경 전부터 실패하던 것으로,
손대지 않은 메인 체크아웃에서 같은 4건이 같게 실패하는 것을 확인했다.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019uYhHQdssRubirPirrdJJC
725 lines
33 KiB
Python
725 lines
33 KiB
Python
import uuid
|
|
|
|
from fastapi import Depends
|
|
|
|
from common.category_schema import CategorySchemaError, get_schema
|
|
from common.database.db_session_manager import DB_SESSION_MNG
|
|
from common.database.model.models import place_links, places, units
|
|
from common.enums import DBWRType, ErrorType, JobStatus, JobType, LinkChannel, PlaceCategory, PlaceStatus, SourceType
|
|
from common.logger import LOG
|
|
from common.models.gmodel import PageParams, UserInfo
|
|
from common.utils.gtime import GTime
|
|
from crud.job_crud import JobQueue
|
|
from crud.place_crud import IPlaceCRUD, PlaceCRUD
|
|
from router.v1.place.protocol import (
|
|
Req_VerifyPlaceByUrl,
|
|
LinkData,
|
|
PlaceData,
|
|
UnitData,
|
|
Req_CreateLink,
|
|
Req_CreatePlace,
|
|
Req_CreateUnit,
|
|
Req_StartCollect,
|
|
Req_StartCopy,
|
|
Req_StartVision,
|
|
Req_UpdatePlace,
|
|
Req_VerifyPlace,
|
|
Res_Link,
|
|
Res_LinkList,
|
|
Res_Place,
|
|
Res_PlaceList,
|
|
Res_VerifyCandidates,
|
|
PlaceCandidate,
|
|
Res_StartCollect,
|
|
Res_StartCopy,
|
|
Res_StartVision,
|
|
Res_Unit,
|
|
Res_UnitList,
|
|
)
|
|
from router.v1.job.protocol import JobData, Res_Job
|
|
# 도로명주소 → 지역 캐시 키. 외부 장소 DB 는 행정구역 코드를 주지 않으므로 여기서 만든다.
|
|
from services.external.naver import region_key
|
|
from services.job_service import enqueue_job
|
|
|
|
|
|
class PlaceService:
|
|
"""사업장 등록·조회·동일 업소 검증.
|
|
|
|
★ 이 서비스의 핵심 규칙: `verified_at` 이 NULL 인 사업장은 수집이 열리지 않는다.
|
|
카카오 로컬로 동일 업소임을 확인하지 않으면 남의 가게 정보가 섞인다.
|
|
"""
|
|
|
|
def __init__(self, crud: IPlaceCRUD = Depends(PlaceCRUD), queue: JobQueue = Depends(JobQueue)):
|
|
self.crud = crud
|
|
self.queue = queue
|
|
|
|
# ---- 조회 ----
|
|
async def list_places(self, user_info: UserInfo, pg: PageParams, search=None, category=None, status=None) -> Res_PlaceList:
|
|
res = Res_PlaceList(page=pg.page, size=pg.size)
|
|
cid = uuid.UUID(user_info.company_id)
|
|
err_type, rows, total = await DB_SESSION_MNG.execute_lambda(
|
|
places.DBType(),
|
|
DBWRType.DB_READ.value,
|
|
lambda s: self.crud.list_places(
|
|
s, cid, search,
|
|
category.value if isinstance(category, PlaceCategory) else category,
|
|
status.value if isinstance(status, PlaceStatus) else status,
|
|
pg.skip, pg.size,
|
|
),
|
|
)
|
|
if err_type != ErrorType.SUCCESS:
|
|
res.result.SetResult(err_type)
|
|
return res
|
|
res.places = [PlaceData.model_validate(r) for r in rows]
|
|
res.total = total
|
|
return res
|
|
|
|
async def get_place(self, user_info: UserInfo, place_id: str) -> Res_Place:
|
|
res = Res_Place()
|
|
err_type, place = await self._load(user_info, place_id)
|
|
if err_type != ErrorType.SUCCESS:
|
|
res.result.SetResult(err_type)
|
|
return res
|
|
res.place = PlaceData.model_validate(place)
|
|
return res
|
|
|
|
async def _load(self, user_info: UserInfo, place_id: str):
|
|
"""회사 스코프로 사업장 1건. 없으면 PLACE_NOT_FOUND(남의 회사 것도 '없음'으로 응답)."""
|
|
err_type, place = await DB_SESSION_MNG.execute_lambda(
|
|
places.DBType(),
|
|
DBWRType.DB_READ.value,
|
|
lambda s: self.crud.get_place(s, uuid.UUID(user_info.company_id), uuid.UUID(place_id)),
|
|
)
|
|
if err_type != ErrorType.SUCCESS:
|
|
return ErrorType.PLACE_NOT_FOUND, None
|
|
return ErrorType.SUCCESS, place
|
|
|
|
# ---- 등록 ----
|
|
async def create_place(self, user_info: UserInfo, req: Req_CreatePlace) -> Res_Place:
|
|
res = Res_Place()
|
|
if not req.name.strip():
|
|
res.result.SetResult(ErrorType.INVALID_REQUEST_DATA)
|
|
return res
|
|
# 업종 스키마가 없는 업종은 받지 않는다 — fact 를 하나도 쓸 수 없다.
|
|
try:
|
|
get_schema(req.category)
|
|
except CategorySchemaError:
|
|
res.result.SetResult(ErrorType.PLACE_INVALID_CATEGORY)
|
|
return res
|
|
|
|
place = places(
|
|
company_id=uuid.UUID(user_info.company_id),
|
|
owner_user_id=req.owner_user_id,
|
|
name=req.name.strip(),
|
|
category=req.category.value,
|
|
status=PlaceStatus.DRAFT.value,
|
|
)
|
|
err_type = await DB_SESSION_MNG.execute_lambda_run(
|
|
[places.DBType()],
|
|
[lambda s: self.crud.add_place(s, place)],
|
|
)
|
|
if err_type != ErrorType.SUCCESS:
|
|
res.result.SetResult(err_type)
|
|
return res
|
|
res.place = PlaceData.model_validate(place)
|
|
return res
|
|
|
|
async def update_place(self, user_info: UserInfo, place_id: str, req: Req_UpdatePlace) -> Res_Place:
|
|
res = Res_Place()
|
|
data = req.model_dump(exclude_unset=True, exclude_none=True)
|
|
if "status" in data:
|
|
data["status"] = req.status.value
|
|
if "name" in data:
|
|
data["name"] = str(data["name"]).strip()
|
|
|
|
if data:
|
|
err_type, rowcount = await DB_SESSION_MNG.execute_lambda_claim(
|
|
places.DBType(),
|
|
lambda s: self.crud.update_place(s, uuid.UUID(user_info.company_id), uuid.UUID(place_id), data),
|
|
)
|
|
if err_type != ErrorType.SUCCESS:
|
|
res.result.SetResult(err_type)
|
|
return res
|
|
if rowcount == 0:
|
|
res.result.SetResult(ErrorType.PLACE_NOT_FOUND)
|
|
return res
|
|
return await self.get_place(user_info, place_id)
|
|
|
|
async def delete_place(self, user_info: UserInfo, place_id: str) -> Res_Place:
|
|
res = Res_Place()
|
|
err_type, rowcount = await DB_SESSION_MNG.execute_lambda_claim(
|
|
places.DBType(),
|
|
lambda s: self.crud.delete_place(
|
|
s, uuid.UUID(user_info.company_id), uuid.UUID(place_id)
|
|
),
|
|
)
|
|
if err_type != ErrorType.SUCCESS:
|
|
res.result.SetResult(err_type)
|
|
elif rowcount == 0:
|
|
res.result.SetResult(ErrorType.PLACE_NOT_FOUND)
|
|
return res
|
|
|
|
async def get_active_collect(self, user_info: UserInfo, place_id: str) -> Res_Job:
|
|
"""재접속한 화면이 진행 중인 수집 잡에 다시 연결할 수 있게 한다."""
|
|
res = Res_Job()
|
|
err_type, _place = await self._load(user_info, place_id)
|
|
if err_type != ErrorType.SUCCESS:
|
|
res.result.SetResult(err_type)
|
|
return res
|
|
row = await self.queue.find_active(f"collect:{place_id}")
|
|
if row:
|
|
res.job = JobData(**row)
|
|
return res
|
|
|
|
# ---- 동일 업소 검증 ----
|
|
async def verify_place_by_url(self, user_info: UserInfo, place_id: str, req: Req_VerifyPlaceByUrl) -> Res_Place:
|
|
"""네이버 플레이스 URL → 상호·주소·좌표를 읽어 동일 업소를 확정하고, 그 URL 을 수집 채널로 등록한다.
|
|
|
|
★ 한 번에 세 가지를 끝낸다: 신원 확정(verified_at) · 채널 등록 · 확정.
|
|
쪼개 놓으면 사장님이 같은 판단을 세 번 하게 된다 — URL 을 붙여넣은 시점에
|
|
"이 가게가 맞다"와 "이 채널이 내 것이다"가 동시에 확인된 것이다.
|
|
|
|
★ 실패는 조용히 넘기지 않는다. URL 이 잘못됐거나 네이버가 막으면 그대로 알려야
|
|
사장님이 다른 주소를 넣는다 — 빈 사이트를 만들어 놓고 나중에 발견하면 늦다.
|
|
"""
|
|
from decimal import Decimal
|
|
|
|
from common.enums import ExternalPlaceSource, LinkChannel, SourceType
|
|
from services.collector.naver_place_adapter import NaverPlaceAdapter
|
|
|
|
res = Res_Place()
|
|
err_type, place = await self._load(user_info, place_id)
|
|
if err_type != ErrorType.SUCCESS:
|
|
res.result.SetResult(err_type)
|
|
return res
|
|
|
|
url = (req.url or "").strip()
|
|
adapter = NaverPlaceAdapter()
|
|
if not url or not adapter.can_handle(url):
|
|
res.result.SetResult(ErrorType.INVALID_REQUEST_DATA)
|
|
res.msg = "네이버 플레이스 주소가 아닙니다."
|
|
return res
|
|
|
|
try:
|
|
naver_id = await adapter._resolve_place_id(url)
|
|
state = await adapter._load_state(naver_id)
|
|
except Exception as ex:
|
|
LOG.w(f"[verify_by_url] 상세를 읽지 못했다: {ex}")
|
|
res.result.SetResult(ErrorType.PLACE_VERIFY_NO_CANDIDATE)
|
|
res.msg = "이 주소에서 가게 정보를 읽지 못했습니다. 주소를 다시 확인해 주세요."
|
|
return res
|
|
|
|
base = state.get(f"PlaceDetailBase:{naver_id}") or next(
|
|
(v for k, v in state.items() if k.startswith("PlaceDetailBase")), None
|
|
)
|
|
if not base or not str(base.get("name") or "").strip():
|
|
res.result.SetResult(ErrorType.PLACE_VERIFY_NO_CANDIDATE)
|
|
res.msg = "이 주소에서 상호를 찾지 못했습니다."
|
|
return res
|
|
|
|
coord = base.get("coordinate") or {}
|
|
verify_req = Req_VerifyPlace(
|
|
source=ExternalPlaceSource.NAVER,
|
|
external_place_id=str(naver_id),
|
|
road_address=base.get("roadAddress") or None,
|
|
address=base.get("address") or None,
|
|
phone=base.get("phone") or base.get("virtualPhone") or None,
|
|
latitude=Decimal(str(coord.get("y"))) if coord.get("y") else None,
|
|
longitude=Decimal(str(coord.get("x"))) if coord.get("x") else None,
|
|
)
|
|
verified = await self.verify_place(user_info, place_id, verify_req)
|
|
if not verified.result.success:
|
|
return verified
|
|
|
|
# 상호도 네이버 표기로 맞춘다 — 사장님이 검색창에 친 이름과 실제 등록 상호가 다를 수 있다.
|
|
official = str(base.get("name")).strip()
|
|
if official and official != place.name:
|
|
await DB_SESSION_MNG.execute_lambda_claim(
|
|
places.DBType(),
|
|
lambda s: self.crud.update_place(
|
|
s, uuid.UUID(user_info.company_id), uuid.UUID(place_id), {"name": official}
|
|
),
|
|
)
|
|
if verified.place:
|
|
verified.place.name = official
|
|
|
|
# 붙여넣은 URL 을 채널로 등록·확정한다. 사장님이 직접 가져온 주소라 추가 확인이 필요 없다.
|
|
canonical = f"https://m.place.naver.com/place/{naver_id}/home"
|
|
await self.create_link(
|
|
user_info, place_id,
|
|
Req_CreateLink(channel=LinkChannel.NAVER_PLACE, url=canonical,
|
|
title=f"{official} 네이버 플레이스", discovered_by=SourceType.OWNER),
|
|
)
|
|
await DB_SESSION_MNG.execute_lambda_claim(
|
|
place_links.DBType(),
|
|
lambda s: self.crud.confirm_link_by_url(
|
|
s, uuid.UUID(place_id), canonical, uuid.UUID(user_info.user_id), GTime.UTC()
|
|
),
|
|
)
|
|
LOG.i(f"[verify_by_url] '{official}' 확정 + 채널 등록 — naver place {naver_id}")
|
|
return verified
|
|
|
|
async def verify_place(self, user_info: UserInfo, place_id: str, req: Req_VerifyPlace) -> Res_Place:
|
|
"""외부 장소 DB(카카오/네이버) 조회 결과를 박제해 동일 업소를 확정한다.
|
|
|
|
★ 이걸 통과해야 수집이 열린다(verified_at).
|
|
|
|
식별 근거가 하나도 없으면 확정하지 않는다 — 외부 고유 id(카카오) 또는 도로명주소(네이버)
|
|
중 하나는 있어야 '이 가게가 그 가게'라고 말할 수 있다."""
|
|
res = Res_Place()
|
|
external_id = req.external_place_id.strip()
|
|
road_address = (req.road_address or "").strip()
|
|
if not external_id and not road_address:
|
|
res.result.SetResult(ErrorType.PLACE_VERIFY_NO_CANDIDATE)
|
|
return res
|
|
|
|
err_type, place = await self._load(user_info, place_id)
|
|
if err_type != ErrorType.SUCCESS:
|
|
res.result.SetResult(err_type)
|
|
return res
|
|
|
|
cid = uuid.UUID(user_info.company_id)
|
|
now = GTime.UTC()
|
|
data = {
|
|
"external_source": req.source.value,
|
|
"external_place_id": external_id or None,
|
|
"road_address": road_address or None,
|
|
"address": req.address,
|
|
"phone": req.phone,
|
|
"latitude": req.latitude,
|
|
"longitude": req.longitude,
|
|
# ★ 지역 코드는 **서버가 유도한다**. 외부 장소 DB(카카오·네이버)는 행정구역 코드를
|
|
# 주지 않으므로 후보에도 없고, 그래서 프론트가 보낼 수가 없다 — 클라이언트가
|
|
# 못 채우는 값을 클라이언트에 맡겨 두면 영원히 NULL 로 남는다(실측: 모든 사업장).
|
|
#
|
|
# region_code 가 비면 지역 정보 캐시를 찾을 키가 없어서
|
|
# 날씨·축제·주변 관광지가 통째로 빈다(local_contents 의 키가 이 값이다).
|
|
# 발행본에는 날씨 섹션이 아무것도 그리지 않고, 하이드레이션 뒤 실시간 조회도
|
|
# 막힌다(use-live-weather 가 regionCode 없이는 fetch 하지 않는다).
|
|
#
|
|
# ★ 지어내지 않는다. 도로명주소에서 '시도 + 시군구' 를 뽑는 것뿐이고,
|
|
# 주소가 없거나 형식이 다르면 None 이다(그때는 지역 정보가 비는 게 맞다).
|
|
# 요청이 값을 실어 보냈으면 그쪽이 이긴다.
|
|
"region_code": req.region_code or region_key(road_address),
|
|
"verified_at": now,
|
|
"verified_by": uuid.UUID(user_info.user_id),
|
|
}
|
|
err_type, rowcount = await DB_SESSION_MNG.execute_lambda_claim(
|
|
places.DBType(),
|
|
lambda s: self.crud.update_place(s, cid, uuid.UUID(place_id), data),
|
|
)
|
|
if err_type != ErrorType.SUCCESS:
|
|
res.result.SetResult(err_type)
|
|
return res
|
|
if rowcount == 0:
|
|
res.result.SetResult(ErrorType.PLACE_NOT_FOUND)
|
|
return res
|
|
|
|
# 외부 장소 DB 가 준 업체 홈페이지를 공식 홈페이지 채널로 등록해 둔다.
|
|
# 실측상 Perplexity 는 이 채널을 잘 못 찾는다 — 검증 단계에서 건지는 게 확실하다.
|
|
# 등록만 하고 확정하지는 않는다(확정은 수집 잡이 어댑터 유무를 보고 판단).
|
|
if (req.place_url or "").strip():
|
|
link = place_links(
|
|
place_id=uuid.UUID(place_id),
|
|
channel=LinkChannel.OFFICIAL_SITE.value,
|
|
url=req.place_url.strip(),
|
|
title=place.name,
|
|
discovered_by=SourceType.API.value,
|
|
discovered_at=now,
|
|
)
|
|
await DB_SESSION_MNG.execute_lambda_run(
|
|
[place_links.DBType()],
|
|
[lambda s: self.crud.add_link(s, link)],
|
|
)
|
|
return await self.get_place(user_info, place_id)
|
|
|
|
# ---- 하위 단위(객실·메뉴·프로그램) ----
|
|
async def list_units(self, user_info: UserInfo, place_id: str) -> Res_UnitList:
|
|
res = Res_UnitList()
|
|
err_type, _place = await self._load(user_info, place_id)
|
|
if err_type != ErrorType.SUCCESS:
|
|
res.result.SetResult(err_type)
|
|
return res
|
|
list_err, rows = await DB_SESSION_MNG.execute_lambda(
|
|
units.DBType(),
|
|
DBWRType.DB_READ.value,
|
|
lambda s: self.crud.list_units(s, uuid.UUID(place_id)),
|
|
)
|
|
if list_err != ErrorType.SUCCESS:
|
|
res.result.SetResult(list_err)
|
|
return res
|
|
res.units = [UnitData.model_validate(r) for r in rows]
|
|
return res
|
|
|
|
async def create_unit(self, user_info: UserInfo, place_id: str, req: Req_CreateUnit) -> Res_Unit:
|
|
res = Res_Unit()
|
|
if not req.name.strip():
|
|
res.result.SetResult(ErrorType.INVALID_REQUEST_DATA)
|
|
return res
|
|
err_type, _place = await self._load(user_info, place_id)
|
|
if err_type != ErrorType.SUCCESS:
|
|
res.result.SetResult(err_type)
|
|
return res
|
|
|
|
unit = units(place_id=uuid.UUID(place_id), name=req.name.strip(), sort_order=req.sort_order)
|
|
run_err = await DB_SESSION_MNG.execute_lambda_run(
|
|
[units.DBType()],
|
|
[lambda s: self.crud.add_unit(s, unit)],
|
|
)
|
|
if run_err != ErrorType.SUCCESS:
|
|
res.result.SetResult(run_err)
|
|
return res
|
|
res.unit = UnitData.model_validate(unit)
|
|
return res
|
|
|
|
# ---- 채널 링크 ----
|
|
async def list_links(self, user_info: UserInfo, place_id: str, confirmed_only: bool = False) -> Res_LinkList:
|
|
res = Res_LinkList()
|
|
err_type, _place = await self._load(user_info, place_id)
|
|
if err_type != ErrorType.SUCCESS:
|
|
res.result.SetResult(err_type)
|
|
return res
|
|
list_err, rows = await DB_SESSION_MNG.execute_lambda(
|
|
place_links.DBType(),
|
|
DBWRType.DB_READ.value,
|
|
lambda s: self.crud.list_links(s, uuid.UUID(place_id), confirmed_only),
|
|
)
|
|
if list_err != ErrorType.SUCCESS:
|
|
res.result.SetResult(list_err)
|
|
return res
|
|
res.links = [LinkData.model_validate(r) for r in rows]
|
|
res.confirmed = sum(1 for r in rows if r.confirmed_at is not None)
|
|
return res
|
|
|
|
async def create_link(self, user_info: UserInfo, place_id: str, req: Req_CreateLink) -> Res_Link:
|
|
"""채널 URL 등록. Perplexity 가 발견한 것도, 사장님이 직접 붙여넣은 것도 여기로 들어온다.
|
|
|
|
★ 확정(confirmed_at)은 별도 액션이다 — 등록만으로 크롤링 대상이 되지 않는다."""
|
|
res = Res_Link()
|
|
if not req.url.strip():
|
|
res.result.SetResult(ErrorType.INVALID_REQUEST_DATA)
|
|
return res
|
|
err_type, _place = await self._load(user_info, place_id)
|
|
if err_type != ErrorType.SUCCESS:
|
|
res.result.SetResult(err_type)
|
|
return res
|
|
|
|
link = place_links(
|
|
place_id=uuid.UUID(place_id),
|
|
channel=req.channel.value,
|
|
url=req.url.strip(),
|
|
title=req.title,
|
|
discovered_by=req.discovered_by.value,
|
|
discovered_at=GTime.UTC(),
|
|
)
|
|
run_err = await DB_SESSION_MNG.execute_lambda_run(
|
|
[place_links.DBType()],
|
|
[lambda s: self.crud.add_link(s, link)],
|
|
)
|
|
if run_err != ErrorType.SUCCESS:
|
|
res.result.SetResult(run_err)
|
|
return res
|
|
res.link = LinkData.model_validate(link)
|
|
return res
|
|
|
|
async def confirm_link(self, user_info: UserInfo, place_id: str, link_id: str) -> Res_Link:
|
|
"""★ 동일 업소로 확인된 URL 만 크롤링 대상이 된다. 사업장 검증이 끝나야 확정할 수 있다."""
|
|
res = Res_Link()
|
|
err_type, place = await self._load(user_info, place_id)
|
|
if err_type != ErrorType.SUCCESS:
|
|
res.result.SetResult(err_type)
|
|
return res
|
|
if place.verified_at is None:
|
|
res.result.SetResult(ErrorType.PLACE_NOT_VERIFIED)
|
|
return res
|
|
|
|
run_err, rowcount = await DB_SESSION_MNG.execute_lambda_claim(
|
|
place_links.DBType(),
|
|
lambda s: self.crud.confirm_link(
|
|
s, uuid.UUID(place_id), uuid.UUID(link_id), uuid.UUID(user_info.user_id), GTime.UTC()
|
|
),
|
|
)
|
|
if run_err != ErrorType.SUCCESS:
|
|
res.result.SetResult(run_err)
|
|
return res
|
|
if rowcount == 0:
|
|
# 없거나 이미 확정됨 — 어느 쪽이든 이 호출로 바뀐 건 없다.
|
|
res.result.SetResult(ErrorType.LINK_NOT_FOUND)
|
|
return res
|
|
|
|
links = await self.list_links(user_info, place_id)
|
|
res.link = next((x for x in links.links if str(x.link_id) == str(link_id)), None)
|
|
return res
|
|
|
|
# ---- 수집 시작 ----
|
|
async def start_collect(self, user_info: UserInfo, place_id: str, req: Req_StartCollect) -> Res_StartCollect:
|
|
"""수집 파이프라인을 큐에 넣고 즉시 응답한다.
|
|
|
|
한 건에 몇 분(Perplexity 10~30s + 크롤링 + Vision 사진 배치)이라 동기로 처리할 수 없다.
|
|
클라이언트는 돌려받은 job_id 로 GET /v1/job/{job_id} 를 폴링한다.
|
|
|
|
★ 진입 게이트는 하나 — 동일 업소 검증(verified_at). 검증 없이 긁으면 남의 가게가 섞인다.
|
|
채널 URL 발견(Perplexity)과 확정은 잡 안에서 순서대로 일어난다:
|
|
Perplexity URL 발견 → 확정 → 확정된 URL 만 크롤링 → fact/사진 후보 적재
|
|
"""
|
|
res = Res_StartCollect()
|
|
err_type, place = await self._load(user_info, place_id)
|
|
if err_type != ErrorType.SUCCESS:
|
|
res.result.SetResult(err_type)
|
|
return res
|
|
|
|
if place.verified_at is None:
|
|
res.result.SetResult(ErrorType.PLACE_NOT_VERIFIED)
|
|
return res
|
|
|
|
# 채널 URL 발견(Perplexity)은 **잡의 첫 단계**다 — 링크가 하나도 없어도 수집을 시작할 수 있다.
|
|
# 여기서는 이미 확정된 링크 수만 세어 응답에 실어준다(진행 상황 표시용).
|
|
link_err, links = await DB_SESSION_MNG.execute_lambda(
|
|
place_links.DBType(),
|
|
DBWRType.DB_READ.value,
|
|
lambda s: self.crud.list_links(s, uuid.UUID(place_id), True),
|
|
)
|
|
if link_err != ErrorType.SUCCESS:
|
|
res.result.SetResult(link_err)
|
|
return res
|
|
|
|
wanted = {str(x) for x in req.link_ids}
|
|
targets = [x for x in links if not wanted or str(x.link_id) in wanted]
|
|
res.confirmed_links = len(targets)
|
|
|
|
# link_ids 를 콕 집었는데 그중 확정된 게 없으면 시작할 이유가 없다(재크롤 요청 경로).
|
|
if wanted and not targets:
|
|
res.result.SetResult(ErrorType.LINK_NOT_CONFIRMED)
|
|
return res
|
|
|
|
payload = {
|
|
"place_id": place_id,
|
|
"company_id": user_info.company_id,
|
|
"category": place.category,
|
|
# 명시적으로 고른 링크가 있을 때만 대상을 제한한다. 기본 요청에서 현재
|
|
# 확정 링크를 복사하면, 잡의 discover 단계가 새로 확정한 네이버 링크가
|
|
# wanted 필터에서 빠져 사진·정보 수집이 0건으로 끝난다.
|
|
"link_ids": [str(x) for x in req.link_ids],
|
|
"force": req.force,
|
|
# 유료 검색은 요청자가 선택한 한 회차에만 실행한다. 이후 확정 링크 크롤링이나
|
|
# 재수집이 이 값을 암묵적으로 물려받으면 같은 URL 을 찾는 데 계속 과금된다.
|
|
"discover_channels": req.discover_channels,
|
|
"requested_by": user_info.user_id,
|
|
}
|
|
# 사업장당 활성 수집 잡 1건 — 버튼을 두 번 눌러도 두 번 돌지 않는다.
|
|
job_id, created = await enqueue_job(
|
|
self.queue, JobType.COLLECT, payload, dedupe_key=f"collect:{place_id}"
|
|
)
|
|
if job_id is None:
|
|
res.result.SetResult(ErrorType.COLLECT_ALREADY_RUNNING)
|
|
return res
|
|
|
|
res.job_id = uuid.UUID(job_id)
|
|
res.status = JobStatus.PENDING
|
|
res.created = created
|
|
|
|
# 수집 진행 중임을 사업장 상태에 반영(관리 화면 배지). 실패해도 잡은 이미 들어갔다.
|
|
if created and place.status == PlaceStatus.DRAFT.value:
|
|
await DB_SESSION_MNG.execute_lambda_claim(
|
|
places.DBType(),
|
|
lambda s: self.crud.update_place(
|
|
s, uuid.UUID(user_info.company_id), uuid.UUID(place_id),
|
|
{"status": PlaceStatus.COLLECTING.value},
|
|
),
|
|
)
|
|
return res
|
|
|
|
# ---- 사진 분석 시작 ----
|
|
async def start_vision(self, user_info: UserInfo, place_id: str, req: Req_StartVision) -> Res_StartVision:
|
|
"""Gemini Vision 사진 분석을 큐에 넣고 즉시 응답한다.
|
|
|
|
수집이 사진을 저장하면 자동으로 걸리지만, 사장님이 사진을 직접 올린 뒤 다시 돌리거나
|
|
force 로 재분석할 때 이 엔드포인트를 쓴다."""
|
|
from sqlalchemy import func, select
|
|
|
|
from common.database.model.models import media
|
|
from services.external import gemini
|
|
|
|
res = Res_StartVision()
|
|
err_type, _place = await self._load(user_info, place_id)
|
|
if err_type != ErrorType.SUCCESS:
|
|
res.result.SetResult(err_type)
|
|
return res
|
|
|
|
if not gemini.is_configured():
|
|
res.result.SetResult(ErrorType.GENERATOR_NOT_CONFIGURED)
|
|
return res
|
|
|
|
conds = [media.place_id == uuid.UUID(place_id), media.deleted == False] # noqa: E712
|
|
if not req.force:
|
|
# ★ 미분석 기준은 alt_text 다 — label 은 수집 어댑터가 페이지 캡션으로 채운다.
|
|
# label 로 세면 캡션 있는 사진이 전부 '분석됨'으로 빠져 pending 0 이 된다
|
|
# (crud/media_crud.list_media 의 같은 주석 참고).
|
|
from sqlalchemy import func as sa_func
|
|
from sqlalchemy import or_ as sa_or
|
|
conds.append(sa_or(media.alt_text.is_(None), sa_func.btrim(media.alt_text) == ""))
|
|
cnt_err, rows = await DB_SESSION_MNG.execute_lambda(
|
|
media.DBType(),
|
|
DBWRType.DB_READ.value,
|
|
lambda s: DB_SESSION_MNG.execute(s, select(func.count()).select_from(media).where(*conds)),
|
|
)
|
|
res.pending_media = int(rows[0] or 0) if cnt_err == ErrorType.SUCCESS and rows else 0
|
|
if res.pending_media == 0:
|
|
res.result.SetResult(ErrorType.MEDIA_NOT_FOUND)
|
|
return res
|
|
|
|
job_id, created = await enqueue_job(
|
|
self.queue, JobType.VISION,
|
|
{"place_id": place_id, "company_id": user_info.company_id, "force": req.force},
|
|
dedupe_key=f"vision:{place_id}",
|
|
)
|
|
if job_id is None:
|
|
res.result.SetResult(ErrorType.COLLECT_ALREADY_RUNNING)
|
|
return res
|
|
res.job_id = uuid.UUID(job_id)
|
|
res.status = JobStatus.PENDING
|
|
res.created = created
|
|
return res
|
|
|
|
# ---- 동일 업소 후보 조회 (UI 가 사람에게 고르게 한다) ----
|
|
async def find_candidates(self, user_info: UserInfo, place_id: str, query: str | None = None) -> Res_VerifyCandidates:
|
|
"""외부 장소 DB 에서 이 상호명의 후보를 찾아 그대로 내려준다.
|
|
|
|
★ 서버가 자동으로 확정하지 않는다. outcome 이 MATCHED 여도 후보 전체를 돌려줘
|
|
UI 가 사람에게 보여주고 고르게 한다 — 남의 가게를 붙이는 게 이 서비스에서 제일 비싼 실수다.
|
|
자동 판정은 'UI 가 한 번만 물어봐도 되는가'(auto_selectable)를 알려주는 힌트일 뿐이다.
|
|
"""
|
|
from common.enums import ExternalPlaceSource
|
|
from services.external import kakao as kakao_client
|
|
from services.external import naver as naver_client
|
|
|
|
res = Res_VerifyCandidates()
|
|
err_type, place = await self._load(user_info, place_id)
|
|
if err_type != ErrorType.SUCCESS:
|
|
res.result.SetResult(err_type)
|
|
return res
|
|
|
|
# ★ 검색어와 판정용 상호명은 다른 값이다.
|
|
# 화면은 '상호명 + 위치'를 합쳐 query 로 보낸다(후보를 좁히려고). 그런데 판정
|
|
# (pick_match)은 후보 상호명과 **정확일치**를 보므로, 지역이 붙은 문자열을 그대로
|
|
# 넘기면 정확일치가 영영 성립하지 않는다 — 실측(2026-08-28) 10건 전부
|
|
# AMBIGUOUS(name_no_exact) 였고, 후보가 1건뿐인 경우까지 그랬다.
|
|
# 상호명은 places.name 이 들고 있다(위저드가 검색 직전에 상호만 PATCH 한다).
|
|
search_query = (query or place.name or "").strip()
|
|
name = (place.name or "").strip() or search_query
|
|
if not search_query:
|
|
res.result.SetResult(ErrorType.INVALID_REQUEST_DATA)
|
|
return res
|
|
|
|
# 카카오 키가 있으면 카카오(전화번호·고유 id 가 있어 판정이 강하다), 없으면 네이버.
|
|
kakao = kakao_client.KakaoLocalClient()
|
|
try:
|
|
if kakao.enabled:
|
|
res.source = ExternalPlaceSource.KAKAO
|
|
match = await kakao.verify_place(name, search_query=search_query)
|
|
await kakao.aclose()
|
|
else:
|
|
client = naver_client.NaverLocalClient()
|
|
if not client.enabled:
|
|
res.result.SetResult(ErrorType.LOCAL_NOT_CONFIGURED)
|
|
return res
|
|
res.source = ExternalPlaceSource.NAVER
|
|
match = await client.verify_place(
|
|
name, address_hint=place.road_address, search_query=search_query
|
|
)
|
|
await client.aclose()
|
|
except (kakao_client.KakaoNotConfigured, naver_client.NaverNotConfigured):
|
|
res.result.SetResult(ErrorType.LOCAL_NOT_CONFIGURED)
|
|
return res
|
|
except (kakao_client.KakaoRequestFailed, naver_client.NaverRequestFailed) as ex:
|
|
LOG.w(f"[verify] 후보 조회 실패 place={place_id}: {type(ex).__name__}: {ex}")
|
|
res.result.SetResult(ErrorType.LOCAL_FETCH_FAILED)
|
|
return res
|
|
|
|
res.outcome = match.outcome.value if hasattr(match.outcome, "value") else str(match.outcome)
|
|
res.reason = match.reason
|
|
res.auto_selectable = bool(match.is_matched)
|
|
|
|
# MATCHED 여도 후보를 전부 내려보낸다 — 사람이 다른 걸 고를 수 있어야 한다.
|
|
rows = match.candidates or ([match.place] if match.place else [])
|
|
# 지역검색 API는 네이버 Place ID를 주지 않는다. 후보를 보여주기 전에 모바일 통합검색에서
|
|
# 상호가 정확히 일치하는 ID를 한 번 찾아, 화면이 "지역 후보 발견"과 "플레이스 발견"을
|
|
# 구분할 수 있게 한다. 실패는 정상적인 fallback이므로 후보 조회 자체는 실패시키지 않는다.
|
|
from services.external import naver_place_lookup
|
|
|
|
try:
|
|
# ★ 여기는 **넓은 검색어**를 쓴다. 통합검색은 한 번만 부르고(5번 부르면 429) 그
|
|
# 한 페이지 안에서 후보들의 id 를 찾는 구조라, 지역이 붙어 결과가 그 동네로
|
|
# 좁혀질수록 찾을 확률이 올라간다. 판정(pick_match)과는 요구가 정반대다.
|
|
naver_ids = await naver_place_lookup.find_place_ids(search_query, [c.name for c in rows])
|
|
except Exception as ex: # noqa: BLE001 — 지도 URL 직접 입력으로 이어진다
|
|
LOG.w(f"[verify] 네이버 플레이스 자동 발견 실패(후보는 유지): {type(ex).__name__}: {ex}")
|
|
naver_ids = {}
|
|
res.candidates = [
|
|
PlaceCandidate(
|
|
external_place_id=getattr(c, "kakao_place_id", None) or getattr(c, "naver_place_id", None),
|
|
name=c.name,
|
|
road_address=c.road_address,
|
|
address=c.address,
|
|
phone=c.phone,
|
|
latitude=c.latitude,
|
|
longitude=c.longitude,
|
|
category_name=c.category_name,
|
|
place_url=c.place_url,
|
|
naver_place_url=(
|
|
naver_place_lookup.place_url(naver_ids[c.name]) if c.name in naver_ids else None
|
|
),
|
|
)
|
|
for c in rows
|
|
]
|
|
if not res.candidates:
|
|
res.result.SetResult(ErrorType.PLACE_VERIFY_NO_CANDIDATE)
|
|
return res
|
|
|
|
# ---- 소개문·FAQ 생성 시작 ----
|
|
async def start_copy(self, user_info: UserInfo, place_id: str, req: Req_StartCopy) -> Res_StartCopy:
|
|
"""소개문·FAQ 생성을 큐에 넣는다.
|
|
|
|
★ 근거로 쓸 확인된 fact 가 없으면 잡을 만들지 않는다 —
|
|
근거 없이 문장을 쓰면 그게 환각이고, 유료 호출만 낭비된다."""
|
|
from common.database.model.models import facts as facts_model
|
|
from crud.fact_crud import FactCRUD
|
|
from services.external import gemini_text
|
|
|
|
res = Res_StartCopy()
|
|
err_type, _place = await self._load(user_info, place_id)
|
|
if err_type != ErrorType.SUCCESS:
|
|
res.result.SetResult(err_type)
|
|
return res
|
|
|
|
if not gemini_text.is_configured():
|
|
res.result.SetResult(ErrorType.GENERATOR_NOT_CONFIGURED)
|
|
return res
|
|
|
|
crud = FactCRUD()
|
|
f_err, rows = await DB_SESSION_MNG.execute_lambda(
|
|
facts_model.DBType(),
|
|
DBWRType.DB_READ.value,
|
|
lambda s: crud.list_facts(s, uuid.UUID(place_id), None, None, True, True),
|
|
)
|
|
if f_err != ErrorType.SUCCESS:
|
|
res.result.SetResult(f_err)
|
|
return res
|
|
res.grounded_facts = sum(1 for r in rows if r.unit_id is None and (r.value or "").strip())
|
|
if res.grounded_facts == 0:
|
|
res.result.SetResult(ErrorType.FAQ_UNGROUNDED)
|
|
return res
|
|
|
|
job_id, created = await enqueue_job(
|
|
self.queue, JobType.COPY,
|
|
{"place_id": place_id, "company_id": user_info.company_id, "requested_by": user_info.user_id},
|
|
dedupe_key=f"copy:{place_id}",
|
|
)
|
|
if job_id is None:
|
|
res.result.SetResult(ErrorType.COLLECT_ALREADY_RUNNING)
|
|
return res
|
|
res.job_id = uuid.UUID(job_id)
|
|
res.status = JobStatus.PENDING
|
|
res.created = created
|
|
return res
|