[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

@@ -371,3 +371,108 @@ async def test_콜백_전송이_실패해도_터지지_않는다(monkeypatch):
monkeypatch.setattr(bot.httpx, "AsyncClient", lambda **_kw: Boom())
await bot._push("https://callback.example/x", "안녕", "누구") # 예외가 새 나오지 않는다
# ── 승인 알림(Event API 로 시작된 스킬 요청) ─────────────────────────────
# ★ 이 자리가 지키는 것: 글 본문은 **연결된 본인의 글일 때만** 나간다. 이벤트 요청의
# params 는 카카오가 채우지만, 발화자 키로 사장님을 찾고 그 글이 그 사장님 가게 것인지
# 서버가 다시 본다 — 글 ID 만 알면 남의 글이 보이는 구멍이 되면 안 된다.
POST_BODY = "비가 그친 뒤 마당 돌이 촉촉합니다. 대청마루에 앉아 빗소리를 들어 보세요."
def event_body(post_id, edit_token="EDITCODE1234", speaker="kakao-speaker-1"):
payload = body("", speaker)
payload["userRequest"]["params"] = {"post_id": str(post_id)}
if edit_token:
payload["userRequest"]["params"]["edit_token"] = edit_token
return payload
async def seed_post(db_engine, place_id, status=3, expires=None):
"""status 3 = SENT. expires 는 tz 를 단 UTC 로 넣는다(raw text() 로 timestamptz 를 바인딩할 때의 함정)."""
post_id = uuid.uuid4()
async with db_engine.begin() as c:
await c.execute(
text("INSERT INTO place_posts (post_id, place_id, body, topic_kind, topic_key, status, token_expires_at) "
"VALUES (:id, :pid, :body, 1, :key, :st, :exp)"),
{"id": post_id, "pid": uuid.UUID(str(place_id)), "body": POST_BODY,
"key": f"weather:{post_id.hex[:6]}", "st": status, "exp": expires},
)
return post_id
def outputs(res):
return res.json()["template"]["outputs"]
async def test_승인_알림은_본인_글이면_본문과_수정_링크를_그린다(client, auth_headers, db_engine):
h, pid, uid = await link(db_engine, client, auth_headers, "승인-발화자", "알림숙소")
post_id = await seed_post(db_engine, pid)
res = await client.post(PATH, headers={"X-Agent-Secret": SECRET}, json=event_body(post_id, speaker="승인-발화자"))
assert res.status_code == 200
first = outputs(res)[0]["simpleText"]["text"]
assert "알림숙소" in first and POST_BODY in first
button = outputs(res)[1]["textCard"]["buttons"][0]
assert button["label"] == "수정하기" and button["action"] == "webLink"
assert button["webLinkUrl"].endswith("/v1/site/post/edit?t=EDITCODE1234")
async def test_승인_알림은_수정_코드가_없으면_버튼_없이_본문만_준다(client, auth_headers, db_engine):
h, pid, uid = await link(db_engine, client, auth_headers, "코드없는-발화자")
post_id = await seed_post(db_engine, pid)
res = await client.post(
PATH, headers={"X-Agent-Secret": SECRET}, json=event_body(post_id, edit_token=None, speaker="코드없는-발화자")
)
assert POST_BODY in outputs(res)[0]["simpleText"]["text"]
assert len(outputs(res)) == 1
async def test_남의_글은_본문을_주지_않는다(client, auth_headers, db_engine):
"""★ 글 ID 를 알아도 그 글의 주인에게 연결된 발화자가 아니면 아무것도 안 나온다."""
_h1, pid1, _uid1 = await link(db_engine, client, auth_headers, "주인-발화자", "주인숙소")
await link(db_engine, client, auth_headers, "남-발화자", "남의숙소")
post_id = await seed_post(db_engine, pid1)
res = await client.post(PATH, headers={"X-Agent-Secret": SECRET}, json=event_body(post_id, speaker="남-발화자"))
assert res.status_code == 200
assert POST_BODY not in res.text and "주인숙소" not in res.text
assert "EDITCODE1234" not in res.text
async def test_연결되지_않은_발화자에게는_본문을_주지_않는다(client, auth_headers, db_engine):
_h, pid, _uid = await link(db_engine, client, auth_headers, "연결된-발화자")
post_id = await seed_post(db_engine, pid)
res = await client.post(PATH, headers={"X-Agent-Secret": SECRET}, json=event_body(post_id, speaker="모르는-발화자"))
assert res.status_code == 200
assert POST_BODY not in res.text and "EDITCODE1234" not in res.text
async def test_이미_처리했거나_기한이_지난_글은_안내로_끝난다(client, auth_headers, db_engine):
from datetime import datetime, timedelta, timezone
h, pid, uid = await link(db_engine, client, auth_headers, "지난-발화자")
approved = await seed_post(db_engine, pid, status=4)
expired = await seed_post(db_engine, pid, expires=datetime.now(timezone.utc) - timedelta(hours=1))
for post_id in (approved, expired):
res = await client.post(PATH, headers={"X-Agent-Secret": SECRET}, json=event_body(post_id, speaker="지난-발화자"))
assert res.status_code == 200
assert POST_BODY not in res.text
assert "기한" in said(res) or "처리" in said(res)
async def test_글_id_가_이상해도_터지지_않는다(client, auth_headers, db_engine):
await link(db_engine, client, auth_headers, "이상한-발화자")
res = await client.post(PATH, headers={"X-Agent-Secret": SECRET}, json=event_body("not-a-uuid", speaker="이상한-발화자"))
assert res.status_code == 200
assert said(res)