[feat] solution/backend: 승인 알림을 카톡으로도 발송하고 웹훅이 메시지를 그린다 (Event API 2-1)

결정(2026-09-29): 카톡과 메일 둘 다, 승인은 링크가 아니라 연결된 계정 신원으로.
이 커밋은 발송과 메시지 그리기까지고 [승인] 버튼은 다음 단계(2-2)다.

- blog_jobs._send_one: 메일에 더해 Event API 로 보낸다. 하나라도 나가면 SENT,
  아무 데도 안 나가면 SENT 로 표시하지 않아 다음 스윕이 다시 시도한다. 카톡은 채널
  친구가 아니거나 차단했으면 실패하므로 메일을 빼지 않는다. send_now 도 같은 경로
- 카톡 params 로 post_id 와 수정용 일회용 코드(edit_token)를 넘긴다. 코드 평문은
  발송 시점에만 알아서다. 로그에는 params 의 키만 남기고 값은 남기지 않는다
- channel.approval_notice: 발화자 키 → 사장님 → 그 글이 그 사장님 가게 것·미처리·
  기한 전일 때만 본문과 [수정하기] 를 준다. 연결 안 됨·남의 글·처리됨·만료·이상한
  ID 는 구분 없이 같은 안내(구분해 주면 글 ID 를 탐색할 수 있다)
- kakao_bot: userRequest.params.post_id 가 있으면 승인 알림 요청으로 처리하고 링크
  버튼은 본문과 따로 textCard 로 그린다(카드 설명 길이 제한을 피한다)
- KAKAO_APPROVAL_PUSH_ENABLED(기본 0), KAKAO_APPROVAL_EVENT_NAME 추가 —
  오픈빌더 이벤트 블록(스킬 연결)과 배포가 끝나기 전에는 켜지 않는다

test_blog_owner 6건·test_kakao_webhook 6건 추가, 카카오·미니블로그 스위트 119 passed,
인접 스위트 110 passed. 실제 카톡 수신은 콘솔 설정·운영 배포 뒤에 확인한다.
This commit is contained in:
skkim committed 2026-09-29 16:13:07 +09:00
1 parent 983c05b3c3
commit f1b473968d
10 files changed
+519 -27

No files matched your search

