[feat] solution/backend,docs: 미니블로그 승인 → 쓰레드 자동 게재, 쓰레드 초안 생성 OpenAI 전환

사장님 지시: "쓰레드에 연동되어 있으면 같이 업로드 되는 기능". 미니블로그의 두
승인 경로(이메일 GET 토큰, 로그인 "바로 발행")를 공통 메서드로 묶고, 그 끝에서
쓰레드 연동을 시도한다. 미니블로그 승인 자체가 발화 동의로 취급되므로 쓰레드
쪽 별도 승인은 묻지 않는다(DECISIONS 7-1-2 개정, 문구를 그대로 재사용하는
경우에 한정). 겸사겸사 쓰레드 초안 생성(generate_social_post)이 LLM_PROVIDER
를 안 타고 Gemini 를 직접 호출하던 것도 다른 생성 함수와 같은 추상화로 맞췄다.

- blog_jobs._published_places: sites.domain IS NOT NULL 조건 추가(쓰레드 기준과 통일)
- social_service.publish_reused_text: 연동 없음/게시 비활성/domain 미확정이면 스킵,
  정상이면 APPROVED 삽입 + run_post(job_type=9) enqueue — 새 게시 로직은 안 만든다
- post_service: decide/approve_by_owner → _approve_and_publish 로 공통화,
  _try_social_share 는 실패를 전부 삼켜 미니블로그 승인을 막지 않는다
- gemini_text.generate_social_post: services.llm.provider.active() 로 전환,
  Gemini 전용 import 제거
- DECISIONS.md 7-1-2, MINI_BLOG.md 5·8절, SOCIAL.md 갱신

test_blog_owner.py·test_social.py 다수 추가/수정, 관련 스위트 전체 PASS
This commit is contained in:
skkim committed 2026-09-22 08:33:40 +09:00
1 parent 07c53d30bf
commit 47da2f29b3
9 files changed
+861 -101

No files matched your search

