Compare commits
34
Commits
No files matched your search
+18
-1
@@ -47,6 +47,8 @@ SUNO_CALLBACK_URL=https://example.com/api/suno/callback
|
|||||||
# ★ 워커가 부르는 주소다. compose 로 띄우면 컨테이너 안에서 보는 주소(http://host.docker.internal:3100),
|
# ★ 워커가 부르는 주소다. compose 로 띄우면 컨테이너 안에서 보는 주소(http://host.docker.internal:3100),
|
||||||
# 백엔드를 네이티브로 돌리면 http://127.0.0.1:3100
|
# 백엔드를 네이티브로 돌리면 http://127.0.0.1:3100
|
||||||
SITE_ONTOLOGY_URL=
|
SITE_ONTOLOGY_URL=
|
||||||
|
# 새 숙소 키워드를 OpenAI 로 만든다(OPENAI_API_KEY 를 함께 쓴다). mock 이면 생성분이 매칭에 나가지 않는다.
|
||||||
|
ONTOLOGY_LLM_PROVIDER=mock
|
||||||
|
|
||||||
# 프리렌더가 절대 굽지 않는 슬러그(쉼표 구분). 손으로 만든 목업(/s/stay·stay2·stay3·stay4·stay5)
|
# 프리렌더가 절대 굽지 않는 슬러그(쉼표 구분). 손으로 만든 목업(/s/stay·stay2·stay3·stay4·stay5)
|
||||||
# 이름과 같은 슬러그로 실제 발행이 생기면 그 payload 로 목업을 덮어 구워버린다 — 비우지 않는다.
|
# 이름과 같은 슬러그로 실제 발행이 생기면 그 payload 로 목업을 덮어 구워버린다 — 비우지 않는다.
|
||||||
@@ -100,10 +102,25 @@ KAKAO_BOT_ID=
|
|||||||
KAKAO_BOT_REST_API_KEY=
|
KAKAO_BOT_REST_API_KEY=
|
||||||
# 1 이면 개발 채널로 보낸다(봇 ID 뒤에 "!"). 운영 채널이면 0.
|
# 1 이면 개발 채널로 보낸다(봇 ID 뒤에 "!"). 운영 채널이면 0.
|
||||||
KAKAO_EVENT_DEV=0
|
KAKAO_EVENT_DEV=0
|
||||||
# 미니블로그 승인 알림을 메일에 더해 연결된 카톡으로도 보낸다(Event API).
|
# 카톡이 연결된 사장님에게는 미니블로그 승인 알림을 메일 대신 카톡으로 보낸다(Event API).
|
||||||
|
# 카톡이 실패했을 때만 메일로 대체하고, 연결이 없으면 예전처럼 메일이다.
|
||||||
# ★ 오픈빌더에 이벤트 블록(스킬 연결)을 만들고 배포하기 전에는 켜지 않는다 — 켜면
|
# ★ 오픈빌더에 이벤트 블록(스킬 연결)을 만들고 배포하기 전에는 켜지 않는다 — 켜면
|
||||||
# 사장님 카톡에 빈 말풍선이 간다. 기본 꺼짐.
|
# 사장님 카톡에 빈 말풍선이 간다. 기본 꺼짐.
|
||||||
KAKAO_APPROVAL_PUSH_ENABLED=0
|
KAKAO_APPROVAL_PUSH_ENABLED=0
|
||||||
|
|
||||||
|
# 미니 블로그 재고 **자동** 채우기(매일 04:10 KST). 기본은 꺼짐 — 글은 빌더의
|
||||||
|
# [지금 생성하기] 로 사장님이 직접 만든다(2026-10-01 결정, docs/MINI_BLOG.md).
|
||||||
|
# ★ 켜면 발행된 사이트 **전체**가 대상이고 업장당 최대 30건이라, 첫 회차에 AI 호출이
|
||||||
|
# 한꺼번에 일어난다. 비용을 확인하고 켠다.
|
||||||
|
# ★ 발송(09:00)은 이 스위치와 무관하게 항상 돈다 — 손으로 만든 글도 나가야 한다.
|
||||||
|
BLOG_AUTO_DRAFTS_ENABLED=0
|
||||||
|
|
||||||
|
# 자동 스윕(생성·발송)을 받을 사장님 — user_id 를 쉼표로. **비면 전체**다.
|
||||||
|
# ★ 발행된 사이트가 전부 대상이라 테스트로 만든 중복 업장까지 매일 알림을 받는다
|
||||||
|
# (실측 2026-10-01: 발행 25곳 중 상당수가 중복·테스트 업장). 시험 운영 중에는 좁혀 둔다.
|
||||||
|
# ★ 빌더의 [지금 생성하기] 는 이 목록을 보지 않는다 — 목록 밖 사장님도 자기 글은 만든다.
|
||||||
|
# ★ 목록 밖 업장의 글은 건너뛸 뿐 버리지 않는다. 목록을 풀면 그때부터 나간다.
|
||||||
|
BLOG_AUTO_OWNER_IDS=
|
||||||
KAKAO_APPROVAL_EVENT_NAME=post_approval
|
KAKAO_APPROVAL_EVENT_NAME=post_approval
|
||||||
# [승인] 버튼이 부르는 블록 ID(오픈빌더 블록 주소의 /intent/<ID>). 그 블록에 우리 스킬이
|
# [승인] 버튼이 부르는 블록 ID(오픈빌더 블록 주소의 /intent/<ID>). 그 블록에 우리 스킬이
|
||||||
# 스킬데이터로 연결돼 있어야 한다. ★ 비우면 [승인] 버튼을 그리지 않는다(수정하기만 나간다).
|
# 스킬데이터로 연결돼 있어야 한다. ★ 비우면 [승인] 버튼을 그리지 않는다(수정하기만 나간다).
|
||||||
|
|||||||
@@ -57,6 +57,11 @@ services:
|
|||||||
<<: *common-env
|
<<: *common-env
|
||||||
# ★ 크론은 이 컨테이너에서만 돈다. 프로세스가 여럿이면 같은 시각에 중복 실행된다.
|
# ★ 크론은 이 컨테이너에서만 돈다. 프로세스가 여럿이면 같은 시각에 중복 실행된다.
|
||||||
SCHEDULER_ENABLED: "1"
|
SCHEDULER_ENABLED: "1"
|
||||||
|
# 미니 블로그 재고 자동 채우기(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)을 아래 볼륨으로 이 컨테이너 안에 마운트한
|
# ★ GSC_CREDENTIALS_HOST_FILE(호스트 경로, .env)을 아래 볼륨으로 이 컨테이너 안에 마운트한
|
||||||
# 고정 자리다. search_console_settings.load_settings() 가 실제로 읽는 건 이 값이다 —
|
# 고정 자리다. search_console_settings.load_settings() 가 실제로 읽는 건 이 값이다 —
|
||||||
# 호스트 경로를 코드에 그대로 넘기면 컨테이너 안에서 그 경로가 없어 실패한다.
|
# 호스트 경로를 코드에 그대로 넘기면 컨테이너 안에서 그 경로가 없어 실패한다.
|
||||||
|
|||||||
+4
-4
@@ -471,7 +471,7 @@ https://<발행호스트>/v1/agent/kakao/webhook
|
|||||||
|
|
||||||
| | 결정 |
|
| | 결정 |
|
||||||
|---|---|
|
|---|---|
|
||||||
| 발송 | **카톡과 메일 둘 다.** 카톡이 연결돼 있어도 메일을 같이 보낸다 — 카톡 발송은 채널 친구가 아니거나 차단했으면 실패하므로 메일이 누락을 막는다 |
|
| 발송 | **카톡이 연결돼 있으면 카톡으로만 보내고, 카톡이 실패했을 때만 메일로 대체한다**(2026-09-30 변경 — 처음엔 '카톡과 메일 둘 다'였는데 같은 알림이 두 통 가는 게 번거롭다는 지시. 카톡만 보내면 채널 친구 아님·차단·Event API 장애인 날 알림이 통째로 사라져 실패 때만 메일로 받쳤다). 연결이 없거나 스위치가 꺼져 있으면 예전처럼 메일. 카톡도 메일도 못 보내면 SENT 로 표시하지 않아 다음 스윕이 다시 시도하고 '승인 알림보내기' 는 실패로 답한다 |
|
||||||
| 승인 방식 | 메시지의 **[승인] [수정] 인라인 버튼** + 누른 사람이 **연결된 본인인지·그 글이 본인 가게 것인지 서버가 확인**. 링크가 없어 메신저 미리보기가 먼저 열어 승인되는 문제가 처음부터 없다. 승인은 기존 `PostService.approve_by_owner` 를 그대로 탄다 |
|
| 승인 방식 | 메시지의 **[승인] [수정] 인라인 버튼** + 누른 사람이 **연결된 본인인지·그 글이 본인 가게 것인지 서버가 확인**. 링크가 없어 메신저 미리보기가 먼저 열어 승인되는 문제가 처음부터 없다. 승인은 기존 `PostService.approve_by_owner` 를 그대로 탄다 |
|
||||||
| 진행 | **1단계(이 절)**: 클라이언트 + 테스트 발송으로 규격 확인. 2단계: 버튼 응답·승인 처리·발송 연결 |
|
| 진행 | **1단계(이 절)**: 클라이언트 + 테스트 발송으로 규격 확인. 2단계: 버튼 응답·승인 처리·발송 연결 |
|
||||||
|
|
||||||
@@ -529,7 +529,7 @@ cd solution/backend && .venv/bin/python scripts/kakao_event_send_test.py --key <
|
|||||||
## 2-1 진행 — 발송과 메시지 그리기 (2026-09-29)
|
## 2-1 진행 — 발송과 메시지 그리기 (2026-09-29)
|
||||||
|
|
||||||
```
|
```
|
||||||
blog_jobs._send_one 메일 + 카톡 Event API(params: post_id, edit_token) — 하나라도 나가면 SENT
|
blog_jobs._send_one 카톡 Event API(params: post_id, edit_token) — 실패했을 때만 메일로 대체, 나가면 SENT
|
||||||
오픈빌더 이벤트 블록 스킬 데이터 응답 → 우리 웹훅(POST /v1/agent/kakao/webhook)
|
오픈빌더 이벤트 블록 스킬 데이터 응답 → 우리 웹훅(POST /v1/agent/kakao/webhook)
|
||||||
kakao_bot._handle userRequest.params.post_id 가 있으면 승인 알림 요청으로 처리
|
kakao_bot._handle userRequest.params.post_id 가 있으면 승인 알림 요청으로 처리
|
||||||
channel.approval_notice 연결된 본인 가게의 글일 때만 본문 + [수정하기] 링크
|
channel.approval_notice 연결된 본인 가게의 글일 때만 본문 + [수정하기] 링크
|
||||||
@@ -542,8 +542,8 @@ channel.approval_notice 연결된 본인 가게의 글일 때만 본문 + [수
|
|||||||
- [수정하기] 는 메일의 '고쳐서 올리려면' 과 **같은 일회용 코드**다(`/v1/site/post/edit?t=`).
|
- [수정하기] 는 메일의 '고쳐서 올리려면' 과 **같은 일회용 코드**다(`/v1/site/post/edit?t=`).
|
||||||
평문은 발송 시점에만 알아서 Event API `params.edit_token` 으로 넘긴다 — 어느 쪽이든 먼저
|
평문은 발송 시점에만 알아서 Event API `params.edit_token` 으로 넘긴다 — 어느 쪽이든 먼저
|
||||||
누른 쪽이 쓴다. 코드는 카카오 서버를 지나가므로 로그에는 params 의 **키만** 남기고 값은 남기지 않는다.
|
누른 쪽이 쓴다. 코드는 카카오 서버를 지나가므로 로그에는 params 의 **키만** 남기고 값은 남기지 않는다.
|
||||||
- 메일이 나갔으면 카톡보다 먼저 SENT 로 표시한다(웹훅이 곧바로 글을 읽는다). 카톡만 나가는
|
- 카톡 발송이 성공한 **뒤에** SENT 로 표시한다(카톡이 실패하면 메일 발송 뒤). 그 사이에 웹훅이 이 글을 읽어도 되는 이유는 웹훅이
|
||||||
경우는 발송 성공 뒤에 표시하고, 웹훅은 REVIEWED 글도 읽는다.
|
REVIEWED 글도 읽고, 사장님이 버튼을 누르기까지의 시간이 그 간격보다 훨씬 길어서다.
|
||||||
- 링크 버튼은 `textCard` 로 본문(`simpleText`)과 따로 둔다 — 카드 설명 길이 제한에 글 문구가 걸리지 않게.
|
- 링크 버튼은 `textCard` 로 본문(`simpleText`)과 따로 둔다 — 카드 설명 길이 제한에 글 문구가 걸리지 않게.
|
||||||
|
|
||||||
### 콘솔에서 바꿔야 하는 것
|
### 콘솔에서 바꿔야 하는 것
|
||||||
|
|||||||
+3
-1
@@ -13,7 +13,9 @@
|
|||||||
| `partial_failure` | 노래 등 곁가지 생성 실패(발행 자체는 계속) | `song_failed:{place_id}` |
|
| `partial_failure` | 노래 등 곁가지 생성 실패(발행 자체는 계속) | `song_failed:{place_id}` |
|
||||||
| `queue_stuck` | dead-letter 누적·좀비 실행·PENDING 30분 이상 정체 | `queue_health` |
|
| `queue_stuck` | dead-letter 누적·좀비 실행·PENDING 30분 이상 정체 | `queue_health` |
|
||||||
| `recovery` | 위 dedupe_key 가 다음 정상 상태에서 풀릴 때 한 번 | 없음(매번 새 행) |
|
| `recovery` | 위 dedupe_key 가 다음 정상 상태에서 풀릴 때 한 번 | 없음(매번 새 행) |
|
||||||
| `activity` | 수집 시작·채널 실패·완료 · 사진 분석 · 첫 발행/재발행/빌드/되돌리기 시작·끝(`services/activity_feed.py`) | 없음(매번 보낸다) |
|
| `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 를 안 채웠거나 고유 콘텐츠가 없어서 막힌 건
|
★ **게이트 반려는 알리지 않는다.** 사장님이 fact 를 안 채웠거나 고유 콘텐츠가 없어서 막힌 건
|
||||||
운영자가 손댈 일이 아니다 — `build_service._fail(reason, gate=None)` 일 때만 `build_failed`.
|
운영자가 손댈 일이 아니다 — `build_service._fail(reason, gate=None)` 일 때만 `build_failed`.
|
||||||
|
|||||||
@@ -42,7 +42,7 @@ React 를 렌더해야 하고, 그때부터 디자인 수정에 백엔드 배포
|
|||||||
BUILD 잡 (worker) ─ services/build_service.py:99 run_build()
|
BUILD 잡 (worker) ─ services/build_service.py:99 run_build()
|
||||||
├ build_snapshot → 원본 데이터(JSONB)
|
├ build_snapshot → 원본 데이터(JSONB)
|
||||||
├ seo_keywords.fetch() → SiteOntology 추천을 이 가게 자료로 거른 키워드 → snapshot["seo"]
|
├ seo_keywords.fetch() → SiteOntology 추천을 이 가게 자료로 거른 키워드 → snapshot["seo"]
|
||||||
│ (숙박만 · 설정 없거나 실패하면 생략 · 발행은 계속)
|
│ (숙박만 · 처음 보는 숙소는 OpenAI 키워드 생성을 기다림 · 실패하면 생략 · 발행은 계속)
|
||||||
│ → site_versions 행 insert
|
│ → site_versions 행 insert
|
||||||
├ 1차 게이트 (DB 사실 기준) → publish_gate.evaluate()
|
├ 1차 게이트 (DB 사실 기준) → publish_gate.evaluate()
|
||||||
├ site_payload.emit_payload() → out/payloads/<slug>.json ★ 백엔드의 유일한 산출물
|
├ site_payload.emit_payload() → out/payloads/<slug>.json ★ 백엔드의 유일한 산출물
|
||||||
|
|||||||
+1
-1
@@ -276,7 +276,7 @@ COPY 단계는 `jobs.progress`(JSONB)의 `steps`·`attempt`에 기록한다.
|
|||||||
|---|---|---|
|
|---|---|---|
|
||||||
| 1 COLLECT | `collect_service.run_collect` | 채널 발견 → 검증 → 크롤링 → fact·사진 적재 |
|
| 1 COLLECT | `collect_service.run_collect` | 채널 발견 → 검증 → 크롤링 → fact·사진 적재 |
|
||||||
| 2 VISION | `vision_service.run_vision` | 사진 분류 + alt 생성 |
|
| 2 VISION | `vision_service.run_vision` | 사진 분류 + alt 생성 |
|
||||||
| 3 COPY | `copy_service.run_copy` | 소개문·FAQ (확보된 fact 만 근거) |
|
| 3 COPY | `copy_service.run_copy` | 소개문·FAQ · 숙박은 첫 화면 캐치프레이즈(fact `tagline`)와 순환 문구(fact `catchphrases`, 한 줄에 하나, `봄 \| ` · `9월 \| ` · `비 \| ` 머리) (확보된 fact 만 근거) |
|
||||||
| 4 BUILD | `build_service.run_build` | ★ 정적 빌드 + 발행 게이트 |
|
| 4 BUILD | `build_service.run_build` | ★ 정적 빌드 + 발행 게이트 |
|
||||||
| 5 LOCAL_SYNC | `story_service.run_local_sync` | 지역 이야기 생성(지역당 1회) |
|
| 5 LOCAL_SYNC | `story_service.run_local_sync` | 지역 이야기 생성(지역당 1회) |
|
||||||
| 6 AI_CHECK | 미구현 | reports 모듈이 붙을 때 |
|
| 6 AI_CHECK | 미구현 | reports 모듈이 붙을 때 |
|
||||||
|
|||||||
@@ -4,6 +4,28 @@
|
|||||||
**나중에 같은 실수를 막아 주는 것**(결정의 이유·밟은 함정·실측값)만 남긴다.
|
**나중에 같은 실수를 막아 주는 것**(결정의 이유·밟은 함정·실측값)만 남긴다.
|
||||||
2026-09-29에 요약본으로 다시 썼다. 원문 전체는 git 히스토리(이 파일의 09-29 이전 버전)에 있다.
|
2026-09-29에 요약본으로 다시 썼다. 원문 전체는 git 히스토리(이 파일의 09-29 이전 버전)에 있다.
|
||||||
|
|
||||||
|
## 2026-10-01 — 온톨로지: 새 숙소 키워드를 OpenAI 로 쌓는다 · 호텔 업종 · 숙소 검색
|
||||||
|
|
||||||
|
- 발행이 `generate:false` 로 불러 사전이 고정이었다 — 사전에 없는 숙소는 새 단어를 못 받았다.
|
||||||
|
이제 **처음 보는 숙소는 첫 발행에서 생성을 기다린다**(실측 7초, 키워드 15·질문 5). 재빌드·재발행은
|
||||||
|
30일 안이면 부르지 않는다 — 재빌드마다 부르는 창구라 조건이 없으면 저장마다 요금이 나간다.
|
||||||
|
- 생성분이 매칭에 안 나오던 이유는 `MATCH_SOURCES` 가 `llm` 을 뺀 것. 업종 뿌리(`stay`)로 거르고
|
||||||
|
brand 는 그 업체 것만 받게 해서 넣었다. **mock 생성분은 `source='mock'`** — compose 기본이 mock 이라
|
||||||
|
키 없이 띄운 환경마다 가짜 단어가 발행본에 나갈 뻔했다.
|
||||||
|
- 호텔(`stay.hotel`): 외부 분류(`places.external_category`, 없으면 상호)에 "호텔" 이면. 매칭은 펜션 사전도
|
||||||
|
받되 메타 게이트가 **자기 유형어만** 자료 없이 통과시킨다 — 호텔에 `군산 독채펜션` 이 붙지 않는다.
|
||||||
|
- `/v1/lodgings/search`: ★ 가까운 키워드를 사전 전체(7천)에서 뽑으면 상위가 아무 숙소에도 안 붙은
|
||||||
|
데이터셋 단어로 차서 `선유도 독채` 가 0건이었다 → **숙소에 연결된 키워드만** 비교한다.
|
||||||
|
★ e5-small 은 지역이 틀려도 0.85 가 나온다(`여수 호텔` → 군산 호텔 0.848) — 지역은 임계값이 아니라
|
||||||
|
**지역 이름**으로 가른다.
|
||||||
|
- ★ 로컬에서 임베딩 모델 내려받기가 Node 에서 `ECONNRESET`(terminated)으로 끊겨 3분 걸리고 실패했다.
|
||||||
|
curl 로는 받힌다. 실패한 로딩 promise 가 프로세스에 남아 **재시작 전까지 모든 임베딩이 500**이다.
|
||||||
|
- ★ 모델 캐시가 볼륨에 안 남았다 — transformers.js 4.x 는 `TRANSFORMERS_CACHE` 를 읽지 않고 node_modules 에
|
||||||
|
받는다. 컨테이너를 새로 만들 때마다 465MB 를 다시 받아 첫 발행이 60초 상한을 넘겼다 → `env.cacheDir`
|
||||||
|
로 직접 넘긴다. 재생성 후 모델 로딩 2분 49초 → 1.7초.
|
||||||
|
- 실키 검증(가짜 숙소 2곳): 메타에 `군산 시내 호텔`·`군산 오션뷰 호텔` 이 실렸고 미확인 `주차`·`애견동반`
|
||||||
|
은 안 나왔다. 백엔드 `1041 passed / 47 failed` — 47건은 이 변경 전 main 과 같은 목록.
|
||||||
|
|
||||||
## 2026-09-30 — 템플릿 검수 · 코랄 · 미니멀 · 솔숲 추가
|
## 2026-09-30 — 템플릿 검수 · 코랄 · 미니멀 · 솔숲 추가
|
||||||
|
|
||||||
- 한국 펜션 사이트(코랄트리 · 바다동화)를 참고해 `coral` · `minimal`, 디자인 스킬 시안에서 `pine`(솔숲).
|
- 한국 펜션 사이트(코랄트리 · 바다동화)를 참고해 `coral` · `minimal`, 디자인 스킬 시안에서 `pine`(솔숲).
|
||||||
|
|||||||
@@ -8,7 +8,7 @@
|
|||||||
↓
|
↓
|
||||||
새로고침 ──────────────────────→ GET /v1/job/{jobId}
|
새로고침 ──────────────────────→ GET /v1/job/{jobId}
|
||||||
↑
|
↑
|
||||||
COPY 워커: prepare → generate → save → faq_fill
|
COPY 워커: prepare → generate → save → catchphrase(숙박만) → faq_fill
|
||||||
각 단계 진입·완료 → jobs.progress(JSONB)
|
각 단계 진입·완료 → jobs.progress(JSONB)
|
||||||
↓
|
↓
|
||||||
화면: 서버 단계 표시 → DONE일 때 데이터 갱신 → editor
|
화면: 서버 단계 표시 → DONE일 때 데이터 갱신 → editor
|
||||||
|
|||||||
+22
-5
@@ -61,8 +61,23 @@
|
|||||||
`scheduler/__init__.py` 에 `add_job` 한 줄, 로직은 `scheduler/jobs.py` → `services/blog_service.py`.
|
`scheduler/__init__.py` 에 `add_job` 한 줄, 로직은 `scheduler/jobs.py` → `services/blog_service.py`.
|
||||||
|
|
||||||
- **주기**: 하루 1회(KST 새벽 04:10). `SCHEDULER_ENABLED=1` 인 프로세스에서만 돈다(이미 그 규약이다)
|
- **주기**: 하루 1회(KST 새벽 04:10). `SCHEDULER_ENABLED=1` 인 프로세스에서만 돈다(이미 그 규약이다)
|
||||||
|
- ★★ **기본으로 돌지 않는다** — `BLOG_AUTO_DRAFTS_ENABLED=1` 이어야 등록된다
|
||||||
|
(2026-10-01 대표 지시: "이거는 안보내도 될것같아"). 글은 빌더의 [지금 생성하기] 로
|
||||||
|
사장님이 직접 만든다. 켜면 발행된 사이트 **전체**가 대상이라 첫 회차에 AI 호출이
|
||||||
|
한꺼번에 일어난다 — 그 비용은 사람이 정할 일이다.
|
||||||
|
★ **발송(09:00)은 이 스위치와 무관하게 항상 돈다.** 손으로 만든 글도 나가야 한다.
|
||||||
|
★ 2026-09-30 까지는 이 잡이 **등록 자체가 없었다** — 함수와 주석("새벽에 채운다")만 있고
|
||||||
|
`add_job` 이 없어 한 번도 돈 적이 없다. 증상은 "메일이 안 온다" 로만 보이고 실제로는
|
||||||
|
보낼 글이 0건이었다. 지금은 꺼져 있다는 사실이 코드에 남는다(`scheduler/__init__.py`)
|
||||||
- **대상**: 발행된 사이트 중 재고(DRAFT+REVIEWED)가 `REFILL_BELOW`(30) 미만인 업장 —
|
- **대상**: 발행된 사이트 중 재고(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` 목록을 프롬프트에 넣어 중복을 막는다
|
- **한 번에 `BATCH_SIZE`(30)건**씩. 앞 회차의 `topic_key` 목록을 프롬프트에 넣어 중복을 막는다
|
||||||
(한 달치를 한 호출로 뽑으면 중복 검사가 안 된다)
|
(한 달치를 한 호출로 뽑으면 중복 검사가 안 된다)
|
||||||
- **배정일**: 그 업장의 `MAX(scheduled_date)` 다음날부터(없으면 오늘부터, KST) 하루 한 건씩
|
- **배정일**: 그 업장의 `MAX(scheduled_date)` 다음날부터(없으면 오늘부터, KST) 하루 한 건씩
|
||||||
@@ -122,11 +137,13 @@
|
|||||||
수정 링크로 할 수 있는 일은 **그 글 한 건의 편집·승인**뿐이다(day-pass 토큰도 `user_id`
|
수정 링크로 할 수 있는 일은 **그 글 한 건의 편집·승인**뿐이다(day-pass 토큰도 `user_id`
|
||||||
까지만 담아, 그 사장님의 다른 글은 못 건드리지 않는다 — `PostService.get_post` 가
|
까지만 담아, 그 사장님의 다른 글은 못 건드리지 않는다 — `PostService.get_post` 가
|
||||||
`place_id` 불일치를 걸러낸다)
|
`place_id` 불일치를 걸러낸다)
|
||||||
- **카톡 병행**(2026-09-29 결정: 카톡과 메일 **둘 다**): 사장님이 카카오톡을 연결했고
|
- **카톡 알림**(2026-09-30 변경: 연결돼 있으면 **카톡으로만, 실패했을 때만 메일로 대체**): 사장님이
|
||||||
`KAKAO_APPROVAL_PUSH_ENABLED=1` 이면 메일에 더해 Event API 로도 보낸다
|
카카오톡을 연결했고 `KAKAO_APPROVAL_PUSH_ENABLED=1` 이면 메일 대신 Event API 로 보낸다
|
||||||
(`blog_jobs._push_kakao`, 규격·콘솔 준비는 `docs/AGENT.md` 5단계). 카톡은 채널 친구가
|
(`blog_jobs._push_kakao`, 규격·콘솔 준비는 `docs/AGENT.md` 5단계). 처음(2026-09-29)엔 '둘 다'
|
||||||
아니거나 차단했으면 실패하므로 메일을 빼지 않는다. **하나라도 나갔으면 SENT**, 아무 데도
|
였는데 같은 알림이 두 통 가는 게 번거롭다는 지시로 바꿨다. 카톡만 보내면 채널 친구 아님·차단·
|
||||||
안 나갔으면 SENT 로 표시하지 않아 다음 스윕이 다시 시도한다. 글 본문과 [수정하기] 링크는
|
Event API 장애인 날 알림이 통째로 사라져서 **카톡이 실패했을 때만 메일로 대체**한다. 연결이
|
||||||
|
없거나 스위치가 꺼져 있으면 예전처럼 메일이다. 카톡도 메일도 못 보내면 SENT 로 표시하지 않아
|
||||||
|
다음 스윕이 다시 시도하고 '승인 알림보내기' 는 실패로 답한다. 글 본문과 [수정하기] 링크는
|
||||||
오픈빌더 이벤트 블록의 스킬(우리 웹훅)이 그린다 — params 로 글 ID 와 수정용 일회용 코드가
|
오픈빌더 이벤트 블록의 스킬(우리 웹훅)이 그린다 — params 로 글 ID 와 수정용 일회용 코드가
|
||||||
가고, 웹훅이 **연결된 본인 가게의 글인지 다시 확인한 뒤에만** 본문을 준다
|
가고, 웹훅이 **연결된 본인 가게의 글인지 다시 확인한 뒤에만** 본문을 준다
|
||||||
(`channel.approval_notice`).
|
(`channel.approval_notice`).
|
||||||
|
|||||||
@@ -49,6 +49,14 @@
|
|||||||
- 같은 목록의 카드는 같은 크기: 사진은 고정 비율 + `object-fit:cover`, 글은 줄 수 말줄임
|
- 같은 목록의 카드는 같은 크기: 사진은 고정 비율 + `object-fit:cover`, 글은 줄 수 말줄임
|
||||||
- 칸 수는 항목 수에 맞춘다(`repeat(auto-fit, minmax(…))`). 3개인데 4칸을 잡아 빈칸을 남기지 않는다
|
- 칸 수는 항목 수에 맞춘다(`repeat(auto-fit, minmax(…))`). 3개인데 4칸을 잡아 빈칸을 남기지 않는다
|
||||||
|
|
||||||
|
### 사진 카드는 하나다 — `layouts/kit/Card.tsx` `PhotoCard`
|
||||||
|
|
||||||
|
- 주변 안내 · 축제 · 명소 · 인물(사진 있을 때)은 모두 `PhotoCard` 를 쓴다. 템플릿마다 카드를 새로 짓지 않는다
|
||||||
|
- 모양: 사진(3:2) 아래에 제목 1줄 · 거리나 날짜 1줄 · 설명 2줄. 템플릿별로 다른 것은 `--kc-*` 변수만
|
||||||
|
(`--kc-r` 사진 모서리, `--kc-tf`·`--kc-tw` 제목 글꼴·굵기, `--kc-mc` 거리 색, 상자형은 `--kc-bg`·`--kc-box-r`)
|
||||||
|
- 사진 없는 목록(맛집 · 홈 가까운 곳 목록)은 행(row)으로 쓴다. 한 섹션 안에서 카드와 행을 섞지 않는다
|
||||||
|
- 모바일 캐러셀 화살표는 숨긴다(카드 위를 가린다). 1024px 이상에서만 사진 가운데 높이에 둔다
|
||||||
|
|
||||||
## 4. 섹션 머리
|
## 4. 섹션 머리
|
||||||
|
|
||||||
- **제목은 위, 내용은 아래.** 참고한 펜션 사이트들이 모두 이 방식이다
|
- **제목은 위, 내용은 아래.** 참고한 펜션 사이트들이 모두 이 방식이다
|
||||||
@@ -77,6 +85,13 @@
|
|||||||
|
|
||||||
## 6. 값 보여주기
|
## 6. 값 보여주기
|
||||||
|
|
||||||
|
- **첫 화면은 캐치프레이즈 한 줄(고정) → 그 아래 순환 문구.** `/s/stay` 목업과 같다(`sections/HeroCatchphrase.tsx`)
|
||||||
|
- 캐치프레이즈 = `narrative.tagline`. 없으면 공통 문구 10개 중 사이트마다 정해진 하나
|
||||||
|
- 순환 = `narrative.catchphrases`, 일반 → 계절 → 일반 → 월 → 일반 → 날씨 순서, 6초. 없으면 줄을 두지 않는다
|
||||||
|
- 두 값은 COPY 잡이 소개문과 함께 만든다(fact `tagline` · `catchphrases`, `services/copy_steps.py`)
|
||||||
|
- 첫 화면에 태그·칩(‘주차 가능’, 지역 말풍선)을 두지 않는다
|
||||||
|
- 부티크 첫 화면은 모바일도 문(아치) 모양이다. 전체화면 사진으로 되돌리지 않는다
|
||||||
|
|
||||||
- **‘가능 · 있음’은 ✓, ‘불가 · 없음’은 ✕ 목록으로 쓴다.** `주차 / 가능` 같은 표로 쓰지 않는다
|
- **‘가능 · 있음’은 ✓, ‘불가 · 없음’은 ✕ 목록으로 쓴다.** `주차 / 가능` 같은 표로 쓰지 않는다
|
||||||
- 마크업: `<ul class="amen"><li class="on"><i class="ic">✓</i><span><b>주차</b> 가능</span></li>`
|
- 마크업: `<ul class="amen"><li class="on"><i class="ic">✓</i><span><b>주차</b> 가능</span></li>`
|
||||||
- 색: ✓ `#15803d`, ✕ `#c2410c`. 가능한 것을 먼저 놓는다
|
- 색: ✓ `#15803d`, ✕ `#c2410c`. 가능한 것을 먼저 놓는다
|
||||||
@@ -91,6 +106,7 @@
|
|||||||
- 같은 동작은 한 이름: 예약 시트를 여는 버튼은 모두 **‘예약하기’**, 이용안내 탭으로 가는 버튼은 **‘이용안내 보기’**
|
- 같은 동작은 한 이름: 예약 시트를 여는 버튼은 모두 **‘예약하기’**, 이용안내 탭으로 가는 버튼은 **‘이용안내 보기’**
|
||||||
- 버튼 글자가 두 줄로 접히면 안 된다. 모바일에서 버튼이 3개 이상이면 2열 격자로, 남는 하나는 한 줄 전체
|
- 버튼 글자가 두 줄로 접히면 안 된다. 모바일에서 버튼이 3개 이상이면 2열 격자로, 남는 하나는 한 줄 전체
|
||||||
- 키보드 포커스와 글자 선택색은 템플릿 색으로(`kit/kit.css`)
|
- 키보드 포커스와 글자 선택색은 템플릿 색으로(`kit/kit.css`)
|
||||||
|
- 상세·예약 창(`paper/Sheet.tsx`)은 모든 폭에서 **화면 가운데** 뜬다. 폭 560px 이하, 모서리는 템플릿의 `--k-r`
|
||||||
|
|
||||||
## 8. 하지 않는 것
|
## 8. 하지 않는 것
|
||||||
|
|
||||||
|
|||||||
+7
-3
@@ -2,7 +2,9 @@
|
|||||||
|
|
||||||
o2o-site-AEO 가 발행한 사이트에 **업체별 SEO/AEO 키워드**를 제공하는 온톨로지 서비스.
|
o2o-site-AEO 가 발행한 사이트에 **업체별 SEO/AEO 키워드**를 제공하는 온톨로지 서비스.
|
||||||
|
|
||||||
- **고정 데이터셋 1회 적재** 정책 — 주기 수집 없음 (`data/gunsan-pension-keywords.json`, 1,000건)
|
- 사전은 **고정 데이터셋 + 업체별 LLM 생성분**이다. 처음 보는 숙소가 발행되면 OpenAI 로 키워드를 만들어
|
||||||
|
쌓고(`source='llm'`), 이후 매칭 후보가 된다. mock 이 만든 단어는 `source='mock'` 으로 남아 후보가 되지 않는다
|
||||||
|
- 업종은 숙박(`stay`) 아래 펜션(`stay.pension`)·호텔(`stay.hotel`). 매칭·검색은 뿌리(`stay`)로 묶는다
|
||||||
- 로컬 임베딩(`multilingual-e5-small`, 384차원)으로 pgvector 에 적재 후 의미 검색
|
- 로컬 임베딩(`multilingual-e5-small`, 384차원)으로 pgvector 에 적재 후 의미 검색
|
||||||
- 업체명 또는 자연어 문장 → 사전에서 잘 맞는 키워드를 골라주는 **매칭 API + 데모 콘솔**
|
- 업체명 또는 자연어 문장 → 사전에서 잘 맞는 키워드를 골라주는 **매칭 API + 데모 콘솔**
|
||||||
- 어휘 단계 중복제거는 자동, 벡터 근접쌍은 자동 병합하지 않고 검토 목록으로만
|
- 어휘 단계 중복제거는 자동, 벡터 근접쌍은 자동 병합하지 않고 검토 목록으로만
|
||||||
@@ -245,13 +247,14 @@ npm run dataset:ingest && npm run dataset:ingest-nationwide
|
|||||||
| 메서드 | 경로 | 용도 |
|
| 메서드 | 경로 | 용도 |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
| `GET` | `/health` | 헬스체크 |
|
| `GET` | `/health` | 헬스체크 |
|
||||||
| `POST` | `/v1/merchants/publish` | **사이트 발행 웹훅** — 업체 upsert + 생성 예약 (`sync:true` 면 동기 실행) |
|
| `POST` | `/v1/merchants/publish` | **사이트 발행 웹훅** — 업체 upsert + 생성. 처음 보는 업체·`REFRESH_INTERVAL_DAYS` 지난 업체만 생성하고, `sync:true` 는 처음 보는 업체에만 동기로 기다린다. 동기 생성이 실패해도 200 (`generation.failed`) |
|
||||||
| `POST` | `/v1/merchants/:id/generate?sync=true` | 수동 재생성 |
|
| `POST` | `/v1/merchants/:id/generate?sync=true` | 수동 재생성 |
|
||||||
| `GET` | `/v1/merchants` `/v1/merchants/:id` | 조회 |
|
| `GET` | `/v1/merchants` `/v1/merchants/:id` | 조회 |
|
||||||
| `GET` | `/v1/sites/:id/seo?limit=20` | **발행 사이트가 렌더링 시 호출** — title/description/keywords/tags |
|
| `GET` | `/v1/sites/:id/seo?limit=20` | **발행 사이트가 렌더링 시 호출** — title/description/keywords/tags |
|
||||||
| `GET` | `/v1/sites/:id/aeo?limit=10` | 답변엔진용 topics/FAQ/structuredDataHints |
|
| `GET` | `/v1/sites/:id/aeo?limit=10` | 답변엔진용 topics/FAQ/structuredDataHints |
|
||||||
| `POST` | `/v1/match` | **업체명 또는 문장 → 사전에서 잘 맞는 키워드.** `mode=fusion`(기본) / `single`(통짜, 비교용) |
|
| `POST` | `/v1/match` | **업체명 또는 문장 → 사전에서 잘 맞는 키워드.** `mode=fusion`(기본) / `single`(통짜, 비교용) |
|
||||||
| `POST` | `/v1/keywords/search` | 의미 기반 키워드 검색 (어드민) |
|
| `POST` | `/v1/keywords/search` | 의미 기반 키워드 검색 (어드민) |
|
||||||
|
| `POST` | `/v1/lodgings/search` | **검색어 → 맞는 숙소와 각 숙소의 SEO 메타.** 숙소에 연결된 키워드와의 유사도(≥0.87, 표기 변형은 aliases) + 지역 이름. 검색어가 지역을 말하면 그 지역 숙소만 |
|
||||||
| `GET` | `/demo` | 매칭 콘솔 (로컬 확인용) |
|
| `GET` | `/demo` | 매칭 콘솔 (로컬 확인용) |
|
||||||
| `POST` | `/v1/sites/:id/performance` | Search Console·유입 로그 피드백 → 저성과 키워드 강등 |
|
| `POST` | `/v1/sites/:id/performance` | Search Console·유입 로그 피드백 → 저성과 키워드 강등 |
|
||||||
|
|
||||||
@@ -401,7 +404,8 @@ curl -s -X POST http://localhost:3100/v1/match \
|
|||||||
|
|
||||||
## 생성 주기
|
## 생성 주기
|
||||||
|
|
||||||
- **발행 즉시** — `/v1/merchants/publish` 가 BullMQ 에 적재 (60초 dedupe 창)
|
- **첫 발행** — 처음 보는 업체는 `/v1/merchants/publish` 가 동기로 생성한다 (o2o-site-AEO 가 `sync:true` 로 부른다)
|
||||||
|
- **기한 지난 업체의 발행** — BullMQ 에 적재 (60초 dedupe 창). 기한 안이면 생성하지 않는다(`generation: 'fresh'`)
|
||||||
- **주기 리프레시** — 매일 03:00 크론이 `REFRESH_INTERVAL_DAYS`(기본 30일) 지난 업체를 적재
|
- **주기 리프레시** — 매일 03:00 크론이 `REFRESH_INTERVAL_DAYS`(기본 30일) 지난 업체를 적재
|
||||||
- **성과 기반** — 노출 100회 이상 & CTR < 0.2% 인 키워드는 `demoted` 로 강등, 다음 사이클에서 대체
|
- **성과 기반** — 노출 100회 이상 & CTR < 0.2% 인 키워드는 `demoted` 로 강등, 다음 사이클에서 대체
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,4 @@
|
|||||||
|
-- 호텔 업종. o2o-site-AEO 가 외부 분류에 "호텔" 이 있는 숙소를 stay.hotel 로 보낸다.
|
||||||
|
-- ★ 시드에만 두면 이미 떠 있는 DB 에는 없고, merchant.industry_id 외래키 위반으로 publish 가 500 이 된다.
|
||||||
|
INSERT INTO industry (id, path, name) VALUES ('stay.hotel', 'stay.hotel', '호텔')
|
||||||
|
ON CONFLICT (id) DO NOTHING;
|
||||||
@@ -18,6 +18,8 @@ export const env = {
|
|||||||
embedding: {
|
embedding: {
|
||||||
provider: (process.env.EMBEDDING_PROVIDER ?? 'local') as 'mock' | 'local' | 'openai',
|
provider: (process.env.EMBEDDING_PROVIDER ?? 'local') as 'mock' | 'local' | 'openai',
|
||||||
localModel: process.env.EMBEDDING_LOCAL_MODEL ?? 'Xenova/multilingual-e5-small',
|
localModel: process.env.EMBEDDING_LOCAL_MODEL ?? 'Xenova/multilingual-e5-small',
|
||||||
|
// transformers.js 4.x 는 이 변수를 읽지 않아 node_modules 에 받는다 — 볼륨에 남기려면 직접 넘긴다.
|
||||||
|
cacheDir: process.env.TRANSFORMERS_CACHE || null,
|
||||||
},
|
},
|
||||||
dedup: {
|
dedup: {
|
||||||
cosineThreshold: num(process.env.DEDUP_COSINE_THRESHOLD, 0.99),
|
cosineThreshold: num(process.env.DEDUP_COSINE_THRESHOLD, 0.99),
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ const industries = [
|
|||||||
['health.dental', 'health.dental', '치과'],
|
['health.dental', 'health.dental', '치과'],
|
||||||
['stay', 'stay', '숙박'],
|
['stay', 'stay', '숙박'],
|
||||||
['stay.pension', 'stay.pension', '펜션'],
|
['stay.pension', 'stay.pension', '펜션'],
|
||||||
|
['stay.hotel', 'stay.hotel', '호텔'],
|
||||||
];
|
];
|
||||||
|
|
||||||
const regions = [
|
const regions = [
|
||||||
|
|||||||
@@ -19,7 +19,8 @@ export class LocalEmbeddingProvider extends EmbeddingProvider {
|
|||||||
if (!this.loading) {
|
if (!this.loading) {
|
||||||
this.loading = (async () => {
|
this.loading = (async () => {
|
||||||
const t0 = Date.now();
|
const t0 = Date.now();
|
||||||
const { pipeline } = await esmImport('@huggingface/transformers');
|
const { pipeline, env: tf } = await esmImport('@huggingface/transformers');
|
||||||
|
if (env.embedding.cacheDir) tf.cacheDir = env.embedding.cacheDir;
|
||||||
const fe = await pipeline('feature-extraction', env.embedding.localModel);
|
const fe = await pipeline('feature-extraction', env.embedding.localModel);
|
||||||
this.logger.log(`model ready: ${env.embedding.localModel} (${Date.now() - t0}ms)`);
|
this.logger.log(`model ready: ${env.embedding.localModel} (${Date.now() - t0}ms)`);
|
||||||
this.extractor = fe;
|
this.extractor = fe;
|
||||||
|
|||||||
@@ -103,6 +103,7 @@ export class GenerationService {
|
|||||||
locale: 'ko-KR',
|
locale: 'ko-KR',
|
||||||
industryId: merchant.industry_id,
|
industryId: merchant.industry_id,
|
||||||
regionId: merchant.region_id,
|
regionId: merchant.region_id,
|
||||||
|
source: keywordSource(this.llm.name),
|
||||||
});
|
});
|
||||||
|
|
||||||
stats.details.push({
|
stats.details.push({
|
||||||
@@ -214,3 +215,8 @@ export class GenerationService {
|
|||||||
return created;
|
return created;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// mock 이 만든 단어를 'llm' 으로 두면 매칭 후보가 되어 가짜 단어가 발행본에 나간다.
|
||||||
|
function keywordSource(provider: string): string {
|
||||||
|
return provider === 'mock' ? 'mock' : 'llm';
|
||||||
|
}
|
||||||
@@ -26,6 +26,8 @@ export interface ResolveInput {
|
|||||||
locale: string;
|
locale: string;
|
||||||
industryId: string | null;
|
industryId: string | null;
|
||||||
regionId: string | null;
|
regionId: string | null;
|
||||||
|
/** 새로 등록될 때 keyword.source — 매칭 후보 여부가 이 값으로 갈린다 */
|
||||||
|
source: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 4단계 계단식 중복제거. */
|
/** 4단계 계단식 중복제거. */
|
||||||
@@ -98,6 +100,7 @@ export class DedupService {
|
|||||||
embedding: input.embedding,
|
embedding: input.embedding,
|
||||||
industryId: input.industryId,
|
industryId: input.industryId,
|
||||||
regionId: input.regionId,
|
regionId: input.regionId,
|
||||||
|
source: input.source,
|
||||||
});
|
});
|
||||||
return { action: 'created', keywordId: created.id, canonical: created.canonical };
|
return { action: 'created', keywordId: created.id, canonical: created.canonical };
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -81,11 +81,12 @@ export class KeywordRepository {
|
|||||||
embedding: number[];
|
embedding: number[];
|
||||||
industryId: string | null;
|
industryId: string | null;
|
||||||
regionId: string | null;
|
regionId: string | null;
|
||||||
|
source: string;
|
||||||
}): Promise<KeywordRow> {
|
}): Promise<KeywordRow> {
|
||||||
const rows = await this.sql<KeywordRow[]>`
|
const rows = await this.sql<KeywordRow[]>`
|
||||||
INSERT INTO keyword (canonical, normalized, locale, intent, embedding, industry_id, region_id, usage_count)
|
INSERT INTO keyword (canonical, normalized, locale, intent, embedding, industry_id, region_id, usage_count, source)
|
||||||
VALUES (${input.canonical}, ${input.normalized}, ${input.locale}, ${input.intent},
|
VALUES (${input.canonical}, ${input.normalized}, ${input.locale}, ${input.intent},
|
||||||
${toVector(input.embedding)}::vector, ${input.industryId}, ${input.regionId}, 0)
|
${toVector(input.embedding)}::vector, ${input.industryId}, ${input.regionId}, 0, ${input.source})
|
||||||
ON CONFLICT (normalized, locale) DO UPDATE SET updated_at = now()
|
ON CONFLICT (normalized, locale) DO UPDATE SET updated_at = now()
|
||||||
RETURNING id, canonical, normalized, aliases, intent, usage_count`;
|
RETURNING id, canonical, normalized, aliases, intent, usage_count`;
|
||||||
return rows[0];
|
return rows[0];
|
||||||
|
|||||||
@@ -92,6 +92,10 @@ const SYSTEM_PROMPT = `당신은 한국 로컬 비즈니스 SEO/AEO 전문가입
|
|||||||
- 지역명 + 업종 + 의도어 조합을 적극 활용합니다.
|
- 지역명 + 업종 + 의도어 조합을 적극 활용합니다.
|
||||||
- 과장광고 표현(최고, 1위, 100%, 무조건, 완치 등)은 절대 사용하지 않습니다.
|
- 과장광고 표현(최고, 1위, 100%, 무조건, 완치 등)은 절대 사용하지 않습니다.
|
||||||
- 제공된 "이미 보유한 키워드"와 의미가 겹치는 것은 생성하지 않습니다.
|
- 제공된 "이미 보유한 키워드"와 의미가 겹치는 것은 생성하지 않습니다.
|
||||||
|
- 시설·전망·객실 유형은 "상세"의 features·nearby 에 있는 것만 씁니다. 없는 것을 지어내지 않습니다.
|
||||||
|
- "상세"의 unverified 에 있는 항목은 확인되지 않은 것이므로 키워드와 답변 어디에도 쓰지 않습니다.
|
||||||
|
- 숙박 유형어는 주어진 업종의 것만 씁니다. 업종이 호텔이면 '펜션'을, 펜션이면 '호텔'을 붙이지 않습니다.
|
||||||
|
- 가격·최저가·할인 같은 가격 주장은 쓰지 않습니다.
|
||||||
- relevance 는 해당 업체와의 관련도를 0.0~1.0 으로 매깁니다.
|
- relevance 는 해당 업체와의 관련도를 0.0~1.0 으로 매깁니다.
|
||||||
- 답변(answer)은 2~3문장, 업체 정보에 근거한 사실만 씁니다.`;
|
- 답변(answer)은 2~3문장, 업체 정보에 근거한 사실만 씁니다.`;
|
||||||
|
|
||||||
|
|||||||
@@ -1,10 +1,13 @@
|
|||||||
import { Body, Controller, Get, Param, Post, Query } from '@nestjs/common';
|
import { Body, Controller, Get, Logger, Param, Post, Query } from '@nestjs/common';
|
||||||
|
import { env } from '../config/env';
|
||||||
import { GenerationService } from '../generation/generation.service';
|
import { GenerationService } from '../generation/generation.service';
|
||||||
import { GenerationQueue } from '../generation/generation.queue';
|
import { GenerationQueue } from '../generation/generation.queue';
|
||||||
import { MerchantsService, UpsertMerchantDto } from './merchants.service';
|
import { MerchantsService, UpsertMerchantDto } from './merchants.service';
|
||||||
|
|
||||||
@Controller('v1/merchants')
|
@Controller('v1/merchants')
|
||||||
export class MerchantsController {
|
export class MerchantsController {
|
||||||
|
private readonly logger = new Logger(MerchantsController.name);
|
||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
private readonly merchants: MerchantsService,
|
private readonly merchants: MerchantsService,
|
||||||
private readonly generation: GenerationService,
|
private readonly generation: GenerationService,
|
||||||
@@ -21,15 +24,25 @@ export class MerchantsController {
|
|||||||
return this.merchants.findWithTaxonomy(id);
|
return this.merchants.findWithTaxonomy(id);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** o2o-site-AEO 사이트 발행 웹훅: 업체 등록 + 키워드 생성 예약 */
|
/** 발행 웹훅 — 재빌드마다 불리므로 처음 보는 업체·기한 지난 업체만 생성해 LLM 요금을 묶는다 */
|
||||||
@Post('publish')
|
@Post('publish')
|
||||||
async publish(@Body() dto: UpsertMerchantDto & { generate?: boolean; sync?: boolean }) {
|
async publish(@Body() dto: UpsertMerchantDto & { generate?: boolean; sync?: boolean }) {
|
||||||
const merchant = await this.merchants.upsert(dto);
|
const merchant = await this.merchants.upsert(dto);
|
||||||
if (dto.generate === false) return { merchant, generation: 'skipped' };
|
if (dto.generate === false) return { merchant, generation: 'skipped' };
|
||||||
|
if (!this.merchants.isStale(merchant, env.generation.refreshIntervalDays)) {
|
||||||
|
return { merchant, generation: 'fresh' };
|
||||||
|
}
|
||||||
|
|
||||||
if (dto.sync) {
|
// 첫 발행부터 새 키워드가 실리도록 처음 보는 업체만 기다린다. 실패해도 사전 키워드로 발행은 나간다.
|
||||||
|
if (dto.sync && merchant.last_generated_at === null) {
|
||||||
|
try {
|
||||||
const stats = await this.generation.runForMerchant(merchant.id, 'published');
|
const stats = await this.generation.runForMerchant(merchant.id, 'published');
|
||||||
return { merchant, generation: stats };
|
return { merchant, generation: { ...stats, details: undefined } };
|
||||||
|
} catch (err) {
|
||||||
|
const message = err instanceof Error ? err.message : String(err);
|
||||||
|
this.logger.warn(`[${merchant.name}] 동기 생성 실패 — 사전 키워드로만 매칭된다: ${message}`);
|
||||||
|
return { merchant, generation: { failed: true, error: message } };
|
||||||
|
}
|
||||||
}
|
}
|
||||||
const jobId = await this.queue.enqueue(merchant.id, 'published');
|
const jobId = await this.queue.enqueue(merchant.id, 'published');
|
||||||
return { merchant, generation: { queued: true, jobId } };
|
return { merchant, generation: { queued: true, jobId } };
|
||||||
|
|||||||
@@ -83,6 +83,12 @@ export class MerchantsService {
|
|||||||
LIMIT ${limit}`;
|
LIMIT ${limit}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** findStale 과 같은 기준을 행 하나에 — publish 가 생성 여부를 정할 때 쓴다 */
|
||||||
|
isStale(merchant: Pick<MerchantRow, 'last_generated_at'>, intervalDays: number): boolean {
|
||||||
|
if (!merchant.last_generated_at) return true;
|
||||||
|
return Date.now() - new Date(merchant.last_generated_at).getTime() > intervalDays * 86_400_000;
|
||||||
|
}
|
||||||
|
|
||||||
async markGenerated(merchantId: string) {
|
async markGenerated(merchantId: string) {
|
||||||
await this.sql`UPDATE merchant SET last_generated_at = now() WHERE id = ${merchantId}`;
|
await this.sql`UPDATE merchant SET last_generated_at = now() WHERE id = ${merchantId}`;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -114,7 +114,7 @@ export function checkAmenity(keyword: string, facts: MerchantFacts): AmenityVerd
|
|||||||
}
|
}
|
||||||
|
|
||||||
// ──────────────────────────────────────────── 서브 질의 빌더
|
// ──────────────────────────────────────────── 서브 질의 빌더
|
||||||
const STAY_TYPE_HINTS = ['독채', '풀빌라', '스테이', '펜션', '글램핑', '카라반', '한옥', '민박', '감성'];
|
const STAY_TYPE_HINTS = ['독채', '풀빌라', '스테이', '펜션', '호텔', '리조트', '글램핑', '카라반', '한옥', '민박', '감성'];
|
||||||
const CAPACITY_TOKEN = /\d+\s*인|기준|최대|소규모|중규모|대규모|수용/;
|
const CAPACITY_TOKEN = /\d+\s*인|기준|최대|소규모|중규모|대규모|수용/;
|
||||||
|
|
||||||
/** 레인 설계 원칙 1. 레인끼리 겹치지 않게 한다. */
|
/** 레인 설계 원칙 1. 레인끼리 겹치지 않게 한다. */
|
||||||
|
|||||||
@@ -15,6 +15,8 @@ const LANE_DEPTH = 50; // 레인당 후보 깊이 — 깊을수록 generic
|
|||||||
const LANE_FLOOR = 0.80; // 이 코사인 미만은 그 레인에서 기여하지 않는다
|
const LANE_FLOOR = 0.80; // 이 코사인 미만은 그 레인에서 기여하지 않는다
|
||||||
// 매칭 후보로 인정하는 출처.
|
// 매칭 후보로 인정하는 출처.
|
||||||
const MATCH_SOURCES = ['dataset', 'nationwide', 'manual'];
|
const MATCH_SOURCES = ['dataset', 'nationwide', 'manual'];
|
||||||
|
// LLM 이 만든 키워드도 후보다. 단 intent=brand 는 남의 상호이므로 그 업체 것만 받는다.
|
||||||
|
const LLM_SOURCE = 'llm';
|
||||||
|
|
||||||
interface Hit {
|
interface Hit {
|
||||||
id: string; canonical: string; intent: string; kind: string;
|
id: string; canonical: string; intent: string; kind: string;
|
||||||
@@ -49,8 +51,9 @@ export class MatchService {
|
|||||||
const vectors = await this.embedder.embed(lanes.map((l) => l.text), 'query');
|
const vectors = await this.embedder.embed(lanes.map((l) => l.text), 'query');
|
||||||
|
|
||||||
// 레인별 검색.
|
// 레인별 검색.
|
||||||
|
// 잎(stay.pension)이 아니라 뿌리(stay)로 좁힌다 — 펜션·호텔이 서로의 관련 키워드를 받고, 틀린 유형어는 호출측이 뺀다.
|
||||||
const perLane = await Promise.all(
|
const perLane = await Promise.all(
|
||||||
vectors.map((v) => this.laneSearch(v, LANE_DEPTH, merchant?.industry_id ?? null)),
|
vectors.map((v) => this.laneSearch(v, LANE_DEPTH, industryRoot(merchant?.industry_path), merchant?.id ?? null)),
|
||||||
);
|
);
|
||||||
|
|
||||||
// 가중 RRF 융합
|
// 가중 RRF 융합
|
||||||
@@ -138,17 +141,22 @@ export class MatchService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private async laneSearch(
|
private async laneSearch(
|
||||||
embedding: number[], limit: number, industryId: string | null,
|
embedding: number[], limit: number, root: string | null, merchantId: string | null,
|
||||||
): Promise<Hit[]> {
|
): Promise<Hit[]> {
|
||||||
const vec = toVector(embedding);
|
const vec = toVector(embedding);
|
||||||
const rows = await this.sql<Hit[]>`
|
const rows = await this.sql<Hit[]>`
|
||||||
SELECT id, canonical, intent, kind, category, aliases,
|
SELECT k.id, k.canonical, k.intent, k.kind, k.category, k.aliases,
|
||||||
1 - (embedding <=> ${vec}::vector) AS score
|
1 - (k.embedding <=> ${vec}::vector) AS score
|
||||||
FROM keyword
|
FROM keyword k
|
||||||
WHERE embedding IS NOT NULL
|
LEFT JOIN industry i ON i.id = k.industry_id
|
||||||
AND source = ANY(${MATCH_SOURCES})
|
WHERE k.embedding IS NOT NULL
|
||||||
AND (${industryId}::text IS NULL OR industry_id IS NULL OR industry_id = ${industryId})
|
AND (k.source = ANY(${MATCH_SOURCES})
|
||||||
ORDER BY embedding <=> ${vec}::vector
|
OR (k.source = ${LLM_SOURCE}
|
||||||
|
AND (k.intent <> 'brand'
|
||||||
|
OR EXISTS (SELECT 1 FROM merchant_keyword mk
|
||||||
|
WHERE mk.keyword_id = k.id AND mk.merchant_id = ${merchantId}::uuid))))
|
||||||
|
AND (${root}::text IS NULL OR k.industry_id IS NULL OR i.path <@ ${root}::ltree)
|
||||||
|
ORDER BY k.embedding <=> ${vec}::vector
|
||||||
LIMIT ${limit}`;
|
LIMIT ${limit}`;
|
||||||
return rows.map((r) => ({ ...r, score: Number(r.score) }));
|
return rows.map((r) => ({ ...r, score: Number(r.score) }));
|
||||||
}
|
}
|
||||||
@@ -185,11 +193,16 @@ export class MatchService {
|
|||||||
async dictionarySize() {
|
async dictionarySize() {
|
||||||
const [row] = await this.sql<Array<{ n: number }>>`
|
const [row] = await this.sql<Array<{ n: number }>>`
|
||||||
SELECT count(*)::int AS n FROM keyword
|
SELECT count(*)::int AS n FROM keyword
|
||||||
WHERE embedding IS NOT NULL AND source = ANY(${MATCH_SOURCES})`;
|
WHERE embedding IS NOT NULL AND (source = ANY(${MATCH_SOURCES}) OR source = ${LLM_SOURCE})`;
|
||||||
return row?.n ?? 0;
|
return row?.n ?? 0;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 'stay.pension' → 'stay'. 업종이 없으면 null(좁히지 않는다) */
|
||||||
|
export function industryRoot(path: string | null | undefined): string | null {
|
||||||
|
return path ? path.split('.')[0] : null;
|
||||||
|
}
|
||||||
|
|
||||||
function str(v: unknown): string[] {
|
function str(v: unknown): string[] {
|
||||||
return Array.isArray(v) ? v.filter((x): x is string => typeof x === 'string') : [];
|
return Array.isArray(v) ? v.filter((x): x is string => typeof x === 'string') : [];
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,11 +7,11 @@ import { EmbeddingProvider } from '../embedding/types';
|
|||||||
import { MerchantsService, MerchantWithTaxonomy } from '../merchants/merchants.service';
|
import { MerchantsService, MerchantWithTaxonomy } from '../merchants/merchants.service';
|
||||||
|
|
||||||
const LODGING_ROOT = 'stay';
|
const LODGING_ROOT = 'stay';
|
||||||
// 검색어 하나당 살펴볼 가까운 키워드 수. 한 숙소가 연결한 키워드는 15개 안팎이라 이 정도면 겹친다.
|
// 검색어 하나당 살펴볼 가까운 키워드 수(숙소에 연결된 키워드 중에서).
|
||||||
const SEARCH_KEYWORD_DEPTH = 60;
|
const SEARCH_KEYWORD_DEPTH = 60;
|
||||||
// ★ 짧은 한글 키워드는 전혀 다른 말도 코사인이 높다(dedup.service 실측: '선유도 펜션' ↔ '새만금 펜션' = 0.936).
|
// e5-small 에서 맞는 숙소는 0.87 이상, 동떨어진 숙소는 0.86 아래로 갈린다. 지역 구분은 이 값이 아니라 지역 이름으로 한다.
|
||||||
// 그래서 벡터 갈래는 이 값 이상만 "같은 뜻" 으로 치고, 지역 구분은 벡터가 아니라 위치 갈래에 맡긴다.
|
// ponytail: 고정 임계값 — 숙소가 늘어 경계가 흐려지면 1위 대비 상대 컷으로 바꾼다.
|
||||||
const SEARCH_FLOOR = 0.94;
|
const SEARCH_FLOOR = 0.87;
|
||||||
const SEARCH_SEO_KEYWORDS = 20;
|
const SEARCH_SEO_KEYWORDS = 20;
|
||||||
|
|
||||||
export interface SeoPayload {
|
export interface SeoPayload {
|
||||||
@@ -181,18 +181,7 @@ export class ServingService {
|
|||||||
return row?.n ?? 0;
|
return row?.n ?? 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/** 검색어 → 맞는 숙소(숙박 전체)와 SEO 메타. 키워드 갈래 + 지역 갈래, 지역을 말하면 그 지역만 */
|
||||||
* 검색어 → 그 말로 찾을 만한 숙소와 각 숙소의 SEO 메타.
|
|
||||||
*
|
|
||||||
* 두 갈래를 합친다.
|
|
||||||
* 키워드 — 검색어와 가까운 키워드(표기 변형은 aliases 로 흡수돼 있다)를 **가진** 숙소
|
|
||||||
* 위치 — 검색어에 지역 이름이 들어 있으면 그 지역(하위 포함) 숙소
|
|
||||||
* 위치가 맞는 숙소를 앞에 둔다. `군산 오션뷰` 로 찾는데 여수 오션뷰 숙소가 먼저 나오면 틀린 답이다.
|
|
||||||
*
|
|
||||||
* ★ 업종은 숙박 뿌리(stay.*)로 묶는다 — 펜션을 찾아도 관련 키워드를 가진 호텔이 함께 나온다(2026-09-30 지시).
|
|
||||||
* ★ 키워드 갈래는 merchant_keyword(생성 때 연결된 것)만 본다. /v1/match 의 추천은 저장되지 않으므로
|
|
||||||
* 생성이 한 번도 안 돈 숙소는 위치 갈래로만 잡힌다.
|
|
||||||
*/
|
|
||||||
async searchLodgings(rawQuery: string, limit: number) {
|
async searchLodgings(rawQuery: string, limit: number) {
|
||||||
const query = rawQuery.trim();
|
const query = rawQuery.trim();
|
||||||
if (!query) return { input: query, results: [] };
|
if (!query) return { input: query, results: [] };
|
||||||
@@ -206,10 +195,11 @@ export class ServingService {
|
|||||||
region_hit: boolean; score: number | null; matched: string[] | null;
|
region_hit: boolean; score: number | null; matched: string[] | null;
|
||||||
}>>`
|
}>>`
|
||||||
WITH near AS (
|
WITH near AS (
|
||||||
SELECT id, 1 - (embedding <=> ${vec}::vector) AS score
|
SELECT k.id, 1 - (k.embedding <=> ${vec}::vector) AS score
|
||||||
FROM keyword
|
FROM keyword k
|
||||||
WHERE embedding IS NOT NULL
|
WHERE k.embedding IS NOT NULL
|
||||||
ORDER BY embedding <=> ${vec}::vector
|
AND EXISTS (SELECT 1 FROM merchant_keyword mk WHERE mk.keyword_id = k.id AND mk.status = 'active')
|
||||||
|
ORDER BY k.embedding <=> ${vec}::vector
|
||||||
LIMIT ${SEARCH_KEYWORD_DEPTH}
|
LIMIT ${SEARCH_KEYWORD_DEPTH}
|
||||||
), hits AS (
|
), hits AS (
|
||||||
SELECT id, score FROM near WHERE score >= ${SEARCH_FLOOR}
|
SELECT id, score FROM near WHERE score >= ${SEARCH_FLOOR}
|
||||||
@@ -221,7 +211,7 @@ export class ServingService {
|
|||||||
SELECT m.external_id, r.name AS region, i.name AS industry,
|
SELECT m.external_id, r.name AS region, i.name AS industry,
|
||||||
COALESCE(bool_or(r.path <@ p.path), false) AS region_hit,
|
COALESCE(bool_or(r.path <@ p.path), false) AS region_hit,
|
||||||
max(h.score) AS score,
|
max(h.score) AS score,
|
||||||
array_remove(array_agg(DISTINCT k.canonical), NULL) AS matched
|
array_remove(array_agg(k.canonical ORDER BY h.score DESC), NULL) AS matched
|
||||||
FROM merchant m
|
FROM merchant m
|
||||||
JOIN industry i ON i.id = m.industry_id AND i.path <@ ${LODGING_ROOT}::ltree
|
JOIN industry i ON i.id = m.industry_id AND i.path <@ ${LODGING_ROOT}::ltree
|
||||||
LEFT JOIN region r ON r.id = m.region_id
|
LEFT JOIN region r ON r.id = m.region_id
|
||||||
@@ -230,7 +220,8 @@ export class ServingService {
|
|||||||
LEFT JOIN hits h ON h.id = mk.keyword_id
|
LEFT JOIN hits h ON h.id = mk.keyword_id
|
||||||
LEFT JOIN keyword k ON k.id = h.id
|
LEFT JOIN keyword k ON k.id = h.id
|
||||||
GROUP BY m.id, r.name, i.name
|
GROUP BY m.id, r.name, i.name
|
||||||
HAVING max(h.score) IS NOT NULL OR bool_or(p.path IS NOT NULL)
|
HAVING (max(h.score) IS NOT NULL OR bool_or(p.path IS NOT NULL))
|
||||||
|
AND (NOT EXISTS (SELECT 1 FROM places) OR bool_or(p.path IS NOT NULL))
|
||||||
ORDER BY region_hit DESC, score DESC NULLS LAST, m.name
|
ORDER BY region_hit DESC, score DESC NULLS LAST, m.name
|
||||||
LIMIT ${limit}`;
|
LIMIT ${limit}`;
|
||||||
|
|
||||||
@@ -241,7 +232,7 @@ export class ServingService {
|
|||||||
industry: r.industry,
|
industry: r.industry,
|
||||||
regionMatched: r.region_hit,
|
regionMatched: r.region_hit,
|
||||||
score: r.score === null ? null : Number(r.score),
|
score: r.score === null ? null : Number(r.score),
|
||||||
matchedKeywords: r.matched ?? [],
|
matchedKeywords: [...new Set(r.matched ?? [])],
|
||||||
seo: await this.seo(r.external_id, SEARCH_SEO_KEYWORDS),
|
seo: await this.seo(r.external_id, SEARCH_SEO_KEYWORDS),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -24,6 +24,8 @@
|
|||||||
{ "key": "accommodation_capacity", "label": "수용 인원", "type": "number", "scope": "place", "required": false, "critical": false, "allow_llm": false, "unit": "명" },
|
{ "key": "accommodation_capacity", "label": "수용 인원", "type": "number", "scope": "place", "required": false, "critical": false, "allow_llm": false, "unit": "명" },
|
||||||
{ "key": "building_scale", "label": "규모", "type": "text", "scope": "place", "required": false, "critical": false, "allow_llm": false },
|
{ "key": "building_scale", "label": "규모", "type": "text", "scope": "place", "required": false, "critical": false, "allow_llm": false },
|
||||||
{ "key": "intro", "label": "숙소 소개", "type": "text", "scope": "place", "required": false, "critical": false, "allow_llm": true },
|
{ "key": "intro", "label": "숙소 소개", "type": "text", "scope": "place", "required": false, "critical": false, "allow_llm": true },
|
||||||
|
{ "key": "tagline", "label": "캐치프레이즈", "type": "text", "scope": "place", "required": false, "critical": false, "allow_llm": true },
|
||||||
|
{ "key": "catchphrases", "label": "첫 화면 순환 문구", "type": "text", "scope": "place", "required": false, "critical": false, "allow_llm": true },
|
||||||
|
|
||||||
{ "key": "room_type", "label": "객실 타입", "type": "text", "scope": "unit", "required": true, "critical": false, "allow_llm": false },
|
{ "key": "room_type", "label": "객실 타입", "type": "text", "scope": "unit", "required": true, "critical": false, "allow_llm": false },
|
||||||
{ "key": "standard_capacity", "label": "기준 인원", "type": "number", "scope": "unit", "required": true, "critical": true, "allow_llm": false, "unit": "명" },
|
{ "key": "standard_capacity", "label": "기준 인원", "type": "number", "scope": "unit", "required": true, "critical": true, "allow_llm": false, "unit": "명" },
|
||||||
|
|||||||
@@ -49,7 +49,8 @@ class AgentConfig(BaseSettings):
|
|||||||
# "1" 이면 봇 ID 뒤에 "!" 를 붙여 **개발 채널**로 보낸다(운영 채널과 요청 주소가 다르다).
|
# "1" 이면 봇 ID 뒤에 "!" 를 붙여 **개발 채널**로 보낸다(운영 채널과 요청 주소가 다르다).
|
||||||
# ★ KAKAO_BOT_ID 자체를 고쳐 쓰지 않는다 — 웹훅이 그 값으로 요청의 bot.id 를 대조한다.
|
# ★ KAKAO_BOT_ID 자체를 고쳐 쓰지 않는다 — 웹훅이 그 값으로 요청의 bot.id 를 대조한다.
|
||||||
KAKAO_EVENT_DEV: str = "0"
|
KAKAO_EVENT_DEV: str = "0"
|
||||||
# 미니블로그 승인 알림을 메일에 더해 카톡으로도 보낸다. ★ 기본 꺼짐 — 오픈빌더에 이벤트
|
# 카톡이 연결된 사장님에게는 미니블로그 승인 알림을 메일 대신 카톡으로 보낸다(카톡이 실패했을
|
||||||
|
# 때만 메일로 대체, 연결이 없으면 메일). ★ 기본 꺼짐 — 오픈빌더에 이벤트
|
||||||
# 블록(스킬 연결)과 배포가 끝나기 전에 켜면 사장님 카톡에 빈 말풍선이 간다.
|
# 블록(스킬 연결)과 배포가 끝나기 전에 켜면 사장님 카톡에 빈 말풍선이 간다.
|
||||||
KAKAO_APPROVAL_PUSH_ENABLED: str = "0"
|
KAKAO_APPROVAL_PUSH_ENABLED: str = "0"
|
||||||
# 오픈빌더에 정의한 이벤트 이름. 말풍선을 그리는 블록이 이 이름에 걸려 있다.
|
# 오픈빌더에 정의한 이벤트 이름. 말풍선을 그리는 블록이 이 이름에 걸려 있다.
|
||||||
|
|||||||
@@ -42,12 +42,12 @@ class PostCRUD:
|
|||||||
return result.scalar()
|
return result.scalar()
|
||||||
|
|
||||||
async def due_for_mail(self, cdb: AsyncSession, status: int, today, limit: int):
|
async def due_for_mail(self, cdb: AsyncSession, status: int, today, limit: int):
|
||||||
"""배정일이 오늘까지 온 것 중 업장당 1건만, 이른 날짜순."""
|
"""배정일이 오늘인 것만, 업장당 1건."""
|
||||||
result = await cdb.execute(
|
result = await cdb.execute(
|
||||||
select(place_posts)
|
select(place_posts)
|
||||||
.where(
|
.where(
|
||||||
place_posts.status == status, place_posts.deleted == False, # noqa: E712
|
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)
|
.distinct(place_posts.place_id)
|
||||||
.order_by(place_posts.place_id, place_posts.scheduled_date)
|
.order_by(place_posts.place_id, place_posts.scheduled_date)
|
||||||
@@ -62,9 +62,9 @@ class PostCRUD:
|
|||||||
.where(
|
.where(
|
||||||
place_posts.place_id == place_id, place_posts.status == status,
|
place_posts.place_id == place_id, place_posts.status == status,
|
||||||
place_posts.deleted == False, # noqa: E712
|
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)
|
.limit(1)
|
||||||
)
|
)
|
||||||
return result.scalars().first()
|
return result.scalars().first()
|
||||||
|
|||||||
@@ -33,12 +33,28 @@ def start_scheduler():
|
|||||||
_scheduler.add_job(run_scheduled_check, "interval", minutes=10,
|
_scheduler.add_job(run_scheduled_check, "interval", minutes=10,
|
||||||
id="search-console", max_instances=1, coalesce=True)
|
id="search-console", max_instances=1, coalesce=True)
|
||||||
|
|
||||||
from scheduler.jobs import sweep_alert_outbox, sweep_blog_mail, sweep_queue_health
|
from scheduler.jobs import (
|
||||||
|
sweep_alert_outbox, sweep_blog_drafts, sweep_blog_mail, sweep_queue_health,
|
||||||
|
)
|
||||||
_scheduler.add_job(sweep_alert_outbox, "interval", minutes=1,
|
_scheduler.add_job(sweep_alert_outbox, "interval", minutes=1,
|
||||||
id="alert-outbox", max_instances=1, coalesce=True)
|
id="alert-outbox", max_instances=1, coalesce=True)
|
||||||
_scheduler.add_job(sweep_queue_health, "interval", minutes=5,
|
_scheduler.add_job(sweep_queue_health, "interval", minutes=5,
|
||||||
id="queue-health", max_instances=1, coalesce=True)
|
id="queue-health", max_instances=1, coalesce=True)
|
||||||
# 미니 블로그 — 새벽에 재고를 채우고, 아침에 검수 통과분을 보낸다(docs/MINI_BLOG.md).
|
# 미니 블로그 — 아침에 검수 통과분을 보낸다(docs/MINI_BLOG.md).
|
||||||
|
#
|
||||||
|
# ★★ 재고 **자동** 채우기는 기본으로 돌지 않는다(2026-10-01 대표 지시: "이거는 안보내도
|
||||||
|
# 될것같아"). 글은 빌더 화면의 [지금 생성하기] 로 사장님이 직접 만든다.
|
||||||
|
# 켜면 발행된 사이트 **전체**가 대상이고 업장당 최대 30건이라, 첫 회차에 AI 호출이
|
||||||
|
# 한꺼번에 일어난다 — 그 비용을 감수할지는 사람이 정할 일이지 기본값이 정할 일이 아니다.
|
||||||
|
#
|
||||||
|
# ★ 그래서 `add_job` 을 지우지 않고 스위치로 격리했다. 예전에는 **등록 자체가 없었고**
|
||||||
|
# 주석만 "새벽에 채운다" 라고 말했다(실측 2026-09-30) — 그 상태는 "끈 것" 과 "빠뜨린 것"
|
||||||
|
# 이 구별되지 않아, 증상("메일이 안 온다")을 보고 발송 쪽을 뒤지게 된다.
|
||||||
|
# 실제로는 보낼 글이 0건이었다. 지금은 꺼져 있다는 사실이 코드에 남는다.
|
||||||
|
if os.environ.get("BLOG_AUTO_DRAFTS_ENABLED") == "1":
|
||||||
|
# 발송(09:00)보다 앞서야 그날 아침에 나갈 재고가 있다.
|
||||||
|
_scheduler.add_job(sweep_blog_drafts, "cron", hour=4, minute=10,
|
||||||
|
id="blog-drafts", max_instances=1, coalesce=True)
|
||||||
_scheduler.add_job(sweep_blog_mail, "cron", hour=9, minute=0,
|
_scheduler.add_job(sweep_blog_mail, "cron", hour=9, minute=0,
|
||||||
id="blog-mail", max_instances=1, coalesce=True)
|
id="blog-mail", max_instances=1, coalesce=True)
|
||||||
_scheduler.start()
|
_scheduler.start()
|
||||||
|
|||||||
@@ -8,6 +8,7 @@
|
|||||||
★ 글마다 scheduled_date(KST) 를 하나씩 배정한다 — "언제 만들어졌나"만 있고 "언제 낼
|
★ 글마다 scheduled_date(KST) 를 하나씩 배정한다 — "언제 만들어졌나"만 있고 "언제 낼
|
||||||
것인가"가 없으면 달력 화면이 근거 없는 날짜를 지어내야 한다(2026-09-17).
|
것인가"가 없으면 달력 화면이 근거 없는 날짜를 지어내야 한다(2026-09-17).
|
||||||
"""
|
"""
|
||||||
|
import os
|
||||||
import uuid
|
import uuid
|
||||||
from datetime import date, datetime, timedelta, timezone
|
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.enums import DBWRType, PostStatus, SiteStatus
|
||||||
from common.logger import LOG
|
from common.logger import LOG
|
||||||
from crud.post_crud import PostCRUD
|
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.external import kakao_event
|
||||||
from services.snapshot import build_snapshot
|
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 []
|
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:
|
async def _pending_count(place_id) -> int:
|
||||||
"""아직 사장님에게 안 나간 재고 — 팀 사전검수가 없어 생성 즉시 REVIEWED 로 쌓인다."""
|
"""아직 사장님에게 안 나간 재고 — 팀 사전검수가 없어 생성 즉시 REVIEWED 로 쌓인다."""
|
||||||
def query(session):
|
def query(session):
|
||||||
@@ -136,7 +160,7 @@ async def _generate_for_place(place) -> int:
|
|||||||
async def generate_drafts() -> int:
|
async def generate_drafts() -> int:
|
||||||
"""재고가 모자란 업장마다 최대 BATCH_SIZE 건. 만든 수를 돌려준다."""
|
"""재고가 모자란 업장마다 최대 BATCH_SIZE 건. 만든 수를 돌려준다."""
|
||||||
made = 0
|
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)
|
made += await _generate_for_place(place)
|
||||||
return made
|
return made
|
||||||
|
|
||||||
@@ -266,46 +290,67 @@ async def _push_kakao(channel_user_key: str, post, edit_token: str) -> bool:
|
|||||||
return False
|
return False
|
||||||
|
|
||||||
|
|
||||||
async def _send_one(place, user, post) -> bool:
|
async def _alert_send_failed(place, post, reason: str) -> None:
|
||||||
"""토큰 발급 → 메일·카톡 발송 → 하나라도 나갔으면 SENT 로 표시. 아무 데도 안 나갔으면
|
await alert_service.send_alert(
|
||||||
DB 를 안 건드린다(다시 시도할 길을 막지 않는다).
|
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}",
|
||||||
|
)
|
||||||
|
|
||||||
★ 카톡과 메일은 **둘 다** 보낸다(2026-09-29 결정). 카톡은 채널 친구가 아니거나 차단했으면
|
|
||||||
실패하므로, 카톡이 붙어도 메일을 빼지 않는다."""
|
async def _send_one(place, user, post) -> bool:
|
||||||
|
"""토큰 발급 → 발송 → 나갔으면 SENT 로 표시. 아무 데도 안 나갔으면 DB 를 안 건드린다
|
||||||
|
(다시 시도할 길을 막지 않는다).
|
||||||
|
|
||||||
|
★ 카톡이 연결돼 있으면 **카톡으로만** 보내고, 카톡이 **실패했을 때만** 메일로 대체한다
|
||||||
|
(2026-09-30). 처음(2026-09-29)엔 '둘 다'였는데 같은 알림이 두 통 가는 게 번거롭다는 지시로
|
||||||
|
바꿨고, 카톡만 보내면 채널 친구가 아니거나 차단했거나 Event API 가 죽은 날 알림이 통째로
|
||||||
|
사라져서 실패 때만 메일로 받치게 했다. 연결이 없거나 스위치가 꺼져 있으면 예전처럼 메일이다.
|
||||||
|
★ 카톡도 메일도 못 보내면 SENT 로 표시하지 않는다 — 다음 스윕이 다시 시도하고 '승인 알림보내기'
|
||||||
|
는 실패로 답한다."""
|
||||||
token, token_hash, expires = blog_service.issue_token()
|
token, token_hash, expires = blog_service.issue_token()
|
||||||
# ★ 수정 링크도 일회용 코드다. 예전에는 여기 빌더 액세스 토큰을 통짜로 실었고,
|
# ★ 수정 링크도 일회용 코드다. 예전에는 여기 빌더 액세스 토큰을 통짜로 실었고,
|
||||||
# 메일 전달 한 번이 자정까지의 권한 양도였다(migrations/0023).
|
# 메일 전달 한 번이 자정까지의 권한 양도였다(migrations/0023).
|
||||||
edit_token, edit_hash, _edit_expires = blog_service.issue_token()
|
edit_token, edit_hash, _edit_expires = blog_service.issue_token()
|
||||||
|
|
||||||
mail_ok = False
|
|
||||||
if _can_mail(place, user):
|
|
||||||
body = _mail_body(
|
|
||||||
place_name=place.name, post=post, user=user,
|
|
||||||
origin=_app_origin(), approve_token=token, edit_token=edit_token,
|
|
||||||
)
|
|
||||||
mail_ok = mail_service.send(to=_notify_address(place, user), subject=f"[{place.name}] 이번 글 올릴까요?", text=body)
|
|
||||||
|
|
||||||
async def mark_sent():
|
async def mark_sent():
|
||||||
await DB_SESSION_MNG.execute_lambda_run(
|
await DB_SESSION_MNG.execute_lambda_run(
|
||||||
[place_posts.DBType()],
|
[place_posts.DBType()],
|
||||||
[lambda s, pid=post.post_id, h=token_hash, e=expires, eh=edit_hash: _crud.mark_sent(s, pid, h, e, eh)],
|
[lambda s, pid=post.post_id, h=token_hash, e=expires, eh=edit_hash: _crud.mark_sent(s, pid, h, e, eh)],
|
||||||
)
|
)
|
||||||
|
|
||||||
# ★ 메일이 나갔으면 카톡보다 **먼저** SENT 로 표시한다. 이벤트가 나가자마자 웹훅이 이 글을
|
|
||||||
# 읽는데, 그때 수정 코드 해시가 저장돼 있으면 [수정하기] 가 바로 먹는다. 카톡만 나가는
|
|
||||||
# 경우는 발송이 성공해야 표시할 수 있어 그 뒤에 한다 — 사장님이 버튼을 누르기까지의
|
|
||||||
# 시간이 그 간격보다 훨씬 길다(웹훅은 REVIEWED 글도 읽는다).
|
|
||||||
if mail_ok:
|
|
||||||
await mark_sent()
|
|
||||||
|
|
||||||
kakao_key = await _kakao_target(user)
|
kakao_key = await _kakao_target(user)
|
||||||
if kakao_key is None:
|
if kakao_key is not None:
|
||||||
return mail_ok
|
# 카톡 발송이 성공해야 SENT 로 표시할 수 있어 그 뒤에 한다. 이벤트가 나가자마자 웹훅이 이
|
||||||
|
# 글을 읽어도 되는 이유: 웹훅은 REVIEWED 글도 읽고, 사장님이 버튼을 누르기까지의 시간이
|
||||||
kakao_ok = await _push_kakao(kakao_key, post, edit_token)
|
# 이 간격보다 훨씬 길다.
|
||||||
if kakao_ok and not mail_ok:
|
if await _push_kakao(kakao_key, post, edit_token):
|
||||||
await mark_sent()
|
await mark_sent()
|
||||||
return mail_ok or kakao_ok
|
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
|
||||||
|
|
||||||
|
|
||||||
async def send_reviewed() -> int:
|
async def send_reviewed() -> int:
|
||||||
@@ -320,15 +365,20 @@ async def send_reviewed() -> int:
|
|||||||
if not rows:
|
if not rows:
|
||||||
return 0
|
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
|
sent = 0
|
||||||
for post in rows:
|
for post in rows:
|
||||||
target = places_by_id.get(str(post.place_id))
|
target = places_by_id.get(str(post.place_id))
|
||||||
if not target:
|
if not target:
|
||||||
continue
|
continue
|
||||||
place, user = target
|
place, user = target
|
||||||
# 메일도 카톡도 보낼 수 없는 사장님은 건너뛴다. 하나라도 되면 _send_one 이 갈래를 정한다.
|
# 메일도 카톡도 보낼 수 없는 사장님은 건너뛴다. 어느 쪽으로 보낼지는 _send_one 이 정한다
|
||||||
|
# (카톡이 연결돼 있으면 카톡, 실패했을 때만 메일 — 연결이 없으면 메일).
|
||||||
if not _can_mail(place, user) and await _kakao_target(user) is None:
|
if not _can_mail(place, user) and await _kakao_target(user) is None:
|
||||||
|
await _alert_send_failed(place, post, "보낼 곳이 없다 — 메일 주소도 카톡 연결도 없다")
|
||||||
continue
|
continue
|
||||||
if await _send_one(place, user, post):
|
if await _send_one(place, user, post):
|
||||||
sent += 1
|
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.database.model.models import places, sites, users
|
||||||
from common.enums import DBWRType, SiteStatus
|
from common.enums import DBWRType, SiteStatus
|
||||||
from common.logger import LOG
|
from common.logger import LOG
|
||||||
from services import mail_service
|
from services import alert_service, mail_service
|
||||||
|
|
||||||
NOT_AVAILABLE = "지금은 온라인 예약 요청을 받을 수 없습니다. 전화로 문의해 주세요."
|
NOT_AVAILABLE = "지금은 온라인 예약 요청을 받을 수 없습니다. 전화로 문의해 주세요."
|
||||||
SENT = "예약 요청을 보냈습니다. 사장님이 확인 후 연락드립니다."
|
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:
|
class BookingRequestService:
|
||||||
async def send(self, body):
|
async def send(self, body):
|
||||||
from router.v1.site.booking_request import ResBookingRequest
|
from router.v1.site.booking_request import ResBookingRequest
|
||||||
@@ -22,6 +31,7 @@ class BookingRequestService:
|
|||||||
place_name, owner_email = target
|
place_name, owner_email = target
|
||||||
if not mail_service.is_configured() or not mail_service.is_valid_address(owner_email):
|
if not mail_service.is_configured() or not mail_service.is_valid_address(owner_email):
|
||||||
LOG.w("[booking-request] 받는 주소나 SMTP 설정이 없어 전달하지 못했다")
|
LOG.w("[booking-request] 받는 주소나 SMTP 설정이 없어 전달하지 못했다")
|
||||||
|
await _alert_failed(body.place_id, place_name, "받는 주소나 메일 설정이 없다")
|
||||||
return ResBookingRequest(success=False, message=NOT_AVAILABLE)
|
return ResBookingRequest(success=False, message=NOT_AVAILABLE)
|
||||||
|
|
||||||
reply_to = body.email if body.email and mail_service.is_valid_address(body.email) else None
|
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,
|
reply_to=reply_to,
|
||||||
)
|
)
|
||||||
if not ok:
|
if not ok:
|
||||||
|
await _alert_failed(body.place_id, place_name, "메일 발송 실패")
|
||||||
return ResBookingRequest(success=False, message=NOT_AVAILABLE)
|
return ResBookingRequest(success=False, message=NOT_AVAILABLE)
|
||||||
|
|
||||||
LOG.i(f"[booking-request] 전달 완료 place={body.place_id}")
|
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)
|
return ResBookingRequest(success=True, message=SENT)
|
||||||
|
|
||||||
async def _target(self, place_id) -> tuple[str, str] | None:
|
async def _target(self, place_id) -> tuple[str, str] | None:
|
||||||
|
|||||||
@@ -1,6 +1,5 @@
|
|||||||
"""정적 빌드 + 발행 — BUILD 잡이 하는 일."""
|
"""정적 빌드 + 발행 — BUILD 잡이 하는 일."""
|
||||||
import os
|
import os
|
||||||
import time
|
|
||||||
import uuid
|
import uuid
|
||||||
|
|
||||||
from sqlalchemy import select
|
from sqlalchemy import select
|
||||||
@@ -26,10 +25,10 @@ from crud.site_crud import SiteCRUD
|
|||||||
from crud.place_crud import PlaceCRUD
|
from crud.place_crud import PlaceCRUD
|
||||||
from crud.post_crud import PostCRUD
|
from crud.post_crud import PostCRUD
|
||||||
from services import (
|
from services import (
|
||||||
activity_feed,
|
|
||||||
alert_service,
|
alert_service,
|
||||||
azure_static,
|
azure_static,
|
||||||
indexnow,
|
indexnow,
|
||||||
|
mockup_blog,
|
||||||
publish_gate,
|
publish_gate,
|
||||||
render_service,
|
render_service,
|
||||||
seo_keywords,
|
seo_keywords,
|
||||||
@@ -104,6 +103,26 @@ async def load_channel_links(place_id: str) -> list:
|
|||||||
return list(rows) if err == ErrorType.SUCCESS else []
|
return list(rows) if err == ErrorType.SUCCESS else []
|
||||||
|
|
||||||
|
|
||||||
|
def _actor_uuid(actor) -> uuid.UUID | None:
|
||||||
|
"""`payload["requested_by"]` 를 actor_user_id 로 옮긴다.
|
||||||
|
|
||||||
|
★★ **여기서 예외를 올리면 발행이 죽는다.** `_log` 는 사이트를 다 구운 **뒤에**, 그런데
|
||||||
|
`sites.status = PUBLISHED` 를 찍기 **전에** 불린다 — 던지면 굽기는 끝났는데 발행 상태만
|
||||||
|
안 바뀌고, 잡은 3회 재시도 끝에 DEAD 가 된다. 사장님 화면에는 "승인했는데 홈페이지가
|
||||||
|
그대로" 로만 보인다. 실측(2026-09-23~09-30): BUILD 잡 5건이 이렇게 죽었다 —
|
||||||
|
`post_service` 가 미니블로그 승인 경로에서 `requested_by="blog-approval"` 이라는
|
||||||
|
**사람이 아닌 라벨**을 넣었고 `uuid.UUID()` 가 ValueError 를 던졌다.
|
||||||
|
★ 그래서 모양이 틀린 값은 **기록만 비우고 넘어간다.** 감사 기록 한 줄이 발행을 막는 것은
|
||||||
|
순서가 뒤집힌 것이다."""
|
||||||
|
if not actor:
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
return uuid.UUID(str(actor))
|
||||||
|
except (ValueError, AttributeError, TypeError):
|
||||||
|
LOG.w(f"[build] requested_by 가 사용자 ID 가 아니다({actor!r}) — actor 없이 기록한다")
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
async def _log(site_id, version_id, action: PublishAction, result: PublishResult, gate=None, actor=None):
|
async def _log(site_id, version_id, action: PublishAction, result: PublishResult, gate=None, actor=None):
|
||||||
"""발행 시도를 기록한다."""
|
"""발행 시도를 기록한다."""
|
||||||
row = site_publish_logs(
|
row = site_publish_logs(
|
||||||
@@ -113,52 +132,26 @@ async def _log(site_id, version_id, action: PublishAction, result: PublishResult
|
|||||||
result=result.value,
|
result=result.value,
|
||||||
reject_reason=(gate.reason.value if gate is not None and gate.reason else None),
|
reject_reason=(gate.reason.value if gate is not None and gate.reason else None),
|
||||||
detail=(gate.as_log() if gate is not None and not gate.passed else None),
|
detail=(gate.as_log() if gate is not None and not gate.passed else None),
|
||||||
actor_user_id=uuid.UUID(actor) if actor else None,
|
actor_user_id=_actor_uuid(actor),
|
||||||
)
|
)
|
||||||
await DB_SESSION_MNG.execute_lambda_run([site_publish_logs.DBType()], [lambda s: _site_crud.add_log(s, row)])
|
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:
|
async def run_build(job: dict) -> dict:
|
||||||
"""BUILD 잡 핸들러."""
|
"""BUILD 잡 핸들러."""
|
||||||
started = time.monotonic()
|
|
||||||
try:
|
|
||||||
result = await _run_build(job)
|
|
||||||
except Exception as ex:
|
|
||||||
await activity_feed.post(
|
|
||||||
"❌ 빌드 실패",
|
|
||||||
[f"place_id={job['payload'].get('place_id')}", f"{type(ex).__name__}: {ex}",
|
|
||||||
f"{time.monotonic() - started:.0f}초"],
|
|
||||||
)
|
|
||||||
raise
|
|
||||||
await post_build_summary(result, time.monotonic() - started)
|
|
||||||
return result
|
|
||||||
|
|
||||||
|
|
||||||
async def post_build_summary(result: dict, elapsed: float) -> None:
|
|
||||||
version = f"v{result.get('version')}"
|
|
||||||
mode = result.get("mode") or "빌드"
|
|
||||||
lines = [f"{result.get('label') or result.get('place_id')} {version}"]
|
|
||||||
if result.get("build_status") == "BUILT":
|
|
||||||
title = f"✅ {mode} 완료"
|
|
||||||
if result.get("url"):
|
|
||||||
lines.append(result["url"])
|
|
||||||
elif result.get("gate", {}).get("passed") is False:
|
|
||||||
title = f"🚫 {mode} 반려(게이트)"
|
|
||||||
lines.append(str(result.get("error") or ""))
|
|
||||||
else:
|
|
||||||
title = f"❌ {mode} 실패"
|
|
||||||
lines.append(str(result.get("error") or ""))
|
|
||||||
media = result.get("render_media")
|
|
||||||
if media:
|
|
||||||
lines.append(
|
|
||||||
f"굽기 — 사진 {media.get('total', 0)}장: 새로 받음 {media.get('fetched', 0)} · "
|
|
||||||
f"기존 {media.get('cached', 0)} · 실패 {media.get('failed', 0)}"
|
|
||||||
)
|
|
||||||
lines.append(f"{elapsed:.0f}초")
|
|
||||||
await activity_feed.post(title, lines)
|
|
||||||
|
|
||||||
|
|
||||||
async def _run_build(job: dict) -> dict:
|
|
||||||
payload = job["payload"]
|
payload = job["payload"]
|
||||||
place_id = payload["place_id"]
|
place_id = payload["place_id"]
|
||||||
owner_user_id = payload["owner_user_id"]
|
owner_user_id = payload["owner_user_id"]
|
||||||
@@ -173,7 +166,10 @@ async def _run_build(job: dict) -> dict:
|
|||||||
raise BuildAborted(f"사업장을 찾을 수 없다: {place_id}")
|
raise BuildAborted(f"사업장을 찾을 수 없다: {place_id}")
|
||||||
|
|
||||||
site = await ensure_site(place_id)
|
site = await ensure_site(place_id)
|
||||||
mode = ("재발행" if site.published_at is not None else "첫 발행") if want_publish else "빌드만"
|
|
||||||
|
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:
|
try:
|
||||||
@@ -240,12 +236,7 @@ async def _run_build(job: dict) -> dict:
|
|||||||
raise BuildAborted(f"버전 생성 실패: {add_err.name}")
|
raise BuildAborted(f"버전 생성 실패: {add_err.name}")
|
||||||
|
|
||||||
result = {"place_id": place_id, "site_id": str(site.site_id), "version": version_no,
|
result = {"place_id": place_id, "site_id": str(site.site_id), "version": version_no,
|
||||||
"site_version_id": str(version.site_version_id), "label": activity_feed.place_label(place),
|
"site_version_id": str(version.site_version_id)}
|
||||||
"mode": mode}
|
|
||||||
await activity_feed.post(
|
|
||||||
f"🏗 {mode} 시작",
|
|
||||||
[f"{result['label']} v{version_no}", f"템플릿 {site.template_id or '기본'}"],
|
|
||||||
)
|
|
||||||
# 잡 결과에 남긴다 — "노래가 왜 없나" 를 잡 하나만 열어 보면 알 수 있어야 한다.
|
# 잡 결과에 남긴다 — "노래가 왜 없나" 를 잡 하나만 열어 보면 알 수 있어야 한다.
|
||||||
if song_result is not None:
|
if song_result is not None:
|
||||||
result["song"] = song_result
|
result["song"] = song_result
|
||||||
@@ -314,8 +305,6 @@ async def _run_build(job: dict) -> dict:
|
|||||||
# 발행하지 않는다.
|
# 발행하지 않는다.
|
||||||
return await _fail(str(ex))
|
return await _fail(str(ex))
|
||||||
|
|
||||||
if report.get("media"):
|
|
||||||
result["render_media"] = report["media"]
|
|
||||||
mismatches = list(report.get("mismatches") or [])
|
mismatches = list(report.get("mismatches") or [])
|
||||||
unique_count_raw = report.get("uniqueContentCount")
|
unique_count_raw = report.get("uniqueContentCount")
|
||||||
unique_count = unique_count_raw or 0
|
unique_count = unique_count_raw or 0
|
||||||
@@ -415,7 +404,6 @@ async def _run_build(job: dict) -> dict:
|
|||||||
if thumbnail_url:
|
if thumbnail_url:
|
||||||
site.thumbnail_url = thumbnail_url
|
site.thumbnail_url = thumbnail_url
|
||||||
result["published"] = True
|
result["published"] = True
|
||||||
result["url"] = site_payload.publish_url(place, site)
|
|
||||||
LOG.i(f"[build] place={place_id} v{version_no} 발행 완료 "
|
LOG.i(f"[build] place={place_id} v{version_no} 발행 완료 "
|
||||||
f"(고유 콘텐츠 {unique_count}건 · {report.get('routes')} 페이지)")
|
f"(고유 콘텐츠 {unique_count}건 · {report.get('routes')} 페이지)")
|
||||||
else:
|
else:
|
||||||
|
|||||||
@@ -0,0 +1,43 @@
|
|||||||
|
"""순환 문구를 fact 한 칸에 담는 글 형식 — 사장님이 빌더에서 줄 단위로 고칠 수 있게 JSON 이 아니라 글로 둔다.
|
||||||
|
|
||||||
|
한 줄에 한 문구. 앞에 `봄 | ` · `9월 | ` · `비 | ` 를 붙이면 계절·월·날씨 문구, 없으면 일반 문구다.
|
||||||
|
"""
|
||||||
|
import re
|
||||||
|
|
||||||
|
SEASONS = ("봄", "여름", "가을", "겨울")
|
||||||
|
WEATHERS = ("맑음", "흐림", "비", "눈")
|
||||||
|
_MONTH = re.compile(r"^(1[0-2]|[1-9])월$")
|
||||||
|
|
||||||
|
|
||||||
|
def encode(items: list[dict]) -> str:
|
||||||
|
lines = []
|
||||||
|
for item in items:
|
||||||
|
text = str(item.get("text") or "").strip()
|
||||||
|
if not text:
|
||||||
|
continue
|
||||||
|
kind = item.get("kind") or "general"
|
||||||
|
tag = {"season": item.get("season"), "month": f"{item.get('month')}월", "weather": item.get("weather")}.get(kind)
|
||||||
|
lines.append(f"{tag} | {text}" if tag else text)
|
||||||
|
return "\n".join(lines)
|
||||||
|
|
||||||
|
|
||||||
|
def decode(value: str) -> list[dict]:
|
||||||
|
items: list[dict] = []
|
||||||
|
for raw in (value or "").splitlines():
|
||||||
|
line = raw.strip()
|
||||||
|
if not line:
|
||||||
|
continue
|
||||||
|
tag, sep, rest = line.partition("|")
|
||||||
|
tag, rest = tag.strip(), rest.strip()
|
||||||
|
if sep and rest:
|
||||||
|
if tag in SEASONS:
|
||||||
|
items.append({"text": rest, "kind": "season", "season": tag})
|
||||||
|
continue
|
||||||
|
if tag in WEATHERS:
|
||||||
|
items.append({"text": rest, "kind": "weather", "weather": tag})
|
||||||
|
continue
|
||||||
|
if m := _MONTH.match(tag):
|
||||||
|
items.append({"text": rest, "kind": "month", "month": int(m.group(1))})
|
||||||
|
continue
|
||||||
|
items.append({"text": line, "kind": "general"})
|
||||||
|
return items
|
||||||
@@ -458,47 +458,14 @@ async def store_media(place_id: str, sources: list, unit_map: dict) -> dict:
|
|||||||
# 오케스트레이션
|
# 오케스트레이션
|
||||||
async def run_collect(job: dict) -> dict:
|
async def run_collect(job: dict) -> dict:
|
||||||
"""COLLECT 잡 핸들러."""
|
"""COLLECT 잡 핸들러."""
|
||||||
started = time.monotonic()
|
|
||||||
with collect_diagnostics.collecting():
|
with collect_diagnostics.collecting():
|
||||||
try:
|
|
||||||
result = await _run_collect(job)
|
result = await _run_collect(job)
|
||||||
except Exception as ex:
|
|
||||||
await activity_feed.post(
|
|
||||||
"❌ 수집 실패",
|
|
||||||
[f"place_id={job['payload'].get('place_id')}", f"{type(ex).__name__}: {ex}",
|
|
||||||
f"{time.monotonic() - started:.0f}초"],
|
|
||||||
)
|
|
||||||
raise
|
|
||||||
issues = collect_diagnostics.snapshot()
|
issues = collect_diagnostics.snapshot()
|
||||||
if issues:
|
if issues:
|
||||||
result["issues"] = issues
|
result["issues"] = issues
|
||||||
await _post_collect_summary(result, issues, time.monotonic() - started)
|
|
||||||
return result
|
return result
|
||||||
|
|
||||||
|
|
||||||
async def _post_collect_summary(result: dict, issues: list[dict], elapsed: float) -> None:
|
|
||||||
lines = [result.get("label") or f"place_id={result.get('place_id')}"]
|
|
||||||
if result.get("note"):
|
|
||||||
lines.append(result["note"])
|
|
||||||
for row in result.get("channels") or []:
|
|
||||||
lines.append(row)
|
|
||||||
facts = result.get("facts")
|
|
||||||
if facts:
|
|
||||||
reasons = ", ".join(f"{k} {v}" for k, v in facts["by_reason"].items())
|
|
||||||
lines.append(f"fact 저장 {facts['stored']} · 반려 {facts['rejected']}" + (f" ({reasons})" if reasons else ""))
|
|
||||||
media = result.get("media")
|
|
||||||
if media:
|
|
||||||
lines.append(f"사진 {media['stored']}장 (중복 {media['skipped_duplicate']})")
|
|
||||||
cov = result.get("coverage")
|
|
||||||
if cov and cov["missing"]:
|
|
||||||
lines.append(f"필수 항목 {cov['covered']}/{cov['total']} — 누락 {', '.join(cov['missing'])}")
|
|
||||||
other = [i for i in issues if i["stage"] != "fetch"]
|
|
||||||
for issue in other:
|
|
||||||
lines.append(f"⚠️ {issue['stage']} 실패: {issue['error_type']}: {issue['message'][:200]}")
|
|
||||||
lines.append(f"{elapsed:.0f}초")
|
|
||||||
await activity_feed.post("✅ 수집 완료", lines)
|
|
||||||
|
|
||||||
|
|
||||||
async def _run_collect(job: dict) -> dict:
|
async def _run_collect(job: dict) -> dict:
|
||||||
payload = job["payload"]
|
payload = job["payload"]
|
||||||
place_id = payload["place_id"]
|
place_id = payload["place_id"]
|
||||||
@@ -528,12 +495,6 @@ async def _run_collect(job: dict) -> dict:
|
|||||||
link.channel == LinkChannel.NAVER_PLACE.value for link in targets
|
link.channel == LinkChannel.NAVER_PLACE.value for link in targets
|
||||||
)
|
)
|
||||||
|
|
||||||
await activity_feed.post(
|
|
||||||
"🔎 수집 시작",
|
|
||||||
[result["label"], f"place_id={place_id}",
|
|
||||||
f"크롤링 대상 {len(targets)}건: " + (", ".join(activity_feed.channel_name(l.channel) for l in targets) or "없음")],
|
|
||||||
)
|
|
||||||
|
|
||||||
if not targets:
|
if not targets:
|
||||||
result["note"] = "크롤링 대상이 없다(어댑터가 처리할 수 있는 확정 URL 0건)"
|
result["note"] = "크롤링 대상이 없다(어댑터가 처리할 수 있는 확정 URL 0건)"
|
||||||
await _finish(place_id, owner_user_id, PlaceStatus.REVIEW)
|
await _finish(place_id, owner_user_id, PlaceStatus.REVIEW)
|
||||||
|
|||||||
@@ -1,11 +1,15 @@
|
|||||||
"""COPY 흐름."""
|
"""COPY 흐름."""
|
||||||
|
from common.enums import PlaceCategory
|
||||||
from common.logger import LOG
|
from common.logger import LOG
|
||||||
from services.copy_steps import CopyAborted, prepare_copy, generate_copy, save_copy, fill_faqs
|
from services.copy_steps import (
|
||||||
|
CopyAborted, fill_faqs, generate_catchphrases, generate_copy, prepare_copy, save_catchphrases, save_copy,
|
||||||
|
)
|
||||||
from services.external import gemini_text
|
from services.external import gemini_text
|
||||||
from services.llm import provider
|
from services.llm import provider
|
||||||
|
from services.llm.errors import LlmError
|
||||||
from services.job_progress import JobProgress
|
from services.job_progress import JobProgress
|
||||||
|
|
||||||
COPY_STEPS = ("prepare", "generate", "save", "faq_fill")
|
COPY_STEPS = ("prepare", "generate", "save", "catchphrase", "faq_fill")
|
||||||
|
|
||||||
|
|
||||||
async def run_copy(job: dict) -> dict:
|
async def run_copy(job: dict) -> dict:
|
||||||
@@ -34,6 +38,18 @@ async def run_copy(job: dict) -> dict:
|
|||||||
async with progress.step("save"):
|
async with progress.step("save"):
|
||||||
result = await save_copy(inputs, copy)
|
result = await save_copy(inputs, copy)
|
||||||
|
|
||||||
|
if inputs.place.category != PlaceCategory.LODGING.value:
|
||||||
|
await progress.skip("catchphrase", "not_lodging")
|
||||||
|
elif copy is None:
|
||||||
|
await progress.skip("catchphrase", "no_facts" if inputs.ungrounded else "not_configured")
|
||||||
|
else:
|
||||||
|
try:
|
||||||
|
async with progress.step("catchphrase"):
|
||||||
|
result["catchphrase"] = await save_catchphrases(inputs, await generate_catchphrases(inputs))
|
||||||
|
except LlmError as ex:
|
||||||
|
LOG.w(f"[copy] 첫 화면 문구 생성 실패, 공통 문구로 계속: {ex}")
|
||||||
|
await progress.skip("catchphrase", "generation_failed")
|
||||||
|
|
||||||
if inputs.catalog is not None:
|
if inputs.catalog is not None:
|
||||||
async with progress.step("faq_fill"):
|
async with progress.step("faq_fill"):
|
||||||
result["faq_fill"] = await fill_faqs(
|
result["faq_fill"] = await fill_faqs(
|
||||||
|
|||||||
@@ -21,7 +21,7 @@ from crud.fact_crud import FactCRUD
|
|||||||
from crud.faq_crud import FaqCRUD
|
from crud.faq_crud import FaqCRUD
|
||||||
from crud.place_crud import PlaceCRUD
|
from crud.place_crud import PlaceCRUD
|
||||||
from router.v1.fact.protocol import Req_UpsertFact
|
from router.v1.fact.protocol import Req_UpsertFact
|
||||||
from services import faq_fill, place_research
|
from services import catchphrase_text, faq_fill, place_research
|
||||||
from services.external import gemini_text
|
from services.external import gemini_text
|
||||||
from services.llm import provider
|
from services.llm import provider
|
||||||
from services.fact_service import FactService
|
from services.fact_service import FactService
|
||||||
@@ -248,6 +248,47 @@ async def save_copy(inputs: CopyInputs, copy: gemini_text.GeneratedCopy | None)
|
|||||||
return stat
|
return stat
|
||||||
|
|
||||||
|
|
||||||
|
async def generate_catchphrases(inputs: CopyInputs) -> gemini_text.GeneratedCatchphrases:
|
||||||
|
active_provider = provider.active()
|
||||||
|
model = (
|
||||||
|
external_api_config.openai_text_model if active_provider.__name__.endswith("openai")
|
||||||
|
else external_api_config.gemini_text_model
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
return await gemini_text.generate_catchphrases(
|
||||||
|
inputs.place.name, inputs.grounded, records=inputs.records or None, model=model,
|
||||||
|
)
|
||||||
|
except gemini_text.GeminiNotConfigured as ex:
|
||||||
|
raise CopyAborted(str(ex)) from ex
|
||||||
|
|
||||||
|
|
||||||
|
async def save_catchphrases(inputs: CopyInputs, generated: gemini_text.GeneratedCatchphrases) -> dict:
|
||||||
|
place_id = str(inputs.place.place_id)
|
||||||
|
stat = {"tagline": False, "catchphrases": 0, "rejected": [list(r) for r in generated.rejected][:20]}
|
||||||
|
actor = UserInfo(user_id=str(inputs.place.owner_user_id), id="generator", role=1)
|
||||||
|
service = FactService(_fact_crud, _place_crud)
|
||||||
|
values = (("tagline", generated.tagline), ("catchphrases", catchphrase_text.encode(generated.items)))
|
||||||
|
for key, value in values:
|
||||||
|
spec = inputs.schema.get(key)
|
||||||
|
if not (value or "").strip() or not (spec and spec.allow_llm):
|
||||||
|
continue
|
||||||
|
res = await service.upsert_fact(
|
||||||
|
actor, place_id,
|
||||||
|
Req_UpsertFact(
|
||||||
|
key=key, value=value.strip(),
|
||||||
|
source_type=SourceType.LLM, source_url=f"llm:{generated.source or external_api_config.gemini_text_model}",
|
||||||
|
),
|
||||||
|
)
|
||||||
|
if not res.result.success:
|
||||||
|
stat["rejected"].append([key, res.result.desc])
|
||||||
|
elif key == "tagline":
|
||||||
|
stat["tagline"] = True
|
||||||
|
else:
|
||||||
|
stat["catchphrases"] = len(generated.items)
|
||||||
|
LOG.i(f"[copy] place={place_id} 캐치프레이즈 {'O' if stat['tagline'] else 'X'} · 순환 {stat['catchphrases']}개")
|
||||||
|
return stat
|
||||||
|
|
||||||
|
|
||||||
async def fill_faqs(pid: uuid.UUID, catalog: FaqCatalog, known_fact_keys: set[str], phone: str | None) -> int:
|
async def fill_faqs(pid: uuid.UUID, catalog: FaqCatalog, known_fact_keys: set[str], phone: str | None) -> int:
|
||||||
"""노출 중인 FAQ 가 목표 수에 모자란 만큼 문의 안내 문항을 넣는다."""
|
"""노출 중인 FAQ 가 목표 수에 모자란 만큼 문의 안내 문항을 넣는다."""
|
||||||
l_err, rows = await DB_SESSION_MNG.execute_lambda(
|
l_err, rows = await DB_SESSION_MNG.execute_lambda(
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ from services.llm import provider
|
|||||||
from services.llm.errors import LlmError
|
from services.llm.errors import LlmError
|
||||||
from services.llm.errors import LlmInvalidOutput as GeminiInvalidOutput
|
from services.llm.errors import LlmInvalidOutput as GeminiInvalidOutput
|
||||||
from services.llm.errors import LlmNotConfigured as GeminiNotConfigured
|
from services.llm.errors import LlmNotConfigured as GeminiNotConfigured
|
||||||
|
from services.prompts import catchphrase as catchphrase_prompt
|
||||||
from services.prompts.copy import RESPONSE_SCHEMA, build_prompt
|
from services.prompts.copy import RESPONSE_SCHEMA, build_prompt
|
||||||
|
|
||||||
|
|
||||||
@@ -159,6 +160,90 @@ async def generate_copy(
|
|||||||
return result
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
# ── 첫 화면 문구(generate_catchphrases) ─────────────────────────────────
|
||||||
|
@dataclass
|
||||||
|
class GeneratedCatchphrases:
|
||||||
|
tagline: Optional[str] = None
|
||||||
|
items: list[dict] = field(default_factory=list)
|
||||||
|
rejected: list[tuple[str, str]] = field(default_factory=list)
|
||||||
|
source: str = ""
|
||||||
|
|
||||||
|
|
||||||
|
async def generate_catchphrases(
|
||||||
|
place_name: str,
|
||||||
|
facts: list[FactInput],
|
||||||
|
*,
|
||||||
|
records: Optional[list[str]] = None,
|
||||||
|
model: Optional[str] = None,
|
||||||
|
max_retries: int = 2,
|
||||||
|
client: Optional[httpx.AsyncClient] = None,
|
||||||
|
) -> GeneratedCatchphrases:
|
||||||
|
"""고정 캐치프레이즈 하나와 순환 문구 모음 — 문구마다 소개문과 같은 근거 검사를 거친다."""
|
||||||
|
llm = provider.active()
|
||||||
|
if not llm.is_configured():
|
||||||
|
raise GeminiNotConfigured(f"{llm.__name__.rsplit('.', 1)[-1].upper()}_API_KEY 가 설정되지 않았다")
|
||||||
|
model = model or llm.DEFAULT_MODEL
|
||||||
|
grounding = list(facts) + [FactInput(key="place_name", label="상호명", value=place_name)]
|
||||||
|
prompt = catchphrase_prompt.build_prompt(place_name, facts, records)
|
||||||
|
|
||||||
|
owns_client = client is None
|
||||||
|
client = client or httpx.AsyncClient(timeout=httpx.Timeout(120.0, connect=10.0))
|
||||||
|
try:
|
||||||
|
llm_result = await llm.generate(
|
||||||
|
client, model, prompt=prompt, response_schema=catchphrase_prompt.RESPONSE_SCHEMA,
|
||||||
|
temperature=0.7, max_retries=max_retries,
|
||||||
|
)
|
||||||
|
finally:
|
||||||
|
if owns_client:
|
||||||
|
await client.aclose()
|
||||||
|
|
||||||
|
parsed = llm_result.json or {}
|
||||||
|
result = GeneratedCatchphrases(source=f"{llm.__name__.rsplit('.', 1)[-1]}:{model}")
|
||||||
|
seen: set[str] = set()
|
||||||
|
|
||||||
|
def accept(text: object) -> Optional[str]:
|
||||||
|
line = str(text or "").strip()
|
||||||
|
if not line or line in seen:
|
||||||
|
return None
|
||||||
|
if not (catchphrase_prompt.MIN_LEN <= len(line) <= catchphrase_prompt.MAX_LEN):
|
||||||
|
result.rejected.append((line, f"길이 {len(line)}자"))
|
||||||
|
return None
|
||||||
|
if place_name and place_name in line:
|
||||||
|
result.rejected.append((line, "상호명 포함"))
|
||||||
|
return None
|
||||||
|
ok, reasons = ground_check(line, grounding)
|
||||||
|
if not ok:
|
||||||
|
result.rejected.append((line, " / ".join(reasons)))
|
||||||
|
return None
|
||||||
|
seen.add(line)
|
||||||
|
return line
|
||||||
|
|
||||||
|
result.tagline = accept(parsed.get("tagline"))
|
||||||
|
for text in (parsed.get("general") or [])[: catchphrase_prompt.COUNT_GENERAL]:
|
||||||
|
if line := accept(text):
|
||||||
|
result.items.append({"text": line, "kind": "general"})
|
||||||
|
for row in parsed.get("season") or []:
|
||||||
|
season = (row or {}).get("season")
|
||||||
|
if season in catchphrase_prompt.SEASONS and (line := accept(row.get("text"))):
|
||||||
|
result.items.append({"text": line, "kind": "season", "season": season})
|
||||||
|
for row in parsed.get("month") or []:
|
||||||
|
month = (row or {}).get("month")
|
||||||
|
if isinstance(month, int) and 1 <= month <= 12 and (line := accept(row.get("text"))):
|
||||||
|
result.items.append({"text": line, "kind": "month", "month": month})
|
||||||
|
for row in parsed.get("weather") or []:
|
||||||
|
weather = (row or {}).get("weather")
|
||||||
|
if weather in catchphrase_prompt.WEATHERS and (line := accept(row.get("text"))):
|
||||||
|
result.items.append({"text": line, "kind": "weather", "weather": weather})
|
||||||
|
|
||||||
|
usage = llm_result.usage
|
||||||
|
LOG.i(
|
||||||
|
f"[llm-text] '{place_name}' 첫 화면 문구 — 캐치프레이즈 {'O' if result.tagline else 'X'} · "
|
||||||
|
f"순환 {len(result.items)}개 · 반려 {len(result.rejected)}건 · model={model} · "
|
||||||
|
f"tokens in={usage.input_tokens} out={usage.output_tokens} · 약 ${llm.price(model, usage)}"
|
||||||
|
)
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
# ── 요약(summarize_text) ──────────────────────────────────────────────────
|
# ── 요약(summarize_text) ──────────────────────────────────────────────────
|
||||||
_SUMMARY_CACHE: dict[str, str] = {}
|
_SUMMARY_CACHE: dict[str, str] = {}
|
||||||
_SUMMARY_CACHE_MAX = 500
|
_SUMMARY_CACHE_MAX = 500
|
||||||
|
|||||||
+8
-5
@@ -7,6 +7,8 @@ from config.server_configs import external_api_config
|
|||||||
|
|
||||||
# 로컬 임베딩 모델이라 호출당 1~2초다.
|
# 로컬 임베딩 모델이라 호출당 1~2초다.
|
||||||
TIMEOUT_SEC = 15.0
|
TIMEOUT_SEC = 15.0
|
||||||
|
# 처음 보는 업체는 publish 가 OpenAI 키워드 생성을 기다린다(키워드 15개 + 질문 5개).
|
||||||
|
PUBLISH_TIMEOUT_SEC = 60.0
|
||||||
DEFAULT_LIMIT = 40
|
DEFAULT_LIMIT = 40
|
||||||
|
|
||||||
PUBLISH_PATH = "/v1/merchants/publish"
|
PUBLISH_PATH = "/v1/merchants/publish"
|
||||||
@@ -25,8 +27,8 @@ def is_configured() -> bool:
|
|||||||
return bool(base_url())
|
return bool(base_url())
|
||||||
|
|
||||||
|
|
||||||
async def _post(client: httpx.AsyncClient, path: str, body: dict) -> dict:
|
async def _post(client: httpx.AsyncClient, path: str, body: dict, timeout: float = TIMEOUT_SEC) -> dict:
|
||||||
res = await client.post(f"{base_url()}{path}", json=body)
|
res = await client.post(f"{base_url()}{path}", json=body, timeout=timeout)
|
||||||
if res.status_code >= 400:
|
if res.status_code >= 400:
|
||||||
raise SiteOntologyError(f"{path} HTTP {res.status_code}: {res.text[:200]}")
|
raise SiteOntologyError(f"{path} HTTP {res.status_code}: {res.text[:200]}")
|
||||||
try:
|
try:
|
||||||
@@ -40,17 +42,18 @@ async def _post(client: httpx.AsyncClient, path: str, body: dict) -> dict:
|
|||||||
|
|
||||||
async def match_for_merchant(merchant: dict, limit: int = DEFAULT_LIMIT) -> dict:
|
async def match_for_merchant(merchant: dict, limit: int = DEFAULT_LIMIT) -> dict:
|
||||||
"""업체를 저장하고, 그 업체로 해석된 추천 결과(/v1/match 응답)를 돌려준다."""
|
"""업체를 저장하고, 그 업체로 해석된 추천 결과(/v1/match 응답)를 돌려준다."""
|
||||||
body = {**merchant, "generate": False}
|
# sync 는 처음 보는 업체에만 먹는다 — 첫 발행부터 새 키워드가 실리고, 갱신은 저쪽 큐가 한다.
|
||||||
|
body = {**merchant, "generate": True, "sync": True}
|
||||||
try:
|
try:
|
||||||
async with httpx.AsyncClient(timeout=TIMEOUT_SEC) as client:
|
async with httpx.AsyncClient(timeout=TIMEOUT_SEC) as client:
|
||||||
try:
|
try:
|
||||||
await _post(client, PUBLISH_PATH, body)
|
await _post(client, PUBLISH_PATH, body, PUBLISH_TIMEOUT_SEC)
|
||||||
except SiteOntologyError as ex:
|
except SiteOntologyError as ex:
|
||||||
if not body.get("regionId"):
|
if not body.get("regionId"):
|
||||||
raise
|
raise
|
||||||
LOG.w(f"[site-ontology] regionId={body['regionId']} 로 저장하지 못했다 — 지역 없이 다시 보낸다: {ex}")
|
LOG.w(f"[site-ontology] regionId={body['regionId']} 로 저장하지 못했다 — 지역 없이 다시 보낸다: {ex}")
|
||||||
body = {**body, "regionId": None}
|
body = {**body, "regionId": None}
|
||||||
await _post(client, PUBLISH_PATH, body)
|
await _post(client, PUBLISH_PATH, body, PUBLISH_TIMEOUT_SEC)
|
||||||
result = await _post(client, MATCH_PATH, {"query": merchant["externalId"], "limit": limit})
|
result = await _post(client, MATCH_PATH, {"query": merchant["externalId"], "limit": limit})
|
||||||
except httpx.HTTPError as ex:
|
except httpx.HTTPError as ex:
|
||||||
raise SiteOntologyError(f"{type(ex).__name__}: {ex}") from ex
|
raise SiteOntologyError(f"{type(ex).__name__}: {ex}") from ex
|
||||||
|
|||||||
@@ -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"])
|
||||||
@@ -452,8 +452,13 @@ class PostService:
|
|||||||
|
|
||||||
job_id, _created = await enqueue_job(
|
job_id, _created = await enqueue_job(
|
||||||
self.queue, JobType.BUILD,
|
self.queue, JobType.BUILD,
|
||||||
|
# ★ requested_by 는 **사용자 ID 칸**이다(site_publish_logs.actor_user_id).
|
||||||
|
# 예전엔 여기에 "blog-approval" 이라는 라벨을 넣었는데, build_service 가 그걸
|
||||||
|
# uuid.UUID() 에 넣다 죽어 **굽기는 끝났는데 발행 상태만 안 바뀌는** 잡이
|
||||||
|
# 5건 쌓였다(2026-09-23~09-30). 승인을 누른 건 사장님이므로 그 ID 를 넣는다 —
|
||||||
|
# 어느 경로로 왔는지는 아래 LOG 한 줄이 남긴다.
|
||||||
{"place_id": str(place_id), "owner_user_id": str(owner_user_id),
|
{"place_id": str(place_id), "owner_user_id": str(owner_user_id),
|
||||||
"publish": True, "requested_by": "blog-approval"},
|
"publish": True, "requested_by": str(owner_user_id)},
|
||||||
dedupe_key=f"build:{place_id}",
|
dedupe_key=f"build:{place_id}",
|
||||||
)
|
)
|
||||||
LOG.i(f"[blog] post={post_id} → build job={job_id}")
|
LOG.i(f"[blog] post={post_id} → build job={job_id}")
|
||||||
@@ -0,0 +1,84 @@
|
|||||||
|
"""숙소 첫 화면 문구 — 고정 캐치프레이즈 하나와 그 아래 줄에서 도는 문구 모음."""
|
||||||
|
|
||||||
|
from typing import Optional, Sequence
|
||||||
|
|
||||||
|
from services.prompts.copy import FactLike, _fact_lines
|
||||||
|
|
||||||
|
SEASONS = ("봄", "여름", "가을", "겨울")
|
||||||
|
WEATHERS = ("맑음", "흐림", "비", "눈")
|
||||||
|
COUNT_GENERAL = 20
|
||||||
|
COUNT_PER_SEASON = 3
|
||||||
|
COUNT_PER_WEATHER = 2
|
||||||
|
MIN_LEN = 8
|
||||||
|
MAX_LEN = 30
|
||||||
|
|
||||||
|
RESPONSE_SCHEMA = {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"tagline": {"type": "string"},
|
||||||
|
"general": {"type": "array", "items": {"type": "string"}},
|
||||||
|
"season": {
|
||||||
|
"type": "array",
|
||||||
|
"items": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {"season": {"type": "string", "enum": list(SEASONS)}, "text": {"type": "string"}},
|
||||||
|
"required": ["season", "text"],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
"month": {
|
||||||
|
"type": "array",
|
||||||
|
"items": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {"month": {"type": "integer"}, "text": {"type": "string"}},
|
||||||
|
"required": ["month", "text"],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
"weather": {
|
||||||
|
"type": "array",
|
||||||
|
"items": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {"weather": {"type": "string", "enum": list(WEATHERS)}, "text": {"type": "string"}},
|
||||||
|
"required": ["weather", "text"],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
"required": ["tagline", "general", "season", "month", "weather"],
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def build_prompt(
|
||||||
|
place_name: str,
|
||||||
|
facts: Sequence[FactLike],
|
||||||
|
records: Optional[Sequence[str]] = None,
|
||||||
|
) -> str:
|
||||||
|
sections = [
|
||||||
|
f"숙소 '{place_name}' 홈페이지 첫 화면 문구를 쓴다.",
|
||||||
|
"첫 화면은 숙소 이름 아래 **고정 캐치프레이즈 한 줄**, 그 아래 줄에서 짧은 문구가 몇 초마다 바뀐다.",
|
||||||
|
"",
|
||||||
|
"확인된 사실:",
|
||||||
|
_fact_lines(facts) if facts else "- 없음",
|
||||||
|
]
|
||||||
|
if records:
|
||||||
|
sections.extend(["", "출처가 있는 기록:", *(f"- {line}" for line in records)])
|
||||||
|
sections.extend([
|
||||||
|
"",
|
||||||
|
"출력:",
|
||||||
|
f"- tagline: 이 숙소만의 캐치프레이즈 1개, {MIN_LEN}~{MAX_LEN}자. 이 집을 한 줄로 알아보게 하는 문장",
|
||||||
|
f"- general: 계절·날씨와 상관없는 문구 {COUNT_GENERAL}개",
|
||||||
|
f"- season: 봄·여름·가을·겨울 각 {COUNT_PER_SEASON}개",
|
||||||
|
"- month: 1월~12월 각 1개",
|
||||||
|
f"- weather: 맑음·흐림·비·눈 각 {COUNT_PER_WEATHER}개. 그 날씨에 이 집에서 보이고 들리는 것",
|
||||||
|
f"- 모든 문구는 공백 포함 {MIN_LEN}~{MAX_LEN}자, 한 문장",
|
||||||
|
"",
|
||||||
|
"좋은 예(다른 숙소): '백 년 된 집에서 하룻밤' · '담 너머는 히로쓰 가옥입니다' ·"
|
||||||
|
" '마당 평상에 앉으면 항구 소리가 들립니다' · '이불에서 볕 냄새가 납니다'",
|
||||||
|
"",
|
||||||
|
"규칙:",
|
||||||
|
"- 위 사실과 기록에 있는 것만 쓴다. 없는 시설·경관·숫자·거리·역사를 지어내지 않는다.",
|
||||||
|
"- 사실이 적으면 머무는 시간·쉼처럼 확인이 필요 없는 말로 쓴다.",
|
||||||
|
"- 담백하게 쓴다. '최고', '완벽한', '특별한', '힐링' 같은 홍보 수식어와 느낌표를 쓰지 않는다.",
|
||||||
|
"- 문구끼리 표현이 겹치지 않게 한다. 상호명은 tagline 에도 넣지 않는다.",
|
||||||
|
"- false·불가·없음 값을 있는 것처럼 쓰지 않는다.",
|
||||||
|
"- 존댓말 평서문 또는 명사형으로 끝낸다.",
|
||||||
|
])
|
||||||
|
return "\n".join(sections)
|
||||||
@@ -1,6 +1,5 @@
|
|||||||
"""대상 버전 스냅샷 로드 → payload 재조립 → 렌더 → 게이트 → 공개 주소 전환"""
|
"""대상 버전 스냅샷 로드 → payload 재조립 → 렌더 → 게이트 → 공개 주소 전환"""
|
||||||
import os
|
import os
|
||||||
import time
|
|
||||||
import uuid
|
import uuid
|
||||||
|
|
||||||
from common.database.db_session_manager import DB_SESSION_MNG
|
from common.database.db_session_manager import DB_SESSION_MNG
|
||||||
@@ -18,8 +17,8 @@ from common.logger import LOG
|
|||||||
from common.utils.gtime import GTime
|
from common.utils.gtime import GTime
|
||||||
from crud.place_crud import PlaceCRUD
|
from crud.place_crud import PlaceCRUD
|
||||||
from crud.site_crud import SiteCRUD
|
from crud.site_crud import SiteCRUD
|
||||||
from services import activity_feed, alert_service, azure_static, indexnow, publish_gate, render_service, site_payload
|
from services import alert_service, azure_static, indexnow, publish_gate, render_service, site_payload
|
||||||
from services.build_service import post_build_summary, ensure_site, load_channel_links
|
from services.build_service import _actor_uuid, ensure_site, load_channel_links
|
||||||
|
|
||||||
_site_crud = SiteCRUD()
|
_site_crud = SiteCRUD()
|
||||||
_place_crud = PlaceCRUD()
|
_place_crud = PlaceCRUD()
|
||||||
@@ -39,32 +38,15 @@ async def _log(site_id, version_id, result: PublishResult, gate=None, actor=None
|
|||||||
result=result.value,
|
result=result.value,
|
||||||
reject_reason=(gate.reason.value if gate is not None and gate.reason else None),
|
reject_reason=(gate.reason.value if gate is not None and gate.reason else None),
|
||||||
detail=(gate.as_log() if gate is not None and not gate.passed else None),
|
detail=(gate.as_log() if gate is not None and not gate.passed else None),
|
||||||
actor_user_id=uuid.UUID(actor) if actor else None,
|
# ★ build_service 와 같은 함수를 쓴다 — 모양이 틀린 actor 하나가 되돌리기를
|
||||||
|
# 죽이면 안 된다(그쪽 주석에 실측이 있다).
|
||||||
|
actor_user_id=_actor_uuid(actor),
|
||||||
)
|
)
|
||||||
await DB_SESSION_MNG.execute_lambda_run([site_publish_logs.DBType()], [lambda s: _site_crud.add_log(s, row)])
|
await DB_SESSION_MNG.execute_lambda_run([site_publish_logs.DBType()], [lambda s: _site_crud.add_log(s, row)])
|
||||||
|
|
||||||
|
|
||||||
async def run_rollback(job: dict) -> dict:
|
async def run_rollback(job: dict) -> dict:
|
||||||
"""ROLLBACK 잡 핸들러."""
|
"""ROLLBACK 잡 핸들러."""
|
||||||
started = time.monotonic()
|
|
||||||
try:
|
|
||||||
result = await _run_rollback(job)
|
|
||||||
except Exception as ex:
|
|
||||||
await activity_feed.post(
|
|
||||||
"❌ 되돌리기 실패",
|
|
||||||
[f"place_id={job['payload'].get('place_id')} → v{job['payload'].get('target_version')}",
|
|
||||||
f"{type(ex).__name__}: {ex}", f"{time.monotonic() - started:.0f}초"],
|
|
||||||
)
|
|
||||||
raise
|
|
||||||
await post_build_summary(
|
|
||||||
{**result, "version": result.get("target_version"), "mode": "되돌리기",
|
|
||||||
"build_status": "BUILT" if result.get("rolled_back") else "FAILED"},
|
|
||||||
time.monotonic() - started,
|
|
||||||
)
|
|
||||||
return result
|
|
||||||
|
|
||||||
|
|
||||||
async def _run_rollback(job: dict) -> dict:
|
|
||||||
payload = job["payload"]
|
payload = job["payload"]
|
||||||
place_id = payload["place_id"]
|
place_id = payload["place_id"]
|
||||||
owner_user_id = payload["owner_user_id"]
|
owner_user_id = payload["owner_user_id"]
|
||||||
@@ -96,9 +78,7 @@ async def _run_rollback(job: dict) -> dict:
|
|||||||
result = {
|
result = {
|
||||||
"place_id": place_id, "site_id": str(site.site_id),
|
"place_id": place_id, "site_id": str(site.site_id),
|
||||||
"target_version": target_version, "site_version_id": str(version.site_version_id),
|
"target_version": target_version, "site_version_id": str(version.site_version_id),
|
||||||
"label": activity_feed.place_label(place),
|
|
||||||
}
|
}
|
||||||
await activity_feed.post("🏗 되돌리기 시작", [f"{result['label']} → v{target_version}"])
|
|
||||||
|
|
||||||
async def _fail(reason: str, gate: publish_gate.GateResult | None = None):
|
async def _fail(reason: str, gate: publish_gate.GateResult | None = None):
|
||||||
await _log(site.site_id, version.site_version_id, PublishResult.REJECTED if gate else PublishResult.FAILED,
|
await _log(site.site_id, version.site_version_id, PublishResult.REJECTED if gate else PublishResult.FAILED,
|
||||||
@@ -129,8 +109,6 @@ async def _run_rollback(job: dict) -> dict:
|
|||||||
except render_service.RenderFailed as ex:
|
except render_service.RenderFailed as ex:
|
||||||
return await _fail(str(ex))
|
return await _fail(str(ex))
|
||||||
|
|
||||||
if report.get("media"):
|
|
||||||
result["render_media"] = report["media"]
|
|
||||||
mismatches = list(report.get("mismatches") or [])
|
mismatches = list(report.get("mismatches") or [])
|
||||||
unique_count_raw = report.get("uniqueContentCount")
|
unique_count_raw = report.get("uniqueContentCount")
|
||||||
|
|
||||||
@@ -165,6 +143,5 @@ async def _run_rollback(job: dict) -> dict:
|
|||||||
await alert_service.resolve_alert(f"build_failed:{place_id}", f"롤백 성공 — {place_id} → v{target_version}")
|
await alert_service.resolve_alert(f"build_failed:{place_id}", f"롤백 성공 — {place_id} → v{target_version}")
|
||||||
|
|
||||||
result["rolled_back"] = True
|
result["rolled_back"] = True
|
||||||
result["url"] = site_payload.publish_url(place, site)
|
|
||||||
LOG.i(f"[rollback] place={place_id} v{target_version} 로 되돌림")
|
LOG.i(f"[rollback] place={place_id} v{target_version} 로 되돌림")
|
||||||
return result
|
return result
|
||||||
@@ -9,6 +9,9 @@ from services.external import site_ontology
|
|||||||
from services.site_payload import _parse_address_parts
|
from services.site_payload import _parse_address_parts
|
||||||
|
|
||||||
LODGING_INDUSTRY = "stay.pension"
|
LODGING_INDUSTRY = "stay.pension"
|
||||||
|
HOTEL_INDUSTRY = "stay.hotel"
|
||||||
|
# 업종별 숙박 유형어. 자기 유형어만 자료 없이 통과한다 — 호텔에 `군산 독채펜션` 이 붙지 않게.
|
||||||
|
_TYPE_WORDS = {LODGING_INDUSTRY: "펜션", HOTEL_INDUSTRY: "호텔"}
|
||||||
MAX_KEYWORDS = 10
|
MAX_KEYWORDS = 10
|
||||||
MAX_NEARBY = 8
|
MAX_NEARBY = 8
|
||||||
|
|
||||||
@@ -57,9 +60,9 @@ _REGION_KEYS = {
|
|||||||
}
|
}
|
||||||
|
|
||||||
# 자료에 없어도 되는 낱말 — 업종어와 "근처" 류.
|
# 자료에 없어도 되는 낱말 — 업종어와 "근처" 류.
|
||||||
_GENERIC_WORDS = frozenset({"펜션", "숙소", "숙박", "스테이", "근처", "가까운", "주변", "인근", "예약", "추천"})
|
_GENERIC_WORDS = frozenset({"숙소", "숙박", "스테이", "근처", "가까운", "주변", "인근", "예약", "추천"})
|
||||||
# "독채펜션"·"감성숙소" 처럼 붙여 쓴 업종어는 떼고 앞부분만 자료와 대조한다.
|
# "독채펜션"·"감성숙소" 처럼 붙여 쓴 업종어는 떼고 앞부분만 자료와 대조한다.
|
||||||
_GENERIC_SUFFIXES = ("펜션", "숙소", "스테이")
|
_GENERIC_SUFFIXES = ("숙소", "스테이")
|
||||||
# 제목에는 싣지 않는 낱말.
|
# 제목에는 싣지 않는 낱말.
|
||||||
_TITLE_BLOCKED_WORDS = frozenset({"예약", "추천"})
|
_TITLE_BLOCKED_WORDS = frozenset({"예약", "추천"})
|
||||||
# 한 글자 낱말("봄"·"뷰")은 소개문 어딘가에 우연히 들어 있어 대조가 무의미하다 — 통과시키지 않는다.
|
# 한 글자 낱말("봄"·"뷰")은 소개문 어딘가에 우연히 들어 있어 대조가 무의미하다 — 통과시키지 않는다.
|
||||||
@@ -102,6 +105,12 @@ def _locality_word(*addresses: str | None) -> str:
|
|||||||
return word[:-1] if len(word) > 2 and word.endswith(("시", "군", "구")) else word
|
return word[:-1] if len(word) > 2 and word.endswith(("시", "군", "구")) else word
|
||||||
|
|
||||||
|
|
||||||
|
def industry_of(place: dict) -> str:
|
||||||
|
"""외부 분류(없으면 상호)에 '호텔' 이 있으면 호텔, 아니면 펜션."""
|
||||||
|
text = f"{_text(place.get('external_category'))} {_text(place.get('name'))}"
|
||||||
|
return HOTEL_INDUSTRY if "호텔" in text else LODGING_INDUSTRY
|
||||||
|
|
||||||
|
|
||||||
def build_merchant(place_id: str, snapshot: dict) -> dict | None:
|
def build_merchant(place_id: str, snapshot: dict) -> dict | None:
|
||||||
"""스냅샷 → SiteOntology publish 요청 본문."""
|
"""스냅샷 → SiteOntology publish 요청 본문."""
|
||||||
place = (snapshot or {}).get("place") or {}
|
place = (snapshot or {}).get("place") or {}
|
||||||
@@ -157,7 +166,7 @@ def build_merchant(place_id: str, snapshot: dict) -> dict | None:
|
|||||||
return {
|
return {
|
||||||
"externalId": place_id,
|
"externalId": place_id,
|
||||||
"name": name,
|
"name": name,
|
||||||
"industryId": LODGING_INDUSTRY,
|
"industryId": industry_of(place),
|
||||||
"regionId": region_key(road_address, address),
|
"regionId": region_key(road_address, address),
|
||||||
"description": description,
|
"description": description,
|
||||||
"profile": {key: value for key, value in profile.items() if value},
|
"profile": {key: value for key, value in profile.items() if value},
|
||||||
@@ -174,13 +183,14 @@ def _evidence(merchant: dict) -> str:
|
|||||||
return _compact(" ".join(_text(p) for p in parts if p))
|
return _compact(" ".join(_text(p) for p in parts if p))
|
||||||
|
|
||||||
|
|
||||||
def _supported(keyword: str, evidence: str) -> bool:
|
def _supported(keyword: str, evidence: str, type_word: str = "펜션") -> bool:
|
||||||
"""모든 낱말이 자료에 있고, **자료로 확인한 낱말이 하나는 있어야** 한다."""
|
"""모든 낱말이 자료에 있고, **자료로 확인한 낱말이 하나는 있어야** 한다."""
|
||||||
|
suffixes = (*_GENERIC_SUFFIXES, type_word)
|
||||||
specific = False
|
specific = False
|
||||||
for word in keyword.split():
|
for word in keyword.split():
|
||||||
if word in _GENERIC_WORDS:
|
if word in _GENERIC_WORDS or word == type_word:
|
||||||
continue
|
continue
|
||||||
core = next((word[: -len(s)] for s in _GENERIC_SUFFIXES if word.endswith(s) and len(word) > len(s)), word)
|
core = next((word[: -len(s)] for s in suffixes if word.endswith(s) and len(word) > len(s)), word)
|
||||||
core = _compact(core)
|
core = _compact(core)
|
||||||
if len(core) < _MIN_CORE_LEN or core not in evidence:
|
if len(core) < _MIN_CORE_LEN or core not in evidence:
|
||||||
return False
|
return False
|
||||||
@@ -193,15 +203,15 @@ def _is_question(item: dict) -> bool:
|
|||||||
return item.get("category") == "질문형" or "?" in canonical or canonical.endswith(("요", "까"))
|
return item.get("category") == "질문형" or "?" in canonical or canonical.endswith(("요", "까"))
|
||||||
|
|
||||||
|
|
||||||
def _usable(item, evidence: str) -> str | None:
|
def _usable(item, evidence: str, type_word: str) -> str | None:
|
||||||
"""메타 태그에 실어도 되는 추천이면 그 표기를, 아니면 None."""
|
"""메타 태그에 실어도 되는 추천이면 그 표기를, 아니면 None."""
|
||||||
if not isinstance(item, dict) or item.get("status") != "ok" or _is_question(item):
|
if not isinstance(item, dict) or item.get("status") != "ok" or _is_question(item):
|
||||||
return None
|
return None
|
||||||
canonical = _text(item.get("canonical"))
|
canonical = _text(item.get("canonical"))
|
||||||
return canonical if canonical and _supported(canonical, evidence) else None
|
return canonical if canonical and _supported(canonical, evidence, type_word) else None
|
||||||
|
|
||||||
|
|
||||||
def _title_keyword(result: dict, evidence: str, locality: str) -> str | None:
|
def _title_keyword(result: dict, evidence: str, locality: str, type_word: str) -> str | None:
|
||||||
"""제목 업종어 자리에 넣을 대표 키워드 — 유형 레인에서 고른다."""
|
"""제목 업종어 자리에 넣을 대표 키워드 — 유형 레인에서 고른다."""
|
||||||
lane = next(
|
lane = next(
|
||||||
(l for l in result.get("byLane") or [] if isinstance(l, dict) and l.get("key") == "type"),
|
(l for l in result.get("byLane") or [] if isinstance(l, dict) and l.get("key") == "type"),
|
||||||
@@ -209,7 +219,7 @@ def _title_keyword(result: dict, evidence: str, locality: str) -> str | None:
|
|||||||
)
|
)
|
||||||
items = [i for i in lane.get("items") or [] if isinstance(i, dict)]
|
items = [i for i in lane.get("items") or [] if isinstance(i, dict)]
|
||||||
for item in sorted(items, key=lambda i: i.get("category") != "코어"):
|
for item in sorted(items, key=lambda i: i.get("category") != "코어"):
|
||||||
canonical = _usable(item, evidence)
|
canonical = _usable(item, evidence, type_word)
|
||||||
if not canonical or _TITLE_BLOCKED_WORDS.intersection(canonical.split()):
|
if not canonical or _TITLE_BLOCKED_WORDS.intersection(canonical.split()):
|
||||||
continue
|
continue
|
||||||
if locality and locality not in canonical:
|
if locality and locality not in canonical:
|
||||||
@@ -221,10 +231,11 @@ def _title_keyword(result: dict, evidence: str, locality: str) -> str | None:
|
|||||||
def select(result: dict, merchant: dict) -> dict:
|
def select(result: dict, merchant: dict) -> dict:
|
||||||
"""/v1/match 응답 → {keywords, titleKeyword?}."""
|
"""/v1/match 응답 → {keywords, titleKeyword?}."""
|
||||||
evidence = _evidence(merchant)
|
evidence = _evidence(merchant)
|
||||||
|
type_word = _TYPE_WORDS.get(merchant.get("industryId"), _TYPE_WORDS[LODGING_INDUSTRY])
|
||||||
keywords: list[str] = []
|
keywords: list[str] = []
|
||||||
seen: set[str] = set()
|
seen: set[str] = set()
|
||||||
for item in result.get("matches") or []:
|
for item in result.get("matches") or []:
|
||||||
canonical = _usable(item, evidence)
|
canonical = _usable(item, evidence, type_word)
|
||||||
if not canonical or _compact(canonical) in seen:
|
if not canonical or _compact(canonical) in seen:
|
||||||
continue
|
continue
|
||||||
seen.add(_compact(canonical))
|
seen.add(_compact(canonical))
|
||||||
@@ -233,7 +244,7 @@ def select(result: dict, merchant: dict) -> dict:
|
|||||||
break
|
break
|
||||||
|
|
||||||
seo: dict = {"keywords": keywords}
|
seo: dict = {"keywords": keywords}
|
||||||
title = _title_keyword(result, evidence, _locality_word((merchant.get("profile") or {}).get("address")))
|
title = _title_keyword(result, evidence, _locality_word((merchant.get("profile") or {}).get("address")), type_word)
|
||||||
if title:
|
if title:
|
||||||
seo["titleKeyword"] = title
|
seo["titleKeyword"] = title
|
||||||
return seo
|
return seo
|
||||||
|
|||||||
@@ -18,6 +18,7 @@ from common.enums import (
|
|||||||
)
|
)
|
||||||
from common.logger import LOG
|
from common.logger import LOG
|
||||||
from common.template_catalog import TEMPLATES, industry_of, resolve_template_id
|
from common.template_catalog import TEMPLATES, industry_of, resolve_template_id
|
||||||
|
from services import catchphrase_text
|
||||||
from services.intro_summary import summarize_intro
|
from services.intro_summary import summarize_intro
|
||||||
from services.stay_guide import nol_stay_guide
|
from services.stay_guide import nol_stay_guide
|
||||||
from services.weather_notes import weather_notes
|
from services.weather_notes import weather_notes
|
||||||
@@ -33,6 +34,9 @@ DEFAULT_PAYLOAD_DIR = "/app/solution/site/payloads"
|
|||||||
SITE_HOST_ENV = "SITE_PUBLIC_HOST"
|
SITE_HOST_ENV = "SITE_PUBLIC_HOST"
|
||||||
DEFAULT_HOST = os.environ.get(SITE_HOST_ENV, "").strip() or "localhost"
|
DEFAULT_HOST = os.environ.get(SITE_HOST_ENV, "").strip() or "localhost"
|
||||||
|
|
||||||
|
_HERO_COPY_KEYS = {"tagline", "catchphrases"}
|
||||||
|
|
||||||
|
|
||||||
def _scheme(host: str) -> str:
|
def _scheme(host: str) -> str:
|
||||||
"""localhost 는 http 다."""
|
"""localhost 는 http 다."""
|
||||||
return "http" if re.match(r"^(localhost|127\.0\.0\.1)(:\d+)?$", host) else "https"
|
return "http" if re.match(r"^(localhost|127\.0\.0\.1)(:\d+)?$", host) else "https"
|
||||||
@@ -596,6 +600,14 @@ def to_site_payload(place, snapshot: dict, site, version, links, publish: bool =
|
|||||||
# 요약은 **첫 문장**이다.
|
# 요약은 **첫 문장**이다.
|
||||||
"summary": _first_sentence(paragraphs[0]) if paragraphs else None,
|
"summary": _first_sentence(paragraphs[0]) if paragraphs else None,
|
||||||
}
|
}
|
||||||
|
tagline = _text(next((f["value"] for f in place_facts if f["key"] == "tagline" and f["value"]), ""))
|
||||||
|
if tagline:
|
||||||
|
narrative["tagline"] = tagline.strip()
|
||||||
|
rotating = catchphrase_text.decode(
|
||||||
|
_text(next((f["value"] for f in place_facts if f["key"] == "catchphrases" and f["value"]), ""))
|
||||||
|
)
|
||||||
|
if rotating:
|
||||||
|
narrative["catchphrases"] = {"version": 1, "items": rotating}
|
||||||
|
|
||||||
theme = _theme(site, category)
|
theme = _theme(site, category)
|
||||||
|
|
||||||
@@ -651,7 +663,7 @@ def to_site_payload(place, snapshot: dict, site, version, links, publish: bool =
|
|||||||
),
|
),
|
||||||
"kakaoPlaceId": kakao_place_id or None,
|
"kakaoPlaceId": kakao_place_id or None,
|
||||||
},
|
},
|
||||||
"facts": place_facts,
|
"facts": [f for f in place_facts if f["key"] not in _HERO_COPY_KEYS],
|
||||||
"units": units,
|
"units": units,
|
||||||
"media": media,
|
"media": media,
|
||||||
"faqs": faqs,
|
"faqs": faqs,
|
||||||
|
|||||||
@@ -109,6 +109,8 @@ async def build_snapshot(place) -> dict:
|
|||||||
"name": place.name,
|
"name": place.name,
|
||||||
"category": category.value,
|
"category": category.value,
|
||||||
"category_name": schema.label,
|
"category_name": schema.label,
|
||||||
|
# 숙박 안의 유형(호텔·펜션) 판정 근거 — services/seo_keywords.industry_of
|
||||||
|
"external_category": getattr(place, "external_category", None),
|
||||||
"road_address": place.road_address,
|
"road_address": place.road_address,
|
||||||
"address": place.address,
|
"address": place.address,
|
||||||
"phone": place.phone,
|
"phone": place.phone,
|
||||||
|
|||||||
@@ -113,8 +113,9 @@ async def run_vision(job: dict) -> dict:
|
|||||||
|
|
||||||
LOG.i(f"[vision] place={place_id} {stat['analyzed']}장 → 자동반영 {stat['approved']} · "
|
LOG.i(f"[vision] place={place_id} {stat['analyzed']}장 → 자동반영 {stat['approved']} · "
|
||||||
f"확인필요 {stat['needs_review']} · 실패 {stat['failed']} (임계값 {threshold})")
|
f"확인필요 {stat['needs_review']} · 실패 {stat['failed']} (임계값 {threshold})")
|
||||||
|
if stat["failed"]:
|
||||||
await activity_feed.post(
|
await activity_feed.post(
|
||||||
"🖼 사진 분석 완료" if not stat["failed"] else "⚠️ 사진 분석 일부 실패",
|
"⚠️ 사진 분석 일부 실패",
|
||||||
[activity_feed.place_label(place),
|
[activity_feed.place_label(place),
|
||||||
f"분석 {stat['analyzed']} · 승인 {stat['approved']} · 확인대기 {stat['needs_review']} · 실패 {stat['failed']}"],
|
f"분석 {stat['analyzed']} · 승인 {stat['approved']} · 확인대기 {stat['needs_review']} · 실패 {stat['failed']}"],
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -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__} 이 자동 스윕 목록을 본다 — 수동 생성까지 막힌다"
|
||||||
|
)
|
||||||
@@ -459,8 +459,8 @@ async def test_send_now_cannot_be_triggered_for_someone_elses_place(client, db_e
|
|||||||
assert res.json()["result"]["success"] is False
|
assert res.json()["result"]["success"] is False
|
||||||
|
|
||||||
|
|
||||||
async def _publish_site_and_link_kakao(client, db_engine, auth_headers, monkeypatch, login_id, name):
|
async def _publish_site_and_link_kakao(client, db_engine, auth_headers, monkeypatch, login_id, name, link=True):
|
||||||
"""발행된 사이트 + 메일 주소 + 카톡이 연결된 사장님. 카톡 Event API 는 켜 둔다."""
|
"""발행된 사이트 + 메일 주소 + (link=True 면) 카톡이 연결된 사장님. 카톡 Event API 는 켜 둔다."""
|
||||||
from services import kakao_link_service
|
from services import kakao_link_service
|
||||||
|
|
||||||
monkeypatch.setenv("KAKAO_CHANNEL_PUBLIC_ID", "_testCh")
|
monkeypatch.setenv("KAKAO_CHANNEL_PUBLIC_ID", "_testCh")
|
||||||
@@ -477,6 +477,7 @@ async def _publish_site_and_link_kakao(client, db_engine, auth_headers, monkeypa
|
|||||||
)
|
)
|
||||||
await conn.execute(text("UPDATE users SET email = :e WHERE id = :id"), {"e": f"{login_id}@example.com", "id": login_id})
|
await conn.execute(text("UPDATE users SET email = :e WHERE id = :id"), {"e": f"{login_id}@example.com", "id": login_id})
|
||||||
user_id = (await conn.execute(text("SELECT user_id FROM users WHERE id = :id"), {"id": login_id})).scalar_one()
|
user_id = (await conn.execute(text("SELECT user_id FROM users WHERE id = :id"), {"id": login_id})).scalar_one()
|
||||||
|
if link:
|
||||||
await kakao_link_service.redeem((await kakao_link_service.issue_code(user_id))["code"], f"speaker-{login_id}")
|
await kakao_link_service.redeem((await kakao_link_service.issue_code(user_id))["code"], f"speaker-{login_id}")
|
||||||
return place_id, f"speaker-{login_id}", h
|
return place_id, f"speaker-{login_id}", h
|
||||||
|
|
||||||
@@ -496,8 +497,9 @@ def _record_kakao_send(monkeypatch, *, fail=False):
|
|||||||
return calls
|
return calls
|
||||||
|
|
||||||
|
|
||||||
async def test_send_reviewed_also_pushes_to_the_linked_kakao(client, db_engine, auth_headers, monkeypatch):
|
async def test_send_reviewed_sends_only_kakao_when_linked(client, db_engine, auth_headers, monkeypatch):
|
||||||
"""승인 알림은 메일에 더해 연결된 카카오톡으로도 나간다(2026-09-29, 결정: 카톡과 메일 둘 다).
|
"""카톡이 연결돼 있으면 승인 알림은 카톡으로만 나가고 메일은 안 나간다(2026-09-30 변경 —
|
||||||
|
처음엔 '둘 다'였는데 사장님에게 같은 알림이 두 통 가는 게 번거롭다고 했다).
|
||||||
카톡에는 글 ID 와 수정 링크용 일회용 코드가 params 로 실려, 웹훅이 메시지를 그린다."""
|
카톡에는 글 ID 와 수정 링크용 일회용 코드가 params 로 실려, 웹훅이 메시지를 그린다."""
|
||||||
from services import blog_jobs, mail_service
|
from services import blog_jobs, mail_service
|
||||||
|
|
||||||
@@ -511,7 +513,7 @@ async def test_send_reviewed_also_pushes_to_the_linked_kakao(client, db_engine,
|
|||||||
sent = await blog_jobs.send_reviewed()
|
sent = await blog_jobs.send_reviewed()
|
||||||
|
|
||||||
assert sent == 1
|
assert sent == 1
|
||||||
assert len(mails) == 1
|
assert mails == []
|
||||||
assert len(kakao) == 1
|
assert len(kakao) == 1
|
||||||
assert kakao[0]["key"] == speaker
|
assert kakao[0]["key"] == speaker
|
||||||
assert kakao[0]["event"] == "post_approval"
|
assert kakao[0]["event"] == "post_approval"
|
||||||
@@ -520,8 +522,9 @@ async def test_send_reviewed_also_pushes_to_the_linked_kakao(client, db_engine,
|
|||||||
assert await _status(db_engine, post_id) == PostStatus.SENT.value
|
assert await _status(db_engine, post_id) == PostStatus.SENT.value
|
||||||
|
|
||||||
|
|
||||||
async def test_a_failed_kakao_push_does_not_block_the_mail(client, db_engine, auth_headers, monkeypatch):
|
async def test_a_failed_kakao_push_falls_back_to_mail(client, db_engine, auth_headers, monkeypatch):
|
||||||
"""카톡은 채널 친구가 아니거나 차단했으면 실패한다 — 그래서 메일도 같이 보낸다."""
|
"""카톡은 채널 친구가 아니거나 차단했거나 Event API 가 죽으면 실패한다 — 그때만 메일로 대체한다
|
||||||
|
(2026-09-30: 연결돼 있으면 카톡만, 실패했을 때만 메일). 알림이 통째로 사라지지 않게."""
|
||||||
from services import blog_jobs, mail_service
|
from services import blog_jobs, mail_service
|
||||||
|
|
||||||
monkeypatch.setattr(mail_service, "is_configured", lambda: True)
|
monkeypatch.setattr(mail_service, "is_configured", lambda: True)
|
||||||
@@ -587,12 +590,13 @@ async def test_kakao_push_is_off_unless_switched_on(client, db_engine, auth_head
|
|||||||
assert kakao == []
|
assert kakao == []
|
||||||
|
|
||||||
|
|
||||||
async def test_send_now_also_pushes_to_kakao(client, db_engine, auth_headers, monkeypatch):
|
async def test_send_now_sends_only_kakao_when_linked(client, db_engine, auth_headers, monkeypatch):
|
||||||
"""'승인 알림보내기' 버튼도 같은 경로다 — 메일만 가고 카톡은 빠지면 안 된다."""
|
"""'승인 알림보내기' 버튼도 같은 경로다 — 연결돼 있으면 카톡으로만 간다."""
|
||||||
from services import mail_service
|
from services import mail_service
|
||||||
|
|
||||||
monkeypatch.setattr(mail_service, "is_configured", lambda: True)
|
monkeypatch.setattr(mail_service, "is_configured", lambda: True)
|
||||||
monkeypatch.setattr(mail_service, "send", lambda **kwargs: True)
|
mails = []
|
||||||
|
monkeypatch.setattr(mail_service, "send", lambda **kwargs: mails.append(kwargs) or True)
|
||||||
kakao = _record_kakao_send(monkeypatch)
|
kakao = _record_kakao_send(monkeypatch)
|
||||||
place_id, _speaker, h = await _publish_site_and_link_kakao(client, db_engine, auth_headers, monkeypatch, "kakaosend6", "카톡즉시펜션")
|
place_id, _speaker, h = await _publish_site_and_link_kakao(client, db_engine, auth_headers, monkeypatch, "kakaosend6", "카톡즉시펜션")
|
||||||
await _seed_post(db_engine, place_id, scheduled=date.today())
|
await _seed_post(db_engine, place_id, scheduled=date.today())
|
||||||
@@ -601,6 +605,61 @@ async def test_send_now_also_pushes_to_kakao(client, db_engine, auth_headers, mo
|
|||||||
|
|
||||||
assert res.json()["result"]["success"] is True
|
assert res.json()["result"]["success"] is True
|
||||||
assert len(kakao) == 1
|
assert len(kakao) == 1
|
||||||
|
assert mails == []
|
||||||
|
|
||||||
|
|
||||||
|
async def test_send_now_falls_back_to_mail_when_kakao_fails(client, db_engine, auth_headers, monkeypatch):
|
||||||
|
"""'승인 알림보내기' 도 같은 정책이다 — 카톡이 실패하면 메일로 나가 사장님 화면에는 성공으로 보인다."""
|
||||||
|
from services import mail_service
|
||||||
|
|
||||||
|
monkeypatch.setattr(mail_service, "is_configured", lambda: True)
|
||||||
|
mails = []
|
||||||
|
monkeypatch.setattr(mail_service, "send", lambda **kwargs: mails.append(kwargs) or True)
|
||||||
|
kakao = _record_kakao_send(monkeypatch, fail=True)
|
||||||
|
place_id, _speaker, h = await _publish_site_and_link_kakao(client, db_engine, auth_headers, monkeypatch, "kakaosend7", "카톡즉시실패펜션")
|
||||||
|
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 len(kakao) == 1
|
||||||
|
assert len(mails) == 1
|
||||||
|
|
||||||
|
|
||||||
|
async def test_send_now_reports_failure_when_both_kakao_and_mail_fail(client, db_engine, auth_headers, monkeypatch):
|
||||||
|
"""둘 다 안 나갔으면 사장님 화면에 실패로 보여야 한다 — 성공처럼 보이면 알림이 안 간 걸 모른다."""
|
||||||
|
from services import mail_service
|
||||||
|
|
||||||
|
monkeypatch.setattr(mail_service, "is_configured", lambda: False)
|
||||||
|
_record_kakao_send(monkeypatch, fail=True)
|
||||||
|
place_id, _speaker, h = await _publish_site_and_link_kakao(client, db_engine, auth_headers, monkeypatch, "kakaosend9", "카톡메일둘다실패펜션")
|
||||||
|
post_id = 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 False
|
||||||
|
assert await _status(db_engine, post_id) == PostStatus.REVIEWED.value
|
||||||
|
|
||||||
|
|
||||||
|
async def test_mail_is_still_sent_when_kakao_is_not_linked(client, db_engine, auth_headers, monkeypatch):
|
||||||
|
"""카톡을 연결하지 않은 사장님은 스위치가 켜져 있어도 예전처럼 메일을 받는다."""
|
||||||
|
from services import blog_jobs, mail_service
|
||||||
|
|
||||||
|
monkeypatch.setattr(mail_service, "is_configured", lambda: True)
|
||||||
|
mails = []
|
||||||
|
monkeypatch.setattr(mail_service, "send", lambda **kwargs: mails.append(kwargs) or True)
|
||||||
|
kakao = _record_kakao_send(monkeypatch)
|
||||||
|
place_id, _speaker, _h = await _publish_site_and_link_kakao(
|
||||||
|
client, db_engine, auth_headers, monkeypatch, "kakaosend8", "카톡미연결펜션", link=False,
|
||||||
|
)
|
||||||
|
post_id = await _seed_post(db_engine, place_id, scheduled=date.today())
|
||||||
|
|
||||||
|
sent = await blog_jobs.send_reviewed()
|
||||||
|
|
||||||
|
assert sent == 1
|
||||||
|
assert len(mails) == 1
|
||||||
|
assert kakao == []
|
||||||
|
assert await _status(db_engine, post_id) == PostStatus.SENT.value
|
||||||
|
|
||||||
|
|
||||||
async def _day_pass_headers(db_engine, login_id: str) -> dict:
|
async def _day_pass_headers(db_engine, login_id: str) -> dict:
|
||||||
@@ -1183,3 +1242,64 @@ def test_메일_본문에_액세스_토큰이_없다():
|
|||||||
assert "eyJ" not in body # JWT 의 머리글자
|
assert "eyJ" not in body # JWT 의 머리글자
|
||||||
longest = max(len(word) for word in body.split())
|
longest = max(len(word) for word in body.split())
|
||||||
assert longest < 120, f"링크가 아직 길다: {longest}자"
|
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.status_code == 200
|
||||||
assert res.json()["success"] is False
|
assert res.json()["success"] is False
|
||||||
assert "전화" in res.json()["message"]
|
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]
|
||||||
@@ -348,3 +348,42 @@ async def test_렌더_보고서의_값이_그대로_박제된다(auth_headers, c
|
|||||||
assert row["jsonld"], "렌더러가 내보낸 JSON-LD 가 박제되지 않았다"
|
assert row["jsonld"], "렌더러가 내보낸 JSON-LD 가 박제되지 않았다"
|
||||||
# 렌더러 대역이 내보낸 노드가 그대로 들어와야 한다(백엔드가 다시 만들지 않는다).
|
# 렌더러 대역이 내보낸 노드가 그대로 들어와야 한다(백엔드가 다시 만들지 않는다).
|
||||||
assert row["jsonld"][0]["@type"] == "LodgingBusiness"
|
assert row["jsonld"][0]["@type"] == "LodgingBusiness"
|
||||||
|
|
||||||
|
|
||||||
|
# ── requested_by 가 사용자 ID 가 아닐 때 (2026-09-30) ──────────────────────────
|
||||||
|
#
|
||||||
|
# ★ 실측: 미니블로그 승인 경로가 `requested_by="blog-approval"` 이라는 **라벨**을 넣었고,
|
||||||
|
# `_log` 가 그걸 uuid.UUID() 에 넣다 ValueError 를 던졌다. `_log` 는 사이트를 다 구운 뒤
|
||||||
|
# `sites.status = PUBLISHED` 를 찍기 **전에** 불리므로, 굽기는 끝났는데 발행만 안 된 채
|
||||||
|
# 3회 재시도 후 DEAD 가 됐다(BUILD 잡 5건, 2026-09-23~09-30).
|
||||||
|
# 사장님 화면에는 "카톡으로 승인했는데 홈페이지가 그대로" 로만 보인다.
|
||||||
|
|
||||||
|
import uuid as _uuid
|
||||||
|
|
||||||
|
from services.build_service import _actor_uuid
|
||||||
|
|
||||||
|
|
||||||
|
def test_actor_가_사용자_ID_가_아니면_기록만_비우고_넘어간다():
|
||||||
|
"""던지면 발행이 죽는 자리다 — 감사 기록 한 줄이 발행을 막으면 순서가 뒤집힌 것이다."""
|
||||||
|
assert _actor_uuid("blog-approval") is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_actor_가_비면_None():
|
||||||
|
assert _actor_uuid(None) is None
|
||||||
|
assert _actor_uuid("") is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_정상_사용자_ID_는_그대로_UUID_가_된다():
|
||||||
|
uid = "6dafad19-48fd-4692-8944-4ba76359205f"
|
||||||
|
assert _actor_uuid(uid) == _uuid.UUID(uid)
|
||||||
|
|
||||||
|
|
||||||
|
def test_미니블로그_승인은_사장님_ID_를_requested_by_로_넣는다():
|
||||||
|
"""★ 라벨을 다시 넣으면 같은 사고가 난다 — 호출부에서도 못 박는다."""
|
||||||
|
import inspect
|
||||||
|
|
||||||
|
from services.post_service import PostService
|
||||||
|
|
||||||
|
src = inspect.getsource(PostService._enqueue_build)
|
||||||
|
assert '"requested_by": "blog-approval"' not in src
|
||||||
|
assert '"requested_by": str(owner_user_id)' in src
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
"""순환 문구 글 형식 — 사장님이 줄 단위로 고친 글이 그대로 계절·월·날씨 문구로 읽혀야 한다."""
|
||||||
|
from services import catchphrase_text
|
||||||
|
|
||||||
|
|
||||||
|
def test_round_trips_every_kind():
|
||||||
|
items = [
|
||||||
|
{"text": "백 년 된 집에서 하룻밤", "kind": "general"},
|
||||||
|
{"text": "봄에는 대문을 열어 둡니다", "kind": "season", "season": "봄"},
|
||||||
|
{"text": "새해 첫 아침을 이 집에서", "kind": "month", "month": 1},
|
||||||
|
{"text": "기와에 빗소리가 납니다", "kind": "weather", "weather": "비"},
|
||||||
|
]
|
||||||
|
text = catchphrase_text.encode(items)
|
||||||
|
assert text.splitlines() == [
|
||||||
|
"백 년 된 집에서 하룻밤",
|
||||||
|
"봄 | 봄에는 대문을 열어 둡니다",
|
||||||
|
"1월 | 새해 첫 아침을 이 집에서",
|
||||||
|
"비 | 기와에 빗소리가 납니다",
|
||||||
|
]
|
||||||
|
assert catchphrase_text.decode(text) == items
|
||||||
|
|
||||||
|
|
||||||
|
def test_unknown_tag_stays_a_general_line():
|
||||||
|
assert catchphrase_text.decode("장마 | 비가 옵니다\n\n 13월 | 없는 달 ") == [
|
||||||
|
{"text": "장마 | 비가 옵니다", "kind": "general"},
|
||||||
|
{"text": "13월 | 없는 달", "kind": "general"},
|
||||||
|
]
|
||||||
@@ -30,6 +30,15 @@ def _patch(monkeypatch, copy):
|
|||||||
|
|
||||||
monkeypatch.setattr(gemini_text, "generate_copy", _gen)
|
monkeypatch.setattr(gemini_text, "generate_copy", _gen)
|
||||||
|
|
||||||
|
async def _phrases(place_name, facts, **kw):
|
||||||
|
return gemini_text.GeneratedCatchphrases(
|
||||||
|
tagline="체크인 오후 세 시, 조용한 집",
|
||||||
|
items=[{"text": "짐을 풀면 골목부터 걸어 보세요", "kind": "general"},
|
||||||
|
{"text": "봄에는 창을 열어 둡니다", "kind": "season", "season": "봄"}],
|
||||||
|
)
|
||||||
|
|
||||||
|
monkeypatch.setattr(gemini_text, "generate_catchphrases", _phrases)
|
||||||
|
|
||||||
|
|
||||||
async def _place_with_facts(client, h, n_verified=5):
|
async def _place_with_facts(client, h, n_verified=5):
|
||||||
pid = (await client.post("/v1/place", headers=h, json={"name": "카피펜션", "category": 1})).json()["place"]["place_id"]
|
pid = (await client.post("/v1/place", headers=h, json={"name": "카피펜션", "category": 1})).json()["place"]["place_id"]
|
||||||
@@ -96,7 +105,7 @@ async def test_resume_reuses_completed_job(auth_headers, client, db_engine, monk
|
|||||||
job = (await client.get(f"/v1/job/{first['job_id']}", headers=h)).json()["job"]
|
job = (await client.get(f"/v1/job/{first['job_id']}", headers=h)).json()["job"]
|
||||||
assert job["place_id"] == pid
|
assert job["place_id"] == pid
|
||||||
assert [(s["id"], s["status"]) for s in job["progress"]["steps"]] == [
|
assert [(s["id"], s["status"]) for s in job["progress"]["steps"]] == [
|
||||||
("prepare", "done"), ("generate", "done"), ("save", "done"), ("faq_fill", "done"),
|
("prepare", "done"), ("generate", "done"), ("save", "done"), ("catchphrase", "done"), ("faq_fill", "done"),
|
||||||
]
|
]
|
||||||
fresh = (await client.post(path, headers=h, json={})).json()
|
fresh = (await client.post(path, headers=h, json={})).json()
|
||||||
assert fresh["job_id"] != first["job_id"]
|
assert fresh["job_id"] != first["job_id"]
|
||||||
@@ -111,7 +120,7 @@ async def test_copy_progress_is_visible_during_generation(auth_headers, client,
|
|||||||
async def generate(*args, **kwargs):
|
async def generate(*args, **kwargs):
|
||||||
row = await JobQueue().get(started["job_id"])
|
row = await JobQueue().get(started["job_id"])
|
||||||
assert row["status"] == JobStatus.RUNNING.value
|
assert row["status"] == JobStatus.RUNNING.value
|
||||||
assert [step["status"] for step in row["progress"]["steps"]] == ["done", "running", "pending", "pending"]
|
assert [step["status"] for step in row["progress"]["steps"]] == ["done", "running", "pending", "pending", "pending"]
|
||||||
return _copy()
|
return _copy()
|
||||||
|
|
||||||
monkeypatch.setattr(gemini_text, "generate_copy", generate)
|
monkeypatch.setattr(gemini_text, "generate_copy", generate)
|
||||||
@@ -303,3 +312,21 @@ async def test_copy_requires_api_key(auth_headers, client, monkeypatch):
|
|||||||
pid = await _place_with_facts(client, h)
|
pid = await _place_with_facts(client, h)
|
||||||
r = await client.post(f"/v1/place/{pid}/copy", headers=h, json={})
|
r = await client.post(f"/v1/place/{pid}/copy", headers=h, json={})
|
||||||
assert r.json()["result"]["code"] == ErrorType.GENERATOR_NOT_CONFIGURED.value
|
assert r.json()["result"]["code"] == ErrorType.GENERATOR_NOT_CONFIGURED.value
|
||||||
|
|
||||||
|
|
||||||
|
async def test_copy_writes_one_catchphrase_and_the_rotating_lines(auth_headers, client, db_engine, monkeypatch):
|
||||||
|
_patch(monkeypatch, _copy())
|
||||||
|
h = await auth_headers("catchphrase-owner")
|
||||||
|
pid = await _place_with_facts(client, h)
|
||||||
|
job_id = (await client.post(f"/v1/place/{pid}/copy", headers=h, json={})).json()["job_id"]
|
||||||
|
await Worker("w", JobQueue(), build_handler(), job_deadline_sec=30).drain()
|
||||||
|
job = (await client.get(f"/v1/job/{job_id}", headers=h)).json()["job"]
|
||||||
|
assert job["result"]["catchphrase"]["tagline"] is True
|
||||||
|
assert job["result"]["catchphrase"]["catchphrases"] == 2
|
||||||
|
async with db_engine.begin() as c:
|
||||||
|
rows = dict((await c.execute(
|
||||||
|
text("SELECT key, value FROM place_facts WHERE place_id = :p AND key IN ('tagline', 'catchphrases')"),
|
||||||
|
{"p": uuid.UUID(pid)},
|
||||||
|
)).all())
|
||||||
|
assert rows["tagline"] == "체크인 오후 세 시, 조용한 집"
|
||||||
|
assert rows["catchphrases"] == "짐을 풀면 골목부터 걸어 보세요\n봄 | 봄에는 창을 열어 둡니다"
|
||||||
@@ -377,3 +377,34 @@ async def test_summarize_empty_text_returns_none():
|
|||||||
"""검증: 빈 문자열."""
|
"""검증: 빈 문자열."""
|
||||||
result = await gt.summarize_text(" ")
|
result = await gt.summarize_text(" ")
|
||||||
assert result is None
|
assert result is None
|
||||||
|
|
||||||
|
|
||||||
|
# ── 첫 화면 문구 ───────────────────────────────────────────────────────────
|
||||||
|
def _phrase_payload(body):
|
||||||
|
return {
|
||||||
|
"candidates": [{"content": {"parts": [{"text": json.dumps(body, ensure_ascii=False)}]}, "finishReason": "STOP"}],
|
||||||
|
"usageMetadata": {"promptTokenCount": 800, "candidatesTokenCount": 400},
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
async def test_catchphrases_keep_only_grounded_lines_of_the_right_shape():
|
||||||
|
body = {
|
||||||
|
"tagline": "주차하고 바로 쉬는 집",
|
||||||
|
"general": ["짐을 풀면 골목부터 걸어 보세요", "오션뷰 수영장이 있습니다", "짧다", "하조대펜션에서 쉬세요"],
|
||||||
|
"season": [{"season": "봄", "text": "봄에는 창을 열어 둡니다"}, {"season": "장마", "text": "비가 오래 오는 계절입니다"}],
|
||||||
|
"month": [{"month": 1, "text": "새해 첫 아침을 조용히"}, {"month": 13, "text": "없는 달의 문구입니다"}],
|
||||||
|
"weather": [{"weather": "비", "text": "빗소리를 들으며 쉬세요"}],
|
||||||
|
}
|
||||||
|
async with _client(_ok(_phrase_payload(body))) as c:
|
||||||
|
res = await gt.generate_catchphrases("하조대펜션", FACTS, client=c)
|
||||||
|
assert res.tagline == "주차하고 바로 쉬는 집"
|
||||||
|
assert res.items == [
|
||||||
|
{"text": "짐을 풀면 골목부터 걸어 보세요", "kind": "general"},
|
||||||
|
{"text": "봄에는 창을 열어 둡니다", "kind": "season", "season": "봄"},
|
||||||
|
{"text": "새해 첫 아침을 조용히", "kind": "month", "month": 1},
|
||||||
|
{"text": "빗소리를 들으며 쉬세요", "kind": "weather", "weather": "비"},
|
||||||
|
]
|
||||||
|
reasons = dict(res.rejected)
|
||||||
|
assert "오션뷰 수영장이 있습니다" in reasons
|
||||||
|
assert reasons["짧다"].startswith("길이")
|
||||||
|
assert reasons["하조대펜션에서 쉬세요"] == "상호명 포함"
|
||||||
@@ -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
|
||||||
@@ -0,0 +1,58 @@
|
|||||||
|
"""스케줄러에 무엇이 등록돼 있나.
|
||||||
|
|
||||||
|
★★ 이 파일이 있는 이유: `sweep_blog_drafts` 가 **등록돼 있지 않았다**(실측 2026-09-30).
|
||||||
|
`scheduler/jobs.py` 에 함수는 있고 주석도 "새벽에 재고를 채운다" 라고 말하는데
|
||||||
|
`add_job` 한 줄이 없어 한 번도 돈 적이 없다. 증상은 "미니블로그 메일이 안 온다" 로만
|
||||||
|
보여서 발송 쪽을 보게 된다 — 실제로는 **보낼 글이 0건**이었다.
|
||||||
|
잡 하나가 빠져도 서버는 정상으로 뜨고 로그에도 에러가 없다. 그래서 세는 것이다.
|
||||||
|
"""
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
import scheduler
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def start(monkeypatch):
|
||||||
|
"""실제로 돌리지 않는다 — 등록만 본다."""
|
||||||
|
def _start(**env):
|
||||||
|
monkeypatch.setenv("SCHEDULER_ENABLED", "1")
|
||||||
|
for k, v in env.items():
|
||||||
|
monkeypatch.setenv(k, v)
|
||||||
|
monkeypatch.setattr("apscheduler.schedulers.asyncio.AsyncIOScheduler.start", lambda self: None)
|
||||||
|
scheduler._scheduler = None
|
||||||
|
scheduler.start_scheduler()
|
||||||
|
return scheduler._scheduler
|
||||||
|
|
||||||
|
yield _start
|
||||||
|
scheduler._scheduler = None
|
||||||
|
|
||||||
|
|
||||||
|
def test_발송은_스위치_없이도_등록된다(start):
|
||||||
|
"""메일·카톡 발송은 항상 돈다 — 사장님이 직접 만든 글도 나가야 한다."""
|
||||||
|
assert "blog-mail" in {j.id for j in start().get_jobs()}
|
||||||
|
|
||||||
|
|
||||||
|
def test_자동_재고채우기는_기본으로_꺼져_있다(start):
|
||||||
|
"""★ 2026-10-01 대표 지시. 켜면 발행 사이트 전체에 업장당 30건씩 AI 호출이 일어난다 —
|
||||||
|
기본값이 정할 일이 아니다."""
|
||||||
|
assert "blog-drafts" not in {j.id for j in start().get_jobs()}
|
||||||
|
|
||||||
|
|
||||||
|
def test_스위치를_켜면_등록된다(start):
|
||||||
|
"""★ 빠뜨린 것과 끈 것은 다르다 — 켜지는지까지 봐야 '격리했다' 가 성립한다."""
|
||||||
|
assert "blog-drafts" in {j.id for j in start(BLOG_AUTO_DRAFTS_ENABLED="1").get_jobs()}
|
||||||
|
|
||||||
|
|
||||||
|
def test_재고_채우기가_발송보다_앞선다(start):
|
||||||
|
"""그날 아침에 나갈 글이 있으려면 생성이 먼저여야 한다."""
|
||||||
|
by_id = {j.id: j for j in start(BLOG_AUTO_DRAFTS_ENABLED="1").get_jobs()}
|
||||||
|
hour = lambda j: int(str(by_id[j].trigger.fields[by_id[j].trigger.FIELD_NAMES.index("hour")]))
|
||||||
|
assert hour("blog-drafts") < hour("blog-mail")
|
||||||
|
|
||||||
|
|
||||||
|
def test_스위치가_꺼지면_아무것도_등록하지_않는다(monkeypatch):
|
||||||
|
"""키 없는 환경에 돌지도 않을 잡을 만들어 두지 않는다."""
|
||||||
|
monkeypatch.setenv("SCHEDULER_ENABLED", "0")
|
||||||
|
scheduler._scheduler = None
|
||||||
|
scheduler.start_scheduler()
|
||||||
|
assert scheduler._scheduler is None
|
||||||
@@ -177,8 +177,8 @@ async def test_업체를_저장한_뒤_그_업체로_추천을_받는다(ontolog
|
|||||||
await site_ontology.match_for_merchant(merchant)
|
await site_ontology.match_for_merchant(merchant)
|
||||||
|
|
||||||
assert [url for url, _ in sent] == ["http://onto.test/v1/merchants/publish", "http://onto.test/v1/match"]
|
assert [url for url, _ in sent] == ["http://onto.test/v1/merchants/publish", "http://onto.test/v1/match"]
|
||||||
# generate:false 가 빠지면 SiteOntology 가 LLM 키워드 생성을 큐에 넣는다.
|
# 처음 보는 업체는 생성을 기다려 첫 발행부터 새 키워드가 실린다(sync 는 저쪽이 처음 보는 업체에만 먹인다).
|
||||||
assert sent[0][1] == {**merchant, "generate": False}
|
assert sent[0][1] == {**merchant, "generate": True, "sync": True}
|
||||||
assert sent[1][1] == {"query": "place-1", "limit": site_ontology.DEFAULT_LIMIT}
|
assert sent[1][1] == {"query": "place-1", "limit": site_ontology.DEFAULT_LIMIT}
|
||||||
|
|
||||||
|
|
||||||
@@ -296,3 +296,32 @@ async def test_SiteOntology_가_죽어도_발행된다(auth_headers, client, db_
|
|||||||
assert site["site"]["status"] == SiteStatus.PUBLISHED.value
|
assert site["site"]["status"] == SiteStatus.PUBLISHED.value
|
||||||
payload = json.loads(open(r["payload_path"], encoding="utf-8").read())
|
payload = json.loads(open(r["payload_path"], encoding="utf-8").read())
|
||||||
assert "seo" not in payload
|
assert "seo" not in payload
|
||||||
|
|
||||||
|
|
||||||
|
# ── 호텔 ───────────────────────────────────────────────────────────────────
|
||||||
|
def test_외부_분류에_호텔이_있으면_호텔_업종으로_보낸다():
|
||||||
|
merchant = seo_keywords.build_merchant("place-1", _snapshot(external_category="여행 > 숙박 > 호텔"))
|
||||||
|
assert merchant["industryId"] == "stay.hotel"
|
||||||
|
|
||||||
|
|
||||||
|
def test_외부_분류가_없으면_상호로_가른다():
|
||||||
|
assert seo_keywords.build_merchant("place-1", _snapshot(name="군산 베이 호텔"))["industryId"] == "stay.hotel"
|
||||||
|
assert seo_keywords.build_merchant("place-1", _snapshot())["industryId"] == "stay.pension"
|
||||||
|
|
||||||
|
|
||||||
|
def _item(canonical):
|
||||||
|
return {"canonical": canonical, "status": "ok", "category": "코어"}
|
||||||
|
|
||||||
|
|
||||||
|
def test_호텔에는_펜션_유형어를_싣지_않는다():
|
||||||
|
merchant = seo_keywords.build_merchant("place-1", _snapshot(name="군산 베이 호텔"))
|
||||||
|
result = {"matches": [_item("군산 독채펜션"), _item("군산 독채 호텔"), _item("말랭이마을 숙소")]}
|
||||||
|
|
||||||
|
assert seo_keywords.select(result, merchant)["keywords"] == ["군산 독채 호텔", "말랭이마을 숙소"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_펜션에는_호텔_유형어를_싣지_않는다():
|
||||||
|
merchant = seo_keywords.build_merchant("place-1", _snapshot())
|
||||||
|
result = {"matches": [_item("군산 독채 호텔"), _item("군산 독채펜션")]}
|
||||||
|
|
||||||
|
assert seo_keywords.select(result, merchant)["keywords"] == ["군산 독채펜션"]
|
||||||
@@ -0,0 +1,104 @@
|
|||||||
|
Copyright (c) 2021, Kil Hyung-jin (https://github.com/orioncactus/pretendard),
|
||||||
|
with Reserved Font Name 'Pretendard'.
|
||||||
|
|
||||||
|
Copyright 2014-2021 Adobe (http://www.adobe.com/),
|
||||||
|
with Reserved Font Name 'Source'.
|
||||||
|
Source is a trademark of Adobe in the United States and/or other countries.
|
||||||
|
|
||||||
|
Copyright (c) 2016 The Inter Project Authors (https://github.com/rsms/inter),
|
||||||
|
with Reserved Font Name 'Inter'.
|
||||||
|
|
||||||
|
Copyright 2021 The M+ FONTS Project Authors (https://github.com/coz-m/MPLUS_FONTS),
|
||||||
|
with Reserved Font Name 'M PLUS 1'.
|
||||||
|
|
||||||
|
This Font Software is licensed under the SIL Open Font License, Version 1.1.
|
||||||
|
This license is copied below, and is also available with a FAQ at:
|
||||||
|
https://scripts.sil.org/OFL
|
||||||
|
|
||||||
|
|
||||||
|
-----------------------------------------------------------
|
||||||
|
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
|
||||||
|
-----------------------------------------------------------
|
||||||
|
|
||||||
|
PREAMBLE
|
||||||
|
The goals of the Open Font License (OFL) are to stimulate worldwide
|
||||||
|
development of collaborative font projects, to support the font creation
|
||||||
|
efforts of academic and linguistic communities, and to provide a free and
|
||||||
|
open framework in which fonts may be shared and improved in partnership
|
||||||
|
with others.
|
||||||
|
|
||||||
|
The OFL allows the licensed fonts to be used, studied, modified and
|
||||||
|
redistributed freely as long as they are not sold by themselves. The
|
||||||
|
fonts, including any derivative works, can be bundled, embedded,
|
||||||
|
redistributed and/or sold with any software provided that any reserved
|
||||||
|
names are not used by derivative works. The fonts and derivatives,
|
||||||
|
however, cannot be released under any other type of license. The
|
||||||
|
requirement for fonts to remain under this license does not apply
|
||||||
|
to any document created using the fonts or their derivatives.
|
||||||
|
|
||||||
|
DEFINITIONS
|
||||||
|
"Font Software" refers to the set of files released by the Copyright
|
||||||
|
Holder(s) under this license and clearly marked as such. This may
|
||||||
|
include source files, build scripts and documentation.
|
||||||
|
|
||||||
|
"Reserved Font Name" refers to any names specified as such after the
|
||||||
|
copyright statement(s).
|
||||||
|
|
||||||
|
"Original Version" refers to the collection of Font Software components as
|
||||||
|
distributed by the Copyright Holder(s).
|
||||||
|
|
||||||
|
"Modified Version" refers to any derivative made by adding to, deleting,
|
||||||
|
or substituting -- in part or in whole -- any of the components of the
|
||||||
|
Original Version, by changing formats or by porting the Font Software to a
|
||||||
|
new environment.
|
||||||
|
|
||||||
|
"Author" refers to any designer, engineer, programmer, technical
|
||||||
|
writer or other person who contributed to the Font Software.
|
||||||
|
|
||||||
|
PERMISSION & CONDITIONS
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining
|
||||||
|
a copy of the Font Software, to use, study, copy, merge, embed, modify,
|
||||||
|
redistribute, and sell modified and unmodified copies of the Font
|
||||||
|
Software, subject to the following conditions:
|
||||||
|
|
||||||
|
1) Neither the Font Software nor any of its individual components,
|
||||||
|
in Original or Modified Versions, may be sold by itself.
|
||||||
|
|
||||||
|
2) Original or Modified Versions of the Font Software may be bundled,
|
||||||
|
redistributed and/or sold with any software, provided that each copy
|
||||||
|
contains the above copyright notice and this license. These can be
|
||||||
|
included either as stand-alone text files, human-readable headers or
|
||||||
|
in the appropriate machine-readable metadata fields within text or
|
||||||
|
binary files as long as those fields can be easily viewed by the user.
|
||||||
|
|
||||||
|
3) No Modified Version of the Font Software may use the Reserved Font
|
||||||
|
Name(s) unless explicit written permission is granted by the corresponding
|
||||||
|
Copyright Holder. This restriction only applies to the primary font name as
|
||||||
|
presented to the users.
|
||||||
|
|
||||||
|
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
|
||||||
|
Software shall not be used to promote, endorse or advertise any
|
||||||
|
Modified Version, except to acknowledge the contribution(s) of the
|
||||||
|
Copyright Holder(s) and the Author(s) or with their explicit written
|
||||||
|
permission.
|
||||||
|
|
||||||
|
5) The Font Software, modified or unmodified, in part or in whole,
|
||||||
|
must be distributed entirely under this license, and must not be
|
||||||
|
distributed under any other license. The requirement for fonts to
|
||||||
|
remain under this license does not apply to any document created
|
||||||
|
using the Font Software.
|
||||||
|
|
||||||
|
TERMINATION
|
||||||
|
This license becomes null and void if any of the above conditions are
|
||||||
|
not met.
|
||||||
|
|
||||||
|
DISCLAIMER
|
||||||
|
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||||
|
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
|
||||||
|
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
|
||||||
|
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
|
||||||
|
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||||
|
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
|
||||||
|
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||||
|
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
|
||||||
|
OTHER DEALINGS IN THE FONT SOFTWARE.
|
||||||
Binary file not shown.
@@ -3,6 +3,7 @@ export const GENERATION_LABELS: Record<string, string> = {
|
|||||||
prepare: '수집된 사진 분류 및 대체 텍스트 생성',
|
prepare: '수집된 사진 분류 및 대체 텍스트 생성',
|
||||||
generate: '브랜드 컬러 시스템 및 타이포그래피 조합',
|
generate: '브랜드 컬러 시스템 및 타이포그래피 조합',
|
||||||
save: '확인된 사실만으로 소개 콘텐츠 구성',
|
save: '확인된 사실만으로 소개 콘텐츠 구성',
|
||||||
|
catchphrase: '첫 화면 캐치프레이즈와 순환 문구 작성',
|
||||||
faq_fill: '위치 기반 길찾기 연동 및 구조화 데이터(JSON-LD) 준비',
|
faq_fill: '위치 기반 길찾기 연동 및 구조화 데이터(JSON-LD) 준비',
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -10,5 +11,6 @@ export const SKIP_REASONS: Record<string, string> = {
|
|||||||
no_facts: '확인된 정보 없음',
|
no_facts: '확인된 정보 없음',
|
||||||
not_configured: '생성 서비스 미설정',
|
not_configured: '생성 서비스 미설정',
|
||||||
no_catalog: '공통 질문 대상 업종 아님',
|
no_catalog: '공통 질문 대상 업종 아님',
|
||||||
|
not_lodging: '숙박 업종만 해당',
|
||||||
generation_failed: '생성 서비스 응답 실패 — 확인된 정보만으로 계속합니다',
|
generation_failed: '생성 서비스 응답 실패 — 확인된 정보만으로 계속합니다',
|
||||||
};
|
};
|
||||||
@@ -3,9 +3,11 @@ import {Link, Navigate, useLocation, useNavigate} from 'react-router';
|
|||||||
import {LogIn} from 'lucide-react';
|
import {LogIn} from 'lucide-react';
|
||||||
import {googleLogin, login} from '@/api';
|
import {googleLogin, login} from '@/api';
|
||||||
import {GoogleSignInButton} from '@/components/auth/GoogleSignInButton';
|
import {GoogleSignInButton} from '@/components/auth/GoogleSignInButton';
|
||||||
|
import {KakaoSignInButton} from '@/components/auth/KakaoSignInButton';
|
||||||
import {Button} from '@/components/ui/button';
|
import {Button} from '@/components/ui/button';
|
||||||
import {Input} from '@/components/ui/input';
|
import {Input} from '@/components/ui/input';
|
||||||
import {isGoogleLoginEnabled} from '@/lib/googleIdentity';
|
import {isGoogleLoginEnabled} from '@/lib/googleIdentity';
|
||||||
|
import {isKakaoLoginEnabled} from '@/lib/kakaoIdentity';
|
||||||
import {notifyApiError} from '@/lib/notify';
|
import {notifyApiError} from '@/lib/notify';
|
||||||
import {establishSession} from '@/lib/session';
|
import {establishSession} from '@/lib/session';
|
||||||
import {useAuthStore} from '@/stores/auth';
|
import {useAuthStore} from '@/stores/auth';
|
||||||
@@ -129,14 +131,19 @@ export function LoginPage({
|
|||||||
<span>로그인</span>
|
<span>로그인</span>
|
||||||
</Button>
|
</Button>
|
||||||
|
|
||||||
{selfServe && isGoogleLoginEnabled() && (
|
{selfServe && (isKakaoLoginEnabled() || isGoogleLoginEnabled()) && (
|
||||||
<>
|
<>
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
<span className="h-px flex-1 bg-border" />
|
<span className="h-px flex-1 bg-border" />
|
||||||
<span className="text-[11px] text-muted-foreground">또는</span>
|
<span className="text-[11px] text-muted-foreground">또는</span>
|
||||||
<span className="h-px flex-1 bg-border" />
|
<span className="h-px flex-1 bg-border" />
|
||||||
</div>
|
</div>
|
||||||
|
{/* ★ 카카오를 위에 둔다 — 카톡 채널로 홈페이지를 관리하려면 이 수단이어야
|
||||||
|
회원번호가 이어진다(docs/AGENT.md). 구글로 들어오면 6자리 코드를 거쳐야 한다. */}
|
||||||
|
<KakaoSignInButton returnTo={from} />
|
||||||
|
{isGoogleLoginEnabled() && (
|
||||||
<GoogleSignInButton onCredential={handleGoogle} text="signin_with" />
|
<GoogleSignInButton onCredential={handleGoogle} text="signin_with" />
|
||||||
|
)}
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
|||||||
@@ -3,9 +3,11 @@ import {Link, Navigate, useNavigate} from 'react-router';
|
|||||||
import {UserPlus} from 'lucide-react';
|
import {UserPlus} from 'lucide-react';
|
||||||
import {googleLogin, signup} from '@/api';
|
import {googleLogin, signup} from '@/api';
|
||||||
import {GoogleSignInButton} from '@/components/auth/GoogleSignInButton';
|
import {GoogleSignInButton} from '@/components/auth/GoogleSignInButton';
|
||||||
|
import {KakaoSignInButton} from '@/components/auth/KakaoSignInButton';
|
||||||
import {Button} from '@/components/ui/button';
|
import {Button} from '@/components/ui/button';
|
||||||
import {Input} from '@/components/ui/input';
|
import {Input} from '@/components/ui/input';
|
||||||
import {isGoogleLoginEnabled} from '@/lib/googleIdentity';
|
import {isGoogleLoginEnabled} from '@/lib/googleIdentity';
|
||||||
|
import {isKakaoLoginEnabled} from '@/lib/kakaoIdentity';
|
||||||
import {notify, notifyApiError} from '@/lib/notify';
|
import {notify, notifyApiError} from '@/lib/notify';
|
||||||
import {establishSession} from '@/lib/session';
|
import {establishSession} from '@/lib/session';
|
||||||
import {useAuthStore} from '@/stores/auth';
|
import {useAuthStore} from '@/stores/auth';
|
||||||
@@ -179,14 +181,19 @@ export function SignupPage() {
|
|||||||
<span>가입하기</span>
|
<span>가입하기</span>
|
||||||
</Button>
|
</Button>
|
||||||
|
|
||||||
{isGoogleLoginEnabled() && (
|
{(isKakaoLoginEnabled() || isGoogleLoginEnabled()) && (
|
||||||
<>
|
<>
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
<span className="h-px flex-1 bg-border" />
|
<span className="h-px flex-1 bg-border" />
|
||||||
<span className="text-[11px] text-muted-foreground">또는</span>
|
<span className="text-[11px] text-muted-foreground">또는</span>
|
||||||
<span className="h-px flex-1 bg-border" />
|
<span className="h-px flex-1 bg-border" />
|
||||||
</div>
|
</div>
|
||||||
|
{/* ★ 카카오는 가입과 로그인이 같은 동작이다 — 처음 온 회원번호면 백엔드가 그 자리에서
|
||||||
|
계정을 만든다. 그래서 두 화면이 같은 버튼을 쓴다. */}
|
||||||
|
<KakaoSignInButton label="카카오로 가입하기" />
|
||||||
|
{isGoogleLoginEnabled() && (
|
||||||
<GoogleSignInButton onCredential={handleGoogle} text="signup_with" />
|
<GoogleSignInButton onCredential={handleGoogle} text="signup_with" />
|
||||||
|
)}
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ import {
|
|||||||
ExternalLink,
|
ExternalLink,
|
||||||
Loader2,
|
Loader2,
|
||||||
MoreHorizontal,
|
MoreHorizontal,
|
||||||
|
Newspaper,
|
||||||
Pencil,
|
Pencil,
|
||||||
Plus,
|
Plus,
|
||||||
Search,
|
Search,
|
||||||
@@ -20,7 +21,7 @@ import {
|
|||||||
X,
|
X,
|
||||||
} from 'lucide-react';
|
} from 'lucide-react';
|
||||||
import {PlaceCategory, publishUrlString, SiteStatus} from '@o2o/shared';
|
import {PlaceCategory, publishUrlString, SiteStatus} from '@o2o/shared';
|
||||||
import {changeStatus, PublishAction, useListMySites, type MySiteData} from '@/api';
|
import {changeStatus, PublishAction, useListMySites, UserRole, type MySiteData} from '@/api';
|
||||||
import {AppShell, EmptyState, PageContainer} from '@/components/layout/AppShell';
|
import {AppShell, EmptyState, PageContainer} from '@/components/layout/AppShell';
|
||||||
import {Badge} from '@/components/ui/badge';
|
import {Badge} from '@/components/ui/badge';
|
||||||
import {Button} from '@/components/ui/button';
|
import {Button} from '@/components/ui/button';
|
||||||
@@ -28,6 +29,7 @@ import {Input} from '@/components/ui/input';
|
|||||||
import {notify, notifyApiError} from '@/lib/notify';
|
import {notify, notifyApiError} from '@/lib/notify';
|
||||||
import {PUBLISH_HOST} from '@/lib/site';
|
import {PUBLISH_HOST} from '@/lib/site';
|
||||||
import {cn} from '@/lib/utils';
|
import {cn} from '@/lib/utils';
|
||||||
|
import {useAuthStore} from '@/stores/auth';
|
||||||
|
|
||||||
// 발행본 주소는 PublishModal·CanvasView 와 같은 규칙이다 — 세 곳이 다른 주소를 말하면 안 된다.
|
// 발행본 주소는 PublishModal·CanvasView 와 같은 규칙이다 — 세 곳이 다른 주소를 말하면 안 된다.
|
||||||
|
|
||||||
@@ -136,6 +138,7 @@ function SiteThumb({row, Icon}: {row: MySiteData; Icon: typeof Building2}) {
|
|||||||
/** 내 사이트 — 로그인한 사장님의 홈이다. */
|
/** 내 사이트 — 로그인한 사장님의 홈이다. */
|
||||||
export function SitesPage() {
|
export function SitesPage() {
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
|
const canManageBlog = (useAuthStore((s) => s.user?.role) ?? 0) >= UserRole.OWNER;
|
||||||
const {data, isLoading, isError, error, refetch} = useListMySites({size: 50});
|
const {data, isLoading, isError, error, refetch} = useListMySites({size: 50});
|
||||||
const [busyId, setBusyId] = useState<string | null>(null);
|
const [busyId, setBusyId] = useState<string | null>(null);
|
||||||
const [menuId, setMenuId] = useState<string | null>(null);
|
const [menuId, setMenuId] = useState<string | null>(null);
|
||||||
@@ -392,6 +395,19 @@ export function SitesPage() {
|
|||||||
<Pencil className="size-3.5" />
|
<Pencil className="size-3.5" />
|
||||||
디자인·컨텐츠 관리
|
디자인·컨텐츠 관리
|
||||||
</button>
|
</button>
|
||||||
|
{canManageBlog && (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => {
|
||||||
|
setMenuId(null);
|
||||||
|
navigate(`/blog?placeId=${row.place_id}`);
|
||||||
|
}}
|
||||||
|
className="flex w-full cursor-pointer items-center gap-2 px-3 py-2 text-left text-xs transition-colors hover:bg-muted"
|
||||||
|
>
|
||||||
|
<Newspaper className="size-3.5" />
|
||||||
|
미니블로그 관리
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
<div className="my-1 border-t border-border" />
|
<div className="my-1 border-t border-border" />
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
|
|||||||
@@ -322,10 +322,19 @@ export interface RouteEntry {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export interface Narrative {
|
export interface Narrative {
|
||||||
/** 히어로 둘째 줄에서 순환할 문구. */
|
/** 히어로 둘째 줄에서 순환할 문구. 첫째 줄(캐치프레이즈)은 `tagline` 하나로 고정이다. */
|
||||||
catchphrases?: {
|
catchphrases?: {
|
||||||
version: 1;
|
version: 1;
|
||||||
items: {text: string; kind?: 'general' | 'season' | 'month' | 'weather'}[];
|
items: {
|
||||||
|
text: string;
|
||||||
|
kind?: 'general' | 'season' | 'month' | 'weather';
|
||||||
|
/** kind=season 일 때 봄·여름·가을·겨울. */
|
||||||
|
season?: string;
|
||||||
|
/** kind=month 일 때 1~12. */
|
||||||
|
month?: number;
|
||||||
|
/** kind=weather 일 때 맑음·흐림·비·눈. */
|
||||||
|
weather?: string;
|
||||||
|
}[];
|
||||||
};
|
};
|
||||||
|
|
||||||
heroHeadline?: string;
|
heroHeadline?: string;
|
||||||
|
|||||||
@@ -0,0 +1,104 @@
|
|||||||
|
Copyright (c) 2021, Kil Hyung-jin (https://github.com/orioncactus/pretendard),
|
||||||
|
with Reserved Font Name 'Pretendard'.
|
||||||
|
|
||||||
|
Copyright 2014-2021 Adobe (http://www.adobe.com/),
|
||||||
|
with Reserved Font Name 'Source'.
|
||||||
|
Source is a trademark of Adobe in the United States and/or other countries.
|
||||||
|
|
||||||
|
Copyright (c) 2016 The Inter Project Authors (https://github.com/rsms/inter),
|
||||||
|
with Reserved Font Name 'Inter'.
|
||||||
|
|
||||||
|
Copyright 2021 The M+ FONTS Project Authors (https://github.com/coz-m/MPLUS_FONTS),
|
||||||
|
with Reserved Font Name 'M PLUS 1'.
|
||||||
|
|
||||||
|
This Font Software is licensed under the SIL Open Font License, Version 1.1.
|
||||||
|
This license is copied below, and is also available with a FAQ at:
|
||||||
|
https://scripts.sil.org/OFL
|
||||||
|
|
||||||
|
|
||||||
|
-----------------------------------------------------------
|
||||||
|
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
|
||||||
|
-----------------------------------------------------------
|
||||||
|
|
||||||
|
PREAMBLE
|
||||||
|
The goals of the Open Font License (OFL) are to stimulate worldwide
|
||||||
|
development of collaborative font projects, to support the font creation
|
||||||
|
efforts of academic and linguistic communities, and to provide a free and
|
||||||
|
open framework in which fonts may be shared and improved in partnership
|
||||||
|
with others.
|
||||||
|
|
||||||
|
The OFL allows the licensed fonts to be used, studied, modified and
|
||||||
|
redistributed freely as long as they are not sold by themselves. The
|
||||||
|
fonts, including any derivative works, can be bundled, embedded,
|
||||||
|
redistributed and/or sold with any software provided that any reserved
|
||||||
|
names are not used by derivative works. The fonts and derivatives,
|
||||||
|
however, cannot be released under any other type of license. The
|
||||||
|
requirement for fonts to remain under this license does not apply
|
||||||
|
to any document created using the fonts or their derivatives.
|
||||||
|
|
||||||
|
DEFINITIONS
|
||||||
|
"Font Software" refers to the set of files released by the Copyright
|
||||||
|
Holder(s) under this license and clearly marked as such. This may
|
||||||
|
include source files, build scripts and documentation.
|
||||||
|
|
||||||
|
"Reserved Font Name" refers to any names specified as such after the
|
||||||
|
copyright statement(s).
|
||||||
|
|
||||||
|
"Original Version" refers to the collection of Font Software components as
|
||||||
|
distributed by the Copyright Holder(s).
|
||||||
|
|
||||||
|
"Modified Version" refers to any derivative made by adding to, deleting,
|
||||||
|
or substituting -- in part or in whole -- any of the components of the
|
||||||
|
Original Version, by changing formats or by porting the Font Software to a
|
||||||
|
new environment.
|
||||||
|
|
||||||
|
"Author" refers to any designer, engineer, programmer, technical
|
||||||
|
writer or other person who contributed to the Font Software.
|
||||||
|
|
||||||
|
PERMISSION & CONDITIONS
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining
|
||||||
|
a copy of the Font Software, to use, study, copy, merge, embed, modify,
|
||||||
|
redistribute, and sell modified and unmodified copies of the Font
|
||||||
|
Software, subject to the following conditions:
|
||||||
|
|
||||||
|
1) Neither the Font Software nor any of its individual components,
|
||||||
|
in Original or Modified Versions, may be sold by itself.
|
||||||
|
|
||||||
|
2) Original or Modified Versions of the Font Software may be bundled,
|
||||||
|
redistributed and/or sold with any software, provided that each copy
|
||||||
|
contains the above copyright notice and this license. These can be
|
||||||
|
included either as stand-alone text files, human-readable headers or
|
||||||
|
in the appropriate machine-readable metadata fields within text or
|
||||||
|
binary files as long as those fields can be easily viewed by the user.
|
||||||
|
|
||||||
|
3) No Modified Version of the Font Software may use the Reserved Font
|
||||||
|
Name(s) unless explicit written permission is granted by the corresponding
|
||||||
|
Copyright Holder. This restriction only applies to the primary font name as
|
||||||
|
presented to the users.
|
||||||
|
|
||||||
|
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
|
||||||
|
Software shall not be used to promote, endorse or advertise any
|
||||||
|
Modified Version, except to acknowledge the contribution(s) of the
|
||||||
|
Copyright Holder(s) and the Author(s) or with their explicit written
|
||||||
|
permission.
|
||||||
|
|
||||||
|
5) The Font Software, modified or unmodified, in part or in whole,
|
||||||
|
must be distributed entirely under this license, and must not be
|
||||||
|
distributed under any other license. The requirement for fonts to
|
||||||
|
remain under this license does not apply to any document created
|
||||||
|
using the Font Software.
|
||||||
|
|
||||||
|
TERMINATION
|
||||||
|
This license becomes null and void if any of the above conditions are
|
||||||
|
not met.
|
||||||
|
|
||||||
|
DISCLAIMER
|
||||||
|
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||||
|
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
|
||||||
|
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
|
||||||
|
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
|
||||||
|
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||||
|
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
|
||||||
|
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||||
|
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
|
||||||
|
OTHER DEALINGS IN THE FONT SOFTWARE.
|
||||||
Binary file not shown.
@@ -46,7 +46,7 @@ it('고택은 섹션 순서와 상관없이 날씨를 첫 화면 바로 아래
|
|||||||
payload.theme.sections = [...payload.theme.sections.filter((s) => s.id !== 'weather'), ...(weather ? [weather] : [])];
|
payload.theme.sections = [...payload.theme.sections.filter((s) => s.id !== 'weather'), ...(weather ? [weather] : [])];
|
||||||
const html = renderToStaticMarkup(<App payload={payload} />);
|
const html = renderToStaticMarkup(<App payload={payload} />);
|
||||||
const hero = html.indexOf('class="hero"');
|
const hero = html.indexOf('class="hero"');
|
||||||
const brief = html.indexOf('class="wbrief"');
|
const brief = html.indexOf('data-editor-id="weather"');
|
||||||
expect(hero).toBeGreaterThan(-1);
|
expect(hero).toBeGreaterThan(-1);
|
||||||
expect(brief).toBeGreaterThan(hero);
|
expect(brief).toBeGreaterThan(hero);
|
||||||
expect(html.slice(hero, brief)).not.toContain('class="sec');
|
expect(html.slice(hero, brief)).not.toContain('class="sec');
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import {useState} from 'react';
|
|||||||
import type {LocalPlace} from '@o2o/shared';
|
import type {LocalPlace} from '@o2o/shared';
|
||||||
import {useSite} from '@site/lib/site-context';
|
import {useSite} from '@site/lib/site-context';
|
||||||
import {naverMapSearchUrl} from '@site/lib/format';
|
import {naverMapSearchUrl} from '@site/lib/format';
|
||||||
|
import {PhotoCard} from '../kit/Card';
|
||||||
import {Sheet} from '../paper/Sheet';
|
import {Sheet} from '../paper/Sheet';
|
||||||
import {Idx} from './SectionHead';
|
import {Idx} from './SectionHead';
|
||||||
import {Tabs} from './Tabs';
|
import {Tabs} from './Tabs';
|
||||||
@@ -66,6 +67,17 @@ export function Around() {
|
|||||||
</li>
|
</li>
|
||||||
);
|
);
|
||||||
|
|
||||||
|
const spot = (place: LocalPlace) => (
|
||||||
|
<PhotoCard
|
||||||
|
key={place.name}
|
||||||
|
image={place.imageUrl}
|
||||||
|
title={place.name}
|
||||||
|
meta={place.distanceText}
|
||||||
|
desc={place.description}
|
||||||
|
onClick={() => setOpen(place)}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
{rail.length > 0 && (
|
{rail.length > 0 && (
|
||||||
@@ -86,16 +98,14 @@ export function Around() {
|
|||||||
<section id="walk" aria-labelledby="walk-heading">
|
<section id="walk" aria-labelledby="walk-heading">
|
||||||
<Idx id="walk-heading" title="주변 명소" aside={`${spots.length} Spots`} />
|
<Idx id="walk-heading" title="주변 명소" aside={`${spots.length} Spots`} />
|
||||||
<Tabs items={rangeTabs(spots)} value={spotRange} onChange={setSpotRange} />
|
<Tabs items={rangeTabs(spots)} value={spotRange} onChange={setSpotRange} />
|
||||||
<ul className="guide">{shownSpots.slice(0, firstSpots).map((place, i) => item(place, i))}</ul>
|
<div className="kgrid">{shownSpots.slice(0, firstSpots).map(spot)}</div>
|
||||||
{shownSpots.length > firstSpots && (
|
{shownSpots.length > firstSpots && (
|
||||||
<details>
|
<details>
|
||||||
<summary className="line">
|
<summary className="line">
|
||||||
<span>{shownSpots.length - firstSpots}곳 더 보기</span>
|
<span>{shownSpots.length - firstSpots}곳 더 보기</span>
|
||||||
<span>+</span>
|
<span>+</span>
|
||||||
</summary>
|
</summary>
|
||||||
<ul className="guide">
|
<div className="kgrid">{shownSpots.slice(firstSpots).map(spot)}</div>
|
||||||
{shownSpots.slice(firstSpots).map((place, i) => item(place, i + firstSpots))}
|
|
||||||
</ul>
|
|
||||||
</details>
|
</details>
|
||||||
)}
|
)}
|
||||||
</section>
|
</section>
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import {useState} from 'react';
|
|||||||
import type {FestivalEntry} from '@o2o/shared';
|
import type {FestivalEntry} from '@o2o/shared';
|
||||||
import {useSite} from '@site/lib/site-context';
|
import {useSite} from '@site/lib/site-context';
|
||||||
import {naverSearchUrl} from '@site/lib/format';
|
import {naverSearchUrl} from '@site/lib/format';
|
||||||
|
import {PhotoCard} from '../kit/Card';
|
||||||
import {Car} from '../paper/Car';
|
import {Car} from '../paper/Car';
|
||||||
import {Sheet} from '../paper/Sheet';
|
import {Sheet} from '../paper/Sheet';
|
||||||
import {Idx} from './SectionHead';
|
import {Idx} from './SectionHead';
|
||||||
@@ -34,17 +35,12 @@ export function Festival() {
|
|||||||
arrows
|
arrows
|
||||||
label="계절별 축제"
|
label="계절별 축제"
|
||||||
slides={shown.map((f) => (
|
slides={shown.map((f) => (
|
||||||
<button type="button" className="fc" onClick={() => setOpen(f)}>
|
<PhotoCard
|
||||||
{f.imageUrl ? (
|
image={f.imageUrl}
|
||||||
<span className="ph">
|
title={f.name}
|
||||||
<img src={f.imageUrl} alt={f.name} loading="lazy" />
|
meta={[f.month, f.location].filter(Boolean).join(' · ')}
|
||||||
</span>
|
onClick={() => setOpen(f)}
|
||||||
) : (
|
/>
|
||||||
<span className="noimg">{f.name}</span>
|
|
||||||
)}
|
|
||||||
<span className="t">{f.name}</span>
|
|
||||||
<span className="d">{[f.month, f.location].filter(Boolean).join(' · ')}</span>
|
|
||||||
</button>
|
|
||||||
))}
|
))}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import {PlaceCategory} from '@o2o/shared';
|
import {PlaceCategory} from '@o2o/shared';
|
||||||
import {HeroCatchphrase} from '@site/sections/HeroCatchphrase';
|
import {HeroCatchphrase, HeroRotator} from '@site/sections/HeroCatchphrase';
|
||||||
import {useSite} from '@site/lib/site-context';
|
import {useSite} from '@site/lib/site-context';
|
||||||
import {bookingActionLabel, bookingLinks, isSectionEnabled, stayBookingView} from '@site/lib/derive';
|
import {bookingActionLabel, bookingLinks, isSectionEnabled, stayBookingView} from '@site/lib/derive';
|
||||||
import {BOOK_EVENT} from '../paper/Rooms';
|
import {BOOK_EVENT} from '../paper/Rooms';
|
||||||
@@ -29,7 +29,7 @@ export function Hero() {
|
|||||||
<span className="no" /> 오늘의 문장
|
<span className="no" /> 오늘의 문장
|
||||||
</p>
|
</p>
|
||||||
{(lodging || fixed) && <p className="rot">{lodging ? <HeroCatchphrase /> : fixed}</p>}
|
{(lodging || fixed) && <p className="rot">{lodging ? <HeroCatchphrase /> : fixed}</p>}
|
||||||
{lodging && fixed && <p className="m sub">{fixed}</p>}
|
<HeroRotator className="m sub" />
|
||||||
<div className="hx">
|
<div className="hx">
|
||||||
{stay ? (
|
{stay ? (
|
||||||
<button type="button" className="line line--ink" onClick={() => window.dispatchEvent(new Event(BOOK_EVENT))}>
|
<button type="button" className="line line--ink" onClick={() => window.dispatchEvent(new Event(BOOK_EVENT))}>
|
||||||
|
|||||||
@@ -284,3 +284,7 @@
|
|||||||
.w4-bigtype .ppl{grid-template-columns:repeat(auto-fit,minmax(220px,1fr))}
|
.w4-bigtype .ppl{grid-template-columns:repeat(auto-fit,minmax(220px,1fr))}
|
||||||
.w4-bigtype .amen{grid-template-columns:repeat(auto-fit,minmax(220px,1fr))}}
|
.w4-bigtype .amen{grid-template-columns:repeat(auto-fit,minmax(220px,1fr))}}
|
||||||
.w4-bigtype .lead+:is(.chips,.tabrow){margin-top:20px}
|
.w4-bigtype .lead+:is(.chips,.tabrow){margin-top:20px}
|
||||||
|
.w4-bigtype{--kc-r:0;--kc-tw:500;--kc-ts:17px;--kc-mc:var(--sub);--kc-sub:var(--sub);--kc-px:12px;--kc-pb:14px}
|
||||||
|
.w4-bigtype .kgrid{gap:0;margin-top:0;border-top:1px solid var(--line);width:calc(100% + 1px);clip-path:inset(0 1px 0 0)}
|
||||||
|
.w4-bigtype .kgrid>.kcard{border-right:1px solid var(--line);border-bottom:1px solid var(--line)}
|
||||||
|
@media (min-width:1024px){.w4-bigtype .kgrid{grid-template-columns:repeat(4,minmax(0,1fr));gap:0}}
|
||||||
@@ -2,6 +2,7 @@ import {useState} from 'react';
|
|||||||
import type {LocalPlace} from '@o2o/shared';
|
import type {LocalPlace} from '@o2o/shared';
|
||||||
import {useSite} from '@site/lib/site-context';
|
import {useSite} from '@site/lib/site-context';
|
||||||
import {naverMapSearchUrl} from '@site/lib/format';
|
import {naverMapSearchUrl} from '@site/lib/format';
|
||||||
|
import {PhotoCard} from '../kit/Card';
|
||||||
import {Sheet} from '../paper/Sheet';
|
import {Sheet} from '../paper/Sheet';
|
||||||
|
|
||||||
const WALK = 80;
|
const WALK = 80;
|
||||||
@@ -70,6 +71,17 @@ export function Around() {
|
|||||||
</button>
|
</button>
|
||||||
);
|
);
|
||||||
|
|
||||||
|
const spot = (item: LocalPlace) => (
|
||||||
|
<PhotoCard
|
||||||
|
key={item.name}
|
||||||
|
image={item.imageUrl}
|
||||||
|
title={item.name}
|
||||||
|
meta={item.distanceText}
|
||||||
|
desc={item.description}
|
||||||
|
onClick={() => setOpen(item)}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
{rail.length > 0 && (
|
{rail.length > 0 && (
|
||||||
@@ -78,7 +90,7 @@ export function Around() {
|
|||||||
<p className="label">AROUND</p>
|
<p className="label">AROUND</p>
|
||||||
<h2 id="around-heading">주변 안내</h2>
|
<h2 id="around-heading">주변 안내</h2>
|
||||||
<p className="lead">걸어서 닿는 명소와 맛집입니다.</p>
|
<p className="lead">걸어서 닿는 명소와 맛집입니다.</p>
|
||||||
<div className="guide">{rail.slice(0, HOME_ROWS).map((item) => place(item))}</div>
|
<div className="guide guide--card">{rail.slice(0, HOME_ROWS).map(spot)}</div>
|
||||||
<a className="link b-more--c" href="#/area">
|
<a className="link b-more--c" href="#/area">
|
||||||
지역 소개에서 모두 보기
|
지역 소개에서 모두 보기
|
||||||
</a>
|
</a>
|
||||||
@@ -95,11 +107,11 @@ export function Around() {
|
|||||||
</h2>
|
</h2>
|
||||||
<p className="lead">걸어서 닿는 곳부터 차로 가는 곳까지 묶었습니다.</p>
|
<p className="lead">걸어서 닿는 곳부터 차로 가는 곳까지 묶었습니다.</p>
|
||||||
<RangeTabs places={spots} value={spotRange} onChange={setSpotRange} />
|
<RangeTabs places={spots} value={spotRange} onChange={setSpotRange} />
|
||||||
<div className="guide">{shownSpots.slice(0, firstSpots).map((item) => place(item))}</div>
|
<div className="guide guide--card">{shownSpots.slice(0, firstSpots).map(spot)}</div>
|
||||||
{shownSpots.length > firstSpots && (
|
{shownSpots.length > firstSpots && (
|
||||||
<details className="fold" key={spotRange}>
|
<details className="fold" key={spotRange}>
|
||||||
<summary className="link">{shownSpots.length - firstSpots}곳 더 보기</summary>
|
<summary className="link">{shownSpots.length - firstSpots}곳 더 보기</summary>
|
||||||
<div className="guide">{shownSpots.slice(firstSpots).map((item) => place(item))}</div>
|
<div className="guide guide--card">{shownSpots.slice(firstSpots).map(spot)}</div>
|
||||||
</details>
|
</details>
|
||||||
)}
|
)}
|
||||||
</section>
|
</section>
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import {useState} from 'react';
|
|||||||
import type {FestivalEntry} from '@o2o/shared';
|
import type {FestivalEntry} from '@o2o/shared';
|
||||||
import {useSite} from '@site/lib/site-context';
|
import {useSite} from '@site/lib/site-context';
|
||||||
import {naverSearchUrl} from '@site/lib/format';
|
import {naverSearchUrl} from '@site/lib/format';
|
||||||
|
import {PhotoCard} from '../kit/Card';
|
||||||
import {Sheet} from '../paper/Sheet';
|
import {Sheet} from '../paper/Sheet';
|
||||||
|
|
||||||
const SEASONS = ['봄', '여름', '가을', '겨울'];
|
const SEASONS = ['봄', '여름', '가을', '겨울'];
|
||||||
@@ -40,15 +41,13 @@ export function Festival() {
|
|||||||
)}
|
)}
|
||||||
<div className="rail">
|
<div className="rail">
|
||||||
{shown.map((f) => (
|
{shown.map((f) => (
|
||||||
<button key={f.name} type="button" className="card" onClick={() => setOpen(f)}>
|
<PhotoCard
|
||||||
{f.imageUrl ? (
|
key={f.name}
|
||||||
<img src={f.imageUrl} alt={f.name} loading="lazy" />
|
image={f.imageUrl}
|
||||||
) : (
|
title={f.name}
|
||||||
<span className="noimg">{f.name}</span>
|
meta={[f.month, f.location].filter(Boolean).join(' · ')}
|
||||||
)}
|
onClick={() => setOpen(f)}
|
||||||
<b className="nm">{f.name}</b>
|
/>
|
||||||
<span className="ds">{[f.month, f.location].filter(Boolean).join(' · ')}</span>
|
|
||||||
</button>
|
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import {useEffect, useState} from 'react';
|
import {useEffect, useState} from 'react';
|
||||||
import {HeroCatchphrase} from '@site/sections/HeroCatchphrase';
|
import {HeroCatchphrase, HeroRotator} from '@site/sections/HeroCatchphrase';
|
||||||
import {useSite} from '@site/lib/site-context';
|
import {useSite} from '@site/lib/site-context';
|
||||||
import {bookingActionLabel, bookingLinks, isSectionEnabled, stayBookingView} from '@site/lib/derive';
|
import {bookingActionLabel, bookingLinks, isSectionEnabled, stayBookingView} from '@site/lib/derive';
|
||||||
import {PlaceCategory} from '@o2o/shared';
|
import {PlaceCategory} from '@o2o/shared';
|
||||||
@@ -26,7 +26,6 @@ export function Hero() {
|
|||||||
}, 5000);
|
}, 5000);
|
||||||
return () => window.clearInterval(timer);
|
return () => window.clearInterval(timer);
|
||||||
}, [total]);
|
}, [total]);
|
||||||
const fixed = narrative.tagline ?? narrative.heroSubline;
|
|
||||||
const english = place.englishName?.trim();
|
const english = place.englishName?.trim();
|
||||||
const locality = [place.addressLocality, place.addressRegion].find(Boolean);
|
const locality = [place.addressLocality, place.addressRegion].find(Boolean);
|
||||||
const stayBooking = place.category === PlaceCategory.LODGING ? stayBookingView(payload) : null;
|
const stayBooking = place.category === PlaceCategory.LODGING ? stayBookingView(payload) : null;
|
||||||
@@ -57,10 +56,10 @@ export function Hero() {
|
|||||||
{english && <p className="b-hero-en">{english}</p>}
|
{english && <p className="b-hero-en">{english}</p>}
|
||||||
<h1 className={english ? 'b-hero-name' : 'b-hero-name b-hero-name--solo'}>{place.name}</h1>
|
<h1 className={english ? 'b-hero-name' : 'b-hero-name b-hero-name--solo'}>{place.name}</h1>
|
||||||
{locality && <p className="b-hero-loc">{locality}</p>}
|
{locality && <p className="b-hero-loc">{locality}</p>}
|
||||||
{fixed && <p className="b-hero-ko">{fixed}</p>}
|
|
||||||
<p className="b-hero-cp">
|
<p className="b-hero-cp">
|
||||||
<HeroCatchphrase />
|
<HeroCatchphrase />
|
||||||
</p>
|
</p>
|
||||||
|
<HeroRotator className="b-hero-ko" />
|
||||||
<div className="b-hero-act">
|
<div className="b-hero-act">
|
||||||
{stayBooking ? (
|
{stayBooking ? (
|
||||||
<button type="button" className="btn" onClick={() => window.dispatchEvent(new Event(BOOK_EVENT))}>
|
<button type="button" className="btn" onClick={() => window.dispatchEvent(new Event(BOOK_EVENT))}>
|
||||||
|
|||||||
@@ -345,3 +345,22 @@
|
|||||||
.w4-boutique[data-page=story] main .b-rule{margin-left:0;margin-right:0}
|
.w4-boutique[data-page=story] main .b-rule{margin-left:0;margin-right:0}
|
||||||
.w4-boutique[data-page=story] main .shell{padding-inline:24px}
|
.w4-boutique[data-page=story] main .shell{padding-inline:24px}
|
||||||
.w4-boutique[data-page=story] main #reviews{margin-top:var(--sec)}}
|
.w4-boutique[data-page=story] main #reviews{margin-top:var(--sec)}}
|
||||||
|
.w4-boutique{--kc-r:999px 999px 0 0;--kc-ar:4/3;--kc-tf:var(--mj);--kc-tw:400;--kc-ts:17px;--kc-mc:var(--rose);--kc-sub:var(--sub);--kc-soft:var(--bg2)}
|
||||||
|
.w4-boutique .rail>.kcard{flex:0 0 62%;height:auto}
|
||||||
|
.w4-boutique .guide--card{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:28px 14px}
|
||||||
|
.w4-boutique #around .guide--card{grid-template-columns:repeat(3,minmax(0,1fr));gap:20px 10px}
|
||||||
|
.w4-boutique #around .kcard-t{font-size:15px}
|
||||||
|
@media (min-width:1024px){.w4-boutique .rail>.kcard{flex-basis:calc((100% - 48px) / 3)}.w4-boutique .guide--card{grid-template-columns:repeat(3,minmax(0,1fr));gap:36px 24px}}
|
||||||
|
@media (max-width:1023px){
|
||||||
|
.w4-boutique{--aw:min(250px,calc(100vw - 88px));--ah:calc(var(--aw) * 1.12)}
|
||||||
|
.w4-boutique[data-page=home] .b-hd:not(.solid){color:var(--brown)}
|
||||||
|
.w4-boutique .b-hero{height:auto;min-height:0;padding:calc(84px + var(--ah) + 24px) var(--g) 8px;background:transparent;overflow:visible}
|
||||||
|
.w4-boutique .b-hero:before{content:"";position:absolute;top:100px;left:50%;width:var(--aw);height:var(--ah);margin-left:calc(var(--aw) / -2 + 14px);border-radius:999px 999px 0 0;background:var(--bg2)}
|
||||||
|
.w4-boutique .b-hero:after{display:none}
|
||||||
|
.w4-boutique .b-slide{inset:84px auto auto 50%;width:var(--aw);height:var(--ah);margin-left:calc(var(--aw) / -2);border-radius:999px 999px 0 0;overflow:hidden;z-index:1}
|
||||||
|
.w4-boutique .b-hero-copy{position:relative;left:auto;right:auto;bottom:auto;padding:0;color:var(--brown)}
|
||||||
|
.w4-boutique .b-hero-ko{color:var(--ink)}
|
||||||
|
.w4-boutique .b-hero-count{top:calc(84px + var(--ah) - 34px);bottom:auto}
|
||||||
|
.w4-boutique .b-hero--plain{padding-top:120px}
|
||||||
|
.w4-boutique .b-hero--plain:before{display:none}
|
||||||
|
}
|
||||||
@@ -2,6 +2,7 @@ import {useState} from 'react';
|
|||||||
import type {LocalPlace} from '@o2o/shared';
|
import type {LocalPlace} from '@o2o/shared';
|
||||||
import {useSite} from '@site/lib/site-context';
|
import {useSite} from '@site/lib/site-context';
|
||||||
import {naverMapSearchUrl} from '@site/lib/format';
|
import {naverMapSearchUrl} from '@site/lib/format';
|
||||||
|
import {PhotoCard} from '../kit/Card';
|
||||||
import {Sheet} from '../paper/Sheet';
|
import {Sheet} from '../paper/Sheet';
|
||||||
import {useWide} from './useWide';
|
import {useWide} from './useWide';
|
||||||
|
|
||||||
@@ -71,6 +72,17 @@ export function Around() {
|
|||||||
</button>
|
</button>
|
||||||
);
|
);
|
||||||
|
|
||||||
|
const spot = (item: LocalPlace) => (
|
||||||
|
<PhotoCard
|
||||||
|
key={item.name}
|
||||||
|
image={item.imageUrl}
|
||||||
|
title={item.name}
|
||||||
|
meta={item.distanceText}
|
||||||
|
desc={item.description}
|
||||||
|
onClick={() => setOpen(item)}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
{rail.length > 0 && (
|
{rail.length > 0 && (
|
||||||
@@ -81,11 +93,13 @@ export function Around() {
|
|||||||
<p className="lead">걸어서 닿는 명소와 맛집입니다.</p>
|
<p className="lead">걸어서 닿는 명소와 맛집입니다.</p>
|
||||||
<div className="grid3">
|
<div className="grid3">
|
||||||
{rail.slice(0, HOME_ROWS).map((item) => (
|
{rail.slice(0, HOME_ROWS).map((item) => (
|
||||||
<button key={item.name} type="button" className="card" onClick={() => setOpen(item)}>
|
<PhotoCard
|
||||||
<img src={item.imageUrl} alt={item.name} loading="lazy" />
|
key={item.name}
|
||||||
<b className="nm clamp">{item.name}</b>
|
image={item.imageUrl}
|
||||||
{item.distanceText && <span className="ds">{item.distanceText}</span>}
|
title={item.name}
|
||||||
</button>
|
meta={item.distanceText}
|
||||||
|
onClick={() => setOpen(item)}
|
||||||
|
/>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
<a className="link more" href="#/area">
|
<a className="link more" href="#/area">
|
||||||
@@ -104,11 +118,11 @@ export function Around() {
|
|||||||
</h2>
|
</h2>
|
||||||
<p className="lead">걸어서 닿는 곳부터 차로 가는 곳까지 묶었습니다.</p>
|
<p className="lead">걸어서 닿는 곳부터 차로 가는 곳까지 묶었습니다.</p>
|
||||||
<RangeTabs places={spots} value={spotRange} onChange={setSpotRange} />
|
<RangeTabs places={spots} value={spotRange} onChange={setSpotRange} />
|
||||||
<div className="guide">{shownSpots.slice(0, firstSpots).map((item) => place(item))}</div>
|
<div className="guide guide--card">{shownSpots.slice(0, firstSpots).map(spot)}</div>
|
||||||
{shownSpots.length > firstSpots && (
|
{shownSpots.length > firstSpots && (
|
||||||
<details className="fold">
|
<details className="fold">
|
||||||
<summary className="link">{shownSpots.length - firstSpots}곳 더 보기</summary>
|
<summary className="link">{shownSpots.length - firstSpots}곳 더 보기</summary>
|
||||||
<div className="guide">{shownSpots.slice(firstSpots).map((item) => place(item))}</div>
|
<div className="guide guide--card">{shownSpots.slice(firstSpots).map(spot)}</div>
|
||||||
</details>
|
</details>
|
||||||
)}
|
)}
|
||||||
</section>
|
</section>
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import {useState} from 'react';
|
|||||||
import type {FestivalEntry} from '@o2o/shared';
|
import type {FestivalEntry} from '@o2o/shared';
|
||||||
import {useSite} from '@site/lib/site-context';
|
import {useSite} from '@site/lib/site-context';
|
||||||
import {naverSearchUrl} from '@site/lib/format';
|
import {naverSearchUrl} from '@site/lib/format';
|
||||||
|
import {PhotoCard} from '../kit/Card';
|
||||||
import {Sheet} from '../paper/Sheet';
|
import {Sheet} from '../paper/Sheet';
|
||||||
|
|
||||||
const SEASONS = ['봄', '여름', '가을', '겨울'];
|
const SEASONS = ['봄', '여름', '가을', '겨울'];
|
||||||
@@ -40,15 +41,13 @@ export function Festival() {
|
|||||||
)}
|
)}
|
||||||
<div className="rail">
|
<div className="rail">
|
||||||
{shown.map((f) => (
|
{shown.map((f) => (
|
||||||
<button key={f.name} type="button" className="card" onClick={() => setOpen(f)}>
|
<PhotoCard
|
||||||
{f.imageUrl ? (
|
key={f.name}
|
||||||
<img src={f.imageUrl} alt={f.name} loading="lazy" />
|
image={f.imageUrl}
|
||||||
) : (
|
title={f.name}
|
||||||
<span className="noimg">{f.name}</span>
|
meta={[f.month, f.location].filter(Boolean).join(' · ')}
|
||||||
)}
|
onClick={() => setOpen(f)}
|
||||||
<b className="nm">{f.name}</b>
|
/>
|
||||||
<span className="ds">{[f.month, f.location].filter(Boolean).join(' · ')}</span>
|
|
||||||
</button>
|
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import {PlaceCategory} from '@o2o/shared';
|
import {PlaceCategory} from '@o2o/shared';
|
||||||
import {HeroCatchphrase} from '@site/sections/HeroCatchphrase';
|
import {HeroCatchphrase, HeroRotator} from '@site/sections/HeroCatchphrase';
|
||||||
import {useSite} from '@site/lib/site-context';
|
import {useSite} from '@site/lib/site-context';
|
||||||
import {galleryImages, isSectionEnabled} from '@site/lib/derive';
|
import {galleryImages, isSectionEnabled} from '@site/lib/derive';
|
||||||
import {useLiveWeather} from '@site/lib/use-live-weather';
|
import {useLiveWeather} from '@site/lib/use-live-weather';
|
||||||
@@ -56,7 +56,8 @@ export function Hero() {
|
|||||||
<HeroCatchphrase />
|
<HeroCatchphrase />
|
||||||
</p>
|
</p>
|
||||||
<h1 className="nm">{place.name}</h1>
|
<h1 className="nm">{place.name}</h1>
|
||||||
{sub && <p className="sub">{sub}</p>}
|
{where && <p className="sub">{where}</p>}
|
||||||
|
<HeroRotator className="sub" />
|
||||||
</>
|
</>
|
||||||
) : (
|
) : (
|
||||||
<>
|
<>
|
||||||
|
|||||||
@@ -296,3 +296,9 @@
|
|||||||
.w4-cinema .unit .btns{grid-template-columns:1fr 1fr}}
|
.w4-cinema .unit .btns{grid-template-columns:1fr 1fr}}
|
||||||
.w4-cinema .wrap>.label:has(+h2),.w4-cinema .book .label,.w4-cinema .rhead>.kicker{display:none}
|
.w4-cinema .wrap>.label:has(+h2),.w4-cinema .book .label,.w4-cinema .rhead>.kicker{display:none}
|
||||||
.w4-cinema :is(h1,h2,.big,.hl){font-family:var(--tpl-font-heading)}
|
.w4-cinema :is(h1,h2,.big,.hl){font-family:var(--tpl-font-heading)}
|
||||||
|
.w4-cinema{--kc-r:14px;--kc-tw:600;--kc-mc:var(--accent);--kc-sub:var(--sub);--kc-soft:rgba(244,239,230,.06)}
|
||||||
|
.w4-cinema .rail>.kcard{flex:0 0 72%;height:auto}
|
||||||
|
.w4-cinema .guide--card{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:24px 14px;border-top:0}
|
||||||
|
.w4-cinema .grid3:has(>.kcard){gap:20px 10px}
|
||||||
|
.w4-cinema .grid3>.kcard .kcard-t{font-size:15px}
|
||||||
|
@media (min-width:1024px){.w4-cinema .rail>.kcard{flex:0 0 calc((100% - 30px) / 4)}.w4-cinema .guide--card,.w4-cinema #walk .guide{grid-template-columns:repeat(4,minmax(0,1fr));gap:32px 16px}.w4-cinema #around .grid3:has(>.kcard){grid-template-columns:repeat(3,minmax(0,1fr));gap:16px}}
|
||||||
@@ -2,6 +2,7 @@ import {useState} from 'react';
|
|||||||
import type {LocalPlace} from '@o2o/shared';
|
import type {LocalPlace} from '@o2o/shared';
|
||||||
import {useSite} from '@site/lib/site-context';
|
import {useSite} from '@site/lib/site-context';
|
||||||
import {naverMapSearchUrl} from '@site/lib/format';
|
import {naverMapSearchUrl} from '@site/lib/format';
|
||||||
|
import {PhotoCard} from '../kit/Card';
|
||||||
import {Sheet} from '../paper/Sheet';
|
import {Sheet} from '../paper/Sheet';
|
||||||
import {useWide} from './useWide';
|
import {useWide} from './useWide';
|
||||||
|
|
||||||
@@ -66,18 +67,14 @@ export function Around() {
|
|||||||
);
|
);
|
||||||
|
|
||||||
const card = (place: LocalPlace) => (
|
const card = (place: LocalPlace) => (
|
||||||
<button key={place.name} type="button" className="place" onClick={() => setOpen(place)}>
|
<PhotoCard
|
||||||
{place.imageUrl && (
|
key={place.name}
|
||||||
<div className="ph">
|
image={place.imageUrl}
|
||||||
<img src={place.imageUrl} alt={place.name} loading="lazy" />
|
title={place.name}
|
||||||
</div>
|
meta={place.distanceText}
|
||||||
)}
|
desc={place.description}
|
||||||
<div className="bd">
|
onClick={() => setOpen(place)}
|
||||||
<h3>{place.name}</h3>
|
/>
|
||||||
{place.distanceText && <small>{place.distanceText}</small>}
|
|
||||||
{place.description && <p className="clamp">{place.description}</p>}
|
|
||||||
</div>
|
|
||||||
</button>
|
|
||||||
);
|
);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@@ -94,15 +91,13 @@ export function Around() {
|
|||||||
</div>
|
</div>
|
||||||
<div className="guide guide--3">
|
<div className="guide guide--3">
|
||||||
{rail.slice(0, railMax).map((place) => (
|
{rail.slice(0, railMax).map((place) => (
|
||||||
<button key={place.name} type="button" className="place" onClick={() => setOpen(place)}>
|
<PhotoCard
|
||||||
<div className="ph">
|
key={place.name}
|
||||||
<img src={place.imageUrl} alt={place.name} loading="lazy" />
|
image={place.imageUrl}
|
||||||
</div>
|
title={place.name}
|
||||||
<div className="bd">
|
meta={place.distanceText}
|
||||||
<h3>{place.name}</h3>
|
onClick={() => setOpen(place)}
|
||||||
{place.distanceText && <small>{place.distanceText}</small>}
|
/>
|
||||||
</div>
|
|
||||||
</button>
|
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
<a href="#/area" className="more">
|
<a href="#/area" className="more">
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import {PlaceCategory} from '@o2o/shared';
|
import {PlaceCategory} from '@o2o/shared';
|
||||||
import {HeroCatchphrase} from '@site/sections/HeroCatchphrase';
|
import {HeroCatchphrase, HeroRotator} from '@site/sections/HeroCatchphrase';
|
||||||
import {useSite} from '@site/lib/site-context';
|
import {useSite} from '@site/lib/site-context';
|
||||||
import {bookingActionLabel, bookingLinks, heroFacts, isSectionEnabled, stayBookingView} from '@site/lib/derive';
|
import {bookingActionLabel, bookingLinks, isSectionEnabled, stayBookingView} from '@site/lib/derive';
|
||||||
import {Car} from '../paper/Car';
|
import {Car} from '../paper/Car';
|
||||||
import {BOOK_EVENT} from '../paper/Rooms';
|
import {BOOK_EVENT} from '../paper/Rooms';
|
||||||
import {Weather} from './Weather';
|
import {Weather} from './Weather';
|
||||||
@@ -20,7 +20,6 @@ export function Hero() {
|
|||||||
const region = place.addressLocality ?? place.addressRegion;
|
const region = place.addressLocality ?? place.addressRegion;
|
||||||
const booking = bookingLinks(payload)[0];
|
const booking = bookingLinks(payload)[0];
|
||||||
const stay = lodging ? stayBookingView(payload) : null;
|
const stay = lodging ? stayBookingView(payload) : null;
|
||||||
const chips = heroFacts(payload).map((row) => `${row.label} ${row.value}`);
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
@@ -56,16 +55,7 @@ export function Hero() {
|
|||||||
) : (
|
) : (
|
||||||
fixed && <p className="hl in">{fixed}</p>
|
fixed && <p className="hl in">{fixed}</p>
|
||||||
)}
|
)}
|
||||||
{lodging && fixed && <p className="tagline">{fixed}</p>}
|
<HeroRotator className="tagline" />
|
||||||
{chips.length > 0 && (
|
|
||||||
<div className="chips">
|
|
||||||
{chips.map((chip) => (
|
|
||||||
<span key={chip} className="chip">
|
|
||||||
{chip}
|
|
||||||
</span>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
<div className="hero-cta">
|
<div className="hero-cta">
|
||||||
{stay ? (
|
{stay ? (
|
||||||
<button type="button" className="btn" onClick={() => window.dispatchEvent(new Event(BOOK_EVENT))}>
|
<button type="button" className="btn" onClick={() => window.dispatchEvent(new Event(BOOK_EVENT))}>
|
||||||
|
|||||||
@@ -12,20 +12,9 @@ const MOOD_ICON = {
|
|||||||
눈: SnowIcon,
|
눈: SnowIcon,
|
||||||
} as const;
|
} as const;
|
||||||
|
|
||||||
const OBSERVED = new Intl.DateTimeFormat('ko-KR', {
|
|
||||||
timeZone: 'Asia/Seoul',
|
|
||||||
month: 'long',
|
|
||||||
day: 'numeric',
|
|
||||||
hour: '2-digit',
|
|
||||||
minute: '2-digit',
|
|
||||||
hourCycle: 'h23',
|
|
||||||
});
|
|
||||||
|
|
||||||
function observed(iso: string): string | undefined {
|
function observed(iso: string): string | undefined {
|
||||||
const date = new Date(iso);
|
const m = /^\d{4}-(\d{2})-(\d{2})T(\d{2}):(\d{2})/.exec(iso);
|
||||||
if (Number.isNaN(date.getTime())) return undefined;
|
return m ? `${Number(m[1])}월 ${Number(m[2])}일 ${m[3]}:${m[4]} 관측` : undefined;
|
||||||
const parts = Object.fromEntries(OBSERVED.formatToParts(date).map((p) => [p.type, p.value]));
|
|
||||||
return `${parts.month} ${parts.day}일 ${parts.hour}:${parts.minute} 관측`;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export function Weather() {
|
export function Weather() {
|
||||||
|
|||||||
@@ -447,3 +447,5 @@
|
|||||||
.w4-coral #about .amen li.off .ic{color:#c2410c}
|
.w4-coral #about .amen li.off .ic{color:#c2410c}
|
||||||
.w4-coral #about .amen li.off{color:var(--sub)}
|
.w4-coral #about .amen li.off{color:var(--sub)}
|
||||||
.w4-coral :is(h1,h2,h3){font-family:var(--tpl-font-heading)}
|
.w4-coral :is(h1,h2,h3){font-family:var(--tpl-font-heading)}
|
||||||
|
.w4-coral{--kc-r:0;--kc-tw:500;--kc-mc:var(--accent);--kc-sub:var(--sub);--kc-soft:var(--alt)}
|
||||||
|
.w4-coral .cards2,.w4-coral .guide--3{row-gap:24px}
|
||||||
@@ -2,6 +2,7 @@ import {useState} from 'react';
|
|||||||
import type {LocalPlace} from '@o2o/shared';
|
import type {LocalPlace} from '@o2o/shared';
|
||||||
import {useSite} from '@site/lib/site-context';
|
import {useSite} from '@site/lib/site-context';
|
||||||
import {naverMapSearchUrl} from '@site/lib/format';
|
import {naverMapSearchUrl} from '@site/lib/format';
|
||||||
|
import {PhotoCard} from '../kit/Card';
|
||||||
import {Sheet} from '../paper/Sheet';
|
import {Sheet} from '../paper/Sheet';
|
||||||
import {SpotIcon} from './Art';
|
import {SpotIcon} from './Art';
|
||||||
import {useWide} from './useWide';
|
import {useWide} from './useWide';
|
||||||
@@ -70,6 +71,18 @@ export function Around() {
|
|||||||
</button>
|
</button>
|
||||||
);
|
);
|
||||||
|
|
||||||
|
const spot = (place: LocalPlace) => (
|
||||||
|
<PhotoCard
|
||||||
|
key={place.name}
|
||||||
|
image={place.imageUrl}
|
||||||
|
title={place.name}
|
||||||
|
meta={place.distanceText}
|
||||||
|
desc={place.description}
|
||||||
|
fallback={<SpotIcon food={false} />}
|
||||||
|
onClick={() => setOpen(place)}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<div data-pg="home">
|
<div data-pg="home">
|
||||||
@@ -103,11 +116,11 @@ export function Around() {
|
|||||||
const shown = spots.filter((p) => inRange(spotRange)(meters(p)));
|
const shown = spots.filter((p) => inRange(spotRange)(meters(p)));
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<div className="guide guide--card">{shown.slice(0, firstSpots).map((p, i) => row(p, i))}</div>
|
<div className="guide guide--card">{shown.slice(0, firstSpots).map(spot)}</div>
|
||||||
{shown.length > firstSpots && (
|
{shown.length > firstSpots && (
|
||||||
<details>
|
<details>
|
||||||
<summary className="more">{shown.length - firstSpots}곳 더 보기</summary>
|
<summary className="more">{shown.length - firstSpots}곳 더 보기</summary>
|
||||||
<div className="guide guide--card">{shown.slice(firstSpots).map((p, i) => row(p, i + firstSpots))}</div>
|
<div className="guide guide--card">{shown.slice(firstSpots).map(spot)}</div>
|
||||||
</details>
|
</details>
|
||||||
)}
|
)}
|
||||||
</>
|
</>
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import {useState} from 'react';
|
|||||||
import type {FestivalEntry} from '@o2o/shared';
|
import type {FestivalEntry} from '@o2o/shared';
|
||||||
import {useSite} from '@site/lib/site-context';
|
import {useSite} from '@site/lib/site-context';
|
||||||
import {naverSearchUrl} from '@site/lib/format';
|
import {naverSearchUrl} from '@site/lib/format';
|
||||||
|
import {PhotoCard} from '../kit/Card';
|
||||||
import {Sheet} from '../paper/Sheet';
|
import {Sheet} from '../paper/Sheet';
|
||||||
|
|
||||||
const SEASONS = ['봄', '여름', '가을', '겨울'];
|
const SEASONS = ['봄', '여름', '가을', '겨울'];
|
||||||
@@ -40,15 +41,13 @@ export function Festival() {
|
|||||||
)}
|
)}
|
||||||
<div className="rail">
|
<div className="rail">
|
||||||
{shown.map((f) => (
|
{shown.map((f) => (
|
||||||
<button key={f.name} type="button" className="card" onClick={() => setOpen(f)}>
|
<PhotoCard
|
||||||
{f.imageUrl ? (
|
key={f.name}
|
||||||
<img src={f.imageUrl} alt={f.name} loading="lazy" />
|
image={f.imageUrl}
|
||||||
) : (
|
title={f.name}
|
||||||
<span className="noimg">{f.name}</span>
|
meta={[f.month, f.location].filter(Boolean).join(' · ')}
|
||||||
)}
|
onClick={() => setOpen(f)}
|
||||||
<b className="nm">{f.name}</b>
|
/>
|
||||||
<span className="ds">{[f.month, f.location].filter(Boolean).join(' · ')}</span>
|
|
||||||
</button>
|
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
|
|||||||
@@ -1,15 +1,14 @@
|
|||||||
import {useEffect, useState, type CSSProperties} from 'react';
|
import {useEffect, useState, type CSSProperties} from 'react';
|
||||||
import {PlaceCategory, type WeatherSky} from '@o2o/shared';
|
import {PlaceCategory, type WeatherSky} from '@o2o/shared';
|
||||||
import {useSite} from '@site/lib/site-context';
|
import {useSite} from '@site/lib/site-context';
|
||||||
|
import {HeroRotator, useMainCatchphrase} from '@site/sections/HeroCatchphrase';
|
||||||
import {useLiveWeather} from '@site/lib/use-live-weather';
|
import {useLiveWeather} from '@site/lib/use-live-weather';
|
||||||
import {useWeatherNotes} from '@site/lib/use-weather-note';
|
import {useWeatherNotes} from '@site/lib/use-weather-note';
|
||||||
import {bookingActionLabel, bookingLinks, isSectionEnabled, stayBookingView, weatherBand, weatherMood} from '@site/lib/derive';
|
import {bookingActionLabel, bookingLinks, isSectionEnabled, stayBookingView, weatherBand, weatherMood} from '@site/lib/derive';
|
||||||
import {BOOK_EVENT} from '../paper/Rooms';
|
import {BOOK_EVENT} from '../paper/Rooms';
|
||||||
import lines from '@site/lib/lodging-catchphrases.json';
|
|
||||||
import {Hills, Sky} from './Art';
|
import {Hills, Sky} from './Art';
|
||||||
|
|
||||||
const STEP_MS = 35;
|
const STEP_MS = 35;
|
||||||
const ROTATE_MS = 4500;
|
|
||||||
|
|
||||||
export function Pop({text}: {text: string}) {
|
export function Pop({text}: {text: string}) {
|
||||||
const words = text.split(/\s+/).map((word) => [...word]);
|
const words = text.split(/\s+/).map((word) => [...word]);
|
||||||
@@ -32,26 +31,6 @@ export function Pop({text}: {text: string}) {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function useCatchphrase(): string | undefined {
|
|
||||||
const {place, narrative} = useSite();
|
|
||||||
const lodging = place.category === PlaceCategory.LODGING;
|
|
||||||
const own = (narrative.catchphrases?.items ?? [])
|
|
||||||
.filter((item) => (item.kind ?? 'general') === 'general')
|
|
||||||
.map((item) => item.text.trim())
|
|
||||||
.filter(Boolean);
|
|
||||||
const phrases = own.length > 0 ? own : lodging ? lines : [];
|
|
||||||
const [index, setIndex] = useState(0);
|
|
||||||
useEffect(() => {
|
|
||||||
if (phrases.length < 2) return;
|
|
||||||
const motion = window.matchMedia('(prefers-reduced-motion: reduce)');
|
|
||||||
const timer = window.setInterval(() => {
|
|
||||||
if (!document.hidden && !motion.matches) setIndex((value) => (value + 1) % phrases.length);
|
|
||||||
}, ROTATE_MS);
|
|
||||||
return () => window.clearInterval(timer);
|
|
||||||
}, [phrases.length]);
|
|
||||||
return phrases.length > 0 ? phrases[index % phrases.length] : undefined;
|
|
||||||
}
|
|
||||||
|
|
||||||
function WeatherCard() {
|
function WeatherCard() {
|
||||||
const payload = useSite();
|
const payload = useSite();
|
||||||
const weather = useLiveWeather({
|
const weather = useLiveWeather({
|
||||||
@@ -101,9 +80,8 @@ function WeatherCard() {
|
|||||||
export function Hero() {
|
export function Hero() {
|
||||||
const payload = useSite();
|
const payload = useSite();
|
||||||
const {place, narrative} = payload;
|
const {place, narrative} = payload;
|
||||||
const phrase = useCatchphrase();
|
const phrase = useMainCatchphrase();
|
||||||
const region = [place.addressRegion, place.addressLocality].filter(Boolean).join(' ');
|
const region = [place.addressRegion, place.addressLocality].filter(Boolean).join(' ');
|
||||||
const fixed = narrative.tagline ?? narrative.heroSubline;
|
|
||||||
const stay = place.category === PlaceCategory.LODGING ? stayBookingView(payload) : null;
|
const stay = place.category === PlaceCategory.LODGING ? stayBookingView(payload) : null;
|
||||||
const link = bookingLinks(payload)[0];
|
const link = bookingLinks(payload)[0];
|
||||||
|
|
||||||
@@ -111,7 +89,6 @@ export function Hero() {
|
|||||||
<section className="scene" id="top" data-pg="home" aria-labelledby="hero-heading">
|
<section className="scene" id="top" data-pg="home" aria-labelledby="hero-heading">
|
||||||
<Sky />
|
<Sky />
|
||||||
<div className="hero-copy">
|
<div className="hero-copy">
|
||||||
{region && <span className="tag">{region}</span>}
|
|
||||||
<h1 id="hero-heading" className="disp">
|
<h1 id="hero-heading" className="disp">
|
||||||
<Pop text={place.name} />
|
<Pop text={place.name} />
|
||||||
</h1>
|
</h1>
|
||||||
@@ -120,7 +97,7 @@ export function Hero() {
|
|||||||
<Pop text={phrase} />
|
<Pop text={phrase} />
|
||||||
</p>
|
</p>
|
||||||
)}
|
)}
|
||||||
{fixed && <p className="sub">{fixed}</p>}
|
<HeroRotator className="sub" />
|
||||||
{(stay || link || place.phone) && (
|
{(stay || link || place.phone) && (
|
||||||
<div className="hgo">
|
<div className="hgo">
|
||||||
{stay ? (
|
{stay ? (
|
||||||
|
|||||||
@@ -334,3 +334,7 @@
|
|||||||
@media(max-width:1023px){.w4-graphic #location .btns{display:grid;grid-template-columns:1fr 1fr;gap:8px}
|
@media(max-width:1023px){.w4-graphic #location .btns{display:grid;grid-template-columns:1fr 1fr;gap:8px}
|
||||||
.w4-graphic #location .btns>:first-child{grid-column:1/-1}
|
.w4-graphic #location .btns>:first-child{grid-column:1/-1}
|
||||||
.w4-graphic #location .btns>*{white-space:nowrap;min-width:0}}
|
.w4-graphic #location .btns>*{white-space:nowrap;min-width:0}}
|
||||||
|
.w4-graphic{--kc-r:0;--kc-box-r:22px;--kc-bg:var(--card);--kc-shadow:0 2px 0 rgba(29,43,36,.08);--kc-px:12px;--kc-pb:14px;--kc-tf:var(--k-head);--kc-tw:400;--kc-ts:17px;--kc-mc:var(--accent);--kc-sub:var(--sub);--kc-soft:#fff1c9}
|
||||||
|
.w4-graphic .rail>.kcard{flex:0 0 72%;height:auto}
|
||||||
|
.w4-graphic .guide--card{grid-template-columns:repeat(2,minmax(0,1fr));gap:24px 14px}
|
||||||
|
@media (min-width:1024px){.w4-graphic .rail>.kcard{flex:0 0 calc((100% - 48px) / 4)}.w4-graphic .guide--card{grid-template-columns:repeat(4,minmax(0,1fr));gap:32px 16px}}
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
import type {ReactNode} from 'react';
|
||||||
|
import './card.css';
|
||||||
|
|
||||||
|
export function PhotoCard({
|
||||||
|
image,
|
||||||
|
title,
|
||||||
|
meta,
|
||||||
|
desc,
|
||||||
|
fallback,
|
||||||
|
ratio,
|
||||||
|
onClick,
|
||||||
|
}: {
|
||||||
|
image?: string | null;
|
||||||
|
title: string;
|
||||||
|
meta?: string | null;
|
||||||
|
desc?: string | null;
|
||||||
|
fallback?: ReactNode;
|
||||||
|
ratio?: string;
|
||||||
|
onClick: () => void;
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<button type="button" className="kcard" onClick={onClick}>
|
||||||
|
<span className="kcard-ph" style={ratio ? {aspectRatio: ratio} : undefined}>
|
||||||
|
{image ? <img src={image} alt={title} loading="lazy" /> : <span className="kcard-no">{fallback ?? title}</span>}
|
||||||
|
</span>
|
||||||
|
<span className="kcard-t">{title}</span>
|
||||||
|
{meta && <span className="kcard-m">{meta}</span>}
|
||||||
|
{desc && <span className="kcard-d">{desc}</span>}
|
||||||
|
</button>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
:is(.w4p,.w4-round,.w4-cinema,.w4-bigtype,.w4-boutique,.w4-graphic,.w4-coral,.w4-minimal,.w4-pine) .kcard{display:flex;flex-direction:column;width:100%;height:100%;min-width:0;margin:0;padding:0 0 var(--kc-pb,0);border:0;border-radius:var(--kc-box-r,0);overflow:hidden;background:var(--kc-bg,none);box-shadow:var(--kc-shadow,none);color:inherit;font:inherit;text-align:left;cursor:pointer;-webkit-appearance:none;appearance:none}
|
||||||
|
:is(.w4p,.w4-round,.w4-cinema,.w4-bigtype,.w4-boutique,.w4-graphic,.w4-coral,.w4-minimal,.w4-pine) .kcard-ph{position:relative;display:block;width:100%;aspect-ratio:var(--kc-ar,3/2);border-radius:var(--kc-r,14px);overflow:hidden;background:var(--kc-soft,rgba(127,127,127,.1))}
|
||||||
|
:is(.w4p,.w4-round,.w4-cinema,.w4-bigtype,.w4-boutique,.w4-graphic,.w4-coral,.w4-minimal,.w4-pine) .kcard-ph img{display:block;width:100%;height:100%;object-fit:cover;transition:transform .5s ease}
|
||||||
|
:is(.w4p,.w4-round,.w4-cinema,.w4-bigtype,.w4-boutique,.w4-graphic,.w4-coral,.w4-minimal,.w4-pine) .kcard:hover .kcard-ph img{transform:scale(1.03)}
|
||||||
|
:is(.w4p,.w4-round,.w4-cinema,.w4-bigtype,.w4-boutique,.w4-graphic,.w4-coral,.w4-minimal,.w4-pine) .kcard-no{display:grid;place-items:center;width:100%;height:100%;padding:0 16px;font-family:var(--kc-tf,inherit);font-size:17px;line-height:1.4;text-align:center;color:var(--kc-sub,inherit)}
|
||||||
|
:is(.w4p,.w4-round,.w4-cinema,.w4-bigtype,.w4-boutique,.w4-graphic,.w4-coral,.w4-minimal,.w4-pine) .kcard-no svg{width:40px;height:40px}
|
||||||
|
:is(.w4p,.w4-round,.w4-cinema,.w4-bigtype,.w4-boutique,.w4-graphic,.w4-coral,.w4-minimal,.w4-pine) .kcard-t{display:-webkit-box;-webkit-line-clamp:1;-webkit-box-orient:vertical;overflow:hidden;margin-top:12px;padding:0 var(--kc-px,2px);font-family:var(--kc-tf,inherit);font-size:var(--kc-ts,16px);font-weight:var(--kc-tw,600);line-height:1.45;letter-spacing:-.01em}
|
||||||
|
:is(.w4p,.w4-round,.w4-cinema,.w4-bigtype,.w4-boutique,.w4-graphic,.w4-coral,.w4-minimal,.w4-pine) .kcard-m{display:-webkit-box;-webkit-line-clamp:1;-webkit-box-orient:vertical;overflow:hidden;margin-top:4px;padding:0 var(--kc-px,2px);font-size:14px;font-weight:500;line-height:1.5;color:var(--kc-mc,inherit)}
|
||||||
|
:is(.w4p,.w4-round,.w4-cinema,.w4-bigtype,.w4-boutique,.w4-graphic,.w4-coral,.w4-minimal,.w4-pine) .kcard-d{display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden;margin-top:6px;padding:0 var(--kc-px,2px);font-size:15px;line-height:1.6;color:var(--kc-sub,inherit)}
|
||||||
|
:is(.w4p,.w4-round,.w4-cinema,.w4-bigtype,.w4-boutique,.w4-graphic,.w4-coral,.w4-minimal,.w4-pine) .kgrid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:24px 14px}
|
||||||
|
@media (min-width:1024px){:is(.w4p,.w4-round,.w4-cinema,.w4-bigtype,.w4-boutique,.w4-graphic,.w4-coral,.w4-minimal,.w4-pine) .kgrid{grid-template-columns:repeat(auto-fill,minmax(220px,1fr));gap:32px 20px}}
|
||||||
|
:is(.w4p,.w4-round,.w4-cinema,.w4-bigtype,.w4-boutique,.w4-graphic,.w4-coral,.w4-minimal,.w4-pine) .car--multi:has(.kcard) .arrow{top:calc(50% - 30px)}
|
||||||
|
@media (max-width:1023px){:is(.w4p,.w4-round,.w4-cinema,.w4-bigtype,.w4-boutique,.w4-graphic,.w4-coral,.w4-minimal,.w4-pine) .car--multi:has(.kcard) .arrow{display:none}}
|
||||||
@@ -1,8 +1,8 @@
|
|||||||
:is(.w4-round,.w4-cinema,.w4-bigtype,.w4-boutique,.w4-graphic,.w4-coral,.w4-minimal,.w4-pine){--k-pad:20px;--k-wide:640px;--k-r:12px;--k-soft:rgba(127,127,127,.08);--k-line:rgba(127,127,127,.22);--k-head:inherit}
|
:is(.w4-round,.w4-cinema,.w4-bigtype,.w4-boutique,.w4-graphic,.w4-coral,.w4-minimal,.w4-pine){--k-pad:20px;--k-wide:640px;--k-r:12px;--k-soft:rgba(127,127,127,.08);--k-line:rgba(127,127,127,.22);--k-head:inherit}
|
||||||
:is(.w4-round,.w4-cinema,.w4-bigtype,.w4-boutique,.w4-graphic,.w4-coral,.w4-minimal,.w4-pine) *{box-sizing:border-box}
|
:is(.w4-round,.w4-cinema,.w4-bigtype,.w4-boutique,.w4-graphic,.w4-coral,.w4-minimal,.w4-pine) *{box-sizing:border-box}
|
||||||
:is(.w4-round,.w4-cinema,.w4-bigtype,.w4-boutique,.w4-graphic,.w4-coral,.w4-minimal,.w4-pine) .sbox{border-radius:20px 20px 0 0}
|
:is(.w4-round,.w4-cinema,.w4-bigtype,.w4-boutique,.w4-graphic,.w4-coral,.w4-minimal,.w4-pine) .sbox{border-radius:var(--k-r)}
|
||||||
:is(.w4-round,.w4-cinema,.w4-bigtype,.w4-boutique,.w4-graphic,.w4-coral,.w4-minimal,.w4-pine) .sform{padding:22px var(--k-pad) 8px}
|
:is(.w4-round,.w4-cinema,.w4-bigtype,.w4-boutique,.w4-graphic,.w4-coral,.w4-minimal,.w4-pine) :is(.sform,.sheetbody){padding:22px var(--k-pad) 8px}
|
||||||
:is(.w4-round,.w4-cinema,.w4-bigtype,.w4-boutique,.w4-graphic,.w4-coral,.w4-minimal,.w4-pine) .sform h3{margin:0 0 16px;font-family:var(--k-head);font-size:21px;font-weight:600}
|
:is(.w4-round,.w4-cinema,.w4-bigtype,.w4-boutique,.w4-graphic,.w4-coral,.w4-minimal,.w4-pine) :is(.sform,.sheetbody) h3{margin:0 0 16px;font-family:var(--k-head);font-size:21px;font-weight:600}
|
||||||
:is(.w4-round,.w4-cinema,.w4-bigtype,.w4-boutique,.w4-graphic,.w4-coral,.w4-minimal,.w4-pine) .sheet .cta,:is(.w4-round,.w4-cinema,.w4-bigtype,.w4-boutique,.w4-graphic,.w4-coral,.w4-minimal,.w4-pine) .sform button.cta{display:flex;align-items:center;justify-content:center;width:100%;height:52px;border:0;border-radius:var(--k-r);background:var(--k-ink);color:var(--k-bg);font:inherit;font-size:16px;font-weight:700;cursor:pointer}
|
:is(.w4-round,.w4-cinema,.w4-bigtype,.w4-boutique,.w4-graphic,.w4-coral,.w4-minimal,.w4-pine) .sheet .cta,:is(.w4-round,.w4-cinema,.w4-bigtype,.w4-boutique,.w4-graphic,.w4-coral,.w4-minimal,.w4-pine) .sform button.cta{display:flex;align-items:center;justify-content:center;width:100%;height:52px;border:0;border-radius:var(--k-r);background:var(--k-ink);color:var(--k-bg);font:inherit;font-size:16px;font-weight:700;cursor:pointer}
|
||||||
:is(.w4-round,.w4-cinema,.w4-bigtype,.w4-boutique,.w4-graphic,.w4-coral,.w4-minimal,.w4-pine) .sform input,:is(.w4-round,.w4-cinema,.w4-bigtype,.w4-boutique,.w4-graphic,.w4-coral,.w4-minimal,.w4-pine) .sform textarea{width:100%;padding:12px 14px;border:1px solid var(--k-line);border-radius:var(--k-r);background:transparent;color:var(--k-ink);font:inherit;font-size:16px}
|
:is(.w4-round,.w4-cinema,.w4-bigtype,.w4-boutique,.w4-graphic,.w4-coral,.w4-minimal,.w4-pine) .sform input,:is(.w4-round,.w4-cinema,.w4-bigtype,.w4-boutique,.w4-graphic,.w4-coral,.w4-minimal,.w4-pine) .sform textarea{width:100%;padding:12px 14px;border:1px solid var(--k-line);border-radius:var(--k-r);background:transparent;color:var(--k-ink);font:inherit;font-size:16px}
|
||||||
:is(.w4-round,.w4-cinema,.w4-bigtype,.w4-boutique,.w4-graphic,.w4-coral,.w4-minimal,.w4-pine) .car{position:relative}
|
:is(.w4-round,.w4-cinema,.w4-bigtype,.w4-boutique,.w4-graphic,.w4-coral,.w4-minimal,.w4-pine) .car{position:relative}
|
||||||
@@ -48,10 +48,10 @@
|
|||||||
:is(.w4-round,.w4-cinema,.w4-bigtype,.w4-boutique,.w4-graphic,.w4-coral,.w4-minimal,.w4-pine) .car .dots button.on{width:18px;border-radius:999px;background:var(--k-ink)}
|
:is(.w4-round,.w4-cinema,.w4-bigtype,.w4-boutique,.w4-graphic,.w4-coral,.w4-minimal,.w4-pine) .car .dots button.on{width:18px;border-radius:999px;background:var(--k-ink)}
|
||||||
:is(.w4-round,.w4-cinema,.w4-bigtype,.w4-boutique,.w4-graphic,.w4-coral,.w4-minimal,.w4-pine) details>summary{list-style:none;cursor:pointer}
|
:is(.w4-round,.w4-cinema,.w4-bigtype,.w4-boutique,.w4-graphic,.w4-coral,.w4-minimal,.w4-pine) details>summary{list-style:none;cursor:pointer}
|
||||||
:is(.w4-round,.w4-cinema,.w4-bigtype,.w4-boutique,.w4-graphic,.w4-coral,.w4-minimal,.w4-pine) details>summary::-webkit-details-marker{display:none}
|
:is(.w4-round,.w4-cinema,.w4-bigtype,.w4-boutique,.w4-graphic,.w4-coral,.w4-minimal,.w4-pine) details>summary::-webkit-details-marker{display:none}
|
||||||
:is(.w4-round,.w4-cinema,.w4-bigtype,.w4-boutique,.w4-graphic,.w4-coral,.w4-minimal,.w4-pine) .sheet{position:fixed;inset:0;z-index:40}
|
:is(.w4-round,.w4-cinema,.w4-bigtype,.w4-boutique,.w4-graphic,.w4-coral,.w4-minimal,.w4-pine) .sheet{position:fixed;inset:0;z-index:40;display:flex;align-items:center;justify-content:center;padding:24px 16px}
|
||||||
:is(.w4-round,.w4-cinema,.w4-bigtype,.w4-boutique,.w4-graphic,.w4-coral,.w4-minimal,.w4-pine) .sheet[hidden]{display:none}
|
:is(.w4-round,.w4-cinema,.w4-bigtype,.w4-boutique,.w4-graphic,.w4-coral,.w4-minimal,.w4-pine) .sheet[hidden]{display:none}
|
||||||
:is(.w4-round,.w4-cinema,.w4-bigtype,.w4-boutique,.w4-graphic,.w4-coral,.w4-minimal,.w4-pine) .sbg{position:absolute;inset:0;background:rgba(14,13,10,.52)}
|
:is(.w4-round,.w4-cinema,.w4-bigtype,.w4-boutique,.w4-graphic,.w4-coral,.w4-minimal,.w4-pine) .sbg{position:absolute;inset:0;background:rgba(14,13,10,.52)}
|
||||||
:is(.w4-round,.w4-cinema,.w4-bigtype,.w4-boutique,.w4-graphic,.w4-coral,.w4-minimal,.w4-pine) .sbox{position:absolute;left:0;right:0;bottom:0;max-width:var(--k-wide);margin:0 auto; max-height:88svh;overflow:auto;background:var(--k-bg);padding:0 0 32px; -webkit-overflow-scrolling:touch}
|
:is(.w4-round,.w4-cinema,.w4-bigtype,.w4-boutique,.w4-graphic,.w4-coral,.w4-minimal,.w4-pine) .sbox{position:relative;width:100%;max-width:560px;margin:0 auto; max-height:calc(100svh - 48px);overflow:auto;background:var(--k-bg);padding:0 0 32px; -webkit-overflow-scrolling:touch}
|
||||||
:is(.w4-round,.w4-cinema,.w4-bigtype,.w4-boutique,.w4-graphic,.w4-coral,.w4-minimal,.w4-pine) .sx{position:sticky;top:0;float:right;width:48px;height:48px;border:0;background:none; font-size:22px;line-height:1;color:var(--k-ink);cursor:pointer;z-index:1}
|
:is(.w4-round,.w4-cinema,.w4-bigtype,.w4-boutique,.w4-graphic,.w4-coral,.w4-minimal,.w4-pine) .sx{position:sticky;top:0;float:right;width:48px;height:48px;border:0;background:none; font-size:22px;line-height:1;color:var(--k-ink);cursor:pointer;z-index:1}
|
||||||
:is(.w4-round,.w4-cinema,.w4-bigtype,.w4-boutique,.w4-graphic,.w4-coral,.w4-minimal,.w4-pine) .sin{padding-top:16px}
|
:is(.w4-round,.w4-cinema,.w4-bigtype,.w4-boutique,.w4-graphic,.w4-coral,.w4-minimal,.w4-pine) .sin{padding-top:16px}
|
||||||
:is(.w4-round,.w4-cinema,.w4-bigtype,.w4-boutique,.w4-graphic,.w4-coral,.w4-minimal,.w4-pine) .sin img{margin:0 0 18px}
|
:is(.w4-round,.w4-cinema,.w4-bigtype,.w4-boutique,.w4-graphic,.w4-coral,.w4-minimal,.w4-pine) .sin img{margin:0 0 18px}
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import {useState} from 'react';
|
|||||||
import type {LocalPlace} from '@o2o/shared';
|
import type {LocalPlace} from '@o2o/shared';
|
||||||
import {useSite} from '@site/lib/site-context';
|
import {useSite} from '@site/lib/site-context';
|
||||||
import {naverMapSearchUrl} from '@site/lib/format';
|
import {naverMapSearchUrl} from '@site/lib/format';
|
||||||
|
import {PhotoCard} from '../kit/Card';
|
||||||
import {Sheet} from '../paper/Sheet';
|
import {Sheet} from '../paper/Sheet';
|
||||||
import {useWide} from './useWide';
|
import {useWide} from './useWide';
|
||||||
|
|
||||||
@@ -66,18 +67,14 @@ export function Around() {
|
|||||||
);
|
);
|
||||||
|
|
||||||
const card = (place: LocalPlace) => (
|
const card = (place: LocalPlace) => (
|
||||||
<button key={place.name} type="button" className="place" onClick={() => setOpen(place)}>
|
<PhotoCard
|
||||||
{place.imageUrl && (
|
key={place.name}
|
||||||
<div className="ph">
|
image={place.imageUrl}
|
||||||
<img src={place.imageUrl} alt={place.name} loading="lazy" />
|
title={place.name}
|
||||||
</div>
|
meta={place.distanceText}
|
||||||
)}
|
desc={place.description}
|
||||||
<div className="bd">
|
onClick={() => setOpen(place)}
|
||||||
<h3>{place.name}</h3>
|
/>
|
||||||
{place.distanceText && <small>{place.distanceText}</small>}
|
|
||||||
{place.description && <p className="clamp">{place.description}</p>}
|
|
||||||
</div>
|
|
||||||
</button>
|
|
||||||
);
|
);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@@ -94,15 +91,13 @@ export function Around() {
|
|||||||
</div>
|
</div>
|
||||||
<div className="guide guide--3">
|
<div className="guide guide--3">
|
||||||
{rail.slice(0, railMax).map((place) => (
|
{rail.slice(0, railMax).map((place) => (
|
||||||
<button key={place.name} type="button" className="place" onClick={() => setOpen(place)}>
|
<PhotoCard
|
||||||
<div className="ph">
|
key={place.name}
|
||||||
<img src={place.imageUrl} alt={place.name} loading="lazy" />
|
image={place.imageUrl}
|
||||||
</div>
|
title={place.name}
|
||||||
<div className="bd">
|
meta={place.distanceText}
|
||||||
<h3>{place.name}</h3>
|
onClick={() => setOpen(place)}
|
||||||
{place.distanceText && <small>{place.distanceText}</small>}
|
/>
|
||||||
</div>
|
|
||||||
</button>
|
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
<a href="#/area" className="more">
|
<a href="#/area" className="more">
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import {PlaceCategory} from '@o2o/shared';
|
import {PlaceCategory} from '@o2o/shared';
|
||||||
import {HeroCatchphrase} from '@site/sections/HeroCatchphrase';
|
import {HeroCatchphrase, HeroRotator} from '@site/sections/HeroCatchphrase';
|
||||||
import {useSite} from '@site/lib/site-context';
|
import {useSite} from '@site/lib/site-context';
|
||||||
import {bookingActionLabel, bookingLinks, heroFacts, isSectionEnabled, stayBookingView} from '@site/lib/derive';
|
import {bookingActionLabel, bookingLinks, isSectionEnabled, stayBookingView} from '@site/lib/derive';
|
||||||
import {Car} from '../paper/Car';
|
import {Car} from '../paper/Car';
|
||||||
import {BOOK_EVENT} from '../paper/Rooms';
|
import {BOOK_EVENT} from '../paper/Rooms';
|
||||||
import {Weather} from './Weather';
|
import {Weather} from './Weather';
|
||||||
@@ -20,7 +20,6 @@ export function Hero() {
|
|||||||
const region = place.addressLocality ?? place.addressRegion;
|
const region = place.addressLocality ?? place.addressRegion;
|
||||||
const booking = bookingLinks(payload)[0];
|
const booking = bookingLinks(payload)[0];
|
||||||
const stay = lodging ? stayBookingView(payload) : null;
|
const stay = lodging ? stayBookingView(payload) : null;
|
||||||
const chips = heroFacts(payload).map((row) => `${row.label} ${row.value}`);
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
@@ -56,16 +55,7 @@ export function Hero() {
|
|||||||
) : (
|
) : (
|
||||||
fixed && <p className="hl in">{fixed}</p>
|
fixed && <p className="hl in">{fixed}</p>
|
||||||
)}
|
)}
|
||||||
{lodging && fixed && <p className="tagline">{fixed}</p>}
|
<HeroRotator className="tagline" />
|
||||||
{chips.length > 0 && (
|
|
||||||
<div className="chips">
|
|
||||||
{chips.map((chip) => (
|
|
||||||
<span key={chip} className="chip">
|
|
||||||
{chip}
|
|
||||||
</span>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
<div className="hero-cta">
|
<div className="hero-cta">
|
||||||
{stay ? (
|
{stay ? (
|
||||||
<button type="button" className="btn" onClick={() => window.dispatchEvent(new Event(BOOK_EVENT))}>
|
<button type="button" className="btn" onClick={() => window.dispatchEvent(new Event(BOOK_EVENT))}>
|
||||||
|
|||||||
@@ -12,20 +12,9 @@ const MOOD_ICON = {
|
|||||||
눈: SnowIcon,
|
눈: SnowIcon,
|
||||||
} as const;
|
} as const;
|
||||||
|
|
||||||
const OBSERVED = new Intl.DateTimeFormat('ko-KR', {
|
|
||||||
timeZone: 'Asia/Seoul',
|
|
||||||
month: 'long',
|
|
||||||
day: 'numeric',
|
|
||||||
hour: '2-digit',
|
|
||||||
minute: '2-digit',
|
|
||||||
hourCycle: 'h23',
|
|
||||||
});
|
|
||||||
|
|
||||||
function observed(iso: string): string | undefined {
|
function observed(iso: string): string | undefined {
|
||||||
const date = new Date(iso);
|
const m = /^\d{4}-(\d{2})-(\d{2})T(\d{2}):(\d{2})/.exec(iso);
|
||||||
if (Number.isNaN(date.getTime())) return undefined;
|
return m ? `${Number(m[1])}월 ${Number(m[2])}일 ${m[3]}:${m[4]} 관측` : undefined;
|
||||||
const parts = Object.fromEntries(OBSERVED.formatToParts(date).map((p) => [p.type, p.value]));
|
|
||||||
return `${parts.month} ${parts.day}일 ${parts.hour}:${parts.minute} 관측`;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export function Weather() {
|
export function Weather() {
|
||||||
|
|||||||
@@ -450,3 +450,5 @@
|
|||||||
.w4-minimal #about .amen li.off .ic{color:#c2410c}
|
.w4-minimal #about .amen li.off .ic{color:#c2410c}
|
||||||
.w4-minimal #about .amen li.off{color:var(--sub)}
|
.w4-minimal #about .amen li.off{color:var(--sub)}
|
||||||
.w4-minimal :is(h1,h2,.hl){font-family:var(--tpl-font-heading)}
|
.w4-minimal :is(h1,h2,.hl){font-family:var(--tpl-font-heading)}
|
||||||
|
.w4-minimal{--kc-r:0;--kc-tw:400;--kc-mc:var(--sub);--kc-sub:var(--sub);--kc-soft:var(--alt)}
|
||||||
|
.w4-minimal .cards2,.w4-minimal .guide--3{row-gap:28px}
|
||||||
@@ -2,6 +2,7 @@ import {useState} from 'react';
|
|||||||
import type {LocalPlace} from '@o2o/shared';
|
import type {LocalPlace} from '@o2o/shared';
|
||||||
import {useSite} from '@site/lib/site-context';
|
import {useSite} from '@site/lib/site-context';
|
||||||
import {naverMapSearchUrl} from '@site/lib/format';
|
import {naverMapSearchUrl} from '@site/lib/format';
|
||||||
|
import {PhotoCard} from '../kit/Card';
|
||||||
import {Car} from './Car';
|
import {Car} from './Car';
|
||||||
import {Sheet} from './Sheet';
|
import {Sheet} from './Sheet';
|
||||||
|
|
||||||
@@ -80,11 +81,7 @@ export function Around() {
|
|||||||
arrows
|
arrows
|
||||||
label="주변 안내"
|
label="주변 안내"
|
||||||
slides={rail.map((place) => (
|
slides={rail.map((place) => (
|
||||||
<button type="button" className="itemcard" onClick={() => setOpen(place)}>
|
<PhotoCard image={place.imageUrl} title={place.name} meta={place.distanceText} onClick={() => setOpen(place)} />
|
||||||
<img src={place.imageUrl} alt={place.name} loading="lazy" style={{aspectRatio: '3 / 2'}} />
|
|
||||||
<p className="cap">{place.name}</p>
|
|
||||||
{place.distanceText && <p className="cap dim">{place.distanceText}</p>}
|
|
||||||
</button>
|
|
||||||
))}
|
))}
|
||||||
/>
|
/>
|
||||||
</section>
|
</section>
|
||||||
@@ -104,17 +101,16 @@ export function Around() {
|
|||||||
걸어서 닿는 곳부터 차로 가는 곳까지 묶었습니다.
|
걸어서 닿는 곳부터 차로 가는 곳까지 묶었습니다.
|
||||||
</p>
|
</p>
|
||||||
<RangeTabs places={spots} value={spotRange} onChange={setSpotRange} />
|
<RangeTabs places={spots} value={spotRange} onChange={setSpotRange} />
|
||||||
<div className="grid2" style={{gap: 14}}>
|
<div className="grid2" style={{gap: '24px 14px'}}>
|
||||||
{shownSpots.map((place) => (
|
{shownSpots.map((place) => (
|
||||||
<button key={place.name} type="button" className="itemcard" onClick={() => setOpen(place)}>
|
<PhotoCard
|
||||||
{place.imageUrl && (
|
key={place.name}
|
||||||
<img src={place.imageUrl} alt={place.name} loading="lazy" style={{aspectRatio: '3 / 2'}} />
|
image={place.imageUrl}
|
||||||
)}
|
title={place.name}
|
||||||
<p className="cap">
|
meta={place.distanceText}
|
||||||
<b>{place.name}</b> {place.distanceText && <span className="dim">{place.distanceText}</span>}
|
desc={place.description}
|
||||||
</p>
|
onClick={() => setOpen(place)}
|
||||||
{place.description && <p className="cap dim clamp">{place.description}</p>}
|
/>
|
||||||
</button>
|
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import {useState} from 'react';
|
|||||||
import type {FestivalEntry} from '@o2o/shared';
|
import type {FestivalEntry} from '@o2o/shared';
|
||||||
import {useSite} from '@site/lib/site-context';
|
import {useSite} from '@site/lib/site-context';
|
||||||
import {naverSearchUrl} from '@site/lib/format';
|
import {naverSearchUrl} from '@site/lib/format';
|
||||||
|
import {PhotoCard} from '../kit/Card';
|
||||||
import {Car} from './Car';
|
import {Car} from './Car';
|
||||||
import {Sheet} from './Sheet';
|
import {Sheet} from './Sheet';
|
||||||
|
|
||||||
@@ -48,19 +49,12 @@ export function Festival() {
|
|||||||
arrows
|
arrows
|
||||||
label="계절별 축제"
|
label="계절별 축제"
|
||||||
slides={shown.map((f) => (
|
slides={shown.map((f) => (
|
||||||
<button type="button" className="itemcard" onClick={() => setOpen(f)}>
|
<PhotoCard
|
||||||
{f.imageUrl ? (
|
image={f.imageUrl}
|
||||||
<img src={f.imageUrl} alt={f.name} loading="lazy" style={{aspectRatio: '3 / 2'}} />
|
title={f.name}
|
||||||
) : (
|
meta={[f.month, f.location].filter(Boolean).join(' · ')}
|
||||||
<span className="noimg" style={{aspectRatio: '3 / 2'}}>
|
onClick={() => setOpen(f)}
|
||||||
{f.name}
|
/>
|
||||||
</span>
|
|
||||||
)}
|
|
||||||
<p className="cap">
|
|
||||||
<b>{f.name}</b>
|
|
||||||
</p>
|
|
||||||
<p className="cap dim">{[f.month, f.location].filter(Boolean).join(' · ')}</p>
|
|
||||||
</button>
|
|
||||||
))}
|
))}
|
||||||
/>
|
/>
|
||||||
</section>
|
</section>
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import {HeroCatchphrase} from '@site/sections/HeroCatchphrase';
|
import {HeroCatchphrase, HeroRotator} from '@site/sections/HeroCatchphrase';
|
||||||
import {useSite} from '@site/lib/site-context';
|
import {useSite} from '@site/lib/site-context';
|
||||||
import {isSectionEnabled} from '@site/lib/derive';
|
import {isSectionEnabled} from '@site/lib/derive';
|
||||||
import {Weather} from './Weather';
|
import {Weather} from './Weather';
|
||||||
@@ -13,7 +13,6 @@ export function Hero() {
|
|||||||
.filter((image) => image.alt?.trim())
|
.filter((image) => image.alt?.trim())
|
||||||
.sort((a, b) => Number(b.isPrimary) - Number(a.isPrimary))
|
.sort((a, b) => Number(b.isPrimary) - Number(a.isPrimary))
|
||||||
.slice(0, MAX_SLIDES);
|
.slice(0, MAX_SLIDES);
|
||||||
const fixed = narrative.tagline ?? narrative.heroSubline;
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
@@ -41,10 +40,10 @@ export function Hero() {
|
|||||||
<p className="eyebrow">{place.addressLocality ?? place.addressRegion}</p>
|
<p className="eyebrow">{place.addressLocality ?? place.addressRegion}</p>
|
||||||
)}
|
)}
|
||||||
<h1 className="mj">{place.name}</h1>
|
<h1 className="mj">{place.name}</h1>
|
||||||
{fixed && <p className="tagline">{fixed}</p>}
|
|
||||||
<p className="cp">
|
<p className="cp">
|
||||||
<HeroCatchphrase />
|
<HeroCatchphrase />
|
||||||
</p>
|
</p>
|
||||||
|
<HeroRotator className="tagline" />
|
||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
{isSectionEnabled(payload, 'weather') && (
|
{isSectionEnabled(payload, 'weather') && (
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import {useState, type ReactNode} from 'react';
|
|||||||
import type {ChronicleItem, PeopleItem, ReadingItem, SongItem} from '@o2o/shared';
|
import type {ChronicleItem, PeopleItem, ReadingItem, SongItem} from '@o2o/shared';
|
||||||
import {useSite} from '@site/lib/site-context';
|
import {useSite} from '@site/lib/site-context';
|
||||||
import {sectionItems, sectionName} from '@site/lib/derive';
|
import {sectionItems, sectionName} from '@site/lib/derive';
|
||||||
|
import {PhotoCard} from '../kit/Card';
|
||||||
import {Sheet} from './Sheet';
|
import {Sheet} from './Sheet';
|
||||||
|
|
||||||
const COUNT_WORD: Record<number, string> = {1: '한', 2: '두', 3: '세', 4: '네'};
|
const COUNT_WORD: Record<number, string> = {1: '한', 2: '두', 3: '세', 4: '네'};
|
||||||
@@ -60,27 +61,35 @@ export function Story() {
|
|||||||
{item.year && <span className="r">{item.year}</span>}
|
{item.year && <span className="r">{item.year}</span>}
|
||||||
</button>
|
</button>
|
||||||
);
|
);
|
||||||
const person = (item: PeopleItem) => (
|
const person = (item: PeopleItem) => {
|
||||||
<button
|
const show = () =>
|
||||||
key={item.name}
|
|
||||||
type="button"
|
|
||||||
className="itemcard"
|
|
||||||
onClick={() =>
|
|
||||||
setOpen({
|
setOpen({
|
||||||
title: item.name,
|
title: item.name,
|
||||||
meta: [item.role, item.years].filter(Boolean).join(' · '),
|
meta: [item.role, item.years].filter(Boolean).join(' · '),
|
||||||
body: item.oneLine,
|
body: item.oneLine,
|
||||||
image: item.imageUrl,
|
image: item.imageUrl,
|
||||||
})
|
});
|
||||||
}
|
if (item.imageUrl)
|
||||||
>
|
return (
|
||||||
{item.imageUrl && <img src={item.imageUrl} alt={item.name} loading="lazy" style={{aspectRatio: '1 / 1'}} />}
|
<PhotoCard
|
||||||
|
key={item.name}
|
||||||
|
image={item.imageUrl}
|
||||||
|
title={item.name}
|
||||||
|
meta={item.role}
|
||||||
|
desc={item.oneLine}
|
||||||
|
ratio="1 / 1"
|
||||||
|
onClick={show}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
return (
|
||||||
|
<button key={item.name} type="button" className="itemcard" onClick={show}>
|
||||||
<p className="cap">
|
<p className="cap">
|
||||||
<b>{item.name}</b> {item.role && <span className="dim">{item.role}</span>}
|
<b>{item.name}</b> {item.role && <span className="dim">{item.role}</span>}
|
||||||
</p>
|
</p>
|
||||||
{item.oneLine && <p className="cap dim clamp">{item.oneLine}</p>}
|
{item.oneLine && <p className="cap dim clamp">{item.oneLine}</p>}
|
||||||
</button>
|
</button>
|
||||||
);
|
);
|
||||||
|
};
|
||||||
const event = (item: ChronicleItem) => (
|
const event = (item: ChronicleItem) => (
|
||||||
<button
|
<button
|
||||||
key={`${item.year}-${item.title}`}
|
key={`${item.year}-${item.title}`}
|
||||||
|
|||||||
@@ -255,10 +255,10 @@
|
|||||||
@supports(padding:max(0px)){
|
@supports(padding:max(0px)){
|
||||||
.w4p .bar{height:calc(var(--bar) + env(safe-area-inset-bottom)); padding-bottom:calc(9px + env(safe-area-inset-bottom))}
|
.w4p .bar{height:calc(var(--bar) + env(safe-area-inset-bottom)); padding-bottom:calc(9px + env(safe-area-inset-bottom))}
|
||||||
}
|
}
|
||||||
.w4p .sheet{position:fixed;inset:0;z-index:40}
|
.w4p .sheet{position:fixed;inset:0;z-index:40;display:flex;align-items:center;justify-content:center;padding:24px 16px}
|
||||||
.w4p .sheet[hidden]{display:none}
|
.w4p .sheet[hidden]{display:none}
|
||||||
.w4p .sbg{position:absolute;inset:0;background:rgba(14,13,10,.52)}
|
.w4p .sbg{position:absolute;inset:0;background:rgba(14,13,10,.52)}
|
||||||
.w4p .sbox{position:absolute;left:0;right:0;bottom:0;max-width:var(--wide);margin:0 auto; max-height:88svh;overflow:auto;background:var(--paper);padding:0 0 32px; -webkit-overflow-scrolling:touch}
|
.w4p .sbox{position:relative;width:100%;max-width:560px;margin:0 auto; max-height:calc(100svh - 48px);border-radius:8px;overflow:auto;background:var(--paper);padding:0 0 32px; -webkit-overflow-scrolling:touch}
|
||||||
.w4p .sx{position:sticky;top:0;float:right;width:48px;height:48px;border:0;background:none; font-size:22px;line-height:1;color:var(--ink);cursor:pointer;z-index:1}
|
.w4p .sx{position:sticky;top:0;float:right;width:48px;height:48px;border:0;background:none; font-size:22px;line-height:1;color:var(--ink);cursor:pointer;z-index:1}
|
||||||
.w4p .sin{padding-top:16px}
|
.w4p .sin{padding-top:16px}
|
||||||
.w4p .sin img{margin:0 0 18px}
|
.w4p .sin img{margin:0 0 18px}
|
||||||
@@ -338,3 +338,4 @@
|
|||||||
.w4p #w4d-panel .w4d-eq i{background:#8c4a2f}
|
.w4p #w4d-panel .w4d-eq i{background:#8c4a2f}
|
||||||
.w4p #w4d-lyrics-box{padding:14px 16px 18px;border-top:1px solid var(--line);font-family:'Noto Serif KR','AppleMyungjo',serif;font-size:15px;line-height:1.95;color:#39352e}
|
.w4p #w4d-lyrics-box{padding:14px 16px 18px;border-top:1px solid var(--line);font-family:'Noto Serif KR','AppleMyungjo',serif;font-size:15px;line-height:1.95;color:#39352e}
|
||||||
.w4p #w4d-panel .w4d-info{line-height:1.45}
|
.w4p #w4d-panel .w4d-info{line-height:1.45}
|
||||||
|
.w4p{--kc-r:4px;--kc-tw:500;--kc-ts:16.5px;--kc-mc:var(--sub);--kc-sub:var(--sub);--kc-soft:var(--tint)}
|
||||||
@@ -2,6 +2,7 @@ import {useState} from 'react';
|
|||||||
import type {LocalPlace} from '@o2o/shared';
|
import type {LocalPlace} from '@o2o/shared';
|
||||||
import {useSite} from '@site/lib/site-context';
|
import {useSite} from '@site/lib/site-context';
|
||||||
import {naverMapSearchUrl} from '@site/lib/format';
|
import {naverMapSearchUrl} from '@site/lib/format';
|
||||||
|
import {PhotoCard} from '../kit/Card';
|
||||||
import {Sheet} from '../paper/Sheet';
|
import {Sheet} from '../paper/Sheet';
|
||||||
import {useWide} from './useWide';
|
import {useWide} from './useWide';
|
||||||
|
|
||||||
@@ -66,18 +67,14 @@ export function Around() {
|
|||||||
);
|
);
|
||||||
|
|
||||||
const card = (place: LocalPlace) => (
|
const card = (place: LocalPlace) => (
|
||||||
<button key={place.name} type="button" className="place" onClick={() => setOpen(place)}>
|
<PhotoCard
|
||||||
{place.imageUrl && (
|
key={place.name}
|
||||||
<div className="ph">
|
image={place.imageUrl}
|
||||||
<img src={place.imageUrl} alt={place.name} loading="lazy" />
|
title={place.name}
|
||||||
</div>
|
meta={place.distanceText}
|
||||||
)}
|
desc={place.description}
|
||||||
<div className="bd">
|
onClick={() => setOpen(place)}
|
||||||
<h3>{place.name}</h3>
|
/>
|
||||||
{place.distanceText && <small>{place.distanceText}</small>}
|
|
||||||
{place.description && <p className="clamp">{place.description}</p>}
|
|
||||||
</div>
|
|
||||||
</button>
|
|
||||||
);
|
);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import {PlaceCategory} from '@o2o/shared';
|
import {PlaceCategory} from '@o2o/shared';
|
||||||
import {HeroCatchphrase} from '@site/sections/HeroCatchphrase';
|
import {HeroCatchphrase, HeroRotator} from '@site/sections/HeroCatchphrase';
|
||||||
import {useSite} from '@site/lib/site-context';
|
import {useSite} from '@site/lib/site-context';
|
||||||
import {bookingActionLabel, bookingLinks, heroFacts, isSectionEnabled, stayBookingView} from '@site/lib/derive';
|
import {bookingActionLabel, bookingLinks, isSectionEnabled, stayBookingView} from '@site/lib/derive';
|
||||||
import {Car} from '../paper/Car';
|
import {Car} from '../paper/Car';
|
||||||
import {BOOK_EVENT} from '../paper/Rooms';
|
import {BOOK_EVENT} from '../paper/Rooms';
|
||||||
import {Weather} from './Weather';
|
import {Weather} from './Weather';
|
||||||
@@ -18,13 +18,8 @@ export function Hero() {
|
|||||||
const fixed = narrative.tagline ?? narrative.heroSubline;
|
const fixed = narrative.tagline ?? narrative.heroSubline;
|
||||||
const lodging = place.category === PlaceCategory.LODGING;
|
const lodging = place.category === PlaceCategory.LODGING;
|
||||||
const region = place.addressLocality ?? place.addressRegion;
|
const region = place.addressLocality ?? place.addressRegion;
|
||||||
const nearest = [...payload.local.attractions]
|
|
||||||
.filter((spot) => spot.distanceText)
|
|
||||||
.sort((a, b) => (a.distanceMeters ?? Infinity) - (b.distanceMeters ?? Infinity))[0];
|
|
||||||
const sub = fixed ?? (nearest ? `${nearest.name}까지 ${nearest.distanceText}` : undefined);
|
|
||||||
const booking = bookingLinks(payload)[0];
|
const booking = bookingLinks(payload)[0];
|
||||||
const stay = lodging ? stayBookingView(payload) : null;
|
const stay = lodging ? stayBookingView(payload) : null;
|
||||||
const chips = heroFacts(payload).map((row) => `${row.label} ${row.value}`);
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
@@ -60,16 +55,7 @@ export function Hero() {
|
|||||||
) : (
|
) : (
|
||||||
fixed && <p className="hl in">{fixed}</p>
|
fixed && <p className="hl in">{fixed}</p>
|
||||||
)}
|
)}
|
||||||
{lodging && sub && <p className="tagline">{sub}</p>}
|
<HeroRotator className="tagline" />
|
||||||
{chips.length > 0 && (
|
|
||||||
<div className="chips">
|
|
||||||
{chips.map((chip) => (
|
|
||||||
<span key={chip} className="chip">
|
|
||||||
{chip}
|
|
||||||
</span>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
<div className="hero-cta">
|
<div className="hero-cta">
|
||||||
{stay ? (
|
{stay ? (
|
||||||
<button type="button" className="btn" onClick={() => window.dispatchEvent(new Event(BOOK_EVENT))}>
|
<button type="button" className="btn" onClick={() => window.dispatchEvent(new Event(BOOK_EVENT))}>
|
||||||
|
|||||||
@@ -12,20 +12,9 @@ const MOOD_ICON = {
|
|||||||
눈: SnowIcon,
|
눈: SnowIcon,
|
||||||
} as const;
|
} as const;
|
||||||
|
|
||||||
const OBSERVED = new Intl.DateTimeFormat('ko-KR', {
|
|
||||||
timeZone: 'Asia/Seoul',
|
|
||||||
month: 'long',
|
|
||||||
day: 'numeric',
|
|
||||||
hour: '2-digit',
|
|
||||||
minute: '2-digit',
|
|
||||||
hourCycle: 'h23',
|
|
||||||
});
|
|
||||||
|
|
||||||
function observed(iso: string): string | undefined {
|
function observed(iso: string): string | undefined {
|
||||||
const date = new Date(iso);
|
const m = /^\d{4}-(\d{2})-(\d{2})T(\d{2}):(\d{2})/.exec(iso);
|
||||||
if (Number.isNaN(date.getTime())) return undefined;
|
return m ? `${Number(m[1])}월 ${Number(m[2])}일 ${m[3]}:${m[4]} 관측` : undefined;
|
||||||
const parts = Object.fromEntries(OBSERVED.formatToParts(date).map((p) => [p.type, p.value]));
|
|
||||||
return `${parts.month} ${parts.day}일 ${parts.hour}:${parts.minute} 관측`;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export function Weather() {
|
export function Weather() {
|
||||||
|
|||||||
Loaded 100 of 113 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user