[feat] solution: 미니블로그 빌더 기능 확장 — 알림 이메일 분리·삭제·즉시발송·공급자 무관 생성
빌더 앱에서 미니블로그를 운영하는 데 필요했던 몇 가지를 묶었다. - notify_email: 업장별 승인 메일 수신자를 계정 로그인 이메일과 분리(places.notify_email, migrations/0021, PlaceCRUD·protocol.py·place_service.py 검증, BlogPostsPage.tsx 설정 UI) - 글 삭제(soft delete): 상태 제한 없이 지우고, 이미 게재된 글이면 재발행 잡까지 큐에 넣는다 (post_crud.py, router/v1/site/post.py DELETE, BlogPostsPage.tsx 삭제 버튼) - 지금 발송하기: 아침 9시 스윕을 안 기다리고 바로 발송(post_crud.next_due_for_mail, BlogPostsPage.tsx 버튼) - blog_service.generate_one: 하드코딩된 Gemini 대신 services/llm/provider.py(LLM_PROVIDER, 기본 openai)를 타도록 전환, 업종별 분기 구조(현재 숙소만 구현) 추가 - site_payload.publish_url(place, site): 발행 주소 조합을 한 곳에 모은 헬퍼 - 프론트: orval 로 재생성한 API 클라이언트(notify_email·삭제·즉시발송·social 엔드포인트 반영) 관련 스위트는 별도 커밋(쓰레드 연동 작업)에서 이미 PASS 확인함
This commit is contained in:
1 parent
adb3460c37
commit
81ea676546
24 files changed
+1813
-44
No files matched your search
@@ -10,7 +10,7 @@ import re
|
||||
import secrets
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
from common.enums import PostStatus, PostTopicKind
|
||||
from common.enums import PlaceCategory, PostStatus, PostTopicKind
|
||||
from common.logger import LOG
|
||||
|
||||
# 본문 길이 — 회의 확정값(140~150자)에 여유를 둔다. 벗어나면 버린다.
|
||||
@@ -64,6 +64,7 @@ def issue_token() -> tuple[str, str, object]:
|
||||
return token, hash_token(token), expires
|
||||
|
||||
|
||||
# 숙소(LODGING) 기본 갈래 규칙 — 업종별 규칙이 없을 때의 폴백이기도 하다.
|
||||
TOPIC_RULES: dict[int, str] = {
|
||||
PostTopicKind.WEATHER.value:
|
||||
"오늘의 날씨와 그 날씨에 이 숙소에서 하기 좋은 일을 한 장면으로 적는다.",
|
||||
@@ -77,6 +78,23 @@ TOPIC_RULES: dict[int, str] = {
|
||||
"확인된 이용 안내 하나를 손님이 알아두면 좋은 말투로 풀어 적는다.",
|
||||
}
|
||||
|
||||
# 업종별 분기 — 지금은 숙소만 채워져 있다. 새 업종을 넣으려면 여기 두 딕셔너리에만 항목을 더한다.
|
||||
_BUSINESS_NOUN_BY_CATEGORY: dict[int, str] = {
|
||||
PlaceCategory.LODGING.value: "숙소",
|
||||
}
|
||||
_TOPIC_RULES_BY_CATEGORY: dict[int, dict[int, str]] = {
|
||||
PlaceCategory.LODGING.value: TOPIC_RULES,
|
||||
}
|
||||
|
||||
|
||||
def _business_noun(place_category: int) -> str:
|
||||
return _BUSINESS_NOUN_BY_CATEGORY.get(place_category, "숙소")
|
||||
|
||||
|
||||
def _topic_rules(place_category: int) -> dict[int, str]:
|
||||
return _TOPIC_RULES_BY_CATEGORY.get(place_category, TOPIC_RULES)
|
||||
|
||||
|
||||
_RULES = (
|
||||
"규칙\n"
|
||||
f"- {MIN_LEN}~{MAX_LEN}자 사이 한 문단. 제목·해시태그·이모지를 쓰지 않는다.\n"
|
||||
@@ -87,12 +105,15 @@ _RULES = (
|
||||
)
|
||||
|
||||
|
||||
def build_prompt(*, place_name: str, region: str, topic_kind: int, material: str, used_topics: list[str]) -> str:
|
||||
def build_prompt(*, place_name: str, region: str, topic_kind: int, material: str, used_topics: list[str],
|
||||
place_category: int = PlaceCategory.LODGING.value) -> str:
|
||||
"""갈래 하나에 대한 프롬프트 한 벌. 프롬프트를 두 곳에 적지 않으려고 여기서만 만든다."""
|
||||
used = ", ".join(used_topics[:40]) or "없음"
|
||||
noun = _business_noun(place_category)
|
||||
rules = _topic_rules(place_category)
|
||||
return (
|
||||
f"{region}에 있는 숙소 '{place_name}'의 짧은 홍보 글을 쓴다.\n"
|
||||
f"갈래: {TOPIC_RULES.get(topic_kind, '')}\n"
|
||||
f"{region}에 있는 {noun} '{place_name}'의 짧은 홍보 글을 쓴다.\n"
|
||||
f"갈래: {rules.get(topic_kind, '')}\n"
|
||||
f"소재: {material}\n"
|
||||
f"이미 쓴 주제: {used}\n\n"
|
||||
f"{_RULES}\n본문만 출력한다."
|
||||
@@ -124,29 +145,37 @@ def filter_drafts(rows: list[dict]) -> tuple[list[dict], list[tuple[str, str]]]:
|
||||
|
||||
|
||||
async def generate_one(*, place_name: str, region: str, topic_kind: int, material: str,
|
||||
used_topics: list[str], client=None) -> tuple[str, str] | None:
|
||||
used_topics: list[str], place_category: int = PlaceCategory.LODGING.value,
|
||||
client=None) -> tuple[str, str] | None:
|
||||
"""(문구, 모델명) 한 쌍. LLM 이 없거나 실패하면 None — 생성 실패가 잡을 죽이지 않는다.
|
||||
모델명은 생성 이력 화면이 "어느 모델썼는지" 보여주는 데 쓴다(2026-09-17, 사장님 지시)."""
|
||||
from services.llm.gemini import DEFAULT_MODEL, GeminiError, call, extract_text, is_configured
|
||||
모델명은 생성 이력 화면이 "어느 모델썼는지" 보여주는 데 쓴다(2026-09-17, 사장님 지시).
|
||||
|
||||
if not is_configured():
|
||||
★ 발행 링크는 여기서 붙이지 않는다 — 호출부가 길이 게이트(is_publishable_body/
|
||||
filter_drafts, MIN_LEN~MAX_LEN)를 이 반환값 그대로에 건다. 링크까지 포함해서
|
||||
길이를 재면 정상 문구도 게이트에 걸려 버려진다. 링크는 게이트를 통과한 뒤 호출부가
|
||||
붙인다.
|
||||
|
||||
★ 공급자는 LLM_PROVIDER 설정을 따른다(services/llm/provider.py) — Gemini 로 고정하지
|
||||
않는다. generate_social_post(services/external/gemini_text.py)와 달리 구조화 출력
|
||||
재시도 루프가 없는 단순 텍스트 생성이라 공급자를 가려도 된다."""
|
||||
from services.llm import provider
|
||||
from services.llm.errors import LlmError
|
||||
|
||||
llm = provider.active()
|
||||
if not llm.is_configured():
|
||||
return None
|
||||
|
||||
prompt = build_prompt(place_name=place_name, region=region, topic_kind=topic_kind,
|
||||
material=material, used_topics=used_topics)
|
||||
body = {
|
||||
"contents": [{"role": "user", "parts": [{"text": prompt}]}],
|
||||
"generationConfig": {"temperature": 0.9},
|
||||
}
|
||||
material=material, used_topics=used_topics, place_category=place_category)
|
||||
owns = client is None
|
||||
if owns:
|
||||
import httpx
|
||||
client = httpx.AsyncClient(timeout=httpx.Timeout(60.0, connect=10.0))
|
||||
try:
|
||||
payload = await call(client, DEFAULT_MODEL, body)
|
||||
text = extract_text(payload).strip()
|
||||
return (text, DEFAULT_MODEL) if text else None
|
||||
except GeminiError as error:
|
||||
result = await llm.generate(client, llm.DEFAULT_MODEL, prompt=prompt, temperature=0.9)
|
||||
text = result.text.strip()
|
||||
return (text, llm.DEFAULT_MODEL) if text else None
|
||||
except LlmError as error:
|
||||
LOG.w(f"[blog] 생성 실패: {error}")
|
||||
return None
|
||||
finally:
|
||||
|
||||
@@ -13,6 +13,7 @@ from common.models.gmodel import PageParams, UserInfo
|
||||
from common.utils.gtime import GTime
|
||||
from crud.job_crud import JobQueue
|
||||
from crud.place_crud import IPlaceCRUD, PlaceCRUD
|
||||
from services import mail_service
|
||||
from router.v1.place.protocol import (
|
||||
Req_VerifyPlaceByUrl,
|
||||
LinkData,
|
||||
@@ -150,6 +151,12 @@ class PlaceService:
|
||||
data["status"] = req.status.value
|
||||
if "name" in data:
|
||||
data["name"] = str(data["name"]).strip()
|
||||
if "notify_email" in data:
|
||||
data["notify_email"] = str(data["notify_email"]).strip()
|
||||
if data["notify_email"] and not mail_service.is_valid_address(data["notify_email"]):
|
||||
res.result.SetResult(ErrorType.INVALID_REQUEST_DATA)
|
||||
return res
|
||||
data["notify_email"] = data["notify_email"] or None
|
||||
|
||||
if data:
|
||||
err_type, rowcount = await DB_SESSION_MNG.execute_lambda_claim(
|
||||
|
||||
@@ -794,6 +794,12 @@ def publish_origin() -> str:
|
||||
return f"{_scheme(DEFAULT_HOST)}://{DEFAULT_HOST}"
|
||||
|
||||
|
||||
def publish_url(place, site) -> str:
|
||||
"""이 사업장 사이트의 전체 발행 주소. 미니 블로그·SNS 초안이 문구 끝에 붙이는 링크가
|
||||
이 값과 갈리면 안 되므로 origin·slug 조합을 여기 한 곳에서만 한다."""
|
||||
return f"{publish_origin()}/s/{publish_slug(place, site)}"
|
||||
|
||||
|
||||
def primary_media(snapshot: dict) -> dict | None:
|
||||
"""대표 사진(og:image) — 객실·메뉴 전용이 아닌 첫 장. 없으면 None.
|
||||
|
||||
|
||||
Reference in new issue
Block a user