merge: origin/main(카톡 승인 알림 Event API) 을 fix/agent-multi-action 에 병합
충돌은 tests/test_kakao_webhook.py 하나 — 양쪽이 파일 끝에 서로 다른 테스트를 붙였다. 둘 다 살렸다(여러 가게·확인 경로 테스트 → 승인 알림 테스트 순). channel.py 는 자동 병합 — 저쪽은 approval_notice·approve_post 추가와 _say 선택 인자 확장이라 이쪽의 _pick_place·확인 경로 변경과 겹치지 않는다. 전체 994 passed / 47 failed — 실패 목록은 병합 전과 동일(gemini·openai 키 미설정, search_console, weather_notes) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
273efb717f
14 files changed
+1163
-29
No files matched your search
@@ -14,13 +14,14 @@
|
||||
import re
|
||||
import uuid
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from urllib.parse import quote
|
||||
|
||||
from sqlalchemy import select
|
||||
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.database.model.models import owner_kakao_links as Link
|
||||
from common.database.model.models import users
|
||||
from common.enums import DBWRType, ErrorType, KakaoLinkStatus
|
||||
from common.database.model.models import place_posts, places, users
|
||||
from common.enums import DBWRType, ErrorType, KakaoLinkStatus, PostStatus
|
||||
from common.models.gmodel import UserInfo
|
||||
from crud.place_crud import PlaceCRUD
|
||||
from crud.site_crud import SiteCRUD
|
||||
@@ -28,8 +29,9 @@ from crud.job_crud import JobQueue
|
||||
from common.enums import SiteStatus
|
||||
from common.models.gmodel import PageParams
|
||||
from services.site_service import SiteService
|
||||
from services import kakao_link_service as link_service
|
||||
from services import blog_service, kakao_link_service as link_service
|
||||
from services.agent import runtime
|
||||
from services.post_service import PostService
|
||||
from services.agent.tools import REGISTRY
|
||||
from services.kakao_link_service import KakaoLinkError
|
||||
|
||||
@@ -60,9 +62,14 @@ def _now():
|
||||
return datetime.now(timezone.utc)
|
||||
|
||||
|
||||
def _say(text: str, quick: list[str] | None = None) -> dict:
|
||||
"""채널이 모르는 모양으로 답한다 — 문구와 바로가기 목록뿐이다."""
|
||||
return {"text": text, "quick_replies": quick or []}
|
||||
def _say(text: str, quick: list[str] | None = None, links: list[dict] | None = None,
|
||||
approve_post_id: str | None = None, hint: str | None = None) -> dict:
|
||||
"""채널이 모르는 모양으로 답한다 — 문구, 바로가기 목록, 링크 버튼({label, url}),
|
||||
승인 버튼을 달 글 ID, 버튼 위에 붙는 한 줄 안내뿐이다. 버튼을 어떻게 그릴지는 채널 몫이다."""
|
||||
return {
|
||||
"text": text, "quick_replies": quick or [], "links": links or [],
|
||||
"approve_post_id": approve_post_id, "hint": hint,
|
||||
}
|
||||
|
||||
|
||||
async def _user_info(user_id) -> UserInfo | None:
|
||||
@@ -313,6 +320,117 @@ async def handle(utterance: str, channel_user_key: str) -> dict:
|
||||
return _say(result["reply"], quick)
|
||||
|
||||
|
||||
# 승인 알림에서 보여줄 수 있는 글 = 아직 사이트에 안 올린 글. 메일 승인 링크와 같은 범위다
|
||||
# (검수 통과 REVIEWED · 메일/카톡이 나간 SENT).
|
||||
_APPROVABLE = (PostStatus.REVIEWED.value, PostStatus.SENT.value)
|
||||
|
||||
|
||||
async def _owned_pending_post(user_id, post_id: str):
|
||||
"""(글, 가게 이름) — **이 사장님 가게의**, 아직 안 올린, 기한이 안 지난 글일 때만. 아니면 None.
|
||||
|
||||
★ 글 ID 는 카카오가 이벤트 params 로 실어 온 값이지만 믿지 않는다. 발화자 키 → user_id 로
|
||||
찾은 사장님이 그 글이 달린 가게의 주인인지를 여기서 다시 본다 — 글 ID 만 알면 남의 글이
|
||||
보이는 구멍이 되면 안 된다(없는 글과 남의 글을 같은 답으로 돌려준다)."""
|
||||
try:
|
||||
pid = uuid.UUID(str(post_id))
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
async def run(s):
|
||||
row = (
|
||||
await s.execute(
|
||||
select(place_posts, places.name)
|
||||
.join(places, places.place_id == place_posts.place_id)
|
||||
.where(
|
||||
place_posts.post_id == pid,
|
||||
place_posts.deleted.is_(False),
|
||||
place_posts.status.in_(_APPROVABLE),
|
||||
places.owner_user_id == user_id,
|
||||
places.deleted.is_(False),
|
||||
)
|
||||
)
|
||||
).first()
|
||||
return ErrorType.SUCCESS, row
|
||||
|
||||
_err, row = await DB_SESSION_MNG.execute_lambda(place_posts.DBType(), DBWRType.DB_READ.value, run)
|
||||
if row is None:
|
||||
return None
|
||||
post, name = row
|
||||
expires = post.token_expires_at
|
||||
if expires is not None:
|
||||
# 메일 링크와 같은 만료(그날 자정 KST). DB 값이 tz 없이 오면 UTC 로 본다.
|
||||
if expires.tzinfo is None:
|
||||
expires = expires.replace(tzinfo=timezone.utc)
|
||||
if expires < _now():
|
||||
return None
|
||||
return post, name
|
||||
|
||||
|
||||
async def approval_notice(channel_user_key: str, post_id: str, edit_token: str | None = None) -> dict:
|
||||
"""Event API 로 시작된 승인 알림을 그린다 — 글 문구와 [수정하기] 링크.
|
||||
|
||||
★ 연결된 본인의 글이 아니면 본문을 한 글자도 주지 않는다. 연결 안 된 발화자·남의 글·
|
||||
이미 처리한 글·기한 지난 글은 구분하지 않고 같은 안내로 답한다(구분해 주면 글 ID 를
|
||||
탐색할 수 있다). 예외를 던지지 않는 것은 handle() 과 같은 규약이다."""
|
||||
row = await _link_row(channel_user_key)
|
||||
if row is None:
|
||||
return _say("연결된 계정을 찾지 못했어요. 관리자 화면에서 다시 연결해 주세요.")
|
||||
|
||||
found = await _owned_pending_post(row.user_id, post_id)
|
||||
if found is None:
|
||||
return _say("이미 처리했거나 기한이 지난 글이에요.")
|
||||
|
||||
post, name = found
|
||||
links = []
|
||||
if edit_token:
|
||||
# 메일의 '고쳐서 올리려면' 과 같은 일회용 코드다 — 어느 쪽이든 먼저 누른 쪽이 쓴다.
|
||||
links = [{"label": "수정하기", "url": f"{blog_service.app_origin()}/v1/site/post/edit?t={quote(edit_token, safe='')}"}]
|
||||
# 승인 버튼은 글 ID 만 실어 돌려주고, 그리는 건 채널 몫이다(블록 ID 같은 카카오 값이 여기 없다).
|
||||
return _say(
|
||||
f"[{name}] 이번 글을 올릴까요?\n\n{post.body}",
|
||||
links=links,
|
||||
approve_post_id=str(post.post_id),
|
||||
hint="고쳐서 올리려면 아래 버튼을 눌러 주세요.", # 승인 버튼이 붙으면 채널이 문구를 바꾼다
|
||||
)
|
||||
|
||||
|
||||
async def approve_post(channel_user_key: str, post_id: str) -> dict:
|
||||
"""카톡 [승인] 버튼 — 연결된 본인의 글일 때만 올린다.
|
||||
|
||||
★ 버튼이 들고 온 post_id 를 믿지 않는다. 발화자 키 → 사장님으로 찾은 뒤 그 글이 그
|
||||
사장님 가게의 미처리·기한 전 글인지를 다시 본다(approval_notice 와 같은 관문).
|
||||
틀리면 아무것도 승인하지 않고, 어느 쪽이 틀렸는지 구분하지 않고 같은 안내로 답한다.
|
||||
★ 승인 자체는 메일 링크·빌더 '바로 발행' 과 같은 PostService.approve_by_owner 다 —
|
||||
재발행 잡과 쓰레드 공유까지 세 경로가 똑같이 탄다. 이미 올린 글을 또 누르면 위 관문에서
|
||||
걸려 두 번 올라가지 않는다. 예외를 던지지 않는 것은 handle() 과 같은 규약이다."""
|
||||
row = await _link_row(channel_user_key)
|
||||
if row is None:
|
||||
return _say("연결된 계정을 찾지 못했어요. 관리자 화면에서 다시 연결해 주세요.")
|
||||
|
||||
found = await _owned_pending_post(row.user_id, post_id)
|
||||
if found is None:
|
||||
return _say("이미 처리했거나 기한이 지난 글이에요.")
|
||||
|
||||
user = await _user_info(row.user_id)
|
||||
if user is None:
|
||||
return _say("계정을 찾지 못했어요. 관리자 화면에서 다시 연결해 주세요.")
|
||||
|
||||
post, name = found
|
||||
service = PostService()
|
||||
result = await service.approve_by_owner(user, str(post.place_id), str(post.post_id))
|
||||
if not result.result.success:
|
||||
return _say("지금은 올리지 못했어요. 잠시 뒤 다시 눌러 주세요.")
|
||||
|
||||
# 재발행은 몇 분 걸린다 — 메일 승인 확인 화면과 같이, 어디로 가면 보이는지를 바로 알려준다.
|
||||
url = await service.blog_url(post.place_id)
|
||||
links = [{"label": "사이트 보기", "url": url}] if url else []
|
||||
return _say(
|
||||
f"[{name}] 올렸습니다.\n사이트에 반영되기까지 몇 분 걸려요.",
|
||||
links=links,
|
||||
hint="반영되면 아래 버튼으로 확인해 보세요.",
|
||||
)
|
||||
|
||||
|
||||
_ERRORS = {
|
||||
"PLACE_NOT_FOUND": "그 가게를 찾지 못했어요.",
|
||||
"AGENT_NOT_CONFIGURED": "지금은 대화 기능이 꺼져 있어요.",
|
||||
|
||||
Reference in new issue
Block a user