Compare commits
9
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
85575e9f9f | ||
|
|
59cd0035fa | ||
|
|
1bf2ed0fd2 | ||
|
|
368762d453 | ||
|
|
412dc3397c | ||
|
|
89feac65c1 | ||
|
|
db7c9254f5 | ||
|
|
3ecd7b3e18 | ||
|
|
ade3bc0f8e |
No files matched your search
@@ -112,6 +112,13 @@ KAKAO_APPROVAL_PUSH_ENABLED=0
|
||||
# 한꺼번에 일어난다. 비용을 확인하고 켠다.
|
||||
# ★ 발송(09:00)은 이 스위치와 무관하게 항상 돈다 — 손으로 만든 글도 나가야 한다.
|
||||
BLOG_AUTO_DRAFTS_ENABLED=0
|
||||
|
||||
# 자동 스윕(생성·발송)을 받을 사장님 — user_id 를 쉼표로. **비면 전체**다.
|
||||
# ★ 발행된 사이트가 전부 대상이라 테스트로 만든 중복 업장까지 매일 알림을 받는다
|
||||
# (실측 2026-10-01: 발행 25곳 중 상당수가 중복·테스트 업장). 시험 운영 중에는 좁혀 둔다.
|
||||
# ★ 빌더의 [지금 생성하기] 는 이 목록을 보지 않는다 — 목록 밖 사장님도 자기 글은 만든다.
|
||||
# ★ 목록 밖 업장의 글은 건너뛸 뿐 버리지 않는다. 목록을 풀면 그때부터 나간다.
|
||||
BLOG_AUTO_OWNER_IDS=
|
||||
KAKAO_APPROVAL_EVENT_NAME=post_approval
|
||||
# [승인] 버튼이 부르는 블록 ID(오픈빌더 블록 주소의 /intent/<ID>). 그 블록에 우리 스킬이
|
||||
# 스킬데이터로 연결돼 있어야 한다. ★ 비우면 [승인] 버튼을 그리지 않는다(수정하기만 나간다).
|
||||
|
||||
@@ -60,6 +60,8 @@ services:
|
||||
# 미니 블로그 재고 자동 채우기(04:10 KST). 기본 꺼짐 — 켜면 발행 사이트 전체에
|
||||
# 업장당 30건씩 AI 호출이 일어난다(docs/MINI_BLOG.md 2절). 발송(09:00)은 무관하게 돈다.
|
||||
BLOG_AUTO_DRAFTS_ENABLED: ${BLOG_AUTO_DRAFTS_ENABLED:-0}
|
||||
# 자동 스윕을 받을 사장님(user_id 쉼표 구분). 비면 전체 — 수동 생성은 안 걸린다.
|
||||
BLOG_AUTO_OWNER_IDS: ${BLOG_AUTO_OWNER_IDS:-}
|
||||
# ★ GSC_CREDENTIALS_HOST_FILE(호스트 경로, .env)을 아래 볼륨으로 이 컨테이너 안에 마운트한
|
||||
# 고정 자리다. search_console_settings.load_settings() 가 실제로 읽는 건 이 값이다 —
|
||||
# 호스트 경로를 코드에 그대로 넘기면 컨테이너 안에서 그 경로가 없어 실패한다.
|
||||
|
||||
@@ -13,6 +13,8 @@
|
||||
| `partial_failure` | 노래 등 곁가지 생성 실패(발행 자체는 계속) | `song_failed:{place_id}` |
|
||||
| `queue_stuck` | dead-letter 누적·좀비 실행·PENDING 30분 이상 정체 | `queue_health` |
|
||||
| `recovery` | 위 dedupe_key 가 다음 정상 상태에서 풀릴 때 한 번 | 없음(매번 새 행) |
|
||||
| `blog_send_failed` | 미니블로그 승인 알림 실패 — 카톡 실패(메일로 대체) · 메일 실패 · 보낼 곳 없음. 다음 발송 성공 때 `recovery` | `blog_kakao_failed:{place_id}` · `blog_send_failed:{place_id}` |
|
||||
| `booking_request_failed` | 손님 예약 요청 메일을 사장님께 못 보냄(손님 이름·연락처는 싣지 않는다). 다음 전달 성공 때 `recovery` | `booking_request_failed:{place_id}` |
|
||||
| `activity` | 채널 크롤링 실패 · 사진 분석 일부 실패(`services/activity_feed.py`) | 없음(매번 보낸다) |
|
||||
|
||||
★ **게이트 반려는 알리지 않는다.** 사장님이 fact 를 안 채웠거나 고유 콘텐츠가 없어서 막힌 건
|
||||
|
||||
@@ -71,6 +71,13 @@
|
||||
보낼 글이 0건이었다. 지금은 꺼져 있다는 사실이 코드에 남는다(`scheduler/__init__.py`)
|
||||
- **대상**: 발행된 사이트 중 재고(DRAFT+REVIEWED)가 `REFILL_BELOW`(30) 미만인 업장 —
|
||||
하루 한 통씩 나간다고 보면 한 달치를 채우는 셈이다
|
||||
- ★ **`BLOG_AUTO_OWNER_IDS` 로 받을 사장님을 좁힐 수 있다**(쉼표 구분 user_id, 비면 전체).
|
||||
생성·발송 **두 스윕에 같이** 걸린다 — 한쪽만 걸면 만들어 놓고 안 보내거나 그 반대가 된다.
|
||||
★★ 거르는 자리는 `blog_jobs._for_auto_sweep` 이고 `_published_places()` 안이 아니다.
|
||||
그 함수는 빌더의 [지금 생성하기](`generate_range`·`generate_one_for_date`)도 쓰는데,
|
||||
거기서 거르면 **목록 밖 사장님이 자기 화면에서 자기 글도 못 만든다**.
|
||||
★ 목록 밖 업장의 글은 건너뛸 뿐 **버리지 않는다** — REVIEWED 로 남아 목록을 풀면 나간다.
|
||||
거기서 SENT 로 찍으면 아무에게도 안 간 글이 보낸 것으로 기록된다
|
||||
- **한 번에 `BATCH_SIZE`(30)건**씩. 앞 회차의 `topic_key` 목록을 프롬프트에 넣어 중복을 막는다
|
||||
(한 달치를 한 호출로 뽑으면 중복 검사가 안 된다)
|
||||
- **배정일**: 그 업장의 `MAX(scheduled_date)` 다음날부터(없으면 오늘부터, KST) 하루 한 건씩
|
||||
|
||||
@@ -42,12 +42,12 @@ class PostCRUD:
|
||||
return result.scalar()
|
||||
|
||||
async def due_for_mail(self, cdb: AsyncSession, status: int, today, limit: int):
|
||||
"""배정일이 오늘까지 온 것 중 업장당 1건만, 이른 날짜순."""
|
||||
"""배정일이 오늘인 것만, 업장당 1건."""
|
||||
result = await cdb.execute(
|
||||
select(place_posts)
|
||||
.where(
|
||||
place_posts.status == status, place_posts.deleted == False, # noqa: E712
|
||||
place_posts.scheduled_date <= today,
|
||||
place_posts.scheduled_date == today,
|
||||
)
|
||||
.distinct(place_posts.place_id)
|
||||
.order_by(place_posts.place_id, place_posts.scheduled_date)
|
||||
@@ -62,9 +62,9 @@ class PostCRUD:
|
||||
.where(
|
||||
place_posts.place_id == place_id, place_posts.status == status,
|
||||
place_posts.deleted == False, # noqa: E712
|
||||
place_posts.scheduled_date <= today,
|
||||
place_posts.scheduled_date == today,
|
||||
)
|
||||
.order_by(place_posts.scheduled_date)
|
||||
.order_by(place_posts.created_at)
|
||||
.limit(1)
|
||||
)
|
||||
return result.scalars().first()
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
★ 글마다 scheduled_date(KST) 를 하나씩 배정한다 — "언제 만들어졌나"만 있고 "언제 낼
|
||||
것인가"가 없으면 달력 화면이 근거 없는 날짜를 지어내야 한다(2026-09-17).
|
||||
"""
|
||||
import os
|
||||
import uuid
|
||||
from datetime import date, datetime, timedelta, timezone
|
||||
|
||||
@@ -20,7 +21,7 @@ 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, kakao_link_service, mail_service, site_payload
|
||||
from services import alert_service, blog_service, kakao_link_service, mail_service, site_payload
|
||||
from services.external import kakao_event
|
||||
from services.snapshot import build_snapshot
|
||||
|
||||
@@ -58,6 +59,29 @@ async def _published_places() -> list:
|
||||
return list(result.all()) if result is not None else []
|
||||
|
||||
|
||||
def _auto_owner_allowlist() -> set:
|
||||
"""자동 스윕을 받을 사장님 목록(`BLOG_AUTO_OWNER_IDS`, 쉼표 구분 user_id).
|
||||
|
||||
★ 비면 **전체**다 — 운영 기본값이고, 이 칸이 비었다고 기능이 꺼지면 안 된다.
|
||||
★ 왜 필요한가: 발행된 사이트가 전부 대상이라 **테스트로 만든 업장까지** 매일 알림을
|
||||
받는다(실측 2026-10-01: 발행 25곳 중 상당수가 중복·테스트 업장이었다).
|
||||
시험 운영 중에는 받을 사람을 좁혀 둔다."""
|
||||
return {x.strip() for x in os.environ.get("BLOG_AUTO_OWNER_IDS", "").split(",") if x.strip()}
|
||||
|
||||
|
||||
def _for_auto_sweep(pairs: list) -> list:
|
||||
"""자동 스윕(생성·발송) 대상만 남긴다.
|
||||
|
||||
★★ **`_published_places()` 안에서 거르지 않는다.** 그 함수는 빌더의 [지금 생성하기]
|
||||
(`generate_range` · `generate_one_for_date`)도 쓰는데, 거기서 걸러 버리면 목록에 없는
|
||||
사장님은 **자기 화면에서 자기 글도 못 만든다** — 자동으로 보낼지와 직접 만들지는
|
||||
다른 질문이다. 그래서 두 스윕에서만 부른다."""
|
||||
allow = _auto_owner_allowlist()
|
||||
if not allow:
|
||||
return pairs
|
||||
return [(place, user) for place, user in pairs if str(user.user_id) in allow]
|
||||
|
||||
|
||||
async def _pending_count(place_id) -> int:
|
||||
"""아직 사장님에게 안 나간 재고 — 팀 사전검수가 없어 생성 즉시 REVIEWED 로 쌓인다."""
|
||||
def query(session):
|
||||
@@ -136,7 +160,7 @@ async def _generate_for_place(place) -> int:
|
||||
async def generate_drafts() -> int:
|
||||
"""재고가 모자란 업장마다 최대 BATCH_SIZE 건. 만든 수를 돌려준다."""
|
||||
made = 0
|
||||
for place, _user in await _published_places():
|
||||
for place, _user in _for_auto_sweep(await _published_places()):
|
||||
made += await _generate_for_place(place)
|
||||
return made
|
||||
|
||||
@@ -266,6 +290,15 @@ async def _push_kakao(channel_user_key: str, post, edit_token: str) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
async def _alert_send_failed(place, post, reason: str) -> None:
|
||||
await alert_service.send_alert(
|
||||
kind="blog_send_failed",
|
||||
title=f"미니블로그 승인 알림 발송 실패 — {place.name}",
|
||||
detail=f"place_id={place.place_id} post_id={post.post_id}\n{reason}",
|
||||
dedupe_key=f"blog_send_failed:{place.place_id}",
|
||||
)
|
||||
|
||||
|
||||
async def _send_one(place, user, post) -> bool:
|
||||
"""토큰 발급 → 발송 → 나갔으면 SENT 로 표시. 아무 데도 안 나갔으면 DB 를 안 건드린다
|
||||
(다시 시도할 길을 막지 않는다).
|
||||
@@ -294,18 +327,29 @@ async def _send_one(place, user, post) -> bool:
|
||||
# 이 간격보다 훨씬 길다.
|
||||
if await _push_kakao(kakao_key, post, edit_token):
|
||||
await mark_sent()
|
||||
await alert_service.resolve_alert(f"blog_kakao_failed:{place.place_id}", f"미니블로그 카톡 알림 정상화 — {place.name}")
|
||||
await alert_service.resolve_alert(f"blog_send_failed:{place.place_id}", f"미니블로그 승인 알림 정상화 — {place.name}")
|
||||
return True
|
||||
LOG.w(f"[blog] post={post.post_id} 카톡 승인 알림이 안 나가 메일로 대체한다")
|
||||
await alert_service.send_alert(
|
||||
kind="blog_send_failed",
|
||||
title=f"미니블로그 카톡 승인 알림 실패(메일로 대체) — {place.name}",
|
||||
detail=f"place_id={place.place_id} post_id={post.post_id}",
|
||||
dedupe_key=f"blog_kakao_failed:{place.place_id}",
|
||||
)
|
||||
|
||||
if not _can_mail(place, user):
|
||||
await _alert_send_failed(place, post, "보낼 곳이 없다 — 메일 미설정 또는 받는 주소 형식 오류")
|
||||
return False
|
||||
body = _mail_body(
|
||||
place_name=place.name, post=post, user=user,
|
||||
origin=_app_origin(), approve_token=token, edit_token=edit_token,
|
||||
)
|
||||
if not mail_service.send(to=_notify_address(place, user), subject=f"[{place.name}] 이번 글 올릴까요?", text=body):
|
||||
await _alert_send_failed(place, post, "메일 발송 실패")
|
||||
return False
|
||||
await mark_sent()
|
||||
await alert_service.resolve_alert(f"blog_send_failed:{place.place_id}", f"미니블로그 승인 알림 정상화 — {place.name}")
|
||||
return True
|
||||
|
||||
|
||||
@@ -321,7 +365,10 @@ async def send_reviewed() -> int:
|
||||
if not rows:
|
||||
return 0
|
||||
|
||||
places_by_id = {str(place.place_id): (place, user) for place, user in await _published_places()}
|
||||
# ★ 목록 밖 업장의 글은 건너뛸 뿐 **버리지 않는다** — REVIEWED 로 남아 있어서, 목록을
|
||||
# 풀면 그때 나간다. 여기서 SENT 로 찍으면 아무에게도 안 간 글이 보낸 것으로 기록된다.
|
||||
places_by_id = {str(place.place_id): (place, user)
|
||||
for place, user in _for_auto_sweep(await _published_places())}
|
||||
sent = 0
|
||||
for post in rows:
|
||||
target = places_by_id.get(str(post.place_id))
|
||||
@@ -331,6 +378,7 @@ async def send_reviewed() -> int:
|
||||
# 메일도 카톡도 보낼 수 없는 사장님은 건너뛴다. 어느 쪽으로 보낼지는 _send_one 이 정한다
|
||||
# (카톡이 연결돼 있으면 카톡, 실패했을 때만 메일 — 연결이 없으면 메일).
|
||||
if not _can_mail(place, user) and await _kakao_target(user) is None:
|
||||
await _alert_send_failed(place, post, "보낼 곳이 없다 — 메일 주소도 카톡 연결도 없다")
|
||||
continue
|
||||
if await _send_one(place, user, post):
|
||||
sent += 1
|
||||
|
||||
@@ -5,12 +5,21 @@ from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.database.model.models import places, sites, users
|
||||
from common.enums import DBWRType, SiteStatus
|
||||
from common.logger import LOG
|
||||
from services import mail_service
|
||||
from services import alert_service, mail_service
|
||||
|
||||
NOT_AVAILABLE = "지금은 온라인 예약 요청을 받을 수 없습니다. 전화로 문의해 주세요."
|
||||
SENT = "예약 요청을 보냈습니다. 사장님이 확인 후 연락드립니다."
|
||||
|
||||
|
||||
async def _alert_failed(place_id, place_name: str, reason: str) -> None:
|
||||
await alert_service.send_alert(
|
||||
kind="booking_request_failed",
|
||||
title=f"손님 예약 요청을 사장님께 전달하지 못함 — {place_name}",
|
||||
detail=f"place_id={place_id}\n{reason}",
|
||||
dedupe_key=f"booking_request_failed:{place_id}",
|
||||
)
|
||||
|
||||
|
||||
class BookingRequestService:
|
||||
async def send(self, body):
|
||||
from router.v1.site.booking_request import ResBookingRequest
|
||||
@@ -22,6 +31,7 @@ class BookingRequestService:
|
||||
place_name, owner_email = target
|
||||
if not mail_service.is_configured() or not mail_service.is_valid_address(owner_email):
|
||||
LOG.w("[booking-request] 받는 주소나 SMTP 설정이 없어 전달하지 못했다")
|
||||
await _alert_failed(body.place_id, place_name, "받는 주소나 메일 설정이 없다")
|
||||
return ResBookingRequest(success=False, message=NOT_AVAILABLE)
|
||||
|
||||
reply_to = body.email if body.email and mail_service.is_valid_address(body.email) else None
|
||||
@@ -32,9 +42,11 @@ class BookingRequestService:
|
||||
reply_to=reply_to,
|
||||
)
|
||||
if not ok:
|
||||
await _alert_failed(body.place_id, place_name, "메일 발송 실패")
|
||||
return ResBookingRequest(success=False, message=NOT_AVAILABLE)
|
||||
|
||||
LOG.i(f"[booking-request] 전달 완료 place={body.place_id}")
|
||||
await alert_service.resolve_alert(f"booking_request_failed:{body.place_id}", f"예약 요청 메일 정상화 — {place_name}")
|
||||
return ResBookingRequest(success=True, message=SENT)
|
||||
|
||||
async def _target(self, place_id) -> tuple[str, str] | None:
|
||||
|
||||
@@ -28,6 +28,7 @@ from services import (
|
||||
alert_service,
|
||||
azure_static,
|
||||
indexnow,
|
||||
mockup_blog,
|
||||
publish_gate,
|
||||
render_service,
|
||||
seo_keywords,
|
||||
@@ -136,6 +137,19 @@ async def _log(site_id, version_id, action: PublishAction, result: PublishResult
|
||||
await DB_SESSION_MNG.execute_lambda_run([site_publish_logs.DBType()], [lambda s: _site_crud.add_log(s, row)])
|
||||
|
||||
|
||||
async def _refresh_mockup_blog(place, place_id: str, slug: str) -> dict:
|
||||
snapshot = await build_snapshot(place)
|
||||
try:
|
||||
count = mockup_blog.refresh_posts(slug, snapshot.get("posts") or [])
|
||||
except mockup_blog.MockupBlogError as ex:
|
||||
raise BuildAborted(str(ex)) from ex
|
||||
await DB_SESSION_MNG.execute_lambda_run(
|
||||
[place_posts.DBType()],
|
||||
[lambda s: _post_crud.mark_published(s, uuid.UUID(place_id), None)],
|
||||
)
|
||||
return {"place_id": place_id, "build_status": "BUILT", "mockup": slug, "posts": count}
|
||||
|
||||
|
||||
async def run_build(job: dict) -> dict:
|
||||
"""BUILD 잡 핸들러."""
|
||||
payload = job["payload"]
|
||||
@@ -153,6 +167,10 @@ async def run_build(job: dict) -> dict:
|
||||
|
||||
site = await ensure_site(place_id)
|
||||
|
||||
mockup_slug = site_payload.publish_slug(place, site)
|
||||
if mockup_blog.is_mockup(mockup_slug):
|
||||
return await _refresh_mockup_blog(place, place_id, mockup_slug)
|
||||
|
||||
# 주변 정보(맛집·관광지·축제·코스)는 빌드 시점에 업장 좌표로 새로 받는다 — 발행본은 정적이라 이때 받은 값이 실린다.
|
||||
try:
|
||||
synced = await LocalContentService().sync_place(place)
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
"""목업(stay · stay2)은 굽지 않고 index.html 의 미니블로그 글만 갈아 끼운다."""
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
from common.logger import LOG
|
||||
from services import render_service
|
||||
|
||||
MOCKUP_SLUGS = frozenset({"stay", "stay2"})
|
||||
PAYLOAD_MARKER = "window.__SITE_PAYLOAD__"
|
||||
BACKUP_NAME = "index.html.bak-blog"
|
||||
|
||||
|
||||
class MockupBlogError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def is_mockup(slug: str) -> bool:
|
||||
return slug in MOCKUP_SLUGS
|
||||
|
||||
|
||||
def index_path(slug: str) -> Path:
|
||||
return Path(render_service.output_dir()) / "s" / slug / "index.html"
|
||||
|
||||
|
||||
def _payload_span(html: str) -> tuple[int, int, dict]:
|
||||
marker = html.find(PAYLOAD_MARKER)
|
||||
if marker < 0:
|
||||
raise MockupBlogError("payload 가 없다")
|
||||
start = html.index("{", marker)
|
||||
payload, end = json.JSONDecoder().raw_decode(html, start)
|
||||
return start, end, payload
|
||||
|
||||
|
||||
def merge_posts(existing: list[dict], snapshot_posts: list[dict]) -> list[dict]:
|
||||
merged = {post["postId"]: post for post in existing if post.get("postId")}
|
||||
for row in snapshot_posts:
|
||||
body = (row.get("body") or "").strip()
|
||||
if not body:
|
||||
continue
|
||||
merged[row["post_id"]] = {"postId": row["post_id"], "body": row["body"], "publishedAt": row["published_at"]}
|
||||
return sorted(merged.values(), key=lambda post: post.get("publishedAt") or "", reverse=True)
|
||||
|
||||
|
||||
def refresh_posts(slug: str, snapshot_posts: list[dict]) -> int:
|
||||
path = index_path(slug)
|
||||
if not path.is_file():
|
||||
raise MockupBlogError(f"목업 파일이 없다: {path}")
|
||||
html = path.read_text(encoding="utf-8")
|
||||
start, end, payload = _payload_span(html)
|
||||
payload["posts"] = merge_posts(payload.get("posts") or [], snapshot_posts)
|
||||
encoded = json.dumps(payload, ensure_ascii=False).replace("</", "<\\/")
|
||||
updated = html[:start] + encoded + html[end:]
|
||||
|
||||
(path.parent / BACKUP_NAME).write_text(html, encoding="utf-8")
|
||||
tmp = path.with_name(f".{path.name}.tmp")
|
||||
tmp.write_text(updated, encoding="utf-8")
|
||||
os.replace(tmp, path)
|
||||
LOG.i(f"[mockup-blog] {slug} 미니블로그 {len(payload['posts'])}건으로 갱신")
|
||||
return len(payload["posts"])
|
||||
@@ -0,0 +1,59 @@
|
||||
"""자동 스윕 수신자 제한 — `BLOG_AUTO_OWNER_IDS`.
|
||||
|
||||
★ 왜 있나: 발행된 사이트가 전부 자동 생성·발송 대상이라, 테스트로 만든 중복 업장까지
|
||||
매일 알림을 받는다(실측 2026-10-01: 발행 25곳 중 상당수가 중복·테스트 업장).
|
||||
★★ 거르는 자리가 중요하다. `_published_places()` 안에서 거르면 빌더의 [지금 생성하기] 도
|
||||
같이 막혀 **목록 밖 사장님이 자기 글도 못 만든다** — 자동으로 보낼지와 직접 만들지는
|
||||
다른 질문이다. 그래서 두 스윕에서만 거른다.
|
||||
"""
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
from services import blog_jobs
|
||||
|
||||
A = "11111111-1111-1111-1111-111111111111"
|
||||
B = "22222222-2222-2222-2222-222222222222"
|
||||
|
||||
|
||||
def _pair(user_id, place_name):
|
||||
return (SimpleNamespace(place_id=f"place-{place_name}", name=place_name),
|
||||
SimpleNamespace(user_id=user_id))
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def pairs():
|
||||
return [_pair(A, "내 숙소"), _pair(B, "남의 숙소"), _pair(B, "테스트 중복")]
|
||||
|
||||
|
||||
def test_비어_있으면_전체가_대상이다(monkeypatch, pairs):
|
||||
"""★ 운영 기본값이다 — 칸이 비었다고 기능이 꺼지면 안 된다."""
|
||||
monkeypatch.delenv("BLOG_AUTO_OWNER_IDS", raising=False)
|
||||
assert blog_jobs._for_auto_sweep(pairs) == pairs
|
||||
|
||||
|
||||
def test_목록에_있는_사장님만_남는다(monkeypatch, pairs):
|
||||
monkeypatch.setenv("BLOG_AUTO_OWNER_IDS", A)
|
||||
assert [p.name for p, _ in blog_jobs._for_auto_sweep(pairs)] == ["내 숙소"]
|
||||
|
||||
|
||||
def test_쉼표로_여럿_공백은_무시한다(monkeypatch, pairs):
|
||||
monkeypatch.setenv("BLOG_AUTO_OWNER_IDS", f" {A} , {B} ")
|
||||
assert len(blog_jobs._for_auto_sweep(pairs)) == 3
|
||||
|
||||
|
||||
def test_쉼표만_있으면_전체로_친다(monkeypatch, pairs):
|
||||
"""빈 항목만 남는 입력을 '아무도 없음' 으로 읽으면 알림이 통째로 멎는다."""
|
||||
monkeypatch.setenv("BLOG_AUTO_OWNER_IDS", " , , ")
|
||||
assert blog_jobs._for_auto_sweep(pairs) == pairs
|
||||
|
||||
|
||||
def test_수동_생성_경로는_이_목록을_보지_않는다():
|
||||
"""★★ 목록 밖 사장님도 빌더에서 자기 글은 만들 수 있어야 한다.
|
||||
`generate_range` · `generate_one_for_date` 가 `_for_auto_sweep` 을 부르면 안 된다."""
|
||||
import inspect
|
||||
|
||||
for fn in (blog_jobs.generate_range, blog_jobs.generate_one_for_date):
|
||||
assert "_for_auto_sweep" not in inspect.getsource(fn), (
|
||||
f"{fn.__name__} 이 자동 스윕 목록을 본다 — 수동 생성까지 막힌다"
|
||||
)
|
||||
@@ -1242,3 +1242,64 @@ def test_메일_본문에_액세스_토큰이_없다():
|
||||
assert "eyJ" not in body # JWT 의 머리글자
|
||||
longest = max(len(word) for word in body.split())
|
||||
assert longest < 120, f"링크가 아직 길다: {longest}자"
|
||||
|
||||
|
||||
async def test_send_now_mail_failure_alerts_once_and_recovers(client, db_engine, auth_headers, monkeypatch):
|
||||
from services import mail_service
|
||||
|
||||
monkeypatch.setattr(mail_service, "is_configured", lambda: True)
|
||||
outcome = {"ok": False}
|
||||
monkeypatch.setattr(mail_service, "send", lambda **kwargs: outcome["ok"])
|
||||
|
||||
h = await auth_headers("bloggen-alert")
|
||||
place_id = await _place(client, h, name="발송실패펜션")
|
||||
async with db_engine.begin() as conn:
|
||||
await conn.execute(
|
||||
text("INSERT INTO sites (site_id, place_id, domain, status) VALUES (:sid, :pid, :dom, :st)"),
|
||||
{"sid": uuid.uuid4(), "pid": place_id, "dom": f"blog-test-{uuid.uuid4().hex[:8]}", "st": SiteStatus.PUBLISHED.value},
|
||||
)
|
||||
await conn.execute(text("UPDATE users SET email = :e WHERE id = :id"), {"e": "alert@example.com", "id": "bloggen-alert"})
|
||||
await _seed_post(db_engine, place_id, scheduled=date.today())
|
||||
|
||||
for _ in range(2):
|
||||
res = await client.post(f"/v1/place/{place_id}/post/send-now", headers=h)
|
||||
assert res.json()["result"]["success"] is False
|
||||
|
||||
async def kinds():
|
||||
async with db_engine.begin() as conn:
|
||||
return [tuple(r) for r in (await conn.execute(text(
|
||||
"SELECT kind, resolved_at IS NOT NULL FROM alert_outbox ORDER BY created_at"))).all()]
|
||||
|
||||
assert await kinds() == [("blog_send_failed", False)]
|
||||
|
||||
outcome["ok"] = True
|
||||
assert (await client.post(f"/v1/place/{place_id}/post/send-now", headers=h)).json()["result"]["success"] is True
|
||||
assert await kinds() == [("blog_send_failed", True), ("recovery", False)]
|
||||
|
||||
|
||||
async def test_mail_goes_only_for_todays_post_not_backlog(client, db_engine, auth_headers, monkeypatch):
|
||||
from services import blog_jobs, mail_service
|
||||
|
||||
monkeypatch.setattr(mail_service, "is_configured", lambda: True)
|
||||
sent_calls = []
|
||||
monkeypatch.setattr(mail_service, "send", lambda **kwargs: sent_calls.append(kwargs) or True)
|
||||
|
||||
h = await auth_headers("bloggen-today")
|
||||
place_id = await _place(client, h, name="오늘글펜션")
|
||||
async with db_engine.begin() as conn:
|
||||
await conn.execute(
|
||||
text("INSERT INTO sites (site_id, place_id, domain, status) VALUES (:sid, :pid, :dom, :st)"),
|
||||
{"sid": uuid.uuid4(), "pid": place_id, "dom": f"blog-test-{uuid.uuid4().hex[:8]}", "st": SiteStatus.PUBLISHED.value},
|
||||
)
|
||||
await conn.execute(text("UPDATE users SET email = :e WHERE id = :id"), {"e": "today@example.com", "id": "bloggen-today"})
|
||||
old_post = await _seed_post(db_engine, place_id, scheduled=date.today() - timedelta(days=8))
|
||||
today_post = await _seed_post(db_engine, place_id, scheduled=date.today())
|
||||
|
||||
res = await client.post(f"/v1/place/{place_id}/post/send-now", headers=h)
|
||||
assert res.json()["result"]["success"] is True
|
||||
assert await _status(db_engine, today_post) == PostStatus.SENT.value
|
||||
assert await _status(db_engine, old_post) == PostStatus.REVIEWED.value
|
||||
|
||||
assert await blog_jobs.send_reviewed() == 0
|
||||
assert await _status(db_engine, old_post) == PostStatus.REVIEWED.value
|
||||
assert len(sent_calls) == 1
|
||||
@@ -99,3 +99,18 @@ async def test_without_smtp_answers_instead_of_failing(client, db_engine, owner_
|
||||
assert res.status_code == 200
|
||||
assert res.json()["success"] is False
|
||||
assert "전화" in res.json()["message"]
|
||||
|
||||
|
||||
async def test_mail_failure_alerts_without_guest_details(client, db_engine, owner_id, monkeypatch):
|
||||
monkeypatch.setattr(mail_service, "is_configured", lambda: True)
|
||||
monkeypatch.setattr(mail_service, "send", lambda **kw: False)
|
||||
place_id = await _seed(db_engine, owner_id)
|
||||
|
||||
res = await client.post("/v1/site/booking-request", json=_form(place_id))
|
||||
|
||||
assert res.json()["success"] is False
|
||||
async with db_engine.begin() as conn:
|
||||
rows = (await conn.execute(text("SELECT kind, title, detail FROM alert_outbox"))).all()
|
||||
assert [r[0] for r in rows] == ["booking_request_failed"]
|
||||
for value in ("김손님", "010-1234-5678", "guest@example.com"):
|
||||
assert value not in rows[0][1] + rows[0][2]
|
||||
@@ -0,0 +1,80 @@
|
||||
import json
|
||||
import uuid
|
||||
|
||||
from sqlalchemy import text
|
||||
|
||||
from common.enums import PostStatus
|
||||
from crud.job_crud import JobQueue
|
||||
from services import mockup_blog
|
||||
from worker.handlers import build_handler
|
||||
from worker.runner import Worker
|
||||
|
||||
MOCKUP_HTML = (
|
||||
'<html><head></head><body><div id="root">옛 마크업</div>'
|
||||
'<script>window.__SITE_PAYLOAD__ = {"site":{"slug":"stay"},"posts":[{"postId":"old","body":"옛 글","publishedAt":"2026-09-01T00:00:00+00:00"}]};</script>'
|
||||
'</body></html>'
|
||||
)
|
||||
|
||||
|
||||
def _write_mockup(tmp_path, monkeypatch, slug="stay"):
|
||||
monkeypatch.setenv("SITE_OUTPUT_DIR", str(tmp_path))
|
||||
page = tmp_path / "s" / slug
|
||||
page.mkdir(parents=True)
|
||||
(page / "index.html").write_text(MOCKUP_HTML, encoding="utf-8")
|
||||
return page / "index.html"
|
||||
|
||||
|
||||
def _posts(html: str) -> list[dict]:
|
||||
start = html.index("{", html.index(mockup_blog.PAYLOAD_MARKER))
|
||||
return json.JSONDecoder().raw_decode(html, start)[0]["posts"]
|
||||
|
||||
|
||||
def test_목업만_대상이다():
|
||||
assert mockup_blog.is_mockup("stay")
|
||||
assert mockup_blog.is_mockup("stay2")
|
||||
assert not mockup_blog.is_mockup("stay3")
|
||||
assert not mockup_blog.is_mockup("euro")
|
||||
|
||||
|
||||
def test_새_글을_더하고_옛_글은_남기고_최신순이다(tmp_path, monkeypatch):
|
||||
path = _write_mockup(tmp_path, monkeypatch)
|
||||
|
||||
count = mockup_blog.refresh_posts("stay", [
|
||||
{"post_id": "new", "body": "새 글 </script> 포함", "published_at": "2026-10-01T00:00:00+00:00"},
|
||||
{"post_id": "empty", "body": " ", "published_at": "2026-10-02T00:00:00+00:00"},
|
||||
])
|
||||
|
||||
html = path.read_text(encoding="utf-8")
|
||||
assert count == 2
|
||||
assert [p["postId"] for p in _posts(html)] == ["new", "old"]
|
||||
assert "</script> 포함" not in html
|
||||
assert '<div id="root">옛 마크업</div>' in html
|
||||
assert (path.parent / mockup_blog.BACKUP_NAME).read_text(encoding="utf-8") == MOCKUP_HTML
|
||||
|
||||
|
||||
async def test_목업_사업장_발행은_굽지_않고_글만_바꾸고_게재로_넘긴다(auth_headers, client, db_engine, tmp_path, monkeypatch):
|
||||
path = _write_mockup(tmp_path, monkeypatch)
|
||||
h = await auth_headers("mockup-owner")
|
||||
pid = (await client.post("/v1/place", headers=h, json={"name": "목업펜션", "category": 1})).json()["place"]["place_id"]
|
||||
post_id = uuid.uuid4()
|
||||
async with db_engine.begin() as c:
|
||||
owner = (await c.execute(text("SELECT owner_user_id FROM places WHERE place_id = :p"), {"p": pid})).scalar()
|
||||
await c.execute(
|
||||
text("INSERT INTO sites (site_id, place_id, status, domain) VALUES (:s, :p, 1, 'stay')"),
|
||||
{"s": uuid.uuid4(), "p": pid},
|
||||
)
|
||||
await c.execute(
|
||||
text("INSERT INTO place_posts (post_id, place_id, body, topic_kind, topic_key, status, approved_at) "
|
||||
"VALUES (:id, :p, '승인된 새 글입니다', 1, 'fog', :st, now())"),
|
||||
{"id": post_id, "p": pid, "st": PostStatus.APPROVED.value},
|
||||
)
|
||||
|
||||
await JobQueue().enqueue(4, {"place_id": pid, "owner_user_id": str(owner), "publish": True})
|
||||
assert await Worker("w", JobQueue(), build_handler(), job_deadline_sec=60).process_one() is True
|
||||
|
||||
assert [p["postId"] for p in _posts(path.read_text(encoding="utf-8"))][0] == str(post_id)
|
||||
async with db_engine.begin() as c:
|
||||
status = (await c.execute(text("SELECT status FROM place_posts WHERE post_id = :id"), {"id": post_id})).scalar()
|
||||
versions = (await c.execute(text("SELECT count(*) FROM site_versions"))).scalar()
|
||||
assert status == PostStatus.PUBLISHED.value
|
||||
assert versions == 0
|
||||
@@ -5,21 +5,7 @@ import {isoDate} from '@site/lib/format';
|
||||
import {Carousel, CarouselSlide, Modal, Section} from '@site/lib/ui';
|
||||
|
||||
/** 미니 블로그 — 사장님이 승인한 짧은 글. */
|
||||
type Season = 'spr' | 'sum' | 'aut' | 'win';
|
||||
|
||||
const SEASON_COLOR: Record<Season, string> = {
|
||||
spr: '#4f7942',
|
||||
sum: '#c9820a',
|
||||
aut: '#bf2f1b',
|
||||
win: '#3b6ea5',
|
||||
};
|
||||
|
||||
function seasonOf(month: number): Season {
|
||||
if (month >= 3 && month <= 5) return 'spr';
|
||||
if (month >= 6 && month <= 8) return 'sum';
|
||||
if (month >= 9 && month <= 11) return 'aut';
|
||||
return 'win';
|
||||
}
|
||||
const AUTOPLAY_MS = 7000;
|
||||
|
||||
/** ISO → 한국 시간 기준 월·일·요일. */
|
||||
function kstDateParts(iso: string) {
|
||||
@@ -46,9 +32,9 @@ export function BlogSection() {
|
||||
title="미니 블로그"
|
||||
lead="사장님이 남기는 숙소 이야기입니다."
|
||||
>
|
||||
<Carousel label={`${payload.place.name} 미니 블로그`} align="start" gap={0.875} loop>
|
||||
<Carousel label={`${payload.place.name} 미니 블로그`} align="start" gap={0.875} loop autoplay={AUTOPLAY_MS}>
|
||||
{posts.map((post) => (
|
||||
<CarouselSlide key={post.postId} basis="basis-[225px]">
|
||||
<CarouselSlide key={post.postId} basis="basis-[272px]">
|
||||
<PostCard post={post} onOpen={() => setOpenId(post.postId)} />
|
||||
</CarouselSlide>
|
||||
))}
|
||||
@@ -65,21 +51,29 @@ export function BlogSection() {
|
||||
|
||||
function PostCard({post, onOpen}: {post: PostEntry; onOpen: () => void}) {
|
||||
const {month, day, weekday} = kstDateParts(post.publishedAt);
|
||||
const season = seasonOf(month);
|
||||
const color = SEASON_COLOR[season];
|
||||
const dateLabel = `${month}월 ${day}일 · ${weekday}`;
|
||||
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onOpen}
|
||||
className="panel flex aspect-square w-full flex-col gap-2 p-4 text-left"
|
||||
style={{backgroundColor: `color-mix(in srgb, ${color} 9%, var(--tpl-card, #efe7d3))`}}
|
||||
aria-label={`${month}월 ${day}일 ${weekday} 글 열기`}
|
||||
className="panel flex h-full min-h-[17rem] w-full flex-col p-5 text-left"
|
||||
style={{backgroundColor: 'var(--tpl-card)'}}
|
||||
>
|
||||
<time dateTime={post.publishedAt} className="block shrink-0 text-[length:var(--fs-xs)] font-bold tracking-wide" style={{color}}>
|
||||
{dateLabel}
|
||||
<time dateTime={post.publishedAt} className="flex shrink-0 items-center gap-3">
|
||||
<span
|
||||
className="text-[2.75rem] leading-none tabular-nums"
|
||||
style={{color: 'var(--tpl-primary)', fontFamily: 'var(--tpl-font-heading)', fontWeight: 'var(--tpl-heading-weight, 700)'}}
|
||||
>
|
||||
{day}
|
||||
</span>
|
||||
<span className="flex flex-col text-[length:var(--fs-xs)] leading-snug opacity-75">
|
||||
<span>{month}월</span>
|
||||
<span>{weekday}</span>
|
||||
</span>
|
||||
</time>
|
||||
<p className="line-clamp-5 min-h-0 flex-1 whitespace-pre-line break-keep text-[length:var(--fs-xs)] leading-relaxed">
|
||||
<span aria-hidden className="my-4 block h-px w-full shrink-0" style={{backgroundColor: 'var(--tpl-border, currentColor)', opacity: 0.6}} />
|
||||
<p className="line-clamp-4 min-h-0 whitespace-pre-line break-keep text-[length:var(--fs-body)] leading-relaxed">
|
||||
{post.body}
|
||||
</p>
|
||||
</button>
|
||||
|
||||
Reference in new issue
Block a user