Compare commits

..
65 Commits
Author SHA1 Message Date
koreafood ecc8ab4474 deploy: umbrel 라이브 dist 직접 서빙으로 전환 — QNAP rsync 제거(2026-11-27) 2026-11-26 18:55:11 +00:00
koreafood beaaf6555c update 2026-11-20 21:47:28 +09:00
koreafood 72e1926d87 카톡 채널 연결 버그 수정·canonical 추가·모바일 내비 터치 영역 확대
- templates/index.html: 인라인 스크립트 문자열에 실제 개행이 들어가 문법 오류 → 카톡 문의 버튼이 동작하지 않던 문제 (배열 join으로 교체)
- content/site.json: 카톡 채널 주소 추가
- templates/base.html: canonical 태그, 헤더 앵커를 같은 페이지에서는 #앵커로 (불필요한 재로딩 제거)
- assets/css/site.css: 모바일 내비 터치 영역 45px (음수 마진으로 글자 위치 유지)
2026-11-01 18:59:49 +09:00
한땀 작업실 7aaa488825 작품 삭제: 솔잎 티매트 2026-11-01 08:12:19 +00:00
한땀 작업실 ddae2c776a 이력 행: 되돌리기 버튼 줄바꿈 방지 2026-11-01 08:09:35 +00:00
한땀 작업실 e1ddbff1f5 되돌리기 화면: 폰 목록 맨 아래 최근 이력 → 그 커밋 revert(초안 있으면 배포만 건너뜀) 2026-11-01 08:08:08 +00:00
한땀 작업실 3d5a015400 작품 삭제 기능: 수정 화면 DELETE — md·사진·페이지 제거, 되돌리기로 복구, 키트/마지막 작품 보호 2026-11-01 07:59:57 +00:00
한땀 작업실 bdbad3ec6d 작품 수정: 코펜하겐, 천 위에 앉히다 2026-11-01 07:48:39 +00:00
한땀 작업실 d84b4e4d61 상품 추가: 코펜하겐, 천 위에 앉히다 (가격 문의) 2026-11-01 06:10:11 +00:00
한땀 작업실 b81eb5745f 작품 수정: 쪽빛 사시코 티매트 2026-11-01 05:57:28 +00:00
한땀 작업실 7619eef367 상품 추가: 파란 천 위의 흰 올 (15000) 2026-11-01 05:37:08 +00:00
한땀 작업실 9434a08480 작품 목록 제목: 판매 중인 작품 -> 작품 2026-11-01 05:10:29 +00:00
한땀 작업실 b803ab4efd 작품 목록 분리: 판매 중 / 판매 완료(카톡 제작 문의 버튼) 2026-11-01 04:56:29 +00:00
한땀 작업실 aba5d4d6e2 상세 페이지 순서: 작은 제목 → 메인사진 → 서브사진 → 스토리 → 맨 아래 DETAILS(구매·소재·규격) 2026-11-01 04:48:34 +00:00
한땀 작업실 ebbec84ba6 어투 지침: 마지막 여운 문장을 작품마다 다르게(상투적 표현 금지) 2026-11-01 04:43:54 +00:00
한땀 작업실 c10a1c76fb 작품 수정: 사시코 티코스터 패키지 2026-11-01 04:43:40 +00:00
한땀 작업실 09ad856c0b 작품 수정: 처음 한 땀 티매트 키트 2026-11-01 04:43:37 +00:00
한땀 작업실 bc01e7cfe6 작품 수정: 솔잎 티매트 2026-11-01 04:43:35 +00:00
한땀 작업실 9c234b0c43 작품 수정: 쪽빛 사시코 티매트 2026-11-01 04:43:31 +00:00
한땀 작업실 07900de9aa 작품 수정: 자주색 위의 벚꽃 2026-11-01 04:43:28 +00:00
한땀 작업실 dd203f2113 작품 수정: 사시코 티코스터 패키지 2026-11-01 04:42:36 +00:00
한땀 작업실 71a01228c6 작품 수정: 처음 한 땀 티매트 키트 2026-11-01 04:42:34 +00:00
한땀 작업실 c766e70922 작품 수정: 솔잎 티매트 2026-11-01 04:42:22 +00:00
한땀 작업실 aa79358d64 작품 수정: 쪽빛 사시코 티매트 2026-11-01 04:42:14 +00:00
한땀 작업실 53477b387d 어투: 기본을 우아한(고급 문어체)으로 — 어휘 상향·구어체/행정어 금지·마지막 문단에 온기 2026-11-01 04:39:29 +00:00
한땀 작업실 97a6961d88 작품 수정: 자주색 위의 벚꽃 2026-11-01 04:38:57 +00:00
한땀 작업실 02e654d75e 본문 어투: 기본 다정한 톤 + 다정한/담백한/서정적인 선택과 다시 쓰기(미리보기·적용) 2026-11-01 04:34:37 +00:00
한땀 작업실 a749b9daf8 작품 수정: 자주색 위의 벚꽃 2026-11-01 04:33:26 +00:00
한땀 작업실 a6835e943a 등록 화면: 작품 수정(사진 재배치·삭제·추가, 항목 편집, 저장/배포) + 배포 시 재빌드 2026-11-01 04:28:53 +00:00
한땀 작업실 f2ae889795 Revert "상품 추가: 수정 시험 작품 (9000)"
This reverts commit 43332601d3.
2026-11-01 04:28:23 +00:00
한땀 작업실 51f3cdbe1c Revert "작품 수정: 수정한 작품 제목"
This reverts commit 481831e00d.
2026-11-01 04:28:23 +00:00
한땀 작업실 481831e00d 작품 수정: 수정한 작품 제목 2026-11-01 04:28:06 +00:00
한땀 작업실 43332601d3 상품 추가: 수정 시험 작품 (9000) 2026-11-01 04:26:44 +00:00
한땀 작업실 5efb86b6b8 등록 화면: 목록 화면 다듬기(하단 바 숨김, 발행 버튼 조건부) + 안내 문서 2026-11-01 04:23:22 +00:00
한땀 작업실 b887c98d5f 등록 화면: 작품 목록(썸네일·미발행 표시), 저장 후 목록 복귀, 사이트에 올리기 버튼, dist 미리보기(/p, /preview) 2026-11-01 04:22:36 +00:00
한땀 작업실 b604bfe047 상품 추가: 자주색 위의 벚꽃 (가격 문의) 2026-11-01 04:17:41 +00:00
한땀 작업실 ae2cc1de7d 문서: 등록 화면을 테일넷 전용(tailscale serve, 토큰 없음)으로 갱신 2026-11-01 04:10:47 +00:00
한땀 작업실 cdf81ccc4e Revert "상품 추가: 연결 시험 티코스터 (12000)"
This reverts commit fc19253ac9.
2026-11-01 04:10:33 +00:00
한땀 작업실 fc19253ac9 상품 추가: 연결 시험 티코스터 (12000) 2026-11-01 04:10:25 +00:00
한땀 작업실 574d4f53cd QNAP: 서버 포트를 로컬호스트에만 게시(테일넷 전용 접속) 2026-11-01 04:09:53 +00:00
한땀 작업실 b41d42694d 등록 화면: 아이콘·미리보기용 /assets 경로 제공 2026-11-01 03:56:17 +00:00
한땀 작업실 984fe68c12 QNAP 이전: 등록 서버를 컨테이너로(8089, Caddy teamat-admin.lala.dedyn.io), 사진 원본 보관, 웹 루트 직접 배포, Gitea 자동 푸시 2026-11-01 03:52:58 +00:00
한땀 작업실 5c5ecef578 Revert "상품 추가: 와인색 티코스터 네 장 (18000)"
This reverts commit b5296f7e08.
2026-11-01 03:52:14 +00:00
한땀 작업실 b5296f7e08 상품 추가: 와인색 티코스터 네 장 (18000) 2026-11-01 03:51:59 +00:00
koreafood e502c32542 휴대폰 등록: 사진→내용→항목→발행 화면(m.html), 사진 인박스·VLM 판독·발행 API, 테일스케일 접속 열쇠, launchd 상시 실행 2026-11-01 12:39:56 +09:00
koreafood 4ce660b740 Revert "상품 추가: 와인색 사시코 연습 티코스터 (18000)"
This reverts commit 929e0d7095.
2026-11-01 12:39:08 +09:00
koreafood 929e0d7095 상품 추가: 와인색 사시코 연습 티코스터 (18000) 2026-11-01 12:38:57 +09:00
koreafood 43d26690c0 Revert "상품 추가: 와인색 사시코 티코스터 (25000)"
This reverts commit fb5b09f3be.
2026-11-01 12:32:45 +09:00
koreafood fb5b09f3be 상품 추가: 와인색 사시코 티코스터 (25000) 2026-11-01 12:32:09 +09:00
koreafood 7f2cb35cdb Revert "상품 추가: 와인색 티코스터 네 장 (16000)"
This reverts commit db6fb9c075.
2026-11-01 12:30:07 +09:00
koreafood db6fb9c075 상품 추가: 와인색 티코스터 네 장 (16000) 2026-11-01 12:29:38 +09:00
koreafood 142116c8e7 상품 추가: 사시코 티코스터 패키지 (라라원단 S048B, 16,000원·스마트스토어 연결) 2026-11-01 11:34:26 +09:00
koreafood 3d908e6e5c 문서: 운영 URL 을 teamat.lala.dedyn.io 로 갱신(서브패스 병행 표기) 2026-10-31 18:42:16 +09:00
koreafood 04211ddf71 전용 도메인: teamat.lala.dedyn.io (og:image 기준 URL 전환, 배포 확인에 신규 도메인 상태 추가) 2026-10-31 18:41:42 +09:00
koreafood 3396d27557 판매 모델 반영: 완성품은 재고 있을 때만 판매·판매완료는 재제작 문의, 키트는 링크만(문서 포함) 2026-10-31 11:41:13 +09:00
koreafood eb55d4849c 스튜디오: price_note 필드 편집 지원 2026-10-31 11:35:27 +09:00
koreafood 4ffd6667b0 키트: 네이버 스마트스토어 상품 주소 연결 2026-10-31 11:34:42 +09:00
koreafood 1483969c06 가격·규격 반영: 티매트 장당 15,000원·4장 50,000원(price_note), 키트 16,000원·10cm 4장, 스마트스토어 주소 2026-10-31 11:34:12 +09:00
koreafood 39d504ab2b 작품 수정: 쪽빛 사시코 티매트 규격 한 장 10 × 10 cm 2026-10-31 11:31:36 +09:00
koreafood cdaac551d6 작품 수정: 쪽빛 사시코 티매트 규격 10 × 10 cm 2026-10-31 11:30:45 +09:00
koreafood 8c565cccc8 작품 글 수정: 쪽빛 사시코 티매트 (실제 사진 4장 + 갤러리) 2026-10-31 11:24:58 +09:00
koreafood ca2c0d077d 작업실: 새 작품 이미지도 함께 커밋, 되돌리기 뒤 빈 폴더 정리 2026-10-31 11:19:50 +09:00
koreafood 767b2a30a3 작품 파일명 연-월-제목 + 작품별 이미지 폴더(assets/img/<slug>/) 2026-10-31 11:18:55 +09:00
koreafood 4dff91b483 작업실: AI 프롬프트로 작품 수정·새 작품 초안(DeepSeek) 2026-10-31 10:58:42 +09:00
koreafood 109bd93bd2 작품 수정: 목련 한 땀 사시코 티매트 2026-10-31 10:47:20 +09:00
63 changed files with 3348 additions and 282 deletions

No files matched your search