+127 -23
View File
@@ -157,39 +157,43 @@ async def test_expired_and_stale_sweep(client, auth_headers, db_engine):
async def test_no_facts_no_paid_call(monkeypatch):
async def forbidden(*args, **kwargs):
from services.llm import provider as llm_provider
def forbidden():
raise AssertionError("paid call")
monkeypatch.setattr(gemini_text, "call", forbidden)
monkeypatch.setattr(llm_provider, "active", forbidden)
with pytest.raises(gemini_text.GeminiInvalidOutput, match="NO_GROUNDED_FACTS"):
await gemini_text.generate_social_post("숙소", [], "https://example.com/s/stay")
async def test_long_draft_regenerates(monkeypatch):
monkeypatch.setattr(gemini_text, "is_configured", lambda: True)
"""generate_social_post 는 LLM_PROVIDER 추상화(services/llm/provider.py)를 탄다
(2026-09-21, Gemini 하드코딩 제거) — 여기서는 provider.active() 가 돌려주는 공급자
자체를 가짜로 바꿔 길이 초과 → 재요청 → 통과 흐름만 검증한다."""
from services.llm import provider as llm_provider
from services.llm.types import LlmResult, Usage
bodies = iter(["가" * 501, "체크인은 15:00입니다."])
async def call(*args, **kwargs):
return {
"candidates": [
{
"content": {
"parts": [
{
"text": json.dumps(
{
"body": next(bodies),
"fact_keys": ["check_in_time"],
}
)
}
]
}
}
]
}
class _FakeLlm:
__name__ = "services.llm.fake"
DEFAULT_MODEL = "fake-model"
monkeypatch.setattr(gemini_text, "call", call)
@staticmethod
def is_configured():
return True
@staticmethod
async def generate(client, model, *, prompt, response_schema=None, temperature=0.2, max_retries=0, images=None):
body = next(bodies)
return LlmResult(
json={"body": body, "fact_keys": ["check_in_time"]},
text=json.dumps({"body": body, "fact_keys": ["check_in_time"]}),
usage=Usage(input_tokens=0, output_tokens=0),
)
monkeypatch.setattr(llm_provider, "active", lambda: _FakeLlm())
result = await gemini_text.generate_social_post(
"숙소",
[gemini_text.FactInput(key="check_in_time", label="체크인", value="15:00")],
@@ -495,3 +499,103 @@ async def test_oauth_roundtrip_saves_encrypted_account(db_engine, monkeypatch):
"SELECT status, access_token FROM owner_social_accounts WHERE user_id = :u"),
{"u": user_id})).first()
assert after.status == "revoked" and after.access_token is None, "해제해도 토큰이 남아 있다"
async def test_publish_reused_text_skips_when_no_threads_account(db_engine, auth_headers, client):
from services import social_service as svc
h, pid, uid, v = await seed(client, auth_headers, db_engine)
result = await svc.publish_reused_text(uid, pid, "오늘도 마당이 조용합니다.")
assert result is None
async with db_engine.begin() as c:
assert (
await c.execute(text("SELECT count(*) FROM place_social_posts WHERE place_id=:p"), {"p": pid})
).scalar_one() == 0
async def test_publish_reused_text_skips_when_posting_disabled(db_engine, auth_headers, client, monkeypatch):
from services import social_service as svc
monkeypatch.setattr(svc, "posting_enabled", lambda: False)
h, pid, uid, v = await seed(client, auth_headers, db_engine)
async with db_engine.begin() as c:
await c.execute(
text(
"INSERT INTO owner_social_accounts(account_id,user_id,provider,provider_user_id,handle,profile_url,status) "
"VALUES (:a,:u,2,'22','host','https://www.threads.com/@host','linked')"
),
{"a": uuid.uuid4(), "u": uid},
)
result = await svc.publish_reused_text(uid, pid, "오늘도 마당이 조용합니다.")
assert result is None
async with db_engine.begin() as c:
assert (
await c.execute(text("SELECT count(*) FROM place_social_posts WHERE place_id=:p"), {"p": pid})
).scalar_one() == 0
async def test_publish_reused_text_skips_when_domain_not_fixed(db_engine, auth_headers, client, monkeypatch):
from services import social_service as svc
monkeypatch.setattr(svc, "posting_enabled", lambda: True)
h, pid, uid, v = await seed(client, auth_headers, db_engine)
async with db_engine.begin() as c:
await c.execute(text("UPDATE sites SET domain=NULL WHERE place_id=:p"), {"p": pid})
await c.execute(
text(
"INSERT INTO owner_social_accounts(account_id,user_id,provider,provider_user_id,handle,profile_url,status) "
"VALUES (:a,:u,2,'22','host','https://www.threads.com/@host','linked')"
),
{"a": uuid.uuid4(), "u": uid},
)
result = await svc.publish_reused_text(uid, pid, "오늘도 마당이 조용합니다.")
assert result is None
async def test_publish_reused_text_inserts_approved_post_with_link_and_enqueues_run_post(
db_engine, auth_headers, client, monkeypatch
):
from services import social_service as svc
monkeypatch.setattr(svc, "posting_enabled", lambda: True)
h, pid, uid, v = await seed(client, auth_headers, db_engine)
account_id = uuid.uuid4()
async with db_engine.begin() as c:
await c.execute(
text(
"INSERT INTO owner_social_accounts(account_id,user_id,provider,provider_user_id,handle,profile_url,status) "
"VALUES (:a,:u,2,'22','host','https://www.threads.com/@host','linked')"
),
{"a": account_id, "u": uid},
)
result = await svc.publish_reused_text(uid, pid, "오늘도 마당이 조용합니다.")
assert result is not None
expected_url = svc.site_payload.publish_origin() + "/s/social-stay"
async with db_engine.begin() as c:
row = (
await c.execute(
text(
"SELECT status, body, link_url, decided_via, account_id FROM place_social_posts WHERE post_id=:p"
),
{"p": result},
)
).first()
assert row.status == "APPROVED"
assert row.body == f"오늘도 마당이 조용합니다.\n\n{expected_url}"
assert row.link_url == expected_url
assert row.decided_via == "mini_blog"
assert row.account_id == account_id
job_count = (
await c.execute(text("SELECT count(*) FROM jobs WHERE job_type=9"))
).scalar_one()
assert job_count == 1
# 같은 site_version 에 두 번째 호출 — 유니크 인덱스가 중복 삽입을 막는다
second = await svc.publish_reused_text(uid, pid, "다른 문구")
assert second is None
async with db_engine.begin() as c:
assert (
await c.execute(text("SELECT count(*) FROM place_social_posts WHERE place_id=:p"), {"p": pid})
).scalar_one() == 1