Merge branch 'main' into feat-tourApi
This commit is contained in:
commit
3b43446fe6
131 files changed
+4624
-1558
No files matched your search
@@ -4,13 +4,12 @@ import uuid
|
||||
from fastapi import Depends
|
||||
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.database.model.models import companies, users
|
||||
from common.enums import AuthProvider, CompanyStatus, DBWRType, ErrorType, UserRole, UserStatus
|
||||
from common.database.model.models import users
|
||||
from common.enums import AuthProvider, DBWRType, ErrorType, UserRole, UserStatus
|
||||
from common.logger import LOG
|
||||
from common.models.gmodel import UserInfo
|
||||
from crud.user_crud import IUserCRUD, UserCRUD
|
||||
from router.v1.auth.protocol import (
|
||||
CompanyData,
|
||||
Req_GoogleLogin,
|
||||
Req_Signup,
|
||||
Req_UpdateMe,
|
||||
@@ -71,11 +70,11 @@ class AuthService:
|
||||
|
||||
@staticmethod
|
||||
def _user_info(user: users) -> UserInfo:
|
||||
# uuid → str (JWT json 직렬화 위해). 기능 라우터는 company_id 로 스코프한다.
|
||||
# uuid → str (JWT json 직렬화 위해). 기능 라우터는 user_id 로 스코프한다
|
||||
# — 사업장이 places.owner_user_id 로 이 값에 매여 있다.
|
||||
return UserInfo(
|
||||
user_id=str(user.user_id),
|
||||
id=user.id,
|
||||
company_id=str(user.company_id),
|
||||
role=user.role,
|
||||
)
|
||||
|
||||
@@ -140,26 +139,17 @@ class AuthService:
|
||||
password_hash: str | None,
|
||||
name: str | None,
|
||||
email: str | None,
|
||||
company_name: str,
|
||||
provider: AuthProvider,
|
||||
provider_uid: str | None,
|
||||
) -> tuple[ErrorType, users]:
|
||||
"""회사 1개 + 그 회사의 첫 계정 1개를 한 트랜잭션으로 만든다.
|
||||
"""계정 1개를 만든다.
|
||||
|
||||
★ 가입은 곧 새 테넌트다. users.company_id 가 NOT NULL 이고 모든 도메인(사업장·사이트)이
|
||||
company_id 로 스코프되므로, 회사 없는 계정은 아무것도 만들지 못한다.
|
||||
★ uuid 를 여기서 미리 만든다. 모델 default 는 flush 시점에 적용돼서, 그 전에
|
||||
company.company_id 를 읽으면 None 이다 — 그대로 넣으면 NOT NULL 위반이다."""
|
||||
company_uuid = uuid.uuid4()
|
||||
company = companies(
|
||||
company_id=company_uuid,
|
||||
name=_fit(company_name, 100),
|
||||
email=_fit(email, 255),
|
||||
status=CompanyStatus.ACTIVE.value,
|
||||
)
|
||||
★ 예전엔 가입 한 번이 **회사(테넌트) 하나**를 같이 만들었고 모든 도메인이 그 회사로
|
||||
스코프됐다. 쓰는 사람은 사장님 혼자인데 자기 회사에 소속된 직원이 되는 구조라
|
||||
걷어냈다(2026-09-08) — 이제 사업장이 `places.owner_user_id` 로 이 계정에 직접 매인다.
|
||||
★ uuid 를 여기서 미리 만든다. 모델 default 는 flush 시점에 적용돼서 그 전에 읽으면 None 이다."""
|
||||
user = users(
|
||||
user_id=uuid.uuid4(),
|
||||
company_id=company_uuid,
|
||||
id=login_id,
|
||||
password=password_hash,
|
||||
name=_fit(name, 50),
|
||||
@@ -171,10 +161,7 @@ class AuthService:
|
||||
)
|
||||
err_type = await DB_SESSION_MNG.execute_lambda_run(
|
||||
[users.DBType()],
|
||||
[
|
||||
lambda s: self.user_crud.add_company(s, company),
|
||||
lambda s: self.user_crud.add_user(s, user),
|
||||
],
|
||||
[lambda s: self.user_crud.add_user(s, user)],
|
||||
)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
return err_type, None
|
||||
@@ -226,7 +213,6 @@ class AuthService:
|
||||
password_hash=await GetHashedPW(req.password),
|
||||
name=name,
|
||||
email=email,
|
||||
company_name=(req.company_name or "").strip() or name or login_id,
|
||||
provider=AuthProvider.LOCAL,
|
||||
provider_uid=None,
|
||||
)
|
||||
@@ -268,13 +254,12 @@ class AuthService:
|
||||
res.result.SetResult(ErrorType.ACCOUNT_PROVIDER_CONFLICT)
|
||||
return res
|
||||
|
||||
# 3) 첫 방문 — 계정과 회사를 만든다.
|
||||
# 3) 첫 방문 — 계정을 만든다.
|
||||
err_type, user = await self._create_account(
|
||||
login_id=_google_login_id(account.sub),
|
||||
password_hash=None,
|
||||
name=account.name or None,
|
||||
email=account.email or None,
|
||||
company_name=account.name or account.email or _google_login_id(account.sub),
|
||||
provider=AuthProvider.GOOGLE,
|
||||
provider_uid=account.sub,
|
||||
)
|
||||
@@ -299,16 +284,6 @@ class AuthService:
|
||||
return res
|
||||
user: users
|
||||
|
||||
# 2) 소속사 조회 (없어도 치명적 아님)
|
||||
company = None
|
||||
c_err, company_row = await DB_SESSION_MNG.execute_lambda(
|
||||
users.DBType(),
|
||||
DBWRType.DB_READ.value,
|
||||
lambda s: self.user_crud.get_company(s, user.company_id),
|
||||
)
|
||||
if c_err == ErrorType.SUCCESS and company_row is not None:
|
||||
company = CompanyData(company_id=str(company_row.company_id), name=company_row.name)
|
||||
|
||||
res.user_id = str(user.user_id)
|
||||
res.id = user.id
|
||||
res.name = user.name
|
||||
@@ -316,7 +291,6 @@ class AuthService:
|
||||
res.contact_number = user.contact_number
|
||||
res.role = UserRole(user.role)
|
||||
res.provider = AuthProvider(user.provider)
|
||||
res.company = company
|
||||
return res
|
||||
|
||||
async def update_me(self, user_info: UserInfo, req: Req_UpdateMe) -> Res_Me:
|
||||
|
||||
@@ -98,18 +98,18 @@ async def _log(site_id, version_id, action: PublishAction, result: PublishResult
|
||||
|
||||
|
||||
async def run_build(job: dict) -> dict:
|
||||
"""BUILD 잡 핸들러. payload: {place_id, company_id, publish?, requested_by?}
|
||||
"""BUILD 잡 핸들러. payload: {place_id, owner_user_id, publish?, requested_by?}
|
||||
|
||||
publish=True 면 게이트를 통과했을 때 바로 발행까지 한다."""
|
||||
payload = job["payload"]
|
||||
place_id = payload["place_id"]
|
||||
company_id = payload["company_id"]
|
||||
owner_user_id = payload["owner_user_id"]
|
||||
want_publish = bool(payload.get("publish"))
|
||||
|
||||
err, place = await DB_SESSION_MNG.execute_lambda(
|
||||
places.DBType(),
|
||||
DBWRType.DB_READ.value,
|
||||
lambda s: _place_crud.get_place(s, uuid.UUID(company_id), uuid.UUID(place_id)),
|
||||
lambda s: _place_crud.get_place(s, uuid.UUID(owner_user_id), uuid.UUID(place_id)),
|
||||
)
|
||||
if err != ErrorType.SUCCESS or place is None:
|
||||
raise BuildAborted(f"사업장을 찾을 수 없다: {place_id}")
|
||||
@@ -258,7 +258,7 @@ async def run_build(job: dict) -> dict:
|
||||
result["azure"] = azure_result
|
||||
# ★ 페이지가 실제로 올라간 뒤에 썸네일을 남긴다 — 없는 페이지의 그림을 쇼케이스에 걸지 않는다.
|
||||
# 실패해도 발행은 성공이다(스크린샷이 아니라 대표 사진이라, 없으면 글자 카드로 떨어진다).
|
||||
thumbnail_url = await site_thumbnail.store(slug, snapshot)
|
||||
thumbnail_url = await site_thumbnail.store(slug, snapshot, version_no)
|
||||
if thumbnail_url:
|
||||
result["thumbnail_url"] = thumbnail_url
|
||||
# ★ 정적 파일이 올라간 **뒤에** 통보한다. 먼저 알리면 크롤러가 옛 파일을 가져간다.
|
||||
@@ -305,7 +305,7 @@ async def run_build(job: dict) -> dict:
|
||||
await DB_SESSION_MNG.execute_lambda_claim(
|
||||
places.DBType(),
|
||||
lambda s: _place_crud.update_place(
|
||||
s, uuid.UUID(company_id), uuid.UUID(place_id), {"status": PlaceStatus.PUBLISHED.value}
|
||||
s, uuid.UUID(owner_user_id), uuid.UUID(place_id), {"status": PlaceStatus.PUBLISHED.value}
|
||||
),
|
||||
)
|
||||
await _log(site.site_id, version.site_version_id, PublishAction.PUBLISH, PublishResult.SUCCESS, None,
|
||||
|
||||
@@ -431,12 +431,12 @@ async def run_collect(job: dict) -> dict:
|
||||
"""COLLECT 잡 핸들러. 반환값이 jobs.result 에 저장돼 폴링·감사에 쓰인다."""
|
||||
payload = job["payload"]
|
||||
place_id = payload["place_id"]
|
||||
company_id = payload["company_id"]
|
||||
owner_user_id = payload["owner_user_id"]
|
||||
|
||||
err, place = await DB_SESSION_MNG.execute_lambda(
|
||||
places.DBType(),
|
||||
DBWRType.DB_READ.value,
|
||||
lambda s: _place_crud.get_place(s, uuid.UUID(company_id), uuid.UUID(place_id)),
|
||||
lambda s: _place_crud.get_place(s, uuid.UUID(owner_user_id), uuid.UUID(place_id)),
|
||||
)
|
||||
if err != ErrorType.SUCCESS or place is None:
|
||||
raise CollectAborted(f"사업장을 찾을 수 없다: {place_id}")
|
||||
@@ -464,7 +464,7 @@ async def run_collect(job: dict) -> dict:
|
||||
|
||||
if not targets:
|
||||
result["note"] = "크롤링 대상이 없다(어댑터가 처리할 수 있는 확정 URL 0건)"
|
||||
await _finish(place_id, company_id, PlaceStatus.REVIEW)
|
||||
await _finish(place_id, owner_user_id, PlaceStatus.REVIEW)
|
||||
return result
|
||||
|
||||
# ★ 이미 충분하면 크롤링 자체를 건너뛴다(force 가 아닐 때).
|
||||
@@ -472,16 +472,19 @@ async def run_collect(job: dict) -> dict:
|
||||
if before["enough"] and not payload.get("force"):
|
||||
result["coverage"] = before
|
||||
result["note"] = "이미 필수 항목이 다 차 있다 — 크롤링 생략(force=true 로 강제 가능)"
|
||||
await _finish(place_id, company_id, PlaceStatus.REVIEW)
|
||||
await _finish(place_id, owner_user_id, PlaceStatus.REVIEW)
|
||||
LOG.i(f"[collect] 충분함 place={place_id} {before['covered']}/{before['total']} — 크롤링 생략")
|
||||
return result
|
||||
|
||||
from common.models.gmodel import UserInfo
|
||||
|
||||
actor = UserInfo(
|
||||
user_id=payload.get("requested_by") or str(place.verified_by or uuid.uuid4()),
|
||||
# ★ 잡이 쓰는 신원. user_id 는 **사업장 주인**이어야 한다 — FactService 가 이 값으로
|
||||
# 사업장을 스코프하고(fact_service._load_place) verified_by 에도 그대로 박는다.
|
||||
# 회사를 걷어내기 전에는 스코프가 company_id 였고 여기엔 요청자·검증자·랜덤 uuid 가
|
||||
# 순서대로 들어갔다. 그 랜덤 uuid 가 이제는 "남의 사업장" 이 되어 조회가 0건이 된다.
|
||||
user_id=owner_user_id,
|
||||
id="collector",
|
||||
company_id=company_id,
|
||||
role=1,
|
||||
)
|
||||
|
||||
@@ -538,24 +541,24 @@ async def run_collect(job: dict) -> dict:
|
||||
# 사진이 들어왔으면 분석을 이어서 건다 — 수집과 분석은 각각 몇 분이라 한 잡에 묶지 않는다.
|
||||
# (묶으면 분석에서 죽었을 때 수집까지 다시 하게 되고, 유료 API 를 두 번 태운다.)
|
||||
if result["media"]["stored"] > 0:
|
||||
result["vision_job_id"] = await _enqueue_vision(place_id, company_id)
|
||||
result["vision_job_id"] = await _enqueue_vision(place_id, owner_user_id)
|
||||
|
||||
await _finish(place_id, company_id, PlaceStatus.REVIEW)
|
||||
await _finish(place_id, owner_user_id, PlaceStatus.REVIEW)
|
||||
LOG.i(f"[collect] 완료 place={place_id} fact {result['facts']['stored']}건 · 사진 {result['media']['stored']}장")
|
||||
return result
|
||||
|
||||
|
||||
async def _finish(place_id: str, company_id: str, status: PlaceStatus):
|
||||
async def _finish(place_id: str, owner_user_id: str, status: PlaceStatus):
|
||||
"""수집이 끝나면 사업장을 검수 대기로 돌린다 — 수집값은 전부 후보라 사람이 봐야 한다."""
|
||||
await DB_SESSION_MNG.execute_lambda_claim(
|
||||
places.DBType(),
|
||||
lambda s: _place_crud.update_place(
|
||||
s, uuid.UUID(company_id), uuid.UUID(place_id), {"status": status.value}
|
||||
s, uuid.UUID(owner_user_id), uuid.UUID(place_id), {"status": status.value}
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
async def _enqueue_vision(place_id: str, company_id: str) -> str | None:
|
||||
async def _enqueue_vision(place_id: str, owner_user_id: str) -> str | None:
|
||||
"""사진 분석 잡을 적재한다. 키가 없거나 중복이면 조용히 건너뛴다(수집 자체는 성공이다)."""
|
||||
from common.enums import JobType
|
||||
from crud.job_crud import JobQueue
|
||||
@@ -567,7 +570,7 @@ async def _enqueue_vision(place_id: str, company_id: str) -> str | None:
|
||||
return None
|
||||
job_id, _created = await enqueue_job(
|
||||
JobQueue(), JobType.VISION,
|
||||
{"place_id": place_id, "company_id": company_id},
|
||||
{"place_id": place_id, "owner_user_id": owner_user_id},
|
||||
dedupe_key=f"vision:{place_id}",
|
||||
)
|
||||
return job_id
|
||||
@@ -40,10 +40,10 @@ class CopyAborted(RuntimeError):
|
||||
|
||||
|
||||
async def run_copy(job: dict) -> dict:
|
||||
"""COPY 잡 핸들러. payload: {place_id, company_id, requested_by?}"""
|
||||
"""COPY 잡 핸들러. payload: {place_id, owner_user_id, requested_by?}"""
|
||||
payload = job["payload"]
|
||||
place_id = payload["place_id"]
|
||||
company_id = payload["company_id"]
|
||||
owner_user_id = payload["owner_user_id"]
|
||||
|
||||
if not gemini_text.is_configured():
|
||||
raise CopyAborted("GEMINI_API_KEY 미설정 — 소개문·FAQ 를 생성할 수 없다")
|
||||
@@ -51,7 +51,7 @@ async def run_copy(job: dict) -> dict:
|
||||
err, place = await DB_SESSION_MNG.execute_lambda(
|
||||
places.DBType(),
|
||||
DBWRType.DB_READ.value,
|
||||
lambda s: _place_crud.get_place(s, uuid.UUID(company_id), uuid.UUID(place_id)),
|
||||
lambda s: _place_crud.get_place(s, uuid.UUID(owner_user_id), uuid.UUID(place_id)),
|
||||
)
|
||||
if err != ErrorType.SUCCESS or place is None:
|
||||
raise CopyAborted(f"사업장을 찾을 수 없다: {place_id}")
|
||||
@@ -165,9 +165,12 @@ async def run_copy(job: dict) -> dict:
|
||||
}
|
||||
|
||||
actor = UserInfo(
|
||||
user_id=payload.get("requested_by") or str(place.verified_by or uuid.uuid4()),
|
||||
# ★ 잡이 쓰는 신원. user_id 는 **사업장 주인**이어야 한다 — FactService 가 이 값으로
|
||||
# 사업장을 스코프하고(fact_service._load_place) verified_by 에도 그대로 박는다.
|
||||
# 회사를 걷어내기 전에는 스코프가 company_id 였고 여기엔 요청자·검증자·랜덤 uuid 가
|
||||
# 순서대로 들어갔다. 그 랜덤 uuid 가 이제는 "남의 사업장" 이 되어 조회가 0건이 된다.
|
||||
user_id=owner_user_id,
|
||||
id="generator",
|
||||
company_id=company_id,
|
||||
role=1,
|
||||
)
|
||||
service = FactService(_fact_crud, _place_crud)
|
||||
|
||||
@@ -73,7 +73,7 @@ class FactService:
|
||||
err_type, place = await DB_SESSION_MNG.execute_lambda(
|
||||
places.DBType(),
|
||||
DBWRType.DB_READ.value,
|
||||
lambda s: self.place_crud.get_place(s, uuid.UUID(user_info.company_id), uuid.UUID(place_id)),
|
||||
lambda s: self.place_crud.get_place(s, uuid.UUID(user_info.user_id), uuid.UUID(place_id)),
|
||||
)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
return ErrorType.PLACE_NOT_FOUND, None
|
||||
|
||||
@@ -38,14 +38,14 @@ class FaqService:
|
||||
self.crud = crud
|
||||
self.place_crud = place_crud
|
||||
|
||||
# ---- 사업장 로드(회사 스코프) ----
|
||||
# ---- 사업장 로드(사장님 스코프) ----
|
||||
async def _load_place(self, user_info: UserInfo, place_id: str):
|
||||
"""company_id 를 WHERE 에 걸어 조회한다 — 남의 회사 place_id 를 넣으면 PLACE_NOT_FOUND.
|
||||
"""owner_user_id 를 WHERE 에 걸어 조회한다 — 남의 place_id 를 넣으면 PLACE_NOT_FOUND.
|
||||
'없다'와 '권한 없다'를 구분해 주지 않는 것도 의도다(존재 여부를 흘리지 않는다)."""
|
||||
err_type, place = await DB_SESSION_MNG.execute_lambda(
|
||||
places.DBType(),
|
||||
DBWRType.DB_READ.value,
|
||||
lambda s: self.place_crud.get_place(s, uuid.UUID(user_info.company_id), uuid.UUID(place_id)),
|
||||
lambda s: self.place_crud.get_place(s, uuid.UUID(user_info.user_id), uuid.UUID(place_id)),
|
||||
)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
return ErrorType.PLACE_NOT_FOUND, None
|
||||
|
||||
@@ -41,7 +41,7 @@ class MediaService:
|
||||
err_type, place = await DB_SESSION_MNG.execute_lambda(
|
||||
places.DBType(),
|
||||
DBWRType.DB_READ.value,
|
||||
lambda s: self.place_crud.get_place(s, uuid.UUID(user_info.company_id), uuid.UUID(place_id)),
|
||||
lambda s: self.place_crud.get_place(s, uuid.UUID(user_info.user_id), uuid.UUID(place_id)),
|
||||
)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
return ErrorType.PLACE_NOT_FOUND, None
|
||||
|
||||
@@ -70,12 +70,12 @@ class PlaceService:
|
||||
# ---- 조회 ----
|
||||
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)
|
||||
uid = uuid.UUID(user_info.user_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,
|
||||
s, uid, search,
|
||||
category.value if isinstance(category, PlaceCategory) else category,
|
||||
status.value if isinstance(status, PlaceStatus) else status,
|
||||
pg.skip, pg.size,
|
||||
@@ -102,7 +102,7 @@ class PlaceService:
|
||||
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)),
|
||||
lambda s: self.crud.get_place(s, uuid.UUID(user_info.user_id), uuid.UUID(place_id)),
|
||||
)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
return ErrorType.PLACE_NOT_FOUND, None
|
||||
@@ -122,8 +122,11 @@ class PlaceService:
|
||||
return res
|
||||
|
||||
place = places(
|
||||
company_id=uuid.UUID(user_info.company_id),
|
||||
owner_user_id=req.owner_user_id,
|
||||
# ★ 주인은 **토큰이 정한다.** 예전엔 요청 body 의 owner_user_id 를 그대로 넣었는데,
|
||||
# 그 값은 아무도 안 보내서 92건 전부 NULL 이었고 스코프는 회사가 대신 하고 있었다.
|
||||
# 회사를 걷어내면서 이 컬럼이 스코프 키가 됐다 — body 로 남의 계정을 적을 수 있으면
|
||||
# 만들자마자 남의 목록에 들어간다.
|
||||
owner_user_id=uuid.UUID(user_info.user_id),
|
||||
name=req.name.strip(),
|
||||
category=req.category.value,
|
||||
status=PlaceStatus.DRAFT.value,
|
||||
@@ -149,7 +152,7 @@ class PlaceService:
|
||||
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),
|
||||
lambda s: self.crud.update_place(s, uuid.UUID(user_info.user_id), uuid.UUID(place_id), data),
|
||||
)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
res.result.SetResult(err_type)
|
||||
@@ -164,7 +167,7 @@ class PlaceService:
|
||||
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)
|
||||
s, uuid.UUID(user_info.user_id), uuid.UUID(place_id)
|
||||
),
|
||||
)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
@@ -253,7 +256,7 @@ class PlaceService:
|
||||
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}
|
||||
s, uuid.UUID(user_info.user_id), uuid.UUID(place_id), {"name": official}
|
||||
),
|
||||
)
|
||||
if verified.place:
|
||||
@@ -294,7 +297,7 @@ class PlaceService:
|
||||
res.result.SetResult(err_type)
|
||||
return res
|
||||
|
||||
cid = uuid.UUID(user_info.company_id)
|
||||
uid = uuid.UUID(user_info.user_id)
|
||||
now = GTime.UTC()
|
||||
data = {
|
||||
"external_source": req.source.value,
|
||||
@@ -325,7 +328,7 @@ class PlaceService:
|
||||
data["external_category"] = req.category_name.strip()[:200]
|
||||
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),
|
||||
lambda s: self.crud.update_place(s, uid, uuid.UUID(place_id), data),
|
||||
)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
res.result.SetResult(err_type)
|
||||
@@ -513,7 +516,7 @@ class PlaceService:
|
||||
|
||||
payload = {
|
||||
"place_id": place_id,
|
||||
"company_id": user_info.company_id,
|
||||
"owner_user_id": user_info.user_id,
|
||||
"category": place.category,
|
||||
# 명시적으로 고른 링크가 있을 때만 대상을 제한한다. 기본 요청에서 현재
|
||||
# 확정 링크를 복사하면, 잡의 discover 단계가 새로 확정한 네이버 링크가
|
||||
@@ -542,7 +545,7 @@ class PlaceService:
|
||||
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),
|
||||
s, uuid.UUID(user_info.user_id), uuid.UUID(place_id),
|
||||
{"status": PlaceStatus.COLLECTING.value},
|
||||
),
|
||||
)
|
||||
@@ -589,7 +592,7 @@ class PlaceService:
|
||||
|
||||
job_id, created = await enqueue_job(
|
||||
self.queue, JobType.VISION,
|
||||
{"place_id": place_id, "company_id": user_info.company_id, "force": req.force},
|
||||
{"place_id": place_id, "owner_user_id": user_info.user_id, "force": req.force},
|
||||
dedupe_key=f"vision:{place_id}",
|
||||
)
|
||||
if job_id is None:
|
||||
@@ -849,7 +852,7 @@ class PlaceService:
|
||||
|
||||
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},
|
||||
{"place_id": place_id, "owner_user_id": user_info.user_id, "requested_by": user_info.user_id},
|
||||
dedupe_key=f"copy:{place_id}",
|
||||
)
|
||||
if job_id is None:
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
고르는 자리를 한 곳으로 모았다. 사이트 한 곳을 여는 것과 발행 업소 명단을 통째로
|
||||
긁는 것은 다른 일이라, 페이지에 이미 적혀 있는 것만 나간다.
|
||||
|
||||
나가지 않는 것: place_id · company_id · site_id · 전화번호 · 상세 주소 · 좌표.
|
||||
나가지 않는 것: place_id · 소유자 · site_id · 전화번호 · 상세 주소 · 좌표.
|
||||
"""
|
||||
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
|
||||
@@ -104,7 +104,7 @@ class SiteService:
|
||||
err_type, place = await DB_SESSION_MNG.execute_lambda(
|
||||
places.DBType(),
|
||||
DBWRType.DB_READ.value,
|
||||
lambda s: self.place_crud.get_place(s, uuid.UUID(user_info.company_id), uuid.UUID(place_id)),
|
||||
lambda s: self.place_crud.get_place(s, uuid.UUID(user_info.user_id), uuid.UUID(place_id)),
|
||||
)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
return ErrorType.PLACE_NOT_FOUND, None
|
||||
@@ -420,16 +420,16 @@ class SiteService:
|
||||
return cleaned
|
||||
|
||||
async def list_my_sites(self, user_info: UserInfo, pg: PageParams) -> Res_MySites:
|
||||
"""로그인한 계정(회사)이 가진 사이트 전부.
|
||||
"""로그인한 사장님이 가진 사이트 전부.
|
||||
|
||||
사업장 목록(/v1/place/list)과 따로 두는 이유: 화면이 알아야 하는 건 '사업장이 있다'가 아니라
|
||||
'발행돼 있나 · 주소가 뭔가 · 다시 구워야 하나'다."""
|
||||
res = Res_MySites(page=pg.page, size=pg.size)
|
||||
cid = uuid.UUID(user_info.company_id)
|
||||
uid = uuid.UUID(user_info.user_id)
|
||||
err_type, rows, total = await DB_SESSION_MNG.execute_lambda(
|
||||
places.DBType(),
|
||||
DBWRType.DB_READ.value,
|
||||
lambda s: self.crud.list_company_sites(s, cid, pg.skip, pg.size),
|
||||
lambda s: self.crud.list_owner_sites(s, uid, pg.skip, pg.size),
|
||||
)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
res.result.SetResult(err_type)
|
||||
@@ -454,6 +454,7 @@ class SiteService:
|
||||
domain=getattr(site, "domain", None),
|
||||
template_id=getattr(site, "template_id", None),
|
||||
published_at=getattr(site, "published_at", None),
|
||||
thumbnail_url=getattr(site, "thumbnail_url", None),
|
||||
needs_rebuild=bool(site is not None and changed and (built_at is None or changed > built_at)),
|
||||
)
|
||||
|
||||
@@ -526,7 +527,7 @@ class SiteService:
|
||||
job_id, created = await enqueue_job(
|
||||
self.queue, JobType.BUILD,
|
||||
{
|
||||
"place_id": place_id, "company_id": user_info.company_id,
|
||||
"place_id": place_id, "owner_user_id": user_info.user_id,
|
||||
"publish": req.publish, "requested_by": user_info.user_id,
|
||||
},
|
||||
dedupe_key=f"build:{place_id}",
|
||||
|
||||
@@ -18,7 +18,7 @@ import asyncio
|
||||
import os
|
||||
|
||||
import httpx
|
||||
from azure.storage.blob import BlobServiceClient, ContentSettings
|
||||
from azure.storage.blob import BlobClient, BlobServiceClient, ContentSettings
|
||||
|
||||
from common.logger import LOG
|
||||
from services import azure_static, site_payload
|
||||
@@ -46,19 +46,71 @@ MAX_BYTES = 5 * 1024 * 1024
|
||||
CACHE_CONTROL = "public, max-age=60, must-revalidate"
|
||||
|
||||
|
||||
# ── 썸네일 전용 저장소 ────────────────────────────────────────────────────────
|
||||
# ★ 왜 스위치를 따로 두나
|
||||
# 원래는 `AZURE_STORAGE_CONNECTION_STRING` 하나가 사이트 업로드(azure_static)와 썸네일을
|
||||
# **같이** 켰다. 그런데 그 둘은 필요한 저장소가 다르다 — 사이트는 정적 호스팅(`$web`)이고
|
||||
# 썸네일은 그냥 이미지 버킷이면 된다. 하나로 묶어 두면 "썸네일 좀 보자" 고 키를 꽂는 순간
|
||||
# **발행할 때마다 사이트 전체가 그 버킷에 업로드된다.** 지금 우리가 빌려 쓰는 곳은
|
||||
# negodata·infinith 와 공용인 미디어 컨테이너라 그렇게 되면 안 된다.
|
||||
#
|
||||
# ★ 값 출처: o2o-negosium/negodata/backend/config/config.local.toml `[StorageConfig]`.
|
||||
# 같은 계정/컨테이너를 root 디렉터리로만 가른다(negodata/ · infinith/ · web4ai/) —
|
||||
# 그쪽 관례를 그대로 따른 것이지 우리 계정이 아니다.
|
||||
#
|
||||
# ⚠️ **임시다.** 이 컨테이너는 정적 사이트 호스팅이 아니라 발행본을 못 올린다. 그리고 SAS 가
|
||||
# 컨테이너 전체에 racwdl(삭제 포함)이라, 남의 프로젝트 파일에 닿을 수 있는 자리다 —
|
||||
# web4ai 전용 스토리지 계정이 생기면 이 블록을 걷고 azure_static 쪽으로 되돌린다.
|
||||
_BASE_ENV = "THUMBNAIL_BLOB_BASE_URL" # https://<계정>.blob.core.windows.net/<컨테이너>
|
||||
_SAS_ENV = "THUMBNAIL_BLOB_SAS_TOKEN" # `?sv=...` (앞의 물음표는 있어도 없어도 된다)
|
||||
_ROOT_ENV = "THUMBNAIL_BLOB_ROOT" # 컨테이너 안에서 우리가 쓰는 디렉터리. 예: web4ai
|
||||
|
||||
|
||||
def _blob_base() -> str:
|
||||
return os.environ.get(_BASE_ENV, "").strip().rstrip("/")
|
||||
|
||||
|
||||
def _blob_sas() -> str:
|
||||
return os.environ.get(_SAS_ENV, "").strip().lstrip("?")
|
||||
|
||||
|
||||
def _blob_root() -> str:
|
||||
return os.environ.get(_ROOT_ENV, "").strip().strip("/")
|
||||
|
||||
|
||||
def uses_blob_store() -> bool:
|
||||
"""썸네일 전용 저장소를 쓰는가. 아니면 예전대로 azure_static 설정을 따른다."""
|
||||
return bool(_blob_base() and _blob_sas())
|
||||
|
||||
|
||||
def is_configured() -> bool:
|
||||
return azure_static.is_configured()
|
||||
return uses_blob_store() or azure_static.is_configured()
|
||||
|
||||
|
||||
def blob_name(slug: str, ext: str) -> str:
|
||||
if uses_blob_store():
|
||||
# base_url 에 컨테이너까지 들어 있다 — 여기서는 컨테이너 안쪽 경로만 만든다.
|
||||
return "/".join(part for part in (_blob_root(), THUMB_DIR, f"{slug}.{ext}") if part)
|
||||
prefix = os.environ.get("AZURE_STORAGE_PREFIX", azure_static.DEFAULT_PREFIX).strip().strip("/")
|
||||
return "/".join(part for part in (prefix, THUMB_DIR, f"{slug}.{ext}") if part)
|
||||
|
||||
|
||||
def public_url(slug: str, ext: str) -> str:
|
||||
def public_url(slug: str, ext: str, version: int | None = None) -> str:
|
||||
"""공개 주소. 발행 사이트와 같은 오리진이다 — 접두사는 오리진 경로로 흡수된다
|
||||
(CLAUDE.md 'AZURE_STORAGE_PREFIX 와 루트 절대경로는 충돌한다')."""
|
||||
return f"{site_payload.publish_origin()}/{THUMB_DIR}/{slug}.{ext}"
|
||||
(CLAUDE.md 'AZURE_STORAGE_PREFIX 와 루트 절대경로는 충돌한다').
|
||||
|
||||
★ `?v=<버전>` 은 캐시 무효화다. 블롭 이름은 발행마다 그대로고 내용만 덮어쓰므로
|
||||
(overwrite=True), 주소가 안 변하면 브라우저·CDN 이 **옛 그림을 계속 보여준다.**
|
||||
아래 CACHE_CONTROL(60초)만으로는 부족하다 — 그 60초 동안 사장님은 방금 바꾼 사진이
|
||||
아니라 지난 발행의 사진을 본다. 버전을 붙이면 발행 즉시 새 주소가 된다.
|
||||
★ 이름에 버전을 넣지 않는 이유: 사이트당 블롭이 발행 횟수만큼 쌓이고, 지우는 코드가 없다.
|
||||
★ version 이 None 이면 붙이지 않는다 — 옛 발행분을 사후에 채우는 경로
|
||||
(scripts/backfill_thumbnails.py)에는 그 시점의 버전이 없다."""
|
||||
# ★ 저장소가 발행 오리진 밖이면 주소도 그쪽이다. 여기서 publish_origin 을 쓰면
|
||||
# 그림은 블롭에 올라가 있는데 카드는 우리 사이트 주소를 가리켜 전부 404 다.
|
||||
base = f"{_blob_base()}/{blob_name(slug, ext)}" if uses_blob_store() \
|
||||
else f"{site_payload.publish_origin()}/{THUMB_DIR}/{slug}.{ext}"
|
||||
return f"{base}?v={version}" if version is not None else base
|
||||
|
||||
|
||||
async def _fetch(url: str) -> tuple[bytes, str, str] | None:
|
||||
@@ -109,6 +161,18 @@ async def _fetch(url: str) -> tuple[bytes, str, str] | None:
|
||||
|
||||
|
||||
def _upload_sync(slug: str, data: bytes, content_type: str, ext: str) -> str:
|
||||
name = blob_name(slug, ext)
|
||||
settings = ContentSettings(content_type=content_type, cache_control=CACHE_CONTROL)
|
||||
|
||||
if uses_blob_store():
|
||||
# ★ SAS 는 연결 문자열이 아니다 — from_connection_string 이 못 받는다.
|
||||
# 블롭 주소에 토큰을 붙여 그 한 파일에만 붙는다(컨테이너 클라이언트를 만들지 않는다:
|
||||
# 남의 디렉터리를 훑을 수 있는 핸들을 굳이 들고 있지 않는다).
|
||||
BlobClient.from_blob_url(f"{_blob_base()}/{name}?{_blob_sas()}").upload_blob(
|
||||
data, overwrite=True, content_settings=settings
|
||||
)
|
||||
return name
|
||||
|
||||
connection_string = os.environ["AZURE_STORAGE_CONNECTION_STRING"].strip()
|
||||
container_name = (
|
||||
os.environ.get("AZURE_STORAGE_CONTAINER", azure_static.DEFAULT_CONTAINER).strip()
|
||||
@@ -116,18 +180,12 @@ def _upload_sync(slug: str, data: bytes, content_type: str, ext: str) -> str:
|
||||
)
|
||||
service = BlobServiceClient.from_connection_string(connection_string)
|
||||
container = service.get_container_client(container_name)
|
||||
name = blob_name(slug, ext)
|
||||
container.upload_blob(
|
||||
name=name,
|
||||
data=data,
|
||||
overwrite=True,
|
||||
# cache_control 은 ContentSettings 에 담아야 블롭 속성으로 실제로 박힌다.
|
||||
content_settings=ContentSettings(content_type=content_type, cache_control=CACHE_CONTROL),
|
||||
)
|
||||
# cache_control 은 ContentSettings 에 담아야 블롭 속성으로 실제로 박힌다.
|
||||
container.upload_blob(name=name, data=data, overwrite=True, content_settings=settings)
|
||||
return name
|
||||
|
||||
|
||||
async def store(slug: str, snapshot: dict) -> str | None:
|
||||
async def store(slug: str, snapshot: dict, version: int | None = None) -> str | None:
|
||||
"""대표 사진을 썸네일로 올리고 공개 URL 을 돌려준다. 못 하면 None(발행은 그대로 간다).
|
||||
|
||||
SDK 의 동기 I/O 는 별도 스레드에서 돈다 — azure_static.publish 와 같은 이유로,
|
||||
@@ -153,4 +211,4 @@ async def store(slug: str, snapshot: dict) -> str | None:
|
||||
return None
|
||||
|
||||
LOG.i(f"[thumbnail] {slug} → {name} ({len(data)} bytes · {content_type})")
|
||||
return public_url(slug, ext)
|
||||
return public_url(slug, ext, version)
|
||||
@@ -28,10 +28,10 @@ class VisionAborted(RuntimeError):
|
||||
|
||||
|
||||
async def run_vision(job: dict) -> dict:
|
||||
"""VISION 잡 핸들러. payload: {place_id, company_id, force?}"""
|
||||
"""VISION 잡 핸들러. payload: {place_id, owner_user_id, force?}"""
|
||||
payload = job["payload"]
|
||||
place_id = payload["place_id"]
|
||||
company_id = payload["company_id"]
|
||||
owner_user_id = payload["owner_user_id"]
|
||||
force = bool(payload.get("force"))
|
||||
|
||||
if not gemini.is_configured():
|
||||
@@ -40,7 +40,7 @@ async def run_vision(job: dict) -> dict:
|
||||
err, place = await DB_SESSION_MNG.execute_lambda(
|
||||
places.DBType(),
|
||||
DBWRType.DB_READ.value,
|
||||
lambda s: _place_crud.get_place(s, uuid.UUID(company_id), uuid.UUID(place_id)),
|
||||
lambda s: _place_crud.get_place(s, uuid.UUID(owner_user_id), uuid.UUID(place_id)),
|
||||
)
|
||||
if err != ErrorType.SUCCESS or place is None:
|
||||
raise VisionAborted(f"사업장을 찾을 수 없다: {place_id}")
|
||||
|
||||
Reference in new issue
Block a user