+3
View File
@@ -2,3 +2,6 @@ dist/
.DS_Store .DS_Store
*.log *.log
.claude/settings.local.json .claude/settings.local.json
studio/_inbox/
__pycache__/
studio/_archive/
+27 -14
View File
@@ -6,9 +6,14 @@
## 0. 절대 규칙 ## 0. 절대 규칙
1. **DB·서버·CMS 를 만들지 않는다.** 정적 HTML/CSS/JS 만. Node/npm/pip 패키지 금지. 1. **DB·서버·CMS 를 만들지 않는다.** 정적 HTML/CSS/JS 만. Node/npm/pip 패키지 금지.
- 예외: `studio/` 는 사이트가 아니라 **아이맥 로컬 편집 도구**다(표준 라이브러리만, 127.0.0.1 전용, `dist/` 에 포함되지 않음). 이 예외를 근거로 사이트에 서버 기능을 붙이지 않는다. - 예외: `studio/` 는 사이트가 아니라 **관리 도구**다(표준 라이브러리만, `dist/` 에 포함되지 않음).
QNAP 컨테이너(`teamat-admin:1`, 호스트 8089 는 127.0.0.1 에만 게시)에서 돌고, QNAP 의 tailscale 컨테이너가
`tailscale serve` 로 `https://naslala.taild8883.ts.net/` 에만 노출한다(테일넷 전용, 공개 도메인·토큰 없음).
아이맥 로컬 실행은 비상용으로만 남긴다. 이 예외를 근거로 사이트에 서버 기능을 붙이지 않는다.
2. **빌드는 `python3 build.py` 하나.** 표준 라이브러리만 사용. 2. **빌드는 `python3 build.py` 하나.** 표준 라이브러리만 사용.
3. **모든 링크·이미지 경로는 상대경로.** 사이트는 `https://home.lala.dedyn.io/teamat/` 서브패스에서 서빙된다. - AI(DeepSeek) 호출은 `studio/server.py` 안에서만. 빌드·사이트 코드에 AI 를 넣지 않는다.
- AI 제안은 사람이 적용·저장해야 파일이 바뀐다(자동 저장 금지). AI 가 쓴 수치는 저장 전에 확인한다.
3. **모든 링크·이미지 경로는 상대경로.** 사이트는 전용 도메인 `https://teamat.lala.dedyn.io/` 루트에서 서빙된다(서브패스 `https://home.lala.dedyn.io/teamat/` 도 병행 유효).
4. **`dist/` 는 커밋하지 않는다.** 소스에서 언제든 재생성된다. 롤백 단위는 커밋 하나. 4. **`dist/` 는 커밋하지 않는다.** 소스에서 언제든 재생성된다. 롤백 단위는 커밋 하나.
5. **`git push --force` 금지.** 되돌리기는 `git revert`. 5. **`git push --force` 금지.** 되돌리기는 `git revert`.
6. 없는 사실을 만들지 않는다 — 후기·별점·판매량·수상·재고. 값이 없으면 비워둔다. 6. 없는 사실을 만들지 않는다 — 후기·별점·판매량·수상·재고. 값이 없으면 비워둔다.
@@ -61,6 +66,7 @@ dist/ 빌드 산출물(.gitignore)
"kakao": "" "kakao": ""
}, },
"shop": { "shop": {
"kit_slug": "2026-10-kit-first-stitch",
"store_url": "https://smartstore.naver.com/", "store_url": "https://smartstore.naver.com/",
"kit_url": "https://smartstore.naver.com/", "kit_url": "https://smartstore.naver.com/",
"kit_note": "키트에 들어가는 것 한 줄" "kit_note": "키트에 들어가는 것 한 줄"
@@ -79,34 +85,39 @@ dist/ 빌드 산출물(.gitignore)
``` ```
- `product_sort`: `newest`(기본) 또는 `oldest`. 이 값 하나로 목록 순서가 바뀐다. - `product_sort`: `newest`(기본) 또는 `oldest`. 이 값 하나로 목록 순서가 바뀐다.
- `shop.kit_slug`: 첫 페이지 '키트' 섹션에 쓸 작품의 slug. 작품 slug 를 바꾸면 여기도 함께 고친다.
- 문구를 고치라는 요청은 대부분 이 파일만 고치면 끝난다. - 문구를 고치라는 요청은 대부분 이 파일만 고치면 끝난다.
## 3. content/products/<slug>.md 스키마 ## 3. content/products/<slug>.md 스키마
```markdown ```markdown
--- ---
slug: whitework-tea-mat # 영문 소문자·하이픈, URL 이 된다(/p/whitework-tea-mat.html) slug: 2026-10-whitework-tea-mat # 파일명과 같다. `연-월-영문제목` → /p/2026-10-whitework-tea-mat.html
title: 목련 한 땀 티매트 title: 목련 한 땀 티매트
subtitle: 봄볕에 널어둔 천 subtitle: 봄볕에 널어둔 천
date: 2026-10-28 # 목록 정렬 기준 date: 2026-10-28 # 목록 정렬 기준
price: 58000 # 원 단위 정수. 비우면 "문의" price: 15000 # 원 단위 정수. 최소 판매 단위(한 장). 비우면 "문의"
sold_out: false price_note: 네 장 세트 50,000원 # 선택. 가격 옵션 안내 한 줄
sold_out: false # 재고 없음 = true → 구매 버튼 대신 "판매 완료" 안내
featured: true # 첫 페이지 상단에 크게 노출 featured: true # 첫 페이지 상단에 크게 노출
image: assets/img/work-whitework.jpg image: assets/img/2026-10-whitework-tea-mat/cover.jpg
image_alt: 아이보리 린넨 위에 흰 실로 목련을 놓은 티매트 image_alt: 아이보리 린넨 위에 흰 실로 목련을 놓은 티매트
gallery: # 선택. 상세 페이지 추가 이미지 gallery: # 선택. 상세 페이지 추가 이미지 (같은 작품 폴더에 둔다)
- assets/img/work-whitework.jpg - assets/img/2026-10-whitework-tea-mat/detail-01.jpg
material: 린넨 100% material: 린넨 100%
size: 30 × 45 cm size: 10 × 10 cm (한 장) # 완성품 기준. 세트면 "10 × 10 cm × 4장"
care: 미지근한 물에 중성세제로 단독 손세탁 care: 미지근한 물에 중성세제로 단독 손세탁
naver_url: "" # 비우면 구매 버튼 대신 "네이버 스토어 준비 중" naver_url: "" # 스마트스토어 상품 주소. 비우면 구매 버튼 대신 "네이버 스토어 준비 중"
--- ---
본문은 2~4문단. 어떤 천에 어떤 실로, 얼마나 걸렸는지. 과장 없이. 본문은 2~4문단. 어떤 천에 어떤 실로, 얼마나 걸렸는지. 과장 없이.
``` ```
- **새 작품 추가 = 이 파일 1개 추가 → `python3 build.py`.** 목록과 상세가 자동 생성된다. - **새 작품 추가 = 이 파일 1개 추가 → `python3 build.py`.** 목록과 상세가 자동 생성된다.
- `slug` 는 파일명과 같게 유지한다. - `sold_out: true` 인 작품은 첫 페이지의 **판매 완료 섹션**으로 내려가고, 카드·상세에 `카톡으로 제작 문의` 버튼이 붙는다. 판매 재개는 `false` 로 되돌리는 것.
- 이미지 파일은 `assets/img/` 에 넣고 파일명은 영문 소문자·하이픈. - 파일명 = `slug` = **`연-월-영문제목`** (예: `2026-11-magnolia-tea-mat.md`). 앞의 연-월로 시기를 바로 구분하고 `ls`·`git log` 가 시간순으로 정렬된다. 한국어 제목은 `title` 에 쓴다(URL 은 영문 유지).
- **작품 이미지는 `assets/img/<slug>/` 폴더에 넣는다** — 대표는 `cover.jpg`, 추가 컷은 `detail-01.jpg` 처럼. 작품마다 폴더 하나, 다른 작품과 섞지 않는다.
- 공정·브랜드 공용 이미지는 `assets/img/process/` 에 둔다.
- 사이트가 JPEG 헤더에서 크기를 읽으므로 **JPG 만** 쓴다(PNG·WebP 는 빌드 실패).
## 4. content/process/*.md 스키마 ## 4. content/process/*.md 스키마
@@ -114,7 +125,7 @@ naver_url: "" # 비우면 구매 버튼 대신 "네이버 스
--- ---
step: 1 step: 1
title: 실 고르기 title: 실 고르기
image: assets/img/craft-jogakbo.jpg image: assets/img/process/fabric.jpg
image_alt: 조각보 image_alt: 조각보
--- ---
한 문단. 무엇을 보고 고르는지. 한 문단. 무엇을 보고 고르는지.
@@ -131,7 +142,7 @@ image_alt: 조각보
- HTML 은 `<!-- escaped -->` 없이 그대로 넣되, front matter 값은 escape 한다. - HTML 은 `<!-- escaped -->` 없이 그대로 넣되, front matter 값은 escape 한다.
- 상세 페이지에서 목록으로 돌아가는 링크는 `../index.html` (서브패스 대응). - 상세 페이지에서 목록으로 돌아가는 링크는 `../index.html` (서브패스 대응).
- 언어 `lang="ko"`, `<title>` 은 `작품명 — 한땀`, meta description 은 `subtitle`+재료. - 언어 `lang="ko"`, `<title>` 은 `작품명 — 한땀`, meta description 은 `subtitle`+재료.
- OG 태그 4개(`og:title`, `og:description`, `og:image`, `og:type`)만 넣는다. og:image 는 상대경로가 아니라 `https://home.lala.dedyn.io/teamat/` 기준 절대 URL 로 만든다. - OG 태그 4개(`og:title`, `og:description`, `og:image`, `og:type`)만 넣는다. og:image 는 상대경로가 아니라 `https://teamat.lala.dedyn.io/` 기준 절대 URL 로 만든다(`build.py` 의 `SITE_BASE`).
- 파비콘은 인라인 SVG data URI 하나. - 파비콘은 인라인 SVG data URI 하나.
## 6. 디자인 토큰 (바꾸려면 사용자 확인) ## 6. 디자인 토큰 (바꾸려면 사용자 확인)
@@ -147,6 +158,8 @@ image_alt: 조각보
- 제목: `Noto Serif KR` (serif), 본문: `Noto Sans KR` (sans). CDN 실패 시 시스템 폰트 폴백. - 제목: `Noto Serif KR` (serif), 본문: `Noto Sans KR` (sans). CDN 실패 시 시스템 폰트 폴백.
- 여백 위주, 그림자·그라데이션·둥근 카드 금지. 구분은 1px 실선. - 여백 위주, 그림자·그라데이션·둥근 카드 금지. 구분은 1px 실선.
- 사진이 주인공: 최소 60vw 폭 또는 4:5 세로 컷. 호버 확대는 1.02 이하. - 사진이 주인공: 최소 60vw 폭 또는 4:5 세로 컷. 호버 확대는 1.02 이하.
- **상세 페이지 순서는 고정**: ① 작은 제목(+부제·가격, `product-head`) ② 메인 사진(`product-hero`, 폭 min(100%,1080px), 자르지 않고 원본 비율)
③ 서브 사진(`gallery`, 한 열로 세로로 이어 붙임) ④ 스토리(`product-story`) ⑤ DETAILS(구매 버튼 + 소재·규격·세탁 `spec`) — 사양은 항상 맨 아래.
## 7. 자주 쓰는 명령 ## 7. 자주 쓰는 명령
+83 -12
View File
@@ -6,7 +6,7 @@ DB 없는 정적 사이트. 콘텐츠는 `content/` 의 md·json 파일이고, `
| 용도 | 주소 | | 용도 | 주소 |
|---|---| |---|---|
| 로컬 미리보기 (아이맥) | http://localhost:8080 | | 로컬 미리보기 (아이맥) | http://localhost:8080 |
| 운영 | https://home.lala.dedyn.io/teamat/ | | 운영 | https://teamat.lala.dedyn.io/ (서브패스 https://home.lala.dedyn.io/teamat/ 도 병행 유효) |
| 소스 저장소 | https://git.lala.dedyn.io/koreafood/teamat | | 소스 저장소 | https://git.lala.dedyn.io/koreafood/teamat |
## 빠른 시작 ## 빠른 시작
@@ -21,10 +21,14 @@ bash scripts/rollback.sh 2f22e71 # 특정 커밋 시점으로 내용 되돌
## 작품 하나 추가하기 ## 작품 하나 추가하기
1. 사진을 `assets/img/` 에 넣는다 (파일명은 영문 소문자-하이픈, 예: `magnolia-02.jpg`) 1. slug 를 정한다 — **`연-월-영문제목`** (예: `2026-11-magnolia-tea-mat`). 파일명 = slug = URL
2. `content/products/magnolia-02.md` 를 만든다 — front matter 스키마는 `CLAUDE.md` 3절 2. 사진을 **`assets/img/2026-11-magnolia-tea-mat/`** 폴더에 넣는다 (대표 `cover.jpg`, 추가 컷은 `detail-01.jpg`)
3. `python3 build.py` 3. `content/products/2026-11-magnolia-tea-mat.md` 를 만든다 — front matter 스키마는 `CLAUDE.md` 3절
4. `bash scripts/deploy.sh` 4. `python3 build.py`
5. `bash scripts/deploy.sh`
작품마다 폴더 하나. 사진이 많아져도 작품별로 모여 있고, 파일명 앞의 연-월로 시기가 바로 보인다.
공정 사진처럼 여러 곳에서 쓰는 이미지는 `assets/img/process/` 에 둔다.
목록과 상세 페이지는 자동으로 생긴다. 코드는 건드리지 않는다. 목록과 상세 페이지는 자동으로 생긴다. 코드는 건드리지 않는다.
@@ -36,6 +40,15 @@ bash scripts/rollback.sh 2f22e71 # 특정 커밋 시점으로 내용 되돌
| 작품 제목·가격·규격·이야기 | `content/products/<slug>.md` | | 작품 제목·가격·규격·이야기 | `content/products/<slug>.md` |
| 제작 과정 단계 | `content/process/*.md` | | 제작 과정 단계 | `content/process/*.md` |
| 네이버 스토어 링크 | `site.json` 의 `shop.store_url`·`shop.kit_url`, 작품별 `naver_url` | | 네이버 스토어 링크 | `site.json` 의 `shop.store_url`·`shop.kit_url`, 작품별 `naver_url` |
| 가격 옵션 안내(세트가 등) | 작품 md 의 `price_note` (예: `네 장 세트 50,000원`) |
### 판매 방식 (한땀 작업실)
- **완성품 티매트**: 미리 만들어 둔 재고만 판매한다. 한 점이 유일품이라 **팔리면 `sold_out: true`** 로 바꾼다.
그러면 구매 버튼이 사라지고 "판매 완료 — 재제작을 원하시면 문의해 주세요" 로 바뀐다. 목록에는 남는다.
- **재제작 판매**: 판매 완료된 작품은 요청이 왔을 때만 `sold_out: false` 로 되돌려 다시 판매한다(그때는 `naver_url` 도 확인).
- **가격**: `price` 는 최소 판매 단위(한 장 15,000원). 세트는 `price_note` 에 문장으로 적는다("네 장 세트 50,000원").
- **키트**: 사이트에서는 링크만 넘긴다. `site.json` 의 `shop.kit_url` = 스마트스토어 상품 주소(16,000원).
| 색·타이포 | `assets/css/site.css` 상단 `:root` 토큰 | | 색·타이포 | `assets/css/site.css` 상단 `:root` 토큰 |
## 작업실 — 화면에서 작품 고치기 (studio) ## 작업실 — 화면에서 작품 고치기 (studio)
@@ -51,10 +64,69 @@ bash scripts/studio.sh # http://localhost:8081
- `배포까지` 체크하면 저장과 동시에 `scripts/deploy.sh` 실행 - `배포까지` 체크하면 저장과 동시에 `scripts/deploy.sh` 실행
- 상단 `이력 / 되돌리기` = 최근 커밋 목록과 `git revert` - 상단 `이력 / 되돌리기` = 최근 커밋 목록과 `git revert`
- 작품 상세 페이지의 `이 작품 고치기` 버튼은 localhost 에서만 보인다 (운영 사이트에서는 hidden) - 작품 상세 페이지의 `이 작품 고치기` 버튼은 localhost 에서만 보인다 (운영 사이트에서는 hidden)
- 이미지: JPG 를 끌어다 놓으면 `assets/img/` 에 저장되고 경로가 자동 입력된다 - 이미지: JPG 를 끌어다 놓으면 `assets/img/<슬러그>/` 에 저장되고 경로가 자동 입력된다 (PNG 는 빌드가 못 읽어 거부)
- 단축키: `/` 검색, `↑↓` 이동, `⌘S` 저장 - **AI 프롬프트**: 입력창에 말로 시키면 부제·본문·소재·규격을 고친 제안을 보여준다. 아무것도 자동 저장되지 않고 `폼에 적용` 또는 `적용하고 저장`을 눌러야 반영된다
- 모드 `새 작품 초안` = 제목·가격·규격을 주면 원고와 slug 를 만들어 폼에 열어준다(이미지·슬러그 확인 후 저장)
- 모델 `deepseek-flash`. 키는 `~/.config/teamat-studio/ai.json`(600) 또는 `DEEPSEEK_API_KEY`
- AI 가 쓴 사실(기간·소재 등)은 저장 전에 사람이 확인한다. 근거 없는 수치는 넣지 않도록 프롬프트에 규칙을 넣어 두었지만 보증은 아니다
- 바로 실행 딥링크: `/?slug=<slug>&prompt=<내용>&run=1`
- 단축키: `/` 검색, `↑↓` 이동, `⌘S` 저장, 프롬프트에서 `⌘Enter` 실행
- 서버는 `127.0.0.1` 에만 붙는다. 외부에서 접근되지 않는다 - 서버는 `127.0.0.1` 에만 붙는다. 외부에서 접근되지 않는다
## 폰에서 등록 (QNAP 관리 화면)
사진을 찍고 내용을 쓰면 상세 페이지 한 장이 만들어지는 화면. **QNAP 컨테이너에서 돌고, 테일넷 안에서만 열린다.**
- 주소: `https://naslala.taild8883.ts.net/` — 열쇠(토큰) 없다. 테일스케일이 켜진 내 기기에서만 접속된다.
(공개 도메인 `teamat-admin.lala.dedyn.io` 는 만들었다가 내렸다. 필요하면 다시 만들 수 있지만 열쇠 없이 공개하면 안 된다.)
- 홈 화면에 추가하면 앱처럼 열린다(PWA). 사진·음성 입력은 HTTPS 라서 그대로 동작한다.
- 첫 화면은 **작품 목록**이다(썸네일·부제·가격, 최근 순). 카드를 누르면 방금 만든 페이지가 그대로 열린다(빌드 결과 `dist` 를 서버가 서빙: `/p/<slug>.html`, 사이트 전체는 `/preview`).
- 흐름: ① 사진 찍기(여러 장, 첫 장이 대표) → ② 내용 작성(사진을 읽어 초안) → ③ 규격·소재·세탁 칩 + 가격 → ④ 확인 후 저장
- 저장하면 완료 화면에 `목록으로 돌아가기` 가 나오고, 목록의 그 작품에 `방금 등록` 배지가 붙는다. `저장만` 으로 저장한 작품은 `미발행` 배지가 붙는다.
- 목록 위 `사이트에 올리기 (미발행 N점)` = 커밋된 상태를 그대로 배포한다. 커밋 안 된 초안이 있으면 먼저 물어본다. 배포 후 배지는 사라진다.
- **어투(말투)**: AI 원고의 기본은 `우아한` — '~습니다'체 문어체에 어휘를 한 단계 높이고('수놓다·앉히다·결·올·여백·온기'),
구어체('~해 줘요')와 행정적 동사('구성하다·제작하다')를 피하며, 마지막 문단에 손끝의 온기를 한 문장으로 남긴다.
신규 등록 화면과 수정 화면에 `다정한 / 담백한 / 서정적인` 칩이 있고, 수정 화면에서는 `이 어투로 다시 쓰기` 로 본문만 다시 쓴 뒤 `본문에 적용`(저장은 따로)한다.
어투 정의는 `studio/register.py` 의 `TONES` — 문구를 고치면 두 화면·재작성·신규 원고에 모두 반영된다.
- **고치기**: 목록 카드 오른쪽 `수정` → 제목·부제·본문·규격·소재·세탁·가격·날짜·네이버 링크·대표작/품절을 그대로 불러온다.
사진은 순서 바꾸기(첫 장이 대표)·삭제·추가(촬영/앨범)가 되고, 저장하면 `assets/img/<slug>/` 를 다시 정리한다(쓰지 않는 사진은 지운다).
`저장하고 사이트에 올리기` 또는 `저장만`. 저장 = md 재작성 → build → 커밋(`작품 수정: 제목`) → push.
- **삭제**: 수정 화면 맨 아래 `이 작품 삭제` → 확인 창 한 번이면 지운다. md + `assets/img/<slug>/` 를 함께 지우고
`작품 삭제: 제목` 커밋을 남긴 뒤 사이트에서도 내린다(목록·첫 페이지·상세 페이지에서 사라진다).
찍은 원본은 `data/photos/<slug>/` 에 남고, 이력에서 그 커밋을 되돌리면 md·사진·페이지가 그대로 살아난다.
실수 방지로 **첫 페이지 키트(`site.json` 의 `shop.kit_slug`)와 마지막 남은 한 점은 거부**한다.
커밋 안 된 다른 초안이 있으면 삭제는 하되 배포는 건너뛴다(목록의 `사이트에 올리기` 로 마저 올린다).
- `/m?slug=<슬러그>` 로 들어가면 그 작품 수정 화면이 바로 열린다.
- 목록 맨 아래 `최근 이력 · 되돌리기` = 최근 커밋 25개 목록. `되돌리기` 를 누르면 그 커밋을 `git revert` 하고(사이트 반영까지)
지운 작품을 되살린다. 커밋 안 된 초안이 있으면 되돌리기는 하되 배포는 건너뛴다.
- `사이트에 올리기` 는 **빌드까지 다시 한 뒤** 복사한다(되돌리기·수동 편집 뒤에도 안전).
- 저장 = `사진 축소(Pillow) → content/products/<slug>.md → build.py → git commit`(경로만 지정) → `git push`(Gitea). `사이트에 올리기` 를 누르면 `dist/` 를 웹 루트로 복사한다.
- 사진은 `studio/_inbox/` 에 잠시 쌓였다가 발행 시 두 곳으로 나뉜다.
- 사이트용: `assets/img/<slug>/cover.jpg`, `detail-NN.jpg` (저장소에 커밋. 최대 1400px, 품질 82)
- 원본 보관: `/share/CACHEDEV8_DATA/docker/teamat-admin/data/photos/<slug>/` (찍은 그대로. 나중에 다시 자를 때 쓴다)
- 커밋되지 않은 **다른 초안**이 있으면 배포를 건너뛰고 알려준다. 그 초안까지 올리려면 화면의 `다른 초안도 함께 올리기` 를 켠다.
- 저장소(작업 사본)는 QNAP 에 있다: `/share/CACHEDEV8_DATA/docker/teamat-admin/repo`. 아이맥에서 편집하려면 `git pull` 로 받는다.
- 접속 경로: 컨테이너 포트는 **127.0.0.1 에만** 게시하고(`-p 127.0.0.1:8089:8089`), QNAP 의 tailscale 컨테이너(호스트 네트워크)가 `tailscale serve --bg --https=443 http://127.0.0.1:8089` 로 테일넷에만 노출한다. Caddy·공인 DNS 는 쓰지 않는다.
- 컨테이너 관리 (QNAP): `bash repo/scripts/run-qnap.sh build|up|down|logs` · 이미지 `teamat-admin:1` · 호스트 포트 8089(로컬 전용)
- 설정 파일(저장소에 넣지 않는다, `chmod 600`): `/share/CACHEDEV8_DATA/docker/teamat-admin/config/{ai.json,vision.json}` — ai.json(문장), vision.json(사진 판독).
- 열쇠를 다시 켜고 싶으면 `config/token.disabled` 를 `config/token` 으로 되돌리고 컨테이너를 재시작한다(그때는 `?t=<토큰>` 이 필요해진다).
- 데스크톱 편집 화면은 같은 주소의 `/desk`.
비상용: 아이맥에서만 돌리는 예전 방식도 남아 있다. `bash scripts/studio-service.sh install`(launchd) + `tailscale serve --bg 8081` → `https://imac.taild8883.ts.net/m`. 지금은 꺼 둔다.
## 작품 목록 — 판매 중 / 판매 완료
- 첫 페이지 작품 섹션은 둘로 나뉜다. 위는 **작품**(`sold_out: false`), 아래는 **지난 작품 — 제작 문의**(`sold_out: true`).
- 판매 완료 카드에는 `카톡으로 제작 문의` 버튼이 붙고, 상세 페이지에도 같은 버튼이 들어간다(품절 안내 문구 대신).
- 버튼 동작: 문의 문구(작품명·원하는 시기·크기/색상·문의 내용)를 클립보드에 복사하고 카톡을 연다. `site.json` 의 `contact.kakao` 에 카카오채널 1:1 채팅 주소(`https://pf.kakao.com/_XXXX/chat`)를 넣으면 그 대화창이 바로 열린다. 비어 있으면 `kakaotalk://` 로 앱만 열리므로, 문구를 붙여넣어 보내면 된다.
- 판매 완료 작품이 하나도 없으면 섹션은 빈 안내 문구만 보여준다(나중에 팔리면 자동으로 채워진다).
- 문구는 `site.json` 의 `sold_works_note`.
## 상세 페이지 구성
① 작은 제목·부제·가격 → ② 메인 사진(자르지 않고 폭 1080px) → ③ 서브 사진(한 열) → ④ 스토리 → ⑤ DETAILS(구매 버튼 + 소재·규격·세탁).
사진이 주인공이고 사양은 맨 아래에 둔다. 템플릿은 `templates/product.html`, 스타일은 `assets/css/site.css` 의 `/* product */` 절.
## 대화로 고치기 ## 대화로 고치기
Claude Code 에 말로 지시하면 위 파일들을 알아서 고친다. 예: Claude Code 에 말로 지시하면 위 파일들을 알아서 고친다. 예:
@@ -79,14 +151,13 @@ Claude Code 에 말로 지시하면 위 파일들을 알아서 고친다. 예:
| 파일 | 원본 | 라이선스 | | 파일 | 원본 | 라이선스 |
|---|---|---| |---|---|---|
| `work-whitework.jpg` | Linen towel with drawn threadwork and whitework embroidery (Wikimedia Commons) | Public domain | | `2026-10-cedar-tea-mat/cover.jpg`, `process/stitch.jpg` | Japanese flat silk embroidery on leno-weave fabric / Ineffablebookkeeper | CC BY-SA 4.0 |
| `work-green-linen.jpg` | Japanese flat silk embroidery on leno-weave fabric / Ineffablebookkeeper | CC BY-SA 4.0 | | `2026-10-kit-first-stitch/cover.jpg`, `process/fabric.jpg` | Wrapping cloth (bojagi), Korea / Hiart | CC0 |
| `craft-jogakbo.jpg` | Wrapping cloth (bojagi), Korea / Hiart | CC0 |
실제 작품 사진으로 교체하면 해당 표기와 `site.json` 의 `image_credits` 도 함께 정리한다. 실제 작품 사진으로 교체하면 해당 표기와 `site.json` 의 `image_credits` 도 함께 정리한다.
## 아직 없는 것 (의도적으로) ## 아직 없는 것 (의도적으로)
결제·회원·장바구니·재고, 게시판·리뷰, 다국어, 사이트 내 검색, 분석 스크립트. 결제·회원·장바구니·**재고 개수 관리**(작품은 유일품이라 판매중/판매완료 두 상태로 충분), 게시판·리뷰, 다국어, 사이트 내 검색, 분석 스크립트.
관리자 화면도 없다 — 대신 아이맥 로컬 편집 도구 `studio/` 가 있다(위 항목). 관리자 화면은 사이트에 없다 — 대신 별도 도구 `studio/` 가 QNAP 컨테이너로 돌고, 폰에서 접속한다.
구매는 네이버 스마트스토어로 넘긴다. 구매는 네이버 스마트스토어로 넘긴다.
+185 -112
View File
@@ -772,7 +772,7 @@ strong {
.back-link { .back-link {
display: inline-block; display: inline-block;
margin-block: 8px 28px; margin-block: 8px 20px;
color: var(--muted); color: var(--muted);
font-size: 13px; font-size: 13px;
text-decoration: none; text-decoration: none;
@@ -786,63 +786,159 @@ strong {
padding-bottom: clamp(40px, 6vw, 80px); padding-bottom: clamp(40px, 6vw, 80px);
} }
.product-top { /* 제목은 작게 — 사진이 먼저 보이도록 */
.product-head {
display: grid; display: grid;
grid-template-columns: minmax(0, 7fr) minmax(0, 4fr); gap: 4px;
gap: clamp(36px, 5vw, 80px); margin-bottom: clamp(14px, 2.5vw, 26px);
align-items: start;
} }
.product-media { .product-title {
aspect-ratio: 4 / 5; margin: 0;
overflow: hidden; font-size: clamp(1.05rem, 1.4vw, 1.3rem);
background: var(--line); font-weight: 400;
} line-height: 1.45;
letter-spacing: 0;
.product-media img {
width: 100%;
height: 110%;
object-fit: cover;
object-position: center top;
}
.product-info {
position: sticky;
top: 32px;
padding-top: clamp(8px, 3vw, 40px);
}
.product-info h1 {
font-size: clamp(2.3rem, 4.4vw, 4.1rem);
letter-spacing: -0.035em;
line-height: 1.06;
} }
.product-sub { .product-sub {
margin-top: 14px; margin: 0;
color: var(--muted); color: var(--muted);
font-size: 17px; font-size: 13px;
} }
.product-price { .product-head-price {
margin-top: 26px; margin: 6px 0 0;
font-size: 18px; font-size: 15px;
font-variant-numeric: tabular-nums; font-variant-numeric: tabular-nums;
} }
.product-info .btn, /* 1. 메인 사진 */
.product-info .pending { .product-hero {
margin-top: 24px; margin: 0 auto;
width: min(100%, 1080px);
background: var(--line);
}
.product-hero img {
display: block;
width: 100%;
height: auto;
}
/* 2. 서브 사진 */
.gallery {
display: grid;
grid-template-columns: minmax(0, 1fr);
gap: clamp(6px, 1vw, 12px);
width: min(100%, 1080px);
margin: clamp(6px, 1vw, 12px) auto 0;
}
.gallery-figure {
margin: 0;
background: var(--line);
}
.gallery-figure img {
display: block;
width: 100%;
height: auto;
}
/* 3. 스토리 */
.product-story {
display: grid;
grid-template-columns: 108px minmax(0, 1fr);
gap: clamp(20px, 4vw, 56px);
align-items: start;
margin-top: clamp(48px, 7vw, 96px);
}
.product-story .label {
padding-top: 10px;
}
.prose {
max-width: 64ch;
}
.prose p {
margin-bottom: 1.4em;
font-size: 17px;
line-height: 1.85;
}
.prose p:first-child {
font-size: clamp(1.15rem, 1.6vw, 1.35rem);
line-height: 1.75;
}
.prose p:last-child {
margin-bottom: 0;
}
.prose h2 {
margin: 2em 0 0.7em;
font-size: clamp(1.3rem, 2vw, 1.6rem);
}
.prose ul {
margin-bottom: 1.4em;
padding-left: 1.2em;
}
.prose li {
margin-bottom: 0.4em;
}
.prose figure {
margin-block: 32px;
}
/* 4. 맨 아래 상품 정보 */
.product-detail {
display: grid;
grid-template-columns: 108px minmax(0, 1fr);
gap: clamp(20px, 4vw, 56px);
align-items: start;
margin-top: clamp(48px, 7vw, 96px);
}
.product-detail > .label {
padding-top: 4px;
}
.detail-body {
max-width: 52ch;
}
.product-price {
margin: 0;
font-size: 16px;
font-variant-numeric: tabular-nums;
}
.product-price-note {
margin-top: 6px;
color: var(--muted);
font-size: 14px;
font-variant-numeric: tabular-nums;
}
.detail-body .btn,
.detail-body .pending {
margin-top: 18px;
} }
.product-sold { .product-sold {
margin-top: 8px; margin-top: 10px;
color: var(--muted); color: var(--muted);
font-size: 12px; font-size: 13px;
} }
.spec { .spec {
margin-top: 44px; margin-top: 30px;
border-top: 1px solid var(--line); border-top: 1px solid var(--line);
} }
@@ -866,73 +962,52 @@ strong {
line-height: 1.6; line-height: 1.6;
} }
.product-story { /* ------------------------------------------------------------ sold out */
display: grid;
grid-template-columns: 120px minmax(0, 1fr); .soldout .section-head {
gap: clamp(20px, 4vw, 56px); border-top: 1px solid var(--line);
align-items: start; padding-top: clamp(36px, 5vw, 64px);
margin-top: clamp(72px, 10vw, 140px);
} }
.product-story .label { .soldout {
padding-top: 10px; margin-top: clamp(56px, 8vw, 112px);
} }
.prose {
max-width: 64ch; .work.is-sold .work-figure img {
filter: saturate(0.86);
opacity: 0.92;
} }
.prose p { .inquiry-btn {
margin-bottom: 1.4em; display: inline-flex;
font-size: 17px; align-items: center;
line-height: 1.85; justify-content: center;
margin-top: 14px;
padding: 11px 16px;
border: 1px solid var(--ink);
background: var(--ink);
color: var(--paper);
font-family: var(--sans, "Noto Sans KR", sans-serif);
font-size: 13px;
letter-spacing: 0.02em;
cursor: pointer;
} }
.prose p:first-child { .inquiry-btn:hover {
font-size: clamp(1.25rem, 1.9vw, 1.5rem); background: var(--sage);
line-height: 1.7; border-color: var(--sage);
} }
.prose p:last-child { .inquiry-note {
margin-bottom: 0; margin-top: 8px;
color: var(--muted);
font-size: 12px;
line-height: 1.6;
} }
.prose h2 { .detail-body .inquiry-btn {
margin: 2em 0 0.7em; margin-top: 18px;
font-size: clamp(1.4rem, 2.2vw, 1.8rem);
}
.prose ul {
margin-bottom: 1.4em;
padding-left: 1.2em;
}
.prose li {
margin-bottom: 0.4em;
}
.prose figure {
margin-block: 32px;
}
.gallery {
grid-column: 2;
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 20px;
margin-top: 24px;
}
.gallery-figure {
aspect-ratio: 4 / 5;
overflow: hidden;
background: var(--line);
}
.gallery-figure img {
width: 100%;
height: 100%;
object-fit: cover;
} }
.pager { .pager {
@@ -1077,29 +1152,20 @@ strong {
gap: 48px; gap: 48px;
} }
.product-top { .product-story,
.product-detail {
grid-template-columns: minmax(0, 1fr); grid-template-columns: minmax(0, 1fr);
gap: 12px;
} }
.product-info { .product-story .label,
position: static; .product-detail > .label {
padding-top: 0;
}
.product-info .spec {
margin-top: 36px;
}
.product-story {
grid-template-columns: minmax(0, 1fr);
}
.product-story .label {
padding-top: 0; padding-top: 0;
} }
.product-hero,
.gallery { .gallery {
grid-column: 1; width: 100%;
} }
.foot-meta { .foot-meta {
@@ -1122,10 +1188,17 @@ strong {
} }
.nav { .nav {
gap: 18px; gap: 0;
font-size: 12px; font-size: 12px;
} }
/* 터치 영역 44px 확보 — 음수 마진으로 글자 위치는 그대로 둔다 */
.nav a {
display: inline-block;
padding: 12px 11px;
margin-block: -12px;
}
.wordmark-en { .wordmark-en {
display: none; display: none;
} }
@@ -1217,7 +1290,7 @@ strong {
} }
.nav { .nav {
gap: 14px; gap: 0;
} }
.wordmark-ko { .wordmark-ko {
File renamed without changes.
Binary file not shown.

After

Width:  |  Height:  |  Size: 62 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 98 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 47 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 217 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 79 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 391 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 327 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 359 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 309 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 212 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 301 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 287 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 332 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 164 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 203 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 350 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 292 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 209 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 506 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 255 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 123 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 101 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 58 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 61 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 332 KiB

File renamed without changes.
Binary file not shown.

Before

Width:  |  Height:  |  Size: 450 KiB

+29 -5
View File
@@ -20,7 +20,7 @@ CONTENT = ROOT / "content"
TEMPLATES = ROOT / "templates" TEMPLATES = ROOT / "templates"
ASSETS = ROOT / "assets" ASSETS = ROOT / "assets"
DIST = ROOT / "dist" DIST = ROOT / "dist"
SITE_BASE = "https://home.lala.dedyn.io/teamat/" SITE_BASE = "https://teamat.lala.dedyn.io/"
VAR_RE = re.compile(r"{{\s*(\w+)\s*}}") VAR_RE = re.compile(r"{{\s*(\w+)\s*}}")
LOOP_RE = re.compile(r"{{#(\w+)}}(.*?){{/\1}}", re.S) LOOP_RE = re.compile(r"{{#(\w+)}}(.*?){{/\1}}", re.S)
@@ -370,6 +370,7 @@ def build_shared(site: Dict[str, Any], home: str, asset_prefix: str) -> Dict[str
"credits": credits, "credits": credits,
"home": home, "home": home,
"asset_prefix": asset_prefix, "asset_prefix": asset_prefix,
"kakao_url": esc(str(contact.get("kakao", "")).strip()),
} }
@@ -390,6 +391,7 @@ def product_loop_items(products: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
"subtitle": esc(product.get("subtitle", "")), "subtitle": esc(product.get("subtitle", "")),
"price_text": format_price(product.get("price")), "price_text": format_price(product.get("price")),
"sold_html": sold_html, "sold_html": sold_html,
"inquiry_title": esc(product["title"]),
} }
) )
return items return items
@@ -432,9 +434,12 @@ def build_index(
hero_image = str(featured["image"]) hero_image = str(featured["image"])
hero_width, hero_height = image_size(hero_image) hero_width, hero_height = image_size(hero_image)
kit = next((p for p in products if p["slug"] == "kit-first-stitch"), None) kit_slug = str(site.get("shop", {}).get("kit_slug", "")).strip()
kit = next((p for p in products if p["slug"] == kit_slug), None) if kit_slug else None
if kit is None: if kit is None:
fail("content/products/kit-first-stitch.md 가 필요합니다.") kit = next((p for p in products if p["slug"].endswith("kit-first-stitch")), None)
if kit is None:
fail("키트로 쓸 작품이 없습니다. content/site.json 의 shop.kit_slug 를 지정하세요.")
kit_image = str(kit["image"]) kit_image = str(kit["image"])
kit_width, kit_height = image_size(kit_image) kit_width, kit_height = image_size(kit_image)
kit_body_html = markdown_to_html(kit["body"]) kit_body_html = markdown_to_html(kit["body"])
@@ -465,6 +470,7 @@ def build_index(
"og_title": esc(title), "og_title": esc(title),
"og_description": esc(intro), "og_description": esc(intro),
"og_image": esc(absolute_url(hero_image)), "og_image": esc(absolute_url(hero_image)),
"canonical": SITE_BASE,
"og_type": "website", "og_type": "website",
"body_class": "is-home", "body_class": "is-home",
"intro": esc(intro), "intro": esc(intro),
@@ -475,7 +481,14 @@ def build_index(
"hero_title": esc(featured["title"]), "hero_title": esc(featured["title"]),
"hero_material": esc(featured.get("material", "")), "hero_material": esc(featured.get("material", "")),
"hero_href": f"p/{featured['slug']}.html", "hero_href": f"p/{featured['slug']}.html",
"products": product_loop_items(products), "works_note": esc(site.get("works_note", "")),
"products": product_loop_items([p for p in products if not p.get("sold_out")]),
"sold_products": product_loop_items([p for p in products if p.get("sold_out")]),
"sold_count": str(sum(1 for p in products if p.get("sold_out"))),
"sold_empty_html": ("" if any(p.get("sold_out") for p in products)
else '<p class="note">아직 판매 완료된 작품이 없습니다. 판매되면 이 자리에 모아 두고, 같은 무늬로 다시 만들 수 있도록 문의 버튼을 붙입니다.</p>'),
"sold_note": esc(site.get("sold_works_note", "")),
"kakao_url": esc(str(site.get("contact", {}).get("kakao", "")).strip()),
"process": process_loop_items(steps), "process": process_loop_items(steps),
"process_intro": esc(site.get("process_intro", "")), "process_intro": esc(site.get("process_intro", "")),
"kit_title": esc(kit["title"]), "kit_title": esc(kit["title"]),
@@ -522,7 +535,11 @@ def build_product_page(
width, height = image_size(image) width, height = image_size(image)
if product.get("sold_out"): if product.get("sold_out"):
buy_html = '<p class="pending">판매 완료</p>' buy_html = (
f'<button class="btn inquiry-btn" type="button" data-inquiry="{esc(product["title"])}">'
"카톡으로 제작 문의</button>"
'<p class="inquiry-note">재고가 없어 주문을 받은 뒤 제작합니다. 아래 문구가 복사되니 카톡 대화창에 붙여넣어 주세요.</p>'
)
else: else:
naver_url = str(product.get("naver_url", "")).strip() naver_url = str(product.get("naver_url", "")).strip()
if naver_url: if naver_url:
@@ -558,6 +575,10 @@ def build_product_page(
subtitle = str(product.get("subtitle", "")).strip() subtitle = str(product.get("subtitle", "")).strip()
material = str(product.get("material", "")).strip() material = str(product.get("material", "")).strip()
price_note = str(product.get("price_note", "")).strip()
price_note_html = (
f'<p class="product-price-note">{esc(price_note)}</p>' if price_note else ""
)
description = ". ".join(part for part in (subtitle, material) if part) description = ". ".join(part for part in (subtitle, material) if part)
title = f"{product['title']} — {brand['name']}" title = f"{product['title']} — {brand['name']}"
@@ -569,6 +590,7 @@ def build_product_page(
"og_title": esc(title), "og_title": esc(title),
"og_description": esc(description), "og_description": esc(description),
"og_image": esc(absolute_url(image)), "og_image": esc(absolute_url(image)),
"canonical": absolute_url("p/" + product["slug"] + ".html"),
"og_type": "product", "og_type": "product",
"body_class": "is-product", "body_class": "is-product",
"slug": esc(product["slug"]), "slug": esc(product["slug"]),
@@ -580,8 +602,10 @@ def build_product_page(
"title_text": esc(product["title"]), "title_text": esc(product["title"]),
"subtitle": esc(subtitle), "subtitle": esc(subtitle),
"price_text": format_price(product.get("price")), "price_text": format_price(product.get("price")),
"price_note_html": price_note_html,
"sold_html": '<p class="product-sold">판매 완료</p>' if product.get("sold_out") else "", "sold_html": '<p class="product-sold">판매 완료</p>' if product.get("sold_out") else "",
"buy_html": buy_html, "buy_html": buy_html,
"inquiry_title": esc(product["title"]),
"material": esc(material) or "—", "material": esc(material) or "—",
"size": esc(product.get("size", "")) or "—", "size": esc(product.get("size", "")) or "—",
"care": esc(product.get("care", "")) or "—", "care": esc(product.get("care", "")) or "—",
+1 -1
View File
@@ -1,7 +1,7 @@
--- ---
step: 1 step: 1
title: 천 고르기 title: 천 고르기
image: assets/img/craft-jogakbo.jpg image: assets/img/process/fabric.jpg
image_alt: 여러 색 천 조각을 이어 붙인 조각보 image_alt: 여러 색 천 조각을 이어 붙인 조각보
--- ---
린넨은 물에 한 번 담갔다 말려 수축을 빼고 시작합니다. 햇빛에 비춰 올이 고른 쪽, 빛을 고르게 받는 쪽을 고릅니다. 천의 폭이 좁으면 두 폭을 이어 붙입니다. 린넨은 물에 한 번 담갔다 말려 수축을 빼고 시작합니다. 햇빛에 비춰 올이 고른 쪽, 빛을 고르게 받는 쪽을 고릅니다. 천의 폭이 좁으면 두 폭을 이어 붙입니다.
+1 -1
View File
@@ -1,7 +1,7 @@
--- ---
step: 3 step: 3
title: 한 땀 놓기 title: 한 땀 놓기
image: assets/img/work-green-linen.jpg image: assets/img/process/stitch.jpg
image_alt: 성긴 직물 위에 녹색 실로 놓은 자수 image_alt: 성긴 직물 위에 녹색 실로 놓은 자수
--- ---
실은 한 번에 길게 빼지 않습니다. 한 땀 놓고, 손을 내리고, 다시 바늘을 잡습니다. 꽃잎은 안쪽에서 바깥으로, 잎은 줄기에서 끝으로 놓습니다. 하루에 두어 시간이 지나면 손목이 먼저 쉬자고 합니다. 실은 한 번에 길게 빼지 않습니다. 한 땀 놓고, 손을 내리고, 다시 바늘을 잡습니다. 꽃잎은 안쪽에서 바깥으로, 잎은 줄기에서 끝으로 놓습니다. 하루에 두어 시간이 지나면 손목이 먼저 쉬자고 합니다.
@@ -0,0 +1,21 @@
---
slug: 2026-10-kit-first-stitch
title: 처음 한 땀 티매트 키트
subtitle: 천과 실, 도안이 함께 오는 상자
date: 2026-10-05
price: 16000
sold_out: false
featured: false
image: assets/img/2026-10-kit-first-stitch/cover.jpg
image_alt: 여러 천 조각을 이어 붙인 조각보
gallery:
material: 린넨 천, 면사, 도안, 바늘
size: 완성 10 × 10 cm × 4장
care: 완성 후 미지근한 물에 단독 손세탁
naver_url: "https://smartstore.naver.com/lalashopkr/products/5758959852"
---
완제품이 아닙니다. 천 위에 도안이 옅게 앉아 있고, 실과 바늘이 한 상자에 함께 들었습니다. 도안을 따라 한 땀씩 놓으면 10 × 10 cm 티매트 네 장이 됩니다.
처음이시라면 가장자리부터 시작하시면 좋습니다. 실을 길게 빼지 않고, 한 땀 놓고 손을 한 번 내리는 리듬이 익숙해지면 안쪽으로 들어갑니다. 도안은 천의 결을 가리지 않도록 단순하게 그렸습니다.
막히면 메일로 연락하실 수 있습니다. 사진 한 장을 보내시면 어느 자리에서 멈추셨는지 함께 살펴보겠습니다. 한 장을 마치고 나면 바늘을 쥔 손이 조금 가벼워집니다.
@@ -0,0 +1,28 @@
---
slug: 2026-10-whitework-tea-mat
title: 쪽빛 사시코 티매트
subtitle: 흰 실로 놓는 네 가지 무늬
date: 2026-10-28
price: 15000
price_note: 네 장 세트 50,000원
sold_out: true
featured: true
image: assets/img/2026-10-whitework-tea-mat/cover.jpg
image_alt: 남색 면 천 네 장에 흰 실로 십자·칠보·마노하 무늬를 놓은 사시코 티매트
gallery:
- assets/img/2026-10-whitework-tea-mat/detail-01.jpg
- assets/img/2026-10-whitework-tea-mat/detail-02.jpg
- assets/img/2026-10-whitework-tea-mat/detail-03.jpg
- assets/img/2026-10-whitework-tea-mat/detail-04.jpg
material: 면 100% (남색·자주) · 사시코 실(면)
size: 10 × 10 cm (한 장)
care: 미지근한 물에 중성세제로 단독 손세탁
naver_url: ""
---
짙은 남색 면 위에 흰 사시코 실을 앉혔습니다. 십자가 이어지는 무늬, 겹친 원이 늘어서는 칠보, 별처럼 뻗어 나가는 마노하 — 네 장에 서로 다른 무늬를 하나씩 수놓았습니다.
도안선을 따라 한 땀씩 나아갑니다. 실이 천의 올을 지나며 결이 살아나고, 남색과 흰 실의 대비가 무늬의 선을 또렷하게 세웁니다. 실은 오리무파스 사시코실을 씁니다.
한 장은 15,000원이며, 네 장을 한 세트로 묶으면 50,000원입니다. 무늬와 장수는 메일로 알려주시면 그에 맞추어 놓습니다.
자주빛으로 물들인 천도 함께 두었습니다. 같은 무늬라도 색이 바뀌면 다른 표정이 되며, 쓰고 난 뒤에는 미지근한 물에 단독으로 손세탁하고 그늘에 뉘어 말립니다. 장마다 실을 앉힌 자리가 조금씩 달라, 네 장을 나란히 두면 그 차이가 드러납니다.
@@ -0,0 +1,24 @@
---
slug: 2026-11-cherry-blossom-purple-linen
title: 자주색 위의 벚꽃
subtitle: 하프 린넨 한 장
date: 2026-11-01
price: ""
price_note: ""
sold_out: false
featured: false
image: assets/img/2026-11-cherry-blossom-purple-linen/cover.jpg
image_alt: 자주색 하프 린넨 위에 흰 실로 벚꽃과 작은 사각형을 놓은 자수 천의 앞면
gallery:
- assets/img/2026-11-cherry-blossom-purple-linen/detail-01.jpg
- assets/img/2026-11-cherry-blossom-purple-linen/detail-02.jpg
material: 11수 코튼린넨(국내산) · 사시코 전용실
size: 10 × 10 cm (한 장)
care: 미지근한 물에 중성세제로 단독 손세탁
naver_url: ""
---
자주색 하프 린넨 위에 흰 실로 벚꽃을 앉혔습니다. 꽃무늬 사이사이로 작은 사각형이 번갈아 놓여, 무늬의 간격을 잡습니다.
앞면과 뒷면은 같은 원단으로 맞추었습니다. 뒤집어 들어도 바탕의 색과 결이 그대로 이어집니다.
자수는 천 위에 실이 앉은 만큼만 두께를 냅니다. 자주색 바탕과 흰 실의 대비가 무늬의 윤곽을 이룹니다. 꽃잎을 따라 실을 앉힌 자리는 손으로 만지면 조금 도톰합니다.
@@ -0,0 +1,25 @@
---
slug: 2026-11-copenhagen-embroidery
title: 코펜하겐, 천 위에 앉히다
subtitle: 이름을 수놓는 일
date: 2026-11-01
price: 98000
price_note: ""
sold_out: false
featured: false
image: assets/img/2026-11-copenhagen-embroidery/cover.jpg
image_alt: 천 위에 실올이 한 땀씩 앉은 코펜하겐 자수 작품을 담은 대표 사진.
gallery:
- assets/img/2026-11-copenhagen-embroidery/detail-01.jpg
- assets/img/2026-11-copenhagen-embroidery/detail-02.jpg
- assets/img/2026-11-copenhagen-embroidery/detail-03.jpg
material: 린넨 100%, 면사 자수
size: ""
care: ""
naver_url: ""
---
코펜하겐이라는 이름의 자수가 천 위에 앉았습니다. 이름 하나가 작품의 첫 문장이 되고, 그 아래로 실올이 한 땀씩 제자리를 찾아갑니다. 도시의 이름을 빌렸으나 완성되는 것은 손의 리듬입니다.
천의 결을 따라 바늘을 세우고, 실은 조이지 않고 놓아둡니다. 성급히 당기면 천이 울고, 알맞게 앉히면 표면이 고르게 정돈됩니다. 그 차이는 손이 먼저 알고 눈이 나중에 알아차립니다.
마지막 땀을 매듭지으면 실은 조용히 천에 눌러앉습니다. 창가의 빛이 비스듬히 들 때, 수놓인 자리의 두께가 손끝에 남는 하루입니다.
@@ -0,0 +1,21 @@
---
slug: 2026-11-magnolia-tea-mat
title: 목련 한 땀 티매트
subtitle: 봄볕에 널어둔 천
date: 2026-11-01
price: 58000
sold_out: false
featured: false
image: assets/img/2026-11-magnolia-tea-mat/cover.jpg
image_alt: 아이보리 린넨 위에 흰 실로 목련 가지를 놓은 티매트
gallery:
material: 린넨 100%, 면사 자수
size: 30 × 45 cm
care: 미지근한 물에 중성세제로 단독 손세탁
naver_url: ""
---
아이보리 린넨 한 폭을 넓게 펴고, 목련 한 가지를 놓았습니다. 꽃잎은 흰 실로, 가지는 회갈색 실로. 천과 실의 색이 가까워서 가까이에서야 무늬가 보입니다.
꽃잎마다 실의 방향을 바꿔 빛이 드는 쪽을 남겼습니다. 창가에 놓으면 오후에 무늬가 한 번 더 드러납니다.
가장자리는 손으로 접어 박음질하고 귀퉁이를 두 번 돌려 마무리했습니다. 완성까지 열흘 남짓 걸렸습니다. 쓰고 나면 미지근한 물에 단독으로 손세탁하고 그늘에 뉘어 말립니다.
@@ -0,0 +1,27 @@
---
slug: 2026-11-sashiko-coaster-blue
title: 파란 천 위의 흰 올
subtitle: 사시코 코스터
date: 2026-11-01
price: 15000
price_note: ""
sold_out: false
featured: false
image: assets/img/2026-11-sashiko-coaster-blue/cover.jpg
image_alt: 파란 천에 흰 실로 격자를 수놓은 코스터 위에 회색 머그컵이 놓인 모습.
gallery:
- assets/img/2026-11-sashiko-coaster-blue/detail-01.jpg
- assets/img/2026-11-sashiko-coaster-blue/detail-02.jpg
- assets/img/2026-11-sashiko-coaster-blue/detail-03.jpg
material: 11수 코튼린넨(국내산) · 사시코 전용실
size: 10 × 10 cm (한 장)
care: 미지근한 물에 중성세제로 단독 손세탁
naver_url: ""
---
파란 천 위에 흰 실이 한 땀씩 앉습니다. 일정한 간격으로 놓인 점선이 격자를 이루고, 그 사이로 천의 올이 고요히 비칩니다.
회색 머그컵을 그 위에 올려 두면, 검은 액체의 온기가 천을 지나 아래로 천천히 옮겨 갑니다. 컵과 탁자 사이에 겹을 하나 두는 일, 그 작은 거리에서 코스터의 쓰임이 시작됩니다.
사시코는 선을 긋는 일이라기보다 올 사이에 숨을 고르는 일에 가깝습니다. 바늘이 지나간 자리마다 실의 두께가 남고, 그 두께가 천의 여백을 조금씩 밀어냅니다.
오후의 빛이 파란 천 위를 지나면, 흰 실 높이만큼 짧은 그림자가 놓입니다.
@@ -0,0 +1,33 @@
---
slug: 2026-11-sashiko-coaster-kit
title: 사시코 티코스터 패키지
subtitle: 네 가지 무늬를 한 장씩
date: 2026-11-01
price: 16000
sold_out: false
featured: false
image: assets/img/2026-11-sashiko-coaster-kit/cover.jpg
image_alt: 와인빛 코튼린넨 네 장에 흰 실로 격자·꽃·육각·지그재그 무늬를 놓은 사시코 티코스터
gallery:
- assets/img/2026-11-sashiko-coaster-kit/detail-01.jpg
- assets/img/2026-11-sashiko-coaster-kit/detail-02.jpg
- assets/img/2026-11-sashiko-coaster-kit/detail-03.jpg
- assets/img/2026-11-sashiko-coaster-kit/detail-04.jpg
- assets/img/2026-11-sashiko-coaster-kit/detail-05.jpg
- assets/img/2026-11-sashiko-coaster-kit/detail-06.jpg
material: 11수 코튼린넨(국내산, 뒷감도 같은 원단) · 사시코 전용실 1타래
size: 완성 10 × 10 cm × 4장 (±1 cm)
care: 자수 완성 전 다림질 금지 · 물세탁은 30분 담갔다 그늘 건조
naver_url: "https://smartstore.naver.com/lalashopkr/products/13640131815"
---
전사지가 없습니다. 도안이 원단 위에 이미 프린트되어 오므로, 봉투를 열어 실을 꿰면 곧바로 첫 땀을 놓으실 수 있습니다. 11수 코튼린넨 네 장과 사시코 전용실 한 타래가 함께 담겨 옵니다. 바늘과 설명서는 들어 있지 않습니다.
무늬는 격자, 꽃, 육각, 지그재그 네 가지입니다. 한 장에 하나씩, 와인빛 천 위에 흰 도안이 앉아 있습니다. 모두 놓으면 손바닥만 한 티코스터 네 장이 되고, 뒷감도 같은 원단이라 안쪽까지 같은 색으로 마무리됩니다. 네 장을 다 놓을 무렵이면 도안선보다 손의 리듬이 먼저 기억됩니다.
다림질은 마지막에 한 번만 하십시오. 도안 위에 다리미를 대면 도안이 깔끔하게 지워집니다. 실수로 지우셨다면 냉동실에 한 시간 두면 대부분 돌아오지만, 흰색 도안은 돌아오지 않습니다.
린넨은 물에 담그면 줄어듭니다. 물세탁할 작품이라면 30분 담갔다가 그늘에 말린 뒤에 수를 놓으십시오.
이 상품은 주문을 받은 뒤 재단하고 프린팅하여 보냅니다. 그래서 발송까지 최대 일주일이 걸리고, 단순 변심으로는 교환·반품이 어렵습니다. 배송비는 3,400원이며 6만원 이상이면 무료입니다. 제주는 2,000원, 제주 외 도서지역은 4,000원이 더 붙습니다.
도안과 촬영 사진의 저작권은 라라원단에 있습니다. 상업적인 사용은 삼가 주십시오.
-21
View File
@@ -1,21 +0,0 @@
---
slug: cedar-tea-mat
title: 솔잎 티매트
subtitle: 창가에 놓은 작은 숲
date: 2026-10-18
price: 62000
sold_out: false
featured: false
image: assets/img/work-green-linen.jpg
image_alt: 성긴 아이보리 직물 위에 녹색 실로 잎을 놓은 티매트
gallery:
material: 린넨 100%, 면사 자수
size: 32 × 48 cm
care: 미지근한 물에 중성세제로 단독 손세탁
naver_url: ""
---
성긴 린넨의 올 사이로 빛이 지나갑니다. 그 위에 녹색 면사로 솔잎을 길게 놓았습니다. 잎마다 방향을 조금씩 달리해, 같은 잎이 반복되지 않게 했습니다.
가장자리는 접어 박음질하고, 귀퉁이마다 실을 두 번 돌려 마무리했습니다. 티포트를 올리면 잎의 방향을 따라 그림자가 생깁니다.
한 점에 보름 남짓 걸렸습니다. 실의 색은 세 가지를 나란히 놓고 골랐습니다. 쓰고 나면 미지근한 물에 단독으로 손세탁하고 그늘에 뉘어 말립니다.
-21
View File
@@ -1,21 +0,0 @@
---
slug: kit-first-stitch
title: 처음 한 땀 티매트 키트
subtitle: 천과 실, 도안이 함께 오는 상자
date: 2026-10-05
price: 32000
sold_out: false
featured: false
image: assets/img/craft-jogakbo.jpg
image_alt: 여러 천 조각을 이어 붙인 조각보
gallery:
material: 린넨 천, 면사, 도안, 바늘
size: 완성 30 × 45 cm
care: 완성 후 미지근한 물에 단독 손세탁
naver_url: ""
---
완제품이 아닙니다. 천에 도안이 옅게 찍혀 있고, 실과 바늘이 함께 들어 있습니다. 도안을 따라 한 땀씩 놓으면 30 × 45 cm 티매트 한 장이 됩니다.
처음이면 가장자리부터 시작하세요. 실을 길게 빼지 않고, 한 땀 놓고 손을 한 번 내리는 리듬이 익숙해지면 안쪽으로 들어갑니다. 도안은 단순하게 그렸습니다. 천의 결을 가리지 않도록.
막히면 메일로 물어보셔도 됩니다. 사진 한 장을 보내주시면 어느 자리에서 멈췄는지 함께 봅니다.
-21
View File
@@ -1,21 +0,0 @@
---
slug: whitework-tea-mat
title: 목련 한 땀 티매트
subtitle: 봄볕에 널어둔 천
date: 2026-10-28
price: 58000
sold_out: false
featured: true
image: assets/img/work-whitework.jpg
image_alt: 아이보리 린넨 위에 흰 실로 문양을 놓은 티매트
gallery:
material: 린넨 100%, 면사 자수
size: 30 × 45 cm
care: 미지근한 물에 중성세제로 단독 손세탁
naver_url: ""
---
아이보리 린넨 위에 흰 면사로 목련 한 송이를 놓았습니다. 꽃잎의 윤곽은 실을 두 번 겹쳐 놓고, 안쪽은 올을 풀어 비웠습니다.
가장자리는 실 한 올씩 풀어 올을 정리했습니다. 찻잔을 올리면 천의 결이 비쳐 보이고, 물기가 닿아도 금세 마릅니다.
한 점에 열흘 남짓 걸렸습니다. 하루에 두어 시간씩, 손이 가는 만큼 천천히 놓았습니다. 쓰고 나면 미지근한 물에 단독으로 손세탁하고 그늘에 뉘어 말립니다.
+17 -7
View File
@@ -9,13 +9,15 @@
"contact": { "contact": {
"email": "hello@hanttam.kr", "email": "hello@hanttam.kr",
"instagram": "", "instagram": "",
"kakao": "" "kakao": "https://pf.kakao.com/_VsLWX/friend"
}, },
"shop": { "shop": {
"store_url": "", "kit_slug": "2026-10-kit-first-stitch",
"kit_url": "", "store_url": "https://smartstore.naver.com/lalashopkr",
"kit_url": "https://smartstore.naver.com/lalashopkr/products/5758959852",
"kit_note": "린넨 천, 면사, 도안, 바늘 — 처음 시작하는 사람에게 필요한 것들" "kit_note": "린넨 천, 면사, 도안, 바늘 — 처음 시작하는 사람에게 필요한 것들"
}, },
"works_note": "완성품은 한 점씩 미리 만들어 두고, 재고가 있을 때만 판매합니다. 판매된 작품은 같은 무늬로 다시 만들 수 있으나, 재제작 문의가 있을 때만 진행합니다. 최근에 만든 순서로 놓았습니다.",
"process_intro": "천을 고르고, 도안을 옮기고, 한 땀씩 놓아 마감하기까지. 서두르지 않고 네 단계로 만납니다.", "process_intro": "천을 고르고, 도안을 옮기고, 한 땀씩 놓아 마감하기까지. 서두르지 않고 네 단계로 만납니다.",
"shipping": [ "shipping": [
"주문 후 3~5일 이내 제작·발송", "주문 후 3~5일 이내 제작·발송",
@@ -29,8 +31,16 @@
"product_sort": "newest", "product_sort": "newest",
"footer_note": "사업자등록번호와 통신판매업 신고 번호는 추후 기재합니다.", "footer_note": "사업자등록번호와 통신판매업 신고 번호는 추후 기재합니다.",
"image_credits": [ "image_credits": [
{"title": "Linen towel with drawn threadwork and whitework embroidery", "author": "Wikimedia Commons", "license": "Public domain"}, {
{"title": "Japanese flat silk embroidery on leno-weave fabric", "author": "Ineffablebookkeeper", "license": "CC BY-SA 4.0"}, "title": "Japanese flat silk embroidery on leno-weave fabric",
{"title": "Wrapping cloth (bojagi), Korea", "author": "Hiart", "license": "CC0"} "author": "Ineffablebookkeeper",
] "license": "CC BY-SA 4.0"
},
{
"title": "Wrapping cloth (bojagi), Korea",
"author": "Hiart",
"license": "CC0"
}
],
"sold_works_note": "재고가 없는 작품입니다. 같은 무늬로 다시 만들 수 있어요 — 카톡으로 문의하시면 제작 일정과 값을 함께 알려 드립니다."
} }
+9 -8
View File
@@ -3,20 +3,21 @@ set -euo pipefail
cd "$(dirname "$0")/.." cd "$(dirname "$0")/.."
REMOTE="admin@100.101.79.24" # 2026-11-27: 공개 사이트는 이 폴더의 dist/ 를 그대로 서빙한다.
REMOTE_DIR="/share/CACHEDEV8_DATA/web/www/teamat/" # umbrel 컨테이너 `web`(caddy :8082) → https://teamat.lala.dedyn.io/ , https://home.lala.dedyn.io/teamat/
# (마운트: /Home/teamat/dist → 웹루트). 그래서 build 만 하면 즉시 반영되고,
# QNAP 으로의 rsync 배포 단계는 폐지했다.
SITE_URL="https://home.lala.dedyn.io/teamat/" SITE_URL="https://home.lala.dedyn.io/teamat/"
SITE_URL2="https://teamat.lala.dedyn.io/"
python3 build.py python3 build.py
echo
echo "배포: ${REMOTE}:${REMOTE_DIR}"
rsync -az --delete dist/ "${REMOTE}:${REMOTE_DIR}"
status="$(curl -s -o /dev/null -w '%{http_code}' "$SITE_URL")" status="$(curl -s -o /dev/null -w '%{http_code}' "$SITE_URL")"
if [ "$status" != "200" ]; then if [ "$status" != "200" ]; then
echo "배포 후 확인 실패: ${SITE_URL} (HTTP ${status})" >&2 echo "확인 실패: ${SITE_URL} (HTTP ${status})" >&2
exit 1 exit 1
fi fi
echo "배포 완료: ${SITE_URL} (HTTP ${status})" status2="$(curl -s --max-time 15 -o /dev/null -w '%{http_code}' "$SITE_URL2" || true)"
echo "반영 완료: ${SITE_URL} (HTTP ${status})"
echo "전용 도메인: ${SITE_URL2} (HTTP ${status2:-000})"
+51
View File
@@ -0,0 +1,51 @@
#!/usr/bin/env bash
# QNAP 에서 등록 서버(teamat-admin)를 띄운다. 컨테이너는 호스트 포트 8089 를 쓰고,
# Caddy 가 teamat-admin.lala.dedyn.io -> 100.101.79.24:8089 로 넘긴다.
#
# bash scripts/run-qnap.sh build # 이미지 빌드
# bash scripts/run-qnap.sh up # (재)시작
# bash scripts/run-qnap.sh down # 중지
# bash scripts/run-qnap.sh logs # 로그
set -euo pipefail
DOCKER="${DOCKER:-/share/CACHEDEV7_DATA/.qpkg/container-station/bin/docker}"
BASE="${BASE:-/share/CACHEDEV8_DATA/docker/teamat-admin}"
WEB_ROOT="${WEB_ROOT:-/share/CACHEDEV8_DATA/web/www/teamat}"
NAME="teamat-admin"
IMAGE="teamat-admin:1"
PORT="${PORT:-8089}"
case "${1:-up}" in
build)
cd "$BASE/repo"
"$DOCKER" build -f studio/Dockerfile.qnap -t "$IMAGE" .
;;
up)
"$DOCKER" rm -f "$NAME" >/dev/null 2>&1 || true
"$DOCKER" run -d --name "$NAME" --restart unless-stopped \
-p "127.0.0.1:$PORT:$PORT" \
-v "$BASE/repo":/repo \
-v "$BASE/config":/config \
-v "$BASE/data":/data \
-v "$WEB_ROOT":/web \
-v "$BASE/.gitconfig":/root/.gitconfig:ro \
-v "$BASE/.git-credentials":/root/.git-credentials \
-e TEAMAT_WEB_ROOT=/web \
-e TEAMAT_ARCHIVE=/data/photos \
-e TEAMAT_PUSH=1 \
-e TEAMAT_DEFAULT_PAGE=m \
"$IMAGE"
sleep 2
"$DOCKER" logs --tail 5 "$NAME" || true
;;
down)
"$DOCKER" rm -f "$NAME"
;;
logs)
"$DOCKER" logs --tail 60 "$NAME"
;;
*)
echo "사용법: bash scripts/run-qnap.sh [build|up|down|logs]" >&2
exit 1
;;
esac
+58
View File
@@ -0,0 +1,58 @@
#!/usr/bin/env bash
# 한땀 작업실 서버를 macOS 로그인 항목(launchd)으로 등록한다.
# bash scripts/studio-service.sh install # 설치 + 시작
# bash scripts/studio-service.sh status # 상태
# bash scripts/studio-service.sh stop # 중지 + 등록 해제
set -euo pipefail
LABEL="io.lala.teamat-studio"
PLIST="$HOME/Library/LaunchAgents/$LABEL.plist"
REPO="$(cd "$(dirname "$0")/.." && pwd)"
PORT="${PORT:-8081}"
PY="$(command -v python3)"
case "${1:-install}" in
install)
mkdir -p "$HOME/Library/LaunchAgents" "$HOME/Library/Logs"
cat > "$PLIST" <<PLISTEOF
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key><string>$LABEL</string>
<key>ProgramArguments</key>
<array>
<string>$PY</string><string>$REPO/studio/server.py</string>
<string>--port</string><string>$PORT</string>
</array>
<key>WorkingDirectory</key><string>$REPO</string>
<key>RunAtLoad</key><true/>
<key>KeepAlive</key><true/>
<key>StandardOutPath</key><string>$HOME/Library/Logs/teamat-studio.log</string>
<key>StandardErrorPath</key><string>$HOME/Library/Logs/teamat-studio.err.log</string>
</dict>
</plist>
PLISTEOF
# 손으로 띄운 서버가 있으면 먼저 정리(포트 충돌 방지)
pkill -f "[s]tudio/server.py" 2>/dev/null || true
launchctl bootout "gui/$(id -u)/$LABEL" 2>/dev/null || true
launchctl bootstrap "gui/$(id -u)" "$PLIST"
launchctl kickstart -k "gui/$(id -u)/$LABEL" 2>/dev/null || true
sleep 1
echo "설치 완료: $LABEL (포트 $PORT)"
curl -s -o /dev/null -w "로컬 응답: HTTP %{http_code}\n" "http://127.0.0.1:$PORT/m" || true
;;
status)
launchctl print "gui/$(id -u)/$LABEL" 2>/dev/null | sed -n '1,10p' || echo "실행 중 아님"
curl -s -o /dev/null -w "로컬 응답: HTTP %{http_code}\n" "http://127.0.0.1:$PORT/m" || true
;;
stop)
launchctl bootout "gui/$(id -u)/$LABEL" 2>/dev/null || true
rm -f "$PLIST"
echo "중지 및 등록 해제"
;;
*)
echo "사용법: bash scripts/studio-service.sh [install|status|stop]" >&2
exit 1
;;
esac
+17
View File
@@ -0,0 +1,17 @@
# 한땀 작업실(QNAP) — 등록 서버 이미지
# 사진 축소·회전에 Pillow 를 쓰고, 커밋·푸시에 git 이 필요하다.
FROM python:3.12-slim
RUN apt-get update \
&& apt-get install -y --no-install-recommends git ca-certificates \
&& rm -rf /var/lib/apt/lists/* \
&& pip install --no-cache-dir pillow==11.3.0
ENV PYTHONUNBUFFERED=1 \
PYTHONDONTWRITEBYTECODE=1 \
TEAMAT_CONFIG_DIR=/config \
TEAMAT_DEFAULT_PAGE=m
WORKDIR /repo
EXPOSE 8089
CMD ["python3", "studio/server.py", "--port", "8089", "--host", "0.0.0.0"]
+90
View File
@@ -0,0 +1,90 @@
#!/usr/bin/env python3
"""AI 프롬프트 수정/초안 API 스모크 테스트 — 호출만 하고 저장은 하지 않는다."""
import json
import subprocess
import sys
import urllib.error
import urllib.request
BASE = "http://127.0.0.1:8081"
fails = []
def check(name, cond, extra=""):
print(("OK " if cond else "FAIL ") + name + (f"\n {extra}" if extra else ""))
if not cond:
fails.append(name)
def post(path, payload):
request = urllib.request.Request(
BASE + path,
data=json.dumps(payload).encode(),
headers={"Content-Type": "application/json"},
method="POST",
)
try:
with urllib.request.urlopen(request, timeout=300) as res:
return res.status, json.loads(res.read().decode())
except urllib.error.HTTPError as error:
body = error.read().decode()
try:
return error.code, json.loads(body)
except json.JSONDecodeError:
return error.code, {"raw": body}
def git_status():
return subprocess.run(["git", "status", "--porcelain"], cwd="/Users/woozooni/Projects/teamat",
capture_output=True, text=True).stdout.strip()
before_status = git_status()
before_head = subprocess.run(["git", "rev-parse", "--short", "HEAD"], cwd="/Users/woozooni/Projects/teamat",
capture_output=True, text=True).stdout.strip()
# 1) 작품 수정 제안
code, data = post("/api/ai", {"mode": "edit", "slug": "2026-10-whitework-tea-mat",
"prompt": "부제를 더 담백하게, 20자 이내로. 본문은 그대로 둬."})
check("edit 200", code == 200 and data.get("ok") is True, json.dumps(data, ensure_ascii=False)[:400])
if data.get("ok"):
check("note 있음", bool(data.get("note")), str(data.get("note")))
check("변경 있음", bool(data.get("changes")), json.dumps({k: v for k, v in data.get("changes", {}).items() if k != "body"}, ensure_ascii=False))
check("부제만 바뀜", set(data.get("changes", {}).keys()) <= {"subtitle"}, str(list(data.get("changes", {}).keys())))
check("본문 유지", "body" not in data.get("changes", {}))
print(" 제안:", data.get("note"))
for k, v in data.get("changes", {}).items():
print(f" {k}: {str(v)[:120]}")
# 2) 본문 다시 쓰기
code, data2 = post("/api/ai", {"mode": "edit", "slug": "2026-10-whitework-tea-mat",
"prompt": "본문을 3문단으로 다시 써. 재료와 걸린 시간을 숫자로 넣어."})
if data2.get("ok"):
body = data2.get("changes", {}).get("body", "")
check("본문 변경 제안", bool(body), str(list(data2.get("changes", {}).keys())))
check("본문 3문단 근사", body.count("\n\n") >= 1, str(body.count("\n\n")))
print(" 본문 앞부분:", body[:160].replace("\n", " / "))
# 3) 새 작품 초안
code, draft = post("/api/ai", {"mode": "draft",
"prompt": "겨울 매화 티매트, 32×48cm, 린넨 100%, 62000원. 눈 내린 창가 분위기."})
check("draft 200", code == 200 and draft.get("ok") is True, json.dumps(draft, ensure_ascii=False)[:400])
if draft.get("ok"):
fields = draft.get("fields", {})
check("draft 제목", bool(str(fields.get("title", "")).strip()), str(fields.get("title")))
check("draft slug 형식", bool(fields.get("slug")) and all(c.islower() or c.isdigit() or c == "-" for c in str(fields.get("slug"))), str(fields.get("slug")))
check("draft 본문", len(str(draft.get("body", ""))) > 60, str(len(str(draft.get("body", "")))))
print(" 초안:", fields.get("slug"), "|", fields.get("title"), "|", fields.get("price"), "|", fields.get("size"))
# 4) 빈 요청 거부
code, bad = post("/api/ai", {"mode": "edit", "slug": "2026-10-whitework-tea-mat", "prompt": ""})
check("빈 요청 거부", code == 400, str(code))
# 5) AI 호출이 저장소를 건드리지 않아야 한다
check("git 상태 불변", git_status() == before_status, git_status())
check("HEAD 불변", subprocess.run(["git", "rev-parse", "--short", "HEAD"], cwd="/Users/woozooni/Projects/teamat",
capture_output=True, text=True).stdout.strip() == before_head)
print()
print("실패 " + str(len(fails)) + "건: " + ", ".join(fails) if fails else "전부 통과")
sys.exit(1 if fails else 0)
+285 -13
View File
@@ -146,6 +146,30 @@
button.ghost { background: none; border-color: transparent; color: var(--muted); } button.ghost { background: none; border-color: transparent; color: var(--muted); }
button.ghost:hover { color: var(--accent); } button.ghost:hover { color: var(--accent); }
/* ---------- AI 프롬프트 ---------- */
.ai-bar { border-bottom: 1px solid var(--line); padding: 10px 20px 12px; background: #fbf8f2; }
.ai-row { display: flex; gap: 8px; align-items: flex-start; }
.ai-row select { width: auto; font-size: 12.5px; padding: 7px 8px; }
.ai-row textarea { flex: 1; min-height: 46px; font-family: inherit; font-size: 13.5px; line-height: 1.5; }
.ai-examples { display: flex; flex-wrap: wrap; gap: 6px; margin-top: 7px; }
.ai-examples .chip { font-size: 11.5px; }
#aiStatus { margin-top: 6px; }
.ai-result { margin-top: 10px; border: 1px solid var(--accent); border-radius: 5px; background: #fff; padding: 12px 14px; }
.ai-note { font-size: 13px; margin: 0 0 9px; }
.ai-note strong { color: var(--accent); }
.ai-changes { width: 100%; border-collapse: collapse; font-size: 12.5px; margin-bottom: 10px; }
.ai-changes th, .ai-changes td { border-bottom: 1px solid var(--line); padding: 4px 6px; text-align: left; vertical-align: top; }
.ai-changes th { color: var(--muted); font-weight: 500; width: 92px; }
.ai-changes .old { color: var(--muted); text-decoration: line-through; }
.ai-changes .new { color: var(--ok); }
.ai-diff { font-family: ui-monospace, Menlo, monospace; font-size: 12px; line-height: 1.55; background: #fffdf9; border: 1px solid var(--line); border-radius: 4px; padding: 8px; max-height: 220px; overflow: auto; white-space: pre-wrap; }
.ai-diff .add { color: var(--ok); background: #edf6f0; }
.ai-diff .del { color: var(--warn); background: #fbefe9; text-decoration: line-through; }
.ai-actions { display: flex; gap: 8px; margin-top: 10px; align-items: center; }
.ai-actions .spacer { flex: 1; }
.ai-spin { display: inline-block; width: 10px; height: 10px; border: 2px solid var(--line); border-top-color: var(--accent); border-radius: 50%; animation: spin .8s linear infinite; vertical-align: -1px; margin-right: 5px; }
@keyframes spin { to { transform: rotate(360deg); } }
/* ---------- 이력 서랍 ---------- */ /* ---------- 이력 서랍 ---------- */
#drawer { #drawer {
position: fixed; inset: 0; background: rgba(31, 28, 24, .28); position: fixed; inset: 0; background: rgba(31, 28, 24, .28);
@@ -217,6 +241,7 @@
<option value="title">이름</option> <option value="title">이름</option>
<option value="price">가격</option> <option value="price">가격</option>
</select> </select>
<button id="btnNew" class="ghost" style="font-size:12px;padding:4px 8px;">+ 새 작품</button>
<span class="count" id="rowcount"></span> <span class="count" id="rowcount"></span>
</div> </div>
<ul class="rows" id="rows"></ul> <ul class="rows" id="rows"></ul>
@@ -229,6 +254,25 @@
<span class="spacer"></span> <span class="spacer"></span>
<span class="hint" id="edModified"></span> <span class="hint" id="edModified"></span>
</div> </div>
<div class="ai-bar" id="aiBar">
<div class="ai-row">
<select id="aiMode">
<option value="edit">이 작품 고치기</option>
<option value="draft">새 작품 초안</option>
</select>
<textarea id="aiPrompt" rows="2" placeholder="예) 부제를 더 담백하게. 본문은 3문단으로, 린넨 결을 첫 문장에."></textarea>
<button id="aiRun" class="primary">AI 실행</button>
</div>
<div class="ai-examples" id="aiExamples">
<button class="chip" data-p="부제를 더 담백하게, 20자 이내로">부제 간결하게</button>
<button class="chip" data-p="본문을 3문단으로 다시 써. 만드는 시간과 재료를 숫자로 넣어">본문 3문단</button>
<button class="chip" data-p="40~50대 여성이 읽기 편하게 문장을 짧게 끊어">문장 짧게</button>
<button class="chip" data-p="규격과 소재를 첫 문단에 자연스럽게 넣어">재료 강조</button>
</div>
<div class="hint" id="aiStatus"></div>
<div id="aiResult"></div>
</div>
<div class="editor-body" id="edBody"> <div class="editor-body" id="edBody">
<p class="empty">왼쪽 목록에서 작품을 고르면 여기서 바로 고칠 수 있습니다.</p> <p class="empty">왼쪽 목록에서 작품을 고르면 여기서 바로 고칠 수 있습니다.</p>
</div> </div>
@@ -282,7 +326,7 @@ async function api(path, opts) {
function markDirty(dirty) { function markDirty(dirty) {
state.dirty = dirty; state.dirty = dirty;
$('state').textContent = dirty ? '저장하지 않은 변경' : '변경 없음'; $('state').textContent = dirty ? '저장하지 않은 변경' : '변경 없음';
$('btnSave').disabled = !state.current || !dirty; $('btnSave').disabled = !($('f_slug') || state.current) || !dirty;
} }
/* ------------------------------------------------------------ 목록 */ /* ------------------------------------------------------------ 목록 */
@@ -347,7 +391,7 @@ function fieldHtml(f, value) {
'<span class="img-line"><input type="text" id="' + id + '" data-key="' + f.key + '" value="' + esc(value) + '">' + '<span class="img-line"><input type="text" id="' + id + '" data-key="' + f.key + '" value="' + esc(value) + '">' +
'<img class="img-preview" id="' + id + '_prev" src="' + (value ? '/media/' + encodeURI(value) : '') + '" alt="">' + '<img class="img-preview" id="' + id + '_prev" src="' + (value ? '/media/' + encodeURI(value) : '') + '" alt="">' +
'<button type="button" class="ghost" id="' + id + '_pick">올리기</button></span>' + '<button type="button" class="ghost" id="' + id + '_pick">올리기</button></span>' +
'<span class="drop-hint" id="' + id + '_hint">JPG를 여기로 끌어다 놓아도 됩니다 (assets/img 에 저장)</span></label>'; '<span class="drop-hint" id="' + id + '_hint">JPG를 끌어다 놓으면 assets/img/&lt;슬러그&gt;/ 에 저장됩니다</span></label>';
} }
const type = f.type === 'number' ? 'number' : (f.type === 'date' ? 'date' : (f.type === 'url' ? 'url' : 'text')); const type = f.type === 'number' ? 'number' : (f.type === 'date' ? 'date' : (f.type === 'url' ? 'url' : 'text'));
return '<label class="field' + wide + '"><span class="lbl">' + esc(f.label) + '</span>' + return '<label class="field' + wide + '"><span class="lbl">' + esc(f.label) + '</span>' +
@@ -355,10 +399,17 @@ function fieldHtml(f, value) {
} }
function renderEditor(p) { function renderEditor(p) {
const known = new Set(state.fields.map((f) => f.key)); const values = p.fields || {};
const grid = state.fields.map((f) => fieldHtml(f, p.fields[f.key])).join(''); const isDraft = !!p.draft;
const extra = p.extra_keys.length if (isDraft) state.current = null;
? '<p class="hint">이 파일에만 있는 키(보존됨): ' + p.extra_keys.map(esc).join(', ') + '</p>' const slugField = isDraft
? '<label class="field wide"><span class="lbl">슬러그 · 파일명 (연-월-제목, 영문 소문자)</span>' +
'<input type="text" id="f_slug" value="' + esc(p.slug || '') + '" placeholder="예: 2026-11-magnolia-tea-mat"></label>'
: '';
const grid = slugField + state.fields.map((f) => fieldHtml(f, values[f.key])).join('');
const extraKeys = p.extra_keys || [];
const extra = extraKeys.length
? '<p class="hint">이 파일에만 있는 키(보존됨): ' + extraKeys.map(esc).join(', ') + '</p>'
: ''; : '';
$('edBody').innerHTML = $('edBody').innerHTML =
'<div class="grid">' + grid + '</div>' + '<div class="grid">' + grid + '</div>' +
@@ -367,9 +418,9 @@ function renderEditor(p) {
'<textarea id="body" rows="14" style="min-height:240px">' + esc(p.body) + '</textarea>' + '<textarea id="body" rows="14" style="min-height:240px">' + esc(p.body) + '</textarea>' +
'<p class="hint" style="margin-top:8px">문단은 빈 줄로 나눕니다. <code>## 제목</code>, <code>- 목록</code>, <code>![설명](assets/img/파일.jpg)</code> 지원.</p>' + '<p class="hint" style="margin-top:8px">문단은 빈 줄로 나눕니다. <code>## 제목</code>, <code>- 목록</code>, <code>![설명](assets/img/파일.jpg)</code> 지원.</p>' +
'<div style="margin-top:10px">' + extra + '</div>'; '<div style="margin-top:10px">' + extra + '</div>';
$('edTitle').textContent = p.fields.title || p.slug; $('edTitle').textContent = isDraft ? '새 작품 (저장 전)' : (values.title || p.slug);
$('edSlug').textContent = p.slug; $('edSlug').textContent = isDraft ? '' : p.slug;
$('edModified').textContent = '파일 수정 ' + p.modified; $('edModified').textContent = isDraft ? 'AI 초안' : '파일 수정 ' + p.modified;
$('btnReload').disabled = false; $('btnReload').disabled = false;
wireEditor(); wireEditor();
markDirty(false); markDirty(false);
@@ -404,8 +455,11 @@ function pickImage(target) {
} }
async function uploadImage(file, target) { async function uploadImage(file, target) {
const slugEl = $('f_slug');
const slug = (slugEl ? slugEl.value.trim() : '') || state.current || '';
if (!slug) { toast('슬러그를 먼저 정해야 이미지를 넣을 수 있습니다', 'err'); return; }
$('state').textContent = '이미지 올리는 중…'; $('state').textContent = '이미지 올리는 중…';
const res = await fetch('/api/upload?name=' + encodeURIComponent(file.name), { const res = await fetch('/api/upload?name=' + encodeURIComponent(file.name) + '&slug=' + encodeURIComponent(slug), {
method: 'POST', headers: { 'Content-Type': 'application/octet-stream' }, body: file, method: 'POST', headers: { 'Content-Type': 'application/octet-stream' }, body: file,
}); });
const data = await res.json().catch(() => ({ ok: false, error: '업로드 실패' })); const data = await res.json().catch(() => ({ ok: false, error: '업로드 실패' }));
@@ -432,12 +486,18 @@ function collect() {
document.querySelectorAll('[data-key]').forEach((el) => { document.querySelectorAll('[data-key]').forEach((el) => {
fields[el.dataset.key] = el.type === 'checkbox' ? el.checked : el.value; fields[el.dataset.key] = el.type === 'checkbox' ? el.checked : el.value;
}); });
return { slug: state.current, fields, body: $('body').value, deploy: $('deployToo').checked }; const slugEl = $('f_slug');
return {
slug: slugEl ? slugEl.value.trim() : state.current,
fields, body: $('body').value,
deploy: $('deployToo').checked,
create: !!slugEl,
};
} }
async function save() { async function save() {
if (!state.current) return;
const payload = collect(); const payload = collect();
if (!payload.slug) { toast('슬러그를 입력해 주세요', 'err'); return; }
$('btnSave').disabled = true; $('btnSave').disabled = true;
$('state').textContent = '저장 중… (빌드 → 커밋)'; $('state').textContent = '저장 중… (빌드 → 커밋)';
const data = await api('/api/product', { const data = await api('/api/product', {
@@ -452,7 +512,13 @@ async function save() {
markDirty(false); markDirty(false);
const deployNote = data.deploy ? (data.deploy.ok ? ' / 배포 OK' : ' / 배포 실패') : ''; const deployNote = data.deploy ? (data.deploy.ok ? ' / 배포 OK' : ' / 배포 실패') : '';
toast(data.message + (data.commit ? ' · ' + data.commit : '') + deployNote + (data.log ? '\n' + data.log : ''), data.deploy && !data.deploy.ok ? 'err' : 'ok'); toast(data.message + (data.commit ? ' · ' + data.commit : '') + deployNote + (data.log ? '\n' + data.log : ''), data.deploy && !data.deploy.ok ? 'err' : 'ok');
if (payload.create) {
state.current = null;
await refresh({ keep: true }); await refresh({ keep: true });
await openProduct(payload.slug);
} else {
await refresh({ keep: true });
}
} }
async function refresh(opts = {}) { async function refresh(opts = {}) {
@@ -468,6 +534,175 @@ async function refresh(opts = {}) {
} }
} }
/* ------------------------------------------------------------ AI */
let aiLast = null;
let aiModelLabel = '';
function labels() {
const map = {};
state.fields.forEach((f) => { map[f.key] = f.label; });
return map;
}
function diffLines(before, after) {
const a = String(before || '').split('\n');
const b = String(after || '').split('\n');
const m = a.length, n = b.length;
const dp = Array.from({ length: m + 1 }, () => new Array(n + 1).fill(0));
for (let i = m - 1; i >= 0; i--) {
for (let j = n - 1; j >= 0; j--) {
dp[i][j] = a[i] === b[j] ? dp[i + 1][j + 1] + 1 : Math.max(dp[i + 1][j], dp[i][j + 1]);
}
}
const out = [];
let i = 0, j = 0;
while (i < m && j < n) {
if (a[i] === b[j]) { out.push({ t: 'same', s: a[i] }); i++; j++; }
else if (dp[i + 1][j] >= dp[i][j + 1]) { out.push({ t: 'del', s: a[i] }); i++; }
else { out.push({ t: 'add', s: b[j] }); j++; }
}
while (i < m) out.push({ t: 'del', s: a[i++] });
while (j < n) out.push({ t: 'add', s: b[j++] });
return out;
}
function diffHtml(before, after) {
const rows = diffLines(before, after);
const shown = rows.slice(0, 160).map((r) => {
if (r.t === 'same') return esc(r.s);
return '<span class="' + (r.t === 'add' ? 'add' : 'del') + '">' + (r.t === 'add' ? '+ ' : '- ') + esc(r.s) + '</span>';
});
if (rows.length > 160) shown.push('…');
return shown.join('\n');
}
async function loadAiStatus() {
const data = await api('/api/ai-status');
const el = $('aiStatus');
if (!data.ok || !data.configured) {
aiModelLabel = '';
el.innerHTML = 'AI 연결 안 됨: ' + esc(data.error || '키를 확인하세요');
el.style.color = 'var(--warn)';
return;
}
aiModelLabel = data.model || '';
el.textContent = 'AI: ' + data.model + ' · 키 출처 ' + data.source;
el.style.color = '';
}
async function runAi() {
const mode = $('aiMode').value;
const prompt = $('aiPrompt').value.trim();
if (prompt.length < 2) { toast('요청 내용을 입력해 주세요', 'err'); $('aiPrompt').focus(); return; }
if (mode === 'edit' && !state.current) { toast('먼저 왼쪽에서 작품을 고르세요', 'err'); return; }
$('aiRun').disabled = true;
$('aiResult').innerHTML = '';
$('aiStatus').innerHTML = '<span class="ai-spin"></span>' + (mode === 'draft' ? 'AI가 초안을 쓰는 중…' : 'AI가 고치는 중…');
const data = await api('/api/ai', {
method: 'POST', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ mode, slug: state.current, prompt }),
});
$('aiRun').disabled = false;
loadAiStatus();
if (!data.ok) { toast(data.error || 'AI 호출 실패', 'err'); return; }
if (mode === 'draft') { renderDraftResult(data); return; }
if (data.empty) {
aiLast = null;
$('aiResult').innerHTML = '<div class="ai-result"><p class="ai-note">' + esc(data.note || '바꿀 내용이 없습니다') + '</p><div class="ai-actions"><span class="spacer"></span><button class="ghost" onclick="document.getElementById(\'aiResult\').innerHTML=\'\'">닫기</button></div></div>';
return;
}
aiLast = data;
renderAiResult(data);
}
function renderAiResult(data) {
const map = labels();
const keys = Object.keys(data.changes).filter((k) => k !== 'body');
const rows = keys.map((key) => {
const before = data.current.fields[key] ?? '';
const after = data.changes[key] ?? '';
return '<tr><th>' + esc(map[key] || key) + '</th><td><span class="old">' + esc(String(before) || '(빈 값)') +
'</span><br><span class="new">' + esc(String(after) || '(비움)') + '</span></td></tr>';
}).join('');
const bodyChanged = Object.prototype.hasOwnProperty.call(data.changes, 'body');
const bodyBlock = bodyChanged
? '<div class="section-label">본문 변경</div><div class="ai-diff">' + diffHtml(data.current.body, data.changes.body) + '</div>'
: '';
const meta = [data.model || aiModelLabel, data.tokens ? data.tokens + ' 토큰' : ''].filter(Boolean).join(' · ');
$('aiResult').innerHTML =
'<div class="ai-result">' +
'<p class="ai-note"><strong>' + esc(data.note || 'AI 제안') + '</strong> <span class="hint">' + esc(meta) + '</span></p>' +
(rows ? '<table class="ai-changes"><tbody>' + rows + '</tbody></table>' : '') +
bodyBlock +
'<div class="ai-actions">' +
'<button class="primary" id="aiApply">폼에 적용</button>' +
'<button id="aiApplySave">적용하고 저장</button>' +
'<span class="spacer"></span>' +
'<button class="ghost" id="aiDiscard">버리기</button>' +
'</div>' +
'</div>';
$('aiApply').addEventListener('click', () => applyAi(false));
$('aiApplySave').addEventListener('click', () => applyAi(true));
$('aiDiscard').addEventListener('click', discardAi);
}
function renderDraftResult(data) {
const f = data.fields || {};
$('aiResult').innerHTML =
'<div class="ai-result">' +
'<p class="ai-note"><strong>' + esc(f.title || '제목 없음') + '</strong> ' +
'<span class="hint">slug ' + esc(f.slug || '') + (f.price ? ' · ' + Number(f.price).toLocaleString('ko-KR') + '원' : '') + '</span></p>' +
(f.subtitle ? '<p class="hint" style="margin:0 0 8px">' + esc(f.subtitle) + '</p>' : '') +
'<div class="ai-diff">' + esc(data.body || '') + '</div>' +
'<div class="ai-actions">' +
'<button class="primary" id="aiDraftOpen">초안 열기 (편집)</button>' +
'<span class="spacer"></span>' +
'<button class="ghost" id="aiDiscardDraft">버리기</button>' +
'</div>' +
'</div>';
$('aiDraftOpen').addEventListener('click', () => applyDraft(data));
$('aiDiscardDraft').addEventListener('click', discardAi);
}
function applyAi(saveNow) {
if (!aiLast) return;
let touched = false;
Object.keys(aiLast.changes).forEach((key) => {
if (key === 'body') {
$('body').value = aiLast.changes.body;
touched = true;
return;
}
const el = document.querySelector('[data-key="' + key + '"]');
if (!el) return;
if (el.type === 'checkbox') el.checked = !!aiLast.changes[key];
else el.value = aiLast.changes[key];
el.dispatchEvent(new Event('input', { bubbles: true }));
touched = true;
});
if (!touched) return;
markDirty(true);
if (saveNow) save();
else toast('폼에 적용했습니다. 확인 후 저장하세요.', 'ok');
}
function applyDraft(data) {
const fields = {};
state.fields.forEach((f) => { fields[f.key] = ''; });
Object.keys(data.fields || {}).forEach((key) => { fields[key] = data.fields[key] == null ? '' : String(data.fields[key]); });
state.current = null;
renderList();
renderEditor({ slug: data.fields.slug || '', fields, body: data.body || '', draft: true, extra_keys: [], modified: '' });
$('aiResult').innerHTML = '<p class="hint">초안을 폼에 열었습니다. 대표 이미지를 올리고 슬러그를 확인한 뒤 [저장(커밋)]을 누르세요.</p>';
if (!fields.image) { const pick = $('f_image'); if (pick) pick.focus(); }
}
function discardAi() {
aiLast = null;
$('aiResult').innerHTML = '';
}
/* ------------------------------------------------------------ 이력 */ /* ------------------------------------------------------------ 이력 */
async function openHistory() { async function openHistory() {
const data = await api('/api/history'); const data = await api('/api/history');
@@ -511,6 +746,31 @@ $('rows').addEventListener('click', (e) => {
if (btn) openProduct(btn.dataset.slug); if (btn) openProduct(btn.dataset.slug);
}); });
$('btnSave').addEventListener('click', save); $('btnSave').addEventListener('click', save);
$('aiRun').addEventListener('click', runAi);
$('aiPrompt').addEventListener('keydown', (e) => {
if ((e.metaKey || e.ctrlKey) && e.key === 'Enter') { e.preventDefault(); runAi(); }
});
$('aiExamples').addEventListener('click', (e) => {
const chip = e.target.closest('.chip');
if (!chip) return;
$('aiPrompt').value = chip.dataset.p;
$('aiPrompt').focus();
});
$('aiMode').addEventListener('change', (e) => {
discardAi();
$('aiPrompt').placeholder = e.target.value === 'draft'
? '예) 겨울 매화 티매트, 32×48cm, 6만원. 매화를 놓은 과정을 담백하게.'
: '예) 부제를 더 담백하게. 본문은 3문단으로, 린넨 결을 첫 문장에.';
});
$('btnNew').addEventListener('click', () => {
if (state.dirty && !confirm('저장하지 않은 변경이 있습니다. 버리고 새 작품을 쓸까요?')) return;
$('aiMode').value = 'draft';
state.q = ''; $('q').value = '';
discardAi();
$('aiPrompt').placeholder = '예) 겨울 매화 티매트, 32×48cm, 6만원. 매화를 놓은 과정을 담백하게.';
$('aiPrompt').focus();
toast('새 작품: 만들 내용을 적고 AI 실행을 누르세요');
});
$('btnReload').addEventListener('click', () => { if (state.current) openProduct(state.current); }); $('btnReload').addEventListener('click', () => { if (state.current) openProduct(state.current); });
$('btnHistory').addEventListener('click', openHistory); $('btnHistory').addEventListener('click', openHistory);
$('btnCloseDrawer').addEventListener('click', () => $('drawer').classList.remove('open')); $('btnCloseDrawer').addEventListener('click', () => $('drawer').classList.remove('open'));
@@ -539,7 +799,19 @@ document.addEventListener('keydown', (e) => {
window.addEventListener('beforeunload', (e) => { if (state.dirty) { e.preventDefault(); e.returnValue = ''; } }); window.addEventListener('beforeunload', (e) => { if (state.dirty) { e.preventDefault(); e.returnValue = ''; } });
refresh(); async function boot() {
await refresh();
const params = new URLSearchParams(location.search);
const preset = params.get('prompt');
if (preset) {
$('aiPrompt').value = preset;
if (params.get('run') === '1') setTimeout(runAi, 600);
}
if (params.get('mode') === 'draft') $('aiMode').value = 'draft';
loadAiStatus();
}
boot();
</script> </script>
</body> </body>
</html> </html>
+97
View File
@@ -0,0 +1,97 @@
#!/usr/bin/env python3
"""새 작품 등록 왕복 테스트: AI 초안 -> 이미지 업로드(작품 폴더) -> 저장/커밋 -> 되돌리기."""
import json
import subprocess
import sys
import urllib.error
import urllib.parse
import urllib.request
from pathlib import Path
BASE = "http://127.0.0.1:8081"
ROOT = Path.home() / "Projects/teamat"
fails = []
def check(name, cond, extra=""):
print(("OK " if cond else "FAIL ") + name + (f"\n {extra}" if extra else ""))
if not cond:
fails.append(name)
def req(path, payload=None, raw=None):
data = None
headers = {}
if payload is not None:
data = json.dumps(payload).encode()
headers["Content-Type"] = "application/json"
if raw is not None:
data = raw
headers["Content-Type"] = "application/octet-stream"
request = urllib.request.Request(BASE + path, data=data, headers=headers,
method="POST" if data else "GET")
try:
with urllib.request.urlopen(request, timeout=300) as res:
return res.status, json.loads(res.read().decode())
except urllib.error.HTTPError as error:
body = error.read().decode()
try:
return error.code, json.loads(body)
except json.JSONDecodeError:
return error.code, {"raw": body}
# 1) AI 초안 — slug 에 연-월 접두가 붙어야 한다
code, draft = req("/api/ai", {"mode": "draft",
"prompt": "겨울 매화 티매트, 32×48cm, 린넨 100%, 62000원. 눈 내린 창가 분위기."})
check("draft ok", code == 200 and draft.get("ok") is True, json.dumps(draft, ensure_ascii=False)[:300])
slug = str(draft.get("fields", {}).get("slug", ""))
check("slug 연-월 접두", bool(__import__("re").fullmatch(r"\d{4}-\d{2}-[a-z0-9-]+", slug)), slug)
# 2) 이미지 업로드 — 작품 폴더로
source = ROOT / "assets/img/2026-10-whitework-tea-mat/cover.jpg"
code, up = req("/api/upload?name=cover.jpg&slug=" + urllib.parse.quote(slug), raw=source.read_bytes())
check("upload ok", up.get("ok") is True, json.dumps(up, ensure_ascii=False))
check("upload 경로가 작품 폴더", str(up.get("path", "")).startswith(f"assets/img/{slug}/"), str(up.get("path")))
check("업로드 파일 존재", (ROOT / str(up.get("path", ""))).is_file())
code, nope = req("/api/upload?name=cover.jpg&slug=", raw=b"\xff\xd8\xff")
check("슬러그 없으면 업로드 거부", nope.get("ok") is False, json.dumps(nope, ensure_ascii=False))
# 3) 저장(새 작품)
fields = dict(draft.get("fields") or {})
fields["image"] = up.get("path")
fields["image_alt"] = fields.get("image_alt") or "테스트 이미지"
fields["date"] = fields.get("date") or "2026-11-01"
body = draft.get("body") or "테스트 본문입니다."
code, saved = req("/api/product", {"slug": slug, "fields": fields, "body": body, "create": True})
check("새 작품 저장", saved.get("ok") is True and saved.get("changed") is True, json.dumps(saved, ensure_ascii=False)[:400])
md = ROOT / "content/products" / f"{slug}.md"
check("md 파일 생성", md.is_file(), str(md))
check("dist 페이지 생성", (ROOT / "dist/p" / f"{slug}.html").is_file())
if md.is_file():
text = md.read_text(encoding="utf-8")
check("front matter image 경로", f"image: assets/img/{slug}/" in text, text[:500])
log = subprocess.run(["git", "log", "-1", "--pretty=%s"], cwd=ROOT, capture_output=True, text=True).stdout.strip()
check("커밋 메시지 = 작품 추가", log.startswith("작품 추가:"), log)
# 4) 규칙 위반 슬러그는 거부
code, bad = req("/api/product", {"slug": "no-date-slug", "fields": {"title": "x", "image": up.get("path")},
"body": "x", "create": True})
check("연-월 없는 새 슬러그 거부", code == 400, json.dumps(bad, ensure_ascii=False)[:200])
# 5) 되돌리기 -> 파일·이미지·페이지가 모두 사라져야 한다
sha = saved.get("head")
code, rev = req("/api/revert", {"sha": sha, "deploy": False})
check("되돌리기", rev.get("ok") is True, json.dumps(rev, ensure_ascii=False)[:300])
check("md 삭제", not md.exists(), str(md))
check("dist 페이지 삭제", not (ROOT / "dist/p" / f"{slug}.html").exists())
check("이미지 폴더 정리", not (ROOT / "assets/img" / slug).exists(), str(ROOT / "assets/img" / slug))
status = subprocess.run(["git", "status", "--porcelain"], cwd=ROOT, capture_output=True, text=True).stdout.strip()
check("작업 트리 깨끗", status == "", status)
print()
print("실패 " + str(len(fails)) + "건: " + ", ".join(fails) if fails else "전부 통과")
sys.exit(1 if fails else 0)
+820
View File
@@ -0,0 +1,820 @@
<!doctype html>
<html lang="ko">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
<meta name="theme-color" content="#F6F2EA">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="default">
<title>한땀 작업실 — 상품 등록</title>
<link rel="manifest" href="manifest.json">
<link rel="apple-touch-icon" href="../assets/img/process/stitch.jpg">
<style>
:root{
--paper:#F6F2EA; --ink:#26241F; --muted:#6B6357; --sage:#6C7A63;
--clay:#A2705A; --line:#DCD3C4; --white:#FFFDF8;
--serif:"Noto Serif KR","Apple SD Gothic Neo",serif;
--sans:-apple-system,BlinkMacSystemFont,"Apple SD Gothic Neo","Noto Sans KR",system-ui,sans-serif;
--safe-b:env(safe-area-inset-bottom,0px);
}
*{box-sizing:border-box;-webkit-tap-highlight-color:transparent}
html,body{margin:0;background:var(--paper);color:var(--ink);font-family:var(--sans);
font-size:16px;line-height:1.65;overscroll-behavior-y:contain}
body{padding-bottom:calc(96px + var(--safe-b))}
header{position:sticky;top:0;z-index:20;background:rgba(246,242,234,.94);
backdrop-filter:blur(8px);border-bottom:1px solid var(--line)}
.head-in{display:flex;align-items:center;gap:10px;padding:12px 18px}
.brand{font-family:var(--serif);font-size:17px;letter-spacing:.02em}
.brand small{font-family:var(--sans);font-size:11px;letter-spacing:.18em;color:var(--muted);margin-left:8px}
.steps{margin-left:auto;font-size:12px;color:var(--muted);letter-spacing:.08em}
main{padding:18px}
section[hidden]{display:none}
h1{font-family:var(--serif);font-weight:400;font-size:24px;margin:6px 0 14px}
h2{font-family:var(--serif);font-weight:400;font-size:19px;margin:0 0 6px}
.label{font-size:11px;letter-spacing:.18em;color:var(--muted);text-transform:uppercase;margin:0 0 10px}
.note{color:var(--muted);font-size:14px;margin:0 0 18px}
.btn{display:flex;align-items:center;justify-content:center;gap:8px;width:100%;
padding:16px;border:1px solid var(--ink);background:var(--ink);color:var(--paper);
font-family:var(--sans);font-size:16px;border-radius:0;cursor:pointer}
.btn:active{opacity:.82}
.btn.ghost{background:transparent;color:var(--ink);border-color:var(--line)}
.btn.sage{background:var(--sage);border-color:var(--sage)}
.btn:disabled{opacity:.45}
.btn-sm{padding:10px 14px;font-size:14px;width:auto}
.stack{display:grid;gap:10px}
.row2{display:grid;grid-template-columns:1fr 1fr;gap:10px}
.card{background:var(--white);border:1px solid var(--line);padding:14px;margin-bottom:10px}
.thumbs{display:grid;grid-template-columns:1fr 1fr;gap:10px;margin-bottom:14px}
.thumb{position:relative;background:var(--line);aspect-ratio:4/5;overflow:hidden}
.thumb img{width:100%;height:100%;object-fit:cover;display:block}
.thumb .badge{position:absolute;left:0;top:0;background:var(--ink);color:var(--paper);
font-size:11px;letter-spacing:.1em;padding:3px 7px}
.thumb .tools{position:absolute;right:0;bottom:0;display:flex;gap:4px;padding:6px}
.thumb .tools button{width:34px;height:34px;border:none;background:rgba(38,36,31,.82);
color:#fff;font-size:15px;line-height:1;cursor:pointer}
.thumb .tools button.del{background:rgba(162,112,90,.92)}
label.field{display:block;margin-bottom:14px}
label.field span{display:block;font-size:12px;letter-spacing:.1em;color:var(--muted);margin-bottom:6px}
input[type=text],input[type=number],input[type=url],input[type=date],textarea{
width:100%;padding:13px 12px;border:1px solid var(--line);background:var(--white);
font-family:var(--sans);font-size:16px;color:var(--ink);border-radius:0}
textarea{min-height:150px;line-height:1.7;resize:vertical}
.chips{display:flex;flex-wrap:wrap;gap:8px;margin:0 0 10px}
.chip{padding:9px 12px;border:1px solid var(--line);background:var(--white);
font-size:13px;cursor:pointer;color:var(--muted)}
.chip[aria-pressed=true]{border-color:var(--sage);background:#EEF0E9;color:var(--ink)}
.bar{display:none;position:fixed;left:0;right:0;bottom:0;z-index:30;background:rgba(246,242,234,.97);
border-top:1px solid var(--line);padding:12px 18px calc(12px + var(--safe-b));
display:grid;grid-template-columns:auto 1fr;gap:10px;align-items:center}
.bar .hint{font-size:12px;color:var(--muted);line-height:1.4}
.facts{white-space:pre-wrap;font-size:13px;color:var(--muted);background:#EFEBE1;
border-left:2px solid var(--sage);padding:12px;margin:0 0 16px}
.voice{background:var(--white);border:1px solid var(--line);color:var(--ink);
padding:10px 12px;font-size:14px;cursor:pointer}
.voice.rec{background:var(--clay);color:#fff;border-color:var(--clay)}
.list-item{display:flex;justify-content:space-between;align-items:baseline;gap:10px;
padding:13px 2px;border-bottom:1px solid var(--line);text-decoration:none;color:var(--ink)}
.list-item small{color:var(--muted)}
.hist-item{align-items:center}
.hist-item span{flex:1;min-width:0;font-size:13px;line-height:1.5}
.hist-item button{flex:none;white-space:nowrap}
.status{font-size:13px;color:var(--muted);margin-top:10px;min-height:20px}
.status.err{color:#9B3B2A}
.toast{position:fixed;left:50%;bottom:calc(110px + var(--safe-b));transform:translateX(-50%);
background:var(--ink);color:var(--paper);padding:11px 16px;font-size:14px;z-index:50;
opacity:0;pointer-events:none;transition:opacity .2s;max-width:88vw;text-align:center}
.toast.on{opacity:1}
.spin{display:inline-block;width:14px;height:14px;border:2px solid var(--line);
border-top-color:var(--ink);border-radius:50%;animation:sp .8s linear infinite;vertical-align:-2px}
@keyframes sp{to{transform:rotate(360deg)}}
.summary{font-size:14px;color:var(--muted);margin-bottom:14px}
.summary b{color:var(--ink);font-weight:500}
a.live{color:var(--sage)}
.work-card{display:block;position:relative;padding:10px 0;border-bottom:1px solid var(--line)}
.work-open{display:grid;grid-template-columns:88px 1fr;gap:12px;align-items:center;
text-decoration:none;color:var(--ink);padding-right:64px}
.work-open img{width:88px;aspect-ratio:4/5;object-fit:cover;background:var(--line);display:block}
.work-meta{display:grid;gap:3px;min-width:0}
.work-meta strong{font-weight:500;font-size:15px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.work-meta span{font-size:12px;color:var(--muted);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.work-meta .price{color:var(--ink);font-size:13px}
.edit-btn{position:absolute;right:0;bottom:12px;border:1px solid var(--line);background:var(--white);
color:var(--ink);font-size:13px;padding:8px 12px;cursor:pointer}
.danger-zone{margin-top:28px;padding-top:18px;border-top:1px solid var(--line)}
.btn.danger{background:var(--clay);border-color:var(--clay);color:#fff}
.new-badge{position:absolute;right:0;top:10px;background:var(--sage);color:#fff;
font-size:10px;letter-spacing:.08em;padding:3px 6px}
</style>
</head>
<body>
<header>
<div class="head-in">
<span class="brand">한땀<small>WORKSPACE</small></span>
<span class="steps" id="steps">등록</span>
</div>
</header>
<main>
<!-- ① 홈: 작품 목록 -->
<section id="s-home">
<p class="label">WORKS</p>
<h1>작품 목록</h1>
<p class="note" id="home-note">불러오는 중…</p>
<button class="btn" id="start">신규 상품 등록</button>
<div style="height:10px"></div>
<button class="btn ghost" id="deploy-all">사이트에 올리기</button>
<div class="status" id="deploy-status"></div>
<div id="home-list" style="margin-top:16px">
<span class="status"><span class="spin"></span> 불러오는 중</span>
</div>
<div style="margin-top:24px">
<p class="label">UNDO</p>
<button class="btn ghost btn-sm" id="hist-toggle" style="width:100%">최근 이력 · 되돌리기</button>
<div id="hist-list" hidden style="margin-top:10px"></div>
</div>
</section>
<!-- ② 사진 -->
<section id="s-photos" hidden>
<p class="label">STEP 1 · 사진</p>
<h1>사진을 찍으세요</h1>
<p class="note">여러 장이면 계속 찍으세요. 첫 장이 대표 사진이 됩니다.</p>
<div class="row2">
<button class="btn" id="shoot">사진 찍기</button>
<button class="btn ghost" id="pick">앨범에서</button>
</div>
<input type="file" id="cam" accept="image/*" capture="environment" hidden>
<input type="file" id="album" accept="image/*" multiple hidden>
<div class="thumbs" id="thumbs" style="margin-top:16px"></div>
<div class="status" id="up-status"></div>
</section>
<!-- ③ 내용 -->
<section id="s-write" hidden>
<p class="label">STEP 2 · 내용</p>
<h1>내용 작성</h1>
<p class="note">사진을 읽어 초안을 씁니다. 말로 덧붙이면 그 내용이 반영됩니다.</p>
<label class="field">
<span>메모 (선택) — 말로 넣어도 됩니다</span>
<textarea id="note" style="min-height:84px" placeholder="예: 와인색 코튼린넨, 네 장, 사시코 실 포함"></textarea>
</label>
<div class="chips"><button class="voice" id="voice">🎙 말로 적기</button></div>
<p class="label" style="margin-top:6px">어투</p>
<div class="chips" id="tone-new"></div>
<button class="btn sage" id="cap">내용 작성</button>
<div class="status" id="cap-status"></div>
<div id="cap-out" hidden style="margin-top:18px">
<p class="label">사진에서 읽은 것</p>
<pre class="facts" id="facts"></pre>
<label class="field"><span>제목</span><input type="text" id="f-title"></label>
<label class="field"><span>부제</span><input type="text" id="f-subtitle"></label>
<label class="field"><span>본문</span><textarea id="f-body" style="min-height:230px"></textarea></label>
<label class="field"><span>사진 설명(alt)</span><input type="text" id="f-alt"></label>
</div>
</section>
<!-- ④ 항목 -->
<section id="s-specs" hidden>
<p class="label">STEP 3 · 항목</p>
<h1>규격과 가격</h1>
<p class="note">표준값을 누르면 채워집니다. 다르면 직접 고쳐 쓰세요.</p>
<label class="field"><span>규격</span><input type="text" id="f-size"></label>
<div class="chips" data-for="f-size"></div>
<label class="field"><span>소재</span><input type="text" id="f-material"></label>
<div class="chips" data-for="f-material"></div>
<label class="field"><span>세탁</span><input type="text" id="f-care"></label>
<div class="chips" data-for="f-care"></div>
<div class="row2">
<label class="field"><span>가격(원) · 비우면 "문의"</span><input type="number" id="f-price" inputmode="numeric"></label>
<label class="field"><span>날짜</span><input type="date" id="f-date"></label>
</div>
<label class="field"><span>가격 옵션 안내 (선택)</span><input type="text" id="f-pricenote" placeholder="예: 네 장 세트 50,000원"></label>
<label class="field"><span>네이버 링크 (선택)</span><input type="url" id="f-naver" placeholder="https://smartstore.naver.com/..."></label>
<label class="field" style="display:flex;gap:10px;align-items:center">
<input type="checkbox" id="f-featured" style="width:20px;height:20px">
<span style="margin:0">첫 페이지 대표작으로</span>
</label>
<label class="field" style="display:flex;gap:10px;align-items:center">
<input type="checkbox" id="f-soldout" style="width:20px;height:20px">
<span style="margin:0">품절 표시</span>
</label>
</section>
<!-- ⑤ 확인 -->
<section id="s-done" hidden>
<p class="label">STEP 4 · 저장</p>
<h1>이대로 만들까요?</h1>
<div class="card" id="summary"></div>
<button class="btn" id="pub-deploy">저장하고 사이트에 올리기</button>
<div style="height:10px"></div>
<button class="btn ghost" id="pub-only">저장만 (배포는 나중에)</button>
<label class="field" style="display:flex;gap:10px;align-items:center;margin-top:16px">
<input type="checkbox" id="force" style="width:20px;height:20px">
<span style="margin:0">다른 초안도 함께 올리기</span>
</label>
<div class="status" id="pub-status"></div>
<div class="stack" id="after-publish" hidden style="margin-top:16px">
<button class="btn sage" id="to-list">목록으로 돌아가기</button>
<a class="btn ghost" id="open-preview" href="#" target="_blank" rel="noopener">이 작품 페이지 열기</a>
<a class="btn ghost" id="open-live" href="#" target="_blank" rel="noopener" hidden>사이트에서 보기</a>
</div>
</section>
<!-- ⑥ 고치기 -->
<section id="s-edit" hidden>
<p class="label">EDIT</p>
<h1 id="edit-head">작품 고치기</h1>
<p class="note" id="edit-slug"></p>
<p class="label">사진</p>
<div class="thumbs" id="edit-thumbs"></div>
<div class="row2">
<button class="btn ghost" id="edit-shoot">사진 찍어 추가</button>
<a class="btn ghost" id="edit-open" href="#" target="_blank" rel="noopener">페이지 열기</a>
</div>
<button class="btn ghost btn-sm" id="edit-album-btn" style="width:100%;margin-top:8px">앨범에서 추가</button>
<input type="file" id="edit-cam" accept="image/*" capture="environment" hidden>
<input type="file" id="edit-album" accept="image/*" multiple hidden>
<div class="status" id="edit-up"></div>
<div style="margin-top:18px">
<label class="field"><span>제목</span><input type="text" id="e-title"></label>
<label class="field"><span>부제</span><input type="text" id="e-subtitle"></label>
<label class="field"><span>본문</span><textarea id="e-body" style="min-height:220px"></textarea></label>
<label class="field"><span>사진 설명(alt)</span><input type="text" id="e-alt"></label>
<label class="field"><span>규격</span><input type="text" id="e-size"></label>
<div class="chips" data-for="e-size"></div>
<label class="field"><span>소재</span><input type="text" id="e-material"></label>
<div class="chips" data-for="e-material"></div>
<label class="field"><span>세탁</span><input type="text" id="e-care"></label>
<div class="chips" data-for="e-care"></div>
<div class="row2">
<label class="field"><span>가격(원)</span><input type="number" id="e-price" inputmode="numeric"></label>
<label class="field"><span>날짜</span><input type="date" id="e-date"></label>
</div>
<label class="field"><span>가격 옵션 안내</span><input type="text" id="e-pricenote"></label>
<label class="field"><span>네이버 링크</span><input type="url" id="e-naver"></label>
<label class="field" style="display:flex;gap:10px;align-items:center">
<input type="checkbox" id="e-featured" style="width:20px;height:20px"><span style="margin:0">첫 페이지 대표작으로</span>
</label>
<label class="field" style="display:flex;gap:10px;align-items:center">
<input type="checkbox" id="e-soldout" style="width:20px;height:20px"><span style="margin:0">품절 표시</span>
</label>
</div>
<p class="label" style="margin-top:22px">본문 어투 바꾸기</p>
<div class="chips" id="tone-edit"></div>
<button class="btn ghost" id="e-rewrite">이 어투로 다시 쓰기</button>
<div class="status" id="rewrite-status"></div>
<div id="rewrite-box" hidden style="margin-top:12px">
<p class="label">새 본문 (아직 저장 안 됨)</p>
<pre class="facts" id="rewrite-text" style="max-height:300px;overflow:auto"></pre>
<div class="row2">
<button class="btn" id="rewrite-apply">본문에 적용</button>
<button class="btn ghost" id="rewrite-discard">버리기</button>
</div>
</div>
<div style="height:14px"></div>
<button class="btn sage" id="e-save">저장하고 사이트에 올리기</button>
<div style="height:10px"></div>
<button class="btn ghost" id="e-save-only">저장만</button>
<div style="height:10px"></div>
<button class="btn ghost" id="e-cancel">목록으로</button>
<div class="status" id="e-status"></div>
<div class="danger-zone">
<p class="label">DELETE</p>
<p class="note">지우면 목록과 상세 페이지에서 사라집니다. 찍은 원본 사진은 보관함에 남고, 이력에서 되돌리면 복구됩니다.</p>
<button class="btn danger" id="e-delete">이 작품 삭제</button>
</div>
</section>
</main>
<div class="bar" id="bar">
<button class="btn ghost btn-sm" id="back">이전</button>
<button class="btn" id="next">다음</button>
</div>
<div class="toast" id="toast"></div>
<script>
const S = { step:'home', photos:[], facts:'', draft:{}, busy:false, presets:null,
tone:'warm', editTone:'warm', rewrite:'' };
const $ = s => document.querySelector(s);
const toast = (m, ms=2200) => { const t=$('#toast'); t.textContent=m; t.classList.add('on');
clearTimeout(t._h); t._h=setTimeout(()=>t.classList.remove('on'), ms); };
async function api(path, body){
const res = await fetch(path, body===undefined ? {} : {
method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify(body)
});
if (res.status === 401){ location.href = '/?t=' ; throw new Error('인증이 풀렸습니다'); }
const data = await res.json().catch(()=>({ok:false,error:'응답을 읽지 못했습니다'}));
if (!res.ok || data.ok === false) throw new Error(data.error || ('오류 '+res.status));
return data;
}
/* ---------- 단계 이동 ---------- */
const STEPS = {
home:{el:'#s-home', n:'', prev:null, next:null},
photos:{el:'#s-photos', n:'1/4 사진', prev:'home', next:'write'},
write:{el:'#s-write', n:'2/4 내용', prev:'photos', next:'specs'},
specs:{el:'#s-specs', n:'3/4 항목', prev:'write', next:'done'},
done:{el:'#s-done', n:'4/4 저장', prev:'specs', next:null},
edit:{el:'#s-edit', n:'고치기', prev:null, next:null},
};
function go(step){
S.step = step;
Object.values(STEPS).forEach(v => $(v.el).hidden = true);
$(STEPS[step].el).hidden = false;
$('#steps').textContent = STEPS[step].n;
const cfg = STEPS[step];
$('#bar').style.display = (step==='home' || step==='edit') ? 'none' : 'grid';
$('#back').style.visibility = cfg.prev ? 'visible' : 'hidden';
const next = $('#next');
next.textContent = step==='specs' ? '확인' : '다음';
next.style.display = cfg.next ? '' : 'none';
if (step==='done') renderSummary();
if (step==='home') loadHome();
window.scrollTo({top:0});
}
$('#back').onclick = () => { const p = STEPS[S.step].prev; if (p) go(p); };
$('#next').onclick = () => {
if (S.step==='photos' && !S.photos.length){ toast('사진을 한 장 이상 올려 주세요'); return; }
if (S.step==='write'){
if (!$('#f-title').value.trim() || !$('#f-body').value.trim()){
toast('먼저 "내용 작성"을 눌러 초안을 만들어 주세요'); return; }
}
go(STEPS[S.step].next);
};
/* ---------- 홈: 작품 목록 ---------- */
async function loadHome(){
try{
const d = await api('/api/state');
S.site = d.site_url || '';
const rows = (d.products || []).slice().sort((a,b) =>
String(b.date||'').localeCompare(String(a.date||'')) || (b.mtime||0)-(a.mtime||0));
$('#home-note').textContent = rows.length
? rows.length + '점 · 최근에 만든 순서입니다. 눌러서 확인하세요.'
: '아직 등록한 작품이 없습니다.';
$('#home-list').innerHTML = rows.map(p => `
<div class="work-card">
<a class="work-open" href="/p/${p.slug}.html" target="_blank" rel="noopener">
${p.image ? `<img src="/${p.image}" alt="" loading="lazy">` : '<span></span>'}
<div class="work-meta">
<strong>${p.title}</strong>
<span>${p.subtitle || ''}</span>
<span class="price">${p.price ? Number(p.price).toLocaleString('ko-KR') + '원' : '가격 문의'}${p.sold_out ? ' · 판매 완료' : ''}</span>
</div>
</a>
<button class="edit-btn" data-slug="${p.slug}">수정</button>
${S.lastSlug === p.slug ? '<span class="new-badge">방금 등록</span>'
: (p.live === false ? '<span class="new-badge" style="background:var(--clay)">미발행</span>' : '')}
</div>`).join('') || '<p class="note">아직 없습니다.</p>';
document.querySelectorAll('.edit-btn').forEach(b => b.onclick = () => openEdit(b.dataset.slug));
const pending = rows.filter(p => p.live === false).length;
const button = $('#deploy-all');
button.disabled = pending === 0;
button.style.display = pending ? 'flex' : 'none';
button.textContent = pending ? `사이트에 올리기 (미발행 ${pending}점)` : '사이트 최신 상태';
}catch(e){
$('#home-note').textContent = '';
$('#home-list').innerHTML = `<span class="status err">${e.message}</span>`;
}
}
$('#start').onclick = () => {
S.photos = []; S.facts=''; S.draft={}; S.lastSlug = null;
$('#after-publish').hidden = true; $('#pub-status').textContent = '';
['#f-title','#f-subtitle','#f-body','#f-alt','#f-size','#f-material','#f-care','#f-price',
'#f-pricenote','#f-naver','#note'].forEach(s=>{ if($(s)) $(s).value=''; });
$('#f-date').value = new Date().toISOString().slice(0,10);
$('#f-featured').checked = false; $('#f-soldout').checked = false;
$('#cap-out').hidden = true; $('#cap-status').textContent = '';
renderPhotos(); go('photos');
};
/* ---------- 사진 ---------- */
$('#shoot').onclick = () => $('#cam').click();
$('#pick').onclick = () => $('#album').click();
$('#cam').onchange = e => uploadFiles(e.target.files, true);
$('#album').onchange = e => uploadFiles(e.target.files, false);
async function uploadFiles(files, single){
const list = Array.from(files || []);
if (!list.length) return;
for (let i=0;i<list.length;i++){
$('#up-status').innerHTML = `<span class="spin"></span> 사진 올리는 중 ${i+1}/${list.length}`;
try{
const res = await fetch('/api/photo?name=' + encodeURIComponent(list[i].name || 'photo.jpg'),
{method:'POST', headers:{'Content-Type':'application/octet-stream'}, body:list[i]});
const d = await res.json();
if (!res.ok || d.ok===false) throw new Error(d.error || '업로드 실패');
S.photos.push({uid:d.uid, name:list[i].name});
}catch(e){ $('#up-status').innerHTML = `<span class="status err">${e.message}</span>`; return; }
}
$('#up-status').textContent = '';
$('#cam').value=''; $('#album').value='';
renderPhotos();
}
function renderPhotos(){
const box = $('#thumbs');
if (!S.photos.length){ box.innerHTML = `<p class="note" style="grid-column:1/-1">아직 사진이 없습니다.</p>`; return; }
box.innerHTML = S.photos.map((p,i)=>`
<div class="thumb">
<img src="/media-inbox/${p.uid}.jpg" alt="">
${i===0?'<span class="badge">대표</span>':''}
<div class="tools">
${i>0?`<button data-mv="${i}:-1" aria-label="앞으로">←</button>`:''}
${i<S.photos.length-1?`<button data-mv="${i}:1" aria-label="뒤로">→</button>`:''}
<button class="del" data-del="${i}" aria-label="삭제">×</button>
</div>
</div>`).join('');
box.querySelectorAll('[data-del]').forEach(b=>b.onclick=()=>{
S.photos.splice(+b.dataset.del,1); renderPhotos();
});
box.querySelectorAll('[data-mv]').forEach(b=>b.onclick=()=>{
const [i,d] = b.dataset.mv.split(':').map(Number);
const j = i+d; if (j<0||j>=S.photos.length) return;
[S.photos[i],S.photos[j]] = [S.photos[j],S.photos[i]]; renderPhotos();
});
}
/* ---------- 내용 작성 ---------- */
$('#cap').onclick = async () => {
if (!S.photos.length){ toast('사진을 먼저 올려 주세요'); return; }
$('#cap').disabled = true;
$('#cap-status').innerHTML = '<span class="spin"></span> 사진을 읽고 문장을 쓰는 중… (10~30초)';
try{
const d = await api('/api/caption', {
tone: S.tone,
photos: S.photos.map(p=>p.uid),
note: $('#note').value.trim(),
known: { size:$('#f-size').value.trim(), material:$('#f-material').value.trim(),
care:$('#f-care').value.trim(), price:$('#f-price').value }
});
S.facts = d.facts; S.draft = d.draft;
$('#facts').textContent = d.facts;
$('#f-title').value = d.draft.title || '';
$('#f-subtitle').value = d.draft.subtitle || '';
$('#f-body').value = d.draft.body || '';
$('#f-alt').value = d.draft.image_alt || '';
$('#cap-out').hidden = false;
$('#cap-status').textContent = d.warning ? ('사진 판독 대신 메모로 썼습니다: ' + d.warning) : '';
}catch(e){ $('#cap-status').innerHTML = `<span class="status err">${e.message}</span>`; }
finally{ $('#cap').disabled = false; }
};
/* ---------- 음성 입력 ---------- */
const SR = window.SpeechRecognition || window.webkitSpeechRecognition;
(() => {
const btn = $('#voice');
if (!SR || !window.isSecureContext){ btn.textContent = '🎙 키보드의 마이크 버튼으로도 말할 수 있습니다'; btn.disabled = true; return; }
const rec = new SR(); rec.lang='ko-KR'; rec.interimResults=false; rec.continuous=false;
let on = false;
rec.onresult = ev => {
const text = Array.from(ev.results).map(r=>r[0].transcript).join(' ');
const t = $('#note'); t.value = (t.value ? t.value + ' ' : '') + text; t.focus();
};
rec.onend = () => { on=false; btn.classList.remove('rec'); btn.textContent='🎙 말로 적기'; };
rec.onerror = () => toast('음성 인식을 쓰지 못했습니다. 키보드 마이크를 써보세요');
btn.onclick = () => { if (on){ rec.stop(); return; } rec.start(); on=true;
btn.classList.add('rec'); btn.textContent='● 말하는 중… (눌러서 끝내기)'; };
})();
/* ---------- 항목 프리셋 ---------- */
async function loadPresets(){
try{
const d = await api('/api/presets');
S.presets = { ...d.presets, tones: d.tones || [] };
S.defaultTone = d.default_tone || 'warm';
document.querySelectorAll('.chips[data-for]').forEach(box=>{
const target = box.dataset.for;
const key = target.endsWith('size') ? 'size'
: target.endsWith('material') ? 'material' : 'care';
box.innerHTML = (d.presets[key]||[]).map(v=>`<button class="chip">${v}</button>`).join('');
box.querySelectorAll('.chip').forEach(ch=>ch.onclick=()=>{
box.querySelectorAll('.chip').forEach(c=>c.setAttribute('aria-pressed','false'));
ch.setAttribute('aria-pressed','true');
$('#'+box.dataset.for).value = ch.textContent;
});
});
S.tone = d.default_tone || 'warm';
S.editTone = S.tone;
paintTones();
}catch(e){ toast(e.message); }
}
/* ---------- 확인·저장 ---------- */
function payload(){
return {
photos: S.photos.map(p=>p.uid),
slug: (S.draft && S.draft.slug) || '',
title: $('#f-title').value.trim(),
subtitle: $('#f-subtitle').value.trim(),
body: $('#f-body').value.trim(),
image_alt: $('#f-alt').value.trim(),
size: $('#f-size').value.trim(),
material: $('#f-material').value.trim(),
care: $('#f-care').value.trim(),
price: $('#f-price').value.trim(),
price_note: $('#f-pricenote').value.trim(),
date: $('#f-date').value || new Date().toISOString().slice(0,10),
naver_url: $('#f-naver').value.trim(),
featured: $('#f-featured').checked,
sold_out: $('#f-soldout').checked,
force_deploy: $('#force').checked
};
}
function renderSummary(){
const p = payload();
const price = p.price ? Number(p.price).toLocaleString('ko-KR') + '원' : '가격 문의';
$('#summary').innerHTML = `
<div class="summary">
<b>${p.title || '(제목 없음)'}</b><br>${p.subtitle || ''}<br>
사진 ${p.photos.length}장 · ${price}<br>
${p.size ? '규격 ' + p.size + '<br>' : ''}
${p.material ? '소재 ' + p.material + '<br>' : ''}
${p.date}
</div>`;
}
async function doPublish(deploy){
if (S.busy) return; S.busy = true;
['#pub-deploy','#pub-only'].forEach(s=>$(s).disabled=true);
$('#pub-status').innerHTML = '<span class="spin"></span> 저장 중… (사진 변환 → 빌드 → 커밋' + (deploy?' → 배포':'') + ')';
try{
const d = await api('/api/publish', Object.assign(payload(), {deploy}));
const tail = d.deployed ? '사이트에 올렸습니다. '
: (deploy ? '저장은 했지만 배포하지 못했습니다.<br><span class="err">' + (d.deploy_log||'') + '</span>'
: '저장했습니다. 사이트에는 아직 안 올라갔습니다 — 목록에서 [사이트에 올리기]를 누르세요.');
$('#pub-status').innerHTML =
`저장했습니다 — <b>${d.slug}</b> · 커밋 ${String(d.commit).slice(0,40)}<br>` + tail +
`<a class="live" href="${d.url}" target="_blank">상세 페이지 열기</a>`;
S.lastSlug = d.slug;
$('#open-preview').href = d.url;
const live = $('#open-live');
if (d.deployed && d.live_url) { live.href = d.live_url; live.hidden = false; } else { live.hidden = true; }
$('#after-publish').hidden = false;
toast('등록 완료');
loadHome();
}catch(e){ $('#pub-status').innerHTML = `<span class="status err">${e.message}</span>`; }
finally{ S.busy=false; ['#pub-deploy','#pub-only'].forEach(s=>$(s).disabled=false); }
}
$('#pub-deploy').onclick = () => doPublish(true);
$('#pub-only').onclick = () => doPublish(false);
$('#to-list').onclick = () => go('home');
document.querySelector('.brand').onclick = () => go('home');
/* ---------- 사이트에 올리기(배포만) ---------- */
$('#deploy-all').onclick = async () => {
const status = $('#deploy-status');
const run = async (force) => {
status.innerHTML = '<span class="spin"></span> 사이트에 올리는 중…';
try{
const d = await api('/api/deploy', {force});
status.innerHTML = d.ok ? '올렸습니다. ' + (d.log||'').split('\n').pop() : `<span class="err">${d.log||'실패'}</span>`;
toast('사이트에 올렸습니다');
loadHome();
return true;
}catch(e){
if (String(e.message).includes('초안')){
if (confirm(e.message + '\n\n그 초안까지 함께 올릴까요?')) return run(true);
status.textContent = '취소했습니다';
return true;
}
status.innerHTML = `<span class="status err">${e.message}</span>`;
return false;
}
};
await run(false);
};
/* ---------- 어투 칩 ---------- */
function paintTones(){
const tones = (S.presets && S.presets.tones) || [];
const fill = (sel, current, onPick) => {
const box = $(sel);
if (!box) return;
box.innerHTML = tones.map(t => `<button class="chip" data-tone="${t.key}"
aria-pressed="${t.key === current ? 'true' : 'false'}">${t.label}</button>`).join('');
box.querySelectorAll('.chip').forEach(ch => ch.onclick = () => onPick(ch.dataset.tone));
};
fill('#tone-new', S.tone, key => { S.tone = key; paintTones(); });
fill('#tone-edit', S.editTone, key => { S.editTone = key; paintTones(); $('#rewrite-box').hidden = true; });
}
/* ---------- 고치기 ---------- */
async function openEdit(slug){
$('#e-status').textContent = ''; $('#edit-up').textContent = '';
try{
const d = await api('/api/product?slug=' + encodeURIComponent(slug));
const p = d.product, f = p.fields || {};
const gallery = Array.isArray(f.gallery)
? f.gallery
: String(f.gallery || '').split('\n').map(s => s.trim()).filter(Boolean);
S.edit = { slug, images: [f.image, ...gallery].filter(Boolean).map(path => ({ path })) };
$('#edit-head').textContent = f.title || '작품 고치기';
$('#edit-slug').textContent = slug;
$('#edit-open').href = '/p/' + slug + '.html';
$('#e-title').value = f.title || '';
$('#e-subtitle').value = f.subtitle || '';
$('#e-body').value = p.body || '';
$('#e-alt').value = f.image_alt || '';
$('#e-size').value = f.size || '';
$('#e-material').value = f.material || '';
$('#e-care').value = f.care || '';
$('#e-price').value = f.price || '';
$('#e-pricenote').value = f.price_note || '';
$('#e-date').value = String(f.date || '').slice(0,10);
$('#e-naver').value = f.naver_url || '';
$('#e-featured').checked = !!f.featured;
$('#e-soldout').checked = !!f.sold_out;
renderEditThumbs();
go('edit');
}catch(e){ toast(e.message); }
}
function renderEditThumbs(){
const box = $('#edit-thumbs');
const imgs = (S.edit && S.edit.images) || [];
if (!imgs.length){ box.innerHTML = '<p class="note" style="grid-column:1/-1">사진이 없습니다. 한 장은 있어야 합니다.</p>'; return; }
box.innerHTML = imgs.map((p,i)=>`
<div class="thumb">
<img src="${p.uid ? '/media-inbox/' + p.uid + '.jpg' : '/' + p.path}" alt="">
${i===0?'<span class="badge">대표</span>':''}
<div class="tools">
${i>0?`<button data-mvn="${i}:-1" aria-label="앞으로">←</button>`:''}
${i<imgs.length-1?`<button data-mvn="${i}:1" aria-label="뒤로">→</button>`:''}
<button class="del" data-deln="${i}" aria-label="삭제">×</button>
</div>
</div>`).join('');
box.querySelectorAll('[data-deln]').forEach(b=>b.onclick=()=>{
S.edit.images.splice(+b.dataset.deln,1); renderEditThumbs();
});
box.querySelectorAll('[data-mvn]').forEach(b=>b.onclick=()=>{
const [i,dv] = b.dataset.mvn.split(':').map(Number);
const j = i + dv; if (j < 0 || j >= S.edit.images.length) return;
[S.edit.images[i], S.edit.images[j]] = [S.edit.images[j], S.edit.images[i]];
renderEditThumbs();
});
}
$('#edit-shoot').onclick = () => $('#edit-cam').click();
$('#edit-album-btn').onclick = () => $('#edit-album').click();
$('#edit-cam').onchange = e => uploadEditFiles(e.target.files);
$('#edit-album').onchange = e => uploadEditFiles(e.target.files);
async function uploadEditFiles(files){
const list = Array.from(files || []);
if (!list.length) return;
for (let i=0;i<list.length;i++){
$('#edit-up').innerHTML = `<span class="spin"></span> 사진 올리는 중 ${i+1}/${list.length}`;
try{
const res = await fetch('/api/photo?name=' + encodeURIComponent(list[i].name || 'photo.jpg'),
{method:'POST', headers:{'Content-Type':'application/octet-stream'}, body:list[i]});
const d = await res.json();
if (!res.ok || d.ok === false) throw new Error(d.error || '업로드 실패');
S.edit.images.push({ uid: d.uid });
}catch(e){ $('#edit-up').innerHTML = `<span class="status err">${e.message}</span>`; return; }
}
$('#edit-up').textContent = '';
$('#edit-cam').value = ''; $('#edit-album').value = '';
renderEditThumbs();
}
async function saveEdit(deploy){
const s = $('#e-status');
if (!$('#e-title').value.trim()){ s.innerHTML = '<span class="err">제목을 넣어 주세요</span>'; return; }
if (!S.edit || !S.edit.images.length){ s.innerHTML = '<span class="err">사진이 최소 한 장 필요합니다</span>'; return; }
['#e-save','#e-save-only'].forEach(x=>$(x).disabled=true);
s.innerHTML = '<span class="spin"></span> 저장 중… (사진 정리 → 빌드 → 커밋' + (deploy?' → 배포':'') + ')';
try{
const d = await api('/api/update', {
slug: S.edit.slug, images: S.edit.images,
title: $('#e-title').value.trim(), subtitle: $('#e-subtitle').value.trim(),
body: $('#e-body').value, image_alt: $('#e-alt').value.trim(),
size: $('#e-size').value.trim(), material: $('#e-material').value.trim(),
care: $('#e-care').value.trim(), price: $('#e-price').value, price_note: $('#e-pricenote').value.trim(),
date: $('#e-date').value, naver_url: $('#e-naver').value.trim(),
featured: $('#e-featured').checked, sold_out: $('#e-soldout').checked, deploy
});
s.innerHTML = `고쳤습니다 — 커밋 ${String(d.commit).slice(0,34)}<br>` +
(d.deployed ? '사이트에 올렸습니다. ' : '저장만 했습니다. ') +
`<a class="live" href="${d.url}" target="_blank">페이지 열기</a>`;
toast('수정 완료');
S.lastSlug = d.slug;
}catch(e){ s.innerHTML = `<span class="status err">${e.message}</span>`; }
finally{ ['#e-save','#e-save-only'].forEach(x=>$(x).disabled=false); }
}
$('#e-rewrite').onclick = async () => {
if (!S.edit){ return; }
const st = $('#rewrite-status');
st.innerHTML = '<span class="spin"></span> 문장을 다시 쓰는 중… (10초 안팎)';
try{
const d = await api('/api/tone', { slug: S.edit.slug, tone: S.editTone });
S.rewrite = d.body;
$('#rewrite-text').textContent = d.body;
$('#rewrite-box').hidden = false;
st.textContent = `${d.tone_label} 어투로 다시 썼습니다. 본문에 적용할지 정해 주세요.`;
}catch(e){ st.innerHTML = `<span class="status err">${e.message}</span>`; }
};
$('#rewrite-apply').onclick = () => {
if (!S.rewrite) return;
$('#e-body').value = S.rewrite;
$('#rewrite-box').hidden = true;
$('#rewrite-status').textContent = '본문에 넣었습니다. 저장을 눌러야 반영됩니다.';
toast('본문에 적용');
};
$('#rewrite-discard').onclick = () => {
S.rewrite = ''; $('#rewrite-box').hidden = true; $('#rewrite-status').textContent = '버렸습니다';
};
$('#e-save').onclick = () => saveEdit(true);
$('#e-save-only').onclick = () => saveEdit(false);
$('#e-cancel').onclick = () => go('home');
/* ---------- 삭제 ---------- */
async function deleteWork(force){
if (!S.edit) return;
const slug = S.edit.slug;
const title = $('#e-title').value.trim() || slug;
const st = $('#e-status');
$('#e-delete').disabled = true;
st.innerHTML = '<span class="spin"></span> 지우는 중… (빌드 → 커밋 → 사이트 반영)';
try{
const d = await api('/api/delete', { slug, deploy:true, force: !!force });
const note = d.deployed
? '사이트에서도 내렸습니다.'
: (d.deploy_log || '저장소에서만 지웠습니다 — 사이트에는 아직 남아 있습니다.');
toast('삭제 완료');
go('home');
$('#deploy-status').innerHTML = `삭제했습니다 — <b>${d.title}</b> · 커밋 ${String(d.commit).slice(0,34)}<br>${note}`;
}catch(e){
st.innerHTML = `<span class="status err">${e.message}</span>`;
toast(e.message, 4000);
}finally{ $('#e-delete').disabled = false; }
}
$('#e-delete').onclick = async () => {
if (!S.edit) return;
const title = $('#e-title').value.trim() || S.edit.slug;
const ok = confirm(`"${title}"을(를) 지울까요?\n\n목록과 상세 페이지에서 사라집니다.\n나중에 이력에서 되돌리면 그대로 살아납니다.`);
if (!ok) return;
await deleteWork(false);
};
/* ---------- 최근 이력 · 되돌리기 ---------- */
$('#hist-toggle').onclick = async () => {
const box = $('#hist-list');
if (!box.hidden){ box.hidden = true; return; }
box.hidden = false;
box.innerHTML = '<span class="status"><span class="spin"></span> 불러오는 중</span>';
try{
const d = await api('/api/history');
box.innerHTML = (d.history || []).map(h => `
<div class="list-item hist-item">
<span>${h.date} · ${h.subject}</span>
<button class="btn ghost btn-sm" data-undo="${h.sha}">되돌리기</button>
</div>`).join('') || '<p class="note">이력이 없습니다.</p>';
box.querySelectorAll('[data-undo]').forEach(b => b.onclick = () => undoCommit(b.dataset.undo, b));
}catch(e){ box.innerHTML = `<span class="status err">${e.message}</span>`; }
};
async function undoCommit(sha, btn){
if (!confirm(`${sha} 커밋을 되돌릴까요?\n\n지운 작품을 되살릴 때 이 버튼을 씁니다. 되돌리기도 새 커밋으로 남습니다.`)) return;
const box = $('#hist-list');
if (btn) btn.disabled = true;
box.innerHTML = '<span class="status"><span class="spin"></span> 되돌리는 중…</span>';
try{
const d = await api('/api/revert', { sha, deploy:true });
const note = d.deployed ? '사이트에도 반영했습니다.'
: (d.deploy_log || '저장소에서만 되돌렸습니다 — 사이트에는 아직 옛 상태입니다.');
box.hidden = true; box.innerHTML = '';
toast('되돌렸습니다');
go('home');
$('#deploy-status').innerHTML = `${sha} 되돌렸습니다 · 커밋 ${String(d.head || '').slice(0,34)}<br>${note}`;
}catch(e){
box.innerHTML = `<span class="status err">${e.message}</span>`;
if (btn) btn.disabled = false;
}
}
/* ---------- 시작 ---------- */
go('home'); loadPresets();
// 목록의 링크나 알림에서 바로 열 수 있게: /m?slug=<슬러그> → 그 작품 고치기 화면
const deepSlug = new URLSearchParams(location.search).get('slug');
if (deepSlug) openEdit(deepSlug);
</script>
</body>
</html>
+15
View File
@@ -0,0 +1,15 @@
{
"name": "한땀 작업실 — 상품 등록",
"short_name": "한땀 등록",
"description": "사진을 찍고 내용을 쓰면 작품 상세 페이지가 만들어집니다.",
"start_url": "/m",
"scope": "/",
"display": "standalone",
"orientation": "portrait",
"background_color": "#F6F2EA",
"theme_color": "#F6F2EA",
"lang": "ko",
"icons": [
{"src": "../assets/img/process/stitch.jpg", "sizes": "512x512", "type": "image/jpeg", "purpose": "any"}
]
}
+507
View File
@@ -0,0 +1,507 @@
"""휴대폰에서 상품을 등록하는 흐름을 받쳐 주는 모듈.
studio/server.py 가 import 해서 쓴다. 표준 라이브러리 + macOS 기본 도구(sips)만 쓴다.
흐름:
1) /api/photo 사진을 _inbox 에 임시 저장 -> uid
2) /api/caption 사진을 읽어(VLM) 사실을 뽑고 문장을 씀 -> draft
3) /api/publish 사진을 assets/img/<slug>/ 로 옮기고 md·빌드·커밋(+배포)
"""
from __future__ import annotations
import base64
import io
import json
import os
import re
import secrets
import shutil
import subprocess
import sys
import time
import urllib.error
import urllib.request
from datetime import datetime
from pathlib import Path
from typing import Any, Dict, List, Tuple
try: # 리눅스(QNAP 컨테이너)에서는 Pillow, macOS 기본 파이썬에는 없음
from PIL import Image, ImageOps
HAS_PIL = True
except ImportError: # pragma: no cover - macOS 폴백
HAS_PIL = False
BASE = Path(__file__).resolve().parent
ROOT = BASE.parent
PRODUCTS = ROOT / "content" / "products"
ASSETS = ROOT / "assets"
INBOX = BASE / "_inbox"
ARCHIVE = Path(os.environ.get("TEAMAT_ARCHIVE") or (BASE / "_archive"))
CONFIG_DIR = Path(os.environ.get("TEAMAT_CONFIG_DIR") or (Path.home() / ".config" / "teamat-studio"))
AI_CONFIG = CONFIG_DIR / "ai.json"
VISION_CONFIG = CONFIG_DIR / "vision.json"
AI_BASE_URL = "https://api.deepseek.com/v1"
AI_MODEL = "deepseek-flash"
VISION_URL = "https://integrate.api.nvidia.com/v1/chat/completions"
VISION_MODEL = os.environ.get("TEAMAT_VISION_MODEL", "nvidia/nemotron-3.5-super-vl-120b-a12b")
MAX_VISION_IMAGES = 3
EXTS = (".jpg", ".jpeg")
# 화면에 칩으로 보여줄 표준값. 자유 입력도 함께 받는다.
PRESETS: Dict[str, List[str]] = {
"size": [
"10 × 10 cm × 4장",
"10 × 10 cm (한 장)",
"30 × 45 cm",
"32 × 48 cm",
"20 × 20 cm",
],
"material": [
"린넨 100%, 면사 자수",
"면 100% · 사시코 실(면)",
"11수 코튼린넨(국내산) · 사시코 전용실",
"무명 100%, 면사 자수",
],
"care": [
"미지근한 물에 중성세제로 단독 손세탁",
"자수 완성 전 다림질 금지 · 물세탁은 30분 담갔다 그늘 건조",
"물세탁하지 않고 그늘에서 털어 말리기",
],
}
# ------------------------------------------------------------------ inbox (사진)
def inbox_save(name: str, data: bytes) -> Dict[str, Any]:
if not data:
return {"ok": False, "error": "사진 데이터가 비었습니다"}
ext = Path(name or "photo.jpg").suffix.lower()
if ext not in EXTS:
return {"ok": False, "error": "JPG 사진만 올릴 수 있습니다"}
INBOX.mkdir(parents=True, exist_ok=True)
uid = secrets.token_hex(6)
(INBOX / f"{uid}.jpg").write_bytes(data)
return {"ok": True, "uid": uid, "bytes": len(data)}
def inbox_path(uid: str) -> Path:
if not re.fullmatch(r"[0-9a-f]{12}", uid or ""):
raise ValueError("사진 식별자가 올바르지 않습니다")
path = INBOX / f"{uid}.jpg"
if not path.is_file():
raise FileNotFoundError("사진이 없습니다(다시 찍어 주세요)")
return path
# --------------------------------------------------------------------- AI 호출
def _ai_cfg() -> Dict[str, str]:
if os.environ.get("DEEPSEEK_API_KEY", "").strip():
return {"api_key": os.environ["DEEPSEEK_API_KEY"].strip(), "base_url": AI_BASE_URL,
"model": os.environ.get("DEEPSEEK_MODEL", AI_MODEL)}
if AI_CONFIG.is_file():
data = json.loads(AI_CONFIG.read_text(encoding="utf-8"))
if data.get("api_key"):
return {"api_key": str(data["api_key"]), "base_url": str(data.get("base_url") or AI_BASE_URL),
"model": str(data.get("model") or AI_MODEL)}
raise RuntimeError("DeepSeek API 키가 없습니다 (~/.config/teamat-studio/ai.json)")
def _vision_key() -> str:
if os.environ.get("NVIDIA_API_KEY", "").strip():
return os.environ["NVIDIA_API_KEY"].strip()
if VISION_CONFIG.is_file():
data = json.loads(VISION_CONFIG.read_text(encoding="utf-8"))
if data.get("api_key"):
return str(data["api_key"])
raise RuntimeError("사진 판독(VLM) 키가 없습니다 (~/.config/teamat-studio/vision.json 의 api_key)")
def vision_status() -> Dict[str, Any]:
try:
_vision_key()
except RuntimeError as error:
return {"ok": True, "configured": False, "error": str(error), "model": VISION_MODEL}
return {"ok": True, "configured": True, "model": VISION_MODEL}
def _shrink(path: Path, limit: int = 900) -> bytes:
"""VLM 에 보낼 용량 줄이기. Pillow(리눅스) 또는 sips(macOS)."""
if HAS_PIL:
with Image.open(path) as image:
image = ImageOps.exif_transpose(image).convert("RGB")
image.thumbnail((limit, limit), Image.LANCZOS)
buffer = io.BytesIO()
image.save(buffer, format="JPEG", quality=75, optimize=True)
return buffer.getvalue()
tmp = INBOX / (path.stem + f"-v{limit}.jpg")
ok = subprocess.run(["sips", "-Z", str(limit), "-s", "format", "jpeg",
"-s", "formatOptions", "75", str(path), "--out", str(tmp)],
capture_output=True).returncode == 0
data = tmp.read_bytes() if ok and tmp.is_file() else path.read_bytes()
tmp.unlink(missing_ok=True)
return data
VISION_PROMPT = """이 사진들만 보고, 한국 공방의 상품 설명에 쓸 사실만 뽑아라.
지어내지 말고 사진에서 확인되는 것만 적는다. 추측하면 "추정"이라고 표시한다.
다음 다섯 줄 형식으로만 답한다(설명·인사말 없이).
① 사물:
② 색:
③ 무늬/패턴:
④ 재질 추정:
⑤ 개수:
사진이 여러 장이면 장마다 무엇이 다른지도 한 줄 덧붙인다."""
def photo_facts(uids: List[str]) -> Dict[str, Any]:
"""사진에서 사실을 뽑는다(비전 모델). 실패해도 등록은 계속되도록 예외를 돌려준다."""
key = _vision_key()
chosen = uids[:MAX_VISION_IMAGES]
parts: List[Dict[str, Any]] = [{"type": "text", "text": VISION_PROMPT}]
for uid in chosen:
path = inbox_path(uid)
b64 = base64.b64encode(_shrink(path)).decode("ascii")
parts.append({"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + b64}})
payload = {"model": VISION_MODEL, "max_tokens": 1800, "temperature": 0.2,
"messages": [{"role": "user", "content": parts}]}
request = urllib.request.Request(
VISION_URL, data=json.dumps(payload).encode("utf-8"),
headers={"Content-Type": "application/json", "Authorization": "Bearer " + key}, method="POST")
try:
with urllib.request.urlopen(request, timeout=180) as response:
body = json.loads(response.read().decode("utf-8"))
except urllib.error.HTTPError as error:
detail = error.read().decode("utf-8", "replace")[:300]
raise RuntimeError(f"사진 판독 오류 {error.code}: {detail}") from error
except urllib.error.URLError as error:
raise RuntimeError(f"사진 판독 연결 실패: {error.reason}") from error
message = (body.get("choices") or [{}])[0].get("message", {})
text = (message.get("content") or "").strip()
if not text:
raise RuntimeError("사진 판독 결과가 비었습니다(다시 시도해 주세요)")
return {"ok": True, "model": body.get("model") or VISION_MODEL, "facts": text[:1200],
"images": len(chosen), "tokens": (body.get("usage") or {}).get("total_tokens")}
TONES: Dict[str, Dict[str, str]] = {
"warm": {
"label": "우아한",
"guide": ("품위 있고 단정한 문어체로 쓴다. 문장은 '~습니다'체로 통일하고 '~어요'체와 섞지 않는다. "
"다만 서류 같은 딱딱한 문장이 아니라 결이 고운 문장으로, 다정함을 어휘와 리듬에 담는다. "
"어휘를 한 단계 높인다 — '수놓다, 앉히다, 결, 올, 여백, 온기, 겹' 같은 말을 쓰고 "
"'자리해요/잡아 줘요/만들어요/~해 줍니다' 같은 구어적 표현은 쓰지 않는다. "
"'구성하다·제작하다' 같은 행정적 동사 대신 '올리다·맞추다·앉히다·수놓다'를 고른다. "
"감정은 형용사로 말하지 않고 사물의 상태로 남긴다(예: '손끝의 온기가 실에 남아 있습니다'). "
"수식은 절제하고, 문단마다 여운은 한 번만 둔다. "
"마지막 문단에 여운을 한 문장 두되, '손끝의 온기' 같은 상투적 표현을 기계적으로 붙이지 말고 "
"작품마다 다른 감각(빛, 결, 두께, 소리, 손의 리듬)을 골라 한 번만 쓴다. "
"어색한 조어나 어려운 한자어를 만들지 말고 널리 쓰는 말을 고른다. "
"과장·감탄·이모지·느낌표, '최고급/프리미엄/특별한' 같은 판매 상투어는 쓰지 않는다."),
},
"plain": {
"label": "담백한",
"guide": ("짧은 문장으로 사실만 담백하게. '~습니다'체. 재료와 시간을 숫자로 말하고 감정은 앞세우지 않는다."),
},
"lyrical": {
"label": "서정적인",
"guide": ("짧은 문장과 여백으로 쓴다. 모든 문장을 '~다'체로 끝내고 말투를 섞지 않는다. "
"계절·빛·손의 움직임 같은 감각을 남기되 사실을 벗어나지 않는다. 시를 읽는 리듬."),
},
}
DEFAULT_TONE = "warm"
WRITE_SYSTEM = """너는 한국의 핸드메이드 자수 브랜드 "한땀"의 카피라이터다.
브랜드: 아이보리 린넨·무명 위에 면사로 그림을 놓는 작은 작업실. 타깃은 40~50대 여성.
재료와 시간은 숫자로 말한다("린넨 100%", "30 × 45 cm", "열흘 남짓"). 어투는 아래 지침을 따른다.
규칙:
1. 주어진 사실(사진에서 읽은 것, 입력된 값) 밖의 내용을 만들지 않는다.
후기·별점·판매량·수상·재고·할인·배송 약속 금지.
2. 이모지 금지, 느낌표 남용 금지, "최고급/완벽한/특별한/럭셔리" 금지.
3. 본문은 2~4문단, 문단당 2~3문장. 줄바꿈은 빈 줄로 문단을 나눈다.
4. 사진에서 읽은 것과 사용자가 적은 메모를 우선한다. 확인되지 않은 규격·가격은 쓰지 않는다.
사진 해석과 메모가 어긋나면 **메모를 따른다**.
5. 사진을 어떻게 읽었는지 설명하는 문장을 본문에 쓰지 않는다.
5-1. 아래 어투 지침의 종결 어미를 글 전체에서 하나로 유지한다(섞으면 어색해진다).
("사진에서는 …로 보입니다", "메모에는 …로 적혀 있습니다" 같은 문장 금지)
6. 같은 내용을 두 문단에 반복하지 않는다.
7. 한국어로만 쓴다.
응답은 설명 없이 JSON 하나만:
{"title": "제목(20자 안쪽)", "subtitle": "부제(15자 안쪽)", "image_alt": "대표 사진 설명 1문장",
"slug": "영문-소문자-하이픈", "body": "본문 전문"}
"""
def tone_system(tone: str) -> str:
guide = TONES.get(tone) or TONES[DEFAULT_TONE]
return WRITE_SYSTEM + f"\n\n[이번 어투: {guide['label']}]\n{guide['guide']}"
def _ai_json(system: str, user: str, max_tokens: int = 2600) -> Dict[str, Any]:
cfg = _ai_cfg()
payload = {"model": cfg["model"],
"messages": [{"role": "system", "content": system}, {"role": "user", "content": user}],
"temperature": 0.4, "max_tokens": max_tokens,
"response_format": {"type": "json_object"}}
request = urllib.request.Request(
cfg["base_url"].rstrip("/") + "/chat/completions",
data=json.dumps(payload).encode("utf-8"),
headers={"Content-Type": "application/json", "Authorization": "Bearer " + cfg["api_key"]},
method="POST")
last = "빈 응답"
for attempt in range(3):
try:
with urllib.request.urlopen(request, timeout=240) as response:
body = json.loads(response.read().decode("utf-8"))
except urllib.error.HTTPError as error:
detail = error.read().decode("utf-8", "replace")[:300]
raise RuntimeError(f"AI 오류 {error.code}: {detail}") from error
except urllib.error.URLError as error:
raise RuntimeError(f"AI 연결 실패: {error.reason}") from error
choice = (body.get("choices") or [{}])[0]
text = (choice.get("message", {}).get("content") or "").strip()
if text:
match = re.search(r"\{.*\}", text, re.S)
try:
return {"data": json.loads(text if text.startswith("{") else match.group(0)),
"model": body.get("model"), "tokens": (body.get("usage") or {}).get("total_tokens")}
except (json.JSONDecodeError, AttributeError):
last = f"JSON 아님(finish={choice.get('finish_reason')}): {text[:120]}"
else:
last = f"빈 응답(finish={choice.get('finish_reason')})"
time.sleep(1.5)
raise RuntimeError(f"AI가 문장을 만들지 못했습니다 — {last}. 다시 눌러 주세요")
def caption(payload: Dict[str, Any]) -> Dict[str, Any]:
"""사진 → 사실 → 원고. 사진 판독이 실패해도 메모만으로 원고를 쓴다."""
uids = [str(u) for u in (payload.get("photos") or [])][:12]
note = str(payload.get("note") or "").strip()
known = payload.get("known") or {}
facts = ""
warning = ""
if uids:
try:
facts = photo_facts(uids)["facts"]
except (RuntimeError, ValueError, FileNotFoundError) as error:
warning = str(error)
facts = "(사진 판독 실패 — 메모와 입력값만 사용)"
tone = str(payload.get("tone") or DEFAULT_TONE)
user = json.dumps({
"어투": (TONES.get(tone) or TONES[DEFAULT_TONE])["label"],
"사진에서_읽은_것": facts,
"사용자_메모": note or "(없음)",
"이미_정해진_값": known,
"요청": "이 작품의 제목·부제·이미지 설명·본문을 쓴다. 값이 정해진 항목은 그대로 따른다.",
}, ensure_ascii=False, indent=2)
result = _ai_json(tone_system(tone), user)
data = result["data"] or {}
slug = re.sub(r"[^a-z0-9-]+", "-", str(data.get("slug") or "").lower()).strip("-")
draft = {
"title": str(data.get("title") or "").strip()[:40],
"subtitle": str(data.get("subtitle") or "").strip()[:40],
"image_alt": str(data.get("image_alt") or "").strip(),
"slug": slug,
"body": str(data.get("body") or "").strip(),
}
return {"ok": True, "facts": facts, "warning": warning, "draft": draft,
"model": result["model"], "tokens": result["tokens"]}
# ------------------------------------------------------------------ publish
DEFAULT_ORDER = ["slug", "title", "subtitle", "date", "price", "price_note", "sold_out", "featured",
"image", "image_alt", "gallery", "material", "size", "care", "naver_url"]
def _value(text: Any) -> str:
if isinstance(text, bool):
return "true" if text else "false"
if isinstance(text, int):
return str(text)
raw = str(text if text is not None else "")
if raw == "" or re.search(r"[:#\"'\n]|^\s|\s$", raw):
return '"' + raw.replace('"', '\\"') + '"'
return raw
def _normalize_slug(raw: str, title: str, date: str) -> str:
slug = re.sub(r"[^a-z0-9-]+", "-", (raw or "").lower()).strip("-")
if not re.fullmatch(r"\d{4}-\d{2}-[a-z0-9-]+", slug or ""):
base = slug or "work"
slug = f"{date[:7]}-{base}"
slug = slug[:60].strip("-")
candidate, index = slug, 2
while (PRODUCTS / f"{candidate}.md").exists() or (ASSETS / "img" / candidate).exists():
candidate = f"{slug}-{index}"
index += 1
return candidate
def _orient(path: Path) -> None:
"""EXIF 회전 정보를 픽셀에 반영한다(빌드가 JPEG 크기를 직접 읽으므로 가로/세로가 뒤집히면 안 된다)."""
try:
info = subprocess.run(["sips", "-g", "orientation", str(path)],
capture_output=True, text=True, timeout=30).stdout
except (OSError, subprocess.SubprocessError):
return
match = re.search(r"orientation:\s*(\d+)", info or "")
if not match:
return
degrees = {"6": "90", "8": "270", "3": "180"}.get(match.group(1))
if degrees:
subprocess.run(["sips", "-r", degrees, str(path)], capture_output=True, timeout=60)
def _to_jpeg(source: Path, target: Path, limit: int = 1400) -> None:
if HAS_PIL:
with Image.open(source) as image:
image = ImageOps.exif_transpose(image).convert("RGB")
image.thumbnail((limit, limit), Image.LANCZOS)
image.save(target, format="JPEG", quality=82, optimize=True, progressive=True)
return
ok = subprocess.run(["sips", "-Z", str(limit), "-s", "format", "jpeg",
"-s", "formatOptions", "80", str(source), "--out", str(target)],
capture_output=True, timeout=120).returncode == 0
if not ok or not target.is_file():
shutil.copyfile(source, target)
_orient(target)
def _other_drafts(slug: str) -> List[str]:
"""커밋되지 않은 다른 작품 초안. 배포하면 함께 올라가므로 미리 알린다."""
return [name for name in pending_drafts() if not name.endswith(f"/{slug}")]
def pending_drafts() -> List[str]:
"""커밋되지 않은 작품 초안 전체(경로 기준)."""
proc = subprocess.run(["git", "status", "--porcelain", "--", "content/products"],
cwd=str(ROOT), capture_output=True, text=True, timeout=30)
return [Path(line[3:].strip()).stem for line in (proc.stdout or "").splitlines()
if line[3:].strip().endswith(".md")]
def publish(payload: Dict[str, Any], helpers: Dict[str, Any]) -> Dict[str, Any]:
"""사진 + 값 -> md 한 개. 빌드 실패하면 원상 복구한다.
helpers: build(), git_commit(message, paths), deploy() 를 넘겨받아 쓴다(순환 import 회피).
"""
photos = [str(u) for u in (payload.get("photos") or [])]
title = str(payload.get("title") or "").strip()
body = str(payload.get("body") or "").strip()
if not title:
raise ValueError("제목을 넣어 주세요")
if not body:
raise ValueError("본문을 넣어 주세요")
if not photos:
raise ValueError("사진을 한 장 이상 올려 주세요")
date = str(payload.get("date") or datetime.now().strftime("%Y-%m-%d"))[:10]
if not re.fullmatch(r"\d{4}-\d{2}-\d{2}", date):
date = datetime.now().strftime("%Y-%m-%d")
slug = _normalize_slug(str(payload.get("slug") or ""), title, date)
price_raw = payload.get("price")
price: Any = ""
if str(price_raw or "").strip() not in ("", "0"):
digits = re.sub(r"[^0-9]", "", str(price_raw))
price = int(digits) if digits else ""
image_dir = ASSETS / "img" / slug
image_dir.mkdir(parents=True, exist_ok=True)
sources = [inbox_path(uid) for uid in photos]
cover = f"assets/img/{slug}/cover.jpg"
_to_jpeg(sources[0], ROOT / cover)
gallery: List[str] = []
for index, source in enumerate(sources[1:], start=1):
name = f"detail-{index:02d}.jpg"
_to_jpeg(source, image_dir / name)
gallery.append(f"assets/img/{slug}/{name}")
# 원본(찍은 그대로)은 저장소 밖 보관함에 남긴다 — 나중에 다시 자르거나 크게 볼 때 쓴다.
if ARCHIVE:
keep = ARCHIVE / slug
keep.mkdir(parents=True, exist_ok=True)
for index, source in enumerate(sources):
shutil.copyfile(source, keep / ("cover.jpg" if index == 0 else f"photo-{index:02d}.jpg"))
data: Dict[str, Any] = {
"slug": slug,
"title": title,
"subtitle": str(payload.get("subtitle") or "").strip(),
"date": date,
"price": price,
"price_note": str(payload.get("price_note") or "").strip(),
"sold_out": bool(payload.get("sold_out")),
"featured": bool(payload.get("featured")),
"image": cover,
"image_alt": str(payload.get("image_alt") or title).strip(),
"gallery": gallery,
"material": str(payload.get("material") or "").strip(),
"size": str(payload.get("size") or "").strip(),
"care": str(payload.get("care") or "").strip(),
"naver_url": str(payload.get("naver_url") or "").strip(),
}
lines: List[str] = ["---"]
for key in DEFAULT_ORDER:
value = data.get(key, "")
if key == "gallery":
if value:
lines.append("gallery:")
lines.extend(f"- {_value(item)}" for item in value)
else:
lines.append("gallery:")
continue
lines.append(f"{key}: {_value(value)}")
lines.append("---")
md_path = PRODUCTS / f"{slug}.md"
md_path.write_text("\n".join(lines) + "\n" + body.rstrip() + "\n", encoding="utf-8")
ok, log = helpers["build"]()
if not ok:
md_path.unlink(missing_ok=True)
shutil.rmtree(image_dir, ignore_errors=True)
raise RuntimeError(f"빌드 실패로 저장을 되돌렸습니다: {log[-400:]}")
commit_ok, commit_log = helpers["git_commit"](
f"상품 추가: {title} ({price or '가격 문의'})",
[str(md_path.relative_to(ROOT)), str(image_dir.relative_to(ROOT))])
if not commit_ok:
raise RuntimeError(f"커밋 실패: {commit_log}")
for source in sources:
source.unlink(missing_ok=True)
drafts = _other_drafts(slug)
push_ok, push_log = True, ""
if os.environ.get("TEAMAT_PUSH", "").strip().lower() in ("1", "true", "yes") and helpers.get("push"):
push_ok, push_log = helpers["push"]()
deploy_ok, deploy_log = (True, "배포하지 않음")
if payload.get("deploy"):
if drafts and not payload.get("force_deploy"):
deploy_ok = False
deploy_log = ("커밋하지 않은 다른 초안이 있어 배포를 건너뛰었습니다: " + ", ".join(drafts)
+ "\n그 초안까지 함께 올리려면 '다른 초안도 올리기'를 켜고 다시 저장하세요.")
else:
deploy_ok, deploy_log = helpers["deploy"]()
return {"ok": True, "slug": slug, "title": title, "commit": commit_log,
"deployed": bool(payload.get("deploy")) and deploy_ok,
"other_drafts": drafts, "pushed": push_ok, "push_log": push_log[-200:],
"build_log": log, "deploy_log": deploy_log[-400:],
"url": f"/p/{slug}.html"}
+559 -12
View File
@@ -13,28 +13,52 @@ from __future__ import annotations
import argparse import argparse
import json import json
import mimetypes import mimetypes
import os
import re import re
import shutil
import subprocess import subprocess
import sys import sys
import urllib.error
import urllib.parse import urllib.parse
import urllib.request
from datetime import datetime from datetime import datetime
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path from pathlib import Path
from typing import Any, Dict, List, Tuple from typing import Any, Dict, List, Optional, Tuple
BASE = Path(__file__).resolve().parent BASE = Path(__file__).resolve().parent
ROOT = BASE.parent ROOT = BASE.parent
PRODUCTS = ROOT / "content" / "products" PRODUCTS = ROOT / "content" / "products"
ASSETS = ROOT / "assets" ASSETS = ROOT / "assets"
APP = BASE / "app.html" APP = BASE / "app.html"
MOBILE = BASE / "m.html"
MANIFEST = BASE / "manifest.json"
DIST = ROOT / "dist"
SITE_URL = os.environ.get("TEAMAT_SITE_URL", "https://teamat.lala.dedyn.io").rstrip("/")
# 폰 우선 배포(QNAP)에서는 첫 화면이 등록 화면이다. 데스크톱 편집 화면은 /desk.
DEFAULT_MOBILE = os.environ.get("TEAMAT_DEFAULT_PAGE", "").strip().lower() in ("m", "mobile")
TOKEN_FILE = Path(os.environ.get("TEAMAT_CONFIG_DIR") or (Path.home() / ".config" / "teamat-studio")) / "token"
import register as reg # 휴대폰 등록 흐름(사진 인박스·판독·발행)
import update as upd # 등록된 작품 고치기
LIST_KEYS = {"gallery"} LIST_KEYS = {"gallery"}
# ---- AI(DeepSeek) 설정 ------------------------------------------------------
AI_BASE_URL = "https://api.deepseek.com/v1"
AI_MODEL = "deepseek-flash"
AI_CONFIG = Path.home() / ".config" / "teamat-studio" / "ai.json"
CLAUDE_SETTINGS = Path.home() / ".claude" / "settings.json"
# AI 가 손댈 수 있는 필드 (slug·date·image·gallery·sold_out·featured·naver_url 은 제외)
AI_FIELDS = ["title", "subtitle", "price", "price_note", "material", "size", "care", "image_alt"]
# 폼에 노출할 필드와 순서. 여기 없는 키도 파일에 있으면 보존한다. # 폼에 노출할 필드와 순서. 여기 없는 키도 파일에 있으면 보존한다.
FIELDS: List[Dict[str, str]] = [ FIELDS: List[Dict[str, str]] = [
{"key": "title", "label": "제목", "type": "text"}, {"key": "title", "label": "제목", "type": "text"},
{"key": "subtitle", "label": "부제", "type": "text"}, {"key": "subtitle", "label": "부제", "type": "text"},
{"key": "date", "label": "날짜", "type": "date"}, {"key": "date", "label": "날짜", "type": "date"},
{"key": "price", "label": "가격(원)", "type": "number"}, {"key": "price", "label": "가격(원)", "type": "number"},
{"key": "price_note", "label": "가격 옵션 안내 (예: 네 장 세트 50,000원)", "type": "text"},
{"key": "sold_out", "label": "품절 표시", "type": "bool"}, {"key": "sold_out", "label": "품절 표시", "type": "bool"},
{"key": "featured", "label": "첫 페이지 대표작", "type": "bool"}, {"key": "featured", "label": "첫 페이지 대표작", "type": "bool"},
{"key": "image", "label": "대표 이미지", "type": "image"}, {"key": "image", "label": "대표 이미지", "type": "image"},
@@ -177,6 +201,16 @@ def git_commit(message: str, paths: List[str]) -> Tuple[bool, str]:
return ok, out.splitlines()[-1] if out else "" return ok, out.splitlines()[-1] if out else ""
def prune_empty_image_dirs() -> None:
"""비어 있는 작품 이미지 폴더를 정리한다(되돌리기 뒤 찌꺼기 방지)."""
img_root = ASSETS / "img"
if not img_root.is_dir():
return
for folder in sorted(img_root.iterdir()):
if folder.is_dir() and not any(folder.iterdir()):
folder.rmdir()
def history(limit: int = 20) -> List[Dict[str, str]]: def history(limit: int = 20) -> List[Dict[str, str]]:
ok, out = git("log", f"-n{limit}", "--date=format:%Y-%m-%d %H:%M", "--pretty=format:%h\x1f%ad\x1f%s") ok, out = git("log", f"-n{limit}", "--date=format:%Y-%m-%d %H:%M", "--pretty=format:%h\x1f%ad\x1f%s")
if not ok: if not ok:
@@ -194,9 +228,42 @@ def build() -> Tuple[bool, str]:
def deploy() -> Tuple[bool, str]: def deploy() -> Tuple[bool, str]:
"""웹 루트가 지정돼 있으면(QNAP 컨테이너) dist 를 그 자리로 복사하고, 아니면 deploy.sh(rsync)."""
web_root = os.environ.get("TEAMAT_WEB_ROOT", "").strip()
if web_root:
target = Path(web_root)
try:
target.mkdir(parents=True, exist_ok=True)
wanted = set()
for path in DIST.rglob("*"):
rel = str(path.relative_to(DIST))
wanted.add(rel)
dest = target / rel
if path.is_dir():
dest.mkdir(parents=True, exist_ok=True)
else:
dest.parent.mkdir(parents=True, exist_ok=True)
shutil.copyfile(path, dest)
removed = 0
for path in sorted(target.rglob("*"), key=lambda p: len(p.parts), reverse=True):
rel = str(path.relative_to(target))
if rel in wanted:
continue
if path.is_file():
path.unlink()
removed += 1
elif path.is_dir() and not any(path.iterdir()):
path.rmdir()
return True, f"복사 완료: {target} (파일 {len(wanted)}개, 정리 {removed}개)"
except OSError as error:
return False, f"웹 루트 복사 실패: {error}"
return run(["bash", "scripts/deploy.sh"], timeout=300) return run(["bash", "scripts/deploy.sh"], timeout=300)
def push() -> Tuple[bool, str]:
return run(["git", "push", "origin", "HEAD:main"], timeout=180)
# -------------------------------------------------------------------- products io # -------------------------------------------------------------------- products io
@@ -278,8 +345,23 @@ def coerce(field: Dict[str, str], value: Any) -> Any:
def save_product(payload: Dict[str, Any]) -> Dict[str, Any]: def save_product(payload: Dict[str, Any]) -> Dict[str, Any]:
slug = str(payload.get("slug", "")) slug = str(payload.get("slug", "")).strip()
path = product_path(slug) if not re.fullmatch(r"[a-z0-9][a-z0-9-]*", slug or ""):
raise ValueError("슬러그는 영문 소문자·숫자·하이픈만 쓸 수 있습니다")
path = PRODUCTS / f"{slug}.md"
creating = not path.exists()
if creating and not payload.get("create"):
raise FileNotFoundError(f"작품 파일이 없습니다: {slug}.md")
if creating and not re.fullmatch(r"\d{4}-\d{2}-[a-z0-9][a-z0-9-]*", slug):
raise ValueError("새 작품 슬러그는 `연-월-제목` 형식이어야 합니다 (예: 2026-11-magnolia-tea-mat)")
if creating:
original = None
old_body = ""
order: List[str] = list(DEFAULT_ORDER)
data: Dict[str, Any] = {"slug": slug, "date": datetime.now().strftime("%Y-%m-%d")}
else:
original = path.read_text(encoding="utf-8") original = path.read_text(encoding="utf-8")
lines, old_body = split_front(original) lines, old_body = split_front(original)
order, data = parse_front(lines) order, data = parse_front(lines)
@@ -293,6 +375,11 @@ def save_product(payload: Dict[str, Any]) -> Dict[str, Any]:
order.append(key) order.append(key)
data[key] = value data[key] = value
if creating and not str(data.get("title") or "").strip():
raise ValueError("제목이 비어 있어 새 작품을 만들 수 없습니다")
if creating and not str(data.get("image") or "").strip():
raise ValueError("대표 이미지가 필요합니다 (assets/img/... 경로)")
body = str(payload.get("body", old_body)) body = str(payload.get("body", old_body))
updated = assemble(order, data, body) updated = assemble(order, data, body)
if updated == original: if updated == original:
@@ -301,10 +388,21 @@ def save_product(payload: Dict[str, Any]) -> Dict[str, Any]:
path.write_text(updated, encoding="utf-8") path.write_text(updated, encoding="utf-8")
built, build_log = build() built, build_log = build()
if not built: if not built:
if creating:
path.unlink(missing_ok=True)
error = "빌드 실패 — 새 작품 파일을 만들지 않았습니다"
else:
path.write_text(original, encoding="utf-8") path.write_text(original, encoding="utf-8")
return {"ok": False, "stage": "build", "error": "빌드 실패 — 저장을 취소하고 원본을 되돌렸습니다", "log": build_log} error = "빌드 실패 — 저장을 취소하고 원본을 되돌렸습니다"
return {"ok": False, "stage": "build", "error": error, "log": build_log}
committed, commit_log = git_commit(f"작품 수정: {data.get('title') or slug}", [str(path.relative_to(ROOT))]) label = "작품 추가" if creating else "작품 수정"
# md 와 그 작품의 이미지 폴더를 함께 커밋한다(새 이미지가 untracked 로 남지 않도록)
paths = [str(path.relative_to(ROOT))]
image_dir = ASSETS / "img" / slug
if image_dir.is_dir():
paths.append(str(image_dir.relative_to(ROOT)))
committed, commit_log = git_commit(f"{label}: {data.get('title') or slug}", paths)
if not committed: if not committed:
return {"ok": False, "stage": "git", "error": "git 커밋 실패 (파일은 저장됨)", "log": commit_log} return {"ok": False, "stage": "git", "error": "git 커밋 실패 (파일은 저장됨)", "log": commit_log}
@@ -330,25 +428,121 @@ def revert(sha: str, redeploy: bool) -> Dict[str, Any]:
if not ok: if not ok:
git("revert", "--abort") git("revert", "--abort")
return {"ok": False, "error": "되돌리기 실패", "log": log} return {"ok": False, "error": "되돌리기 실패", "log": log}
prune_empty_image_dirs()
built, build_log = build() built, build_log = build()
if not built: if not built:
return {"ok": False, "error": "되돌린 뒤 빌드 실패", "log": build_log} return {"ok": False, "error": "되돌린 뒤 빌드 실패", "log": build_log}
result: Dict[str, Any] = {"ok": True, "message": f"{sha} 되돌림", "head": head_sha(), "log": build_log} result: Dict[str, Any] = {"ok": True, "message": f"{sha} 되돌림", "head": head_sha(), "log": build_log}
if redeploy: if redeploy:
drafts = reg.pending_drafts()
if drafts:
# 초안까지 함께 올라가는 사고를 막는다(삭제 취소 버튼에서도 같은 규칙).
result["drafts"] = drafts
result["deployed"] = False
result["deploy_log"] = ("커밋하지 않은 초안이 있어 배포를 건너뛰었습니다: " + ", ".join(drafts)
+ " — 목록에서 [사이트에 올리기]로 마저 올려 주세요.")
result["message"] += " (사이트 반영은 건너뜀)"
return result
deployed, deploy_log = deploy() deployed, deploy_log = deploy()
result["deploy"] = {"ok": deployed, "log": deploy_log} result["deploy"] = {"ok": deployed, "log": deploy_log}
result["deployed"] = deployed
result["deploy_log"] = deploy_log[-400:]
result["message"] += " · 배포 완료" if deployed else " (배포 실패)" result["message"] += " · 배포 완료" if deployed else " (배포 실패)"
return result return result
def upload_image(name: str, data: bytes) -> Dict[str, Any]: def restore_paths(paths: List[str]) -> None:
"""git rm 으로 지운 파일을 커밋 전(HEAD) 상태 그대로 되살린다."""
git("reset", "-q", "HEAD", "--", *paths)
git("checkout", "HEAD", "--", *paths)
def delete_product(slug: str, deploy_after: bool = False, force: bool = False) -> Dict[str, Any]:
"""작품 하나를 md·이미지 폴더와 함께 지운다.
- 빌드가 깨지면(예: 키트·대표작이 사라짐) 지운 파일을 HEAD 에서 되살리고 취소한다.
- 지운 사실은 `작품 삭제: 제목` 커밋으로 남는다 → 이력에서 revert 하면 그대로 복구된다.
"""
slug = str(slug or "").strip()
path = product_path(slug) # 슬러그 검증 + 파일 존재 확인
lines, _ = split_front(path.read_text(encoding="utf-8"))
_, data = parse_front(lines)
title = str(data.get("title") or slug)
if not [p for p in PRODUCTS.glob("*.md") if p.stem != slug]:
return {"ok": False, "error": "마지막 남은 작품은 지울 수 없습니다 — 첫 페이지가 비어 버립니다."}
try:
site = json.loads((ROOT / "content" / "site.json").read_text(encoding="utf-8"))
except (OSError, json.JSONDecodeError):
site = {}
kit_slug = str((site.get("shop") or {}).get("kit_slug") or "").strip()
if kit_slug and kit_slug == slug:
return {"ok": False, "error": "이 작품은 첫 페이지의 키트로 지정돼 있습니다. content/site.json 의 "
"shop.kit_slug 를 다른 작품으로 바꾼 뒤 지워 주세요."}
paths = [str(path.relative_to(ROOT))]
image_dir = ASSETS / "img" / slug
if image_dir.is_dir():
paths.append(str(image_dir.relative_to(ROOT)))
removed, rm_log = git("rm", "-r", "-f", "--quiet", "--", *paths)
if not removed:
return {"ok": False, "stage": "git_rm", "error": "작품 파일을 지우지 못했습니다", "log": rm_log}
built, build_log = build()
if not built:
restore_paths(paths)
build()
return {"ok": False, "stage": "build", "log": build_log[-800:],
"error": "빌드가 깨져 삭제를 취소하고 원래대로 되돌렸습니다"}
committed, commit_log = git("commit", "-m", f"작품 삭제: {title}", "--", *paths)
if not committed:
restore_paths(paths)
build()
return {"ok": False, "stage": "git", "error": "커밋에 실패해 삭제를 되돌렸습니다", "log": commit_log}
prune_empty_image_dirs()
summary = next((line for line in (build_log or "").splitlines() if line.startswith("검증")),
(build_log or "").splitlines()[0] if build_log else "")
result: Dict[str, Any] = {
"ok": True, "slug": slug, "title": title, "deployed": False, "pushed": False,
"message": f"삭제 · 커밋 완료 — {title}",
"commit": commit_log, "head": head_sha(),
"build_log": summary,
}
if os.environ.get("TEAMAT_PUSH", "").strip().lower() in ("1", "true", "yes"):
pushed, push_log = push()
result["pushed"] = pushed
result["push_log"] = push_log[-200:]
if deploy_after:
drafts = [d for d in reg.pending_drafts() if d != slug]
if drafts and not force:
result["drafts"] = drafts
result["deploy_log"] = ("커밋하지 않은 다른 초안이 있어 배포를 건너뛰었습니다: " + ", ".join(drafts)
+ " — 목록에서 [사이트에 올리기]로 마저 올려 주세요.")
else:
deployed, deploy_log = deploy()
result["deployed"] = deployed
result["deploy_log"] = deploy_log[-400:]
result["message"] += " · 사이트에 반영" if deployed else " (사이트 반영 실패)"
return result
def upload_image(name: str, data: bytes, slug: str = "") -> Dict[str, Any]:
"""이미지는 assets/img/<작품슬러그>/ 에 넣는다. 작품마다 폴더 하나."""
if not data: if not data:
return {"ok": False, "error": "이미지 데이터가 비었습니다"} return {"ok": False, "error": "이미지 데이터가 비었습니다"}
ext = Path(name).suffix.lower() ext = Path(name).suffix.lower()
if ext not in (".jpg", ".jpeg"): if ext not in (".jpg", ".jpeg"):
return {"ok": False, "error": "JPG만 올릴 수 있습니다 (사이트가 JPEG 크기를 읽습니다)"} return {"ok": False, "error": "JPG만 올릴 수 있습니다 (사이트가 JPEG 크기를 읽습니다)"}
stem = re.sub(r"[^a-z0-9-]+", "-", Path(name).stem.lower()).strip("-") or "image" slug = slug.strip()
target_dir = ASSETS / "img" if not re.fullmatch(r"[a-z0-9][a-z0-9-]*", slug or ""):
return {"ok": False, "error": "슬러그를 먼저 정해야 이미지를 넣을 수 있습니다 (예: 2026-11-magnolia-tea-mat)"}
stem = re.sub(r"[^a-z0-9-]+", "-", Path(name).stem.lower()).strip("-") or "photo"
target_dir = ASSETS / "img" / slug
target_dir.mkdir(parents=True, exist_ok=True) target_dir.mkdir(parents=True, exist_ok=True)
target = target_dir / f"{stem}{ext}" target = target_dir / f"{stem}{ext}"
counter = 2 counter = 2
@@ -356,12 +550,176 @@ def upload_image(name: str, data: bytes) -> Dict[str, Any]:
target = target_dir / f"{stem}-{counter}{ext}" target = target_dir / f"{stem}-{counter}{ext}"
counter += 1 counter += 1
target.write_bytes(data) target.write_bytes(data)
return {"ok": True, "path": f"assets/img/{target.name}", "bytes": len(data)} return {"ok": True, "path": f"assets/img/{slug}/{target.name}", "bytes": len(data)}
# --------------------------------------------------------------------------- AI
SYSTEM_PROMPT = """너는 한국의 핸드메이드 자수 브랜드 "한땀"의 카피라이터다.
브랜드: 아이보리 린넨·무명 위에 면사로 그림을 놓는 작은 작업실. 타깃은 40~50대 여성, 일부 20대.
톤: 담백하고 구체적. 재료와 시간을 숫자로 말한다("린넨 100%", "30 × 45 cm", "열흘 남짓").
반드시 지킬 규칙:
1. 없는 사실을 만들지 않는다. 후기·별점·판매량·수상·재고·할인·배송일 약속 금지.
2. 이모지 금지. 느낌표 남용 금지. "최고급/완벽한/특별한/럭셔리" 같은 형용사 금지.
3. 본문은 2~4문단, 문단당 2~3문장. 마크다운은 문단, "## 소제목", "- 목록", "![설명](경로)" 만 쓴다.
4. 요청받지 않은 필드는 건드리지 않는다. 특히 price·material·size·care 는 근거 없이 바꾸지 않는다.
5. 한국어로만 쓴다.
응답은 설명 없이 JSON 객체 하나만 출력한다. 스키마:
{"note": "무엇을 어떻게 바꿨는지 한 줄(한국어)",
"fields": {"바꾼필드": "새 값"}, // 바꾼 필드만 넣는다. 없으면 {}
"body": "새 본문 전문"} // 본문을 바꿀 때만 넣는다. 안 바꾸면 생략
"""
DRAFT_SCHEMA = """너는 위 규칙에 따라 새 작품 1점의 원고를 쓴다.
응답은 설명 없이 JSON 객체 하나만 출력한다. 스키마:
{"note": "한 줄 요약",
"fields": {"slug": "영문-소문자-하이픈", "title": "", "subtitle": "", "price": 0,
"material": "", "size": "", "care": "", "image_alt": ""},
"body": "본문 전문(2~4문단)"}
price 는 원 단위 정수. 모르면 0 이 아니라 null 이 아니라 빈 문자열 "" 로 둔다.
slug 는 제목을 영문 소문자·하이픈으로 옮긴 것(예: magnolia-tea-mat).
"""
DEFAULT_ORDER = ["slug", "title", "subtitle", "date", "price", "price_note", "sold_out", "featured",
"image", "image_alt", "gallery", "material", "size", "care", "naver_url"]
def ai_config() -> Dict[str, str]:
"""키 우선순위: 환경변수 -> ~/.config/teamat-studio/ai.json -> Claude Code 의 DeepSeek 토큰."""
if os.environ.get("DEEPSEEK_API_KEY", "").strip():
return {"api_key": os.environ["DEEPSEEK_API_KEY"].strip(), "base_url": AI_BASE_URL,
"model": os.environ.get("DEEPSEEK_MODEL", AI_MODEL), "source": "환경변수 DEEPSEEK_API_KEY"}
if AI_CONFIG.is_file():
data = json.loads(AI_CONFIG.read_text(encoding="utf-8"))
if data.get("api_key"):
return {"api_key": str(data["api_key"]), "base_url": str(data.get("base_url") or AI_BASE_URL),
"model": str(data.get("model") or AI_MODEL), "source": str(AI_CONFIG)}
if CLAUDE_SETTINGS.is_file():
env = json.loads(CLAUDE_SETTINGS.read_text(encoding="utf-8")).get("env", {})
token = str(env.get("ANTHROPIC_AUTH_TOKEN") or "")
if token.startswith("sk-") and "api.deepseek.com" in str(env.get("ANTHROPIC_BASE_URL") or ""):
return {"api_key": token, "base_url": AI_BASE_URL, "model": AI_MODEL,
"source": "~/.claude/settings.json 의 DeepSeek 토큰"}
raise RuntimeError(
"DeepSeek API 키가 없습니다. ~/.config/teamat-studio/ai.json 에 "
'{"api_key": "sk-..."} 를 만들거나 DEEPSEEK_API_KEY 환경변수를 주세요.'
)
def ai_status() -> Dict[str, Any]:
try:
cfg = ai_config()
except RuntimeError as error:
return {"ok": True, "configured": False, "error": str(error)}
return {"ok": True, "configured": True, "model": cfg["model"], "source": cfg["source"]}
def ai_chat(system: str, user: str, max_tokens: int = 3000) -> Dict[str, Any]:
cfg = ai_config()
payload = {
"model": cfg["model"],
"messages": [{"role": "system", "content": system}, {"role": "user", "content": user}],
"temperature": 0.4,
"max_tokens": max_tokens,
"response_format": {"type": "json_object"},
}
request = urllib.request.Request(
cfg["base_url"].rstrip("/") + "/chat/completions",
data=json.dumps(payload).encode("utf-8"),
headers={"Content-Type": "application/json", "Authorization": "Bearer " + cfg["api_key"]},
method="POST",
)
try:
with urllib.request.urlopen(request, timeout=240) as response:
body = json.loads(response.read().decode("utf-8"))
except urllib.error.HTTPError as error:
detail = error.read().decode("utf-8", "replace")[:400]
raise RuntimeError(f"DeepSeek 오류 {error.code}: {detail}") from error
except urllib.error.URLError as error:
raise RuntimeError(f"DeepSeek 연결 실패: {error.reason}") from error
text = (body.get("choices") or [{}])[0].get("message", {}).get("content", "")
usage = body.get("usage") or {}
try:
data = json.loads(text)
except json.JSONDecodeError:
match = re.search(r"\{.*\}", text, re.S)
if not match:
raise RuntimeError(f"AI 응답을 JSON 으로 읽지 못했습니다: {text[:300]}")
data = json.loads(match.group(0))
return {"data": data, "model": body.get("model") or cfg["model"],
"tokens": usage.get("total_tokens"), "prompt_tokens": usage.get("prompt_tokens")}
def ai_edit(slug: str, prompt: str) -> Dict[str, Any]:
product = load_product(slug)
current_fields = {key: product["fields"].get(key, "") for key in AI_FIELDS}
current_body = product["body"]
user = json.dumps(
{"요청": prompt, "현재_작품": {"fields": current_fields, "body": current_body}},
ensure_ascii=False,
indent=2,
)
result = ai_chat(SYSTEM_PROMPT, user)
data = result["data"]
changes: Dict[str, Any] = {}
proposed = data.get("fields") or {}
if isinstance(proposed, dict):
for key, value in proposed.items():
if key not in AI_FIELDS:
continue
if str(value).strip() == str(current_fields.get(key, "")).strip():
continue
changes[key] = value
new_body = str(data.get("body") or "").strip()
if new_body and new_body != current_body.strip():
changes["body"] = new_body
if not changes:
return {"ok": True, "note": str(data.get("note") or "바꿀 것이 없다고 판단했습니다"), "changes": {},
"current": {"fields": current_fields, "body": current_body},
"model": result["model"], "tokens": result["tokens"], "empty": True}
return {"ok": True, "note": str(data.get("note") or ""), "changes": changes,
"current": {"fields": current_fields, "body": current_body},
"model": result["model"], "tokens": result["tokens"]}
def ai_draft(prompt: str) -> Dict[str, Any]:
result = ai_chat(SYSTEM_PROMPT + "\n" + DRAFT_SCHEMA, prompt)
data = result["data"]
fields = data.get("fields") or {}
slug = re.sub(r"[^a-z0-9-]+", "-", str(fields.get("slug") or "").lower()).strip("-")
if not slug:
slug = "work-" + datetime.now().strftime("%m%d-%H%M")
prefix = str(fields.get("date") or datetime.now().strftime("%Y-%m-%d"))[:7]
regex_prefix = re.compile(r"^\d{4}-\d{2}-")
if not regex_prefix.match(slug):
slug = f"{prefix}-{slug}"
candidate, index = slug, 2
while (PRODUCTS / f"{candidate}.md").exists():
candidate = f"{slug}-{index}"
index += 1
fields["slug"] = candidate
return {"ok": True, "note": str(data.get("note") or ""), "fields": fields,
"body": str(data.get("body") or ""), "model": result["model"], "tokens": result["tokens"]}
# ------------------------------------------------------------------------ server # ------------------------------------------------------------------------ server
def studio_token() -> str:
"""휴대폰에서 접속할 때 쓰는 열쇠. 비어 있으면 인증 없이 로컬에서만 쓰는 모드."""
token = os.environ.get("STUDIO_TOKEN", "").strip()
if token:
return token
if TOKEN_FILE.is_file():
return TOKEN_FILE.read_text(encoding="utf-8").strip()
return ""
class Handler(BaseHTTPRequestHandler): class Handler(BaseHTTPRequestHandler):
server_version = "hanttam-studio" server_version = "hanttam-studio"
protocol_version = "HTTP/1.1" protocol_version = "HTTP/1.1"
@@ -370,14 +728,36 @@ class Handler(BaseHTTPRequestHandler):
pass pass
# -- helpers --------------------------------------------------------- # -- helpers ---------------------------------------------------------
def send_body(self, code: int, body: bytes, ctype: str = "application/json; charset=utf-8") -> None: def send_body(self, code: int, body: bytes, ctype: str = "application/json; charset=utf-8",
extra: Optional[List[Tuple[str, str]]] = None) -> None:
self.send_response(code) self.send_response(code)
self.send_header("Content-Type", ctype) self.send_header("Content-Type", ctype)
self.send_header("Content-Length", str(len(body))) self.send_header("Content-Length", str(len(body)))
self.send_header("Cache-Control", "no-store") self.send_header("Cache-Control", "no-store")
for key, value in (extra or []):
self.send_header(key, value)
self.end_headers() self.end_headers()
self.wfile.write(body) self.wfile.write(body)
def authed(self) -> bool:
"""열쇠가 설정돼 있으면 쿠키나 ?t= 로 확인한다(테일스케일 너머 폰 접속용)."""
token = studio_token()
if not token:
return True
cookie = self.headers.get("Cookie") or ""
if any(part.strip() == "studio_token=" + token for part in cookie.split(";")):
return True
query = urllib.parse.parse_qs(urllib.parse.urlparse(self.path).query)
self._grant = (query.get("t") or [""])[0] == token
return self._grant
def send_page(self, path: Path, ctype: str = "text/html; charset=utf-8") -> None:
extra: List[Tuple[str, str]] = []
token = studio_token()
if token and getattr(self, "_grant", False):
extra.append(("Set-Cookie", f"studio_token={token}; Path=/; Max-Age=31536000; HttpOnly; SameSite=Lax"))
self.send_body(200, path.read_bytes(), ctype, extra)
def send_json(self, obj: Any, code: int = 200) -> None: def send_json(self, obj: Any, code: int = 200) -> None:
self.send_body(code, json.dumps(obj, ensure_ascii=False).encode("utf-8")) self.send_body(code, json.dumps(obj, ensure_ascii=False).encode("utf-8"))
@@ -396,16 +776,77 @@ class Handler(BaseHTTPRequestHandler):
path = parsed.path path = parsed.path
query = urllib.parse.parse_qs(parsed.query) query = urllib.parse.parse_qs(parsed.query)
if not self.authed():
self.send_json({"ok": False, "error": "열쇠가 필요합니다 — 주소 뒤에 ?t=<토큰> 을 붙여 한 번만 열어 주세요"}, 401)
return
if path in ("/", "/index.html"): if path in ("/", "/index.html"):
self.send_body(200, APP.read_bytes(), "text/html; charset=utf-8") self.send_page(MOBILE if DEFAULT_MOBILE else APP)
return
if path in ("/m", "/m.html"):
self.send_page(MOBILE)
return
if path in ("/desk", "/app", "/app.html"):
self.send_page(APP)
return
if path == "/manifest.json":
self.send_page(MANIFEST, "application/manifest+json; charset=utf-8")
return
if path.startswith("/media-inbox/"):
uid = path[len("/media-inbox/"):].split(".", 1)[0]
try:
target = reg.inbox_path(uid)
except (ValueError, FileNotFoundError) as error:
self.send_json({"ok": False, "error": str(error)}, 404)
return
self.send_body(200, target.read_bytes(), "image/jpeg")
return
if path.startswith("/assets/"):
# 등록 화면의 아이콘·미리보기용. assets 밖으로 나가는 경로는 막는다.
target = (ROOT / path.lstrip("/")).resolve()
try:
target.relative_to(ASSETS.resolve())
except ValueError:
self.send_json({"ok": False, "error": "허용되지 않은 경로"}, 403)
return
if not target.is_file():
self.send_json({"ok": False, "error": "파일 없음"}, 404)
return
ctype = mimetypes.guess_type(target.name)[0] or "application/octet-stream"
self.send_body(200, target.read_bytes(), ctype)
return
if path.startswith("/p/") or path in ("/preview", "/preview/"):
# 빌드 결과(dist)를 그대로 보여준다 — 저장만 한 작품도 여기서 확인할 수 있다.
rel = "index.html" if path.startswith("/preview") else path.lstrip("/")
target = (DIST / rel).resolve()
try:
target.relative_to(DIST.resolve())
except ValueError:
self.send_json({"ok": False, "error": "허용되지 않은 경로"}, 403)
return
if not target.is_file():
self.send_json({"ok": False, "error": "아직 만들어진 페이지가 없습니다"}, 404)
return
ctype = mimetypes.guess_type(target.name)[0] or "application/octet-stream"
self.send_body(200, target.read_bytes(), ctype)
return
if path == "/api/presets":
self.send_json({"ok": True, "presets": reg.PRESETS, "vision": reg.vision_status(),
"tones": [{"key": k, "label": v["label"]} for k, v in reg.TONES.items()],
"default_tone": reg.DEFAULT_TONE})
return return
if path == "/api/state": if path == "/api/state":
rows = summaries() rows = summaries()
web_root = os.environ.get("TEAMAT_WEB_ROOT", "").strip()
if web_root:
for row in rows:
row["live"] = (Path(web_root) / "p" / f"{row['slug']}.html").is_file()
self.send_json( self.send_json(
{ {
"ok": True, "ok": True,
"products": rows, "products": rows,
"count": len(rows), "count": len(rows),
"site_url": SITE_URL,
"head": head_sha(), "head": head_sha(),
"history": history(8), "history": history(8),
"fields": FIELDS, "fields": FIELDS,
@@ -422,6 +863,9 @@ class Handler(BaseHTTPRequestHandler):
except ValueError as error: except ValueError as error:
self.send_json({"ok": False, "error": str(error)}, 400) self.send_json({"ok": False, "error": str(error)}, 400)
return return
if path == "/api/ai-status":
self.send_json(ai_status())
return
if path == "/api/history": if path == "/api/history":
self.send_json({"ok": True, "history": history(25), "head": head_sha()}) self.send_json({"ok": True, "history": history(25), "head": head_sha()})
return return
@@ -447,6 +891,84 @@ class Handler(BaseHTTPRequestHandler):
path = parsed.path path = parsed.path
query = urllib.parse.parse_qs(parsed.query) query = urllib.parse.parse_qs(parsed.query)
if not self.authed():
self.send_json({"ok": False, "error": "열쇠가 필요합니다 — 주소 뒤에 ?t=<토큰> 을 붙여 다시 열어 주세요"}, 401)
return
if path == "/api/photo":
name = (query.get("name") or ["photo.jpg"])[0]
length = int(self.headers.get("Content-Length") or 0)
data = self.rfile.read(length) if length else b""
self.send_json(reg.inbox_save(name, data))
return
if path == "/api/caption":
try:
self.send_json(reg.caption(self.read_json()))
except FileNotFoundError as error:
self.send_json({"ok": False, "error": str(error)}, 404)
except ValueError as error:
self.send_json({"ok": False, "error": str(error)}, 400)
except RuntimeError as error:
self.send_json({"ok": False, "error": str(error)}, 502)
return
if path == "/api/tone":
payload = self.read_json()
try:
self.send_json(upd.rewrite_body(str(payload.get("slug") or ""), str(payload.get("tone") or "")))
except FileNotFoundError as error:
self.send_json({"ok": False, "error": str(error)}, 404)
except (ValueError, RuntimeError) as error:
self.send_json({"ok": False, "error": str(error)}, 502)
return
if path == "/api/update":
helpers = {"build": build, "git_commit": git_commit, "deploy": deploy, "push": push}
try:
result = upd.update_product(self.read_json(), helpers)
result["live_url"] = SITE_URL + str(result.get("url") or "")
self.send_json(result)
except FileNotFoundError as error:
self.send_json({"ok": False, "error": str(error)}, 404)
except ValueError as error:
self.send_json({"ok": False, "error": str(error)}, 400)
except RuntimeError as error:
self.send_json({"ok": False, "error": str(error)}, 500)
return
if path == "/api/deploy":
payload = self.read_json()
drafts = reg.pending_drafts()
if drafts and not payload.get("force"):
self.send_json({"ok": False, "needs_force": True, "drafts": drafts,
"error": "커밋하지 않은 초안이 있어 배포를 멈췄습니다: " + ", ".join(drafts)}, 409)
return
built, build_log = build()
if not built:
self.send_json({"ok": False, "log": build_log[-500:]}, 500)
return
ok, log = deploy()
self.send_json({"ok": ok, "log": (build_log.splitlines()[0] + " · " + log)[-500:], "head": head_sha()})
return
if path == "/api/publish":
helpers = {"build": build, "git_commit": git_commit, "deploy": deploy, "push": push}
try:
result = reg.publish(self.read_json(), helpers)
result["live_url"] = SITE_URL + str(result.get("url") or "")
self.send_json(result)
except ValueError as error:
self.send_json({"ok": False, "error": str(error)}, 400)
except (RuntimeError, FileNotFoundError) as error:
self.send_json({"ok": False, "error": str(error)}, 500)
return
if path == "/api/delete":
payload = self.read_json()
try:
self.send_json(delete_product(str(payload.get("slug") or ""),
bool(payload.get("deploy")),
bool(payload.get("force"))))
except FileNotFoundError as error:
self.send_json({"ok": False, "error": str(error)}, 404)
except ValueError as error:
self.send_json({"ok": False, "error": str(error)}, 400)
return
if path == "/api/product": if path == "/api/product":
try: try:
self.send_json(save_product(self.read_json())) self.send_json(save_product(self.read_json()))
@@ -455,15 +977,34 @@ class Handler(BaseHTTPRequestHandler):
except ValueError as error: except ValueError as error:
self.send_json({"ok": False, "error": str(error)}, 400) self.send_json({"ok": False, "error": str(error)}, 400)
return return
if path == "/api/ai":
payload = self.read_json()
prompt = str(payload.get("prompt") or "").strip()
if len(prompt) < 2:
self.send_json({"ok": False, "error": "요청 내용을 입력해 주세요"}, 400)
return
try:
if str(payload.get("mode")) == "draft":
self.send_json(ai_draft(prompt))
else:
self.send_json(ai_edit(str(payload.get("slug") or ""), prompt))
except FileNotFoundError as error:
self.send_json({"ok": False, "error": str(error)}, 404)
except (RuntimeError, ValueError) as error:
self.send_json({"ok": False, "error": str(error)}, 502)
except json.JSONDecodeError as error:
self.send_json({"ok": False, "error": f"AI 응답 형식 오류: {error}"}, 502)
return
if path == "/api/revert": if path == "/api/revert":
payload = self.read_json() payload = self.read_json()
self.send_json(revert(str(payload.get("sha", "")), bool(payload.get("deploy")))) self.send_json(revert(str(payload.get("sha", "")), bool(payload.get("deploy"))))
return return
if path == "/api/upload": if path == "/api/upload":
name = (query.get("name") or ["image.jpg"])[0] name = (query.get("name") or ["image.jpg"])[0]
slug = (query.get("slug") or [""])[0]
length = int(self.headers.get("Content-Length") or 0) length = int(self.headers.get("Content-Length") or 0)
data = self.rfile.read(length) if length else b"" data = self.rfile.read(length) if length else b""
self.send_json(upload_image(name, data)) self.send_json(upload_image(name, data, slug))
return return
if path == "/api/build": if path == "/api/build":
ok, log = build() ok, log = build()
@@ -483,6 +1024,12 @@ def main() -> None:
server = ThreadingHTTPServer((args.host, args.port), Handler) server = ThreadingHTTPServer((args.host, args.port), Handler)
print(f"한땀 작업실: http://{args.host}:{args.port} (repo {ROOT})") print(f"한땀 작업실: http://{args.host}:{args.port} (repo {ROOT})")
print(" · 책상 화면: / · 폰 등록 화면: /m")
token = studio_token()
if token:
print(f" · 열쇠 있음({token[:4]}…) — 폰에서 /m?t=<토큰> 으로 한 번 열면 쿠키에 저장됩니다")
else:
print(" · 열쇠 없음(이 컴퓨터에서만). 폰에서 열려면 ~/.config/teamat-studio/token 파일을 만드세요")
try: try:
server.serve_forever() server.serve_forever()
except KeyboardInterrupt: except KeyboardInterrupt:
+8 -5
View File
@@ -9,10 +9,13 @@ from pathlib import Path
BASE = "http://127.0.0.1:8081" BASE = "http://127.0.0.1:8081"
ROOT = Path.home() / "Projects/teamat" ROOT = Path.home() / "Projects/teamat"
SLUG = "whitework-tea-mat" SLUG = "2026-10-whitework-tea-mat"
MD = ROOT / "content/products" / f"{SLUG}.md" MD = ROOT / "content/products" / f"{SLUG}.md"
fails = [] fails = []
# 제목은 파일에서 읽는다(사용자가 스튜디오로 언제든 바꿀 수 있으므로 하드코딩하지 않는다)
TITLE = next(line.split(":", 1)[1].strip() for line in MD.read_text(encoding="utf-8").splitlines()
if line.startswith("title:"))
def check(name, cond, extra=""): def check(name, cond, extra=""):
@@ -52,7 +55,7 @@ head0 = state["head"]
# 2. 작품 열기 # 2. 작품 열기
code, data = req(f"/api/product?slug={SLUG}") code, data = req(f"/api/product?slug={SLUG}")
check("GET /api/product", code == 200 and data["product"]["fields"]["title"] == "목련 한 땀 티매트", str(code)) check("GET /api/product", code == 200 and data["product"]["fields"]["title"] == TITLE, str(code))
fields0 = data["product"]["fields"] fields0 = data["product"]["fields"]
body0 = data["product"]["body"] body0 = data["product"]["body"]
check("본문 읽힘", len(body0) > 50) check("본문 읽힘", len(body0) > 50)
@@ -66,7 +69,7 @@ check("무변경 저장은 커밋 안 함", data["ok"] and data["changed"] is Fa
fields = dict(fields0) fields = dict(fields0)
fields["subtitle"] = "스모크 테스트 부제" fields["subtitle"] = "스모크 테스트 부제"
fields["price"] = "59000" fields["price"] = "59000"
fields["gallery"] = "assets/img/work-whitework.jpg" fields["gallery"] = "assets/img/2026-10-whitework-tea-mat/cover.jpg"
code, data = req("/api/product", {"slug": SLUG, "fields": fields, "body": body0}) code, data = req("/api/product", {"slug": SLUG, "fields": fields, "body": body0})
check("수정 저장 성공", data["ok"] and data.get("changed") is True, json.dumps(data)[:300]) check("수정 저장 성공", data["ok"] and data.get("changed") is True, json.dumps(data)[:300])
sha = data.get("head", "") sha = data.get("head", "")
@@ -75,11 +78,11 @@ check("HEAD 이동", sha != head0, f"{head0} -> {sha}")
text = MD.read_text(encoding="utf-8") text = MD.read_text(encoding="utf-8")
check("파일 반영(subtitle)", "subtitle: 스모크 테스트 부제" in text) check("파일 반영(subtitle)", "subtitle: 스모크 테스트 부제" in text)
check("파일 반영(price 정수)", "price: 59000" in text, text[:400]) check("파일 반영(price 정수)", "price: 59000" in text, text[:400])
check("목록 형식 유지(gallery)", "gallery:\n- assets/img/work-whitework.jpg" in text, text[:600]) check("목록 형식 유지(gallery)", "gallery:\n- assets/img/2026-10-whitework-tea-mat/cover.jpg" in text, text[:600])
check("front matter 순서 유지", text.splitlines()[1].startswith("slug:"), text.splitlines()[1]) check("front matter 순서 유지", text.splitlines()[1].startswith("slug:"), text.splitlines()[1])
code, data = req("/api/history") code, data = req("/api/history")
check("이력에 수정 커밋", any("목련 한 땀 티매트" in row["subject"] for row in data["history"]), str(data["history"][:2])) check("이력에 수정 커밋", any(TITLE in row["subject"] for row in data["history"]), str(data["history"][:2]))
# 5. 이미지 업로드 거부 (JPG 아님) # 5. 이미지 업로드 거부 (JPG 아님)
code, data = req("/api/upload?name=x.png", raw=b"\x89PNG\r\n") code, data = req("/api/upload?name=x.png", raw=b"\x89PNG\r\n")
+199
View File
@@ -0,0 +1,199 @@
"""등록된 작품 수정 — 발행(publish)과 같은 규칙으로 md·이미지·커밋을 다시 쓴다."""
from __future__ import annotations
import json
import re
import shutil
from pathlib import Path
from typing import Any, Dict, List, Tuple
import register as reg
def parse_front(raw: str) -> Tuple[Dict[str, Any], str]:
if not raw.startswith("---"):
raise ValueError("md 파일이 --- 로 시작하지 않습니다")
parts = raw.split("---", 2)
if len(parts) != 3:
raise ValueError("front matter 가 닫히지 않았습니다")
front, body = parts[1], parts[2].lstrip("\n")
data: Dict[str, Any] = {}
key = ""
for line in front.splitlines():
if not line.strip() or line.lstrip().startswith("#"):
continue
if line.startswith("- ") or line.startswith(" - "):
if key:
if not isinstance(data.get(key), list):
data[key] = []
data[key].append(line.split("- ", 1)[1].strip().strip('"'))
continue
if ":" in line:
key, value = line.split(":", 1)
key, value = key.strip(), value.strip()
if value == "":
data[key] = []
elif value in ("true", "false"):
data[key] = value == "true"
elif re.fullmatch(r"-?\d+", value):
data[key] = int(value)
else:
data[key] = value.strip('"')
return data, body
def render(data: Dict[str, Any], body: str) -> str:
order = [k for k in reg.DEFAULT_ORDER if k in data] + [k for k in data if k not in reg.DEFAULT_ORDER]
lines = ["---"]
for key in order:
value = data.get(key, "")
if key == "gallery":
lines.append("gallery:")
for item in value or []:
lines.append(f"- {reg._value(item)}")
continue
lines.append(f"{key}: {reg._value(value)}")
lines.append("---")
return "\n".join(lines) + "\n" + body.rstrip() + "\n"
def _restage_images(slug: str, items: List[Dict[str, Any]]) -> List[str]:
"""items 순서대로 cover/detail-NN 으로 다시 배치한다. 기존 사진은 복사, 새 사진(uid)은 변환."""
image_dir = reg.ASSETS / "img" / slug
image_dir.mkdir(parents=True, exist_ok=True)
staged: List[Path] = []
inbox_sources: List[Path] = []
for index, item in enumerate(items):
temp = image_dir / f".staging-{index:02d}.jpg"
if item.get("uid"):
source = reg.inbox_path(str(item["uid"]))
reg._to_jpeg(source, temp)
inbox_sources.append(source)
else:
rel = str(item.get("path") or "")
existing = (reg.ROOT / rel).resolve()
try:
existing.relative_to(image_dir.resolve())
except ValueError as error:
raise ValueError("이 작품 폴더의 사진만 쓸 수 있습니다") from error
if not existing.is_file():
raise ValueError(f"사진이 없습니다: {rel}")
shutil.copyfile(existing, temp)
staged.append(temp)
final: List[str] = []
for index, temp in enumerate(staged):
name = "cover.jpg" if index == 0 else f"detail-{index:02d}.jpg"
target = image_dir / name
temp.replace(target)
final.append(f"assets/img/{slug}/{name}")
keep = {Path(path).name for path in final}
for old in image_dir.glob("*.jpg"):
if old.name not in keep:
old.unlink(missing_ok=True)
if reg.ARCHIVE and inbox_sources:
archive_dir = reg.ARCHIVE / slug
archive_dir.mkdir(parents=True, exist_ok=True)
for index, source in enumerate(inbox_sources):
shutil.copyfile(source, archive_dir / f"added-{index:02d}.jpg")
for source in inbox_sources:
source.unlink(missing_ok=True)
return final
def update_product(payload: Dict[str, Any], helpers: Dict[str, Any]) -> Dict[str, Any]:
slug = re.sub(r"[^a-z0-9-]+", "-", str(payload.get("slug") or "").lower()).strip("-")
path = reg.PRODUCTS / f"{slug}.md"
if not path.is_file():
raise FileNotFoundError(f"작품을 찾을 수 없습니다: {slug}")
data, old_body = parse_front(path.read_text(encoding="utf-8"))
items = payload.get("images")
if isinstance(items, list) and items:
final = _restage_images(slug, items)
data["image"] = final[0]
data["gallery"] = final[1:]
for key in ("title", "subtitle", "price_note", "material", "size", "care", "image_alt", "naver_url"):
if key in payload:
data[key] = str(payload.get(key) or "").strip()
if not str(data.get("title") or "").strip():
raise ValueError("제목을 비울 수 없습니다")
if "price" in payload:
digits = re.sub(r"[^0-9]", "", str(payload.get("price") or ""))
data["price"] = int(digits) if digits and digits != "0" else ""
for key in ("sold_out", "featured"):
if key in payload:
data[key] = bool(payload.get(key))
if payload.get("date"):
date = str(payload["date"])[:10]
if re.fullmatch(r"\d{4}-\d{2}-\d{2}", date):
data["date"] = date
body = str(payload.get("body") or "").strip() or old_body
original = path.read_bytes()
path.write_text(render(data, body), encoding="utf-8")
ok, log = helpers["build"]()
if not ok:
path.write_bytes(original)
raise RuntimeError(f"빌드 실패로 수정을 되돌렸습니다: {log[-300:]}")
image_dir = reg.ASSETS / "img" / slug
commit_ok, commit_log = helpers["git_commit"](
f"작품 수정: {data.get('title')}",
[str(path.relative_to(reg.ROOT)), str(image_dir.relative_to(reg.ROOT))])
if not commit_ok:
raise RuntimeError(f"커밋 실패: {commit_log}")
push_ok, push_log = True, ""
if helpers.get("push"):
push_ok, push_log = helpers["push"]()
deploy_ok, deploy_log = (True, "배포하지 않음")
if payload.get("deploy"):
deploy_ok, deploy_log = helpers["deploy"]()
return {"ok": True, "slug": slug, "commit": commit_log,
"deployed": bool(payload.get("deploy")) and deploy_ok,
"pushed": push_ok, "build_log": log[-300:], "deploy_log": deploy_log[-300:],
"url": f"/p/{slug}.html"}
def rewrite_body(slug: str, tone: str) -> Dict[str, Any]:
"""기존 본문을 다른 어투로 다시 쓴다(저장은 사람이 확인하고 한다)."""
slug = re.sub(r"[^a-z0-9-]+", "-", str(slug or "").lower()).strip("-")
path = reg.PRODUCTS / f"{slug}.md"
if not path.is_file():
raise FileNotFoundError(f"작품을 찾을 수 없습니다: {slug}")
data, body = parse_front(path.read_text(encoding="utf-8"))
guide = reg.TONES.get(tone) or reg.TONES[reg.DEFAULT_TONE]
system = reg.tone_system(tone) + (
"\n\n지금 할 일: 아래 '지금 본문'을 같은 사실 그대로 두고 어투만 바꿔 다시 쓴다."
"\n- 재료·규격·가격·기간 같은 값은 바꾸지 않는다. 없는 사실을 더하지 않는다."
"\n- 문단 수는 2~4개를 지킨다."
'\n응답은 설명 없이 JSON 하나: {"body": "새 본문 전문"}'
)
user = json.dumps({
"제목": str(data.get("title") or ""),
"부제": str(data.get("subtitle") or ""),
"소재": str(data.get("material") or ""),
"규격": str(data.get("size") or ""),
"지금_본문": body.strip(),
"지금_어투": "지금 본문의 어미를 물려받지 말고, 문장 종결 어미를 반드시 위 어투로 바꾼다",
}, ensure_ascii=False, indent=2)
result = reg._ai_json(system, user)
new_body = str((result.get("data") or {}).get("body") or "").strip()
if not new_body:
raise RuntimeError("AI가 본문을 만들지 못했습니다 — 다시 눌러 주세요")
return {"ok": True, "slug": slug, "tone": tone, "tone_label": guide["label"],
"before": body.strip(), "body": new_body, "tokens": result.get("tokens")}
+5 -4
View File
@@ -9,6 +9,7 @@
<link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Noto+Sans+KR:wght@300;400;500&amp;family=Noto+Serif+KR:wght@400;600&amp;display=swap" rel="stylesheet"> <link href="https://fonts.googleapis.com/css2?family=Noto+Sans+KR:wght@300;400;500&amp;family=Noto+Serif+KR:wght@400;600&amp;display=swap" rel="stylesheet">
<link rel="canonical" href="{{canonical}}">
<link rel="stylesheet" href="{{asset_prefix}}assets/css/site.css"> <link rel="stylesheet" href="{{asset_prefix}}assets/css/site.css">
<link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3E%3Crect width='32' height='32' fill='%23F6F2EA'/%3E%3Cpath d='M9 9l14 14M23 9L9 23' stroke='%236C7A63' stroke-width='2'/%3E%3C/svg%3E"> <link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3E%3Crect width='32' height='32' fill='%23F6F2EA'/%3E%3Cpath d='M9 9l14 14M23 9L9 23' stroke='%236C7A63' stroke-width='2'/%3E%3C/svg%3E">
<meta property="og:title" content="{{og_title}}"> <meta property="og:title" content="{{og_title}}">
@@ -26,10 +27,10 @@
<span class="wordmark-en">{{brand_name_en}}</span> <span class="wordmark-en">{{brand_name_en}}</span>
</a> </a>
<nav class="nav" aria-label="주요"> <nav class="nav" aria-label="주요">
<a href="{{home}}index.html#works">작품</a> <a href="{{home}}#works">작품</a>
<a href="{{home}}index.html#process">과정</a> <a href="{{home}}#process">과정</a>
<a href="{{home}}index.html#kit">키트</a> <a href="{{home}}#kit">키트</a>
<a href="{{home}}index.html#contact">문의</a> <a href="{{home}}#contact">문의</a>
</nav> </nav>
</div> </div>
</header> </header>
+71 -2
View File
@@ -27,7 +27,7 @@
<header class="section-head"> <header class="section-head">
<p class="label">WORKS</p> <p class="label">WORKS</p>
<h2 id="works-title">작품</h2> <h2 id="works-title">작품</h2>
<p class="section-note">최근에 만든 순서로 놓았습니다. 한 점씩, 천과 실을 고른 뒤에 시작합니다.</p> <p class="section-note">{{works_note}}</p>
</header> </header>
<div class="works-grid"> <div class="works-grid">
@@ -41,7 +41,6 @@
<h3>{{title}}</h3> <h3>{{title}}</h3>
<p class="work-sub">{{subtitle}}</p> <p class="work-sub">{{subtitle}}</p>
<p class="work-price">{{price_text}}</p> <p class="work-price">{{price_text}}</p>
{{sold_html}}
</div> </div>
</a> </a>
</article> </article>
@@ -50,6 +49,76 @@
</div> </div>
</section> </section>
<section class="section soldout" id="soldout" aria-labelledby="soldout-title">
<div class="shell">
<header class="section-head">
<p class="label">SOLD OUT</p>
<h2 id="soldout-title">지난 작품 — 제작 문의</h2>
<p class="section-note">{{sold_note}}</p>
</header>
{{sold_empty_html}}
<div class="works-grid">
{{#sold_products}}
<article class="work is-sold">
<a class="work-link" href="{{href}}">
<figure class="work-figure">
<img src="{{image}}" alt="{{alt}}" width="{{width}}" height="{{height}}" loading="lazy" decoding="async">
</figure>
<div class="work-caption">
<h3>{{title}}</h3>
<p class="work-sub">{{subtitle}}</p>
<p class="work-price">{{price_text}}</p>
<p class="work-sold">판매 완료</p>
</div>
</a>
<button class="inquiry-btn" type="button" data-inquiry="{{inquiry_title}}">카톡으로 제작 문의</button>
<p class="inquiry-note">재고가 없어 주문을 받은 뒤 제작합니다. 아래 문구가 복사되니 카톡 대화창에 붙여넣어 주세요.</p>
</article>
{{/sold_products}}
</div>
</div>
</section>
<script>
(function () {
var KAKAO = "{{kakao_url}}";
var TEMPLATE = function (title) {
return [
title + " 재제작 문의드립니다.",
"",
"- 원하는 시기: ",
"- 크기·색상: ",
"- 문의 내용: "
].join("\n");
};
document.querySelectorAll("[data-inquiry]").forEach(function (btn) {
btn.addEventListener("click", function () {
var title = btn.getAttribute("data-inquiry") || "작품";
var text = TEMPLATE(title);
var note = btn.parentElement.querySelector(".inquiry-note");
var done = function (copied) {
if (note) {
note.textContent = copied
? "문의 문구를 복사했습니다. 카톡 대화창에 붙여넣어 보내 주세요."
: "카톡에서 새 대화를 열고 아래 내용을 적어 보내 주세요: " + text;
}
};
if (navigator.clipboard && navigator.clipboard.writeText) {
navigator.clipboard.writeText(text).then(function () { done(true); }, function () { done(false); });
} else {
done(false);
}
if (KAKAO) {
window.open(KAKAO, "_blank", "noopener");
} else {
window.location.href = "kakaotalk://";
}
});
});
})();
</script>
<section class="section process" id="process" aria-labelledby="process-title"> <section class="section process" id="process" aria-labelledby="process-title">
<div class="shell"> <div class="shell">
<header class="section-head"> <header class="section-head">
+23 -17
View File
@@ -2,16 +2,30 @@
<a class="back-link" href="../index.html#works">← 작품 목록</a> <a class="back-link" href="../index.html#works">← 작품 목록</a>
</div> </div>
<article class="product shell"> <article class="product">
<div class="product-top"> <header class="product-head shell">
<figure class="product-media"> <h1 class="product-title">{{title}}</h1>
<p class="product-sub">{{subtitle}}</p>
<p class="product-head-price">{{price_text}}</p>
{{price_note_html}}
</header>
<figure class="product-hero">
<img src="../{{image}}" alt="{{alt}}" width="{{width}}" height="{{height}}" loading="eager" fetchpriority="high" decoding="async"> <img src="../{{image}}" alt="{{alt}}" width="{{width}}" height="{{height}}" loading="eager" fetchpriority="high" decoding="async">
</figure> </figure>
<div class="product-info"> {{gallery_html}}
<h1>{{title}}</h1>
<p class="product-sub">{{subtitle}}</p> <section class="product-story shell">
<p class="product-price">{{price_text}}</p> <p class="label">STORY</p>
<div class="prose">
{{body_html}}
</div>
</section>
<section class="product-detail shell">
<p class="label">DETAILS</p>
<div class="detail-body">
{{sold_html}} {{sold_html}}
{{buy_html}} {{buy_html}}
<a class="studio-edit" href="http://localhost:8081/?slug={{slug}}" hidden>이 작품 고치기</a> <a class="studio-edit" href="http://localhost:8081/?slug={{slug}}" hidden>이 작품 고치기</a>
@@ -31,17 +45,9 @@
</div> </div>
</dl> </dl>
</div> </div>
</div> </section>
<div class="product-story"> <nav class="pager shell" aria-label="다른 작품">
<p class="label">STORY</p>
<div class="prose">
{{body_html}}
</div>
{{gallery_html}}
</div>
<nav class="pager" aria-label="다른 작품">
<div class="pager-slot pager-prev">{{prev_html}}</div> <div class="pager-slot pager-prev">{{prev_html}}</div>
<div class="pager-slot pager-next">{{next_html}}</div> <div class="pager-slot pager-next">{{next_html}}</div>
</nav> </nav>
+9 -6
View File
@@ -29,10 +29,13 @@
## 4. 판매 구조 ## 4. 판매 구조
- **완제품(자수 티매트)**: 사이트에서 소개·상세 → 구매 버튼은 **네이버 스마트스토어**로 이동 - **완성품(자수 티매트)**: 한 점씩 미리 완성해 두고 **재고가 있을 때만** 판매한다. 작품은 유일품(1점 = 1개)이라 재고는 `sold_out` 두 상태로 관리한다.
- **자수 키트**: 같은 방식으로 네이버 링크 - **판매되면** `sold_out: true` → 구매 버튼이 사라지고 "판매 완료 — 재제작을 원하시면 문의해 주세요" 안내로 바뀐다.
- 사이트 안에는 결제·회원·장바구니·재고 관리를 두지 않는다 - **판매 완료된 작품**은 같은 무늬로 다시 만들 수 있으나, **별도 문의가 있을 때만** 판매한다. 목록에는 남겨 두어 지난 작업을 볼 수 있게 한다.
- 가격은 표시하되(정보 제공) 결제는 외부. 링크는 `content/products/*.md` 의 `naver_url`, 키트는 `content/site.json` 의 `shop.kit_url` 에서 관리 - **가격**: 한 장 15,000원, 네 장 세트 50,000원 (`price` = 최소 판매 단위, `price_note` = 세트·옵션 문장).
- **구매 동선**: 재고가 있으면 구매 버튼 → **네이버 스마트스토어 상품 페이지**(`naver_url`)로 이동. 재고가 없으면 버튼을 만들지 않는다.
- **자수 키트**: 완성품이 아니라 손으로 놓는 작업물. **키트 페이지에서 링크만 연결**해 스마트스토어 상품으로 넘긴다(`shop.kit_url`). 사이트에 키트용 판매 로직을 두지 않는다. 가격 16,000원(10 × 10 cm 네 장 분량 원단).
- 사이트 안에는 결제·회원·장바구니·재고 개수 관리를 두지 않는다. 판매중/판매완료 두 상태로 충분하다.
## 5. 사이트 구조 (1차 범위) ## 5. 사이트 구조 (1차 범위)
@@ -82,7 +85,7 @@
|---|---| |---|---|
| 소스 저장소 | Gitea `https://git.lala.dedyn.io/koreafood/teamat` (QNAP) | | 소스 저장소 | Gitea `https://git.lala.dedyn.io/koreafood/teamat` (QNAP) |
| 로컬 미리보기 | iMac `~/Projects/teamat/dist` → `http://localhost:8080` | | 로컬 미리보기 | iMac `~/Projects/teamat/dist` → `http://localhost:8080` |
| 운영 서비스 | QNAP `/share/CACHEDEV8_DATA/web/www/teamat` → `https://home.lala.dedyn.io/teamat/` | | 운영 서비스 | QNAP `/share/CACHEDEV8_DATA/web/www/teamat` → `https://teamat.lala.dedyn.io/` (Caddy 전용 도메인, 서브패스 `/teamat/` 병행) |
| 배포 | iMac 에서 `scripts/deploy.sh` (rsync over ssh) | | 배포 | iMac 에서 `scripts/deploy.sh` (rsync over ssh) |
| 향후 | 독립 도메인(`teamat.lala.dedyn.io`), Cloudflare Pages·터널 | | 향후 | 독립 도메인(`teamat.lala.dedyn.io`), Cloudflare Pages·터널 |
@@ -118,7 +121,7 @@
2. `http://localhost:8080` 에서 첫 페이지·작품 상세·이미지가 모두 뜬다 2. `http://localhost:8080` 에서 첫 페이지·작품 상세·이미지가 모두 뜬다
3. 링크가 전부 살아 있다(깨진 상대경로 0개) 3. 링크가 전부 살아 있다(깨진 상대경로 0개)
4. 새 작품 md 1개를 넣고 빌드하면 목록과 상세가 자동으로 생긴다 4. 새 작품 md 1개를 넣고 빌드하면 목록과 상세가 자동으로 생긴다
5. Gitea 에 푸시되어 있고, `https://home.lala.dedyn.io/teamat/` 에서 동일하게 보인다 5. Gitea 에 푸시되어 있고, `https://teamat.lala.dedyn.io/` 에서 동일하게 보인다
6. `scripts/rollback.sh` 로 직전 상태로 되돌아간다 6. `scripts/rollback.sh` 로 직전 상태로 되돌아간다
--- ---