+83 -19
View File
@@ -11,15 +11,17 @@
import uuid
from datetime import date, datetime, timedelta, timezone
import httpx
from sqlalchemy import select
from config import social_config
from config import agent_config, social_config
from common.database.db_session_manager import DB_SESSION_MNG
from common.database.model.models import place_posts, places, sites, users
from common.enums import DBWRType, PostStatus, SiteStatus
from common.logger import LOG
from crud.post_crud import PostCRUD
from services import blog_service, mail_service, site_payload
from services import blog_service, kakao_link_service, mail_service, site_payload
from services.external import kakao_event
from services.snapshot import build_snapshot
BATCH_SIZE = 30
@@ -225,29 +227,90 @@ def _app_origin() -> str:
return blog_service.app_origin()
def _kakao_push_ready() -> bool:
"""카톡 승인 알림을 보낼 수 있는 환경인가. DB 를 안 본다 — 스윕 맨 앞에서 싸게 거른다."""
return agent_config.approval_push_enabled() and kakao_event.is_configured()
async def _kakao_target(user) -> str | None:
"""이 사장님에게 카톡으로 보낼 수 있으면 발화자 키, 아니면 None(스위치 꺼짐·미연결·끊김)."""
if not _kakao_push_ready():
return None
return await kakao_link_service.linked_key(user.user_id)
def _can_mail(place, user) -> bool:
return mail_service.is_configured() and mail_service.is_valid_address(_notify_address(place, user) or "")
async def _push_kakao(channel_user_key: str, post, edit_token: str) -> bool:
"""승인 알림을 카톡으로. 실패해도 예외를 올리지 않는다 — 친구가 아니거나 차단했으면
실패하는 게 정상 경로라, 호출부가 메일로 대신할 수 있어야 한다.
★ 글 본문·수정 링크는 여기서 만들지 않는다. 오픈빌더 이벤트 블록의 스킬(우리 웹훅)이
params 의 글 ID 로 **연결된 본인 글인지 다시 확인한 뒤** 그린다. 수정 링크용 일회용
코드는 평문을 지금밖에 모르므로 params 로 넘긴다(메일과 같은 코드다)."""
try:
async with httpx.AsyncClient(timeout=10.0) as client:
await kakao_event.send(
channel_user_key,
agent_config.get("KAKAO_APPROVAL_EVENT_NAME", "post_approval"),
params={"post_id": str(post.post_id), "edit_token": edit_token},
client=client,
)
return True
except kakao_event.KakaoEventError as ex:
LOG.w(f"[blog] post={post.post_id} 카톡 승인 알림 실패: {ex}")
except httpx.HTTPError as ex:
LOG.w(f"[blog] post={post.post_id} 카톡 승인 알림 실패: {type(ex).__name__}")
return False
async def _send_one(place, user, post) -> bool:
"""토큰 발급 → 메일 본문 조립 → 발송 → 성공하면 SENT 로 표시. 실패하면 DB 를 안 건드린다."""
"""토큰 발급 → 메일·카톡 발송 → 하나라도 나갔으면 SENT 로 표시. 아무 데도 안 나갔으면
DB 를 안 건드린다(다시 시도할 길을 막지 않는다).
★ 카톡과 메일은 **둘 다** 보낸다(2026-09-29 결정). 카톡은 채널 친구가 아니거나 차단했으면
실패하므로, 카톡이 붙어도 메일을 빼지 않는다."""
token, token_hash, expires = blog_service.issue_token()
# ★ 수정 링크도 일회용 코드다. 예전에는 여기 빌더 액세스 토큰을 통짜로 실었고,
# 메일 전달 한 번이 자정까지의 권한 양도였다(migrations/0023).
edit_token, edit_hash, _edit_expires = blog_service.issue_token()
body = _mail_body(
place_name=place.name, post=post, user=user,
origin=_app_origin(), approve_token=token, edit_token=edit_token,
)
ok = mail_service.send(to=_notify_address(place, user), subject=f"[{place.name}] 이번 글 올릴까요?", text=body)
if not ok:
return False
await DB_SESSION_MNG.execute_lambda_run(
[place_posts.DBType()],
[lambda s, pid=post.post_id, h=token_hash, e=expires, eh=edit_hash: _crud.mark_sent(s, pid, h, e, eh)],
)
return True
mail_ok = False
if _can_mail(place, user):
body = _mail_body(
place_name=place.name, post=post, user=user,
origin=_app_origin(), approve_token=token, edit_token=edit_token,
)
mail_ok = mail_service.send(to=_notify_address(place, user), subject=f"[{place.name}] 이번 글 올릴까요?", text=body)
async def mark_sent():
await DB_SESSION_MNG.execute_lambda_run(
[place_posts.DBType()],
[lambda s, pid=post.post_id, h=token_hash, e=expires, eh=edit_hash: _crud.mark_sent(s, pid, h, e, eh)],
)
# ★ 메일이 나갔으면 카톡보다 **먼저** SENT 로 표시한다. 이벤트가 나가자마자 웹훅이 이 글을
# 읽는데, 그때 수정 코드 해시가 저장돼 있으면 [수정하기] 가 바로 먹는다. 카톡만 나가는
# 경우는 발송이 성공해야 표시할 수 있어 그 뒤에 한다 — 사장님이 버튼을 누르기까지의
# 시간이 그 간격보다 훨씬 길다(웹훅은 REVIEWED 글도 읽는다).
if mail_ok:
await mark_sent()
kakao_key = await _kakao_target(user)
if kakao_key is None:
return mail_ok
kakao_ok = await _push_kakao(kakao_key, post, edit_token)
if kakao_ok and not mail_ok:
await mark_sent()
return mail_ok or kakao_ok
async def send_reviewed() -> int:
"""검수를 통과한 글을 사장님에게 한 통씩 보낸다. 보낸 수를 돌려준다."""
if not mail_service.is_configured():
if not mail_service.is_configured() and not _kakao_push_ready():
return 0
_err, rows = await DB_SESSION_MNG.execute_lambda(
@@ -264,7 +327,8 @@ async def send_reviewed() -> int:
if not target:
continue
place, user = target
if not mail_service.is_valid_address(_notify_address(place, user) or ""):
# 메일도 카톡도 보낼 수 없는 사장님은 건너뛴다. 하나라도 되면 _send_one 이 갈래를 정한다.
if not _can_mail(place, user) and await _kakao_target(user) is None:
continue
if await _send_one(place, user, post):
sent += 1
@@ -275,7 +339,7 @@ async def send_now_for_place(place_id: str) -> dict:
"""사장님이 빌더 화면에서 누르는 즉시 발송 — 아침 9시 스윕을 기다리지 않고 이 업장의
오늘 몫을 지금 보낸다(2026-09-21, 사장님 요청: "지금 바로 발송할 수 있도록").
'하루 한 통' 원칙은 그대로다 — 이미 오늘 보냈으면(REVIEWED 가 아니면) 보낼 게 없다."""
if not mail_service.is_configured():
if not mail_service.is_configured() and not _kakao_push_ready():
return {"sent": False, "reason": "MAIL_NOT_CONFIGURED"}
place = user = None
@@ -293,7 +357,7 @@ async def send_now_for_place(place_id: str) -> dict:
if post is None:
return {"sent": False, "reason": "NOTHING_DUE"}
if not mail_service.is_valid_address(_notify_address(place, user) or ""):
if not _can_mail(place, user) and await _kakao_target(user) is None:
return {"sent": False, "reason": "NO_VALID_EMAIL"}
if not await _send_one(place, user, post):