Compare commits

..
12 Commits
Author SHA1 Message Date
skkim 3b43446fe6 Merge branch 'main' into feat-tourApi 2026-09-08 13:09:31 +09:00
minaChoiandClaude Opus 5 f2dad65792 [fix] site,deploy: 발행본 목록의 정본 주소를 /s 로 — 끝 슬래시 제거
`/s` 는 nginx `location ^~ /s/` 에 안 걸려 맨 아래 `location /` 로 떨어진다.
그래서 404 가 아니라 **빌더 SPA 셸이 200 으로** 나가고 있었다 — 실측 2026-09-08:
`/s` 3.1KB `<title>Web4Ai</title>` · `/s/` 6.7KB 목록. 404 도 목록도 아닌 세 번째
페이지가 오리진에 있었던 셈이다. 목록만 슬래시가 붙어 있던 이유도 이것 하나였다.

색인 요청·사이트맵이 canonical 과 어긋나면 구글이 제출분을 "대체 페이지(적절한
표준 태그가 있음)" 로 분류한다 — 슬러그 쪽에서 이미 밟은 함정인데(prerender.ts
주석) 목록만 반대 형태로 남아 있었다.

- nginx/site.conf.example: `location = /s` 로 목록 index.html 직접 서빙, `/s/` 는 301.
  `^~ /s/` 의 `index index.html` 은 남긴다 — `/s/<slug>/` 가 그걸로 열린다
- 같은 파일: `absolute_redirect off`. TLS 를 앞단 Apache 가 끊어 nginx 의 `$scheme` 는
  늘 `http` 다 — 기본값대로 절대 URL 을 내면 https 페이지가 http 로 내려간다
- prerender.ts: `indexUrl` 의 `+ '/'` 제거. canonical·og:url·사이트맵·llms.txt 가
  이 값 하나를 쓴다
- directory.ts · AGENTS.md · DEVLOG.md: 슬래시 규칙과 근거 갱신

검증: `nginx -t` 통과 · `tsc --noEmit` 통과 · 컨테이너 실측
`/s`→200 목록 · `/s/`→301 `Location: /s`(상대) · `/s/<slug>`→200 · `/s/<slug>/`→200 ·
`/nope`→200 앱 셸(변화 없음)

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0129XqVdjDk9JmMNFAepBJvs
2026-09-08 13:02:11 +09:00
minaChoiandClaude Opus 5 9f16c3224b [feat] solution/backend,frontend: 내 사이트 목록을 카드로 — 썸네일·주소·시각 · 발행마다 그림 갱신
목록 줄이 아이콘·상호·배지·주소 넷뿐이었다. 서버는 이미 road_address·created_at·
published_at 을 주는데 화면이 안 썼다. 실측(계정 test): 35줄 중 34줄이 발행 전이고
같은 상호 '버터브루' 가 4줄이라 어느 게 어느 건지 가릴 단서가 화면에 없었다.

리서치 — Wix My Sites 는 이름·URL·Premium·협업자만 두고 검색·그리드/리스트 전환·폴더가 있다.
Sites API 문서가 권하는 조합은 displayName·thumbnail·viewUrl·editUrl 이다.
아임웹 내사이트는 **실제 화면을 열어 봤다**(imweb.me 가이드): 줄 왼쪽에 큰 가로형 썸네일,
상호 아래 도메인, 그리고 도메인/SSL·PG 신청처럼 **안 끝난 설정**을 줄 안에 배지로 늘어놓는다.
공통 원칙은 목록이 ① 구분 ② 상태 ③ 여는 길 셋만 한다는 것 — 통계는 사이트 안 대시보드다.

- protocol·site_service: `MySiteData.thumbnail_url` 추가. 목록이 사이트 행을 이미 조인해
  읽고 있어서 쿼리는 그대로다
- site_thumbnail: 공개 주소에 `?v=<발행 버전>`. 블롭 이름은 고정이고 내용만 덮어쓰므로
  주소가 안 변하면 사진을 바꿔 재발행해도 **캐시에 남은 지난 그림**이 계속 보인다
  (CACHE_CONTROL 60초로는 그 60초를 못 막는다). 이름에 버전을 넣지 않은 이유는
  사이트당 블롭이 발행 횟수만큼 쌓이는데 지우는 코드가 없어서다
- site_thumbnail: 썸네일 전용 저장소 스위치(`THUMBNAIL_BLOB_*`). 예전엔 키 하나가
  사이트 전체 업로드(azure_static)까지 같이 켰다 — 둘은 필요한 저장소가 다르다
  (사이트는 정적 호스팅 `$web`, 썸네일은 이미지 버킷이면 된다)
- SitesPage: 줄 → **카드 그리드**. 썸네일은 16:10(브라우저 창 비율 — 사이트 미리보기를
  1:1 로 자르면 무슨 사이트인지 못 알아본다). 검색(상호·주소, 공백 무시) + 상태 칸
  `전체/발행됨/발행 전` 에 건수. 판정은 `bucketOf` 하나가 소유한다(배지·필터·정렬이 갈라지면
  건수가 어긋나 목록을 못 믿게 된다). 검색 0건 화면을 처음 온 사람의 빈 화면과 분리했다 —
  35개 있는데 "아직 없습니다" 라고 말하던 자리다
- 카드 골격은 **상태와 무관하게 같다**. 발행 전 카드에만 줄이 하나 더 붙어 높이와 버튼
  위치가 어긋났다(사장님 지적). 버튼 문구도 '편집' 하나로 — 하는 일이 같은데 글자만 달랐다

아직 그림이 없는 사이트가 대부분이다. 썸네일은 발행에 성공해야 생긴다.

검증: 백엔드 전체 통과. 목록 줄이 주소·생성일·썸네일을 들고 오는지, 발행 전 줄에
`thumbnail_url` 키가 아예 없는지, 재발행하면 `?v=1` → `?v=2` 로 주소가 바뀌는지 4건 추가.
프론트 tsc+eslint 통과. 실제 발행으로 블롭 업로드(232KB) → 공개 주소 200 → 목록 반영 확인.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QLWEFx4X3XRmKewUKjJWow
2026-09-08 13:01:47 +09:00
minaChoiandClaude Opus 5 94551afdaf [refactor] solution/backend,frontend,postgres-init: 회사(테넌트) 제거 — 사장님 계정이 곧 스코프
가입 한 번이 회사를 하나 만들고 사장님이 그 회사의 직원이 됐다. 가입 폼은 "상호"를 묻고
에디터 헤더에는 "이름 · 회사명" 이 붙었다 — 쓰는 사람은 사장님 한 명인데.
negodata 보일러플레이트의 멀티테넌트 스코프 키를 그대로 물려받은 것이고,
DECISIONS.md 2절이 "대행사/운영사 단위로 그대로 쓴다" 로 유지 결정을 적어 뒀던 자리다.

- gmodel: `UserInfo.company_id` 삭제 — JWT 클레임에서도 사라진다. 스코프 키는 `user_id` 다
- place_crud·site_crud: WHERE 를 `places.owner_user_id` 로. `list_company_sites` → `list_owner_sites`
- place_service: **주인은 토큰이 정한다.** `Req_CreatePlace.owner_user_id` 를 없앴다 —
  body 로 받으면 남의 계정을 적어 만들자마자 남의 목록에 넣을 수 있다.
  실측: 기존 92건은 아무도 안 보내서 전부 NULL 이었고 스코프는 회사가 대신 하고 있었다
- 워커(collect·copy·build·vision): 잡 페이로드 키 `company_id` → `owner_user_id`.
  잡이 세우는 `UserInfo.user_id` 는 이제 **사업장 주인**이다 — 예전엔 요청자·검증자·랜덤 uuid
  순으로 채웠는데, 그 랜덤 uuid 가 스코프 키가 되는 순간 "남의 사업장" 이라 fact 조회가 0건이 된다
- auth: `Res_Me.company` · `Req_Signup.company_name` · `CompanyData` 삭제
- models·init.sql: `company.companies` 테이블 · `users.company_id` 삭제,
  `places.owner_user_id` NOT NULL. 마이그레이션은 백필 → NOT NULL → DROP 순서다.
  회사에 계정이 여럿이면 **가장 먼저 만든 계정**에게 몰고, 주인을 못 찾은 행은 지운다 —
  스코프가 없으면 아무에게도 안 보이는 유령이다.
  실측(로컬): place 92 → 91(고아 1건 삭제), `demoebf050` 56 · `test` 35
- 프론트: 가입 폼의 상호 칸, 내 정보의 상호 항목, 헤더의 "이름 · 회사명" 삭제
- 테스트: `company_id`/`other_company_id` 픽스처 → `owner_id` 하나.
  격리는 `auth_headers("o2")` 를 한 번 더 부르면 그게 남이다

남긴 것 — DB 스키마 이름 `company` 는 그대로다. rename 은 모든 모델의 `__table_args__` 를
건드려야 해서 이번 변경에 섞지 않았다.

검증: 전체 568 passed(실패 1건은 HEAD 에서도 깨지는 레이트리밋 테스트) ·
프론트 tsc+eslint 통과 · 실제 API 로 가입→사업장→목록→격리→발행 한 바퀴

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QLWEFx4X3XRmKewUKjJWow
2026-09-08 13:01:14 +09:00
skkim 01824a7a91 [feat] solution,admin,postgres-init: 주변정보를 업장 좌표 기준으로 — 시군구 캐시는 "가까운 곳"을 못 준다
지역 정보(맛집·관광지·축제)는 행정구역 코드(local_contents.region_code) 단위로 캐시돼
"그 시군구에 있는 것"을 줬다. 양양군 업장 옆 5km 속초 관광지는 빠지고 같은 군 반대편
30km 맛집이 붙는 구조라, 캔버스의 지역 정보 섹션은 늘 "준비 중"이었다. 업장 좌표로
TourAPI 를 직접 물어 업장 단위(place_contents)에 담고, 캔버스는 스크린샷으로 받은
형식(도보 시간 필터 + 카드 캐러셀)으로 통일했다.
2026-09-08 11:46:03 +09:00
minaChoiandClaude Opus 5 00e13bca7f [feat] solution/site,shared: 발행본을 /s/stay 목업에 맞춘다 — 잃어버린 CSS 토큰 복원 + 섹션 마크업 이식
목업(/s/stay)이 참조하는 스타일시트가 서버에서 사라져(404) 그 화면을 기준으로 삼을 수
없었다. 브라우저 캐시에 남아 있던 규칙을 꺼내 레포에 되돌리고, 섹션 마크업을 목업 HTML
에서 그대로 옮겼다. Playwright 대조로 섹션 래퍼·제목 16/17, 안쪽 구조 14/17 일치.

- index.css: --fs-display~--fs-xs(유동 타이포 7) · --section-space · --color-line/muted ·
  .h2 .h3 .panel .paper .measure .border-line .text-muted .divide-line .slider-viewport/track
  ★ 이 토큰이 없던 동안 컴포넌트가 var(--fs-display)를 써도 브라우저가 조용히 무시했다 —
    히어로 제목이 본문 크기로 나오던 원인
- HeroSection: 가운데 → 좌하단. 사진 위에 글자를 한가운데 얹으면 피사체를 정확히 가린다
- AnswerBlock·EssentialInfo·Units·Gallery·Location·Faq·LocalGuide·Weather·About:
  목업 마크업 그대로. embla 를 scroll-snap 으로 바꿔 스크립트 없이도 레일이 밀린다
- FestivalSection(계절 탭) · StorySection(이야기 탭 래퍼) · items/TripMap(OSM 타일 지도) 신설
  ★ 지도는 iframe 이 아니라 타일을 직접 깐다 — iframe 은 핀을 하나밖에 못 찍어
    "어떤 순서로 도는가" 를 그릴 수 없다
- items: itinerary·event·video kind 추가(파서에 없어 payload 까지 실려 오고도 화면에서
  사라지던 것) · Rail 을 slider-viewport/track 으로 · SongsSection 을 턴테이블로
- color.ts: 선 색을 secondary → mix(bg, text, .2). secondary 는 '본문 다음으로 진한
  글자색' 이라 선으로 쓰면 표와 카드가 격자무늬처럼 새까맣게 그어진다
- seo/head.ts: --tpl-texture. 없으면 색만 갱지고 면은 매끈해서 인쇄물로 안 보인다
- seo/verify.ts: unitCode·numberOfRooms 를 화면 대조에서 뺀다
  ★ unitCode 는 ㎡의 ISO 코드로 priceCurrency 와 같은 성격인데 예외에 없었다. 그래서
    room_size 가 있는 사업장은 발행 게이트가 전부 막았다(실측: 가은채 객실 12개).
    stay 는 객실 2개 + room_size 없음이라 우연히 통과했다
- shared: LocalPlace.imageUrl/distanceMeters · FestivalEntry.imageUrl ·
  ItineraryStop 좌표 · TemplateLook.texture · people/chronicle/postcard imageUrl
  ★ 좌표·사진은 모델이 만드는 칸이 아니다. 공식 API 로 조회해 채운다

검증: tsc 통과 · Playwright 대조(목업 CSS 주입) 섹션 래퍼·제목 16/17, 안쪽 14/17.
남은 차이는 데이터 한계다 — people 사진은 위키에 원본이 없고(original:false),
weather.note 는 정적 페이지에 날씨 문장을 박는 문제라 보류.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KP1ykMnWZFtLFpm2mow1Sw
2026-09-08 09:53:19 +09:00
minaChoiandClaude Opus 5 6df125d840 [fix] solution/site: 발행본이 참조하는 자산은 기간과 무관하게 남긴다 — 목업이 죽었다
/s/stay · /s/stay2 · /s/stay3 의 CSS·JS·이미지가 전부 404 가 됐고 재굽기로 살아나지 않았다.

out/s/ 에 디렉토리가 8개인데 payload 는 4개뿐이다. 나머지는 손으로 넣은 목업이고, 프리렌더는
payload 를 받은 사이트만 굽는다 — 목업은 재굽기 대상이 아니라서 자산이 한 번 지워지면
영영 복구되지 않는다. 문서 어디에도 목업 얘기가 없어서(grep 0건) 그 존재를 모르고 자산
삭제 코드를 건드렸다.

보관 기간으로는 못 막는다. 기간이 지나면 같은 사고가 난다. 참조가 살아 있으면 남겨야 한다.

- referencedAssets(): 굽기 전에 out/s/**/index.html 을 훑어 /assets/… 참조를 모은다
- pruneAssets: 그 목록은 절대 지우지 않는다 — 보관 기간보다 우선한다
- AGENTS.md: 목업의 존재와 "자산 삭제 코드는 참조를 먼저 뺀다" 를 함정 맨 위에 ★★로
- docs/DEVLOG.md: 사고 기록과 복구 경로

검증: payload 없는 목업을 재현해 재굽기 → 참조 3개 유지. 대장을 60일 전으로 돌려 만료를
강제해도 유지. tsc·eslint 통과

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018xTWrJ6Mrr6HhEN6hZEER4
2026-09-07 14:06:09 +09:00
minaChoiandClaude Opus 5 f008b24574 [fix] solution/site: 자산 보관 코드를 되살린다 — 목업은 재굽기가 안 되므로 자산이 지워지면 끝이다
되돌렸던 6f4e055 를 그대로 되살린다. out/s/ 에는 payload 가 없는 사이트(목업)가 있고,
그건 재굽기 대상이 아니라서 자산이 한 번 지워지면 영영 복구되지 않는다.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018xTWrJ6Mrr6HhEN6hZEER4
2026-09-07 14:04:50 +09:00
minaChoi de5ff5186f Revert "[fix] solution/site: 사이트맵 lastmod 를 파일 mtime 에서 뗀다 — 페이지의 dateModified 를 그대로 쓴다"
This reverts commit 09b0538c9c.
2026-09-07 13:33:34 +09:00
minaChoi b797535b17 Revert "[fix] solution/site: 옛 해시 자산을 30일 남긴다 — 배포와 전체 재굽기를 뗀다"
This reverts commit 8f6ea16f65.
2026-09-07 13:33:34 +09:00
minaChoi 9a4bc0e123 Revert "[fix] solution/site: 대장에 없는 자산을 지우지 않는다 — 첫 배포에 운영 사이트가 끊겼다"
This reverts commit 292cf26fd9.
2026-09-07 13:33:34 +09:00
minaChoi 22447ae041 Revert "[docs] AGENTS,deploy: 재굽기 컨테이너는 solution-prerender 다 — solution-frontend 는 개발용"
This reverts commit 6f4e05517f.
2026-09-07 13:33:34 +09:00
137 changed files with 5054 additions and 1933 deletions

No files matched your search

+18 -2
View File
@@ -25,6 +25,15 @@
밟으면 **조용히 틀린다** — 빌드는 성공하고 화면도 뜨는데 결과가 잘못된 종류다.
- **★★ `out/s/` 에는 payload 가 없는 사이트가 있다 — 목업(`stay` · `stay2` · `stay3` · `*.old`).**
프리렌더는 **payload 를 받은 사이트만** 굽는다. 목업은 손으로 넣은 것이라 재굽기 대상이
아니고, **자산이 한 번 지워지면 영영 복구되지 않는다** — 재굽기를 몇 번 돌려도 안 살아나고
사람이 파일을 되돌려 넣어야 한다. 실측(2026-09-07): 번들 해시가 바뀌자 목업 3개의 CSS·JS·
이미지가 전부 404 가 됐고, 그 파일들은 `stay-mockup` 워크트리에서 손으로 꺼내 복구했다.
→ **`out/assets` 에서 파일을 지우는 코드는 `out/s/**` 의 HTML 이 참조하는 것을 먼저 뺀다**
(`prerender.ts` `referencedAssets`). 보관 기간으로는 못 막는다 — 기간이 지나면 같은 일이 난다.
→ 목업을 다루는 작업은 `out/s/` 를 먼저 열어 **payload 가 없는 디렉토리가 무엇인지** 본다.
- **번들 파일명은 콘텐츠 해시다.** HTML 은 `/assets/index-DvNTmLhy.css` 를 **루트 절대경로**로
가리킨다. 경로는 프리렌더가 `dist/client/.vite/manifest.json` 에서 읽어 박는다
(`prerender.ts:160`). 렌더러 CSS 를 고치면 이름이 바뀐다.
@@ -64,8 +73,15 @@
- **`AZURE_STORAGE_CONTAINER=$web`** — 셸에서 export 할 땐 반드시 작은따옴표(`'$web'`).
- **슬러그 규칙은 두 곳에 있고 같아야 한다**: `site_payload.publish_slug()` ↔
`solution/shared/src/lib/slug.ts publishUrl`. 어긋나면 발행은 성공하고 주소만 404 다.
- **디렉토리 요청 → `index.html`.** `/s/<slug>` 가 **끝 슬래시 없이** 열려야 한다.
정적 서버를 바꾸든 nginx 설정을 만지든 이 규칙부터 확인한다.
- **★ 발행본 주소는 끝 슬래시가 없다 — 목록 페이지 `/s` 도 마찬가지다.**
canonical · 사이트맵 · llms.txt · 서치콘솔 색인 요청이 전부 이 형태여야 한다. 어긋나면
구글이 제출분을 **"대체 페이지(적절한 표준 태그가 있음)"** 로 분류한다 — 색인은 되는데
제출 URL 은 0건으로 보이는, 눈으로 원인을 못 찾는 종류다.
→ nginx 는 `location = /s` 로 목록 index.html 을 **직접** 주고 `/s/` 는 거기로 301 한다.
이 블록을 지우면 `/s` 가 맨 아래 `location /` 로 떨어져 **빌더 SPA 셸이 200 으로 나간다**
— 404 도 목록도 아닌 세 번째 페이지가 크롤러에 잡힌다(실측 2026-09-08).
→ 리다이렉트는 `absolute_redirect off` 로 **상대 Location** 이어야 한다. TLS 를 앞단
Apache 가 끊어서 nginx 의 `$scheme` 는 늘 `http` 다 — 절대 URL 로 내면 https→http 다.
## 코드 규약
+31 -9
View File
@@ -9,9 +9,13 @@ import {customFetch} from '@/api/mutator/custom-fetch';
import {toast} from 'sonner';
type Status = 1 | 2 | 3;
// LocalContentType — common/enums.py 와 값을 맞춘다. WEATHER(1) 은 사업장 발행본에 실시간으로
// 붙는 별도 흐름이라 이 화면에서는 다루지 않는다(services/local_content_service.get_weather).
type ContentType = 2 | 3 | 4;
type LocalContent = {
id: string;
contentType: ContentType;
title: string;
region: string;
period: string;
@@ -24,10 +28,15 @@ type LocalContent = {
};
const STATUS_LABEL: Record<Status, string> = {1: '검수 대기', 2: '발행됨', 3: '종료됨'};
const TYPE_LABEL: Record<ContentType, string> = {2: '축제', 3: '관광지', 4: '맛집'};
const TYPE_BADGE_VARIANT: Record<ContentType, 'accent' | 'default' | 'outline'> = {
2: 'accent', 3: 'default', 4: 'outline',
};
type ApiContent = {
local_content_id: string;
region_code: string;
content_type: ContentType;
external_id?: string;
title?: string;
body: Record<string, unknown>;
@@ -43,14 +52,17 @@ function formatDate(value: unknown) {
}
function toContent(item: ApiContent): LocalContent {
// 기간은 축제만 있다(eventstartdate/eventenddate) — 관광지·맛집은 상시 정보라 비어 있는 게 정상이다.
const start = formatDate(item.body.eventstartdate);
const end = formatDate(item.body.eventenddate);
const period = [start, end].filter(Boolean).join(' ~ ') || (item.content_type === 2 ? '기간 미정' : '상시');
return {
id: item.local_content_id,
contentType: item.content_type,
title: item.title || '제목 없음',
region: String(item.body.addr1 || item.region_code),
period: [start, end].filter(Boolean).join(' ~ ') || '기간 미정',
source: `공공데이터포털 전국문화축제표준데이터 · ${item.external_id ?? '-'}`,
period,
source: `한국관광공사 TourAPI · ${item.external_id ?? '-'}`,
status: item.status,
selected: false,
displayStart: item.display_start_at,
@@ -95,15 +107,24 @@ export function LocalContentPage() {
} catch { toast.error('발행하지 못했습니다.'); }
};
const sync = async () => {
const regionCode = window.prompt('내부 지역 코드(예: gunsan)를 입력하세요.', 'gunsan')?.trim();
if (!regionCode) return;
// ★ 주변정보는 업장 단위(place_contents)다 — 지역 코드가 아니라 사업장 id 로 받는다.
// 이 화면의 목록은 아직 지역 캐시(local_contents)를 보여준다. 업장별 목록 화면은 다음 작업이다.
const placeId = window.prompt('사업장 ID(place_id)를 입력하세요. 사업장 목록 주소의 /places/ 뒤 값입니다.')?.trim();
if (!placeId) return;
setSyncing(true);
try {
const res = await customFetch<{result?: {success?: boolean}; msg?: string; collected?: number; skipped?: number}>({
url: '/v1/admin/local-content/sync-festivals', method: 'POST', data: {region_code: regionCode},
});
const res = await customFetch<{
result?: {success?: boolean}; msg?: string;
festivals?: number; attractions?: number; restaurants?: number; changed?: boolean;
}>({url: `/v1/admin/local-content/place/${placeId}/sync`, method: 'POST'});
if (res.result?.success === false) throw new Error(res.msg);
toast.success(`${res.collected ?? 0}건 수집 · ${res.skipped ?? 0}건 중복 제외`);
// ★ 여행코스(코스)는 2026-09-08부터 수집하지 않는다(반경을 넓혀도 데이터가 거의 없었다) — 표기에서 뺀다.
const summary = `축제 ${res.festivals ?? 0} · 관광지 ${res.attractions ?? 0} · 맛집 ${res.restaurants ?? 0}건`;
if (!res.changed) {
toast.info(`바뀐 내용이 없습니다 (${summary}, TourAPI 원문 그대로).`);
} else {
toast.success(`${summary} 반영 — 다음 빌드부터 발행본에 실립니다.`);
}
await load();
} catch (error) {
toast.error(error instanceof Error ? error.message : '공공데이터 수집에 실패했습니다.');
@@ -138,7 +159,7 @@ export function LocalContentPage() {
return (
<PageContainer
title="지역 콘텐츠"
description="공공데이터에서 지역 축제를 가져와 검수한 뒤 사장님에게 발행합니다."
description="한국관광공사 TourAPI 에서 지역 축제·관광지·맛집을 가져와 자동 발행합니다. 필요하면 여기서 수정하거나 발행을 종료할 수 있습니다."
actions={<Button onClick={sync} disabled={syncing}><Download className="size-4" />{syncing ? '수집 중…' : '공공데이터 수집'}</Button>}
>
<div className="mb-4 grid gap-3 sm:grid-cols-3">
@@ -174,6 +195,7 @@ export function LocalContentPage() {
<div className="min-w-0 flex-1">
<div className="mb-1 flex flex-wrap items-center gap-2">
<h2 className="text-sm font-semibold">{item.title}</h2>
<Badge variant={TYPE_BADGE_VARIANT[item.contentType]}>{TYPE_LABEL[item.contentType]}</Badge>
<Badge variant={item.status === 2 ? 'success' : 'warning'}>{STATUS_LABEL[item.status]}</Badge>
</div>
<div className="flex flex-wrap gap-x-4 gap-y-1 text-xs text-muted-foreground">
+4 -3
View File
@@ -186,10 +186,11 @@ USER role=1 → 403 DEVELOPER role=3 → 200
OWNER role=2 → 403
```
OWNER 가 막히는 게 핵심이다 — 자기 회사 최상위일 뿐 남의 회사를 볼 권한이 아니다.
OWNER 가 막히는 게 핵심이다 — 내부 운영 화면을 볼 권한이 아니다.
`auth` 라우터만 게이트 밖이다(로그인 자체를 막으면 아무도 못 들어온다). `signup`·`google` 도
같은 이유로 토큰 없이 열려 있다 — **여기서 만들어지는 계정은 언제나 `role=USER` 이고 자기
회사(새 테넌트) 하나만 본다.** 권한이 올라가는 경로는 이 문 뒤에 없다.
같은 이유로 토큰 없이 열려 있다 — **여기서 만들어지는 계정은 언제나 `role=USER` 이고
`places.owner_user_id` 가 자기 계정인 사업장만 본다.** 권한이 올라가는 경로는 이 문 뒤에 없다.
(2026-09-08 전에는 이 스코프가 회사(테넌트)였다 — DECISIONS.md 2절)
⚠️ **`/v1/admin/local-content` 는 아직 :9800 에도 마운트돼 있다**(`router/router.py`).
위 논리대로라면 이 라우터는 :9801 에만 있어야 한다. 지금은 엔드포인트별 `RequireOwner` 가
+2 -2
View File
@@ -88,9 +88,9 @@
| 포트 | **9800** | negosium 9300 / negodata 9400 / agent 9500 / lps 9600 / anchoring 9700 다음 번호 |
| DB | `web4ai_db` (테스트 `web4ai_test_db`), 기존 로컬 postgres(`negosium-db` 컨테이너, 5432) 안의 **별도 database** | 원본과 같은 인스턴스·다른 DB. 스키마 네임스페이스 컨벤션 유지 |
| 마이그레이션 | Alembic 안 씀. `postgres-init/init-data/init.sql` **한 벌**(전체 DDL, 재실행 안전) | 2026-08-31: 누적 ALTER 파일(`alters/`)을 없앴다. 아직 git·서버 어디에도 안 올라가 **보정할 기존 DB 가 없다** — init.sql 에 이미 전부 반영돼 있어 두 벌을 유지할 이유가 없었다. 운영 DB 가 생기는 순간 다시 필요해진다 |
| 남긴 것 | config 로더 · 로거 · 싱글톤 · DB 세션 매니저(R/W 분리) · gmodel · gtime · authz · JWT/bcrypt dependencies · `company.companies`/`company.users` · auth 라우터 · 스케줄러 껍데기 · conftest(테스트 DB 자동 생성/삭제) | 전 모듈이 공통으로 쓰는 인프라. 인증은 places·facts·sites 전부가 `IsValidAccessToken` 에 의존한다 |
| 남긴 것 | config 로더 · 로거 · 싱글톤 · DB 세션 매니저(R/W 분리) · gmodel · gtime · authz · JWT/bcrypt dependencies · `company.users` · auth 라우터 · 스케줄러 껍데기 · conftest(테스트 DB 자동 생성/삭제) | 전 모듈이 공통으로 쓰는 인프라. 인증은 places·facts·sites 전부가 `IsValidAccessToken` 에 의존한다 |
| 뺀 것 | quotation · supplier · item · card · dashboard · statistics · learning · renegotiation · landing · admin · notification · LPS 연동 · anchoring · 초청메일(ACS/SMTP) · Azure Blob 클라이언트 | negodata 고유 도메인. Blob 클라이언트만 1-2 결론 후 media 모듈과 함께 재이식 예정 |
| `companies` 테이블 유지 | 유지 | 보일러플레이트의 멀티테넌트 스코프 키(`UserInfo.company_id`)가 전 계층에 박혀 있다. 대행사/운영사 단위로 그대로 쓴다 |
| `companies` 테이블 유지 | **2026-09-08 철회 — 걷어냈다** | 보일러플레이트를 그대로 둔 결정이었는데, 이 제품의 사용자는 사장님 한 명이다. 가입 한 번이 회사를 만들고 사장님이 자기 회사의 직원이 되는 구조가 화면에까지 나왔다(가입 폼의 "상호", 헤더의 "이름 · 회사명"). 스코프 키를 `places.owner_user_id` 로 옮기고 `company.companies` 테이블 · `users.company_id` · `UserInfo.company_id` 를 삭제했다. 스키마 이름 `company` 만 남았다 — rename 은 모든 모델의 `__table_args__` 를 건드려서 따로 둔다 |
| ErrorType 구간 | 계정 = 1100. 도메인 구간 예약 — places 1200 / facts 1300 / collector 1400 / generator 1500 / local 1600 / sites 1700 / reports 1800 | 원본이 구간을 나눠 쓰는 방식 유지 |
| 외부 API 키 | `[ExternalApiConfig]` 로 toml + env override. **키가 비면 해당 어댑터만 비활성, 서버는 그대로 뜬다** | 부팅이 외부 계약에 묶이면 안 됨 |
| 백그라운드 작업 | 원본에 전용 작업 큐 없음(APScheduler 크론만). 수집·비전분석·빌드는 몇 분 걸리므로 **큐를 새로 얹어야 한다** — 방식 미정 | 원본에 없는 것이라 팀 컨벤션 확인 필요. 아래 3번 참고 |
+133
View File
@@ -5,6 +5,139 @@
---
## 2026-09-08 — 발행본 목록의 정본 주소를 `/s` 로 — `/s` 가 앱 셸을 200 으로 주고 있었다
**무슨 일**
사이트맵에서 끝 슬래시가 붙은 줄이 무엇이냐는 물음에서 시작했다. 슬러그 페이지
(`/s/<slug>`)는 이미 슬래시가 없었고, 붙은 건 호스트 루트(`/`)와 목록 페이지(`/s/`) 둘뿐이다.
목록만 형태가 다른 이유는 nginx 였다 — `location ^~ /s/` 는 **슬래시로 시작하는 것만** 잡고,
`/s` 는 맨 아래 `location /` 로 떨어진다.
**그런데 그게 404 가 아니었다.** `/s` 는 200 을 주고 있었고 내용이 **빌더 SPA 셸**이다
(실측: `/s` 3.1KB `<title>Web4Ai</title>` · `/s/` 6.7KB 목록). 크롤러 입장에서는 404 도
목록도 아닌 세 번째 페이지가 오리진에 하나 더 있는 셈이었다.
**바꾼 것**
- `nginx/site.conf(.example)`: `location = /s` 로 목록 index.html 을 직접 준다. `/s/` 는
거기로 301. `^~ /s/` 의 `index index.html` 은 남긴다 — `/s/<slug>/` 가 그걸로 열린다
- `absolute_redirect off`: TLS 를 앞단 Apache 가 끊어서 nginx 의 `$scheme` 는 늘 `http` 다.
기본값대로 절대 URL 을 내면 https 페이지가 http 로 내려가는 301 이 나간다
- `prerender.ts` `indexUrl`: `+ '/'` 제거. canonical·og:url·사이트맵·llms.txt 가 이 값 하나를
쓰므로 전부 같이 따라온다
**왜 형태를 맞추나**
색인 요청·사이트맵 URL 이 canonical 과 어긋나면 구글이 제출분을 "대체 페이지(적절한 표준
태그가 있음)" 로 분류한다 — 색인은 되는데 제출 URL 은 0건으로 보인다. 슬러그 쪽에서 한 번
밟은 함정이고(`prerender.ts` 주석), 목록만 반대 형태로 남아 있었다.
**남은 것**
`/s/<slug>/` 는 여전히 200 이다(canonical 로만 접힌다). 목록과 달리 사이트맵에 없어서
크롤러가 스스로 만들어낼 주소는 아니다.
---
## 2026-09-08 — 내 사이트 목록에 썸네일·주소·시각 — 발행할 때마다 그림이 바뀐다
**무슨 일**
목록 줄이 아이콘·상호·배지·주소 넷뿐이었다. 서버는 이미 `road_address`·`created_at`·
`published_at` 을 주고 있는데 화면이 안 썼다. 한 계정에 '버터브루' 가 4줄 있으면 어느 게
어느 건지 가릴 단서가 화면에 하나도 없다.
**리서치** (Wix · 아임웹)
- Wix `My Sites` 줄에 보이는 건 이름·URL·Premium·협업자뿐이고 **썸네일도 수정일도 없다.**
대신 Sites API 문서가 "이렇게 그려라" 로 지목한 조합은 `displayName · thumbnail · viewUrl ·
editUrl` 이고, 정렬은 최근 수정순이다 — 화면보다 API 권고 쪽이 우리 상황에 맞다.
- 아임웹 내사이트는 기본 정보 + 액션(관리자 접속·복제·템플릿 변경·소유권 이전),
리셀러 목록은 **만료일**을 목록에서 바로 본다. 방문자·주문 숫자는 목록이 아니라
사이트 안 대시보드에 있다.
- 공통: 목록은 **구분 · 상태 · 여는 길** 셋만 한다. 그리고 **둘 다 생성일을 안 쓴다** —
구분은 그림·주소·이름이 하고, 시각은 "마지막으로 뭔가 한 시각" 이 쓰인다.
**바꾼 것**
- `MySiteData.thumbnail_url` 추가(`site_service._my_site_row`). 목록이 사이트 행을 이미
조인해 읽고 있어서 쿼리는 그대로다
- 줄 앞에 썸네일. 없으면 업종 아이콘으로 떨어지고, 로드 실패해도 아이콘으로 되돌린다 —
블롭이 지워진 옛 주소에서 깨진 그림이 뜨는 것보다 낫다
- 줄 아래 한 칸: `도로명 주소 · 시각`. 시각은 **발행됐으면 발행일, 아니면 만든 날** 하나만
쓴다(위 리서치의 결론). 올해면 연도를 뗀다 — 줄이 좁아 주소가 먼저 잘린다
**썸네일이 발행마다 바뀌게** (`site_thumbnail.public_url`)
블롭 이름은 `thumbs/<slug>.<ext>` 로 고정이고 내용만 `overwrite=True` 로 덮어쓴다. 그래서
주소가 안 변했고, 사장님이 사진을 바꿔 재발행해도 **캐시에 남은 지난 그림**이 계속 보였다
(`CACHE_CONTROL` 60초만으로는 그 60초를 못 막는다). 주소에 `?v=<발행 버전>` 을 붙인다.
→ 이름에 버전을 넣지 않는 이유: 사이트당 블롭이 발행 횟수만큼 쌓이는데 지우는 코드가 없다.
→ `scripts/backfill_thumbnails.py` 처럼 그 시점 버전이 없는 경로는 `version=None` 으로
그냥 붙이지 않는다.
**아직 그림이 한 장도 없다** — 로컬·현재 DB 의 사이트 39개 전부 `thumbnail_url` 이 NULL 이다.
버그가 아니라 `AZURE_STORAGE_CONNECTION_STRING` 이 비어 `site_thumbnail.is_configured()` 가
False 라서다(썸네일은 Blob 에만 올라간다). 키를 채우면 다음 발행부터 채워진다.
**검증** — 백엔드 전체 통과. 목록 줄이 주소·생성일·썸네일을 들고 오는지, 발행 안 한 줄에
`thumbnail_url` 키가 아예 없는지, **재발행하면 `?v=1` → `?v=2` 로 주소가 바뀌는지** 4건 추가.
프론트 `tsc + eslint` 통과.
---
## 2026-09-08 — 회사(테넌트)를 걷어냈다 — 사장님 계정이 곧 스코프다
**무슨 일**
사장님이 가입하면 회사가 하나 생기고 그 회사의 직원이 됐다. 가입 폼은 "상호"를 묻고,
에디터 헤더에는 "이름 · 회사명" 이 붙었다. 쓰는 사람은 사장님 한 명인데.
**왜 그랬나**
보일러플레이트(negodata)의 멀티테넌트 스코프 키를 그대로 물려받았다. DECISIONS.md 2절이
"대행사/운영사 단위로 그대로 쓴다" 로 유지 결정을 적어 뒀던 자리다 — 2026-09-08 철회했다.
**바꾼 것**
- 스코프 키가 `company_id` → `places.owner_user_id` 다. `UserInfo` 에서 `company_id` 를 뺐고
(JWT 클레임도 같이 사라진다), `place_crud`·`site_crud` 의 WHERE 가 전부 주인으로 바뀌었다
- **주인은 토큰이 정한다.** `Req_CreatePlace.owner_user_id` 를 없앴다 — body 로 받으면 남의
계정을 적어 만들자마자 남의 목록에 넣을 수 있다. 실측: 기존 92건은 아무도 안 보내서 전부 NULL 이었고,
스코프는 회사가 대신 하고 있었다
- 잡 페이로드 키 `company_id` → `owner_user_id`. 워커가 세우는 `UserInfo.user_id` 는 이제
**사업장 주인**이다 — 예전엔 요청자·검증자·랜덤 uuid 순으로 채웠는데, 그 랜덤 uuid 가
스코프 키가 되는 순간 "남의 사업장" 이 되어 fact 조회가 0건이 된다
- `company.companies` 테이블 · `users.company_id` · `Res_Me.company` · 가입 폼의 상호 칸 삭제
- 테스트: `company_id`/`other_company_id` 픽스처 → `owner_id` 하나. 격리 테스트는
`auth_headers("o2")` 를 한 번 더 부르면 그게 남이다
**마이그레이션** (`init.sql` 끝, 재실행 안전)
백필 → NOT NULL → 컬럼 삭제 순서다. 회사에 계정이 여럿이던 경우는 **가장 먼저 만든 계정**에게
몰아준다. 주인을 못 찾은 행은 지운다 — 스코프가 없으면 아무에게도 안 보이는 유령이다.
실측(로컬): 92건 → 91건(고아 1건 삭제), `demoebf050` 56 · `test` 35.
**남긴 것** — DB 스키마 이름 `company` 는 그대로다. rename 은 모든 모델의 `__table_args__` 를
건드려야 해서 이번 변경에 섞지 않았다.
---
## 2026-09-07 — (사고 2) 목업 사이트가 죽었다 — 참조된 자산은 기간과 무관하게 남긴다
**무슨 일**
`/s/stay` · `/s/stay2` · `/s/stay3` 의 CSS·JS·이미지가 전부 404 가 됐다. 재굽기를 돌려도
살아나지 않았다.
**왜**
`out/s/` 에 디렉토리가 8개인데 payload 는 4개뿐이다. 나머지는 **손으로 넣은 목업**이고,
프리렌더는 payload 를 받은 사이트만 굽는다 — 목업은 **재굽기 대상이 아니다.** 그래서 번들
해시가 바뀌어 옛 자산이 지워지는 순간 영영 복구 불가가 된다. 문서 어디에도 목업 얘기가
한 줄도 없어서(2026-09-07 grep 0건) 이 존재를 모르고 자산 삭제 코드를 건드렸다.
**고친 것** (`scripts/prerender.ts`)
- `referencedAssets()` — 굽기 **전에** `out/s/**/index.html` 을 훑어 `/assets/…` 참조를 모은다
- `pruneAssets` 가 그 목록을 절대 지우지 않는다. **보관 기간보다 우선한다** —
기간으로 막으면 30일 뒤에 똑같은 사고가 난다
- AGENTS.md 함정 목록 맨 위에 ★★ 로 박았다. 목업의 존재 자체가 문서에 없던 게 근본 원인이다
**복구** — 지워진 파일은 `stay-mockup` 워크트리(`solution/site/out/assets`)에 남아 있어서
서버 볼륨에 손으로 되돌려 넣었다. `docker cp` → `out/assets`.
**검증** — 목업 상황 재현: payload 없는 `out/s/mock/index.html` 이 옛 해시를 가리키게 두고
재굽기 → 참조 3개가 남는다. 대장을 60일 전으로 돌려 만료를 강제해도 그대로 남는다.
---
## 2026-09-07 — (사고) 자산 보관 첫 배포에 운영 사이트 CSS 가 끊겼다
**무슨 일**
+22 -2
View File
@@ -44,10 +44,30 @@ server {
image/svg+xml;
# ── 발행 사이트 ────────────────────────────────────────────
# ★ 리다이렉트는 상대 Location 으로 낸다. 기본값(absolute_redirect on)은 `$scheme` 로
# 절대 URL 을 만드는데, TLS 는 앞단 Apache 가 끊으므로 여기 `$scheme` 는 늘 `http` 다 —
# `/s/` 를 접으면 https 페이지가 http 로 내려가는 리다이렉트가 나간다.
absolute_redirect off;
# ★ 발행본 목록의 정본 주소는 **`/s`** 다 — 슬러그 페이지(`/s/<slug>`)와 형태를 맞춘다.
# 이 블록이 없으면 `/s` 는 `^~ /s/` 에 안 걸려 맨 아래 `location /` 로 떨어지고
# **빌더 SPA 셸이 200 으로 나간다.** 404 도 목록도 아닌 세 번째 페이지가 크롤러에
# 잡힌다(실측 2026-09-08: `/s` 3.1KB 앱 셸 · `/s/` 6.7KB 목록).
location = /s {
root /srv/sites;
try_files /s/index.html =404;
add_header Cache-Control "public, max-age=300, must-revalidate";
}
# 옛 주소. 사이트맵·서치콘솔에 `/s/` 로 제출된 것이 남아 있다.
location = /s/ {
return 301 /s;
}
# ^~ 로 잡아 아래 정규식 location 들이 끼어들지 못하게 한다.
location ^~ /s/ {
# ★ `/s/` 자체(발행본 목록 페이지)를 위해 필요하다. try_files 의 첫 인자 `$uri` 가
# 끝 슬래시면 nginx 는 **디렉토리 검사**로 읽고, 디렉토리가 있으면 거기서 멈춘다 —
# ★ `/s/<slug>/`(끝 슬래시) 를 위해 필요하다. try_files 의 첫 인자 `$uri` 가 끝
# 슬래시면 nginx 는 **디렉토리 검사**로 읽고, 디렉토리가 있으면 거기서 멈춘다 —
# index 지시자가 없으면 그 순간 403 이다(=404 로도 안 떨어진다).
index index.html;
# $uri/ 를 거치면 nginx 가 끝 슬래시로 301 을 내보낸다. 크롤러가 리다이렉트를
+50 -26
View File
@@ -5,7 +5,7 @@
-- 단일 PostgreSQL 인스턴스, 단일 database(web4ai_db) 안에서 도메인별 schema 로 묶는다.
-- postgres (1개 서버, 5432)
-- └── web4ai_db
-- ├── company : companies, users
-- ├── company : users
-- ├── place : places, place_aliases, place_links, units, media
-- ├── fact : facts, faqs
-- ├── local : local_contents, routes, nearby_links
@@ -46,28 +46,12 @@ CREATE SCHEMA IF NOT EXISTS site;
CREATE SCHEMA IF NOT EXISTS job;
-- ============================================================
-- company : 회사 / 내부 유저
-- company : 계정
-- ★ 스키마 이름만 company 다. 회사(테넌트) 개념은 2026-09-08 에 걷어냈다 —
-- 스키마 rename 은 모든 모델의 __table_args__ 를 건드려야 해서 따로 둔다.
-- ============================================================
CREATE TABLE IF NOT EXISTS company.companies (
company_id uuid PRIMARY KEY DEFAULT gen_random_uuid(), -- 회사 식별자(PK)
name VARCHAR(100) NOT NULL, -- 회사명
business_number VARCHAR(30) NULL, -- 사업자등록번호
code INTEGER NULL, -- 회사코드 (내부 인덱스용)
representative_name VARCHAR(50) NULL, -- 대표자명
email VARCHAR(255) NULL, -- 대표 이메일
contact_number VARCHAR(20) NULL, -- 대표 연락처
website_url VARCHAR(255) NULL, -- 홈페이지 URL
industry SMALLINT NULL, -- 업종 ( 필요한 만큼 숫자에 매핑하여 사용 )
status SMALLINT NOT NULL DEFAULT 1, -- 상태: 1=active(활성), 2=inactive(비활성)
settings JSONB NULL, -- 회사별 커스터마이징: branding(CI)/labels(용어)/features(동작)
created_at TIMESTAMPTZ NOT NULL DEFAULT now(), -- 생성 시각(UTC)
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(), -- 수정 시각(UTC, 앱에서 갱신)
deleted BOOLEAN NOT NULL DEFAULT FALSE -- 소프트 삭제 여부
);
CREATE TABLE IF NOT EXISTS company.users (
user_id uuid PRIMARY KEY DEFAULT gen_random_uuid(), -- 유저 식별자(PK)
company_id uuid NOT NULL, -- 소속 회사(company.companies.company_id)
id VARCHAR(64) NOT NULL, -- 로그인 ID (구글 계정은 google_<sub>)
password VARCHAR(255) NULL, -- bcrypt 해시. 소셜 계정은 NULL
name VARCHAR(50) NULL, -- 이름
@@ -88,8 +72,7 @@ CREATE TABLE IF NOT EXISTS company.users (
-- ============================================================
CREATE TABLE IF NOT EXISTS place.places (
place_id uuid PRIMARY KEY DEFAULT gen_random_uuid(), -- 사업장 식별자(PK)
company_id uuid NOT NULL, -- 테넌트(company.companies.company_id)
owner_user_id uuid NULL, -- 사장님 계정(company.users.user_id)
owner_user_id uuid NOT NULL, -- ★ 스코프 키. 사장님 계정(company.users.user_id)
name VARCHAR(200) NOT NULL, -- 상호명(입력값)
category SMALLINT NOT NULL, -- 업종(PlaceCategory): 1=숙박 2=카페 3=음식점 4=피부과·성형외과
status SMALLINT NOT NULL DEFAULT 1, -- 상태(PlaceStatus): 1=draft 2=collecting 3=review 4=published 5=suspended
@@ -101,6 +84,7 @@ CREATE TABLE IF NOT EXISTS place.places (
latitude NUMERIC(10,7) NULL, -- 위도
longitude NUMERIC(10,7) NULL, -- 경도
region_code VARCHAR(10) NULL, -- 카카오 행정구역 코드 — ★ 지역정보 캐시 키
external_category VARCHAR(200) NULL, -- 외부 장소 DB 분류 원문("음식점 > 한식 > 육류" / "펜션") — 주변 맛집 경쟁업소 제외 기준(폴백)
verified_at TIMESTAMPTZ NULL, -- ★ 동일 업소 검증 통과 시각. NULL = 수집·발행 금지
verified_by uuid NULL, -- 검증자(company.users.user_id)
content_updated_at TIMESTAMPTZ NULL, -- ★ 노출값이 마지막으로 바뀐 시각 — 개별 재빌드 대상 판별용
@@ -228,6 +212,25 @@ CREATE TABLE IF NOT EXISTS local.local_contents (
deleted BOOLEAN NOT NULL DEFAULT FALSE
);
-- 업장 반경의 주변 정보(맛집·관광지·축제·여행코스). ★ 키는 place_id — local_contents(행정구역 캐시)와 다르다.
-- 빌드 때마다 TourAPI locationBasedList2 로 갱신. 응답에서 사라진 행은 소프트 삭제, hidden 은 유지.
CREATE TABLE IF NOT EXISTS local.place_contents (
place_content_id uuid PRIMARY KEY DEFAULT gen_random_uuid(), -- 주변 정보 식별자(PK)
place_id uuid NOT NULL, -- 사업장(place.places.place_id)
content_type SMALLINT NOT NULL, -- 종류(LocalContentType): 2=축제 3=관광지 4=맛집 5=여행코스
external_id VARCHAR(100) NOT NULL, -- TourAPI contentid
title VARCHAR(300) NOT NULL,
body JSONB NOT NULL, -- 정규화한 TourAPI 항목(좌표·주소·사진·기간)
distance_m INTEGER NOT NULL, -- 업장 좌표에서의 거리(m). 정렬 기준
has_image BOOLEAN NOT NULL DEFAULT FALSE, -- 상업 이용 가능한 대표사진 유무
display_end_at TIMESTAMPTZ NULL, -- 축제 종료. 지나면 스냅샷이 거른다
hidden BOOLEAN NOT NULL DEFAULT FALSE, -- 운영자 숨김(재수집이 덮어쓰지 않음)
collected_at TIMESTAMPTZ NOT NULL DEFAULT now(),
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
deleted BOOLEAN NOT NULL DEFAULT FALSE
);
CREATE TABLE IF NOT EXISTS local.routes (
route_id uuid PRIMARY KEY DEFAULT gen_random_uuid(), -- 경로 식별자(PK)
place_id uuid NOT NULL, -- 사업장(place.places.place_id)
@@ -355,15 +358,11 @@ CREATE TABLE IF NOT EXISTS job.jobs (
-- ============================================================
-- 인덱스
-- ============================================================
CREATE INDEX IF NOT EXISTS idx_users_company_id ON company.users (company_id);
-- 소프트 삭제를 쓰므로 자연키 유니크는 부분 인덱스(deleted = FALSE)로 건다.
CREATE UNIQUE INDEX IF NOT EXISTS uq_users_id ON company.users (id) WHERE deleted = FALSE;
CREATE UNIQUE INDEX IF NOT EXISTS uq_companies_biz_number ON company.companies (business_number) WHERE deleted = FALSE AND business_number IS NOT NULL;
CREATE INDEX IF NOT EXISTS idx_companies_code ON company.companies (code) WHERE deleted = FALSE;
-- place
CREATE INDEX IF NOT EXISTS idx_places_company_id ON place.places (company_id);
CREATE INDEX IF NOT EXISTS idx_places_owner_user_id ON place.places (owner_user_id);
CREATE INDEX IF NOT EXISTS idx_places_region_code ON place.places (region_code) WHERE deleted = FALSE;
CREATE INDEX IF NOT EXISTS idx_place_aliases_place ON place.place_aliases (place_id);
@@ -400,6 +399,8 @@ CREATE INDEX IF NOT EXISTS idx_facts_publishable ON fact.facts (place_id, status
-- local
CREATE INDEX IF NOT EXISTS idx_local_contents_region ON local.local_contents (region_code);
CREATE INDEX IF NOT EXISTS idx_routes_place ON local.routes (place_id);
CREATE INDEX IF NOT EXISTS idx_place_contents_place ON local.place_contents (place_id);
CREATE UNIQUE INDEX IF NOT EXISTS uq_place_contents_keyed ON local.place_contents (place_id, content_type, external_id) WHERE deleted = false;
CREATE INDEX IF NOT EXISTS idx_nearby_links_place ON local.nearby_links (place_id);
-- 지역 캐시 중복 방지. external_id 가 있는 항목(축제·관광지·맛집)과 없는 항목(날씨)을 나눠 건다.
@@ -448,3 +449,26 @@ CREATE UNIQUE INDEX IF NOT EXISTS uq_users_provider_uid ON company.users (provid
-- 2026-09-03 쇼케이스 카드 썸네일. CREATE TABLE 에만 있어서 기존 DB 가 조용히 깨졌다
-- (실측: 킹서버에서 GET /v1/showcase 가 200 인데 내용은 비었다).
ALTER TABLE site.sites ADD COLUMN IF NOT EXISTS thumbnail_url VARCHAR(500) NULL;
-- 2026-09-08 회사(테넌트) 제거. 쓰는 사람은 사장님 혼자인데 가입 한 번이 회사를 하나 만들고
-- 그 회사의 직원이 되는 구조였다. 사업장을 계정에 직접 매단다.
-- ★ 순서가 중요하다 — 백필 → NOT NULL → 컬럼 삭제. 반대로 하면 주인을 잃은 행이 남는다.
-- ★ 회사에 계정이 여럿이던 경우(내부 운영 계정)는 **가장 먼저 만든 계정**에게 몰아준다.
DO $$
BEGIN
IF EXISTS (SELECT 1 FROM information_schema.columns
WHERE table_schema='place' AND table_name='places' AND column_name='company_id') THEN
UPDATE place.places p
SET owner_user_id = (
SELECT u.user_id FROM company.users u
WHERE u.company_id = p.company_id AND u.deleted = FALSE
ORDER BY u.created_at LIMIT 1)
WHERE p.owner_user_id IS NULL;
-- 주인을 못 찾은 행(회사가 통째로 지워진 경우)은 남겨 둘 수 없다 — 스코프가 없으면 아무에게도 안 보인다.
DELETE FROM place.places WHERE owner_user_id IS NULL;
ALTER TABLE place.places ALTER COLUMN owner_user_id SET NOT NULL;
ALTER TABLE place.places DROP COLUMN company_id;
END IF;
END $$;
ALTER TABLE company.users DROP COLUMN IF EXISTS company_id;
DROP TABLE IF EXISTS company.companies;
@@ -19,6 +19,10 @@
{ "key": "breakfast", "label": "조식 제공", "type": "bool", "scope": "place", "required": false, "critical": false, "allow_llm": false },
{ "key": "baby_amenities", "label": "유아용품 비치", "type": "bool", "scope": "place", "required": false, "critical": false, "allow_llm": false },
{ "key": "pickup_service", "label": "픽업 서비스", "type": "bool", "scope": "place", "required": false, "critical": false, "allow_llm": false },
{ "key": "facilities", "label": "부대시설", "type": "text", "scope": "place", "required": false, "critical": false, "allow_llm": false },
{ "key": "total_rooms", "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": "intro", "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 },
@@ -29,6 +33,15 @@
{ "key": "bathroom_count", "label": "욕실 수", "type": "number", "scope": "unit", "required": false, "critical": false, "allow_llm": false, "unit": "개" },
{ "key": "has_kitchen", "label": "주방 여부", "type": "bool", "scope": "unit", "required": false, "critical": true, "allow_llm": false },
{ "key": "has_aircon", "label": "에어컨", "type": "bool", "scope": "unit", "required": false, "critical": false, "allow_llm": false },
{ "key": "has_bathroom", "label": "욕실", "type": "bool", "scope": "unit", "required": false, "critical": false, "allow_llm": false },
{ "key": "has_tv", "label": "TV", "type": "bool", "scope": "unit", "required": false, "critical": false, "allow_llm": false },
{ "key": "has_internet", "label": "인터넷", "type": "bool", "scope": "unit", "required": false, "critical": false, "allow_llm": false },
{ "key": "has_refrigerator", "label": "냉장고", "type": "bool", "scope": "unit", "required": false, "critical": false, "allow_llm": false },
{ "key": "has_hairdryer", "label": "드라이기", "type": "bool", "scope": "unit", "required": false, "critical": false, "allow_llm": false },
{ "key": "has_toiletries", "label": "세면도구", "type": "bool", "scope": "unit", "required": false, "critical": false, "allow_llm": false },
{ "key": "has_table", "label": "테이블", "type": "bool", "scope": "unit", "required": false, "critical": false, "allow_llm": false },
{ "key": "has_sofa", "label": "소파", "type": "bool", "scope": "unit", "required": false, "critical": false, "allow_llm": false },
{ "key": "has_home_theater", "label": "홈시어터", "type": "bool", "scope": "unit", "required": false, "critical": false, "allow_llm": false },
{ "key": "view", "label": "전망", "type": "text", "scope": "unit", "required": false, "critical": false, "allow_llm": false },
{ "key": "weekday_price", "label": "주중 요금", "type": "number", "scope": "unit", "required": false, "critical": true, "allow_llm": false, "unit": "원" },
{ "key": "weekend_price", "label": "주말 요금", "type": "number", "scope": "unit", "required": false, "critical": true, "allow_llm": false, "unit": "원" },
@@ -10,7 +10,6 @@ from common.enums import (
DBType,
UserStatus,
UserRole,
CompanyStatus,
PlaceStatus,
FactStatus,
MediaStatus,
@@ -45,30 +44,11 @@ class MainTableMixin(_DBTypeMixin):
# ERD 도메인 모델
class companies(MainTableMixin, MAIN_BASE):
__tablename__ = "companies"
__table_args__ = {"schema": "company"}
company_id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
name = Column(String(100), nullable=False)
business_number = Column(String(30), nullable=True)
code = Column(Integer, nullable=True) # 내부 인덱스용
representative_name = Column(String(50), nullable=True)
email = Column(String(255), nullable=True)
contact_number = Column(String(20), nullable=True)
website_url = Column(String(255), nullable=True)
industry = Column(SmallInteger, nullable=True) # 업종 코드 (스키마 SMALLINT)
status = Column(SmallInteger, nullable=False, default=CompanyStatus.ACTIVE.value) # CompanyStatus
# 회사별 커스터마이징 설정. branding(CI)/labels(용어)/features(동작)
settings = Column(JSONB, nullable=True)
class users(MainTableMixin, MAIN_BASE):
__tablename__ = "users"
__table_args__ = {"schema": "company"}
user_id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
company_id = Column(UUID(as_uuid=True), nullable=False, index=True)
# 20자였다. 구글 계정의 로그인 아이디를 `google_<sub>`(최대 28자)로 만들면서 넓혔다 —
# sub 를 잘라 쓰면 앞자리가 같은 두 계정이 한 아이디로 겹친다.
id = Column(String(64), nullable=False, unique=True, index=True) # 로그인 아이디
@@ -102,8 +82,8 @@ class places(MainTableMixin, MAIN_BASE):
)
place_id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
company_id = Column(UUID(as_uuid=True), nullable=False, index=True) # 테넌트 스코프(company.companies)
owner_user_id = Column(UUID(as_uuid=True), nullable=True, index=True) # 사장님 계정(company.users)
# ★ 스코프 키. 사장님 한 명이 자기 가게만 본다 — 회사(테넌트)를 걷어내면서 이 컬럼이 그 자리를 받았다.
owner_user_id = Column(UUID(as_uuid=True), nullable=False, index=True) # 사장님 계정(company.users)
name = Column(String(200), nullable=False) # 상호명(입력값)
category = Column(SmallInteger, nullable=False) # PlaceCategory — 업종 스키마 선택 키
status = Column(SmallInteger, nullable=False, server_default=text("1"), default=PlaceStatus.DRAFT.value)
@@ -119,6 +99,10 @@ class places(MainTableMixin, MAIN_BASE):
latitude = Column(Numeric(10, 7), nullable=True)
longitude = Column(Numeric(10, 7), nullable=True)
region_code = Column(String(10), nullable=True) # 행정구역 코드 — ★ 지역정보 캐시 키(사이트 50개여도 조회 1회)
# 외부 장소 DB 가 준 분류 문자열 원문(카카오 "음식점 > 한식 > 육류" · 네이버 "펜션"). 검증 때 박제한다.
# ★ 쓰임: 주변 맛집에서 **같은 중분류(경쟁 업소)를 빼는** 기준. TourAPI 에 등록된 업장이면 그쪽 분류가 우선이고,
# 이 값은 그 폴백이다(services/local_content_service._own_food_class).
external_category = Column(String(200), nullable=True)
verified_at = Column(DateTime(timezone=True), nullable=True) # ★ NULL = 미검증 → 수집·발행 금지
verified_by = Column(UUID(as_uuid=True), nullable=True)
# ★ 노출값(VERIFIED/CORRECTED fact)이 마지막으로 바뀐 시각. 개별 재빌드 대상 판별용 —
@@ -335,6 +319,42 @@ class local_contents(MainTableMixin, MAIN_BASE):
expires_at = Column(DateTime(timezone=True), nullable=True) # TTL — 지나면 갱신 대상(값은 유지)
class place_contents(MainTableMixin, MAIN_BASE):
"""업장 반경의 주변 정보(맛집·관광지·축제·여행코스). ★ 키는 place_id 다.
local_contents 는 행정구역(region_code) 단위 캐시라 '그 시군구에 있는 것'을 줄 뿐
'이 업장에서 가까운 것'을 못 준다(2026-09-04 결정, specs/2026-09-04-tourapi-radius-spike.md).
그래서 업장 좌표로 TourAPI locationBasedList2 를 직접 물어 여기 담는다.
★ 빌드 때마다 갱신된다(services/local_content_service.sync_place). 응답에서 사라진 행은
소프트 삭제한다 — 업장 전용 데이터라 반경 밖으로 밀린 것을 남길 이유가 없다.
단 hidden(운영자 숨김)은 재수집이 덮어쓰지 않는다.
★ 외부 API 실패 시 행을 지우거나 비우지 않는다 — 직전 값을 그대로 쓴다."""
__tablename__ = "place_contents"
__table_args__ = (
Index(
"uq_place_contents_keyed",
"place_id", "content_type", "external_id",
unique=True,
postgresql_where=text("deleted = false"),
),
{"schema": "local"},
)
place_content_id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
place_id = Column(UUID(as_uuid=True), nullable=False, index=True)
content_type = Column(SmallInteger, nullable=False) # LocalContentType 2~5
external_id = Column(String(100), nullable=False) # TourAPI contentid
title = Column(String(300), nullable=False)
body = Column(JSONB, nullable=False) # 정규화한 TourAPI 항목(좌표·주소·사진·기간)
distance_m = Column(Integer, nullable=False) # 업장 좌표에서의 거리(m). 정렬 기준
has_image = Column(Boolean, nullable=False, server_default=text("false"), default=False) # 상업 이용 가능한 대표사진이 있는가
display_end_at = Column(DateTime(timezone=True), nullable=True) # 축제 종료(KST 자정). 지나면 스냅샷이 거른다
hidden = Column(Boolean, nullable=False, server_default=text("false"), default=False) # 운영자 숨김
collected_at = Column(DateTime(timezone=True), nullable=False, server_default=_utc_now_sql())
class routes(MainTableMixin, MAIN_BASE):
"""가는 길. 검증 상태(FactStatus)를 그대로 쓴다 — 틀린 경로 안내도 헛걸음을 만든다."""
+6 -4
View File
@@ -286,10 +286,12 @@ VISION_AUTO_APPROVE_CONFIDENCE = 0.7
class LocalContentType(CodeEnum):
"""local_contents.content_type 코드값. 행정구역 코드 단위로 캐싱되는 지역 정보 종류."""
WEATHER = 1 # 날씨 (Open-Meteo)
FESTIVAL = 2 # 축제 (TourAPI 행사정보, 주 1회)
ATTRACTION = 3 # 관광지 (TourAPI 지역기반, 월 1회)
RESTAURANT = 4 # 주변 맛집 (카카오 카테고리 검색)
WEATHER = 1 # 날씨 (Open-Meteo) — local_contents(지역 캐시)
# ↓ 2~5 는 place_contents(업장 반경 캐시). TourAPI locationBasedList2 contentTypeId 와 짝: 15·12·39·25
FESTIVAL = 2 # 축제/공연/행사 (15)
ATTRACTION = 3 # 관광지 (12)
RESTAURANT = 4 # 음식점 (39)
COURSE = 5 # 여행코스 (25) — 백엔드만. 렌더러 자리는 아직 없다
class LocalSource(CodeEnum):
+1 -2
View File
@@ -67,9 +67,8 @@ class PageParams:
class UserInfo(StructModel):
"""JWT subject 로 인코딩되는 유저 식별 정보."""
user_id: str # users.user_id (uuid) — 데이터 스코프 키
user_id: str # users.user_id (uuid) — 데이터 스코프 키. 사업장은 owner_user_id 로 이 값에 매인다
id: str # users.id (로그인 아이디) — get_me 재조회 키
company_id: str # users.company_id (uuid) — 멀티테넌트 스코프 키
role: int # users.role (UserRole) — 권한 게이트(최고관리자 등) 판단 키
def __init__(self, *args, **kwargs) -> None:
+24
View File
@@ -0,0 +1,24 @@
"""좌표 거리 — 공용 한 벌.
★ 같은 하버사인 공식이 tour_lookup(500m 동일업소 판정)·itinerary(일정 반경)·tour_api(축제 20km 필터)
세 곳에 각각 복사돼 있었다(2026-09-08 정리). 지구 반지름·단위가 파일마다 달라지면 같은 두 점의
거리가 모듈마다 다르게 나온다 — 거리로 무엇을 넣고 뺄지 정하는 코드가 셋이라 한 벌이어야 한다.
국내 범위라 하버사인(구면 근사)이면 충분하다. 오차는 수 m 수준으로, 우리가 쓰는 판정
(500m 이내·5~20km 반경)에서 결과를 바꾸지 않는다.
"""
import math
EARTH_RADIUS_M = 6_371_000.0
def haversine_m(lat1: float, lng1: float, lat2: float, lng2: float) -> float:
"""두 좌표(위도, 경도) 사이의 거리(m). ★ 인자 순서는 (위도, 경도) — mapx/mapy 는 (경도, 위도)라 뒤집어 넣는다."""
p1, p2 = math.radians(lat1), math.radians(lat2)
dp, dl = math.radians(lat2 - lat1), math.radians(lng2 - lng1)
a = math.sin(dp / 2) ** 2 + math.cos(p1) * math.cos(p2) * math.sin(dl / 2) ** 2
return 2 * EARTH_RADIUS_M * math.asin(math.sqrt(a))
def haversine_km(lat1: float, lng1: float, lat2: float, lng2: float) -> float:
return haversine_m(lat1, lng1, lat2, lng2) / 1000.0
+25 -32
View File
@@ -14,7 +14,7 @@ from sqlalchemy import text
from sqlalchemy.ext.asyncio import create_async_engine
from common.database.model.models import MAIN_BASE
from common.enums import CompanyStatus
from common.enums import UserRole, UserStatus
from config.server_configs import main_db_config
@@ -92,7 +92,7 @@ async def db_engine(_test_db_lifecycle):
# 도메인 테이블 전부 비워 격리 (CASCADE: FK 미설정이라 안전망)
await conn.execute(
text(
"TRUNCATE TABLE users, companies, places, place_aliases, place_links, units, media, "
"TRUNCATE TABLE users, places, place_aliases, place_links, units, media, "
"facts, faqs, local_contents, routes, nearby_links, "
"sites, site_versions, publish_logs, ai_check_results, jobs RESTART IDENTITY CASCADE"
)
@@ -102,30 +102,24 @@ async def db_engine(_test_db_lifecycle):
@pytest_asyncio.fixture
async def company_id(db_engine) -> str:
"""테스트용 소속사 1개를 시드하고 company_id(uuid str)를 돌려준다.
users 는 company_id 를 요구하므로 계정 생성 테스트의 선행 조건이다.
async def owner_id(db_engine) -> str:
"""사장님 계정 1개를 시드하고 user_id(uuid str)를 돌려준다.
★ 예전엔 `company_id`(소속사)였다. 회사(테넌트)를 걷어내면서 사업장이 `owner_user_id` 로
계정에 직접 매이게 됐다 — DB 를 직접 시드하는 테스트가 place 에 넣을 주인이 이 값이다.
"""
cid = uuid.uuid4()
uid = uuid.uuid4()
async with db_engine.begin() as conn:
# status 는 NOT NULL(모델 default 는 ORM 전용이라 raw INSERT 엔 안 먹음) → 명시.
# status·role 은 NOT NULL(모델 default 는 ORM 전용이라 raw INSERT 엔 안 먹음) → 명시.
await conn.execute(
text("INSERT INTO companies (company_id, name, status) VALUES (:cid, :name, :status)"),
{"cid": cid, "name": "테스트사", "status": CompanyStatus.ACTIVE.value},
text(
"INSERT INTO users (user_id, id, password, name, status, role, last_accessed_at) "
"VALUES (:uid, :id, NULL, :name, :status, :role, now())"
),
{"uid": uid, "id": f"seed{uid.hex[:8]}", "name": "시드사장",
"status": UserStatus.ACTIVE.value, "role": UserRole.USER.value},
)
return str(cid)
@pytest_asyncio.fixture
async def other_company_id(db_engine) -> str:
"""company_id 와 다른 소속사 1개(회사 스코프/IDOR 격리 테스트용)."""
cid = uuid.uuid4()
async with db_engine.begin() as conn:
await conn.execute(
text("INSERT INTO companies (company_id, name, status) VALUES (:cid, :name, :status)"),
{"cid": cid, "name": "다른회사", "status": CompanyStatus.ACTIVE.value},
)
return str(cid)
return str(uid)
@pytest_asyncio.fixture
@@ -139,28 +133,27 @@ async def client(db_engine):
@pytest_asyncio.fixture
async def auth_headers(db_engine, client, company_id):
async def auth_headers(db_engine, client):
"""테스트 유저를 시드하고 로그인 헤더(Bearer)를 돌려주는 팩토리.
계정 생성 API 가 없으므로 users 행을 직접 INSERT(비번 bcrypt 해시)한 뒤 /v1/auth/login 으로 토큰을 받는다.
company 미지정 시 기본 소속사(company_id 픽스처). role 로 OWNER 계정도 만들 수 있다.
호출: `h = await auth_headers("user1")` / `await auth_headers("userB", other_company_id)`.
★ 회사 인자가 없다. 스코프가 계정 자체이므로 **다른 login_id 로 한 번 더 부르면 그게 남**이다
— 격리 테스트는 `await auth_headers("o2")` 하나면 된다.
호출: `h = await auth_headers("user1")`.
"""
from common.enums import UserRole, UserStatus
from router.v1.validator.dependencies import GetHashedPW
async def _make(login_id, company=None, *, password="pw1234", role=UserRole.USER.value, name="n"):
cid = company or company_id
async def _make(login_id, *, password="pw1234", role=UserRole.USER.value, name="n"):
hashed = await GetHashedPW(password)
async with db_engine.begin() as conn:
# status·role 은 NOT NULL — ORM default 는 raw INSERT 에 안 먹으므로 명시(companies.status 와 동일).
# status·role 은 NOT NULL — ORM default 는 raw INSERT 에 안 먹으므로 명시.
await conn.execute(
text(
"INSERT INTO users (user_id, company_id, id, password, name, status, role, last_accessed_at) "
"VALUES (:uid, :cid, :id, :pw, :name, :status, :role, now())"
"INSERT INTO users (user_id, id, password, name, status, role, last_accessed_at) "
"VALUES (:uid, :id, :pw, :name, :status, :role, now())"
),
{
"uid": uuid.uuid4(), "cid": uuid.UUID(cid), "id": login_id, "pw": hashed,
"uid": uuid.uuid4(), "id": login_id, "pw": hashed,
"name": name, "status": UserStatus.ACTIVE.value, "role": role,
},
)
+37 -13
View File
@@ -9,7 +9,9 @@ from common.utils.gtime import GTime
class LocalContentCRUD:
async def list(self, db, status: int | None = None, region_code: str | None = None):
conds = [local_contents.deleted == False, local_contents.content_type == LocalContentType.FESTIVAL.value] # noqa: E712
"""축제·관광지·맛집·날씨 전 종류. ★ 예전엔 FESTIVAL 로 고정돼 있어 sync_region 이 받은
관광지·맛집이 이 목록에 영영 안 보였다(admin 화면이 축제만 검수/발행하는 줄 알게 됨)."""
conds = [local_contents.deleted == False] # noqa: E712
if status is not None:
conds.append(local_contents.status == status)
if region_code:
@@ -21,18 +23,6 @@ class LocalContentCRUD:
async def insert(self, db, row):
return await DB_SESSION_MNG.insert(db, row)
async def get_by_external_id(self, db, region_code: str, external_id: str):
err, rows = await DB_SESSION_MNG.execute(
db,
select(local_contents).where(
local_contents.region_code == region_code,
local_contents.content_type == LocalContentType.FESTIVAL.value,
local_contents.external_id == external_id,
local_contents.deleted == False, # noqa: E712
).limit(1),
)
return err, rows[0] if rows else None
async def publish(self, db, ids: list, user_id):
return await DB_SESSION_MNG.add_with_rowcount(
db,
@@ -52,6 +42,40 @@ class LocalContentCRUD:
async def end(self, db, content_id):
return await self.update(db, content_id, {"status": 3})
async def list_keyed(self, db, region_code: str, content_type: int):
"""지역 × 종류의 외부 ID 있는 행 전부(축제·관광지·맛집). 동기화가 기존값과 비교할 때 쓴다."""
return await DB_SESSION_MNG.execute(
db,
select(local_contents).where(
local_contents.region_code == region_code,
local_contents.content_type == content_type,
local_contents.external_id.isnot(None),
local_contents.deleted == False, # noqa: E712
),
)
async def upsert_keyed(self, db, values: dict):
"""외부 ID 로 식별되는 행(축제·관광지·맛집)의 삽입/갱신.
★ uq_local_contents_keyed 부분 유니크 인덱스에 태운다 — 같은 지역을 두 번 동기화해도
중복 행이 생기지 않고 기존 값만 갱신된다."""
stmt = pg_insert(local_contents).values(**values)
stmt = stmt.on_conflict_do_update(
index_elements=[local_contents.region_code, local_contents.content_type, local_contents.external_id],
index_where=and_(local_contents.deleted == False, local_contents.external_id.isnot(None)), # noqa: E712
set_={
"title": stmt.excluded.title,
"body": stmt.excluded.body,
"source": stmt.excluded.source,
"status": stmt.excluded.status,
"collected_at": stmt.excluded.collected_at,
"display_end_at": stmt.excluded.display_end_at,
"published_at": stmt.excluded.published_at,
"updated_at": GTime.UTC(),
},
)
return await DB_SESSION_MNG.add(db, stmt)
async def get_weather(self, db, region_code: str):
err, rows = await DB_SESSION_MNG.execute(
db,
@@ -0,0 +1,63 @@
from sqlalchemy import and_, select, update
from sqlalchemy.dialects.postgresql import insert as pg_insert
from common.database.db_session_manager import DB_SESSION_MNG
from common.database.model.models import place_contents
from common.utils.gtime import GTime
class PlaceContentCRUD:
"""업장 반경 주변정보(place_contents). 키는 place_id 다."""
async def list_by_place(self, db, place_id, *, include_hidden: bool = True):
conds = [place_contents.place_id == place_id, place_contents.deleted == False] # noqa: E712
if not include_hidden:
conds.append(place_contents.hidden == False) # noqa: E712
return await DB_SESSION_MNG.execute(
db,
select(place_contents).where(and_(*conds))
.order_by(place_contents.content_type.asc(), place_contents.has_image.desc(), place_contents.distance_m.asc()),
)
async def upsert(self, db, values: dict):
"""(place_id, content_type, external_id) 로 삽입/갱신. ★ hidden 은 건드리지 않는다 —
운영자가 숨긴 것을 재수집이 되살리면 안 된다."""
stmt = pg_insert(place_contents).values(**values)
stmt = stmt.on_conflict_do_update(
index_elements=[place_contents.place_id, place_contents.content_type, place_contents.external_id],
index_where=(place_contents.deleted == False), # noqa: E712
set_={
"title": stmt.excluded.title,
"body": stmt.excluded.body,
"distance_m": stmt.excluded.distance_m,
"has_image": stmt.excluded.has_image,
"display_end_at": stmt.excluded.display_end_at,
"collected_at": stmt.excluded.collected_at,
"updated_at": GTime.UTC(),
},
)
return await DB_SESSION_MNG.add(db, stmt)
async def soft_delete_missing(self, db, place_id, keep: set[tuple[int, str]]):
"""이번 응답에 없는 행을 소프트 삭제. keep = {(content_type, external_id)}."""
err, rows = await DB_SESSION_MNG.execute(
db,
select(place_contents.place_content_id, place_contents.content_type, place_contents.external_id)
.where(place_contents.place_id == place_id, place_contents.deleted == False), # noqa: E712
)
gone = [r.place_content_id for r in (rows or []) if (int(r.content_type), r.external_id) not in keep]
if not gone:
return err, 0
return await DB_SESSION_MNG.add_with_rowcount(
db,
update(place_contents).where(place_contents.place_content_id.in_(gone))
.values(deleted=True, updated_at=GTime.UTC()),
)
async def set_hidden(self, db, place_content_id, hidden: bool):
return await DB_SESSION_MNG.add_with_rowcount(
db,
update(place_contents).where(
place_contents.place_content_id == place_content_id, place_contents.deleted == False # noqa: E712
).values(hidden=hidden, updated_at=GTime.UTC()),
)
+13 -13
View File
@@ -11,26 +11,26 @@ from common.logger import LOG
from common.utils.gtime import GTime
# 사업장 CRUD. 모든 조회는 company_id(테넌트)로 스코프한다 — 남의 회사 사업장이 보이면 안 된다.
# 사업장 CRUD. 모든 조회는 owner_user_id(사장님)로 스코프한다 — 남의 가게가 보이면 안 된다.
class IPlaceCRUD(ABC):
@abstractmethod
async def add_place(self, cdb: AsyncSession, place: places) -> ErrorType:
pass
@abstractmethod
async def get_place(self, cdb: AsyncSession, company_id, place_id) -> Tuple[ErrorType, places]:
async def get_place(self, cdb: AsyncSession, owner_user_id, place_id) -> Tuple[ErrorType, places]:
pass
@abstractmethod
async def list_places(self, cdb: AsyncSession, company_id, search, category, status, skip, limit) -> Tuple[ErrorType, list, int]:
async def list_places(self, cdb: AsyncSession, owner_user_id, search, category, status, skip, limit) -> Tuple[ErrorType, list, int]:
pass
@abstractmethod
async def update_place(self, cdb: AsyncSession, company_id, place_id, data: dict) -> Tuple[ErrorType, int]:
async def update_place(self, cdb: AsyncSession, owner_user_id, place_id, data: dict) -> Tuple[ErrorType, int]:
pass
@abstractmethod
async def delete_place(self, cdb: AsyncSession, company_id, place_id) -> Tuple[ErrorType, int]:
async def delete_place(self, cdb: AsyncSession, owner_user_id, place_id) -> Tuple[ErrorType, int]:
pass
@abstractmethod
@@ -73,11 +73,11 @@ class PlaceCRUD(IPlaceCRUD):
LOG.e_no_callstack(ex)
return ErrorType.DB_RUN_FAILED
async def get_place(self, cdb: AsyncSession, company_id, place_id) -> Tuple[ErrorType, places]:
async def get_place(self, cdb: AsyncSession, owner_user_id, place_id) -> Tuple[ErrorType, places]:
try:
query = (
select(places)
.where(places.place_id == place_id, places.company_id == company_id, places.deleted == False) # noqa: E712
.where(places.place_id == place_id, places.owner_user_id == owner_user_id, places.deleted == False) # noqa: E712
.limit(1)
)
err_type, row_list = await DB_SESSION_MNG.execute(cdb, query)
@@ -91,11 +91,11 @@ class PlaceCRUD(IPlaceCRUD):
return ErrorType.DB_RUN_FAILED, None
async def list_places(
self, cdb: AsyncSession, company_id, search: Optional[str], category: Optional[int],
self, cdb: AsyncSession, owner_user_id, search: Optional[str], category: Optional[int],
status: Optional[int], skip: int, limit: int,
) -> Tuple[ErrorType, list, int]:
try:
conditions = [places.deleted == False, places.company_id == company_id] # noqa: E712
conditions = [places.deleted == False, places.owner_user_id == owner_user_id] # noqa: E712
if category is not None:
conditions.append(places.category == category)
if status is not None:
@@ -126,14 +126,14 @@ class PlaceCRUD(IPlaceCRUD):
LOG.e_no_callstack(ex)
return ErrorType.DB_RUN_FAILED, [], 0
async def update_place(self, cdb: AsyncSession, company_id, place_id, data: dict) -> Tuple[ErrorType, int]:
async def update_place(self, cdb: AsyncSession, owner_user_id, place_id, data: dict) -> Tuple[ErrorType, int]:
"""회사 스코프를 WHERE 에 걸어 남의 회사 사업장을 못 건드리게 한다. (ErrorType, 적용행수)."""
try:
if not data:
return ErrorType.SUCCESS, 0
query = (
update(places)
.where(places.place_id == place_id, places.company_id == company_id, places.deleted == False) # noqa: E712
.where(places.place_id == place_id, places.owner_user_id == owner_user_id, places.deleted == False) # noqa: E712
.values(**data, updated_at=GTime.UTC())
)
return await DB_SESSION_MNG.add_with_rowcount(cdb, query)
@@ -141,12 +141,12 @@ class PlaceCRUD(IPlaceCRUD):
LOG.e_no_callstack(ex)
return ErrorType.DB_RUN_FAILED, 0
async def delete_place(self, cdb: AsyncSession, company_id, place_id) -> Tuple[ErrorType, int]:
async def delete_place(self, cdb: AsyncSession, owner_user_id, place_id) -> Tuple[ErrorType, int]:
"""사업장을 실제 삭제한다. 회사 스코프 밖의 행은 건드리지 않는다."""
try:
query = (
delete(places)
.where(places.place_id == place_id, places.company_id == company_id, places.deleted == False) # noqa: E712
.where(places.place_id == place_id, places.owner_user_id == owner_user_id, places.deleted == False) # noqa: E712
)
return await DB_SESSION_MNG.add_with_rowcount(cdb, query)
except Exception as ex:
+4 -4
View File
@@ -22,7 +22,7 @@ class ISiteCRUD(ABC):
pass
@abstractmethod
async def list_company_sites(self, cdb: AsyncSession, company_id, skip, limit) -> Tuple[ErrorType, list, int]:
async def list_owner_sites(self, cdb: AsyncSession, owner_user_id, skip, limit) -> Tuple[ErrorType, list, int]:
pass
@abstractmethod
@@ -93,13 +93,13 @@ class SiteCRUD(ISiteCRUD):
LOG.e_no_callstack(ex)
return ErrorType.DB_RUN_FAILED, None
async def list_company_sites(self, cdb: AsyncSession, company_id, skip: int, limit: int) -> Tuple[ErrorType, list, int]:
"""회사의 사업장 + 사이트 + 마지막 빌드 시각. (ErrorType, [(place, site, built_at)], 총건수).
async def list_owner_sites(self, cdb: AsyncSession, owner_user_id, skip: int, limit: int) -> Tuple[ErrorType, list, int]:
"""사장님의 사업장 + 사이트 + 마지막 빌드 시각. (ErrorType, [(place, site, built_at)], 총건수).
따로 읽으면 줄마다 사이트를 다시 물어 N+1 이다. LEFT JOIN 이라 사이트가 없는 사업장
(위저드만 걸어온 것)도 내려간다 — 빠지면 만들다 만 것을 찾을 길이 없다."""
try:
where = and_(places.deleted == False, places.company_id == company_id) # noqa: E712
where = and_(places.deleted == False, places.owner_user_id == owner_user_id) # noqa: E712
cnt_err, cnt_rows = await DB_SESSION_MNG.execute(cdb, select(func.count()).select_from(places).where(where))
if cnt_err != ErrorType.SUCCESS:
+4 -86
View File
@@ -1,12 +1,12 @@
from abc import ABC, abstractmethod
from typing import Optional, Tuple
from typing import Tuple
from sqlalchemy import select, func, and_, or_, update
from sqlalchemy import select, func, update
from sqlalchemy.ext.asyncio import AsyncSession
from common.database.db_session_manager import DB_SESSION_MNG
from common.database.model.models import users, companies
from common.enums import ErrorType, UserRole
from common.database.model.models import users
from common.enums import ErrorType
from common.logger import LOG
from common.utils.gtime import GTime
@@ -39,22 +39,6 @@ class IUserCRUD(ABC):
async def update_last_accessed(self, cdb: AsyncSession, user_id) -> ErrorType:
pass
@abstractmethod
async def add_company(self, cdb: AsyncSession, company: companies) -> ErrorType:
pass
@abstractmethod
async def get_company(self, cdb: AsyncSession, company_id) -> Tuple[ErrorType, companies]:
pass
@abstractmethod
async def update_company_settings(self, cdb: AsyncSession, company_id, settings: dict) -> ErrorType:
pass
@abstractmethod
async def list_by_company(self, cdb: AsyncSession, company_id, search, skip, limit, hide_dev: bool = False) -> Tuple[ErrorType, list, int]:
pass
@abstractmethod
async def get_by_user_id(self, cdb: AsyncSession, user_id) -> Tuple[ErrorType, users]:
pass
@@ -145,72 +129,6 @@ class UserCRUD(IUserCRUD):
LOG.e_no_callstack(ex)
return ErrorType.DB_RUN_FAILED
async def add_company(self, cdb: AsyncSession, company: companies) -> ErrorType:
try:
return await DB_SESSION_MNG.insert(cdb, company)
except Exception as ex:
LOG.e_no_callstack(ex)
return ErrorType.DB_RUN_FAILED
async def get_company(self, cdb: AsyncSession, company_id) -> Tuple[ErrorType, companies]:
try:
query = select(companies).where(companies.company_id == company_id, companies.deleted == False).limit(1) # noqa: E712
err_type, row_list = await DB_SESSION_MNG.execute(cdb, query)
if err_type != ErrorType.SUCCESS:
return err_type, None
if len(row_list) != 1:
return ErrorType.DB_INVALID_KEY, None
return ErrorType.SUCCESS, row_list[0]
except Exception as ex:
LOG.e_no_callstack(ex)
return ErrorType.DB_RUN_FAILED, None
async def update_company_settings(self, cdb: AsyncSession, company_id, settings: dict) -> ErrorType:
try:
query = (
update(companies)
.where(companies.company_id == company_id, companies.deleted == False) # noqa: E712
.values(settings=settings, updated_at=GTime.UTC())
)
return await DB_SESSION_MNG.add(cdb, query)
except Exception as ex:
LOG.e_no_callstack(ex)
return ErrorType.DB_RUN_FAILED
async def list_by_company(
self, cdb: AsyncSession, company_id, search: Optional[str], skip: int, limit: int, hide_dev: bool = False
) -> Tuple[ErrorType, list, int]:
try:
conditions = [users.deleted == False, users.company_id == company_id] # noqa: E712
# 개발자(내부 운영) 계정은 고객사에 존재 자체가 보이면 안 된다 — 목록에서 빼고 총계에도 넣지 않는다.
if hide_dev:
conditions.append(users.role != UserRole.DEVELOPER.value)
if search:
conditions.append(
or_(
users.id.ilike(f"%{search}%"),
users.name.ilike(f"%{search}%"),
users.email.ilike(f"%{search}%"),
)
)
where = and_(*conditions)
cnt_err, cnt_rows = await DB_SESSION_MNG.execute(cdb, select(func.count()).select_from(users).where(where))
if cnt_err != ErrorType.SUCCESS:
return cnt_err, [], 0
total = int(cnt_rows[0] or 0) if cnt_rows else 0
list_err, rows = await DB_SESSION_MNG.execute(
cdb,
select(users).where(where).order_by(users.created_at.desc()).offset(skip).limit(limit),
)
if list_err != ErrorType.SUCCESS:
return list_err, [], 0
return ErrorType.SUCCESS, list(rows), total
except Exception as ex:
LOG.e_no_callstack(ex)
return ErrorType.DB_RUN_FAILED, [], 0
async def get_by_user_id(self, cdb: AsyncSession, user_id) -> Tuple[ErrorType, users]:
try:
query = select(users).where(users.user_id == user_id, users.deleted == False).limit(1) # noqa: E712
+2 -11
View File
@@ -1,7 +1,5 @@
from typing import Optional
from pydantic import Field
from common.enums import AuthProvider, UserRole
from common.models.gmodel import Res_WebPacketProtocol, WebPacketProtocol
@@ -17,7 +15,7 @@ class Req_Login(AuthProtocol):
class Req_Signup(AuthProtocol):
"""id/pw 가입. 가입 = 새 테넌트(회사) 1개 + 그 회사의 첫 계정 1개다.
"""id/pw 가입. 가입 = 계정 1개다.
★ 이메일을 필수로 받는 이유: 같은 이메일이 이미 구글로 가입돼 있는지 판단할 근거가 없으면
한 사람에게 계정이 둘 생긴다. 지금 이메일 인증 절차는 없다 — 소유 증명이 아니라
@@ -27,7 +25,6 @@ class Req_Signup(AuthProtocol):
password: str = ""
name: Optional[str] = None
email: str = ""
company_name: Optional[str] = None # 상호. 비우면 이름 → 아이디 순으로 채운다
class Req_GoogleLogin(AuthProtocol):
@@ -46,7 +43,7 @@ class Res_Login(Res_WebPacketProtocol):
class Req_UpdateMe(AuthProtocol):
# 본인 정보 수정. role·company·id 는 받지 않는다(자기 권한·소속 변경 불가).
# 본인 정보 수정. role·id 는 받지 않는다(자기 권한 변경 불가).
name: Optional[str] = None
email: Optional[str] = None
contact_number: Optional[str] = None
@@ -58,11 +55,6 @@ class Res_RefreshToken(Res_WebPacketProtocol):
token_type: str = "bearer"
class CompanyData(WebPacketProtocol):
company_id: str = ""
name: str = ""
class Res_Me(Res_WebPacketProtocol):
user_id: str = ""
id: str = ""
@@ -73,4 +65,3 @@ class Res_Me(Res_WebPacketProtocol):
# 이 계정이 무엇으로 로그인하는가. 구글 계정에는 바꿀 비밀번호가 없어서(update_me 가 막는다)
# 내 정보 화면이 붙을 때 이 값으로 갈라야 한다.
provider: AuthProvider = AuthProvider.LOCAL
company: Optional[CompanyData] = Field(default=None)
+35 -6
View File
@@ -1,10 +1,15 @@
import uuid
from fastapi import APIRouter, Depends, Query
from common.enums import LocalContentStatus
from common.models.gmodel import UserInfo
from router.v1.validator.dependencies import RequireOwner, RemoveNoneResponse
from services.local_content_service import LocalContentService
from .protocol import ReqPublishLocalContent, ReqSyncFestivals, ReqUpdateLocalContent, ResLocalContentList, ResSyncFestivals, ResWeather
from .protocol import (
ReqHidePlaceContent, ReqPublishLocalContent, ReqUpdateLocalContent,
ResLocalContentList, ResLocalGuide, ResPlaceContentList, ResSyncPlace, ResWeather,
)
router = APIRouter(prefix="/v1/admin/local-content", tags=["LocalContent"])
weather_router = APIRouter(prefix="/v1/local", tags=["LocalContent"])
@@ -20,6 +25,35 @@ async def get_weather(
return RemoveNoneResponse(await service.get_weather(region_code, latitude, longitude))
@weather_router.get("/guide", response_model=ResLocalGuide, summary="업장 주변 가이드(맛집·명소·축제·코스) — 에디터 캔버스용")
async def get_guide(
place_id: uuid.UUID = Query(),
service: LocalContentService = Depends(),
):
"""날씨와 같은 공개 조회다 — 운영자가 숨기지 않은 공공데이터만 나가므로 인증을 요구하지 않는다."""
return RemoveNoneResponse(await service.get_guide(place_id))
@router.get("/place/{place_id}", response_model=ResPlaceContentList, summary="업장 주변정보 목록 (숨김 포함)")
async def list_place_contents(place_id: uuid.UUID, service: LocalContentService = Depends(), _user=Depends(RequireOwner)):
return RemoveNoneResponse(await service.list_place_contents(place_id))
@router.post("/place/{place_id}/sync", response_model=ResSyncPlace, summary="업장 주변정보 재수집 (TourAPI 반경)")
async def sync_place(place_id: uuid.UUID, service: LocalContentService = Depends(), _user=Depends(RequireOwner)):
"""빌드가 매번 하는 것과 같은 수집을 운영자가 직접 누른다. 무인 갱신(스케줄러)은 아직 없다."""
return RemoveNoneResponse(await service.sync_place_by_id(place_id))
@router.post("/place-content/{place_content_id}/hide", response_model=ResPlaceContentList, summary="주변정보 숨김/해제")
async def hide_place_content(
place_content_id: uuid.UUID, req: ReqHidePlaceContent,
service: LocalContentService = Depends(), _user=Depends(RequireOwner),
):
"""숨긴 항목은 재수집이 되살리지 않는다. 다음 빌드부터 발행본에서 빠진다."""
return RemoveNoneResponse(await service.set_hidden(place_content_id, req.hidden))
@router.get("", response_model=ResLocalContentList)
async def list_contents(
status: LocalContentStatus | None = Query(None), region_code: str | None = Query(None),
@@ -28,11 +62,6 @@ async def list_contents(
return RemoveNoneResponse(await service.list(status.value if status else None, region_code))
@router.post("/sync-festivals", response_model=ResSyncFestivals)
async def sync_festivals(req: ReqSyncFestivals, service: LocalContentService = Depends(), _user=Depends(RequireOwner)):
return RemoveNoneResponse(await service.sync_festivals(req))
@router.post("/publish", response_model=ResLocalContentList)
async def publish(req: ReqPublishLocalContent, service: LocalContentService = Depends(), user=Depends(RequireOwner)):
return RemoveNoneResponse(await service.publish(req.content_ids, user.user_id))
+42 -7
View File
@@ -25,10 +25,29 @@ class LocalContentData(WebPacketProtocol):
display_end_at: datetime | None = None
class ReqSyncFestivals(WebPacketProtocol):
region_code: str = Field(min_length=1, max_length=10)
area_code: str | None = None
start_date: str | None = Field(default=None, pattern=r"^\d{8}$")
class PlaceContentData(WebPacketProtocol):
"""업장 반경 주변정보 1건(admin 목록용)."""
model_config = ConfigDict(from_attributes=True)
place_content_id: uuid.UUID
place_id: uuid.UUID
content_type: LocalContentType
external_id: str
title: str
body: dict[str, Any]
distance_m: int
has_image: bool
hidden: bool
display_end_at: datetime | None = None
collected_at: datetime | None = None
class ResPlaceContentList(Res_WebPacketProtocol):
contents: list[PlaceContentData] = []
class ReqHidePlaceContent(WebPacketProtocol):
hidden: bool
class ReqPublishLocalContent(WebPacketProtocol):
@@ -46,9 +65,25 @@ class ResLocalContentList(Res_WebPacketProtocol):
contents: list[LocalContentData] = []
class ResSyncFestivals(Res_WebPacketProtocol):
collected: int = 0
skipped: int = 0
class ResSyncPlace(Res_WebPacketProtocol):
"""업장 반경 동기화 결과 — 종류별로 **남긴** 건수(반경·기간 필터 뒤). changed 는 값이 바뀌었는지."""
festivals: int = 0
attractions: int = 0
restaurants: int = 0
courses: int = 0
changed: bool = False
class ResLocalGuide(Res_WebPacketProtocol):
"""에디터 캔버스가 그리는 지역 가이드. ★ 항목 모양은 발행 payload 의 LocalContents 와 **동일**하다
(services/site_payload._local 을 그대로 거친다) — 캔버스와 발행본이 다른 목록을 보이면 안 된다."""
attractions: list[dict[str, Any]] = []
restaurants: list[dict[str, Any]] = []
festivals: list[dict[str, Any]] = []
courses: list[dict[str, Any]] = []
synced_at: str | None = None
class WeatherData(WebPacketProtocol):
+1 -1
View File
@@ -31,7 +31,7 @@ from .protocol import (
Res_UnitList,
)
# 사업장 라우터. 모든 조회·변경은 토큰의 회사(company_id)로 스코프된다.
# 사업장 라우터. 모든 조회·변경은 토큰의 사장님(places.owner_user_id)으로 스코프된다.
router = APIRouter(prefix="/v1/place", tags=["Place"], responses={404: {"description": "Not found"}})
+6 -3
View File
@@ -18,7 +18,8 @@ class Req_CreatePlace(PlaceProtocol):
# 상호명 하나로 시작한다. 나머지는 카카오 로컬 검증이 채운다.
name: str = ""
category: PlaceCategory = PlaceCategory.LODGING
owner_user_id: Optional[uuid.UUID] = None
# ★ 주인은 받지 않는다 — 토큰이 정한다(place_service.create_place). 여기로 받으면
# 남의 계정을 적어 만들자마자 남의 목록에 넣을 수 있다.
class Req_VerifyPlace(PlaceProtocol):
@@ -39,6 +40,8 @@ class Req_VerifyPlace(PlaceProtocol):
latitude: Optional[Decimal] = None
longitude: Optional[Decimal] = None
region_code: Optional[str] = None
# 외부 장소 DB 의 분류 문자열(후보의 category_name). 주변 맛집에서 같은 업태(경쟁 업소)를 빼는 기준으로 박제한다.
category_name: Optional[str] = None
class Req_VerifyPlaceByUrl(PlaceProtocol):
@@ -58,8 +61,8 @@ class Req_VerifyPlaceByUrl(PlaceProtocol):
class Req_UpdatePlace(PlaceProtocol):
# ★ 주인은 못 바꾼다(위 Req_CreatePlace 주석). 소유권 이전은 아직 기능이 아니다.
name: Optional[str] = None
owner_user_id: Optional[uuid.UUID] = None
status: Optional[PlaceStatus] = None
@@ -212,7 +215,7 @@ class Res_VerifyCandidates(Res_WebPacketProtocol):
class PlaceSearchItem(WebPacketProtocol):
"""공개 검색 결과 1건.
★ 외부 장소 DB 가 공개적으로 주는 값만 담는다. 우리 DB 값(place_id·company_id·소유자)은
★ 외부 장소 DB 가 공개적으로 주는 값만 담는다. 우리 DB 값(place_id·소유자)은
하나도 나가지 않는다 — 로그인 없이 열려 있는 응답이라 여기에 우리 것을 실으면 그대로 샌다.
★ 좌표·전화번호도 뺐다. 랜딩이 하는 일은 '어느 가게인지 고르게 하는 것'뿐이고,
확정과 수집은 로그인 뒤 기존 경로(POST /place → verify)가 그대로 한다."""
+3 -1
View File
@@ -85,6 +85,8 @@ class MySiteData(WebPacketProtocol):
domain: Optional[str] = None
template_id: Optional[str] = None
published_at: Optional[datetime] = None
# 목록 카드의 그림. 발행에 성공해야 채워지고, 발행마다 `?v=` 가 바뀐다(site_thumbnail.public_url).
thumbnail_url: Optional[str] = None
# 단건과 같은 규칙 — 노출값이 마지막 빌드보다 나중에 바뀌었으면 재발행 대상이다.
needs_rebuild: bool = False
@@ -235,7 +237,7 @@ class ShowcaseItem(WebPacketProtocol):
"""랜딩 쇼케이스 카드 한 장. **로그인 없이 나가는 값이다.**
★ 여기 있는 것은 전부 이미 발행된 페이지에 적혀 있는 것뿐이다.
place_id·company_id·전화번호·상세 주소는 절대 싣지 않는다 — 사이트 한 곳을 여는 것과
place_id·소유자·전화번호·상세 주소는 절대 싣지 않는다 — 사이트 한 곳을 여는 것과
발행 업소 명단을 통째로 긁는 것은 다른 일이다. 지역도 시·군·구까지만 준다."""
name: str
+4 -6
View File
@@ -53,13 +53,11 @@ async def main():
engine = create_async_engine(dsn)
from router.v1.validator.dependencies import GetHashedPW
cid, uid, login = uuid.uuid4(), uuid.uuid4(), f"demo{uuid.uuid4().hex[:6]}"
uid, login = uuid.uuid4(), f"demo{uuid.uuid4().hex[:6]}"
async with engine.begin() as c:
await c.execute(text("INSERT INTO company.companies (company_id,name,status) VALUES (:c,:n,1)"),
{"c": cid, "n": "데모대행사"})
await c.execute(text("INSERT INTO company.users (user_id,company_id,id,password,name,status,role,last_accessed_at) "
"VALUES (:u,:c,:i,:p,:n,:s,:r,now())"),
{"u": uid, "c": cid, "i": login, "p": await GetHashedPW("pw1234"),
await c.execute(text("INSERT INTO company.users (user_id,id,password,name,status,role,last_accessed_at) "
"VALUES (:u,:i,:p,:n,:s,:r,now())"),
{"u": uid, "i": login, "p": await GetHashedPW("pw1234"),
"n": "데모", "s": UserStatus.ACTIVE.value, "r": UserRole.OWNER.value})
from router.router import app
+4 -5
View File
@@ -41,12 +41,11 @@ async def main():
engine = create_async_engine(dsn)
from router.v1.validator.dependencies import GetHashedPW
cid, uid, login = uuid.uuid4(), uuid.uuid4(), f"demo{uuid.uuid4().hex[:6]}"
uid, login = uuid.uuid4(), f"demo{uuid.uuid4().hex[:6]}"
async with engine.begin() as c:
await c.execute(text("INSERT INTO company.companies (company_id,name,status) VALUES (:c,:n,1)"), {"c": cid, "n": "데모대행사"})
await c.execute(text("INSERT INTO company.users (user_id,company_id,id,password,name,status,role,last_accessed_at) "
"VALUES (:u,:c,:i,:p,:n,:s,:r,now())"),
{"u": uid, "c": cid, "i": login, "p": await GetHashedPW("pw1234"),
await c.execute(text("INSERT INTO company.users (user_id,id,password,name,status,role,last_accessed_at) "
"VALUES (:u,:i,:p,:n,:s,:r,now())"),
{"u": uid, "i": login, "p": await GetHashedPW("pw1234"),
"n": "데모", "s": UserStatus.ACTIVE.value, "r": UserRole.OWNER.value})
await engine.dispose()
+11 -37
View File
@@ -4,13 +4,12 @@ import uuid
from fastapi import Depends
from common.database.db_session_manager import DB_SESSION_MNG
from common.database.model.models import companies, users
from common.enums import AuthProvider, CompanyStatus, DBWRType, ErrorType, UserRole, UserStatus
from common.database.model.models import users
from common.enums import AuthProvider, DBWRType, ErrorType, UserRole, UserStatus
from common.logger import LOG
from common.models.gmodel import UserInfo
from crud.user_crud import IUserCRUD, UserCRUD
from router.v1.auth.protocol import (
CompanyData,
Req_GoogleLogin,
Req_Signup,
Req_UpdateMe,
@@ -71,11 +70,11 @@ class AuthService:
@staticmethod
def _user_info(user: users) -> UserInfo:
# uuid → str (JWT json 직렬화 위해). 기능 라우터는 company_id 로 스코프한다.
# uuid → str (JWT json 직렬화 위해). 기능 라우터는 user_id 로 스코프한다
# — 사업장이 places.owner_user_id 로 이 값에 매여 있다.
return UserInfo(
user_id=str(user.user_id),
id=user.id,
company_id=str(user.company_id),
role=user.role,
)
@@ -140,26 +139,17 @@ class AuthService:
password_hash: str | None,
name: str | None,
email: str | None,
company_name: str,
provider: AuthProvider,
provider_uid: str | None,
) -> tuple[ErrorType, users]:
"""회사 1개 + 그 회사의 첫 계정 1개를 한 트랜잭션으로 만든다.
"""계정 1개를 만든다.
★ 가입은 곧 새 테넌트다. users.company_id 가 NOT NULL 이고 모든 도메인(사업장·사이트)이
company_id 로 스코프되므로, 회사 없는 계정은 아무것도 만들지 못한다.
★ uuid 를 여기서 미리 만든다. 모델 default 는 flush 시점에 적용돼서, 그 전에
company.company_id 를 읽으면 None 이다 — 그대로 넣으면 NOT NULL 위반이다."""
company_uuid = uuid.uuid4()
company = companies(
company_id=company_uuid,
name=_fit(company_name, 100),
email=_fit(email, 255),
status=CompanyStatus.ACTIVE.value,
)
★ 예전엔 가입 한 번이 **회사(테넌트) 하나**를 같이 만들었고 모든 도메인이 그 회사로
스코프됐다. 쓰는 사람은 사장님 혼자인데 자기 회사에 소속된 직원이 되는 구조라
걷어냈다(2026-09-08) — 이제 사업장이 `places.owner_user_id` 로 이 계정에 직접 매인다.
★ uuid 를 여기서 미리 만든다. 모델 default 는 flush 시점에 적용돼서 그 전에 읽으면 None 이다."""
user = users(
user_id=uuid.uuid4(),
company_id=company_uuid,
id=login_id,
password=password_hash,
name=_fit(name, 50),
@@ -171,10 +161,7 @@ class AuthService:
)
err_type = await DB_SESSION_MNG.execute_lambda_run(
[users.DBType()],
[
lambda s: self.user_crud.add_company(s, company),
lambda s: self.user_crud.add_user(s, user),
],
[lambda s: self.user_crud.add_user(s, user)],
)
if err_type != ErrorType.SUCCESS:
return err_type, None
@@ -226,7 +213,6 @@ class AuthService:
password_hash=await GetHashedPW(req.password),
name=name,
email=email,
company_name=(req.company_name or "").strip() or name or login_id,
provider=AuthProvider.LOCAL,
provider_uid=None,
)
@@ -268,13 +254,12 @@ class AuthService:
res.result.SetResult(ErrorType.ACCOUNT_PROVIDER_CONFLICT)
return res
# 3) 첫 방문 — 계정과 회사를 만든다.
# 3) 첫 방문 — 계정을 만든다.
err_type, user = await self._create_account(
login_id=_google_login_id(account.sub),
password_hash=None,
name=account.name or None,
email=account.email or None,
company_name=account.name or account.email or _google_login_id(account.sub),
provider=AuthProvider.GOOGLE,
provider_uid=account.sub,
)
@@ -299,16 +284,6 @@ class AuthService:
return res
user: users
# 2) 소속사 조회 (없어도 치명적 아님)
company = None
c_err, company_row = await DB_SESSION_MNG.execute_lambda(
users.DBType(),
DBWRType.DB_READ.value,
lambda s: self.user_crud.get_company(s, user.company_id),
)
if c_err == ErrorType.SUCCESS and company_row is not None:
company = CompanyData(company_id=str(company_row.company_id), name=company_row.name)
res.user_id = str(user.user_id)
res.id = user.id
res.name = user.name
@@ -316,7 +291,6 @@ class AuthService:
res.contact_number = user.contact_number
res.role = UserRole(user.role)
res.provider = AuthProvider(user.provider)
res.company = company
return res
async def update_me(self, user_info: UserInfo, req: Req_UpdateMe) -> Res_Me:
+17 -5
View File
@@ -30,6 +30,7 @@ from common.utils.gtime import GTime
from crud.site_crud import SiteCRUD
from crud.place_crud import PlaceCRUD
from services import azure_static, indexnow, publish_gate, render_report, site_payload, site_thumbnail
from services.local_content_service import LocalContentService
from services.site_payload import emit_payload
from services.snapshot import build_snapshot
@@ -97,23 +98,34 @@ async def _log(site_id, version_id, action: PublishAction, result: PublishResult
async def run_build(job: dict) -> dict:
"""BUILD 잡 핸들러. payload: {place_id, company_id, publish?, requested_by?}
"""BUILD 잡 핸들러. payload: {place_id, owner_user_id, publish?, requested_by?}
publish=True 면 게이트를 통과했을 때 바로 발행까지 한다."""
payload = job["payload"]
place_id = payload["place_id"]
company_id = payload["company_id"]
owner_user_id = payload["owner_user_id"]
want_publish = bool(payload.get("publish"))
err, place = await DB_SESSION_MNG.execute_lambda(
places.DBType(),
DBWRType.DB_READ.value,
lambda s: _place_crud.get_place(s, uuid.UUID(company_id), uuid.UUID(place_id)),
lambda s: _place_crud.get_place(s, uuid.UUID(owner_user_id), uuid.UUID(place_id)),
)
if err != ErrorType.SUCCESS or place is None:
raise BuildAborted(f"사업장을 찾을 수 없다: {place_id}")
site = await ensure_site(place_id)
# ★ 주변 정보(맛집·관광지·축제·코스)는 빌드 시점에 업장 좌표로 새로 받는다 — 발행본은 정적이라
# 이때 받은 값이 실린다. 실패해도 빌드는 계속한다: 곁들이 정보가 사장님 사이트 발행을 막을 이유가 없고,
# place_contents 는 직전 값을 그대로 갖고 있다.
try:
synced = await LocalContentService().sync_place(place)
if not synced.result.success:
LOG.w(f"[build] place={place_id} 주변정보 갱신 건너뜀(직전 값 사용): {synced.msg}")
except Exception as ex: # noqa: BLE001 — 곁들이 정보 실패가 빌드를 죽이면 안 된다
LOG.w(f"[build] place={place_id} 주변정보 갱신 실패(직전 값 사용): {type(ex).__name__}: {ex}")
snapshot = await build_snapshot(place)
v_err, version_no = await DB_SESSION_MNG.execute_lambda(
@@ -246,7 +258,7 @@ async def run_build(job: dict) -> dict:
result["azure"] = azure_result
# ★ 페이지가 실제로 올라간 뒤에 썸네일을 남긴다 — 없는 페이지의 그림을 쇼케이스에 걸지 않는다.
# 실패해도 발행은 성공이다(스크린샷이 아니라 대표 사진이라, 없으면 글자 카드로 떨어진다).
thumbnail_url = await site_thumbnail.store(slug, snapshot)
thumbnail_url = await site_thumbnail.store(slug, snapshot, version_no)
if thumbnail_url:
result["thumbnail_url"] = thumbnail_url
# ★ 정적 파일이 올라간 **뒤에** 통보한다. 먼저 알리면 크롤러가 옛 파일을 가져간다.
@@ -293,7 +305,7 @@ async def run_build(job: dict) -> dict:
await DB_SESSION_MNG.execute_lambda_claim(
places.DBType(),
lambda s: _place_crud.update_place(
s, uuid.UUID(company_id), uuid.UUID(place_id), {"status": PlaceStatus.PUBLISHED.value}
s, uuid.UUID(owner_user_id), uuid.UUID(place_id), {"status": PlaceStatus.PUBLISHED.value}
),
)
await _log(site.site_id, version.site_version_id, PublishAction.PUBLISH, PublishResult.SUCCESS, None,
+15 -12
View File
@@ -431,12 +431,12 @@ async def run_collect(job: dict) -> dict:
"""COLLECT 잡 핸들러. 반환값이 jobs.result 에 저장돼 폴링·감사에 쓰인다."""
payload = job["payload"]
place_id = payload["place_id"]
company_id = payload["company_id"]
owner_user_id = payload["owner_user_id"]
err, place = await DB_SESSION_MNG.execute_lambda(
places.DBType(),
DBWRType.DB_READ.value,
lambda s: _place_crud.get_place(s, uuid.UUID(company_id), uuid.UUID(place_id)),
lambda s: _place_crud.get_place(s, uuid.UUID(owner_user_id), uuid.UUID(place_id)),
)
if err != ErrorType.SUCCESS or place is None:
raise CollectAborted(f"사업장을 찾을 수 없다: {place_id}")
@@ -464,7 +464,7 @@ async def run_collect(job: dict) -> dict:
if not targets:
result["note"] = "크롤링 대상이 없다(어댑터가 처리할 수 있는 확정 URL 0건)"
await _finish(place_id, company_id, PlaceStatus.REVIEW)
await _finish(place_id, owner_user_id, PlaceStatus.REVIEW)
return result
# ★ 이미 충분하면 크롤링 자체를 건너뛴다(force 가 아닐 때).
@@ -472,16 +472,19 @@ async def run_collect(job: dict) -> dict:
if before["enough"] and not payload.get("force"):
result["coverage"] = before
result["note"] = "이미 필수 항목이 다 차 있다 — 크롤링 생략(force=true 로 강제 가능)"
await _finish(place_id, company_id, PlaceStatus.REVIEW)
await _finish(place_id, owner_user_id, PlaceStatus.REVIEW)
LOG.i(f"[collect] 충분함 place={place_id} {before['covered']}/{before['total']} — 크롤링 생략")
return result
from common.models.gmodel import UserInfo
actor = UserInfo(
user_id=payload.get("requested_by") or str(place.verified_by or uuid.uuid4()),
# ★ 잡이 쓰는 신원. user_id 는 **사업장 주인**이어야 한다 — FactService 가 이 값으로
# 사업장을 스코프하고(fact_service._load_place) verified_by 에도 그대로 박는다.
# 회사를 걷어내기 전에는 스코프가 company_id 였고 여기엔 요청자·검증자·랜덤 uuid 가
# 순서대로 들어갔다. 그 랜덤 uuid 가 이제는 "남의 사업장" 이 되어 조회가 0건이 된다.
user_id=owner_user_id,
id="collector",
company_id=company_id,
role=1,
)
@@ -538,24 +541,24 @@ async def run_collect(job: dict) -> dict:
# 사진이 들어왔으면 분석을 이어서 건다 — 수집과 분석은 각각 몇 분이라 한 잡에 묶지 않는다.
# (묶으면 분석에서 죽었을 때 수집까지 다시 하게 되고, 유료 API 를 두 번 태운다.)
if result["media"]["stored"] > 0:
result["vision_job_id"] = await _enqueue_vision(place_id, company_id)
result["vision_job_id"] = await _enqueue_vision(place_id, owner_user_id)
await _finish(place_id, company_id, PlaceStatus.REVIEW)
await _finish(place_id, owner_user_id, PlaceStatus.REVIEW)
LOG.i(f"[collect] 완료 place={place_id} fact {result['facts']['stored']}건 · 사진 {result['media']['stored']}장")
return result
async def _finish(place_id: str, company_id: str, status: PlaceStatus):
async def _finish(place_id: str, owner_user_id: str, status: PlaceStatus):
"""수집이 끝나면 사업장을 검수 대기로 돌린다 — 수집값은 전부 후보라 사람이 봐야 한다."""
await DB_SESSION_MNG.execute_lambda_claim(
places.DBType(),
lambda s: _place_crud.update_place(
s, uuid.UUID(company_id), uuid.UUID(place_id), {"status": status.value}
s, uuid.UUID(owner_user_id), uuid.UUID(place_id), {"status": status.value}
),
)
async def _enqueue_vision(place_id: str, company_id: str) -> str | None:
async def _enqueue_vision(place_id: str, owner_user_id: str) -> str | None:
"""사진 분석 잡을 적재한다. 키가 없거나 중복이면 조용히 건너뛴다(수집 자체는 성공이다)."""
from common.enums import JobType
from crud.job_crud import JobQueue
@@ -567,7 +570,7 @@ async def _enqueue_vision(place_id: str, company_id: str) -> str | None:
return None
job_id, _created = await enqueue_job(
JobQueue(), JobType.VISION,
{"place_id": place_id, "company_id": company_id},
{"place_id": place_id, "owner_user_id": owner_user_id},
dedupe_key=f"vision:{place_id}",
)
return job_id
@@ -284,9 +284,11 @@ class TourApiAdapter:
def _lodging_facts(self, intro: dict) -> list[CollectedFact]:
"""숙박 detailIntro2 → 사업장 단위 fact.
★ 스키마에 없는 값은 만들지 않는다. roomcount·scalelodging·foodplace 는
lodging 스키마에 자리가 없어서 **일부러 버린다** — 억지로 다른 key 에 넣으면
'식음료장 있음' 이 '조식 제공' 으로 둔갑한다.
★ 스키마에 없는 값은 만들지 않는다. foodplace('식음료장 있음')는 lodging 스키마에
자리가 없어서 **일부러 버린다** — 억지로 breakfast 에 넣으면 '조식 제공' 으로 둔갑한다.
★ roomcount·scalelodging·accomcountlodging·subfacility 는 2026-09-07 에 자리를 만들었다
(total_rooms·building_scale·accommodation_capacity·facilities). 실측(오블로모프 3103191)에서
TourAPI 가 준 값의 절반이 자리가 없어 버려지고 있었다.
"""
return self._collect([
("check_in_time", self._plain(intro.get("checkintime"))[:40]),
@@ -296,6 +298,11 @@ class TourApiAdapter:
("parking", self._bool_str(self._head_bool(intro.get("parkinglodging")))),
("pickup_service", self._bool_str(self._head_bool(intro.get("pickup")))),
("bbq_available", self._bool_str(self._yn(intro.get("barbecue")))),
("facilities", self._plain(intro.get("subfacility"))[:500]),
("total_rooms", self._number(intro.get("roomcount"))),
("accommodation_capacity", self._number(intro.get("accomcountlodging"))),
# "약 23평" · "대지 면적 11,570㎡" 처럼 단위가 제각각이라 숫자로 뽑지 않고 원문을 싣는다.
("building_scale", self._plain(intro.get("scalelodging"))[:200]),
])
def _restaurant_facts(self, intro: dict) -> list[CollectedFact]:
@@ -362,6 +369,16 @@ class TourApiAdapter:
("peak_price", self._number(row.get("roompeakseasonminfee1")), name),
("has_kitchen", self._bool_str(self._yn(row.get("roomcook"))), name),
("has_aircon", self._bool_str(self._yn(row.get("roomaircondition"))), name),
# 객실 편의시설 Y/N. ★ 빈 값은 '없음'이 아니라 '모름'이다 — _yn 이 None 을 주면 fact 를 만들지 않는다.
("has_bathroom", self._bool_str(self._yn(row.get("roombathfacility"))), name),
("has_tv", self._bool_str(self._yn(row.get("roomtv"))), name),
("has_internet", self._bool_str(self._yn(row.get("roominternet"))), name),
("has_refrigerator", self._bool_str(self._yn(row.get("roomrefrigerator"))), name),
("has_hairdryer", self._bool_str(self._yn(row.get("roomhairdryer"))), name),
("has_toiletries", self._bool_str(self._yn(row.get("roomtoiletries"))), name),
("has_table", self._bool_str(self._yn(row.get("roomtable"))), name),
("has_sofa", self._bool_str(self._yn(row.get("roomsofa"))), name),
("has_home_theater", self._bool_str(self._yn(row.get("roomhometheater"))), name),
])
return facts
+8 -5
View File
@@ -40,10 +40,10 @@ class CopyAborted(RuntimeError):
async def run_copy(job: dict) -> dict:
"""COPY 잡 핸들러. payload: {place_id, company_id, requested_by?}"""
"""COPY 잡 핸들러. payload: {place_id, owner_user_id, requested_by?}"""
payload = job["payload"]
place_id = payload["place_id"]
company_id = payload["company_id"]
owner_user_id = payload["owner_user_id"]
if not gemini_text.is_configured():
raise CopyAborted("GEMINI_API_KEY 미설정 — 소개문·FAQ 를 생성할 수 없다")
@@ -51,7 +51,7 @@ async def run_copy(job: dict) -> dict:
err, place = await DB_SESSION_MNG.execute_lambda(
places.DBType(),
DBWRType.DB_READ.value,
lambda s: _place_crud.get_place(s, uuid.UUID(company_id), uuid.UUID(place_id)),
lambda s: _place_crud.get_place(s, uuid.UUID(owner_user_id), uuid.UUID(place_id)),
)
if err != ErrorType.SUCCESS or place is None:
raise CopyAborted(f"사업장을 찾을 수 없다: {place_id}")
@@ -165,9 +165,12 @@ async def run_copy(job: dict) -> dict:
}
actor = UserInfo(
user_id=payload.get("requested_by") or str(place.verified_by or uuid.uuid4()),
# ★ 잡이 쓰는 신원. user_id 는 **사업장 주인**이어야 한다 — FactService 가 이 값으로
# 사업장을 스코프하고(fact_service._load_place) verified_by 에도 그대로 박는다.
# 회사를 걷어내기 전에는 스코프가 company_id 였고 여기엔 요청자·검증자·랜덤 uuid 가
# 순서대로 들어갔다. 그 랜덤 uuid 가 이제는 "남의 사업장" 이 되어 조회가 0건이 된다.
user_id=owner_user_id,
id="generator",
company_id=company_id,
role=1,
)
service = FactService(_fact_crud, _place_crud)
+24 -1
View File
@@ -43,9 +43,10 @@ _BASE_URL = "https://dapi.kakao.com"
_KEYWORD_URL = f"{_BASE_URL}/v2/local/search/keyword.json"
_COORD2REGION_URL = f"{_BASE_URL}/v2/local/geo/coord2regioncode.json"
_CATEGORY_URL = f"{_BASE_URL}/v2/local/search/category.json"
_ADDRESS_URL = f"{_BASE_URL}/v2/local/search/address.json"
# 초과 단가(원). 로그에 함께 남겨 어떤 호출이 비싼지 바로 보이게 한다.
_UNIT_COST_KRW = {"keyword": 2.0, "category": 2.0, "coord2region": 0.5}
_UNIT_COST_KRW = {"keyword": 2.0, "category": 2.0, "coord2region": 0.5, "address": 0.5}
# 프로세스 누적 호출 수 — 생성 1건당 검색 횟수를 세는 근거.
_CALL_COUNTS: Counter = Counter()
@@ -362,6 +363,28 @@ class KakaoLocalClient:
picked = next((d for d in docs if d.get("region_type") == "H"), docs[0])
return RegionCode.from_document(picked)
# ---- 2-1) 주소 → 좌표 ----
async def geocode_address(self, address: str) -> Optional[tuple[float, float]]:
"""도로명·지번 주소 → (위도, 경도). 결과가 없으면 None — 좌표를 지어내지 않는다.
★ 쓰는 곳: 좌표 없이 검증된 사업장의 주변 정보 수집(local_content_service.sync_place).
동일 업소 검증(카카오 후보·네이버 상세)은 좌표를 같이 주므로 보통은 비어 있지 않다 —
비는 건 옛 데이터나 좌표 없는 후보를 고른 경우다. 그때 주소로 한 번 더 찾는다.
싸다(초과 시 건당 0.5원). 결과는 places 에 박제하므로 사업장당 1회다.
"""
query = (address or "").strip()
if not query:
return None
data = await self._get(_ADDRESS_URL, {"query": query, "size": "1"}, "address")
docs = data.get("documents") or []
if not docs:
LOG.i(f"[kakao] 주소 → 좌표 결과 없음: {query[:60]}")
return None
lat, lon = _to_float(docs[0].get("y")), _to_float(docs[0].get("x")) # ★ y=위도 · x=경도
if lat is None or lon is None:
return None
return lat, lon
# ---- 3) 주변 맛집·시설 ----
async def search_category(
self,
+263 -49
View File
@@ -1,17 +1,58 @@
"""공공데이터포털 전국문화축제표준데이터 클라이언트.
"""한국관광공사 TourAPI(KorService2) — **업장 반경** 주변정보 수집 클라이언트.
설정 키 이름은 기존 배포 계약을 유지하기 위해 TOUR_API_KEY를 그대로 사용한다.
collector/tour_api_adapter.py 가 '사업장 1곳'의 fact 를 캐는 쪽이라면, 여기는
업장 좌표 반경 안의 곁들이 정보(맛집·관광지·축제·여행코스)를 긁는 쪽이다.
결과는 place_contents(업장 단위 캐시)에 들어가 발행본·캔버스의 지역 정보 섹션이 된다.
★ 왜 행정구역이 아니라 좌표인가 (2026-09-04, specs/2026-09-04-tourapi-radius-spike.md)
처음엔 법정동 코드로 areaBasedList2 를 불렀다. 그건 '그 시군구에 있는 것'이지
'이 업장에서 가까운 것'이 아니다 — 양양군 업장 옆 5km 속초 관광지가 빠지고,
같은 시군구 반대편 30km 맛집이 붙는다. locationBasedList2 는 좌표+반경으로 묻고
거리(dist)까지 준다. 실측(군산 절골길 18): 10km 안 133건, 5km 안 100건.
★ 호출 수 — 업장당 종류별 1회 (맛집·관광지·축제)
2026-09-08 부터 종류마다 **따로** 부른다(맛집 5km · 관광지 10km · 축제는 시도 전체, 반경 없음) —
한 걸음에 갈 맛집과 차 타고 갈 축제를 같은 반경으로 재는 게 맞지 않았다.
여행코스(25)는 실측 결과 반경을 넓혀도 데이터가 거의 없어(전북 전체 3건) 뺐다.
★ 축제는 locationBasedList2 가 아니라 searchFestival2 를 쓴다 (2026-09-08 교체)
locationBasedList2(contentTypeId=15) 의 위치 색인은 못 믿는다 — 실측(군산 절골길 18):
반경 20km 를 아무리 넓혀도 2023년에 끝난 서천 전시 1건만 나오고, 코앞 500m 의
진행 예정 축제(군산시간여행축제 등)는 끝내 안 잡혔다. searchFestival2 는 법정동(시도)
단위로 묻지만 정확하고 기간까지 함께 준다 — 그래서 시도 전체를 받아 우리가 거리로 거른다.
eventStartDate 는 파라미터로 준 날짜 **이후 시작하는** 행사만 거른다(이전에 시작해 아직
진행 중인 행사는 잡히지 않는다 — 실측). 그래서 항상 **그 해 1월 1일**로 고정해 부르고,
이미 끝난 행사(eventenddate < 오늘)만 우리가 한 번 더 거른다.
★ 이미지 저작권 — 수집 단계에서 끝낸다 (collector/tour_api_adapter.py 와 같은 규칙)
firstimage 는 공공누리 Type1(출처표시)·Type3(출처표시+변경금지)만 남긴다.
발행본은 상업적 이용이라 Type2·Type4 는 싣지 못한다. 유형을 모르면 버린다.
"""
import hashlib
from datetime import date
from urllib.parse import unquote
from typing import Optional
from urllib.parse import unquote, urlencode
import httpx
from common.enums import LocalContentType
from common.utils.geo import haversine_m
from config.server_configs import external_api_config
_URL = "https://api.data.go.kr/openapi/tn_pubr_public_cltur_fstvl_api"
BASE_URL = "https://apis.data.go.kr/B551011/KorService2"
REQUEST_TIMEOUT = 25
PAGE_SIZE = 100
# 반경 10km 도심은 300건을 넘지 않는다(실측 133건). 그 이상은 어차피 종류별 20건 상한에 안 든다.
MAX_PAGES = 4
# TourAPI contentTypeId ↔ 우리 종류 코드(locationBasedList2 용). 축제(15)는 여기 없다 —
# searchFestival2 로 따로 받는다(위 모듈 docstring 참고). 여행코스(25)도 뺐다(데이터 부족).
CONTENT_TYPE_MAP = {
"39": LocalContentType.RESTAURANT.value,
"12": LocalContentType.ATTRACTION.value,
}
# 상업적 이용이 허용된 공공누리 유형(tour_api_adapter 와 동일 규칙·동일 이유).
_COMMERCIAL_OK_LICENSES = frozenset({"type1", "type3"})
class TourApiNotConfigured(RuntimeError):
@@ -22,52 +63,225 @@ class TourApiRequestFailed(RuntimeError):
pass
def _normalize(item: dict) -> dict:
"""표준데이터 필드명을 화면/저장소의 공통 축제 필드로 변환한다."""
identity = "|".join(str(item.get(key) or "") for key in ("fstvlNm", "fstvlStartDate", "fstvlEndDate", "insttCode"))
return {
"contentid": hashlib.sha256(identity.encode("utf-8")).hexdigest()[:32],
"title": item.get("fstvlNm"),
"eventstartdate": str(item.get("fstvlStartDate") or "").replace("-", ""),
"eventenddate": str(item.get("fstvlEndDate") or "").replace("-", ""),
"addr1": item.get("rdnmadr") or item.get("lnmadr") or item.get("eventPlace"),
"mapx": item.get("longitude"),
"mapy": item.get("latitude"),
"tel": item.get("phoneNumber"),
"homepage": item.get("homepageUrl"),
"organizer": item.get("suprtInsttNm"),
"overview": item.get("relateInfo") or item.get("opar"),
"raw": item,
}
# ── HTTP ───────────────────────────────────────────────────────────────
async def search_festivals(*, start_date: date, area_code: str | None = None, rows: int = 100) -> list[dict]:
def _service_key() -> str:
key = (external_api_config.tour_api_key or "").strip()
if not key:
raise TourApiNotConfigured("TOUR_API_KEY is not configured")
params = {
# 포털의 "Encoding" 키를 넣어도 httpx가 이중 인코딩하지 않도록 원문으로 되돌린다.
"serviceKey": unquote(key),
"type": "json",
"numOfRows": max(1, min(rows, 1000)),
"pageNo": 1,
}
return key
async def _call(client: httpx.AsyncClient, op: str, **params) -> tuple[list[dict], int]:
"""오퍼레이션 1회 → (항목, totalCount). 결과 없음은 빈 목록 — 없는 것과 실패를 구분한다.
★ 포털의 'Encoding' 키를 그대로 넣어도 이중 인코딩되지 않도록 원문으로 되돌린다
(collector/tour_api_adapter._call 과 같은 처리).
"""
query = urlencode(
{"serviceKey": unquote(_service_key()), "MobileOS": "ETC", "MobileApp": "o2o-web4ai",
"_type": "json", "numOfRows": str(PAGE_SIZE), "pageNo": "1", **params},
safe="",
)
res = await client.get(f"{BASE_URL}/{op}?{query}")
if res.status_code != 200:
raise TourApiRequestFailed(f"{op} HTTP {res.status_code}")
try:
async with httpx.AsyncClient(timeout=httpx.Timeout(20.0, connect=5.0)) as client:
response = await client.get(_URL, params=params)
response.raise_for_status()
payload = response.json()
response_data = payload.get("response", payload)
header = response_data.get("header", {})
if header.get("resultCode") not in (None, "00", "0000"):
raise TourApiRequestFailed(header.get("resultMsg") or "TourAPI returned an error")
items_node = response_data.get("body", {}).get("items", [])
items = items_node.get("item", []) if isinstance(items_node, dict) else items_node
if isinstance(items, dict):
items = [items]
normalized = [_normalize(item) for item in (items or [])]
# API가 날짜 필터를 제공하지 않으므로 종료된 축제는 애플리케이션에서 제외한다.
cutoff = start_date.strftime("%Y%m%d")
return [item for item in normalized if not item["eventenddate"] or item["eventenddate"] >= cutoff]
except (httpx.HTTPError, ValueError, TypeError) as ex:
raise TourApiRequestFailed(str(ex)) from ex
payload = res.json()
except ValueError:
# 인증 실패·쿼터 초과는 XML 로 온다. 본문 앞부분을 그대로 올려 원인을 감추지 않는다.
raise TourApiRequestFailed(f"{op} 응답이 JSON 이 아니다: {res.text[:160]}")
# 게이트웨이 오류(미등록 키 등)는 200 + JSON 이지만 response 가 없다. 그것도 원인을 드러낸다.
if "response" not in payload:
raise TourApiRequestFailed(f"{op} 게이트웨이 오류: {str(payload)[:160]}")
header = payload["response"].get("header", {})
code = str(header.get("resultCode") or "")
if code not in ("0000", "00"):
raise TourApiRequestFailed(f"{op} 실패 [{code}] {header.get('resultMsg')}")
body = payload["response"].get("body", {}) or {}
items = (body.get("items") or {}).get("item") if isinstance(body.get("items"), dict) else None
if isinstance(items, dict):
items = [items]
total = int(body.get("totalCount") or 0)
return items or [], total
# ── 정규화 ──────────────────────────────────────────────────────────────
def _int(value) -> Optional[int]:
try:
return int(float(str(value).strip()))
except (TypeError, ValueError):
return None
def _normalize(item: dict) -> Optional[dict]:
"""locationBasedList2 항목 1건 → place_contents.body. contentid·title·거리·종류 없으면 버린다."""
content_id = str(item.get("contentid") or "").strip()
title = str(item.get("title") or "").strip()
kind = CONTENT_TYPE_MAP.get(str(item.get("contenttypeid") or "").strip())
distance = _int(item.get("dist"))
if not content_id or not title or kind is None or distance is None:
return None
body = {"contentid": content_id, "title": title, "content_type": kind, "distance_m": distance}
# lclsSystm1~3 = 분류체계 대/중/소. ★ 중분류(lclsSystm2)가 주변 맛집에서 같은 업태(경쟁 업소)를 빼는 기준이다.
for key in ("addr1", "addr2", "tel", "mapx", "mapy", "lDongRegnCd", "lDongSignguCd",
"lclsSystm1", "lclsSystm2", "lclsSystm3"):
value = str(item.get(key) or "").strip()
if value:
body[key] = value
# 사진은 상업적 이용이 허용된 공공누리 유형일 때만 싣는다. 유형을 모르면 버린다.
image = str(item.get("firstimage") or "").strip()
license_code = str(item.get("cpyrhtDivCd") or "").strip().lower()
if image and license_code in _COMMERCIAL_OK_LICENSES:
body["firstimage"] = image
body["license"] = license_code
thumb = str(item.get("firstimage2") or "").strip()
if thumb:
body["firstimage2"] = thumb
return body
# ── 공개 API ────────────────────────────────────────────────────────────
def make_client() -> httpx.AsyncClient:
return httpx.AsyncClient(timeout=REQUEST_TIMEOUT)
async def fetch_nearby(client: httpx.AsyncClient, latitude: float, longitude: float,
*, radius_m: int, content_type_id: str) -> list[dict]:
"""업장 좌표 반경 안의 한 종류(정규화, 거리순). 종류마다 반경이 달라 호출도 따로 한다.
★ mapX=경도 · mapY=위도. 뒤집으면 엉뚱한 지역이 붙는다(카카오와 같은 함정).
"""
out: list[dict] = []
seen: set[str] = set()
for page in range(1, MAX_PAGES + 1):
items, total = await _call(
client, "locationBasedList2",
mapX=str(longitude), mapY=str(latitude), radius=str(radius_m),
contentTypeId=content_type_id, arrange="E", pageNo=str(page),
)
for item in items:
body = _normalize(item)
if body and body["contentid"] not in seen:
seen.add(body["contentid"])
out.append(body)
if not items or page * PAGE_SIZE >= total:
break
out.sort(key=lambda b: b["distance_m"])
return out
def _normalize_festival(item: dict, distance_m: int) -> Optional[dict]:
"""searchFestival2 항목 1건 → place_contents.body. locationBasedList2 와 달리 `dist` 를
안 주므로(호출측이 haversine 으로 잰 값을) 그대로 받는다. 기간은 여기 이미 있다."""
content_id = str(item.get("contentid") or "").strip()
title = str(item.get("title") or "").strip()
if not content_id or not title:
return None
body = {"contentid": content_id, "title": title,
"content_type": LocalContentType.FESTIVAL.value, "distance_m": distance_m}
for key in ("addr1", "addr2", "tel", "mapx", "mapy", "lDongRegnCd", "lDongSignguCd",
"lclsSystm1", "lclsSystm2", "lclsSystm3", "eventstartdate", "eventenddate"):
value = str(item.get(key) or "").strip()
if value:
body[key] = value
image = str(item.get("firstimage") or "").strip()
license_code = str(item.get("cpyrhtDivCd") or "").strip().lower()
if image and license_code in _COMMERCIAL_OK_LICENSES:
body["firstimage"] = image
body["license"] = license_code
thumb = str(item.get("firstimage2") or "").strip()
if thumb:
body["firstimage2"] = thumb
return body
def _festival_not_ended(body: dict, today: date) -> bool:
"""종료일이 지났으면 끝난 축제 — 신지 않는다. 기간을 아예 모르면 못 믿으니 역시 뺀다.
종료일 없이 시작일만 있으면(무기한 진행) 유지한다 — 끝났다는 증거가 없다."""
end, start = body.get("eventenddate"), body.get("eventstartdate")
ymd = today.strftime("%Y%m%d")
if end:
return len(end) == 8 and end.isdigit() and end >= ymd
return bool(start)
async def fetch_festivals_in_sido(client: httpx.AsyncClient, latitude: float, longitude: float,
*, sido_code: str, today: date) -> list[dict]:
"""업장이 속한 시도의 축제 **전부**(정규화, 거리순, 이미 끝난 것 제외). 반경으로 자르지 않는다.
★ 반경을 안 두는 이유(2026-09-08 결정): 축제는 차로 가는 행사라 20km 로 자르면 시도 안의
큰 축제가 빠진다. 시도 전체를 그대로 싣고, 거리는 정렬·표시용으로만 잰다.
(종류별 노출 상한은 스냅샷이 20건으로 자른다 — 사진 있는 것 우선 → 가까운 순.)
★ locationBasedList2 의 위치 색인은 못 믿어서 searchFestival2 를 쓴다(위 모듈 docstring).
eventStartDate 는 그 해 1월 1일로 **고정** — "오늘" 을 넣으면 그 이전에 시작해 아직 진행 중인
축제가 파라미터 자체에서 빠진다(실측). 연초부터 전부 받고, 끝난 것만 여기서 거른다.
★ 좌표 없는 항목은 뺀다 — distance_m 이 NOT NULL 이고, 거리 없는 카드는 도보 필터에 못 얹는다.
"""
start_date = date(today.year, 1, 1).strftime("%Y%m%d")
out: list[dict] = []
seen: set[str] = set()
for page in range(1, MAX_PAGES + 1):
items, total = await _call(
client, "searchFestival2",
eventStartDate=start_date, lDongRegnCd=sido_code, pageNo=str(page),
)
for item in items:
lnglat = _mapxy(item) # (경도, 위도) — 좌표가 없으면 거리를 잴 수 없다
if lnglat is None:
continue
lng, lat = lnglat
distance = haversine_m(latitude, longitude, lat, lng) # 자르지 않는다 — 정렬·표시용
body = _normalize_festival(item, round(distance))
if not body or body["contentid"] in seen:
continue
if not _festival_not_ended(body, today):
continue
seen.add(body["contentid"])
out.append(body)
if not items or page * PAGE_SIZE >= total:
break
out.sort(key=lambda b: b["distance_m"])
return out
def _mapxy(item: dict) -> Optional[tuple[float, float]]:
"""(경도, 위도). 좌표가 없거나 숫자가 아니면 None — 거리를 잴 수 없는 항목은 반경으로 못 거른다."""
try:
return float(item.get("mapx")), float(item.get("mapy"))
except (TypeError, ValueError):
return None
async def fetch_content_class(client: httpx.AsyncClient, content_id: str) -> Optional[str]:
"""콘텐츠 1건의 중분류 코드(lclsSystm2). 못 구하면 None.
업장 자신이 TourAPI 에 등록돼 있을 때(place_links 의 tour:// 링크) 그 업장의 업태를 여기서 읽는다 —
주변 맛집에서 같은 중분류를 빼기 위해서다. 외부 분류 문자열 매핑보다 이 값이 우선이다(같은 체계라 오차가 없다).
"""
items, _ = await _call(client, "detailCommon2", contentId=content_id)
if not items:
return None
code = str(items[0].get("lclsSystm2") or "").strip()
return code or None
def festival_is_current(period: Optional[tuple[str, str]], today: date) -> bool:
"""종료일이 지났으면 끝난 축제 — 싣지 않는다. 기간을 아예 모르면(None) 못 믿으니 역시 뺀다.
종료일 없이 시작일만 있으면(무기한 진행) 시작일이 지났어도 유지한다 — 끝났다는 증거가 없다."""
if not period:
return False
start, end = period
ymd = today.strftime("%Y%m%d")
if end:
return len(end) == 8 and end.isdigit() and end >= ymd
return bool(start)
+1 -1
View File
@@ -73,7 +73,7 @@ class FactService:
err_type, place = await DB_SESSION_MNG.execute_lambda(
places.DBType(),
DBWRType.DB_READ.value,
lambda s: self.place_crud.get_place(s, uuid.UUID(user_info.company_id), uuid.UUID(place_id)),
lambda s: self.place_crud.get_place(s, uuid.UUID(user_info.user_id), uuid.UUID(place_id)),
)
if err_type != ErrorType.SUCCESS:
return ErrorType.PLACE_NOT_FOUND, None
+3 -3
View File
@@ -38,14 +38,14 @@ class FaqService:
self.crud = crud
self.place_crud = place_crud
# ---- 사업장 로드(회사 스코프) ----
# ---- 사업장 로드(사장님 스코프) ----
async def _load_place(self, user_info: UserInfo, place_id: str):
"""company_id 를 WHERE 에 걸어 조회한다 — 남의 회사 place_id 를 넣으면 PLACE_NOT_FOUND.
"""owner_user_id 를 WHERE 에 걸어 조회한다 — 남의 place_id 를 넣으면 PLACE_NOT_FOUND.
'없다'와 '권한 없다'를 구분해 주지 않는 것도 의도다(존재 여부를 흘리지 않는다)."""
err_type, place = await DB_SESSION_MNG.execute_lambda(
places.DBType(),
DBWRType.DB_READ.value,
lambda s: self.place_crud.get_place(s, uuid.UUID(user_info.company_id), uuid.UUID(place_id)),
lambda s: self.place_crud.get_place(s, uuid.UUID(user_info.user_id), uuid.UUID(place_id)),
)
if err_type != ErrorType.SUCCESS:
return ErrorType.PLACE_NOT_FOUND, None
+120
View File
@@ -0,0 +1,120 @@
"""여행 일정(1박2일·2박3일) 생성 — 순수 함수 모듈. DB·HTTP 없음.
빌드(payload) 시점에 그 지역의 발행된 지역정보(관광지·맛집·축제)와 업체 좌표로
일정을 **즉석 계산**한다. 저장하지 않는 이유: 재료(local_contents)가 갱신되면
다음 빌드에서 일정도 저절로 최신이 된다 — 따로 저장하면 그 동기화를 또 만들어야 한다.
(docs/superpowers/specs/2026-09-03-local-tourapi-sync-design.md)
★ 지어내지 않는 규칙은 여기도 적용된다.
재료가 부족하면 채울 수 있는 만큼만 담고, 하루도 못 채우면 일정 자체를 내지 않는다.
좌표 없는 항목은 거리를 잴 수 없으므로 후보에서 뺀다 — 동선을 보장 못 하는 추천은 틀린 추천이다.
하루의 뼈대: 관광지 2 + 맛집 2(점심·저녁). 진행 중 축제가 있으면 그날 관광지 한 자리를 대신한다.
일자 배분은 업체에서 가까운 순으로 후보를 끊고, 일자 안에서는 최근접 이웃 순서로 동선을 만든다.
"""
from typing import Optional
from common.utils.geo import haversine_km
# 하루 구성 정원. 관광지 자리는 축제가 하나 대신할 수 있다.
_SPOTS_PER_DAY = 2
_MEALS_PER_DAY = 2
# 후보 반경(km). 업체에서 이보다 먼 곳은 '근처'가 아니다 — 1박2일 생활권을 넘는다.
_MAX_RADIUS_KM = 30.0
_STOP_ATTRACTION = "attraction"
_STOP_RESTAURANT = "restaurant"
_STOP_FESTIVAL = "festival"
def _as_float(value) -> Optional[float]:
try:
return float(value)
except (TypeError, ValueError):
return None
def _candidates(rows: list[dict], stop_type: str,
base_lat: float, base_lng: float) -> list[dict]:
"""payload 지역정보 행 → 거리 오름차순 후보. 좌표가 없거나 반경 밖이면 뺀다.
행 모양은 스냅샷 local.contents 의 body(services/external/tour_api._normalize)다 —
mapx=경도, mapy=위도 (WGS84 문자열).
"""
out = []
for row in rows:
body = row.get("body") or {}
name = str(row.get("title") or body.get("title") or "").strip()
lat, lng = _as_float(body.get("mapy")), _as_float(body.get("mapx"))
if not name or lat is None or lng is None:
continue
dist = haversine_km(base_lat, base_lng, lat, lng)
if dist > _MAX_RADIUS_KM:
continue
out.append({"type": stop_type, "name": name, "lat": lat, "lng": lng,
"distanceKm": round(dist, 1)})
out.sort(key=lambda c: c["distanceKm"])
return out
def _order_by_route(stops: list[dict], base_lat: float, base_lng: float) -> list[dict]:
"""일자 안 동선: 업체에서 출발해 최근접 이웃 순으로 잇는다."""
remaining = list(stops)
ordered: list[dict] = []
lat, lng = base_lat, base_lng
while remaining:
nxt = min(remaining, key=lambda s: haversine_km(lat, lng, s["lat"], s["lng"]))
remaining.remove(nxt)
ordered.append(nxt)
lat, lng = nxt["lat"], nxt["lng"]
return ordered
def _take(pool: list[dict], count: int) -> list[dict]:
taken, pool[:] = pool[:count], pool[count:]
return taken
def _plan_days(days: int, attractions: list[dict], restaurants: list[dict],
festivals: list[dict], base_lat: float, base_lng: float) -> Optional[dict]:
"""일자별 계획. 첫날 하루도 못 채우면 None — 반쪽짜리 일정은 내지 않는다."""
spots = list(attractions)
meals = list(restaurants)
fests = list(festivals)
plan = []
for day in range(1, days + 1):
day_stops = []
# 축제는 하루 하나까지, 관광지 한 자리를 대신한다.
fest = _take(fests, 1)
day_stops += fest
day_stops += _take(spots, _SPOTS_PER_DAY - len(fest))
day_stops += _take(meals, _MEALS_PER_DAY)
if not day_stops:
break
plan.append({"day": day, "stops": _order_by_route(day_stops, base_lat, base_lng)})
if not plan:
return None
return {"days": days, "plan": plan}
def build_itineraries(base_lat: Optional[float], base_lng: Optional[float],
attractions: list[dict], restaurants: list[dict],
festivals: list[dict]) -> list[dict]:
"""업체 좌표 기준 1박2일(2일)·2박3일(3일) 일정. 좌표가 없으면 빈 배열.
입력 행 모양은 스냅샷 local.contents 항목({title, body:{mapx, mapy, …}})이다.
"""
if base_lat is None or base_lng is None:
return []
spot_pool = _candidates(attractions, _STOP_ATTRACTION, base_lat, base_lng)
meal_pool = _candidates(restaurants, _STOP_RESTAURANT, base_lat, base_lng)
fest_pool = _candidates(festivals, _STOP_FESTIVAL, base_lat, base_lng)
out = []
for days in (2, 3):
# 세트마다 독립된 풀 복사 — 1박2일이 소비한 후보가 2박3일에서 빠지면 안 된다.
built = _plan_days(days, list(spot_pool), list(meal_pool), list(fest_pool),
base_lat, base_lng)
if built:
out.append(built)
return out
@@ -1,17 +1,71 @@
from datetime import date, datetime, timedelta, timezone
import re
import uuid
from datetime import datetime, timedelta, timezone
from decimal import Decimal
from sqlalchemy import select
from common.database.db_session_manager import DB_SESSION_MNG
from common.database.model.models import local_contents
from common.enums import DBWRType, ErrorType, LocalContentStatus, LocalContentType, LocalSource
from common.database.model.models import local_contents, place_contents, place_links, places
from common.enums import DBWRType, ErrorType, LocalContentStatus, LocalContentType, LocalSource, PlaceCategory
from common.logger import LOG
from crud.local_content_crud import LocalContentCRUD
from router.v1.local.protocol import ResLocalContentList, ResSyncFestivals, ResWeather, WeatherData
from crud.place_content_crud import PlaceContentCRUD
from crud.place_crud import PlaceCRUD
from services.external.kakao import KakaoLocalClient, KakaoNotConfigured, KakaoRequestFailed
from services.external.naver import region_key
from router.v1.local.protocol import (
ResLocalContentList, ResLocalGuide, ResPlaceContentList, ResSyncPlace, ResWeather, WeatherData,
)
from services.external import tour_api
from services.external.open_meteo import OpenMeteoRequestFailed, fetch_current_weather
from services.external.tour_api import TourApiNotConfigured, TourApiRequestFailed, search_festivals
from services.external.tour_api import TourApiNotConfigured, TourApiRequestFailed
from services.place_category import guess_food_class
# collect_service.discover_tour_api 가 등록하는 업장 자신의 TourAPI 링크. (contentTypeId, contentId)
_TOUR_LINK = re.compile(r"^tour://(\d+)/(\d+)$", re.I)
# 업종별 기본 중분류 — 외부 분류도 TourAPI 링크도 없을 때의 마지막 폴백. 카페는 카페(FD05)를 뺀다.
# 음식점은 어떤 음식인지 모르면 아무것도 빼지 않는다(한식당에서 양식집을 빼면 안 된다).
_DEFAULT_FOOD_CLASS = {PlaceCategory.CAFE.value: "FD05"}
# 축제 노출 종료를 KST 그 날 자정으로 잡기 위한 시간대. 행사 날짜는 한국 날짜다.
_KST = timezone(timedelta(hours=9))
# 업장 반경(m). 2026-09-04 실측(군산 절골길 18)으로 정했다 — specs/2026-09-04-tourapi-radius-spike.md
# 관광지·축제·여행코스 10km: 5km 는 관광지 16건, 10km 는 38건. 원도심 밖 명소가 10km 에서 잡힌다.
# 맛집 5km: 10km 에서도 66건 중 59건이 5km 안이다. 밥은 동네에서 먹는다.
# 종류마다 반경이 다르다(2026-09-08) — 걸어갈 맛집과 차로 갈 관광지를 같은 반경으로 재지 않는다.
# 축제는 반경이 없다 — 업장이 속한 시도 전체를 그대로 싣는다(tour_api.fetch_festivals_in_sido).
RESTAURANT_RADIUS_M = 5_000
ATTRACTION_RADIUS_M = 10_000
def _festival_display_end(body: dict) -> datetime | None:
"""eventenddate(YYYYMMDD) → 그 날 KST 자정(다음날 00:00) UTC.
★ 이 값이 있어야 끝난 축제가 발행본에서 저절로 빠진다 —
스냅샷의 노출창 필터(snapshot._local_contents)가 display_end_at 을 본다."""
raw = str(body.get("eventenddate") or "").strip()
if len(raw) != 8 or not raw.isdigit():
return None
try:
end_day = datetime(int(raw[:4]), int(raw[4:6]), int(raw[6:]), tzinfo=_KST)
except ValueError:
return None
return (end_day + timedelta(days=1)).astimezone(timezone.utc)
def _as_float(value) -> float | None:
try:
return float(value) if value is not None else None
except (TypeError, ValueError):
return None
class LocalContentService:
def __init__(self):
self.crud = LocalContentCRUD()
self.place_crud = PlaceContentCRUD()
async def list(self, status=None, region_code=None):
res = ResLocalContentList()
@@ -22,11 +76,67 @@ class LocalContentService:
res.contents = list(rows) if err == ErrorType.SUCCESS else []
return res
async def sync_festivals(self, req):
res = ResSyncFestivals()
# ── 업장 반경 주변정보 ───────────────────────────────────────────────
async def sync_place(self, place) -> ResSyncPlace:
"""업장 좌표 반경의 맛집·관광지·축제를 TourAPI 에서 받아 place_contents 를 맞춘다.
종류마다 따로 부른다(맛집 5km · 관광지 10km · 축제는 시도 전체, 2026-09-08).
여행코스(25)는 뺐다 — 반경을 넓혀도 데이터가 거의 없다(전북 전체 3건 실측).
빌드가 매번 부른다(services/build_service.run_build) — 발행본은 정적이라 이때 채운 값이 실린다.
★ 실패해도 기존 행을 지우지 않는다 — 직전 값 유지가 이 캐시의 규약이다(모델 주석).
★ 응답에 없는 행은 소프트 삭제한다 — 반경 밖으로 밀렸거나 TourAPI 가 내린 것이다.
hidden(운영자 숨김)은 재수집이 덮어쓰지 않는다(crud.upsert). 이 변경으로 기존에 저장된
여행코스 행도 다음 재수집 때 자연스레 소프트 삭제된다(더는 keep 목록에 없으므로).
★ 공공데이터는 검수 없이 그대로 싣는다(2026-09-03 결정). 틀린 항목은 운영자가 숨긴다.
"""
res = ResSyncPlace()
place_id = getattr(place, "place_id", None)
if place_id is None:
res.result.SetResult(ErrorType.INVALID_REQUEST_DATA)
return res
lat, lng = _as_float(getattr(place, "latitude", None)), _as_float(getattr(place, "longitude", None))
if lat is None or lng is None:
# ★ 좌표가 비면 주소로 한 번 더 찾는다(카카오 주소검색). 주변 정보는 TourAPI 에 이 업소가
# 등록돼 있느냐와 무관하다 — 필요한 건 좌표뿐이다. 찾으면 places 에 박제해 다음부터는 안 부른다.
found = await self._geocode_and_store(place)
if found is None:
res.result.SetResult(ErrorType.INVALID_REQUEST_DATA)
res.msg = "사업장 좌표가 없어 주변 정보를 받을 수 없습니다(주소로도 찾지 못함)."
return res
lat, lng = found
try:
start = datetime.strptime(req.start_date, "%Y%m%d").date() if req.start_date else date.today()
items = await search_festivals(start_date=start, area_code=req.area_code)
async with tour_api.make_client() as client:
# 종류마다 반경이 달라 따로 부른다 — 맛집은 걸어갈 거리, 축제는 차로 갈 거리다.
restaurants = await tour_api.fetch_nearby(
client, lat, lng, radius_m=RESTAURANT_RADIUS_M, content_type_id="39")
# ★ 업종별 제외(2026-09-08 결정): 음식점·카페 업장은 **같은 중분류(경쟁 업소)** 를 뺀다 —
# 카페 사이트에 옆 카페를, 한식당 사이트에 옆 한식당을 추천할 이유가 없다.
# 숙박 업장은 숙박(32)을 빼야 하는데 애초에 요청하지 않으므로 여기서 할 일이 없다.
own_class = await self._own_food_class(client, place)
if own_class:
before = len(restaurants)
restaurants = [r for r in restaurants if r.get("lclsSystm2") != own_class]
LOG.i(f"[local] place={place_id} 같은 업태({own_class}) 맛집 {before - len(restaurants)}건 제외")
attractions = await tour_api.fetch_nearby(
client, lat, lng, radius_m=ATTRACTION_RADIUS_M, content_type_id="12")
# ★ 축제는 locationBasedList2 가 아니라 searchFestival2 를 쓴다(2026-09-08 교체) —
# 위치 색인을 못 믿는다(실측: 반경 20km 를 넓혀도 몇 년 전에 끝난 전시만 잡히고,
# 500m 옆 진행 예정 축제는 안 잡혔다). 시도 코드가 있어야 부를 수 있다.
sido_code = str(getattr(place, "region_code", None) or "")[:2] or None
if not sido_code:
address = str(getattr(place, "road_address", None) or getattr(place, "address", None) or "")
derived = region_key(address)
sido_code = derived[:2] if derived else None
today = datetime.now(_KST).date()
if sido_code:
festivals = await tour_api.fetch_festivals_in_sido(
client, lat, lng, sido_code=sido_code, today=today)
else:
LOG.w(f"[local] place={place_id} 시도 코드를 못 구해 축제는 건너뜀")
festivals = []
except TourApiNotConfigured:
res.result.SetResult(ErrorType.LOCAL_NOT_CONFIGURED)
res.msg = "TOUR_API_KEY를 먼저 설정해주세요."
@@ -36,35 +146,208 @@ class LocalContentService:
res.msg = str(ex)
return res
collected = skipped = 0
for item in items:
external_id = str(item.get("contentid") or "")
if not external_id:
skipped += 1
kept: list[dict] = restaurants + attractions + festivals
err, rows = await DB_SESSION_MNG.execute_lambda(
place_contents.DBType(), DBWRType.DB_READ.value,
lambda s: self.place_crud.list_by_place(s, place_id),
)
if err != ErrorType.SUCCESS:
res.result.SetResult(err)
return res
existing = {(int(r.content_type), r.external_id): r for r in (rows or [])}
now = datetime.now(timezone.utc)
changed = 0
for body in kept:
key = (body["content_type"], body["contentid"])
prev = existing.get(key)
# 원문이 그대로면 쓰지 않는다 — collected_at 만 밀리면 '갱신된 척'이 된다.
if prev is not None and prev.body == body:
continue
_, existing = await DB_SESSION_MNG.execute_lambda(
local_contents.DBType(), DBWRType.DB_READ.value,
lambda s, eid=external_id: self.crud.get_by_external_id(s, req.region_code, eid),
values = {
"place_id": place_id,
"content_type": body["content_type"],
"external_id": body["contentid"],
"title": body["title"],
"body": body,
"distance_m": body["distance_m"],
"has_image": bool(body.get("firstimage")),
"display_end_at": (
_festival_display_end(body) if body["content_type"] == LocalContentType.FESTIVAL.value else None
),
"collected_at": now,
}
write_err = await DB_SESSION_MNG.execute_lambda_run(
[place_contents.DBType()], [lambda s, v=values: self.place_crud.upsert(s, v)]
)
if existing:
skipped += 1
continue
row = local_contents(
region_code=req.region_code,
content_type=LocalContentType.FESTIVAL.value,
source=LocalSource.TOUR_API.value,
external_id=external_id,
title=item.get("title"),
body=item,
status=LocalContentStatus.REVIEW.value,
collected_at=datetime.now(timezone.utc),
)
err = await DB_SESSION_MNG.execute_lambda_run([row.DBType()], [lambda s, r=row: self.crud.insert(s, r)])
collected += int(err == ErrorType.SUCCESS)
skipped += int(err != ErrorType.SUCCESS)
res.collected, res.skipped = collected, skipped
if write_err == ErrorType.SUCCESS:
changed += 1
keep_keys = {(b["content_type"], b["contentid"]) for b in kept}
_, removed = await DB_SESSION_MNG.execute_lambda_claim(
place_contents.DBType(), lambda s: self.place_crud.soft_delete_missing(s, place_id, keep_keys)
)
counts = {k: 0 for k in (LocalContentType.FESTIVAL.value, LocalContentType.ATTRACTION.value,
LocalContentType.RESTAURANT.value, LocalContentType.COURSE.value)}
for b in kept:
counts[b["content_type"]] += 1
res.festivals = counts[LocalContentType.FESTIVAL.value]
res.attractions = counts[LocalContentType.ATTRACTION.value]
res.restaurants = counts[LocalContentType.RESTAURANT.value]
res.courses = counts[LocalContentType.COURSE.value]
res.changed = changed > 0 or bool(removed)
LOG.i(f"[local] place={place_id} 주변정보 {len(kept)}건(갱신 {changed} · 제거 {removed or 0})")
return res
async def _own_food_class(self, client, place) -> str | None:
"""음식점·카페 업장 자신의 TourAPI 중분류(FD01~FD05). 숙박·병원은 None(제외할 게 없다).
우선순위 — 정확한 쪽부터:
1. 업장이 TourAPI 에 등록돼 있으면(place_links 의 tour:// 링크) 그 콘텐츠의 lclsSystm2.
주변 항목과 **같은 체계**라 오차가 없다. 링크는 수집(COLLECT)이 상호+좌표 검증을 거쳐 붙인다.
2. 검증 때 박제한 외부 분류 문자열(places.external_category)을 키워드로 매핑.
3. 그래도 모르면 업종 기본값 — 카페는 FD05. 음식점은 None(무엇을 빼야 할지 모른다).
실패는 전부 '제외 없음'으로 떨어진다 — 경쟁 업소가 섞이는 것이 맛집 섹션이 통째로 비는 것보다 낫다.
"""
category = getattr(place, "category", None)
if category not in (PlaceCategory.CAFE.value, PlaceCategory.RESTAURANT.value):
return None
err, links = await DB_SESSION_MNG.execute_lambda(
place_links.DBType(), DBWRType.DB_READ.value,
lambda s: PlaceCRUD().list_links(s, place.place_id, confirmed_only=True),
)
for link in (links or []) if err == ErrorType.SUCCESS else []:
m = _TOUR_LINK.match(str(getattr(link, "url", "") or ""))
if not m:
continue
try:
code = await tour_api.fetch_content_class(client, m.group(2))
except TourApiRequestFailed as ex:
LOG.w(f"[local] 업장 TourAPI 분류 조회 실패(외부 분류로 폴백): {ex}")
code = None
if code:
return code
break
guessed = guess_food_class(getattr(place, "external_category", None))
if guessed:
return guessed
return _DEFAULT_FOOD_CLASS.get(category)
async def _geocode_and_store(self, place) -> tuple[float, float] | None:
"""주소 → 좌표(카카오). 찾으면 places.latitude/longitude 에 박제한다. 키가 없거나 실패하면 None."""
address = str(getattr(place, "road_address", None) or getattr(place, "address", None) or "").strip()
if not address:
return None
client = KakaoLocalClient()
if not client.enabled:
LOG.w("[local] 좌표 없는 사업장인데 KAKAO_REST_API_KEY 가 없어 주소로 찾지 못한다")
return None
try:
found = await client.geocode_address(address)
except (KakaoNotConfigured, KakaoRequestFailed) as ex:
LOG.w(f"[local] 주소 → 좌표 실패(계속): {ex}")
return None
finally:
await client.aclose()
if found is None:
return None
lat, lng = found
company_id = getattr(place, "company_id", None)
if company_id is not None:
data = {"latitude": Decimal(str(lat)), "longitude": Decimal(str(lng))}
err, _ = await DB_SESSION_MNG.execute_lambda_claim(
places.DBType(),
lambda s: PlaceCRUD().update_place(s, company_id, place.place_id, data),
)
if err != ErrorType.SUCCESS:
LOG.w(f"[local] 좌표 박제 실패(이번 수집엔 그대로 씀): {err.name}")
else:
place.latitude, place.longitude = data["latitude"], data["longitude"]
LOG.i(f"[local] place={place.place_id} 주소로 좌표 확보 ({lat:.5f}, {lng:.5f}) — {address[:40]}")
return lat, lng
async def _load_place(self, place_id):
"""회사 스코프 없이 사업장 1건. ★ 공개 조회(guide)와 운영자 화면이 쓴다 — 사장님 API 는 place_service 를 탄다."""
err, rows = await DB_SESSION_MNG.execute_lambda(
places.DBType(), DBWRType.DB_READ.value,
lambda s: DB_SESSION_MNG.execute(
s, select(places).where(places.place_id == place_id, places.deleted == False).limit(1) # noqa: E712
),
)
return (rows[0] if rows else None) if err == ErrorType.SUCCESS else None
async def sync_place_by_id(self, place_id: uuid.UUID) -> ResSyncPlace:
place = await self._load_place(place_id)
if place is None:
res = ResSyncPlace()
res.result.SetResult(ErrorType.DB_EMPTY_DATA)
return res
return await self.sync_place(place)
async def list_place_contents(self, place_id: uuid.UUID) -> ResPlaceContentList:
res = ResPlaceContentList()
err, rows = await DB_SESSION_MNG.execute_lambda(
place_contents.DBType(), DBWRType.DB_READ.value,
lambda s: self.place_crud.list_by_place(s, place_id, include_hidden=True),
)
res.result.SetResult(err)
res.contents = list(rows) if err == ErrorType.SUCCESS else []
return res
async def set_hidden(self, place_content_id: uuid.UUID, hidden: bool) -> ResPlaceContentList:
res = ResPlaceContentList()
err, count = await DB_SESSION_MNG.execute_lambda_claim(
place_contents.DBType(), lambda s: self.place_crud.set_hidden(s, place_content_id, hidden)
)
res.result.SetResult(err if count else ErrorType.DB_EMPTY_DATA)
return res
async def get_guide(self, place_id: uuid.UUID) -> ResLocalGuide:
"""에디터 캔버스용 주변 가이드(맛집·명소·축제·코스).
★ 스냅샷 필터(숨김·노출창)와 payload 변환을 **그대로 재사용**한다 —
캔버스가 발행본과 다른 목록을 보이면 사장님이 "미리보기와 다르다"고 읽는다.
그래서 여기서 DB 를 따로 읽지 않고 발행 파이프라인의 두 함수를 잇기만 한다.
★ 일정(itineraries)은 payload 가 만들어도 여기선 내려보내지 않는다 — 캔버스에 그릴 자리가 아직 없다.
"""
# 순환 import 회피 — snapshot·site_payload 는 발행 파이프라인 모듈이라 서비스 최상단에서 끌어오지 않는다.
from services.site_payload import _local
from services.snapshot import _local_contents
res = ResLocalGuide()
place = await self._load_place(place_id)
if place is None:
res.result.SetResult(ErrorType.DB_EMPTY_DATA)
return res
# ★ 아직 한 번도 수집하지 않은 사업장은 **지금** 채운다(cache-aside — 날씨와 같은 규약).
# 빌드 때만 채우면 방금 만든 사업장은 첫 빌드 전까지 캔버스가 계속 "준비 중"이다(2026-09-07 실측).
# 행이 하나라도 있으면 부르지 않는다 — 갱신은 빌드·운영자 재수집이 맡는다.
err, rows = await DB_SESSION_MNG.execute_lambda(
place_contents.DBType(), DBWRType.DB_READ.value,
lambda s: self.place_crud.list_by_place(s, place_id),
)
if err == ErrorType.SUCCESS and not rows:
synced = await self.sync_place(place)
if not synced.result.success:
LOG.w(f"[local] place={place_id} 첫 조회 수집 실패(빈 채로 응답): {synced.msg}")
snapshot_local = await _local_contents(place)
local, synced_at = _local(snapshot_local, _as_float(place.latitude), _as_float(place.longitude))
res.attractions = local.get("attractions") or []
res.restaurants = local.get("restaurants") or []
res.festivals = local.get("festivals") or []
res.courses = local.get("courses") or []
res.synced_at = synced_at
return res
# ── 지역 캐시(local_contents) — 운영자 수기 항목·날씨 ────────────────
async def publish(self, ids, user_id):
res = ResLocalContentList()
err, _ = await DB_SESSION_MNG.execute_lambda_claim(
+1 -1
View File
@@ -41,7 +41,7 @@ class MediaService:
err_type, place = await DB_SESSION_MNG.execute_lambda(
places.DBType(),
DBWRType.DB_READ.value,
lambda s: self.place_crud.get_place(s, uuid.UUID(user_info.company_id), uuid.UUID(place_id)),
lambda s: self.place_crud.get_place(s, uuid.UUID(user_info.user_id), uuid.UUID(place_id)),
)
if err_type != ErrorType.SUCCESS:
return ErrorType.PLACE_NOT_FOUND, None
@@ -68,3 +68,39 @@ def _match(text: str) -> Optional[PlaceCategory]:
if any(word in text for word in words):
return category
return None
# ── 음식 중분류(TourAPI lclsSystm2) 추정 ─────────────────────────────────
# 주변 맛집에서 **같은 중분류(경쟁 업소)를 빼는** 기준이다(2026-09-08 결정).
# TourAPI 분류체계(lclsSystmCode2 실측) — FD01 한식 · FD02 외국식(중·일·서양·기타외국·퓨전)
# · FD03 간이음식(제과·피자/햄버거/샌드위치·치킨·김밥분식·이동음식) · FD04 주점 · FD05 카페/찻집.
#
# ★ 순서가 결과를 바꾼다. 카카오는 카페를 "음식점 > 카페 > …" 아래 두므로 "음식점"이 항상 붙어 있다 —
# 그래서 "음식점" 은 판정어로 쓰지 않고, 구체적인 업태(카페·주점·간이·외국식)를 한식보다 먼저 본다.
# ★ 한식은 마지막이고 판정어가 좁다("한식"·"한정식"·"백반"·"국밥"…). 고기·회 같은 재료명은 넣지 않는다 —
# "양식 > 스테이크" 를 고기라고 한식으로 넣으면 서양식 스테이크집이 한식이 된다.
_FOOD_CLASS_KEYWORDS: list[tuple[str, tuple[str, ...]]] = [
("FD05", ("카페", "커피", "찻집", "디저트", "음료", "주스", "빙수", "케이크", "브런치")),
("FD04", ("주점", "술집", "호프", "맥주", "이자카야", "포차", "와인바", "칵테일", "펍")),
("FD03", ("제과", "베이커리", "빵", "도넛", "피자", "햄버거", "샌드위치", "치킨", "분식", "김밥",
"떡볶이", "간식", "토스트", "패스트푸드")),
("FD02", ("중식", "중국", "일식", "일본", "초밥", "라멘", "양식", "서양", "이탈리", "파스타", "스테이크",
"프렌치", "프랑스", "멕시", "아시아", "베트남", "태국", "인도", "퓨전")),
("FD01", ("한식", "한정식", "백반", "국밥", "찌개", "국수", "냉면", "삼겹", "갈비", "곱창", "족발", "보쌈",
"해장국", "설렁탕", "감자탕", "칼국수", "횟집", "회")),
]
def guess_food_class(category_name: Optional[str]) -> Optional[str]:
"""외부 분류 문자열 → TourAPI 음식 중분류 코드(FD01~FD05). 모르면 None(제외 없음).
예 — 카카오 "음식점 > 카페 > 커피전문점" → FD05 · 네이버 "카페,디저트" → FD05 ·
카카오 "음식점 > 한식 > 육류,고기" → FD01 · "음식점 > 양식 > 스테이크,립" → FD02
"""
text = (category_name or "").replace(" ", "")
if not text:
return None
for code, words in _FOOD_CLASS_KEYWORDS:
if any(word in text for word in words):
return code
return None
+22 -14
View File
@@ -70,12 +70,12 @@ class PlaceService:
# ---- 조회 ----
async def list_places(self, user_info: UserInfo, pg: PageParams, search=None, category=None, status=None) -> Res_PlaceList:
res = Res_PlaceList(page=pg.page, size=pg.size)
cid = uuid.UUID(user_info.company_id)
uid = uuid.UUID(user_info.user_id)
err_type, rows, total = await DB_SESSION_MNG.execute_lambda(
places.DBType(),
DBWRType.DB_READ.value,
lambda s: self.crud.list_places(
s, cid, search,
s, uid, search,
category.value if isinstance(category, PlaceCategory) else category,
status.value if isinstance(status, PlaceStatus) else status,
pg.skip, pg.size,
@@ -102,7 +102,7 @@ class PlaceService:
err_type, place = await DB_SESSION_MNG.execute_lambda(
places.DBType(),
DBWRType.DB_READ.value,
lambda s: self.crud.get_place(s, uuid.UUID(user_info.company_id), uuid.UUID(place_id)),
lambda s: self.crud.get_place(s, uuid.UUID(user_info.user_id), uuid.UUID(place_id)),
)
if err_type != ErrorType.SUCCESS:
return ErrorType.PLACE_NOT_FOUND, None
@@ -122,8 +122,11 @@ class PlaceService:
return res
place = places(
company_id=uuid.UUID(user_info.company_id),
owner_user_id=req.owner_user_id,
# ★ 주인은 **토큰이 정한다.** 예전엔 요청 body 의 owner_user_id 를 그대로 넣었는데,
# 그 값은 아무도 안 보내서 92건 전부 NULL 이었고 스코프는 회사가 대신 하고 있었다.
# 회사를 걷어내면서 이 컬럼이 스코프 키가 됐다 — body 로 남의 계정을 적을 수 있으면
# 만들자마자 남의 목록에 들어간다.
owner_user_id=uuid.UUID(user_info.user_id),
name=req.name.strip(),
category=req.category.value,
status=PlaceStatus.DRAFT.value,
@@ -149,7 +152,7 @@ class PlaceService:
if data:
err_type, rowcount = await DB_SESSION_MNG.execute_lambda_claim(
places.DBType(),
lambda s: self.crud.update_place(s, uuid.UUID(user_info.company_id), uuid.UUID(place_id), data),
lambda s: self.crud.update_place(s, uuid.UUID(user_info.user_id), uuid.UUID(place_id), data),
)
if err_type != ErrorType.SUCCESS:
res.result.SetResult(err_type)
@@ -164,7 +167,7 @@ class PlaceService:
err_type, rowcount = await DB_SESSION_MNG.execute_lambda_claim(
places.DBType(),
lambda s: self.crud.delete_place(
s, uuid.UUID(user_info.company_id), uuid.UUID(place_id)
s, uuid.UUID(user_info.user_id), uuid.UUID(place_id)
),
)
if err_type != ErrorType.SUCCESS:
@@ -240,6 +243,8 @@ class PlaceService:
phone=base.get("phone") or base.get("virtualPhone") or None,
latitude=Decimal(str(coord.get("y"))) if coord.get("y") else None,
longitude=Decimal(str(coord.get("x"))) if coord.get("x") else None,
# 네이버 상세의 분류("펜션"·"카페,디저트"). 주변 맛집 경쟁업소 제외의 폴백 근거(실측 2026-09-08: 있음).
category_name=str(base.get("category") or "").strip() or None,
)
verified = await self.verify_place(user_info, place_id, verify_req)
if not verified.result.success:
@@ -251,7 +256,7 @@ class PlaceService:
await DB_SESSION_MNG.execute_lambda_claim(
places.DBType(),
lambda s: self.crud.update_place(
s, uuid.UUID(user_info.company_id), uuid.UUID(place_id), {"name": official}
s, uuid.UUID(user_info.user_id), uuid.UUID(place_id), {"name": official}
),
)
if verified.place:
@@ -292,7 +297,7 @@ class PlaceService:
res.result.SetResult(err_type)
return res
cid = uuid.UUID(user_info.company_id)
uid = uuid.UUID(user_info.user_id)
now = GTime.UTC()
data = {
"external_source": req.source.value,
@@ -318,9 +323,12 @@ class PlaceService:
"verified_at": now,
"verified_by": uuid.UUID(user_info.user_id),
}
# ★ 값이 왔을 때만 덮는다 — 네이버 URL 재검증이 분류를 못 읽었다고 카카오가 준 값을 지우면 안 된다.
if (req.category_name or "").strip():
data["external_category"] = req.category_name.strip()[:200]
err_type, rowcount = await DB_SESSION_MNG.execute_lambda_claim(
places.DBType(),
lambda s: self.crud.update_place(s, cid, uuid.UUID(place_id), data),
lambda s: self.crud.update_place(s, uid, uuid.UUID(place_id), data),
)
if err_type != ErrorType.SUCCESS:
res.result.SetResult(err_type)
@@ -508,7 +516,7 @@ class PlaceService:
payload = {
"place_id": place_id,
"company_id": user_info.company_id,
"owner_user_id": user_info.user_id,
"category": place.category,
# 명시적으로 고른 링크가 있을 때만 대상을 제한한다. 기본 요청에서 현재
# 확정 링크를 복사하면, 잡의 discover 단계가 새로 확정한 네이버 링크가
@@ -537,7 +545,7 @@ class PlaceService:
await DB_SESSION_MNG.execute_lambda_claim(
places.DBType(),
lambda s: self.crud.update_place(
s, uuid.UUID(user_info.company_id), uuid.UUID(place_id),
s, uuid.UUID(user_info.user_id), uuid.UUID(place_id),
{"status": PlaceStatus.COLLECTING.value},
),
)
@@ -584,7 +592,7 @@ class PlaceService:
job_id, created = await enqueue_job(
self.queue, JobType.VISION,
{"place_id": place_id, "company_id": user_info.company_id, "force": req.force},
{"place_id": place_id, "owner_user_id": user_info.user_id, "force": req.force},
dedupe_key=f"vision:{place_id}",
)
if job_id is None:
@@ -844,7 +852,7 @@ class PlaceService:
job_id, created = await enqueue_job(
self.queue, JobType.COPY,
{"place_id": place_id, "company_id": user_info.company_id, "requested_by": user_info.user_id},
{"place_id": place_id, "owner_user_id": user_info.user_id, "requested_by": user_info.user_id},
dedupe_key=f"copy:{place_id}",
)
if job_id is None:
@@ -5,7 +5,7 @@
고르는 자리를 한 곳으로 모았다. 사이트 한 곳을 여는 것과 발행 업소 명단을 통째로
긁는 것은 다른 일이라, 페이지에 이미 적혀 있는 것만 나간다.
나가지 않는 것: place_id · company_id · site_id · 전화번호 · 상세 주소 · 좌표.
나가지 않는 것: place_id · 소유자 · site_id · 전화번호 · 상세 주소 · 좌표.
"""
from common.database.db_session_manager import DB_SESSION_MNG
+71 -9
View File
@@ -31,6 +31,7 @@ from common.enums import (
SourceType,
)
from common.logger import LOG
from services.itinerary import build_itineraries
# 렌더러가 확인하는 스키마 버전. 모양이 바뀌면 여기와 site-payload.ts 를 같이 올린다.
SCHEMA_VERSION = 1
@@ -477,32 +478,77 @@ def _festival(row: dict):
# 공식 홈페이지는 출처가 준 값일 때만 싣는다. 형식이 URL 이 아니면 링크로 걸지 않는다.
if homepage.startswith("http://") or homepage.startswith("https://"):
entry["officialUrl"] = homepage
# 업장 반경 캐시(place_contents)에서 온 축제는 거리·사진도 있다 — 카드 캐러셀이 맛집·명소와
# 같은 모양으로 그리려면 필요하다(2026-09-07, 도보 시간 필터 형식 결정).
_put_distance(entry, body)
image = _text(body.get("firstimage"))
if image:
entry["imageUrl"] = image
return entry
def _local_place(row: dict, category: str):
"""LocalPlace(주변 명소·맛집).
★ title 컬럼만 믿는다. 이 두 종류(ATTRACTION·RESTAURANT)를 채우는 수집기가 아직 없어서
body 의 모양이 정해지지 않았다 — 있지도 않은 키를 가정해 파싱하면 수집기가 붙는 날
조용히 빈 값이 나간다. 지금은 테이블 스키마가 보장하는 것(title)만 쓰고,
설명·거리는 실제 수집기가 붙을 때 그 모양을 보고 채운다."""
body 는 TourAPI 수집기가 채운다(services/external/tour_api._normalize) —
주소(addr1)가 있으면 위치로 싣는다. 없는 값은 만들지 않는다."""
name = _text(row.get("title"))
if not name:
return None
return {"name": name, "category": category, "searchQuery": name}
body = row.get("body") or {}
entry = {"name": name, "category": category, "searchQuery": name}
location = _text(body.get("addr1"))
if location:
entry["location"] = location
# 거리는 수집 시점에 업장 좌표로 잰 값(place_contents.distance_m). 지역 캐시 항목엔 없다.
# ★ 숫자(distanceMeters)도 함께 싣는다 — 화면이 도보 시간 필터(분속 80m 환산)를 계산하려면
# "1.2km" 같은 문자열을 다시 파싱하는 것보다 원값이 안전하다.
_put_distance(entry, body)
image = _text(body.get("firstimage"))
if image:
entry["imageUrl"] = image
return entry
def _local(snapshot_local: dict) -> tuple[dict, str | None]:
def _put_distance(entry: dict, body: dict) -> None:
"""distance_m → distanceText("850m") + distanceMeters(850). 값이 없거나 음수면 둘 다 넣지 않는다."""
distance = _distance_text(body.get("distance_m"))
if not distance:
return
entry["distanceText"] = distance
entry["distanceMeters"] = int(body.get("distance_m"))
def _distance_text(meters) -> str:
"""850 → "850m", 1234 → "1.2km". 없으면 빈 문자열."""
try:
m = int(meters)
except (TypeError, ValueError):
return ""
if m < 0:
return ""
if m < 1000:
return f"{m}m"
# 반올림은 '5 는 올림'으로 — f"{1.45:.1f}" 는 부동소수 탓에 1.4 가 나온다.
return f"{(m + 50) // 100 / 10:.1f}km"
def _local(snapshot_local: dict, base_lat: float | None, base_lng: float | None) -> tuple[dict, str | None]:
"""스냅샷의 지역 정보 → LocalContents.
★ 스냅샷이 이미 걸렀다(PUBLISHED + 노출 기간 안). 여기서 더 거르지 않고 모양만 바꾼다 —
fact·사진과 같은 분업이다.
★ 예전에는 이 자리가 무조건 빈 배열이었다. local_contents 에 검수·발행된 지역 정보가 있어도
payload 경계에서 통째로 버려져, 모든 발행 사이트의 지역 정보 섹션이 영구히 안 나왔다."""
payload 경계에서 통째로 버려져, 모든 발행 사이트의 지역 정보 섹션이 영구히 안 나왔다.
★ itineraries(1박2일·2박3일 일정)는 저장하지 않고 여기서 즉석 계산한다 —
재료가 갱신되면 다음 빌드에서 일정도 저절로 최신이 된다(services/itinerary.py).
렌더러에 아직 이 필드의 자리가 없다 — 모르는 필드는 무시되므로 화면은 변하지 않는다."""
contents = (snapshot_local or {}).get("contents") or []
local = {"attractions": [], "restaurants": [], "festivals": []}
# courses(여행코스)는 백엔드만 채운다 — 렌더러 타입에 아직 자리가 없어 화면은 무시한다(2026-09-07).
local = {"attractions": [], "restaurants": [], "festivals": [], "courses": []}
synced_at = None
# 일정 계산용 원본 행(좌표가 body 에 있다). payload 항목은 좌표를 싣지 않으므로 따로 모은다.
raw = {"attractions": [], "restaurants": [], "festivals": []}
for row in contents:
if not isinstance(row, dict):
@@ -523,16 +569,29 @@ def _local(snapshot_local: dict) -> tuple[dict, str | None]:
entry = _festival(row)
if entry:
local["festivals"].append(entry)
raw["festivals"].append(row)
elif content_type == LocalContentType.ATTRACTION.value:
entry = _local_place(row, "관광지")
if entry:
local["attractions"].append(entry)
raw["attractions"].append(row)
elif content_type == LocalContentType.RESTAURANT.value:
entry = _local_place(row, "맛집")
if entry:
local["restaurants"].append(entry)
raw["restaurants"].append(row)
elif content_type == LocalContentType.COURSE.value:
entry = _local_place(row, "여행코스")
if entry:
local["courses"].append(entry)
# 그 밖의 content_type 은 버린다 — 렌더러 타입에 담을 자리가 없다.
itineraries = build_itineraries(
base_lat, base_lng, raw["attractions"], raw["restaurants"], raw["festivals"]
)
if itineraries:
local["itineraries"] = itineraries
return local, synced_at
@@ -708,7 +767,10 @@ def to_site_payload(place, snapshot: dict, site, version, links) -> dict:
# ★ 스냅샷에서 읽는다 — 여기서 DB 를 다시 읽으면 '스냅샷과 다른 페이지'가 나온다(파일 상단 원칙).
# 지역 정보를 스냅샷에 담는 필터링은 services/snapshot._local_contents 가 한다.
# 옛 스냅샷에는 "local" 키가 없다. 그때는 빈 채로 나가고, 다음 빌드에서 채워진다.
local, local_synced_at = _local(snapshot.get("local") or {})
local, local_synced_at = _local(
snapshot.get("local") or {},
_as_float(snap_place.get("latitude")), _as_float(snap_place.get("longitude")),
)
if local_synced_at:
local["syncedAt"] = local_synced_at
+6 -5
View File
@@ -104,7 +104,7 @@ class SiteService:
err_type, place = await DB_SESSION_MNG.execute_lambda(
places.DBType(),
DBWRType.DB_READ.value,
lambda s: self.place_crud.get_place(s, uuid.UUID(user_info.company_id), uuid.UUID(place_id)),
lambda s: self.place_crud.get_place(s, uuid.UUID(user_info.user_id), uuid.UUID(place_id)),
)
if err_type != ErrorType.SUCCESS:
return ErrorType.PLACE_NOT_FOUND, None
@@ -420,16 +420,16 @@ class SiteService:
return cleaned
async def list_my_sites(self, user_info: UserInfo, pg: PageParams) -> Res_MySites:
"""로그인한 계정(회사)이 가진 사이트 전부.
"""로그인한 사장님이 가진 사이트 전부.
사업장 목록(/v1/place/list)과 따로 두는 이유: 화면이 알아야 하는 건 '사업장이 있다'가 아니라
'발행돼 있나 · 주소가 뭔가 · 다시 구워야 하나'다."""
res = Res_MySites(page=pg.page, size=pg.size)
cid = uuid.UUID(user_info.company_id)
uid = uuid.UUID(user_info.user_id)
err_type, rows, total = await DB_SESSION_MNG.execute_lambda(
places.DBType(),
DBWRType.DB_READ.value,
lambda s: self.crud.list_company_sites(s, cid, pg.skip, pg.size),
lambda s: self.crud.list_owner_sites(s, uid, pg.skip, pg.size),
)
if err_type != ErrorType.SUCCESS:
res.result.SetResult(err_type)
@@ -454,6 +454,7 @@ class SiteService:
domain=getattr(site, "domain", None),
template_id=getattr(site, "template_id", None),
published_at=getattr(site, "published_at", None),
thumbnail_url=getattr(site, "thumbnail_url", None),
needs_rebuild=bool(site is not None and changed and (built_at is None or changed > built_at)),
)
@@ -526,7 +527,7 @@ class SiteService:
job_id, created = await enqueue_job(
self.queue, JobType.BUILD,
{
"place_id": place_id, "company_id": user_info.company_id,
"place_id": place_id, "owner_user_id": user_info.user_id,
"publish": req.publish, "requested_by": user_info.user_id,
},
dedupe_key=f"build:{place_id}",
+73 -15
View File
@@ -18,7 +18,7 @@ import asyncio
import os
import httpx
from azure.storage.blob import BlobServiceClient, ContentSettings
from azure.storage.blob import BlobClient, BlobServiceClient, ContentSettings
from common.logger import LOG
from services import azure_static, site_payload
@@ -46,19 +46,71 @@ MAX_BYTES = 5 * 1024 * 1024
CACHE_CONTROL = "public, max-age=60, must-revalidate"
# ── 썸네일 전용 저장소 ────────────────────────────────────────────────────────
# ★ 왜 스위치를 따로 두나
# 원래는 `AZURE_STORAGE_CONNECTION_STRING` 하나가 사이트 업로드(azure_static)와 썸네일을
# **같이** 켰다. 그런데 그 둘은 필요한 저장소가 다르다 — 사이트는 정적 호스팅(`$web`)이고
# 썸네일은 그냥 이미지 버킷이면 된다. 하나로 묶어 두면 "썸네일 좀 보자" 고 키를 꽂는 순간
# **발행할 때마다 사이트 전체가 그 버킷에 업로드된다.** 지금 우리가 빌려 쓰는 곳은
# negodata·infinith 와 공용인 미디어 컨테이너라 그렇게 되면 안 된다.
#
# ★ 값 출처: o2o-negosium/negodata/backend/config/config.local.toml `[StorageConfig]`.
# 같은 계정/컨테이너를 root 디렉터리로만 가른다(negodata/ · infinith/ · web4ai/) —
# 그쪽 관례를 그대로 따른 것이지 우리 계정이 아니다.
#
# ⚠️ **임시다.** 이 컨테이너는 정적 사이트 호스팅이 아니라 발행본을 못 올린다. 그리고 SAS 가
# 컨테이너 전체에 racwdl(삭제 포함)이라, 남의 프로젝트 파일에 닿을 수 있는 자리다 —
# web4ai 전용 스토리지 계정이 생기면 이 블록을 걷고 azure_static 쪽으로 되돌린다.
_BASE_ENV = "THUMBNAIL_BLOB_BASE_URL" # https://<계정>.blob.core.windows.net/<컨테이너>
_SAS_ENV = "THUMBNAIL_BLOB_SAS_TOKEN" # `?sv=...` (앞의 물음표는 있어도 없어도 된다)
_ROOT_ENV = "THUMBNAIL_BLOB_ROOT" # 컨테이너 안에서 우리가 쓰는 디렉터리. 예: web4ai
def _blob_base() -> str:
return os.environ.get(_BASE_ENV, "").strip().rstrip("/")
def _blob_sas() -> str:
return os.environ.get(_SAS_ENV, "").strip().lstrip("?")
def _blob_root() -> str:
return os.environ.get(_ROOT_ENV, "").strip().strip("/")
def uses_blob_store() -> bool:
"""썸네일 전용 저장소를 쓰는가. 아니면 예전대로 azure_static 설정을 따른다."""
return bool(_blob_base() and _blob_sas())
def is_configured() -> bool:
return azure_static.is_configured()
return uses_blob_store() or azure_static.is_configured()
def blob_name(slug: str, ext: str) -> str:
if uses_blob_store():
# base_url 에 컨테이너까지 들어 있다 — 여기서는 컨테이너 안쪽 경로만 만든다.
return "/".join(part for part in (_blob_root(), THUMB_DIR, f"{slug}.{ext}") if part)
prefix = os.environ.get("AZURE_STORAGE_PREFIX", azure_static.DEFAULT_PREFIX).strip().strip("/")
return "/".join(part for part in (prefix, THUMB_DIR, f"{slug}.{ext}") if part)
def public_url(slug: str, ext: str) -> str:
def public_url(slug: str, ext: str, version: int | None = None) -> str:
"""공개 주소. 발행 사이트와 같은 오리진이다 — 접두사는 오리진 경로로 흡수된다
(CLAUDE.md 'AZURE_STORAGE_PREFIX 와 루트 절대경로는 충돌한다')."""
return f"{site_payload.publish_origin()}/{THUMB_DIR}/{slug}.{ext}"
(CLAUDE.md 'AZURE_STORAGE_PREFIX 와 루트 절대경로는 충돌한다').
★ `?v=<버전>` 은 캐시 무효화다. 블롭 이름은 발행마다 그대로고 내용만 덮어쓰므로
(overwrite=True), 주소가 안 변하면 브라우저·CDN 이 **옛 그림을 계속 보여준다.**
아래 CACHE_CONTROL(60초)만으로는 부족하다 — 그 60초 동안 사장님은 방금 바꾼 사진이
아니라 지난 발행의 사진을 본다. 버전을 붙이면 발행 즉시 새 주소가 된다.
★ 이름에 버전을 넣지 않는 이유: 사이트당 블롭이 발행 횟수만큼 쌓이고, 지우는 코드가 없다.
★ version 이 None 이면 붙이지 않는다 — 옛 발행분을 사후에 채우는 경로
(scripts/backfill_thumbnails.py)에는 그 시점의 버전이 없다."""
# ★ 저장소가 발행 오리진 밖이면 주소도 그쪽이다. 여기서 publish_origin 을 쓰면
# 그림은 블롭에 올라가 있는데 카드는 우리 사이트 주소를 가리켜 전부 404 다.
base = f"{_blob_base()}/{blob_name(slug, ext)}" if uses_blob_store() \
else f"{site_payload.publish_origin()}/{THUMB_DIR}/{slug}.{ext}"
return f"{base}?v={version}" if version is not None else base
async def _fetch(url: str) -> tuple[bytes, str, str] | None:
@@ -109,6 +161,18 @@ async def _fetch(url: str) -> tuple[bytes, str, str] | None:
def _upload_sync(slug: str, data: bytes, content_type: str, ext: str) -> str:
name = blob_name(slug, ext)
settings = ContentSettings(content_type=content_type, cache_control=CACHE_CONTROL)
if uses_blob_store():
# ★ SAS 는 연결 문자열이 아니다 — from_connection_string 이 못 받는다.
# 블롭 주소에 토큰을 붙여 그 한 파일에만 붙는다(컨테이너 클라이언트를 만들지 않는다:
# 남의 디렉터리를 훑을 수 있는 핸들을 굳이 들고 있지 않는다).
BlobClient.from_blob_url(f"{_blob_base()}/{name}?{_blob_sas()}").upload_blob(
data, overwrite=True, content_settings=settings
)
return name
connection_string = os.environ["AZURE_STORAGE_CONNECTION_STRING"].strip()
container_name = (
os.environ.get("AZURE_STORAGE_CONTAINER", azure_static.DEFAULT_CONTAINER).strip()
@@ -116,18 +180,12 @@ def _upload_sync(slug: str, data: bytes, content_type: str, ext: str) -> str:
)
service = BlobServiceClient.from_connection_string(connection_string)
container = service.get_container_client(container_name)
name = blob_name(slug, ext)
container.upload_blob(
name=name,
data=data,
overwrite=True,
# cache_control 은 ContentSettings 에 담아야 블롭 속성으로 실제로 박힌다.
content_settings=ContentSettings(content_type=content_type, cache_control=CACHE_CONTROL),
)
# cache_control 은 ContentSettings 에 담아야 블롭 속성으로 실제로 박힌다.
container.upload_blob(name=name, data=data, overwrite=True, content_settings=settings)
return name
async def store(slug: str, snapshot: dict) -> str | None:
async def store(slug: str, snapshot: dict, version: int | None = None) -> str | None:
"""대표 사진을 썸네일로 올리고 공개 URL 을 돌려준다. 못 하면 None(발행은 그대로 간다).
SDK 의 동기 I/O 는 별도 스레드에서 돈다 — azure_static.publish 와 같은 이유로,
@@ -153,4 +211,4 @@ async def store(slug: str, snapshot: dict) -> str | None:
return None
LOG.i(f"[thumbnail] {slug} → {name} ({len(data)} bytes · {content_type})")
return public_url(slug, ext)
return public_url(slug, ext, version)
+68 -34
View File
@@ -22,13 +22,14 @@ from sqlalchemy import or_, select
from common.category_schema import get_schema
from common.database.db_session_manager import DB_SESSION_MNG
from common.database.model.models import facts, faqs, local_contents, media, units
from common.database.model.models import facts, faqs, local_contents, media, place_contents, units
from common.enums import (
PUBLISHABLE_FACT_STATUSES,
DBWRType,
ErrorType,
FactStatus,
LocalContentStatus,
LocalSource,
MediaStatus,
PlaceCategory,
)
@@ -38,9 +39,9 @@ from services.external.naver import region_key
_PUBLISHABLE = tuple(s.value for s in PUBLISHABLE_FACT_STATUSES)
# 지역 정보를 종류별로 몇 건까지 박제할지.
# ★ 스냅샷은 site_versions.snapshot 에 통째로 들어간다. 지역 캐시는 region_code 단위 공용이라
# 한 지역에 수백 건이 쌓일 수 있고, 그걸 다 박제하면 버전 행마다 그만큼이 복사된다.
# 화면(LocalGuideSection)도 그만큼 보여주지 않는다 — 최근 수집분 위주로 자른다.
# ★ 종류별(맛집·관광지·축제·코스) 노출 상한 — 화면·캔버스·발행본 모두 이 수까지만 보여준다(2026-09-07 결정).
# 스냅샷은 site_versions.snapshot 에 통째로 들어가므로 반경 안 수백 건을 다 박제하면 버전 행마다 복사된다.
# 두 캐시(지역 수기 항목 + 업장 반경)를 **합쳐서** 센다 — 따로 세면 최대 40건이 나간다.
_LOCAL_MAX_PER_TYPE = 20
# 지역 원문(body)에서 스냅샷으로 옮기지 않는 키.
@@ -164,7 +165,11 @@ async def build_snapshot(place) -> dict:
async def _local_contents(place) -> dict:
"""사업장 지역의 노출 가능한 지역 정보. {"region_code", "contents":[...]}
"""사업장의 노출 가능한 지역·주변 정보. {"region_code", "contents":[...]}
두 캐시를 합친다 —
local_contents (region_code) 날씨 + 운영자가 수기로 발행한 항목
place_contents (place_id) TourAPI 반경 수집분(맛집·관광지·축제·여행코스). 숨김·종료된 것 제외
★ 노출 가능 = PUBLISHED + 노출 기간 안.
local_contents.status 는 운영 관리자의 검수 결과다(REVIEW=1 · PUBLISHED=2 · ENDED=3).
@@ -192,48 +197,77 @@ async def _local_contents(place) -> dict:
region_code = region_key(
str(getattr(place, "road_address", None) or getattr(place, "address", None) or "")
) or ""
if not region_code:
return {"region_code": None, "contents": []}
now = datetime.now(timezone.utc)
query = (
select(local_contents)
.where(
local_contents.region_code == region_code,
local_contents.deleted == False, # noqa: E712
local_contents.status == LocalContentStatus.PUBLISHED.value,
or_(local_contents.display_start_at.is_(None), local_contents.display_start_at <= now),
or_(local_contents.display_end_at.is_(None), local_contents.display_end_at > now),
)
.order_by(local_contents.content_type.asc(), local_contents.collected_at.desc())
)
err, rows = await DB_SESSION_MNG.execute_lambda(
local_contents.DBType(), DBWRType.DB_READ.value, lambda s: DB_SESSION_MNG.execute(s, query)
)
if err != ErrorType.SUCCESS:
# ★ 지역 정보가 없다고 발행을 막지 않는다 — 사업장의 사실이 아니라 곁들이는 정보다.
# 빈 채로 나가면 렌더러가 그 섹션을 아예 그리지 않는다.
LOG.w(f"[snapshot] 지역 정보 조회 실패 region={region_code}: {err.name}")
return {"region_code": region_code, "contents": []}
contents: list[dict] = []
seen: dict[int, int] = {} # 종류별 누적 건수 — 두 캐시를 합쳐 상한을 센다
seen: dict[int, int] = {}
contents = []
for row in rows or []:
# ── 지역 캐시(local_contents): 날씨 + 운영자가 수기로 발행한 항목 ──
if region_code:
query = (
select(local_contents)
.where(
local_contents.region_code == region_code,
local_contents.deleted == False, # noqa: E712
local_contents.status == LocalContentStatus.PUBLISHED.value,
or_(local_contents.display_start_at.is_(None), local_contents.display_start_at <= now),
or_(local_contents.display_end_at.is_(None), local_contents.display_end_at > now),
)
.order_by(local_contents.content_type.asc(), local_contents.collected_at.desc())
)
err, rows = await DB_SESSION_MNG.execute_lambda(
local_contents.DBType(), DBWRType.DB_READ.value, lambda s: DB_SESSION_MNG.execute(s, query)
)
if err != ErrorType.SUCCESS:
# ★ 지역 정보가 없다고 발행을 막지 않는다 — 사업장의 사실이 아니라 곁들이는 정보다.
LOG.w(f"[snapshot] 지역 정보 조회 실패 region={region_code}: {err.name}")
rows = []
contents += _local_rows(rows or [], seen)
# ── 업장 반경 캐시(place_contents): 맛집·관광지·축제·여행코스 ──
# ★ 정렬은 **사진 있는 것 우선 → 가까운 순**(2026-09-07 결정). 종류별 상한 안에 들려면
# 사진 없는 가까운 곳보다 사진 있는 조금 먼 곳이 이긴다 — 화면이 카드라 사진이 없으면 자리가 빈다.
place_id = getattr(place, "place_id", None)
if place_id is not None:
nearby_q = (
select(place_contents)
.where(
place_contents.place_id == place_id,
place_contents.deleted == False, # noqa: E712
place_contents.hidden == False, # noqa: E712
or_(place_contents.display_end_at.is_(None), place_contents.display_end_at > now),
)
.order_by(place_contents.content_type.asc(), place_contents.has_image.desc(), place_contents.distance_m.asc())
)
err, rows = await DB_SESSION_MNG.execute_lambda(
place_contents.DBType(), DBWRType.DB_READ.value, lambda s: DB_SESSION_MNG.execute(s, nearby_q)
)
if err != ErrorType.SUCCESS:
LOG.w(f"[snapshot] 주변 정보 조회 실패 place={place_id}: {err.name}")
rows = []
contents += _local_rows(rows or [], seen, source=LocalSource.TOUR_API.value)
return {"region_code": region_code or None, "contents": contents}
def _local_rows(rows, seen: dict[int, int], source: int | None = None) -> list[dict]:
"""행 → 스냅샷 항목. 종류별 상한(_LOCAL_MAX_PER_TYPE)은 들어온 순서(정렬)대로 자른다.
seen 은 호출측이 넘겨 두 캐시에 걸쳐 누적한다."""
out = []
for row in rows:
content_type = int(row.content_type)
# 종류별 상한. 위 order_by 가 collected_at 내림차순이라 최근 수집분이 남는다.
taken = seen.get(content_type, 0)
if taken >= _LOCAL_MAX_PER_TYPE:
continue
seen[content_type] = taken + 1
body = row.body if isinstance(row.body, dict) else {}
contents.append({
out.append({
"content_type": content_type,
"source": row.source,
"source": source if source is not None else row.source,
"title": row.title,
"body": {k: v for k, v in body.items() if k not in _LOCAL_BODY_DROP},
"collected_at": _iso(row.collected_at),
})
return {"region_code": region_code, "contents": contents}
return out
def _iso(value) -> str | None:
+3 -3
View File
@@ -28,10 +28,10 @@ class VisionAborted(RuntimeError):
async def run_vision(job: dict) -> dict:
"""VISION 잡 핸들러. payload: {place_id, company_id, force?}"""
"""VISION 잡 핸들러. payload: {place_id, owner_user_id, force?}"""
payload = job["payload"]
place_id = payload["place_id"]
company_id = payload["company_id"]
owner_user_id = payload["owner_user_id"]
force = bool(payload.get("force"))
if not gemini.is_configured():
@@ -40,7 +40,7 @@ async def run_vision(job: dict) -> dict:
err, place = await DB_SESSION_MNG.execute_lambda(
places.DBType(),
DBWRType.DB_READ.value,
lambda s: _place_crud.get_place(s, uuid.UUID(company_id), uuid.UUID(place_id)),
lambda s: _place_crud.get_place(s, uuid.UUID(owner_user_id), uuid.UUID(place_id)),
)
if err != ErrorType.SUCCESS or place is None:
raise VisionAborted(f"사업장을 찾을 수 없다: {place_id}")
+5 -5
View File
@@ -4,9 +4,9 @@
"""
async def test_login_and_me_flow(auth_headers, client, company_id):
async def test_login_and_me_flow(auth_headers, client):
"""검증: 시드된 유저가 로그인해 받은 토큰으로 /me 호출.
기대결과: 200, 본인 id·name·소속사(company_id)가 그대로 반환."""
기대결과: 200, 본인 id·name 이 그대로 반환."""
h = await auth_headers("user1", name="홍길동")
r = await client.get("/v1/auth/me", headers=h)
@@ -14,7 +14,8 @@ async def test_login_and_me_flow(auth_headers, client, company_id):
me = r.json()
assert me["id"] == "user1"
assert me["name"] == "홍길동"
assert me["company"]["company_id"] == company_id
# ★ 소속사 필드는 없다. 회사(테넌트)를 걷어냈다(2026-09-08) — 쓰는 사람은 사장님 혼자다.
assert "company" not in me
async def test_login_with_wrong_password(auth_headers, client):
@@ -49,7 +50,7 @@ _SIGNUP = {"id": "sajang1", "password": "pw12345678", "name": "김사장", "emai
async def test_signup_creates_account_and_logs_in(client, db_engine):
"""검증: 가입 → 받은 토큰으로 곧바로 /me.
기대결과: 토큰이 실려 오고, /me 가 방금 만든 신원과 **새로 생긴 소속사**를 돌려준다."""
기대결과: 토큰이 실려 오고, /me 가 방금 만든 신원을 돌려준다."""
r = await client.post("/v1/auth/signup", json=_SIGNUP)
body = r.json()
assert body["result"]["success"] is True
@@ -59,7 +60,6 @@ async def test_signup_creates_account_and_logs_in(client, db_engine):
assert me["id"] == "sajang1"
assert me["email"] == "boss@example.com"
assert me["provider"] == 1 # AuthProvider.LOCAL
assert me["company"]["name"] == "김사장" # 회사명 미입력 → 이름으로 채운다
async def test_signup_rejects_duplicate_id(client, db_engine):
+3 -3
View File
@@ -264,12 +264,12 @@ async def test_versions_accumulate(auth_headers, client, db_engine):
assert [v["version"] for v in versions] == [2, 1]
async def test_site_is_scoped_to_company(auth_headers, client, other_company_id):
"""검증: 다른 회사 계정으로 남의 사이트를 본다.
async def test_site_is_scoped_to_owner(auth_headers, client):
"""검증: 다른 사장님 계정으로 남의 사이트를 본다.
기대결과: PLACE_NOT_FOUND."""
h1 = await auth_headers("o1")
pid = await _place(client, h1, "스코프펜션")
h2 = await auth_headers("o2", other_company_id)
h2 = await auth_headers("o2")
r = await client.get(f"/v1/place/{pid}/site", headers=h2)
assert r.json()["result"]["code"] == ErrorType.PLACE_NOT_FOUND.value
+3 -3
View File
@@ -156,13 +156,13 @@ async def test_targeted_collect_payload_carries_requested_confirmed_link(auth_he
assert job["payload"]["link_ids"] == [confirmed]
async def test_collect_is_scoped_to_company(auth_headers, client, other_company_id):
"""검증: 다른 회사 계정으로 남의 사업장 수집을 시작한다.
async def test_collect_is_scoped_to_owner(auth_headers, client):
"""검증: 다른 사장님 계정으로 남의 사업장 수집을 시작한다.
기대결과: PLACE_NOT_FOUND — 사업장이 안 보이니 수집도 못 건다."""
h1 = await auth_headers("o1")
pid = await _place(client, h1, kakao="c7")
await _confirmed_link(client, h1, pid)
h2 = await auth_headers("o2", other_company_id)
h2 = await auth_headers("o2")
r = await client.post(f"/v1/place/{pid}/collect", headers=h2, json={})
assert r.json()["result"]["code"] == ErrorType.PLACE_NOT_FOUND.value
@@ -208,7 +208,7 @@ async def test_recollect_cannot_overwrite_corrected_value(auth_headers, client):
assert check_in[0]["status"] == FactStatus.CORRECTED.value
async def test_pipeline_refuses_unverified_place(db_engine, company_id):
async def test_pipeline_refuses_unverified_place(db_engine, owner_id):
"""검증: 검증 안 된 사업장의 수집 잡이 큐에 직접 들어간 경우(잡 적재 후 검증이 취소된 상황).
기대결과: 잡이 실패한다 — ★ 잡 실행 시점에도 게이트를 다시 확인한다."""
from sqlalchemy import text
@@ -216,13 +216,13 @@ async def test_pipeline_refuses_unverified_place(db_engine, company_id):
pid = uuid.uuid4()
async with db_engine.begin() as conn:
await conn.execute(
text("INSERT INTO places (place_id, company_id, name, category, status) "
text("INSERT INTO places (place_id, owner_user_id, name, category, status) "
"VALUES (:pid, :cid, :n, 1, 1)"),
{"pid": pid, "cid": uuid.UUID(company_id), "n": "미검증펜션"},
{"pid": pid, "cid": uuid.UUID(owner_id), "n": "미검증펜션"},
)
q = JobQueue()
job_id = await q.enqueue(JobType.COLLECT.value, {"place_id": str(pid), "company_id": company_id}, max_attempts=1)
job_id = await q.enqueue(JobType.COLLECT.value, {"place_id": str(pid), "owner_user_id": owner_id}, max_attempts=1)
worker = Worker("test-worker", q, build_handler(), backoff_fn=lambda _a: 0)
await worker.process_one()
+3 -3
View File
@@ -269,12 +269,12 @@ async def test_crawl_only_does_not_mark_rebuild(auth_headers, client):
assert place.get("content_updated_at") is None
async def test_facts_are_scoped_to_company(auth_headers, client, other_company_id):
"""검증: 다른 회사 계정으로 남의 사업장 fact 를 조회한다.
async def test_facts_are_scoped_to_owner(auth_headers, client):
"""검증: 다른 사장님 계정으로 남의 사업장 fact 를 조회한다.
기대결과: PLACE_NOT_FOUND — 사업장이 안 보이니 fact 도 안 보인다."""
h1 = await auth_headers("o1")
pid = await _verified_place(client, h1, kakao="p6")
h2 = await auth_headers("o2", other_company_id)
h2 = await auth_headers("o2")
r = await client.get(f"/v1/place/{pid}/fact/list", headers=h2)
assert r.json()["result"]["code"] == ErrorType.PLACE_NOT_FOUND.value
+15 -15
View File
@@ -22,17 +22,17 @@ from common.enums import (
)
async def _seed_place(db_engine, company_id) -> str:
async def _seed_place(db_engine, owner_id) -> str:
"""검증까지 끝난 사업장 1개를 시드하고 place_id 를 돌려준다."""
pid = uuid.uuid4()
async with db_engine.begin() as conn:
await conn.execute(
text(
"INSERT INTO places (place_id, company_id, name, category, status, external_place_id, verified_at) "
"INSERT INTO places (place_id, owner_user_id, name, category, status, external_place_id, verified_at) "
"VALUES (:pid, :cid, :name, :cat, :status, :kakao, now())"
),
{
"pid": pid, "cid": uuid.UUID(company_id), "name": "테스트펜션",
"pid": pid, "cid": uuid.UUID(owner_id), "name": "테스트펜션",
"cat": PlaceCategory.LODGING.value, "status": PlaceStatus.DRAFT.value,
"kakao": "12345678",
},
@@ -54,20 +54,20 @@ async def _insert_fact(db_engine, place_id, key, value, status, unit_id=None):
)
async def test_published_fact_is_unique_per_place_and_key(db_engine, company_id):
async def test_published_fact_is_unique_per_place_and_key(db_engine, owner_id):
"""검증: 같은 사업장·같은 key 로 노출 상태 fact 를 두 번 넣는다.
기대결과: 두 번째 INSERT 가 유니크 인덱스에 막힌다(체크인 시간이 두 값으로 갈라지지 않는다)."""
place_id = await _seed_place(db_engine, company_id)
place_id = await _seed_place(db_engine, owner_id)
await _insert_fact(db_engine, place_id, "check_in_time", "15:00", FactStatus.VERIFIED)
with pytest.raises(IntegrityError):
await _insert_fact(db_engine, place_id, "check_in_time", "16:00", FactStatus.CORRECTED)
async def test_candidates_coexist_with_published_value(db_engine, company_id):
async def test_candidates_coexist_with_published_value(db_engine, owner_id):
"""검증: 노출값이 있는 상태에서 재수집 후보를 여러 건 넣는다.
기대결과: 전부 공존한다 — ★ 재수집이 노출 중인 사실을 밀어내지 않는다."""
place_id = await _seed_place(db_engine, company_id)
place_id = await _seed_place(db_engine, owner_id)
await _insert_fact(db_engine, place_id, "check_in_time", "15:00", FactStatus.VERIFIED)
await _insert_fact(db_engine, place_id, "check_in_time", "16:00", FactStatus.PENDING_OWNER)
await _insert_fact(db_engine, place_id, "check_in_time", "14:00", FactStatus.UNVERIFIED)
@@ -80,10 +80,10 @@ async def test_candidates_coexist_with_published_value(db_engine, company_id):
assert len(rows) == 3, "노출값 1건 + 후보 2건이 공존해야 한다"
async def test_rejected_fact_frees_the_key(db_engine, company_id):
async def test_rejected_fact_frees_the_key(db_engine, owner_id):
"""검증: 기존 값을 REJECTED 로 내린 뒤 같은 key 를 새로 노출한다.
기대결과: 통과 — 틀린 값은 이력으로 남고, 새 값이 노출 자리를 차지한다."""
place_id = await _seed_place(db_engine, company_id)
place_id = await _seed_place(db_engine, owner_id)
await _insert_fact(db_engine, place_id, "check_in_time", "15:00", FactStatus.REJECTED)
await _insert_fact(db_engine, place_id, "check_in_time", "16:00", FactStatus.VERIFIED)
@@ -95,18 +95,18 @@ async def test_rejected_fact_frees_the_key(db_engine, company_id):
assert len(rows) == 2, "REJECTED 이력과 새 값이 함께 남아야 한다"
async def test_expired_fact_frees_the_key(db_engine, company_id):
async def test_expired_fact_frees_the_key(db_engine, owner_id):
"""검증: 유효기간이 지나 EXPIRED 로 내린 값과 새 수집값의 공존.
기대결과: 통과 — EXPIRED 도 유니크에서 빠진다."""
place_id = await _seed_place(db_engine, company_id)
place_id = await _seed_place(db_engine, owner_id)
await _insert_fact(db_engine, place_id, "cancel_policy", "구 규정", FactStatus.EXPIRED)
await _insert_fact(db_engine, place_id, "cancel_policy", "새 규정", FactStatus.VERIFIED)
async def test_same_key_allowed_across_units(db_engine, company_id):
async def test_same_key_allowed_across_units(db_engine, owner_id):
"""검증: 객실이 다르면 같은 key 를 각각 가질 수 있는지.
기대결과: 통과 — A동·B동이 각자의 기준 인원을 갖는다."""
place_id = await _seed_place(db_engine, company_id)
place_id = await _seed_place(db_engine, owner_id)
unit_a, unit_b = uuid.uuid4(), uuid.uuid4()
async with db_engine.begin() as conn:
for uid, name in ((unit_a, "A동"), (unit_b, "B동")):
@@ -122,10 +122,10 @@ async def test_same_key_allowed_across_units(db_engine, company_id):
await _insert_fact(db_engine, place_id, "standard_capacity", "6", FactStatus.CORRECTED, unit_id=unit_a)
async def test_unit_fact_and_place_fact_are_separate(db_engine, company_id):
async def test_unit_fact_and_place_fact_are_separate(db_engine, owner_id):
"""검증: 같은 key 를 사업장 단위와 객실 단위로 동시에 갖는 경우.
기대결과: 통과 — 부분 인덱스가 unit_id NULL 여부로 갈라져 있다."""
place_id = await _seed_place(db_engine, company_id)
place_id = await _seed_place(db_engine, owner_id)
unit_id = uuid.uuid4()
async with db_engine.begin() as conn:
await conn.execute(
+3 -3
View File
@@ -56,14 +56,14 @@ async def test_generated_faq_is_pending_and_not_publishable(auth_headers, client
assert (await _list(client, h, pid, publishable_only=True)).get("faqs", []) == []
async def test_other_company_cannot_read_or_touch_faq(auth_headers, client, db_engine, other_company_id):
"""검증: 남의 회사 사용자가 place_id 를 알아내 FAQ 를 조회·전이한다.
async def test_other_owner_cannot_read_or_touch_faq(auth_headers, client, db_engine):
"""검증: 남의 사용자가 place_id 를 알아내 FAQ 를 조회·전이한다.
기대결과: PLACE_NOT_FOUND — 존재 여부조차 알려주지 않는다."""
h = await auth_headers("u1")
pid = await _place(client, h)
fid = await _seed_generated_faq(db_engine, pid)
other = await auth_headers("u2", other_company_id)
other = await auth_headers("u2")
assert (await _list(client, other, pid))["result"]["code"] == ErrorType.PLACE_NOT_FOUND.value
body = await _transition(client, other, pid, fid, {"status": FactStatus.VERIFIED.value})
assert body["result"]["code"] == ErrorType.PLACE_NOT_FOUND.value
+40 -4
View File
@@ -3,7 +3,7 @@
이 경로가 절대 하면 안 되는 것:
- 사이트가 아직 없는 사업장을 빼는 것 — 위저드를 걸어오다 만 가게가 목록에서 사라지면
사장님은 그걸 다시 찾을 길이 없다(에디터 주소를 아무도 기억하지 않는다).
- 회사 스코프를 놓치는 것 — 남의 가게가 내 목록에 섞이면 그건 목록이 아니라 사고다.
- 사장님 스코프를 놓치는 것 — 남의 가게가 내 목록에 섞이면 그건 목록이 아니라 사고다.
- 단건(GET /v1/place/{id}/site)과 다른 재빌드 판정을 내는 것 — 목록과 에디터가 서로 다른
답을 하면 사장님은 어느 쪽을 믿을지 알 수 없다.
"""
@@ -53,11 +53,47 @@ async def test_site_row_is_joined_into_the_line(auth_headers, client):
assert row["status"] == SiteStatus.DRAFT.value
async def test_other_company_sites_are_not_listed(auth_headers, client, other_company_id):
"""검증: 회사(테넌트) 스코프. 남의 회사 사업장은 보이지 않는다.
async def test_row_carries_what_the_card_draws(auth_headers, client, db_engine):
"""검증: 목록 줄이 카드가 그릴 값을 다 들고 온다 — 주소·생성일·썸네일.
★ 왜 이걸 본다: 같은 상호로 만든 사업장이 여러 줄일 때(실측: 한 계정에 '버터브루' 4줄)
이름과 상태 배지만으로는 어느 게 어느 건지 가릴 수 없다. 가르는 값은 주소와 시각이고,
**한 번이라도 발행한 줄은 그림**이다."""
h = await auth_headers("my2b")
pid = await _place(client, h, "카드펜션")
async with db_engine.begin() as conn:
await conn.execute(
text("UPDATE places SET road_address = :addr WHERE place_id = :pid"),
{"addr": "강원특별자치도 양양군 현북면 하조대3길 12", "pid": uuid.UUID(pid)},
)
await conn.execute(
text("INSERT INTO sites (site_id, place_id, domain, status, thumbnail_url) "
"VALUES (:s, :p, :d, :st, :t)"),
{"s": uuid.uuid4(), "p": uuid.UUID(pid), "d": "card-stay",
"st": SiteStatus.PUBLISHED.value, "t": "https://w4ai.o2o.kr/thumbs/card-stay.jpg?v=2"},
)
row = (await _list(client, h))["sites"][0]
assert row["road_address"] == "강원특별자치도 양양군 현북면 하조대3길 12"
assert row["created_at"]
assert row["thumbnail_url"] == "https://w4ai.o2o.kr/thumbs/card-stay.jpg?v=2"
async def test_row_without_a_site_has_no_thumbnail(auth_headers, client):
"""검증: 아직 발행 안 한 줄은 그림이 없다(키 자체가 없다).
기대결과: 화면이 '그림 없음' 자리를 그릴 근거가 된다 — 빈 문자열로 오면 깨진 이미지가 뜬다."""
h = await auth_headers("my2c")
await _place(client, h, "그림없는펜션")
row = (await _list(client, h))["sites"][0]
assert "thumbnail_url" not in row
async def test_other_owners_sites_are_not_listed(auth_headers, client):
"""검증: 사장님 스코프. 남의 사업장은 보이지 않는다.
기대결과: 각자 자기 것만 1건."""
mine = await auth_headers("my3")
theirs = await auth_headers("my3b", other_company_id)
theirs = await auth_headers("my3b")
await _place(client, mine, "내펜션")
await _place(client, theirs, "남의펜션")
+6 -6
View File
@@ -1,8 +1,8 @@
"""places 도메인 e2e — 등록 / 동일 업소 검증 / 회사 스코프 / 채널 URL 확정 게이트.
"""places 도메인 e2e — 등록 / 동일 업소 검증 / 사장님 스코프 / 채널 URL 확정 게이트.
★ 이 도메인의 핵심 규칙 두 개를 고정한다:
1. 검증(verify) 전에는 채널 URL 을 확정할 수 없다 → 크롤링이 안 열린다
2. 남의 회사 사업장은 '없음'으로 보인다
2. 남의 사업장은 '없음'으로 보인다
"""
import uuid
@@ -61,7 +61,7 @@ async def test_verify_place_opens_collection(auth_headers, client):
async def test_duplicate_kakao_place_is_allowed(auth_headers, client):
"""검증: 같은 회사에서 같은 카카오 장소를 두 사업장에 붙인다.
"""검증: 같은 사장님이 같은 카카오 장소를 두 사업장에 붙인다.
기대결과: 둘 다 등록된다 — 한 사용자가 같은 실제 업장으로 여러 프로젝트를 만들 수 있다."""
h = await auth_headers("u1")
first = (await _create_place(client, h, "A펜션"))["place"]["place_id"]
@@ -138,13 +138,13 @@ async def test_verify_without_any_identifier_is_rejected(auth_headers, client):
assert r.json()["result"]["code"] == ErrorType.PLACE_VERIFY_NO_CANDIDATE.value
async def test_place_is_scoped_to_company(auth_headers, client, other_company_id):
"""검증: 다른 회사 계정으로 남의 사업장을 조회한다.
async def test_place_is_scoped_to_owner(auth_headers, client):
"""검증: 다른 사장님 계정으로 남의 사업장을 조회한다.
기대결과: PLACE_NOT_FOUND — 존재 자체가 보이지 않는다(IDOR 차단)."""
h1 = await auth_headers("owner1")
pid = (await _create_place(client, h1))["place"]["place_id"]
h2 = await auth_headers("owner2", other_company_id)
h2 = await auth_headers("owner2")
r = await client.get(f"/v1/place/{pid}", headers=h2)
assert r.json()["result"]["code"] == ErrorType.PLACE_NOT_FOUND.value
+1 -1
View File
@@ -80,7 +80,7 @@ async def test_search_leaks_nothing_of_ours(client, monkeypatch):
item = (await client.get("/v1/place/search", params={"q": "하조대펜션"})).json()["items"][0]
for leaked in ("place_id", "company_id", "owner_user_id", "phone", "latitude", "longitude",
for leaked in ("place_id", "owner_user_id", "phone", "latitude", "longitude",
"external_place_id", "address"):
assert leaked not in item, f"{leaked} 가 공개 응답에 나갔다"
+2 -2
View File
@@ -31,7 +31,7 @@ def test_empty_site_returns_actionable_failures():
assert any(c["status"] == "fail" and c["recommendation"] for c in report["checks"])
async def test_audit_api_is_company_scoped(auth_headers, client, other_company_id):
async def test_audit_api_is_owner_scoped(auth_headers, client):
h1 = await auth_headers("audit-owner")
pid = (await client.post("/v1/place", headers=h1, json={"name": "진단가게", "category": 2})).json()["place"]["place_id"]
@@ -41,6 +41,6 @@ async def test_audit_api_is_company_scoped(auth_headers, client, other_company_i
assert 0 <= own["aeo_score"] <= 100
assert own["checks"]
h2 = await auth_headers("audit-other", other_company_id)
h2 = await auth_headers("audit-other")
denied = (await client.get(f"/v1/place/{pid}/site/audit", headers=h2)).json()
assert denied["result"]["success"] is False
+13 -13
View File
@@ -13,14 +13,14 @@ from sqlalchemy import text
from common.enums import PlaceCategory, PlaceStatus, SiteStatus
async def _publish(db_engine, company_id, name, *, status, domain, thumb=None, minutes_ago=0):
async def _publish(db_engine, owner_id, name, *, status, domain, thumb=None, minutes_ago=0):
"""places + sites 를 직접 넣는다 — 여기서 보는 건 목록 조회지 빌드 파이프라인이 아니다."""
pid, sid = uuid.uuid4(), uuid.uuid4()
async with db_engine.begin() as c:
await c.execute(
text("INSERT INTO places (place_id, company_id, name, category, status, road_address, address, phone) "
text("INSERT INTO places (place_id, owner_user_id, name, category, status, road_address, address, phone) "
"VALUES (:p,:c,:n,:cat,:st,:road,:addr,:phone)"),
{"p": pid, "c": uuid.UUID(company_id), "n": name, "cat": PlaceCategory.LODGING.value,
{"p": pid, "c": uuid.UUID(owner_id), "n": name, "cat": PlaceCategory.LODGING.value,
"st": PlaceStatus.PUBLISHED.value,
"road": "강원특별자치도 양양군 현북면 하조대3길 12-3", "addr": "강원특별자치도 양양군 현북면 하광정리 1-2",
"phone": "033-672-0000"},
@@ -34,12 +34,12 @@ async def _publish(db_engine, company_id, name, *, status, domain, thumb=None, m
return str(pid)
async def test_발행된_사이트만_로그인_없이_보인다(client, db_engine, company_id):
async def test_발행된_사이트만_로그인_없이_보인다(client, db_engine, owner_id):
"""검증: 발행본 1개 + 미발행(DRAFT) 1개를 두고 인증 헤더 없이 부른다.
기대결과: 발행본만 나온다."""
await _publish(db_engine, company_id, "하조대펜션", status=SiteStatus.PUBLISHED.value,
await _publish(db_engine, owner_id, "하조대펜션", status=SiteStatus.PUBLISHED.value,
domain="hajodae", thumb="https://w4ai.o2o.kr/thumbs/hajodae.jpg")
await _publish(db_engine, company_id, "아직펜션", status=SiteStatus.DRAFT.value, domain="notyet")
await _publish(db_engine, owner_id, "아직펜션", status=SiteStatus.DRAFT.value, domain="notyet")
res = await client.get("/v1/showcase")
@@ -51,10 +51,10 @@ async def test_발행된_사이트만_로그인_없이_보인다(client, db_engi
assert items[0]["category"] == PlaceCategory.LODGING.value
async def test_개인정보와_내부값은_나가지_않는다(client, db_engine, company_id):
async def test_개인정보와_내부값은_나가지_않는다(client, db_engine, owner_id):
"""검증: 응답 항목의 키를 그대로 본다.
기대결과: 상호명·업종·지역·주소·썸네일뿐. 지역은 시·군까지고 상세 주소는 없다."""
await _publish(db_engine, company_id, "하조대펜션", status=SiteStatus.PUBLISHED.value, domain="hajodae")
await _publish(db_engine, owner_id, "하조대펜션", status=SiteStatus.PUBLISHED.value, domain="hajodae")
item = (await client.get("/v1/showcase")).json()["items"][0]
@@ -66,10 +66,10 @@ async def test_개인정보와_내부값은_나가지_않는다(client, db_engin
assert "하조대3길" not in body
async def test_썸네일이_없으면_키가_없다(client, db_engine, company_id):
async def test_썸네일이_없으면_키가_없다(client, db_engine, owner_id):
"""★ 썸네일은 발행의 부수 효과라 실패할 수 있다(대표 사진이 없거나 CDN 이 죽었거나).
그때 카드는 글자로 떨어져야지 목록에서 사라지면 안 된다."""
await _publish(db_engine, company_id, "그림없는집", status=SiteStatus.PUBLISHED.value, domain="nopic")
await _publish(db_engine, owner_id, "그림없는집", status=SiteStatus.PUBLISHED.value, domain="nopic")
item = (await client.get("/v1/showcase")).json()["items"][0]
@@ -77,9 +77,9 @@ async def test_썸네일이_없으면_키가_없다(client, db_engine, company_i
assert "thumbnail_url" not in item
async def test_최신_발행순이고_limit_로_자른다(client, db_engine, company_id):
await _publish(db_engine, company_id, "먼저", status=SiteStatus.PUBLISHED.value, domain="first", minutes_ago=60)
await _publish(db_engine, company_id, "나중", status=SiteStatus.PUBLISHED.value, domain="second", minutes_ago=1)
async def test_최신_발행순이고_limit_로_자른다(client, db_engine, owner_id):
await _publish(db_engine, owner_id, "먼저", status=SiteStatus.PUBLISHED.value, domain="first", minutes_ago=60)
await _publish(db_engine, owner_id, "나중", status=SiteStatus.PUBLISHED.value, domain="second", minutes_ago=1)
items = (await client.get("/v1/showcase")).json()["items"]
assert [i["name"] for i in items] == ["나중", "먼저"]
+3 -3
View File
@@ -129,11 +129,11 @@ async def test_published_site_slug_is_locked(auth_headers, client, db_engine):
assert same["site"]["domain"] == "published-stay"
async def test_other_company_place_is_blocked(auth_headers, client, other_company_id):
"""검증: 남의 회사 사업장 주소는 확인도 예약도 못 한다.
async def test_other_owners_place_is_blocked(auth_headers, client):
"""검증: 남의 사업장 주소는 확인도 예약도 못 한다.
기대결과: PLACE_NOT_FOUND(존재 여부조차 알려주지 않는다)."""
h = await auth_headers("slug5")
intruder = await auth_headers("slug6", other_company_id)
intruder = await auth_headers("slug6")
pid = await _place(client, h)
assert (await _check(client, intruder, pid, "doflo"))["result"]["code"] == ErrorType.PLACE_NOT_FOUND.value
+3 -3
View File
@@ -99,11 +99,11 @@ async def test_published_site_template_is_not_locked(auth_headers, client, db_en
assert changed["needs_rebuild"] is True
async def test_other_company_place_is_blocked(auth_headers, client, other_company_id):
"""검증: 남의 회사 사업장의 템플릿은 바꿀 수 없다.
async def test_other_owners_place_is_blocked(auth_headers, client):
"""검증: 남의 사업장의 템플릿은 바꿀 수 없다.
기대결과: PLACE_NOT_FOUND(존재 여부조차 알려주지 않는다)."""
h = await auth_headers("tpl6")
intruder = await auth_headers("tpl7", other_company_id)
intruder = await auth_headers("tpl7")
pid = await _place(client, h)
blocked = await _set_template(client, intruder, pid, "stay-quiet-margin")
+3 -3
View File
@@ -129,11 +129,11 @@ async def test_published_site_theme_is_not_locked(auth_headers, client, db_engin
assert changed["needs_rebuild"] is True
async def test_other_company_place_is_blocked(auth_headers, client, other_company_id):
"""검증: 남의 회사 사업장의 디자인은 바꿀 수 없다.
async def test_other_owners_place_is_blocked(auth_headers, client):
"""검증: 남의 사업장의 디자인은 바꿀 수 없다.
기대결과: PLACE_NOT_FOUND(존재 여부조차 알려주지 않는다)."""
h = await auth_headers("thm7")
intruder = await auth_headers("thm8", other_company_id)
intruder = await auth_headers("thm8")
pid = await _place(client, h)
assert (await _set_theme(client, intruder, pid, _THEME))["result"]["code"] == ErrorType.PLACE_NOT_FOUND.value
+16 -5
View File
@@ -110,9 +110,11 @@ async def test_사이트_디렉터리_밖의_thumbs_에_올린다(blob, monkeypa
_transport(monkeypatch, lambda req: httpx.Response(200, headers={"content-type": "image/jpeg"}, content=b"jpegbytes"))
snapshot = _snapshot({"media_id": "m1", "url": "https://cdn.test/front.jpg", "unit_id": None})
url = await site_thumbnail.store("butter", snapshot)
url = await site_thumbnail.store("butter", snapshot, 3)
assert url == "https://w4ai.o2o.kr/thumbs/butter.jpg"
# ★ `?v=` 는 캐시 무효화다. 블롭 이름은 그대로 덮어쓰므로 주소가 안 변하면
# 브라우저·CDN 이 지난 발행의 그림을 계속 보여준다(site_thumbnail.public_url).
assert url == "https://w4ai.o2o.kr/thumbs/butter.jpg?v=3"
name = f"{azure_static.DEFAULT_PREFIX}/thumbs/butter.jpg"
assert set(blob.uploads) == {name}
assert not name.startswith(f"{azure_static.DEFAULT_PREFIX}/{azure_static.SITE_ROOT_DIR}/")
@@ -131,8 +133,8 @@ async def test_발행하면_사이트에_썸네일_주소가_남는다(auth_head
from services import build_service
from tests.test_build_publish import _approved_media, _place, _run, _verified_facts
async def _store(slug, snapshot):
return f"https://w4ai.o2o.kr/thumbs/{slug}.jpg"
async def _store(slug, snapshot, version=None):
return f"https://w4ai.o2o.kr/thumbs/{slug}.jpg?v={version}"
monkeypatch.setattr(build_service.site_thumbnail, "store", _store)
@@ -146,6 +148,15 @@ async def test_발행하면_사이트에_썸네일_주소가_남는다(auth_head
site = (await client.get(f"/v1/place/{pid}/site", headers=h)).json()["site"]
assert site["thumbnail_url"].startswith("https://w4ai.o2o.kr/thumbs/")
assert site["thumbnail_url"].endswith("?v=1")
# ★ 재발행하면 주소가 바뀌어야 한다. 블롭 이름은 그대로 덮어쓰므로, 주소가 그대로면
# 사장님은 사진을 바꾸고 다시 발행해도 캐시에 남은 **지난 그림**을 계속 본다.
await client.post(f"/v1/place/{pid}/site/build", headers=h, json={"publish": True})
await _run()
again = (await client.get(f"/v1/place/{pid}/site", headers=h)).json()["site"]
assert again["thumbnail_url"].endswith("?v=2")
assert again["thumbnail_url"] != site["thumbnail_url"]
async def test_썸네일을_못_만들어도_발행은_성공한다(auth_headers, client, db_engine, monkeypatch):
@@ -154,7 +165,7 @@ async def test_썸네일을_못_만들어도_발행은_성공한다(auth_headers
from services import build_service
from tests.test_build_publish import _approved_media, _place, _run, _verified_facts
async def _store(slug, snapshot):
async def _store(slug, snapshot, version=None):
return None
monkeypatch.setattr(build_service.site_thumbnail, "store", _store)
+25 -25
View File
@@ -10,13 +10,13 @@ from common.enums import FactStatus, MediaStatus, PlaceCategory, SourceType
from services.snapshot import build_snapshot
async def _seed(db_engine, company_id, category=PlaceCategory.LODGING):
async def _seed(db_engine, owner_id, category=PlaceCategory.LODGING):
pid = uuid.uuid4()
async with db_engine.begin() as c:
await c.execute(
text("INSERT INTO places (place_id, company_id, name, category, status, road_address, phone, verified_at) "
text("INSERT INTO places (place_id, owner_user_id, name, category, status, road_address, phone, verified_at) "
"VALUES (:p,:c,:n,:cat,3,:addr,:tel,now())"),
{"p": pid, "c": uuid.UUID(company_id), "n": "스냅샷펜션", "cat": category.value,
{"p": pid, "c": uuid.UUID(owner_id), "n": "스냅샷펜션", "cat": category.value,
"addr": "강원특별자치도 양양군 현북면 하조대3길 11", "tel": "033-000-0000"},
)
return pid
@@ -53,10 +53,10 @@ class _Place:
self.longitude = None
async def test_only_publishable_facts_enter_snapshot(db_engine, company_id):
async def test_only_publishable_facts_enter_snapshot(db_engine, owner_id):
"""검증: 여러 상태의 fact 를 섞어 넣는다.
기대결과: ★ VERIFIED·CORRECTED 만 스냅샷에 담긴다 — 미검증 값이 사이트로 새지 않는다."""
pid = await _seed(db_engine, company_id)
pid = await _seed(db_engine, owner_id)
await _fact(db_engine, pid, "check_in_time", "15:00", FactStatus.VERIFIED)
await _fact(db_engine, pid, "wifi", "true", FactStatus.CORRECTED)
await _fact(db_engine, pid, "parking", "true", FactStatus.UNVERIFIED)
@@ -69,10 +69,10 @@ async def test_only_publishable_facts_enter_snapshot(db_engine, company_id):
assert keys == {"check_in_time", "wifi"}
async def test_only_approved_media_enters_snapshot(db_engine, company_id):
async def test_only_approved_media_enters_snapshot(db_engine, owner_id):
"""검증: 승인/확인대기/반려 사진을 섞어 넣는다.
기대결과: ★ APPROVED 만 담긴다 — Vision 신뢰도가 낮아 확인 큐에 남은 사진은 안 나간다."""
pid = await _seed(db_engine, company_id)
pid = await _seed(db_engine, owner_id)
await _media(db_engine, pid, "https://cdn.test/ok.jpg", MediaStatus.APPROVED)
await _media(db_engine, pid, "https://cdn.test/pending.jpg", MediaStatus.PENDING_REVIEW)
await _media(db_engine, pid, "https://cdn.test/no.jpg", MediaStatus.REJECTED)
@@ -81,10 +81,10 @@ async def test_only_approved_media_enters_snapshot(db_engine, company_id):
assert [m["url"] for m in snap["media"]] == ["https://cdn.test/ok.jpg"]
async def test_media_without_alt_is_excluded(db_engine, company_id):
async def test_media_without_alt_is_excluded(db_engine, owner_id):
"""검증: 승인됐지만 alt 텍스트가 없는 사진.
기대결과: 빠진다 — alt 없는 이미지는 접근성도 AI 검색 신호도 없다."""
pid = await _seed(db_engine, company_id)
pid = await _seed(db_engine, owner_id)
await _media(db_engine, pid, "https://cdn.test/noalt.jpg", MediaStatus.APPROVED, alt="")
await _media(db_engine, pid, "https://cdn.test/withalt.jpg", MediaStatus.APPROVED, alt="침실 사진")
@@ -92,10 +92,10 @@ async def test_media_without_alt_is_excluded(db_engine, company_id):
assert [m["url"] for m in snap["media"]] == ["https://cdn.test/withalt.jpg"]
async def test_fact_labels_come_from_category_schema(db_engine, company_id):
async def test_fact_labels_come_from_category_schema(db_engine, owner_id):
"""검증: 스냅샷의 fact 라벨.
기대결과: 업종 스키마의 한글 라벨이 붙는다 — 화면이 key 를 그대로 노출하지 않게."""
pid = await _seed(db_engine, company_id)
pid = await _seed(db_engine, owner_id)
await _fact(db_engine, pid, "check_in_time", "15:00", FactStatus.VERIFIED)
snap = await build_snapshot(_Place(pid))
@@ -104,10 +104,10 @@ async def test_fact_labels_come_from_category_schema(db_engine, company_id):
assert f["scope"] == "place"
async def test_unit_scoped_facts_carry_unit_id(db_engine, company_id):
async def test_unit_scoped_facts_carry_unit_id(db_engine, owner_id):
"""검증: 객실 단위 fact.
기대결과: unit_id 가 실려 빌더가 객실별로 묶을 수 있다."""
pid = await _seed(db_engine, company_id)
pid = await _seed(db_engine, owner_id)
uid = uuid.uuid4()
async with db_engine.begin() as c:
await c.execute(text("INSERT INTO units (unit_id, place_id, name, sort_order) VALUES (:u,:p,:n,0)"),
@@ -120,10 +120,10 @@ async def test_unit_scoped_facts_carry_unit_id(db_engine, company_id):
assert snap["facts"][0]["scope"] == "unit"
async def test_empty_place_gives_empty_snapshot(db_engine, company_id):
async def test_empty_place_gives_empty_snapshot(db_engine, owner_id):
"""검증: 아무것도 없는 사업장.
기대결과: 빈 스냅샷 — 게이트가 고유 콘텐츠 0건으로 거부할 재료가 된다."""
pid = await _seed(db_engine, company_id)
pid = await _seed(db_engine, owner_id)
snap = await build_snapshot(_Place(pid))
assert snap["facts"] == [] and snap["media"] == [] and snap["faqs"] == []
assert snap["place"]["name"] == "스냅샷펜션"
@@ -156,13 +156,13 @@ class _RegionPlace(_Place):
self.region_code = region_code
async def test_only_published_local_content_enters_snapshot(db_engine, company_id):
async def test_only_published_local_content_enters_snapshot(db_engine, owner_id):
"""검증: 검수대기·종료·발행 지역 정보를 섞어 넣는다.
기대결과: ★ PUBLISHED 만 담긴다 — 운영자가 검수하지 않은 외부 API 원문이 사이트로 새면
'미검증 값 노출 금지'가 깨진다(fact 를 VERIFIED 로 거르는 것과 같은 규칙)."""
from common.enums import LocalContentStatus, LocalContentType
pid = await _seed(db_engine, company_id)
pid = await _seed(db_engine, owner_id)
await _local(db_engine, "4113500", LocalContentType.FESTIVAL, LocalContentStatus.PUBLISHED, "발행축제")
await _local(db_engine, "4113500", LocalContentType.FESTIVAL, LocalContentStatus.REVIEW, "검수대기축제")
await _local(db_engine, "4113500", LocalContentType.FESTIVAL, LocalContentStatus.ENDED, "종료축제")
@@ -171,7 +171,7 @@ async def test_only_published_local_content_enters_snapshot(db_engine, company_i
assert [c["title"] for c in snap["local"]["contents"]] == ["발행축제"]
async def test_local_content_outside_display_window_is_excluded(db_engine, company_id):
async def test_local_content_outside_display_window_is_excluded(db_engine, owner_id):
"""검증: 발행됐지만 노출 기간을 벗어난 지역 정보.
기대결과: 빠진다 — 끝난 축제를 '이번 주말 행사'로 걸어두는 것도 틀린 정보다."""
from datetime import datetime, timedelta, timezone
@@ -179,7 +179,7 @@ async def test_local_content_outside_display_window_is_excluded(db_engine, compa
from common.enums import LocalContentStatus, LocalContentType
now = datetime.now(timezone.utc)
pid = await _seed(db_engine, company_id)
pid = await _seed(db_engine, owner_id)
await _local(db_engine, "4113500", LocalContentType.FESTIVAL, LocalContentStatus.PUBLISHED, "지금축제")
await _local(db_engine, "4113500", LocalContentType.FESTIVAL, LocalContentStatus.PUBLISHED, "끝난축제",
display_end_at=now - timedelta(days=1))
@@ -190,12 +190,12 @@ async def test_local_content_outside_display_window_is_excluded(db_engine, compa
assert [c["title"] for c in snap["local"]["contents"]] == ["지금축제"]
async def test_local_content_is_scoped_to_the_places_region(db_engine, company_id):
async def test_local_content_is_scoped_to_the_places_region(db_engine, owner_id):
"""검증: 지역 캐시는 region_code 로 묶인다.
기대결과: 다른 지역의 발행 콘텐츠는 담기지 않는다."""
from common.enums import LocalContentStatus, LocalContentType
pid = await _seed(db_engine, company_id)
pid = await _seed(db_engine, owner_id)
await _local(db_engine, "4113500", LocalContentType.FESTIVAL, LocalContentStatus.PUBLISHED, "우리지역축제")
await _local(db_engine, "5011025", LocalContentType.FESTIVAL, LocalContentStatus.PUBLISHED, "남의지역축제")
@@ -203,7 +203,7 @@ async def test_local_content_is_scoped_to_the_places_region(db_engine, company_i
assert [c["title"] for c in snap["local"]["contents"]] == ["우리지역축제"]
async def test_region_code_is_derived_from_the_address_when_missing(db_engine, company_id):
async def test_region_code_is_derived_from_the_address_when_missing(db_engine, owner_id):
"""검증: region_code 가 비어 있지만 도로명주소는 있는 사업장.
기대결과: 주소에서 지역 키를 유도해 그 지역 콘텐츠를 담는다 — places.region_code 를 채우는
코드가 생기기 전에 만들어진 사업장(실측 28곳 중 25곳)이 영영 지역 정보 없이 발행되지 않게 한다."""
@@ -211,7 +211,7 @@ async def test_region_code_is_derived_from_the_address_when_missing(db_engine, c
from services.external.naver import region_key
derived = region_key(_Place("x").road_address)
pid = await _seed(db_engine, company_id)
pid = await _seed(db_engine, owner_id)
await _local(db_engine, derived, LocalContentType.FESTIVAL, LocalContentStatus.PUBLISHED, "양양축제")
snap = await build_snapshot(_RegionPlace(pid, ""))
@@ -219,12 +219,12 @@ async def test_region_code_is_derived_from_the_address_when_missing(db_engine, c
assert [c["title"] for c in snap["local"]["contents"]] == ["양양축제"]
async def test_place_without_any_region_key_gets_no_local_content(db_engine, company_id):
async def test_place_without_any_region_key_gets_no_local_content(db_engine, owner_id):
"""검증: 지역 코드도 읽을 만한 주소도 없는 사업장.
기대결과: 빈 목록 — 조회할 캐시 키가 없다. 지어내지 않는다."""
from common.enums import LocalContentStatus, LocalContentType
pid = await _seed(db_engine, company_id)
pid = await _seed(db_engine, owner_id)
await _local(db_engine, "4113500", LocalContentType.FESTIVAL, LocalContentStatus.PUBLISHED, "어딘가축제")
place = _RegionPlace(pid, "")
@@ -136,13 +136,13 @@ async def test_candidates_require_configured_source(auth_headers, client, monkey
assert body["result"]["code"] == ErrorType.LOCAL_NOT_CONFIGURED.value
async def test_candidates_scoped_to_company(auth_headers, client, other_company_id, monkeypatch):
"""검증: 다른 회사 계정으로 남의 사업장 후보를 조회한다.
async def test_candidates_scoped_to_owner(auth_headers, client, monkeypatch):
"""검증: 다른 사장님 계정으로 남의 사업장 후보를 조회한다.
기대결과: PLACE_NOT_FOUND."""
_patch_naver(monkeypatch, _match(kakao_client.MatchOutcome.MATCHED, _np("a", "b"), [], "x"))
h1 = await auth_headers("o1")
pid = await _place(client, h1)
h2 = await auth_headers("o2", other_company_id)
h2 = await auth_headers("o2")
body = (await client.get(f"/v1/place/{pid}/verify/candidates", headers=h2)).json()
assert body["result"]["code"] == ErrorType.PLACE_NOT_FOUND.value
+2
View File
@@ -0,0 +1,2 @@
User-agent: *
Disallow: /admin/
+10
View File
@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url>
<loc>https://web4ai.o2osolution.ai/</loc>
<lastmod>2026-08-12T00:00:00+09:00</lastmod>
<priority>1.0</priority>
</url>
</urlset>
@@ -1,11 +0,0 @@
/**
* Generated by orval v7.21.0 🍺
* Do not edit manually.
* Web4Ai API
* OpenAPI spec version: 0.1.0
*/
export interface CompanyData {
company_id?: string;
name?: string;
}
@@ -10,7 +10,6 @@ export * from './auditCheckDataRecommendation';
export * from './authProvider';
export * from './buildStatus';
export * from './checkSlugParams';
export * from './companyData';
export * from './errorInfo';
export * from './errorInfoCode';
export * from './errorInfoDesc';
@@ -83,6 +82,7 @@ export * from './mySiteData';
export * from './mySiteDataCreatedAt';
export * from './mySiteDataDomain';
export * from './mySiteDataPublishedAt';
export * from './mySiteDataThumbnailUrl';
export * from './mySiteDataRoadAddress';
export * from './mySiteDataSiteId';
export * from './mySiteDataStatus';
@@ -139,7 +139,6 @@ export * from './reqGoogleLogin';
export * from './reqLogin';
export * from './reqPublishLocalContent';
export * from './reqSignup';
export * from './reqSignupCompanyName';
export * from './reqSignupName';
export * from './reqSiteSlug';
export * from './reqSiteStatus';
@@ -222,7 +221,6 @@ export * from './resLocalContentListMsg';
export * from './resLogin';
export * from './resLoginMsg';
export * from './resMe';
export * from './resMeCompany';
export * from './resMeContactNumber';
export * from './resMeEmail';
export * from './resMeMsg';
@@ -13,6 +13,7 @@ import type { MySiteDataStatus } from './mySiteDataStatus';
import type { MySiteDataDomain } from './mySiteDataDomain';
import type { MySiteDataTemplateId } from './mySiteDataTemplateId';
import type { MySiteDataPublishedAt } from './mySiteDataPublishedAt';
import type { MySiteDataThumbnailUrl } from './mySiteDataThumbnailUrl';
/**
* 내 사이트 목록의 한 줄 — 사업장(place) + 사이트(site).
@@ -32,5 +33,7 @@ export interface MySiteData {
domain?: MySiteDataDomain;
template_id?: MySiteDataTemplateId;
published_at?: MySiteDataPublishedAt;
/** 목록 카드의 그림. 발행에 성공해야 채워지고, 발행마다 `?v=` 가 바뀐다(site_thumbnail.public_url). */
thumbnail_url?: MySiteDataThumbnailUrl;
needs_rebuild?: boolean;
}
@@ -5,4 +5,4 @@
* OpenAPI spec version: 0.1.0
*/
export type ReqSignupCompanyName = string | null;
export type MySiteDataThumbnailUrl = string | null;
@@ -11,7 +11,7 @@ import type { PlaceSearchItemCategory } from './placeSearchItemCategory';
/**
* 공개 검색 결과 1건.
★ 외부 장소 DB 가 공개적으로 주는 값만 담는다. 우리 DB 값(place_id·company_id·소유자)은
★ 외부 장소 DB 가 공개적으로 주는 값만 담는다. 우리 DB 값(place_id·소유자)은
하나도 나가지 않는다 — 로그인 없이 열려 있는 응답이라 여기에 우리 것을 실으면 그대로 샌다.
★ 좌표·전화번호도 뺐다. 랜딩이 하는 일은 '어느 가게인지 고르게 하는 것'뿐이고,
확정과 수집은 로그인 뒤 기존 경로(POST /place → verify)가 그대로 한다.
@@ -5,10 +5,9 @@
* OpenAPI spec version: 0.1.0
*/
import type { ReqSignupName } from './reqSignupName';
import type { ReqSignupCompanyName } from './reqSignupCompanyName';
/**
* id/pw 가입. 가입 = 새 테넌트(회사) 1개 + 그 회사의 첫 계정 1개다.
* id/pw 가입. 가입 = 계정 1개다.
★ 이메일을 필수로 받는 이유: 같은 이메일이 이미 구글로 가입돼 있는지 판단할 근거가 없으면
한 사람에게 계정이 둘 생긴다. 지금 이메일 인증 절차는 없다 — 소유 증명이 아니라
@@ -19,5 +18,4 @@ export interface ReqSignup {
password?: string;
name?: ReqSignupName;
email?: string;
company_name?: ReqSignupCompanyName;
}
@@ -11,7 +11,6 @@ import type { ResMeEmail } from './resMeEmail';
import type { ResMeContactNumber } from './resMeContactNumber';
import type { UserRole } from './userRole';
import type { AuthProvider } from './authProvider';
import type { ResMeCompany } from './resMeCompany';
export interface ResMe {
result?: ErrorInfo;
@@ -23,5 +22,4 @@ export interface ResMe {
contact_number?: ResMeContactNumber;
role?: UserRole;
provider?: AuthProvider;
company?: ResMeCompany;
}
@@ -1,9 +0,0 @@
/**
* Generated by orval v7.21.0 🍺
* Do not edit manually.
* Web4Ai API
* OpenAPI spec version: 0.1.0
*/
import type { CompanyData } from './companyData';
export type ResMeCompany = CompanyData | null;
@@ -12,7 +12,7 @@ import type { ShowcaseItemThumbnailUrl } from './showcaseItemThumbnailUrl';
* 랜딩 쇼케이스 카드 한 장. **로그인 없이 나가는 값이다.**
★ 여기 있는 것은 전부 이미 발행된 페이지에 적혀 있는 것뿐이다.
place_id·company_id·전화번호·상세 주소는 절대 싣지 않는다 — 사이트 한 곳을 여는 것과
place_id·소유자·전화번호·상세 주소는 절대 싣지 않는다 — 사이트 한 곳을 여는 것과
발행 업소 명단을 통째로 긁는 것은 다른 일이다. 지역도 시·군·구까지만 준다.
*/
export interface ShowcaseItem {
@@ -82,7 +82,6 @@ export function AppShell({children, nav = OWNER_NAV}: {children: ReactNode; nav?
className="mb-2 block truncate rounded-md px-2 py-1 text-[11px] text-sidebar-foreground transition-colors hover:bg-sidebar-accent/60"
>
{userLabel(user)}
{user.companyName ? ` · ${user.companyName}` : ''}
</Link>
) : (
<div className="mb-2 truncate px-2 py-1 text-[11px] text-sidebar-foreground">
@@ -0,0 +1,205 @@
import {useCallback, useEffect, useRef, useState, type ReactNode} from 'react';
import {ArrowUpRight, ChevronLeft, ChevronRight} from 'lucide-react';
import type {TemplateItem} from '@o2o/shared';
import {cn} from '@/lib/utils';
import type {GuideCard} from '../variants/local/types';
import {walkMinutes} from '../variants/local/walking';
const naverSearch = (q: string) =>
`https://search.naver.com/search.naver?query=${encodeURIComponent(q)}`;
/**
* 가이드 카드 한 장 — 사진(좌하단 "도보 약 N분 850m" 배지) · 이름 · 설명 2줄 · "검색으로 열기".
*
* ★ 사진이 없으면 회색 판에 이름을 크게 쓴다(스크린샷의 '군산복집' 카드). 자리를 비우거나
* 남의 사진을 채우지 않는다 — 카드 폭이 들쭉날쭉해지면 캐러셀이 흔들린다.
* ★ 거리를 모르면 배지를 생략한다. "도보 N분"은 업장 기준 직선거리에서만 계산한다.
*/
function GuideCardView({card, colors, leading}: {card: GuideCard; colors: TemplateItem['colors']; leading?: ReactNode}) {
const minutes = card.distanceMeters !== undefined ? walkMinutes(card.distanceMeters) : undefined;
return (
<a
href={naverSearch(card.searchQuery)}
target="_blank"
rel="noopener noreferrer"
onClick={(e) => e.stopPropagation()}
className="group flex w-[240px] shrink-0 snap-start flex-col overflow-hidden rounded-lg border border-stone-200/80 bg-white shadow-2xs transition-shadow hover:shadow-md sm:w-[260px]"
>
<div className="relative aspect-[4/3] w-full overflow-hidden bg-stone-200/70">
{card.imageUrl ? (
<img
src={card.imageUrl}
alt={card.name}
loading="lazy"
className="size-full object-cover transition-transform duration-300 group-hover:scale-[1.03]"
/>
) : (
<div className="flex size-full items-center justify-center px-4 text-center">
<span className="serif-title text-base font-bold text-stone-700">{card.name}</span>
</div>
)}
{minutes !== undefined && (
<span className="absolute bottom-2.5 left-2.5 inline-flex items-center gap-1.5 rounded bg-stone-900/80 px-2 py-1 text-[11px] font-semibold text-white backdrop-blur-sm">
<span>도보 약 {minutes}분</span>
{card.distanceText && <span className="font-mono font-normal text-white/75">{card.distanceText}</span>}
</span>
)}
</div>
<div className="flex flex-1 flex-col gap-1.5 p-3.5">
{leading}
<h4 className="text-sm font-bold text-stone-900" style={{color: colors.text}}>
{card.name}
</h4>
{card.description && (
<p className="line-clamp-2 text-xs leading-relaxed text-stone-500">{card.description}</p>
)}
<span className="mt-auto flex items-center gap-0.5 pt-1 text-[11px] font-medium text-stone-400 group-hover:text-stone-900">
검색으로 열기
<ArrowUpRight className="size-3" />
</span>
</div>
</a>
);
}
/**
* 카드 캐러셀 — 가로 스크롤(스냅) + 좌우 화살표 + 점 페이지네이션 + "1 / N".
*
* ★ 페이지 = 한 화면에 온전히 들어가는 카드 수. 미리보기 해상도(PC/태블릿/모바일)가 바뀌면
* ResizeObserver 가 다시 센다 — 고정 4장으로 두면 모바일에서 점이 카드 수와 어긋난다.
* ★ 화살표는 컨테이너 폭만큼 넘긴다(한 페이지). 한 장씩 넘기면 24장에 화살표 23번이다.
*/
export function PlaceCarousel({
cards,
colors,
renderLeading,
}: {
cards: GuideCard[];
colors: TemplateItem['colors'];
/** 카드 이름 위에 얹을 배지(축제의 "10월" 등). */
renderLeading?: (card: GuideCard) => ReactNode;
}) {
const trackRef = useRef<HTMLDivElement>(null);
const [perPage, setPerPage] = useState(1);
const [page, setPage] = useState(0);
const pages = Math.max(1, Math.ceil(cards.length / perPage));
// 카드 한 장 폭(gap 포함)으로 한 화면에 몇 장 들어가는지 잰다.
const measure = useCallback(() => {
const track = trackRef.current;
const first = track?.firstElementChild as HTMLElement | null;
if (!track || !first) return;
const gap = parseFloat(getComputedStyle(track).columnGap || '0') || 0;
const step = first.offsetWidth + gap;
const fit = Math.max(1, Math.floor((track.clientWidth + gap) / step));
setPerPage(fit);
setPage(Math.min(Math.round(track.scrollLeft / (step * fit)), Math.max(0, Math.ceil(cards.length / fit) - 1)));
}, [cards.length]);
useEffect(() => {
measure();
const track = trackRef.current;
if (!track) return;
const ro = new ResizeObserver(measure);
ro.observe(track);
return () => ro.disconnect();
}, [measure]);
// 필터가 바뀌어 카드가 줄면 첫 페이지로.
useEffect(() => {
trackRef.current?.scrollTo({left: 0});
setPage(0);
}, [cards]);
const scrollToPage = (next: number) => {
const track = trackRef.current;
if (!track) return;
const clamped = Math.max(0, Math.min(pages - 1, next));
track.scrollTo({left: clamped * track.clientWidth, behavior: 'smooth'});
setPage(clamped);
};
const onScroll = () => {
const track = trackRef.current;
if (!track || track.clientWidth === 0) return;
setPage(Math.max(0, Math.min(pages - 1, Math.round(track.scrollLeft / track.clientWidth))));
};
const arrow =
'flex size-9 cursor-pointer items-center justify-center rounded-full border transition-colors disabled:cursor-default disabled:opacity-30';
return (
<div className="space-y-3">
<div className="flex items-center justify-end gap-2">
<button
type="button"
aria-label="이전"
disabled={page === 0}
onClick={(e) => {
e.stopPropagation();
scrollToPage(page - 1);
}}
className={cn(arrow, 'border-stone-300/70 bg-white/70 text-stone-500 hover:bg-white')}
>
<ChevronLeft className="size-4" />
</button>
<button
type="button"
aria-label="다음"
disabled={page >= pages - 1}
onClick={(e) => {
e.stopPropagation();
scrollToPage(page + 1);
}}
style={{borderColor: colors.text, color: colors.text}}
className={cn(arrow, 'bg-white hover:bg-stone-50')}
>
<ChevronRight className="size-4" />
</button>
</div>
<div
ref={trackRef}
onScroll={onScroll}
className="scrollbar-none flex snap-x snap-mandatory gap-4 overflow-x-auto pb-1"
>
{cards.map((card) => (
<GuideCardView
key={`${card.name}-${card.distanceMeters ?? ''}`}
card={card}
colors={colors}
leading={renderLeading?.(card)}
/>
))}
</div>
{pages > 1 && (
<div className="flex items-center justify-center gap-3">
<div className="flex items-center gap-1.5">
{Array.from({length: pages}, (_, i) => (
<button
key={i}
type="button"
aria-label={`${i + 1}페이지`}
onClick={(e) => {
e.stopPropagation();
scrollToPage(i);
}}
className={cn(
'h-1.5 cursor-pointer rounded-full transition-all',
i === page ? 'w-5' : 'w-1.5 bg-stone-300 hover:bg-stone-400',
)}
style={i === page ? {backgroundColor: colors.text} : undefined}
/>
))}
</div>
<span className="font-mono text-[11px] text-stone-400">
{page + 1} / {pages}
</span>
</div>
)}
</div>
);
}
@@ -0,0 +1,58 @@
import type {TemplateItem} from '@o2o/shared';
import {cn} from '@/lib/utils';
import {
WALK_FILTERS,
matchesWalkFilter,
type WalkFilterKey,
} from '../variants/local/walking';
/**
* 도보 시간 필터 탭 — "전체 24 · 걸어서 5분 이내 8 · 10분 이내 19 · 10분 이상 5".
*
* ★ 구간은 누적이다(walking.ts 주석). 그래서 숫자가 서로 더해져 전체가 되지 않는다 —
* "5분 이내" ⊂ "10분 이내". 배타 구간으로 바꾸면 라벨("이내")과 숫자가 어긋난다.
* ★ 상태는 부르는 쪽(카테고리 섹션)이 든다. 섹션마다 필터가 따로 움직여야 한다.
*/
export function WalkFilterTabs({
distances,
value,
onChange,
colors,
}: {
/** 항목별 거리(m). 모르는 항목은 undefined — '전체'에만 센다. */
distances: (number | undefined)[];
value: WalkFilterKey;
onChange: (key: WalkFilterKey) => void;
colors: TemplateItem['colors'];
}) {
return (
<div className="flex flex-wrap items-center gap-2" role="tablist" aria-label="도보 시간 필터">
{WALK_FILTERS.map(({key, label}) => {
const count = distances.filter((m) => matchesWalkFilter(key, m)).length;
const active = key === value;
return (
<button
key={key}
type="button"
role="tab"
aria-selected={active}
onClick={(e) => {
e.stopPropagation();
onChange(key);
}}
style={active ? {backgroundColor: colors.text, borderColor: colors.text} : undefined}
className={cn(
'flex cursor-pointer items-center gap-1.5 rounded-full border px-3.5 py-1.5 text-xs font-semibold transition-colors',
active
? 'text-white'
: 'border-stone-300/80 bg-white/70 text-stone-700 hover:bg-white',
)}
>
<span>{label}</span>
<span className={cn('font-mono text-[11px]', active ? 'text-white/80' : 'text-stone-400')}>{count}</span>
</button>
);
})}
</div>
);
}
@@ -12,6 +12,8 @@ export {EmptyStateNotice} from './EmptyStateNotice';
export {PhotoTile, type TilePhoto} from './PhotoTile';
export {Lightbox} from './Lightbox';
export {PlaceRow, ListCard} from './PlaceRow';
export {PlaceCarousel} from './PlaceCarousel';
export {WalkFilterTabs} from './WalkFilterTabs';
export {PriceRow, type PricedItem} from './PriceRow';
export {AddressCard} from './AddressCard';
export {FeatureCard} from './FeatureCard';
@@ -28,9 +28,7 @@ import {PhotosWithVideos} from './variants/photos/PhotosWithVideos';
import {MapDetailed} from './variants/map/MapDetailed';
import {MapCompact} from './variants/map/MapCompact';
import {LocalFull} from './variants/local/LocalFull';
import {LocalTabs} from './variants/local/LocalTabs';
import {LocalCompact} from './variants/local/LocalCompact';
import {LocalGuide} from './variants/local/LocalGuide';
import {WeatherSection} from './variants/weather/WeatherSection';
import {FaqAccordion} from './variants/faq/FaqAccordion';
@@ -208,29 +206,17 @@ export const SECTION_VARIANTS: Record<string, SectionVariant[]> = {
},
],
// ★ 전체/탭/요약 세 개를 하나로 통일했다(2026-09-07). 저장된 옛 id(local.tabs·local.compact)는
// resolveVariant 가 기본값으로 떨어뜨리므로 기존 사이트가 깨지지 않는다.
local: [
{
id: 'local.full',
name: '전체',
description: '날씨 + 맛집 + 명소 + 축제를 전부 세로로.',
id: 'local.guide',
name: '가이드',
description: '맛집 · 명소 · 축제를 도보 시간으로 걸러 카드로 넘겨 본다.',
thumb: 'stack',
Component: LocalFull,
Component: LocalGuide,
isDefault: true,
},
{
id: 'local.tabs',
name: '탭 전환',
description: '맛집/명소/축제를 탭으로. 화면 길이를 1/3 로 줄인다.',
thumb: 'accordion',
Component: LocalTabs,
},
{
id: 'local.compact',
name: '요약',
description: '날씨 한 줄과 추천 6곳만. 주인공이 아닐 때.',
thumb: 'compact',
Component: LocalCompact,
},
],
weather: [
@@ -1,27 +0,0 @@
import {useEffect, useState} from 'react';
/** "실시간 업데이트: 오후 4:41:56" 표시. 1초마다 갱신된다. */
export function LiveClock() {
const [clock, setClock] = useState('');
useEffect(() => {
const update = () => {
const now = new Date();
const period = now.getHours() >= 12 ? '오후' : '오전';
const hours = now.getHours() % 12 || 12;
const minutes = String(now.getMinutes()).padStart(2, '0');
const seconds = String(now.getSeconds()).padStart(2, '0');
setClock(`${period} ${hours}:${minutes}:${seconds}`);
};
update();
const timer = setInterval(update, 1000);
return () => clearInterval(timer);
}, []);
return (
<span className="flex items-center gap-1.5 rounded-full border border-stone-200/80 bg-white px-2.5 py-1 text-[11px] text-stone-500 shadow-2xs">
<span className="size-1.5 animate-pulse rounded-full bg-emerald-500" />
<span>실시간 업데이트: {clock}</span>
</span>
);
}
@@ -0,0 +1,61 @@
/**
* 지역 가이드 · 카테고리 한 묶음 — 제목(아이콘) → 도보 시간 필터 → 카드 캐러셀.
*
* 맛집·명소·축제가 전부 이 모양이다. 필터 상태는 묶음마다 따로 든다 —
* 맛집을 "5분 이내"로 걸렀는데 명소까지 줄어들면 사장님이 명소가 사라진 줄 안다.
*/
import {useState, type ReactNode} from 'react';
import type {LucideIcon} from 'lucide-react';
import type {TemplateItem} from '@o2o/shared';
import {EmptyStateNotice, PlaceCarousel, WalkFilterTabs} from '../../primitives';
import type {GuideCard} from './types';
import {matchesWalkFilter, type WalkFilterKey} from './walking';
export function LocalCategorySection({
icon: Icon,
title,
cards,
emptyText,
colors,
renderLeading,
}: {
icon: LucideIcon;
title: string;
cards: GuideCard[];
emptyText: string;
colors: TemplateItem['colors'];
renderLeading?: (card: GuideCard) => ReactNode;
}) {
const [filter, setFilter] = useState<WalkFilterKey>('all');
const visible = cards.filter((c) => matchesWalkFilter(filter, c.distanceMeters));
return (
<section className="space-y-4">
<h3
className="flex items-center gap-2 text-sm font-bold text-stone-900"
style={{color: colors.text}}
>
<Icon className="size-4" style={{color: colors.primary}} />
<span>{title}</span>
</h3>
{cards.length === 0 ? (
<EmptyStateNotice>{emptyText}</EmptyStateNotice>
) : (
<>
<WalkFilterTabs
distances={cards.map((c) => c.distanceMeters)}
value={filter}
onChange={setFilter}
colors={colors}
/>
{visible.length === 0 ? (
<EmptyStateNotice>이 거리 안에는 아직 없습니다. 다른 구간을 눌러 보세요.</EmptyStateNotice>
) : (
<PlaceCarousel cards={visible} colors={colors} renderLeading={renderLeading} />
)}
</>
)}
</section>
);
}
@@ -1,50 +0,0 @@
/**
* 지역 가이드 · 요약 — 날씨 한 줄과 추천 6곳만.
* 지역 정보가 주인공이 아닌 사이트에서 "있긴 하다" 정도로 둘 때.
*/
import {
EmptyStateNotice,
ListCard,
PlaceRow,
SectionBody,
SectionFrame,
SectionHeading,
} from '../../primitives';
import type {SectionRenderProps} from '../../types';
const naverSearch = (q: string) =>
`https://search.naver.com/search.naver?query=${encodeURIComponent(q)}`;
export function LocalCompact(props: SectionRenderProps) {
const {section, isSelected, onSelect, location, template} = props;
// 맛집·명소를 섞어 딱 6개만. 목록이 길어지면 요약이 아니게 된다.
// ★ 지역 정보는 서버(local.local_contents)가 소유하고 캔버스 계약(SectionRenderProps)에 없다.
// 시연용 목록(제주 애월)으로 자리를 메우지 않는다 — 남의 동네 맛집이 사장님 사이트에 붙는다.
const picks: {name: string; meta: string; description: string; q: string}[] = [];
return (
<SectionFrame section={section} isSelected={isSelected} onSelect={onSelect} tone="paper">
<SectionBody width="narrow">
<SectionHeading variant="minimal" title="주변 안내" colors={template.colors} />
{picks.length === 0 ? (
<EmptyStateNotice>주변 추천은 아직 준비 중입니다.</EmptyStateNotice>
) : (
<ListCard>
{picks.map((p) => (
<PlaceRow
key={p.name}
name={p.name}
meta={p.meta}
description={p.description}
href={naverSearch(p.q)}
actionLabel="보기"
colors={template.colors}
/>
))}
</ListCard>
)}
</SectionBody>
</SectionFrame>
);
}
@@ -1,163 +0,0 @@
/**
* 지역 가이드 · 전체 — 날씨 카드 + 맛집 + 명소 + 월별 축제를 세로로 전부.
* "여기 오면 근처에 뭐가 있나"를 한 화면에서 다 보여주고 싶을 때.
*/
import {Calendar, MapPin, Sparkles, Utensils} from 'lucide-react';
import type {TemplateItem} from '@o2o/shared';
import {
EmptyStateNotice,
ListCard,
PlaceRow,
Pill,
SectionBody,
SectionFrame,
SectionHeading,
} from '../../primitives';
import type {SectionRenderProps} from '../../types';
import {LiveClock} from './LiveClock';
import type {FestivalItem, NearbyPlace} from './types';
const naverSearch = (q: string) =>
`https://search.naver.com/search.naver?query=${encodeURIComponent(q)}`;
function GroupHeading({
icon: Icon,
title,
note,
colors,
}: {
icon: typeof Utensils;
title: string;
note: string;
colors: TemplateItem['colors'];
}) {
return (
<div className="flex items-center justify-between">
<h3
className="serif-title flex items-center gap-2 text-base font-bold text-stone-900 sm:text-lg"
style={{color: colors.text}}
>
<Icon className="size-4 text-stone-600" style={{color: colors.primary}} />
<span>{title}</span>
</h3>
{/* 오른쪽 출처 문구는 부가 정보라 중립 회색 그대로 둔다. */}
<span className="text-[11px] text-stone-400">{note}</span>
</div>
);
}
export function LocalFull(props: SectionRenderProps) {
const {section, isSelected, onSelect, industryId, location, template} = props;
const isStay = industryId === 'stay';
const locName = location.split(' ')[0] || '주변';
// ★ 맛집·명소·축제는 전부 제주 애월 시연용 목록이다 — 실사업장은 빈 목록으로 떨어진다.
// (지역 큐레이션을 읽어올 백엔드 창구가 아직 없어 당분간 계속 빈다.)
// 지역 정보는 서버(local.local_contents)가 소유하고 캔버스 계약에 없다 — 시연용 목록을 깔지 않는다.
const foods: NearbyPlace[] = [];
const spots: NearbyPlace[] = [];
const festivals: FestivalItem[] = [];
return (
<SectionFrame section={section} isSelected={isSelected} onSelect={onSelect} tone="paper">
<SectionBody className="space-y-8">
<SectionHeading
variant="eyebrow"
eyebrow="AI Local Guide"
title={`AI ${locName} 실시간 가이드`}
subtitle="실시간 날씨와 인근 미식·명소·축제를 AI가 큐레이션합니다"
trailing={<LiveClock />}
colors={template.colors}
/>
<div className="space-y-3.5">
<GroupHeading
icon={Utensils}
title="숙소 인근 엄선 맛집 & 카페"
note="호스트 & 네이버 플레이스 연동"
colors={template.colors}
/>
{foods.length === 0 ? (
<EmptyStateNotice>주변 맛집·카페 추천은 아직 준비 중입니다.</EmptyStateNotice>
) : (
<ListCard>
{foods.map((place) => (
<PlaceRow
key={place.name}
name={place.name}
meta={place.distance}
description={place.description}
href={naverSearch(place.searchQuery)}
colors={template.colors}
/>
))}
</ListCard>
)}
</div>
<div className="space-y-3.5">
<GroupHeading
icon={MapPin}
title="주변 힐링 명소 & 해변"
note="차량 5~20분 거리"
colors={template.colors}
/>
{spots.length === 0 ? (
<EmptyStateNotice>주변 명소 추천은 아직 준비 중입니다.</EmptyStateNotice>
) : (
<ListCard>
{spots.map((spot) => (
<PlaceRow
key={spot.name}
name={spot.name}
meta={spot.duration}
description={spot.description}
href={naverSearch(spot.searchQuery)}
actionLabel="상세정보"
colors={template.colors}
/>
))}
</ListCard>
)}
</div>
{isStay && (
<div className="space-y-3.5">
<GroupHeading
icon={Calendar}
title="월별 축제 & 문화 행사"
note="사계절 캘린더"
colors={template.colors}
/>
{festivals.length === 0 ? (
<EmptyStateNotice>월별 축제 안내는 아직 준비 중입니다.</EmptyStateNotice>
) : (
<ListCard>
{festivals.map((fest) => (
<PlaceRow
key={fest.name}
name={fest.name}
description={fest.description || fest.period}
href={naverSearch(fest.searchQuery)}
actionLabel="검색"
leading={
<>
<Pill tone="accent">{fest.month}</Pill>
{fest.isFeatured && (
<Pill tone="good">
<Sparkles className="size-2.5" />
대표축제
</Pill>
)}
</>
}
colors={template.colors}
/>
))}
</ListCard>
)}
</div>
)}
</SectionBody>
</SectionFrame>
);
}
@@ -0,0 +1,88 @@
/**
* 지역 가이드 — 맛집 · 명소 · 축제를 카테고리별 "도보 시간 필터 + 카드 캐러셀"로 세로 나열.
*
* ★ 2026-09-07 결정으로 전체/탭/요약 세 배리에이션을 이 하나로 통일했다.
* 데이터가 이미 카테고리별로 나뉘어 있어 "탭으로 갈아끼우기"라는 구분이 캐러셀 구조에서는
* 의미가 없어졌고, 요약(6곳)은 필터가 그 역할을 대신한다.
* ★ 값은 서버(local.place_contents)가 소유한다 — 업장 좌표 반경으로 받은 것만 그린다.
* 시연용 목록으로 자리를 메우지 않는다(남의 동네 맛집이 사장님 사이트에 붙는다).
*/
import {Calendar, MapPin, Utensils} from 'lucide-react';
import {useLocalGuide} from '@/hooks/useLocalGuide';
import {Pill, SectionBody, SectionFrame, SectionHeading} from '../../primitives';
import type {SectionRenderProps} from '../../types';
import type {FestivalCard, GuideCard} from './types';
import {LocalCategorySection} from './LocalCategorySection';
import {WALK_DISCLAIMER} from './walking';
/** "2026년 9월 3일 갱신" — 서버 수집 시각(ISO)에서. 없으면 비운다(지어내지 않는다). */
function syncedLabel(iso?: string): string | undefined {
if (!iso) return undefined;
const d = new Date(iso);
if (Number.isNaN(d.getTime())) return undefined;
return `${d.getFullYear()}년 ${d.getMonth() + 1}월 ${d.getDate()}일 갱신`;
}
/** "전북특별자치도 군산시 …" → "군산시". 시군구 토큰이 없으면 첫 토큰. */
function regionLabel(location: string): string {
const tokens = location.split(' ').filter(Boolean);
return tokens[1] ?? tokens[0] ?? '주변';
}
export function LocalGuide(props: SectionRenderProps) {
const {section, isSelected, onSelect, industryId, location, template} = props;
const {foods, spots, festivals, syncedAt} = useLocalGuide();
const colors = template.colors;
const isStay = industryId === 'stay';
const synced = syncedLabel(syncedAt);
return (
<SectionFrame section={section} isSelected={isSelected} onSelect={onSelect} tone="paper">
<SectionBody width="wide" className="space-y-10">
<SectionHeading
title={section.name || '주변 안내'}
subtitle={`${regionLabel(location)} 지역의 맛집 · 명소 안내입니다.`}
trailing={synced && <span className="text-xs text-stone-400">{synced}</span>}
colors={colors}
/>
<LocalCategorySection
icon={Utensils}
title="주변 맛집"
cards={foods}
emptyText="주변 맛집·카페 추천은 아직 준비 중입니다."
colors={colors}
/>
<LocalCategorySection
icon={MapPin}
title="주변 명소"
cards={spots}
emptyText="주변 명소 추천은 아직 준비 중입니다."
colors={colors}
/>
{isStay && (
<LocalCategorySection
icon={Calendar}
title="주변 축제 & 문화 행사"
cards={festivals}
emptyText="주변 축제 안내는 아직 준비 중입니다."
colors={colors}
renderLeading={(card: GuideCard) => {
const fest = card as FestivalCard;
return (
<div className="flex flex-wrap items-center gap-1.5">
{fest.month && <Pill tone="accent">{fest.month}</Pill>}
{fest.period && <Pill mono>{fest.period}</Pill>}
</div>
);
}}
/>
)}
<p className="text-[11px] leading-relaxed text-stone-400">{WALK_DISCLAIMER}</p>
</SectionBody>
</SectionFrame>
);
}
@@ -1,124 +0,0 @@
/**
* 지역 가이드 · 탭 — 맛집/명소/축제를 탭으로 갈아 끼운다.
* 목록이 길어 스크롤이 부담스러울 때 화면 길이를 1/3 로 줄인다.
*/
import {useState} from 'react';
import {Calendar, MapPin, Utensils} from 'lucide-react';
import {cn} from '@/lib/utils';
import {
EmptyStateNotice,
ListCard,
Pill,
PlaceRow,
SectionBody,
SectionFrame,
SectionHeading,
} from '../../primitives';
import type {SectionRenderProps} from '../../types';
import type {FestivalItem, NearbyPlace} from './types';
const naverSearch = (q: string) =>
`https://search.naver.com/search.naver?query=${encodeURIComponent(q)}`;
type TabKey = 'food' | 'spots' | 'festivals';
const TABS: {key: TabKey; label: string; icon: typeof Utensils}[] = [
{key: 'food', label: '맛집 · 카페', icon: Utensils},
{key: 'spots', label: '명소', icon: MapPin},
{key: 'festivals', label: '축제', icon: Calendar},
];
export function LocalTabs(props: SectionRenderProps) {
const {section, isSelected, onSelect, industryId, location, template} = props;
const [tab, setTab] = useState<TabKey>('food');
const isStay = industryId === 'stay';
const tabs = isStay ? TABS : TABS.filter((t) => t.key !== 'festivals');
const locName = location.split(' ')[0] || '주변';
// ★ 세 탭 모두 제주 애월 시연용 목록이다 — 실사업장은 빈 목록으로 떨어진다.
// 지역 정보는 서버(local.local_contents)가 소유하고 캔버스 계약에 없다 — 시연용 목록을 깔지 않는다.
const foods: NearbyPlace[] = [];
const spots: NearbyPlace[] = [];
const festivals: FestivalItem[] = [];
// 탭을 눌렀는데 아무것도 없으면 섹션이 사라진 것처럼 보인다 — 자리는 지키고 상태만 알린다.
const isEmpty = (tab === 'food' ? foods : tab === 'spots' ? spots : festivals).length === 0;
return (
<SectionFrame section={section} isSelected={isSelected} onSelect={onSelect} tone="paper">
<SectionBody>
<SectionHeading
variant="eyebrow"
eyebrow="AI Local Guide"
title={`AI ${locName} 실시간 가이드`}
subtitle="탭을 눌러 원하는 정보만 보세요"
colors={template.colors}
/>
<div className="flex items-center gap-1 rounded-xl border border-stone-200/80 bg-white p-1">
{tabs.map(({key, label, icon: Icon}) => (
<button
key={key}
type="button"
onClick={(e) => {
e.stopPropagation();
setTab(key);
}}
aria-pressed={tab === key}
style={tab === key ? {backgroundColor: template.colors.primary} : undefined}
className={cn(
'flex flex-1 cursor-pointer items-center justify-center gap-1.5 rounded-lg py-2 text-xs font-semibold transition-colors',
tab === key ? 'text-white' : 'text-stone-500 hover:bg-stone-100',
)}
>
<Icon className="size-3.5" />
<span>{label}</span>
</button>
))}
</div>
{isEmpty ? (
<EmptyStateNotice>주변 정보는 아직 준비 중입니다.</EmptyStateNotice>
) : (
<ListCard>
{tab === 'food' &&
foods.map((place) => (
<PlaceRow
key={place.name}
name={place.name}
meta={place.distance}
description={place.description}
href={naverSearch(place.searchQuery)}
colors={template.colors}
/>
))}
{tab === 'spots' &&
spots.map((spot) => (
<PlaceRow
key={spot.name}
name={spot.name}
meta={spot.duration}
description={spot.description}
href={naverSearch(spot.searchQuery)}
actionLabel="상세정보"
colors={template.colors}
/>
))}
{tab === 'festivals' &&
festivals.map((fest) => (
<PlaceRow
key={fest.name}
name={fest.name}
description={fest.description || fest.period}
href={naverSearch(fest.searchQuery)}
actionLabel="검색"
leading={<Pill tone="accent">{fest.month}</Pill>}
colors={template.colors}
/>
))}
</ListCard>
)}
</SectionBody>
</SectionFrame>
);
}
@@ -1,32 +1,26 @@
/**
* 지역 정보 항목의 모양.
* 지역 가이드 카드 한 장의 모양(맛집·명소·축제 공통).
*
* ★ 원래 이 타입들은 시연용 데이터 파일(data/stayData.ts)이 소유했다. 그 파일을 지우면서
* 실제로 쓰는 쪽인 여기로 옮겼다 — 타입이 데이터 시드에 매여 있을 이유가 없다.
*
* ★ 값은 서버(local.local_contents)가 소유한다. 지금은 캔버스 계약(SectionRenderProps)에
* 지역 정보가 없어서 배리에이션들이 빈 목록을 그린다. 흘려보낼 창구가 생기면
* 이 모양에 맞춰 매핑하면 된다.
* ★ 값은 서버(local.place_contents)가 소유한다. hooks/useLocalGuide 가 GET /v1/local/guide
* 응답(발행 payload 와 같은 모양)을 이 타입으로 매핑한다.
* ★ 도보 시간 배지·필터는 distanceMeters 로 계산한다(walking.ts::walkMinutes, 분속 80m).
* distanceMeters 가 없으면(지역 캐시에서 온 수기 항목 등) 배지·필터 대상에서 빠진다 —
* 업장 기준 거리를 모르는 값으로 "도보 N분"을 지어내지 않는다.
*/
export interface NearbyPlace {
export interface GuideCard {
name: string;
category: string;
/** 거리 표기("차로 5분", "1.2km") — 원문 그대로 옮긴다. */
distance: string;
duration: string;
description: string;
/** 상세 페이지 대신 검색으로 보낸다 — 없는 주소를 지어내지 않기 위해서다. */
searchQuery: string;
tag: string;
imageUrl?: string;
distanceMeters?: number;
/** 화면 배지에 그대로 쓰는 거리 문자열("850m"/"1.2km"). */
distanceText?: string;
}
export interface FestivalItem {
/** 축제는 기간·월 배지가 더 붙는다. */
export interface FestivalCard extends GuideCard {
month: string;
name: string;
period: string;
location: string;
description: string;
isFeatured?: boolean;
officialUrl?: string;
searchQuery: string;
}
@@ -0,0 +1,36 @@
/**
* 도보 시간 환산 — 직선거리(m) → 분.
*
* ★ 분속 80m 로 나눈다(보통 걸음 4.8km/h). 스크린샷 문구와 같은 기준이며 화면 하단에도 그대로 적는다:
* "도보 시간은 숙소에서 잰 직선거리를 분속 80m 로 환산한 값입니다. 실제로 걷는 길은 이보다 길 수 있습니다."
* ★ 실측 검증(2026-09-07): 135m→2분 · 297m→4분 · 305m→4분 · 566m→7분 · 13m→1분 — 반올림 + 최소 1분.
*/
export const WALK_METERS_PER_MINUTE = 80;
export const WALK_DISCLAIMER =
`도보 시간은 숙소에서 잰 직선거리를 분속 ${WALK_METERS_PER_MINUTE}m 로 환산한 값입니다. 실제로 걷는 길은 이보다 길 수 있습니다.`;
export function walkMinutes(meters: number): number {
return Math.max(1, Math.round(meters / WALK_METERS_PER_MINUTE));
}
/**
* 도보 시간 필터. ★ 구간은 배타적이 아니라 **누적**이다 — "10분 이내"는 "5분 이내"를 포함한다.
* (스크린샷 수치 8·19·5 → 19+5=24=전체 로 확인. "5분 이내"는 "10분 이내"의 부분집합.)
*/
export type WalkFilterKey = 'all' | 'within5' | 'within10' | 'over10';
export const WALK_FILTERS: {key: WalkFilterKey; label: string; test: (minutes: number) => boolean}[] = [
{key: 'all', label: '전체', test: () => true},
{key: 'within5', label: '걸어서 5분 이내', test: (m) => m <= 5},
{key: 'within10', label: '걸어서 10분 이내', test: (m) => m <= 10},
{key: 'over10', label: '걸어서 10분 이상', test: (m) => m > 10},
];
/** 거리를 모르는 항목은 '전체'에만 들어간다 — 모르는 값으로 구간을 정하지 않는다. */
export function matchesWalkFilter(key: WalkFilterKey, meters: number | undefined): boolean {
if (key === 'all') return true;
if (meters === undefined) return false;
const filter = WALK_FILTERS.find((f) => f.key === key);
return filter ? filter.test(walkMinutes(meters)) : true;
}
@@ -315,9 +315,7 @@ export const TOKEN_AWARE_VARIANT_IDS = new Set([
'photos.with-videos',
'map.detailed',
'map.compact',
'local.full',
'local.tabs',
'local.compact',
'local.guide',
'faq.accordion',
'faq.open-list',
'faq.two-column',
@@ -320,8 +320,20 @@ export function Step3DataReview() {
가게만 채널을 긁을 수 있습니다 — 2단계에서 지도 검색으로 가게를 확인하시면
주소 붙여넣기와 자동 찾기가 모두 열립니다.
</p>
{/* ★ 이 길로 나가면 **발행까지 못 간다** — 서버에 사업장이 없어서 구울 대상이
없고, 발행 모달은 [내 가게 확인하러 가기] 만 내놓는다(PublishModal
PlaceFirstPanel). 예전에는 아무 말 없이 통과시켜서, 사장님은 사이트를 다
만든 뒤 발행을 누르는 자리에서야 그 사실을 알았다.
버튼은 남긴다 — 검증을 못 통과한 분이 화면을 구경할 길까지 막지는 않는다. */}
<p className="rounded-xl border border-border bg-muted/40 p-3 text-[11px] leading-relaxed text-muted-foreground">
<strong className="text-foreground">
이대로 진행하면 화면은 만들 수 있지만 발행은 되지 않습니다.
</strong>{' '}
발행본은 확인된 가게 한 곳에 묶여서, 가게 확인 전에는 만들어 둘 페이지가
없습니다. 둘러보신 뒤 언제든 가게를 확인하시면 그때 발행이 열립니다.
</p>
<Button variant="outline" className="w-full" onClick={() => goToStep('template')}>
<span>수집 없이 다음 단계로</span>
<span>발행 없이 화면만 둘러보기</span>
<ArrowRight />
</Button>
</>
@@ -1,21 +1,29 @@
import {useCallback, useEffect, useMemo, useState} from 'react';
import {useNavigate} from 'react-router';
import {
AlertTriangle,
ArrowUpRight,
Check,
Copy,
ExternalLink,
Eye,
Loader2,
RefreshCw,
Search,
ServerCrash,
ShieldAlert,
Store,
} from 'lucide-react';
import {publishUrlString, toSlug} from '@o2o/shared';
import {getAccessToken} from '@/api';
import {Badge} from '@/components/ui/badge';
import {Button} from '@/components/ui/button';
import {Dialog} from '@/components/ui/dialog';
import {SignInForm} from '@/features/auth/SignInForm';
import type {WizardStep} from '@/features/onboarding/wizardUrl';
import {notify, notifyApiError} from '@/lib/notify';
import {cn} from '@/lib/utils';
import {useAuthStore} from '@/stores/auth';
import {useBuilderStore} from '@/stores/builder';
import {runPublishGate, type GateFinding} from './publishGate';
import {checkSiteSlug, reserveSiteSlug} from './siteSlug';
@@ -34,6 +42,27 @@ import {
// 화면의 모듈 최상위 코드도 빌드 때 한 번 실행된다 — 여기서 window 를 만지면 빌드가 죽는다.
// (PUBLISH_HOST 는 @/lib/site 가 유일한 출처다)
/**
* 가게 확인이 안 끝난 사장님을 돌려보낼 곳.
*
* ★ 단계 이름은 wizardUrl 이 소유한다 — 문자열을 그냥 박아 두면 이름이 바뀌는 날
* 주소창의 step 을 아무도 못 알아보고 조용히 첫 화면이 열린다(defaultStep).
*/
const PLACE_SEARCH_STEP: WizardStep = 'search';
const PLACE_SEARCH_URL = `/builder?step=${PLACE_SEARCH_STEP}`;
/**
* 발행을 **시작조차 할 수 없는** 상태. 서버를 부를 수 없으므로 발행 버튼을 그리지 않는다.
*
* ★ 예전에는 이 두 경우가 [지금 발행하기] 로 그대로 흘러 들어와, 서버를 한 번도 부르지 않고
* 성공 토스트를 띄운 뒤 [사이트 열기] 까지 그렸다. 그 주소는 아무것도 굽지 않은 주소라
* 404 였고 내 사이트 목록에도 없었다 — 사장님만 발행됐다고 믿는 상태가 남았다.
* ★ 'place' 가 진짜 함정이다. 로그인은 했는데(에디터 관문을 지났다) 3단계의
* [발행 없이 화면만 둘러보기] 로 나오면 서버에 사업장이 없다 — 화면은 끝까지 도는데
* 발행만 안 된다.
*/
type PublishBlocker = 'signin' | 'place';
export function PublishModal() {
const isOpen = useBuilderStore((s) => s.isPublishModalOpen);
const close = useBuilderStore((s) => s.closePublishModal);
@@ -57,11 +86,28 @@ export function PublishModal() {
/**
* 실사업장이면 진짜 빌드를 태운다(`POST /site/build {publish:true}` → 잡 폴링).
* ★ placeId 가 없는 데모 경로는 예전처럼 주소만 확정한다 — 없는 사업장을 서버에 빌드시킬 수 없다.
* ★ 그럴 수 없는 상태(로그인 전 · 사업장 미확정)에서는 발행 버튼 자체를 그리지 않는다.
* PublishBlocker 주석 참고.
*/
const publisher = usePublishSite(placeId);
const {state, reset} = publisher;
const navigate = useNavigate();
/*
* ★ 토큰은 스토어 밖(custom-fetch)에 있어 구독할 수 없다. 로그인이 auth 스토어의 user 도
* 함께 심으므로(lib/session.establishSession) 그걸 **재렌더 신호로만** 구독한다 —
* 없으면 아래 로그인 폼으로 로그인을 마쳐도 모달은 계속 "로그인해 주세요" 로 남는다.
*/
useAuthStore((s) => s.user);
/** 판정 기준은 usePublishSite.isLive 와 같다(placeId + 토큰) — 갈리면 버튼과 실제가 어긋난다. */
const blocker: PublishBlocker | null = publisher.isLive
? null
: getAccessToken()
? 'place'
: 'signin';
const gate = useMemo(
() =>
runPublishGate({
@@ -110,7 +156,12 @@ export function PublishModal() {
if (!isOpen) reset();
}, [isOpen, reset]);
const isDone = state.phase === 'published' || (!publisher.isLive && Boolean(publishedUrl));
/**
* ★ 서버가 발행을 확정한 것만 '발행됨'이다.
* 예전에는 `!isLive && publishedUrl` 도 완료로 쳤는데, 그 publishedUrl 을 채우던 것이
* 서버를 한 번도 부르지 않는 가짜 경로였다 — 굽지도 않은 주소에 [사이트 열기] 가 붙었다.
*/
const isDone = state.phase === 'published';
/**
* 이미 한 번 발행한 사이트인가 — 문구를 '발행'과 '재발행'으로 가른다.
@@ -149,25 +200,22 @@ export function PublishModal() {
}, [slug, placeId]);
const handlePublish = async () => {
if (!gate.canPublish || publisher.isPublishing || !slugReady) return;
// ★ blocker 가 있으면 이 버튼은 그려지지도 않는다. 그래도 한 번 더 막는다 —
// 서버를 못 부르는 상태로 여기를 지나가는 것이 곧 '가짜 발행'이다.
if (blocker || !gate.canPublish || publisher.isPublishing || !slugReady) return;
if (publisher.isLive) {
// ★ 주소를 먼저 확정하고 빌드한다. 순서가 반대면 주소 없는 사이트가 발행되고,
// 그 뒤에 주소를 붙이면 이미 색인된 주소가 하나 더 생긴다.
if (!isSlugLocked) {
try {
await reserveSiteSlug(placeId ?? '', slug);
} catch (error) {
notifyApiError(error, '주소를 확정하지 못했습니다.');
return;
}
// ★ 주소를 먼저 확정하고 빌드한다. 순서가 반대면 주소 없는 사이트가 발행되고,
// 그 뒤에 주소를 붙이면 이미 색인된 주소가 하나 더 생긴다.
if (!isSlugLocked) {
try {
await reserveSiteSlug(placeId ?? '', slug);
} catch (error) {
notifyApiError(error, '주소를 확정하지 못했습니다.');
return;
}
// 진짜 게이트는 서버에 있다(services/publish_gate). 여기 gate 는 왕복을 줄이는 사전 점검일 뿐이다.
publisher.publish();
return;
}
setPublishedUrl(url);
notify.success('발행 준비가 끝났습니다', '확인된 정보만 담긴 정적 페이지가 생성됩니다.');
// 진짜 게이트는 서버에 있다(services/publish_gate). 여기 gate 는 왕복을 줄이는 사전 점검일 뿐이다.
publisher.publish();
};
const handleCopy = async () => {
@@ -184,11 +232,25 @@ export function PublishModal() {
<Dialog
open={isOpen}
onClose={close}
title={isDone ? '발행 완료' : isRepublish ? '재발행 전 점검' : '발행 전 점검'}
title={
blocker === 'signin'
? '지금 화면은 미리보기입니다'
: blocker === 'place'
? '가게 확인이 먼저입니다'
: isDone
? '발행 완료'
: isRepublish
? '재발행 전 점검'
: '발행 전 점검'
}
description={
isDone
? '확인된 정보만 담긴 정적 페이지가 생성되었습니다.'
: '검색·AI 노출에 직접 영향을 주는 항목부터 확인합니다.'
blocker === 'signin'
? '만드신 화면은 아직 어디에도 올라가 있지 않습니다.'
: blocker === 'place'
? '발행본은 확인된 가게 한 곳에 묶입니다.'
: isDone
? '확인된 정보만 담긴 정적 페이지가 생성되었습니다.'
: '검색·AI 노출에 직접 영향을 주는 항목부터 확인합니다.'
}
className="max-w-lg"
footer={
@@ -197,7 +259,23 @@ export function PublishModal() {
계속 편집하기
</Button>
{isDone ? (
{/* ★ 로그인 전에는 여기에 아무 버튼도 두지 않는다 — 다음 행동(로그인)은 본문의
폼이고, 옆에 [발행하기] 를 세워 두면 누를 수 있는 것처럼 보인다. */}
{blocker === 'signin' ? null : blocker === 'place' ? (
<Button
variant="primary"
className="flex-1"
onClick={() => {
// 모달을 먼저 닫는다 — 같은 화면(BuilderPage) 안에서 단계만 바뀌는 이동이라
// 열어 둔 채로 가면 가게 찾기 위에 이 모달이 그대로 떠 있는다.
close();
navigate(PLACE_SEARCH_URL);
}}
>
<Search />
<span>내 가게 확인하러 가기</span>
</Button>
) : isDone ? (
<Button
variant="primary"
className="flex-1"
@@ -236,8 +314,11 @@ export function PublishModal() {
}
>
<div className="space-y-4">
{blocker === 'signin' && <SignInFirstPanel />}
{blocker === 'place' && <PlaceFirstPanel />}
{/* 서버가 보는 현재 상태. 편집 중 상태만 보고 판단하지 않게 맨 위에 둔다. */}
{publisher.isLive && !isDone && (
{!blocker && !isDone && (
<SiteStatusRow
version={publisher.currentVersion?.version}
needsRebuild={publisher.needsRebuild}
@@ -245,8 +326,10 @@ export function PublishModal() {
/>
)}
{/* 주소는 발행의 전제다 — 점검 항목보다 먼저 정해야 [발행하기] 가 열린다. */}
{!isDone && (
{/* 주소는 발행의 전제다 — 점검 항목보다 먼저 정해야 [발행하기] 가 열린다.
★ blocker 상태에서는 그리지 않는다. 주소 중복 확인이 사업장·토큰을 요구하므로
입력칸만 열어 두면 확인 버튼이 매번 실패한다. */}
{!blocker && !isDone && (
<SlugField
value={slug}
host={PUBLISH_HOST}
@@ -261,7 +344,7 @@ export function PublishModal() {
/>
)}
{!isDone && gate.blockers.length > 0 && (
{!blocker && !isDone && gate.blockers.length > 0 && (
<section className="space-y-2">
<h3 className="flex items-center gap-1.5 text-xs font-bold text-destructive">
<ShieldAlert className="size-3.5" />
@@ -273,7 +356,7 @@ export function PublishModal() {
</section>
)}
{!isDone && gate.warnings.length > 0 && (
{!blocker && !isDone && gate.warnings.length > 0 && (
<section className="space-y-2">
<h3 className="flex items-center gap-1.5 text-xs font-bold text-warning">
<AlertTriangle className="size-3.5" />
@@ -285,7 +368,7 @@ export function PublishModal() {
</section>
)}
{!isDone && gate.findings.length === 0 && state.phase === 'idle' && (
{!blocker && !isDone && gate.findings.length === 0 && state.phase === 'idle' && (
<div className="flex items-center gap-2 rounded-lg border border-success/30 bg-success/8 p-3 text-xs text-success">
<Check className="size-4 shrink-0" />
<span>
@@ -319,6 +402,71 @@ export function PublishModal() {
);
}
/**
* 로그인 전 — **미리보기라고 말하고, 그 자리에서 로그인을 받는다.**
*
* ★ /login 으로 튕기지 않는다. 위저드·에디터 상태는 브라우저에 저장하지 않으므로
* (stores/builder 주석) 화면을 떠나는 순간 지금까지 만든 것이 통째로 사라진다.
* 에디터 관문(EditorSignInGate)이 같은 이유로 같은 폼을 그 자리에 놓는다.
* ★ 로그인이 끝나면 폼이 심은 토큰으로 blocker 가 저절로 다시 계산된다 — 이 패널이 사라지고
* 발행 점검 화면이 뜬다(사업장이 아직 없으면 아래 PlaceFirstPanel 로 넘어간다).
*/
function SignInFirstPanel() {
return (
<div className="space-y-3">
<div className="rounded-lg border border-warning/40 bg-warning/8 p-3 text-xs">
<div className="mb-1 flex items-center gap-1.5 font-bold text-warning">
<Eye className="size-3.5" />
<span>여기까지는 미리보기입니다</span>
</div>
<p className="leading-relaxed text-muted-foreground">
발행하면 검색·AI 가 읽는 정적 페이지(HTML)가 구워집니다. 그 페이지는 계정과 실제
가게에 묶이므로, 로그인과 내 가게 확인이 끝나야 시작할 수 있습니다.
</p>
<p className="mt-1.5 text-[11px] font-medium">
→ 여기서 로그인하시면 지금까지 만든 내용은 그대로 둔 채 이어집니다.
</p>
</div>
<div className="flex justify-center">
<SignInForm
submitLabel="로그인하고 발행 준비"
header={
<p className="text-center text-xs leading-relaxed text-muted-foreground">
발행본은 나중에 고치고 내릴 수 있어야 해서 계정에 묶어 둡니다.
</p>
}
/>
</div>
</div>
);
}
/**
* 로그인은 했는데 서버에 사업장이 없다 — 3단계에서 수집을 건너뛰고 나온 경로다.
*
* ★ 여기서 사업장을 몰래 만들지 않는다. 생성과 네이버 검증의 순서는
* features/onboarding/ensureServerPlace 한 곳이 소유한다 — 검증을 건너뛰고 만든 사업장은
* 수집도 발행도 못 하는 껍데기로 남고, 그 사실은 화면에 안 나온다.
*/
function PlaceFirstPanel() {
return (
<div className="rounded-lg border border-warning/40 bg-warning/8 p-3 text-xs">
<div className="mb-1 flex items-center gap-1.5 font-bold text-warning">
<Store className="size-3.5" />
<span>내 가게가 아직 확인되지 않았습니다</span>
</div>
<p className="leading-relaxed text-muted-foreground">
발행본은 실제 가게 한 곳에 묶입니다 — 주소·전화·영업시간이 그 가게의 것이라는 근거가
있어야 검색·AI 가 이 페이지를 출처로 씁니다. 직접 입력으로만 진행하셨다면 그 가게가
아직 서버에 없어서, 발행을 눌러도 구울 대상이 없습니다.
</p>
<p className="mt-1.5 text-[11px] font-medium">
→ 상호로 내 가게를 찾아 확인하시면 그때부터 발행이 열립니다.
</p>
</div>
);
}
/** 서버가 보는 사이트 상태 한 줄. 편집 중 상태(gate)와 저장된 상태를 구분해 준다. */
/**
* 서버가 보는 현재 발행 상태 한 줄.
@@ -0,0 +1,113 @@
import {useEffect, useState} from 'react';
import type {FestivalCard, GuideCard} from '@/features/builder/canvas/variants/local/types';
import {useBuilderStore} from '@/stores/builder';
export interface LocalGuideData {
foods: GuideCard[];
spots: GuideCard[];
festivals: FestivalCard[];
/** 서버가 가장 최근에 수집한 시각(ISO). 아직 아무것도 없으면 undefined. */
syncedAt?: string;
}
const EMPTY: LocalGuideData = {foods: [], spots: [], festivals: []};
// 종류별 노출 상한. 서버(snapshot._LOCAL_MAX_PER_TYPE)가 같은 수로 자르지만, 화면이 먼저 넘치지 않게 여기서도 막는다.
const MAX_PER_TYPE = 20;
/** 서버 응답 항목 — 발행 payload 의 LocalPlace / FestivalEntry 와 같은 모양(백엔드 ResLocalGuide 주석). */
interface GuidePlace {
name: string;
category: string;
searchQuery: string;
distanceText?: string;
distanceMeters?: number;
imageUrl?: string;
location?: string;
description?: string;
}
interface GuideFestival extends GuidePlace {
month: string;
period?: string;
officialUrl?: string;
}
function toCard(p: GuidePlace): GuideCard {
return {
name: p.name,
// 설명이 없으면 주소로 대신한다 — 카드에 이름만 덜렁 있는 것보다 어디인지가 낫다.
description: p.description ?? p.location ?? '',
searchQuery: p.searchQuery,
imageUrl: p.imageUrl,
distanceMeters: typeof p.distanceMeters === 'number' ? p.distanceMeters : undefined,
distanceText: p.distanceText,
};
}
function toFestival(f: GuideFestival): FestivalCard {
return {
...toCard(f),
month: f.month,
period: f.period ?? '',
officialUrl: f.officialUrl,
};
}
// 사업장 하나당 한 번만 받는다 — 필터·캐러셀 조작마다 API 를 다시 때리지 않는다.
const cache = new Map<string, LocalGuideData>();
/**
* 업장 주변 가이드(맛집·명소·축제). 날씨(useWeather)와 같은 규약이다 —
* 실패해도 에러를 띄우지 않고 빈 목록을 유지한다. 부가 정보라 사장님 작업을 막을 이유가 없다.
*
* ★ 값은 서버(local.place_contents)가 소유하고, 발행본과 같은 필터·모양으로 온다.
* 캔버스가 보여주는 목록 = 발행 사이트에 나갈 목록. 첫 조회 때 서버가 채우므로 비어 있는 건 잠깐이다.
*/
export function useLocalGuide(): LocalGuideData {
const placeId = useBuilderStore((s) => s.placeId);
const [guide, setGuide] = useState<LocalGuideData>(() => (placeId && cache.get(placeId)) || EMPTY);
useEffect(() => {
if (!placeId) {
setGuide(EMPTY);
return;
}
const cached = cache.get(placeId);
if (cached) {
setGuide(cached);
return;
}
let alive = true;
const controller = new AbortController();
async function fetchGuide() {
try {
const baseUrl = import.meta.env.VITE_API_BASE_URL ?? 'http://localhost:9800';
const query = new URLSearchParams({place_id: placeId!});
const res = await fetch(`${baseUrl}/v1/local/guide?${query}`, {signal: controller.signal});
if (!res.ok) return;
const data = await res.json();
if (!data?.result?.success || !alive) return;
const next: LocalGuideData = {
foods: ((data.restaurants ?? []) as GuidePlace[]).slice(0, MAX_PER_TYPE).map(toCard),
spots: ((data.attractions ?? []) as GuidePlace[]).slice(0, MAX_PER_TYPE).map(toCard),
festivals: ((data.festivals ?? []) as GuideFestival[]).slice(0, MAX_PER_TYPE).map(toFestival),
syncedAt: data.synced_at ?? undefined,
};
// ★ 빈 응답은 캐시하지 않는다 — 수집 전에 열어둔 화면이 빈 결과를 물고 있으면
// 수집이 끝나도 새로고침 전까지 계속 "준비 중"으로 보인다.
if (next.foods.length || next.spots.length || next.festivals.length) cache.set(placeId!, next);
setGuide(next);
} catch {
// 빈 목록 유지 — 화면에 에러를 띄우지 않는다.
}
}
void fetchGuide();
return () => {
alive = false;
controller.abort();
};
}, [placeId]);
return guide;
}
+2 -9
View File
@@ -10,8 +10,8 @@ import {toAuthUser, useAuthStore} from '@/stores/auth';
/**
* 내 정보 — `PATCH /v1/auth/me` 한 곳이 받는 것만 그린다.
*
* ★ 상호(company)는 읽기 전용이다. Req_UpdateMe 에 없다 — 자기 소속을 스스로 바꾸지 못하게
* 일부러 뺀 필드라, 입력칸을 두면 저장을 눌러도 아무 일이 안 일어난다.
* ★ 상호 칸은 없다. 회사(테넌트)를 걷어내면서(2026-09-08) 계정에 상호가 없어졌다 —
* 가게 이름은 사업장(place)이 갖는다.
* ★ 구글 계정에는 바꿀 비밀번호가 없다(서버가 ACCOUNT_PROVIDER_CONFLICT 로 막는다) —
* 입력칸 자체를 그리지 않는다.
*/
@@ -77,13 +77,6 @@ export function AccountPage() {
{isGoogle ? '구글 계정으로 로그인합니다.' : '아이디는 바꿀 수 없습니다.'}
</p>
</Field>
<Field label="상호">
<p className="text-sm">{data?.company?.name ?? '-'}</p>
<p className="mt-0.5 text-xs text-muted-foreground">
상호 변경은 고객센터로 문의해 주세요.
</p>
</Field>
</section>
<section className="space-y-4 rounded-xl border border-border bg-card p-5">
+1 -2
View File
@@ -212,10 +212,9 @@ export function BuilderPage() {
<span className="h-3.5 w-px bg-white/20" />
<span
className="max-w-[14rem] truncate text-background/70"
title={user.companyName ? `${userLabel(user)} · ${user.companyName}` : userLabel(user)}
title={userLabel(user)}
>
{userLabel(user)}
{user.companyName ? ` · ${user.companyName}` : ''}
</span>
<button
type="button"
@@ -31,7 +31,6 @@ export function SignupPage() {
passwordConfirm: '',
name: '',
email: '',
companyName: '',
});
const [isSubmitting, setIsSubmitting] = useState(false);
@@ -63,7 +62,6 @@ export function SignupPage() {
password: form.password,
name: form.name.trim() || null,
email: form.email.trim(),
company_name: form.companyName.trim() || null,
});
if (res.result?.success === false) {
notifyApiError({data: res}, '가입하지 못했습니다.');
@@ -180,17 +178,6 @@ export function SignupPage() {
required
/>
</div>
<div>
<label htmlFor="signup-company" className="mb-1.5 block text-xs font-semibold">
상호 <span className="font-normal text-muted-foreground">(선택)</span>
</label>
<Input
id="signup-company"
value={form.companyName}
onChange={set('companyName')}
placeholder="비우면 이름으로 채웁니다"
/>
</div>
</div>
<Button type="submit" variant="primary" className="w-full" isLoading={isSubmitting}>
+294 -53
View File
@@ -1,4 +1,4 @@
import {useState} from 'react';
import {useMemo, useState} from 'react';
import {Link, useNavigate} from 'react-router';
import {
Building2,
@@ -8,17 +8,22 @@ import {
MoreHorizontal,
Pencil,
Plus,
Search,
SearchX,
Stethoscope,
UtensilsCrossed,
Wand2,
X,
} from 'lucide-react';
import {PlaceCategory, publishUrlString, SiteStatus} from '@o2o/shared';
import {changeStatus, PublishAction, useListMySites, type MySiteData} from '@/api';
import {AppShell, EmptyState, PageContainer} from '@/components/layout/AppShell';
import {Badge} from '@/components/ui/badge';
import {Button} from '@/components/ui/button';
import {Input} from '@/components/ui/input';
import {notify, notifyApiError} from '@/lib/notify';
import {PUBLISH_HOST} from '@/lib/site';
import {cn} from '@/lib/utils';
// 발행본 주소는 PublishModal·CanvasView 와 같은 규칙이다 — 세 곳이 다른 주소를 말하면 안 된다.
// ★ window 로 떨어지지 않는다. 서버 번들은 라우트를 한 파일로 묶어서, 프리렌더가 아닌
@@ -32,24 +37,51 @@ const CATEGORY_ICON: Record<number, typeof Building2> = {
[PlaceCategory.CLINIC]: Stethoscope,
};
/**
* 줄이 속하는 칸. **배지·필터·정렬이 전부 이 하나로 판정한다.**
*
* ★ 판정을 갈라 쓰면 조용히 틀린다 — '발행됨(1)' 을 눌렀는데 '내림' 배지가 낀 줄이 같이
* 나오는 종류다. 건수까지 틀리므로 사장님은 목록을 못 믿게 된다.
* ★ 세 칸이 목록을 빈틈없이 나눈다. 하나라도 빠지면 '전체' 건수와 칸 건수의 합이 어긋난다.
*/
type SiteBucket = 'live' | 'draft';
type SiteFilter = SiteBucket | 'all';
/**
* ★ 칸은 **둘**이다. 예전엔 '만드는 중'(사이트 행 없음)을 따로 뒀는데, 사장님에게 그 둘은
* 같은 상태다 — "아직 안 나가 있다". `site_id` 가 있고 없고는 우리 DB 사정이지 사장님의
* 구분이 아니고, 칸이 셋이면 34개가 어디 있는지 두 번 세게 된다.
*/
const FILTER_LABEL: Record<SiteFilter, string> = {
all: '전체',
live: '발행됨',
draft: '발행 전',
};
const FILTER_TABS: readonly SiteFilter[] = ['all', 'live', 'draft'];
/** 나가 있는 것부터 본다 — 실측(계정 test): 35개 중 34개가 발행 전이라 1개가 묻힌다. */
const BUCKET_ORDER: Record<SiteBucket, number> = {live: 0, draft: 1};
function bucketOf(row: MySiteData): SiteBucket {
return row.site_id && row.status === SiteStatus.PUBLISHED ? 'live' : 'draft';
}
/**
* 줄의 상태 배지. **사이트 상태(sites.status)만 본다** — 사업장 상태(places.status)는
* 수집 단계를 말하는 값이라 사장님이 궁금한 "지금 나가 있나"와 다르다.
*/
function statusBadge(row: MySiteData) {
if (!row.site_id) return {label: '만드는 중', variant: 'outline' as const};
switch (row.status) {
case SiteStatus.PUBLISHED:
return row.needs_rebuild
? {label: '수정됨 · 재발행 필요', variant: 'warning' as const}
: {label: '발행됨', variant: 'success' as const};
case SiteStatus.SUSPENDED:
return {label: '중지', variant: 'outline' as const};
case SiteStatus.UNPUBLISHED:
return {label: '내림', variant: 'outline' as const};
default:
return {label: '발행 전', variant: 'default' as const};
if (bucketOf(row) === 'live') {
return row.needs_rebuild
? {label: '수정됨 · 재발행 필요', variant: 'warning' as const}
: {label: '발행됨', variant: 'success' as const};
}
// 같은 '발행 전' 이어도 **한 번 나갔다가 내린 것**은 말해 준다 — 되돌리는 일과 처음 내는 일은
// 사장님이 할 행동이 다르다. 그 외(초안·수집 중)는 전부 '발행 전' 한 마디다.
if (row.status === SiteStatus.SUSPENDED) return {label: '중지', variant: 'outline' as const};
if (row.status === SiteStatus.UNPUBLISHED) return {label: '내림', variant: 'outline' as const};
return {label: '발행 전', variant: 'default' as const};
}
/** 발행본이 실제로 열리는 주소. ★ 주소는 발행 전에 예약되므로 PUBLISHED 일 때만 연다 — 아니면 404 다. */
@@ -58,19 +90,135 @@ function publishedUrl(row: MySiteData): string | null {
return publishUrlString(row.domain.split('.')[0], PUBLISH_HOST);
}
/**
* 줄 뒤에 붙는 시각. **발행됐으면 발행일, 아니면 만든 날**이다.
*
* ★ 두 개를 같이 걸지 않는다. Wix·아임웹 목록이 시각을 한 칸만 쓰는 이유와 같다 —
* 목록에서 궁금한 건 "이게 언제 나갔나" 하나이고, 아직 안 나간 줄에만 만든 날이 의미가 있다.
* ★ 연도는 올해면 뗀다. 줄이 좁아 주소가 먼저 잘린다.
*/
function whenLabel(row: MySiteData): string {
const raw = row.published_at ?? row.created_at;
if (!raw) return '';
const at = new Date(raw);
if (Number.isNaN(at.getTime())) return '';
const now = new Date();
const date = at.toLocaleDateString('ko-KR', {
...(at.getFullYear() === now.getFullYear() ? {} : {year: 'numeric'}),
month: 'long',
day: 'numeric',
});
return row.published_at ? `${date} 발행` : `${date} 만듦`;
}
/** 정렬용 시각. whenLabel 이 고른 값과 같은 것을 쓴다 — 화면에 보이는 날짜와 순서가 갈라지면 안 된다. */
function rowTime(row: MySiteData): number {
const raw = row.published_at ?? row.created_at;
if (!raw) return 0;
const at = new Date(raw).getTime();
return Number.isNaN(at) ? 0 : at;
}
/**
* 검색 비교용 정규화. **공백을 지운다** — 실측(계정 test)에 같은 상호 '버터브루' 가 4줄인데
* 사장님은 '버터 브루' 로도 친다. 한국어 상호는 띄어쓰기가 원본마다 다르다.
*/
function normalizeText(value: string): string {
return value.toLowerCase().replace(/\s+/g, '');
}
/** 상호와 도로명 주소만 본다 — 상호가 겹치는 줄을 실제로 가르는 건 주소다. */
function matchesQuery(row: MySiteData, needle: string): boolean {
if (!needle) return true;
return normalizeText(row.name).includes(needle) || normalizeText(row.road_address ?? '').includes(needle);
}
/**
* 줄 앞의 그림. 발행에 성공한 사이트만 썸네일이 있고(sites.thumbnail_url),
* 없으면 업종 아이콘으로 떨어진다.
*
* ★ 주소에 `?v=<버전>` 이 붙어 있다 — 발행할 때마다 바뀐다(site_thumbnail.public_url).
* 그래서 <img> 에 캐시 무효화를 따로 걸지 않는다. 여기서 또 붙이면 발행하지 않은
* 재방문에도 매번 새로 받는다.
* ★ 못 받으면 아이콘으로 되돌린다. 블롭이 지워졌거나 옛 주소인 줄에서 깨진 그림이
* 뜨는 것보다 낫다.
*/
function SiteThumb({row, Icon}: {row: MySiteData; Icon: typeof Building2}) {
const [failed, setFailed] = useState(false);
const src = row.thumbnail_url;
// ★ 비율은 **16:10 — 브라우저 창 비율**이다. 이 그림은 사이트 미리보기라 1:1 로 자르면
// 위아래가 잘려 무슨 사이트인지 알아볼 수 없다(사진첩이 아니다).
// ★ 크기는 아임웹 내사이트 화면을 보고 키웠다(2026-09-08). 거기 썸네일도 줄 높이의 대부분을
// 차지한다 — 같은 상호가 여러 줄일 때 그림이 유일한 구분자인데 작으면 있으나 마나다.
if (!src || failed) {
return (
<div className="flex aspect-[16/10] w-full items-center justify-center border-b border-border bg-muted/60">
<Icon className="size-7 text-muted-foreground/60" />
</div>
);
}
return (
<img
src={src}
alt=""
loading="lazy"
onError={() => setFailed(true)}
className="aspect-[16/10] w-full border-b border-border object-cover"
/>
);
}
/**
* 내 사이트 — 로그인한 사장님의 홈이다.
*
* 흐름은 하나다: 위저드로 만든다 → 여기 생긴다 → 눌러서 에디터로 들어가 고친다 → 재발행한다.
* ★ 그래서 줄을 누르면 에디터로 간다. 목록에 온 용건은 열에 아홉 "내 사이트 고치기"다.
*
* ★ 목록이 하는 일은 셋뿐이다 — ① 어느 게 어느 건지 가르고 ② 지금 상태를 말하고 ③ 여는 길을 준다.
* 방문자·주문 같은 숫자는 여기 넣지 않는다(Wix·아임웹도 사이트 안 대시보드에 둔다).
*/
export function SitesPage() {
const navigate = useNavigate();
const {data, isLoading, isError, error, refetch} = useListMySites({size: 50});
const [busyId, setBusyId] = useState<string | null>(null);
const [menuId, setMenuId] = useState<string | null>(null);
const [query, setQuery] = useState('');
const [filter, setFilter] = useState<SiteFilter>('all');
const rows = data?.sites ?? [];
const rows = useMemo(() => data?.sites ?? [], [data]);
// ★ 서버로 안 보낸다. 한 번에 50줄을 이미 다 받아 놓았고(실측 35줄), 서버 검색을 붙이면
// 글자마다 왕복 + 디바운스 + 늦게 온 응답이 최신 결과를 덮는 경합까지 따라온다.
// → 50줄을 넘어 페이지가 생기는 날이 오면 그때는 서버가 맞다(이 필터는 첫 페이지만 본다).
const found = useMemo(() => {
const needle = normalizeText(query);
return rows.filter((row) => matchesQuery(row, needle));
}, [rows, query]);
// ★ 건수는 **검색 결과 위에서** 센다. 검색어를 친 뒤 "발행됨 0 · 만드는 중 3" 이 보여야
// 찾는 게 어느 칸에 있는지 알 수 있다. 검색 전 건수를 그대로 두면 칸을 눌러 보고서야 안다.
const counts = useMemo(() => {
const tally: Record<SiteFilter, number> = {all: found.length, live: 0, draft: 0};
for (const row of found) tally[bucketOf(row)] += 1;
return tally;
}, [found]);
// 서버는 사업장 생성 역순으로만 준다(site_crud.list_owner_sites) — 발행 여부를 모른다.
// 나가 있는 것을 위로 올리는 건 여기서 한다.
const visible = useMemo(() => {
const picked = filter === 'all' ? found : found.filter((row) => bucketOf(row) === filter);
return [...picked].sort(
(a, b) => BUCKET_ORDER[bucketOf(a)] - BUCKET_ORDER[bucketOf(b)] || rowTime(b) - rowTime(a),
);
}, [found, filter]);
const isNarrowed = query.trim().length > 0 || filter !== 'all';
const resetView = () => {
setQuery('');
setFilter('all');
};
// 발행 내리기만 둔다. ★ 삭제 경로는 만들지 않는다 — 색인된 페이지를 404 로 만들면
// 그 자리를 다시 OTA 가 가져가고, 되돌릴 방법이 사장님에게 없다(sites.status 주석).
@@ -135,53 +283,145 @@ export function SitesPage() {
/>
)}
{rows.length > 0 && (
<ul className="divide-y divide-border overflow-hidden rounded-xl border border-border bg-card">
{rows.map((row) => {
{!isLoading && !isError && rows.length > 0 && (
<div className="mb-3 flex flex-wrap items-center gap-2">
<div className="relative min-w-56 flex-1">
<Search className="pointer-events-none absolute top-1/2 left-2.5 size-3.5 -translate-y-1/2 text-muted-foreground" />
<Input
type="search"
value={query}
onChange={(event) => setQuery(event.target.value)}
placeholder="상호나 주소로 찾기"
aria-label="상호나 주소로 찾기"
className="h-9 pr-8 pl-8"
/>
{query && (
<button
type="button"
aria-label="검색어 지우기"
onClick={() => setQuery('')}
className="absolute top-1/2 right-2 -translate-y-1/2 cursor-pointer text-muted-foreground transition-colors hover:text-foreground"
>
<X className="size-3.5" />
</button>
)}
</div>
{/* 건수를 배지가 아니라 칸 안에 붙인다 — "34가 어디 있나"는 칸을 눌러 보기 전에 보여야 한다. */}
<div className="flex items-center gap-0.5 rounded-md border border-border p-0.5">
{FILTER_TABS.map((key) => (
<button
key={key}
type="button"
aria-pressed={filter === key}
onClick={() => setFilter(key)}
className={cn(
'h-8 cursor-pointer rounded px-2.5 text-xs font-medium transition-colors',
filter === key
? 'bg-muted text-foreground'
: 'text-muted-foreground hover:text-foreground',
)}
>
{FILTER_LABEL[key]}
<span className="ml-1 tabular-nums opacity-60">{counts[key]}</span>
</button>
))}
</div>
</div>
)}
{/* ★ 처음 온 사람의 빈 화면과 섞지 않는다 — 사이트가 35개인데 "아직 없습니다" 라고 하면
사장님은 목록이 아니라 자기 사이트가 사라진 줄 안다. */}
{!isLoading && !isError && rows.length > 0 && visible.length === 0 && (
<EmptyState
icon={SearchX}
title="조건에 맞는 사이트가 없습니다"
description={`가진 사이트 ${rows.length}개 중에 없습니다. 검색어를 줄이거나 다른 칸을 보세요.`}
action={
<Button size="sm" onClick={resetView}>
조건 지우기
</Button>
}
/>
)}
{visible.length > 0 && (
/* ★ 줄이 아니라 카드다. 아임웹 내사이트 화면을 보고 바꿨다(2026-09-08) — 거기 썸네일은
줄 높이의 대부분을 차지한다. 사이트 목록에서 그림은 장식이 아니라 **유일한 구분자**라
(실측: 같은 상호 '버터브루' 4줄) 작으면 있으나 마나다.
비율은 16:10 — 사이트 미리보기라 브라우저 창 비율이어야 한다. 1:1 은 사진첩이지 사이트가 아니다. */
<ul className="grid grid-cols-1 gap-4 sm:grid-cols-2 xl:grid-cols-3">
{visible.map((row) => {
const Icon = CATEGORY_ICON[row.category] ?? Building2;
const badge = statusBadge(row);
const url = publishedUrl(row);
const isLive = bucketOf(row) === 'live';
const editHref = `/builder?placeId=${row.place_id}`;
return (
<li key={row.place_id} className="relative flex items-center gap-3 px-4 py-3.5 hover:bg-muted/40">
<Icon className="size-4 shrink-0 text-muted-foreground" />
<Link to={editHref} className="min-w-0 flex-1">
<div className="flex items-center gap-2">
<span className="truncate text-sm font-semibold">{row.name}</span>
<Badge variant={badge.variant}>{badge.label}</Badge>
</div>
<p className="mt-0.5 truncate text-xs text-muted-foreground">
{url ?? (row.domain ? `주소 예약됨 · ${row.domain}` : '주소를 아직 정하지 않았습니다')}
</p>
/* ★ 카드는 **상태와 무관하게 같은 골격**이다. 예전엔 발행 전 카드에만 '할 일'
줄이 하나 더 붙어서 같은 줄의 카드끼리 높이와 버튼 위치가 어긋났다(사장님 지적).
h-full + flex-col + mt-auto 로 액션 줄을 항상 카드 바닥에 붙인다. */
<li
key={row.place_id}
className="group relative flex h-full flex-col overflow-hidden rounded-xl border border-border bg-card transition-shadow hover:shadow-md"
>
<Link to={editHref} className="block">
<SiteThumb row={row} Icon={Icon} />
</Link>
<div className="flex shrink-0 items-center gap-1.5">
{url && (
<a
href={url}
target="_blank"
rel="noopener noreferrer"
className="inline-flex h-8 items-center gap-1.5 rounded-md border border-border px-2.5 text-xs font-medium transition-colors hover:bg-muted"
{/* 배지는 그림 위에 얹는다 — 카드에서 상태는 제목보다 먼저 읽혀야 한다. */}
<Badge variant={badge.variant} className="absolute top-2.5 left-2.5 shadow-sm">
{badge.label}
</Badge>
<div className="flex flex-1 flex-col p-3.5">
<Link to={editHref} className="block min-w-0">
<p className="truncate text-sm font-semibold">{row.name}</p>
{/* ★ 나가 있는 카드만 주소를 진하게. 나머지의 이 자리는 "아직 없다"는 안내라
같은 색이면 34개의 안내문 사이에 진짜 주소가 묻힌다. */}
<p
className={cn(
'mt-1 truncate text-xs',
isLive ? 'font-medium text-foreground' : 'text-muted-foreground',
)}
>
<ExternalLink className="size-3.5" />
사이트 열기
</a>
)}
<Button size="sm" onClick={() => navigate(editHref)}>
<Pencil />
{row.site_id ? '편집' : '이어서 만들기'}
</Button>
<Button
size="icon"
variant="ghost"
aria-label="더보기"
isLoading={busyId === row.place_id}
onClick={() => setMenuId(menuId === row.place_id ? null : row.place_id)}
>
{busyId === row.place_id ? null : <MoreHorizontal />}
</Button>
{url ?? (row.domain ? `주소 예약됨 · ${row.domain}` : '주소를 아직 정하지 않았습니다')}
</p>
{/* 같은 상호가 여럿일 때 가르는 값 — 주소와 시각. */}
<p className="mt-1 mb-3 truncate text-[11px] text-muted-foreground/70">
{[row.road_address, whenLabel(row)].filter(Boolean).join(' · ')}
</p>
</Link>
<div className="mt-auto flex items-center gap-1.5 border-t border-border pt-3">
{/* 버튼 문구도 하나로 둔다 — '편집' 과 '이어서 만들기' 는 사장님이 할 일이
같은데(에디터를 연다) 글자만 달라 카드마다 폭이 들쭉날쭉했다. */}
<Button size="sm" className="flex-1" onClick={() => navigate(editHref)}>
<Pencil />
편집
</Button>
{url && (
<a
href={url}
target="_blank"
rel="noopener noreferrer"
className="inline-flex h-8 items-center gap-1.5 rounded-md border border-border px-2.5 text-xs font-medium transition-colors hover:bg-muted"
>
<ExternalLink className="size-3.5" />
열기
</a>
)}
<Button
size="icon"
variant="ghost"
aria-label="더보기"
isLoading={busyId === row.place_id}
onClick={() => setMenuId(menuId === row.place_id ? null : row.place_id)}
>
{busyId === row.place_id ? null : <MoreHorizontal />}
</Button>
</div>
</div>
{menuId === row.place_id && (
@@ -193,7 +433,7 @@ export function SitesPage() {
className="fixed inset-0 z-10 cursor-default"
onClick={() => setMenuId(null)}
/>
<div className="absolute right-4 top-12 z-20 w-44 rounded-md border border-border bg-card py-1 shadow-md">
<div className="absolute right-3.5 bottom-12 z-20 w-44 rounded-md border border-border bg-card py-1 shadow-md">
<button
type="button"
disabled={row.status !== SiteStatus.PUBLISHED}
@@ -210,6 +450,7 @@ export function SitesPage() {
})}
</ul>
)}
</PageContainer>
</AppShell>
);
-4
View File
@@ -8,8 +8,6 @@ export interface AuthUser {
name?: string;
email?: string;
role: number;
companyId?: string;
companyName?: string;
}
/**
@@ -26,8 +24,6 @@ export function toAuthUser(res: ResMe): AuthUser {
name: res.name ?? undefined,
email: res.email ?? undefined,
role: res.role ?? UserRole.USER,
companyId: res.company?.company_id,
companyName: res.company?.name,
};
}
+8 -1
View File
@@ -33,6 +33,13 @@ export function deriveSurfaces(colors: {bg: string; card: string; text: string;
surface: mix(colors.bg, colors.text, 0.06),
surfaceAlt: colors.card,
inverse: '#1c1917',
border: colors.secondary,
/**
* 선 색.
*
* ★ secondary 를 그대로 쓰면 안 된다 — 그건 '본문 다음으로 진한 글자색' 이라
* 선으로 쓰면 표와 카드가 격자무늬처럼 새까맣게 그어진다(갱지 팔레트에서 특히).
* 바탕에서 글자색 쪽으로 20%만 간 값이 목업의 선 색이다(#e4dac0 → #bcb49e).
*/
border: mix(colors.bg, colors.text, 0.2),
};
}
+66 -2
View File
@@ -85,10 +85,16 @@ export interface PeopleItem {
role?: string;
oneLine?: string;
/**
* 사진 검색어. ★ 이미지 URL 을 받지 않는다 — 초상권·저작권 확인은 사장님 몫이고,
* 모델이 지어낸 주소를 링크하면 깨진 사진이 인물 얼굴 자리에 남는다(LocalPlace.searchQuery 와 같은 규약).
* 사진 검색어. 모델은 이 값만 만든다 — 주소를 지어내면 깨진 사진이 인물 얼굴 자리에 남는다.
*/
imageQuery?: string;
/**
* 초상 사진.
*
* ★ **모델이 채우는 칸이 아니다.** 권리가 확인된 출처(위키미디어 등)에서 사람이 넣거나,
* 수집기가 라이선스를 확인하고 넣는다. 초상권은 지어낸 URL 로 감당할 수 없다.
*/
imageUrl?: string;
verified?: DataVerified;
source?: DataSource;
}
@@ -101,6 +107,8 @@ export interface ChronicleItem {
place?: string;
/** 도시의 성격을 바꾼 해. 레일의 붉은 점이 이 값이다 — 점의 색이 장식이 아니라 정보다. */
turning?: boolean;
/** 사진. 재게시 권리가 확실한 출처(공공누리·위키미디어)만 싣는다. 없으면 글자만 나간다. */
imageUrl?: string;
verified?: DataVerified;
source?: DataSource;
}
@@ -124,6 +132,8 @@ export interface PostcardItem {
place?: string;
/** 소인에 찍을 짧은 지명. 없으면 place 가 그 자리에 들어간다. */
postmark?: string;
/** 엽서 앞면 사진. 권리가 확실한 출처만. 없으면 글자만 있는 뒷면 한 장이 된다. */
imageUrl?: string;
verified?: DataVerified;
source?: DataSource;
}
@@ -138,6 +148,56 @@ export interface QuizItem {
source?: DataSource;
}
export interface ItineraryStop {
name: string;
minutes?: number;
note?: string;
searchQuery?: string;
/**
* 좌표.
*
* ★ **모델이 만드는 값이 아니다.** 지도에 핀을 찍는 값이라 한 자리만 틀려도 손님이
* 엉뚱한 데로 간다. 장소명으로 공식 API(TourAPI·카카오)를 조회해 채운다.
* 없으면 지도를 그리지 않고 타임라인만 낸다.
*/
latitude?: number;
longitude?: number;
/** 사진. 권리가 확실한 출처만. */
imageUrl?: string;
}
export interface ItineraryDay {
label: string;
startTime?: string;
stops?: ItineraryStop[];
}
/** 며칠 묵느냐로 갈리는 일정. days 가 하루씩이다. */
export interface ItineraryItem {
name: string;
duration?: string;
audience?: string;
why?: string;
days?: ItineraryDay[];
verified?: DataVerified;
source?: DataSource;
}
/** 사장님이 쓰는 공지·소식. 지역 리서치가 아니라 업소가 소유한 글이다. */
export interface EventItem {
kind?: string;
title: string;
summary?: string;
body?: string;
verified?: DataVerified;
}
export interface VideoItem {
url: string;
caption?: string;
verified?: DataVerified;
}
export interface PlannerStop {
name: string;
/** 여기서 머무는 시간(분). 없으면 60분으로 본다 — 못 재면 시각을 계산할 수 없다. */
@@ -181,6 +241,10 @@ export const SECTION_ITEM_REQUIRED_KEY: Record<string, string> = {
postcard: 'line',
quiz: 'question',
planner: 'name',
// ★ 여기 없는 kind 는 파서가 통째로 건너뛴다 — payload 에 실려 와도 화면에서 사라진다.
itinerary: 'name',
event: 'title',
video: 'url',
};
export interface ParsedSectionData<T> {
+7
View File
@@ -106,6 +106,13 @@ export interface TemplateLook {
headingWeight: string;
/** 섹션 세로 여백. 이 값 하나로 페이지의 호흡이 바뀐다. */
sectionSpace: string;
/**
* 종이 질감 — `background-image` 에 그대로 들어간다(`.paper`).
*
* ★ 레트로(갱지)의 인상이 사실상 이 값에서 온다. 없으면 색만 갱지고 면은 매끈해서
* 같은 팔레트인데도 인쇄물로 안 보인다. 비워 두면 아무것도 깔지 않는다.
*/
texture?: string;
}
export interface PhotoItem {
Loaded 100 of 137 files, more files were not shown because too many files have changed in this diff. Show more