[feat] solution/backend: 카톡 승인 알림에 [승인] 버튼 — 연결된 계정이 권한 (Event API 2-2)

2-1 로 카톡에 글과 [수정하기] 가 오게 됐고, 이제 카톡 안에서 바로 올린다.
승인 권한은 링크가 아니라 연결된 계정이다 — 버튼이 들고 온 글 ID 는 믿지 않는다.

- kakao_bot: 알림 카드에 [승인](action: block, blockId=KAKAO_APPROVE_BLOCK_ID,
  extra={kind:approve, post_id}) 을 그리고, 클릭은 action.clientExtra 로 받는다.
  블록 ID 가 비면 버튼을 그리지 않는다(눌러도 안 되는 버튼을 보내지 않는다)
- channel.approve_post: 누른 발화자 → 사장님 → 그 가게의 미처리·기한 전 글인지 재확인 후
  approve_by_owner(메일·'바로 발행' 과 같은 경로라 재발행 잡·쓰레드 공유까지 동일).
  연결 안 됨·남의 글·이미 올림·기한 지남은 같은 안내로 끝나고 두 번 올라가지 않는다.
  답장은 "올렸습니다" + [사이트 보기](#blog). LLM 을 부르지 않는다
- 5초를 넘겨도 승인 작업은 취소하지 않는다(asyncio.shield) — 여러 번 커밋하는 작업이라
  중간에 끊기면 승인만 되고 재발행이 안 걸린 글이 남는다
- PostService._blog_url → blog_url(채널이 [사이트 보기] 에 쓴다)

test_kakao_webhook 10건 추가(구현 전 5건 실패 확인), 관련 11개 스위트 239 passed.
실제 클릭 본문(action.clientExtra 위치)은 첫 클릭의 로그로 확인한다.
This commit is contained in:
skkim committed 2026-09-29 16:50:40 +09:00
1 parent f1b473968d
commit e0155d0423
8 files changed
+333 -20

No files matched your search

@@ -476,3 +476,172 @@ async def test_글_id_가_이상해도_터지지_않는다(client, auth_headers,
assert res.status_code == 200
assert said(res)
# ── [승인] 버튼 ──────────────────────────────────────────────────────────
# ★ 승인 권한은 링크가 아니라 **연결된 계정**이다. 버튼이 들고 오는 post_id 는 믿지 않고,
# 누른 발화자 → 사장님 → 그 글이 그 사장님 가게의 미처리·기한 전 글인지를 서버가 다시 본다.
# 틀리면 아무것도 승인되지 않고, 어느 쪽이 틀렸는지는 구분해 답하지 않는다.
APPROVE_BLOCK = "6abb6a319e1c4d176fa81ff4"
BUILD = 4 # JobType.BUILD
def click_body(post_id, speaker, kind="approve"):
"""[승인] 버튼(action: block)을 누르면 다음 스킬 요청의 action.clientExtra 로 extra 가 돌아온다."""
payload = body("승인", speaker)
payload["action"] = {"clientExtra": {"kind": kind, "post_id": str(post_id)}}
return payload
async def status_of(db_engine, post_id):
async with db_engine.begin() as c:
return (await c.execute(text("SELECT status FROM place_posts WHERE post_id=:p"), {"p": post_id})).scalar_one()
async def build_jobs(db_engine, place_id):
async with db_engine.begin() as c:
return (
await c.execute(
text("SELECT count(*) FROM jobs WHERE job_type=:t AND payload->>'place_id'=:p"),
{"t": BUILD, "p": str(place_id)},
)
).scalar_one()
async def publish_site(db_engine, place_id, domain="approve-click-test"):
async with db_engine.begin() as c:
await c.execute(
text("INSERT INTO sites (site_id, place_id, domain, status) VALUES (:sid, :pid, :dom, 3)"),
{"sid": uuid.uuid4(), "pid": uuid.UUID(str(place_id)), "dom": domain},
)
def card_buttons(res):
return outputs(res)[1]["textCard"]["buttons"]
async def test_승인_알림에_블록_id_가_있으면_승인_버튼을_그린다(client, auth_headers, db_engine, monkeypatch):
monkeypatch.setenv("KAKAO_APPROVE_BLOCK_ID", APPROVE_BLOCK)
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="버튼-발화자"))
buttons = card_buttons(res)
approve = next(b for b in buttons if b["label"] == "승인")
assert approve["action"] == "block" and approve["blockId"] == APPROVE_BLOCK
assert approve["extra"] == {"kind": "approve", "post_id": str(post_id)}
assert any(b["label"] == "수정하기" and b["action"] == "webLink" for b in buttons)
async def test_블록_id_가_없으면_죽은_승인_버튼을_그리지_않는다(client, auth_headers, db_engine, monkeypatch):
"""콘솔 준비 전에 켜도 눌러도 안 되는 버튼이 사장님 카톡에 나가지 않는다."""
monkeypatch.setenv("KAKAO_APPROVE_BLOCK_ID", "")
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 [b["label"] for b in card_buttons(res)] == ["수정하기"]
async def test_승인_버튼을_누르면_올라가고_사이트_보기를_준다(client, auth_headers, db_engine):
h, pid, uid = await link(db_engine, client, auth_headers, "승인-클릭자", "클릭숙소")
await publish_site(db_engine, pid)
post_id = await seed_post(db_engine, pid)
res = await client.post(PATH, headers={"X-Agent-Secret": SECRET}, json=click_body(post_id, "승인-클릭자"))
assert res.status_code == 200
assert "올렸습니다" in said(res)
assert await status_of(db_engine, post_id) == 4 # APPROVED
assert await build_jobs(db_engine, pid) == 1
button = card_buttons(res)[0]
assert button["label"] == "사이트 보기" and button["action"] == "webLink"
assert button["webLinkUrl"].endswith("/s/approve-click-test#blog")
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=click_body(post_id, "사이트없는-클릭자"))
assert "올렸습니다" in said(res)
assert await status_of(db_engine, post_id) == 4
assert len(outputs(res)) == 1
async def test_남의_글의_승인_버튼은_아무것도_승인하지_않는다(client, auth_headers, db_engine):
"""★ post_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=click_body(post_id, "다른사람-발화자"))
assert res.status_code == 200
assert "올렸습니다" not in said(res)
assert await status_of(db_engine, post_id) == 3 # 그대로 SENT
assert await build_jobs(db_engine, pid1) == 0
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=click_body(post_id, "모르는-클릭자"))
assert "올렸습니다" not in said(res)
assert await status_of(db_engine, post_id) == 3
assert await build_jobs(db_engine, pid) == 0
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)
first = await client.post(PATH, headers={"X-Agent-Secret": SECRET}, json=click_body(post_id, "두번-클릭자"))
second = await client.post(PATH, headers={"X-Agent-Secret": SECRET}, json=click_body(post_id, "두번-클릭자"))
assert "올렸습니다" in said(first)
assert "올렸습니다" not in said(second)
assert await build_jobs(db_engine, pid) == 1
async def test_기한이_지난_글의_승인_버튼은_먹지_않는다(client, auth_headers, db_engine):
from datetime import datetime, timedelta, timezone
h, pid, uid = await link(db_engine, client, auth_headers, "만료-클릭자")
post_id = await seed_post(db_engine, pid, expires=datetime.now(timezone.utc) - timedelta(hours=1))
res = await client.post(PATH, headers={"X-Agent-Secret": SECRET}, json=click_body(post_id, "만료-클릭자"))
assert "올렸습니다" not in said(res)
assert await status_of(db_engine, post_id) == 3
async def test_승인_클릭은_모델을_부르지_않는다(client, auth_headers, db_engine, monkeypatch):
"""버튼 처리는 결정적이어야 한다 — 유료 호출도 없고, 모델이 다른 도구를 고를 여지도 없다."""
h, pid, uid = await link(db_engine, client, auth_headers, "모델없는-클릭자")
post_id = await seed_post(db_engine, pid)
called = AsyncMock()
monkeypatch.setattr(runtime, "chat", called)
await client.post(PATH, headers={"X-Agent-Secret": SECRET}, json=click_body(post_id, "모델없는-클릭자"))
called.assert_not_awaited()
async def test_모르는_종류나_이상한_글_id_의_클릭은_터지지_않는다(client, auth_headers, db_engine):
await link(db_engine, client, auth_headers, "이상한-클릭자")
bad_id = await client.post(PATH, headers={"X-Agent-Secret": SECRET}, json=click_body("not-a-uuid", "이상한-클릭자"))
unknown = await client.post(
PATH, headers={"X-Agent-Secret": SECRET}, json=click_body(uuid.uuid4(), "이상한-클릭자", kind="delete")
)
assert bad_id.status_code == 200 and said(bad_id)
assert "올렸습니다" not in said(bad_id)
assert unknown.status_code == 200