Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ecc8ab4474 | ||
|
|
beaaf6555c | ||
|
|
72e1926d87 | ||
|
|
7aaa488825 | ||
|
|
ddae2c776a | ||
|
|
e1ddbff1f5 | ||
|
|
3d5a015400 | ||
|
|
bdbad3ec6d | ||
|
|
d84b4e4d61 | ||
|
|
b81eb5745f | ||
|
|
7619eef367 | ||
|
|
9434a08480 | ||
|
|
b803ab4efd | ||
|
|
aba5d4d6e2 | ||
|
|
ebbec84ba6 | ||
|
|
c10a1c76fb | ||
|
|
09ad856c0b | ||
|
|
bc01e7cfe6 | ||
|
|
9c234b0c43 | ||
|
|
07900de9aa | ||
|
|
dd203f2113 | ||
|
|
71a01228c6 | ||
|
|
c766e70922 | ||
|
|
aa79358d64 | ||
|
|
53477b387d | ||
|
|
97a6961d88 | ||
|
|
02e654d75e | ||
|
|
a749b9daf8 | ||
|
|
a6835e943a | ||
|
|
f2ae889795 | ||
|
|
51f3cdbe1c | ||
|
|
481831e00d | ||
|
|
43332601d3 | ||
|
|
5efb86b6b8 | ||
|
|
b887c98d5f | ||
|
|
b604bfe047 | ||
|
|
ae2cc1de7d | ||
|
|
cdf81ccc4e | ||
|
|
fc19253ac9 | ||
|
|
574d4f53cd | ||
|
|
b41d42694d | ||
|
|
984fe68c12 | ||
|
|
5c5ecef578 | ||
|
|
b5296f7e08 | ||
|
|
e502c32542 | ||
|
|
4ce660b740 | ||
|
|
929e0d7095 | ||
|
|
43d26690c0 | ||
|
|
fb5b09f3be | ||
|
|
7f2cb35cdb | ||
|
|
db6fb9c075 | ||
|
|
142116c8e7 | ||
|
|
3d908e6e5c | ||
|
|
04211ddf71 | ||
|
|
3396d27557 | ||
|
|
eb55d4849c | ||
|
|
4ffd6667b0 | ||
|
|
1483969c06 | ||
|
|
39d504ab2b | ||
|
|
cdaac551d6 | ||
|
|
8c565cccc8 | ||
|
|
ca2c0d077d | ||
|
|
767b2a30a3 | ||
|
|
4dff91b483 | ||
|
|
109bd93bd2 | ||
|
|
6249317528 | ||
|
|
8248ba94d8 | ||
|
|
c6eff765e1 | ||
|
|
857656a145 |
No files matched your search
@@ -2,3 +2,6 @@ dist/
|
||||
.DS_Store
|
||||
*.log
|
||||
.claude/settings.local.json
|
||||
studio/_inbox/
|
||||
__pycache__/
|
||||
studio/_archive/
|
||||
@@ -6,8 +6,14 @@
|
||||
## 0. 절대 규칙
|
||||
|
||||
1. **DB·서버·CMS 를 만들지 않는다.** 정적 HTML/CSS/JS 만. Node/npm/pip 패키지 금지.
|
||||
- 예외: `studio/` 는 사이트가 아니라 **관리 도구**다(표준 라이브러리만, `dist/` 에 포함되지 않음).
|
||||
QNAP 컨테이너(`teamat-admin:1`, 호스트 8089 는 127.0.0.1 에만 게시)에서 돌고, QNAP 의 tailscale 컨테이너가
|
||||
`tailscale serve` 로 `https://naslala.taild8883.ts.net/` 에만 노출한다(테일넷 전용, 공개 도메인·토큰 없음).
|
||||
아이맥 로컬 실행은 비상용으로만 남긴다. 이 예외를 근거로 사이트에 서버 기능을 붙이지 않는다.
|
||||
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/` 는 커밋하지 않는다.** 소스에서 언제든 재생성된다. 롤백 단위는 커밋 하나.
|
||||
5. **`git push --force` 금지.** 되돌리기는 `git revert`.
|
||||
6. 없는 사실을 만들지 않는다 — 후기·별점·판매량·수상·재고. 값이 없으면 비워둔다.
|
||||
@@ -36,6 +42,10 @@ scripts/
|
||||
preview.sh 로컬 미리보기(빌드 후 8080 서빙)
|
||||
deploy.sh dist → QNAP 웹루트 rsync
|
||||
rollback.sh 커밋 되돌리기 + 재빌드·재배포
|
||||
studio.sh 로컬 편집 도구 실행(8081)
|
||||
studio/
|
||||
server.py 작품 md 조회·수정 API (127.0.0.1 전용, 표준 라이브러리)
|
||||
app.html 작업실 화면(목록+검색+편집+이력)
|
||||
dist/ 빌드 산출물(.gitignore)
|
||||
```
|
||||
|
||||
@@ -56,6 +66,7 @@ dist/ 빌드 산출물(.gitignore)
|
||||
"kakao": ""
|
||||
},
|
||||
"shop": {
|
||||
"kit_slug": "2026-10-kit-first-stitch",
|
||||
"store_url": "https://smartstore.naver.com/",
|
||||
"kit_url": "https://smartstore.naver.com/",
|
||||
"kit_note": "키트에 들어가는 것 한 줄"
|
||||
@@ -74,34 +85,39 @@ dist/ 빌드 산출물(.gitignore)
|
||||
```
|
||||
|
||||
- `product_sort`: `newest`(기본) 또는 `oldest`. 이 값 하나로 목록 순서가 바뀐다.
|
||||
- `shop.kit_slug`: 첫 페이지 '키트' 섹션에 쓸 작품의 slug. 작품 slug 를 바꾸면 여기도 함께 고친다.
|
||||
- 문구를 고치라는 요청은 대부분 이 파일만 고치면 끝난다.
|
||||
|
||||
## 3. content/products/<slug>.md 스키마
|
||||
|
||||
```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: 목련 한 땀 티매트
|
||||
subtitle: 봄볕에 널어둔 천
|
||||
date: 2026-10-28 # 목록 정렬 기준
|
||||
price: 58000 # 원 단위 정수. 비우면 "문의"
|
||||
sold_out: false
|
||||
price: 15000 # 원 단위 정수. 최소 판매 단위(한 장). 비우면 "문의"
|
||||
price_note: 네 장 세트 50,000원 # 선택. 가격 옵션 안내 한 줄
|
||||
sold_out: false # 재고 없음 = true → 구매 버튼 대신 "판매 완료" 안내
|
||||
featured: true # 첫 페이지 상단에 크게 노출
|
||||
image: assets/img/work-whitework.jpg
|
||||
image: assets/img/2026-10-whitework-tea-mat/cover.jpg
|
||||
image_alt: 아이보리 린넨 위에 흰 실로 목련을 놓은 티매트
|
||||
gallery: # 선택. 상세 페이지 추가 이미지
|
||||
- assets/img/work-whitework.jpg
|
||||
gallery: # 선택. 상세 페이지 추가 이미지 (같은 작품 폴더에 둔다)
|
||||
- assets/img/2026-10-whitework-tea-mat/detail-01.jpg
|
||||
material: 린넨 100%
|
||||
size: 30 × 45 cm
|
||||
size: 10 × 10 cm (한 장) # 완성품 기준. 세트면 "10 × 10 cm × 4장"
|
||||
care: 미지근한 물에 중성세제로 단독 손세탁
|
||||
naver_url: "" # 비우면 구매 버튼 대신 "네이버 스토어 준비 중"
|
||||
naver_url: "" # 스마트스토어 상품 주소. 비우면 구매 버튼 대신 "네이버 스토어 준비 중"
|
||||
---
|
||||
본문은 2~4문단. 어떤 천에 어떤 실로, 얼마나 걸렸는지. 과장 없이.
|
||||
```
|
||||
|
||||
- **새 작품 추가 = 이 파일 1개 추가 → `python3 build.py`.** 목록과 상세가 자동 생성된다.
|
||||
- `slug` 는 파일명과 같게 유지한다.
|
||||
- 이미지 파일은 `assets/img/` 에 넣고 파일명은 영문 소문자·하이픈.
|
||||
- `sold_out: true` 인 작품은 첫 페이지의 **판매 완료 섹션**으로 내려가고, 카드·상세에 `카톡으로 제작 문의` 버튼이 붙는다. 판매 재개는 `false` 로 되돌리는 것.
|
||||
- 파일명 = `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 스키마
|
||||
|
||||
@@ -109,7 +125,7 @@ naver_url: "" # 비우면 구매 버튼 대신 "네이버 스
|
||||
---
|
||||
step: 1
|
||||
title: 실 고르기
|
||||
image: assets/img/craft-jogakbo.jpg
|
||||
image: assets/img/process/fabric.jpg
|
||||
image_alt: 조각보
|
||||
---
|
||||
한 문단. 무엇을 보고 고르는지.
|
||||
@@ -126,7 +142,7 @@ image_alt: 조각보
|
||||
- HTML 은 `<!-- escaped -->` 없이 그대로 넣되, front matter 값은 escape 한다.
|
||||
- 상세 페이지에서 목록으로 돌아가는 링크는 `../index.html` (서브패스 대응).
|
||||
- 언어 `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 하나.
|
||||
|
||||
## 6. 디자인 토큰 (바꾸려면 사용자 확인)
|
||||
@@ -142,12 +158,15 @@ image_alt: 조각보
|
||||
- 제목: `Noto Serif KR` (serif), 본문: `Noto Sans KR` (sans). CDN 실패 시 시스템 폰트 폴백.
|
||||
- 여백 위주, 그림자·그라데이션·둥근 카드 금지. 구분은 1px 실선.
|
||||
- 사진이 주인공: 최소 60vw 폭 또는 4:5 세로 컷. 호버 확대는 1.02 이하.
|
||||
- **상세 페이지 순서는 고정**: ① 작은 제목(+부제·가격, `product-head`) ② 메인 사진(`product-hero`, 폭 min(100%,1080px), 자르지 않고 원본 비율)
|
||||
③ 서브 사진(`gallery`, 한 열로 세로로 이어 붙임) ④ 스토리(`product-story`) ⑤ DETAILS(구매 버튼 + 소재·규격·세탁 `spec`) — 사양은 항상 맨 아래.
|
||||
|
||||
## 7. 자주 쓰는 명령
|
||||
|
||||
```bash
|
||||
python3 build.py # 빌드
|
||||
bash scripts/preview.sh # 빌드 + http://localhost:8080
|
||||
bash scripts/studio.sh # 작품 편집 화면 http://localhost:8081
|
||||
git add -A && git commit -m "작품 추가: 목련 티매트"
|
||||
git push
|
||||
bash scripts/deploy.sh # QNAP 배포 (rsync)
|
||||
|
||||
@@ -0,0 +1,163 @@
|
||||
# 한땀 — 자수 티매트 사이트 (가칭)
|
||||
|
||||
DB 없는 정적 사이트. 콘텐츠는 `content/` 의 md·json 파일이고, `python3 build.py` 가 `dist/` 를 만든다.
|
||||
사이트를 고치는 일 = 파일 몇 개 고치고 커밋하고 배포하는 일. 그래서 전부 git 이력으로 되돌릴 수 있다.
|
||||
|
||||
| 용도 | 주소 |
|
||||
|---|---|
|
||||
| 로컬 미리보기 (아이맥) | http://localhost:8080 |
|
||||
| 운영 | https://teamat.lala.dedyn.io/ (서브패스 https://home.lala.dedyn.io/teamat/ 도 병행 유효) |
|
||||
| 소스 저장소 | https://git.lala.dedyn.io/koreafood/teamat |
|
||||
|
||||
## 빠른 시작
|
||||
|
||||
```bash
|
||||
cd ~/Projects/teamat
|
||||
bash scripts/preview.sh # 빌드 + http://localhost:8080 (Ctrl+C 로 종료)
|
||||
bash scripts/deploy.sh # QNAP 운영 서버로 배포
|
||||
bash scripts/rollback.sh # 마지막 커밋 되돌리기
|
||||
bash scripts/rollback.sh 2f22e71 # 특정 커밋 시점으로 내용 되돌리기
|
||||
```
|
||||
|
||||
## 작품 하나 추가하기
|
||||
|
||||
1. slug 를 정한다 — **`연-월-영문제목`** (예: `2026-11-magnolia-tea-mat`). 파일명 = slug = URL
|
||||
2. 사진을 **`assets/img/2026-11-magnolia-tea-mat/`** 폴더에 넣는다 (대표 `cover.jpg`, 추가 컷은 `detail-01.jpg`)
|
||||
3. `content/products/2026-11-magnolia-tea-mat.md` 를 만든다 — front matter 스키마는 `CLAUDE.md` 3절
|
||||
4. `python3 build.py`
|
||||
5. `bash scripts/deploy.sh`
|
||||
|
||||
작품마다 폴더 하나. 사진이 많아져도 작품별로 모여 있고, 파일명 앞의 연-월로 시기가 바로 보인다.
|
||||
공정 사진처럼 여러 곳에서 쓰는 이미지는 `assets/img/process/` 에 둔다.
|
||||
|
||||
목록과 상세 페이지는 자동으로 생긴다. 코드는 건드리지 않는다.
|
||||
|
||||
## 문구·가격·링크 고치기
|
||||
|
||||
| 바꾸고 싶은 것 | 고칠 파일 |
|
||||
|---|---|
|
||||
| 브랜드 소개, 배송·세탁 안내, 연락처 | `content/site.json` |
|
||||
| 작품 제목·가격·규격·이야기 | `content/products/<slug>.md` |
|
||||
| 제작 과정 단계 | `content/process/*.md` |
|
||||
| 네이버 스토어 링크 | `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` 토큰 |
|
||||
|
||||
## 작업실 — 화면에서 작품 고치기 (studio)
|
||||
|
||||
작품이 많아져 파일을 일일이 찾기 힘들 때 쓰는 **로컬 전용** 관리 화면이다. 사이트가 아니라 편집 도구다.
|
||||
|
||||
```bash
|
||||
bash scripts/studio.sh # http://localhost:8081
|
||||
```
|
||||
|
||||
- 왼쪽 목록: 검색(제목·슬러그·소재·본문) + 칩(판매중/품절/대표작/올해) + 정렬. 오른쪽: 편집 폼
|
||||
- 저장 = md 파일 쓰기 → `build.py` → `git commit`. **빌드가 실패하면 원본을 자동 복원**한다
|
||||
- `배포까지` 체크하면 저장과 동시에 `scripts/deploy.sh` 실행
|
||||
- 상단 `이력 / 되돌리기` = 최근 커밋 목록과 `git revert`
|
||||
- 작품 상세 페이지의 `이 작품 고치기` 버튼은 localhost 에서만 보인다 (운영 사이트에서는 hidden)
|
||||
- 이미지: JPG 를 끌어다 놓으면 `assets/img/<슬러그>/` 에 저장되고 경로가 자동 입력된다 (PNG 는 빌드가 못 읽어 거부)
|
||||
- **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` 에만 붙는다. 외부에서 접근되지 않는다
|
||||
|
||||
## 폰에서 등록 (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 에 말로 지시하면 위 파일들을 알아서 고친다. 예:
|
||||
|
||||
- "작품 목록에서 가격을 더 크게 보이게 해줘"
|
||||
- "새 작품 '겨울 매화 티매트', 32×48, 6만원으로 추가해줘. 사진은 아직 없으니 기존 이미지 재사용"
|
||||
- "제작 과정을 3단계로 줄여줘"
|
||||
- "모바일에서 글자가 조금 큰 것 같아. 본문 15px로"
|
||||
- "방금 바꾼 거 되돌려줘"
|
||||
|
||||
지시 후에는 항상 미리보기(`localhost:8080`)로 확인 → 만족하면 "커밋하고 올려줘".
|
||||
|
||||
## 롤백 원칙
|
||||
|
||||
- 되돌리기는 **새 커밋(revert)** 으로 한다. `git push --force` 는 쓰지 않는다
|
||||
- `dist/` 는 git 에 없다. 소스 커밋 하나만 맞으면 언제든 같은 결과가 재생성된다
|
||||
- 배포 사고 시: `bash scripts/rollback.sh <직전 정상 커밋>`
|
||||
|
||||
## 이미지 출처
|
||||
|
||||
샘플 이미지는 공개 라이선스 자료이며 푸터에 표기되어 있다.
|
||||
|
||||
| 파일 | 원본 | 라이선스 |
|
||||
|---|---|---|
|
||||
| `2026-10-cedar-tea-mat/cover.jpg`, `process/stitch.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 |
|
||||
|
||||
실제 작품 사진으로 교체하면 해당 표기와 `site.json` 의 `image_credits` 도 함께 정리한다.
|
||||
|
||||
## 아직 없는 것 (의도적으로)
|
||||
|
||||
결제·회원·장바구니·**재고 개수 관리**(작품은 유일품이라 판매중/판매완료 두 상태로 충분), 게시판·리뷰, 다국어, 사이트 내 검색, 분석 스크립트.
|
||||
관리자 화면은 사이트에 없다 — 대신 별도 도구 `studio/` 가 QNAP 컨테이너로 돌고, 폰에서 접속한다.
|
||||
구매는 네이버 스마트스토어로 넘긴다.
|
||||
@@ -772,7 +772,7 @@ strong {
|
||||
|
||||
.back-link {
|
||||
display: inline-block;
|
||||
margin-block: 8px 28px;
|
||||
margin-block: 8px 20px;
|
||||
color: var(--muted);
|
||||
font-size: 13px;
|
||||
text-decoration: none;
|
||||
@@ -786,63 +786,159 @@ strong {
|
||||
padding-bottom: clamp(40px, 6vw, 80px);
|
||||
}
|
||||
|
||||
.product-top {
|
||||
/* 제목은 작게 — 사진이 먼저 보이도록 */
|
||||
.product-head {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 7fr) minmax(0, 4fr);
|
||||
gap: clamp(36px, 5vw, 80px);
|
||||
align-items: start;
|
||||
gap: 4px;
|
||||
margin-bottom: clamp(14px, 2.5vw, 26px);
|
||||
}
|
||||
|
||||
.product-media {
|
||||
aspect-ratio: 4 / 5;
|
||||
overflow: hidden;
|
||||
background: var(--line);
|
||||
}
|
||||
|
||||
.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-title {
|
||||
margin: 0;
|
||||
font-size: clamp(1.05rem, 1.4vw, 1.3rem);
|
||||
font-weight: 400;
|
||||
line-height: 1.45;
|
||||
letter-spacing: 0;
|
||||
}
|
||||
|
||||
.product-sub {
|
||||
margin-top: 14px;
|
||||
margin: 0;
|
||||
color: var(--muted);
|
||||
font-size: 17px;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.product-price {
|
||||
margin-top: 26px;
|
||||
font-size: 18px;
|
||||
.product-head-price {
|
||||
margin: 6px 0 0;
|
||||
font-size: 15px;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
.product-info .btn,
|
||||
.product-info .pending {
|
||||
margin-top: 24px;
|
||||
/* 1. 메인 사진 */
|
||||
.product-hero {
|
||||
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 {
|
||||
margin-top: 8px;
|
||||
margin-top: 10px;
|
||||
color: var(--muted);
|
||||
font-size: 12px;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.spec {
|
||||
margin-top: 44px;
|
||||
margin-top: 30px;
|
||||
border-top: 1px solid var(--line);
|
||||
}
|
||||
|
||||
@@ -866,73 +962,52 @@ strong {
|
||||
line-height: 1.6;
|
||||
}
|
||||
|
||||
.product-story {
|
||||
display: grid;
|
||||
grid-template-columns: 120px minmax(0, 1fr);
|
||||
gap: clamp(20px, 4vw, 56px);
|
||||
align-items: start;
|
||||
margin-top: clamp(72px, 10vw, 140px);
|
||||
/* ------------------------------------------------------------ sold out */
|
||||
|
||||
.soldout .section-head {
|
||||
border-top: 1px solid var(--line);
|
||||
padding-top: clamp(36px, 5vw, 64px);
|
||||
}
|
||||
|
||||
.product-story .label {
|
||||
padding-top: 10px;
|
||||
.soldout {
|
||||
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 {
|
||||
margin-bottom: 1.4em;
|
||||
font-size: 17px;
|
||||
line-height: 1.85;
|
||||
.inquiry-btn {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
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 {
|
||||
font-size: clamp(1.25rem, 1.9vw, 1.5rem);
|
||||
line-height: 1.7;
|
||||
.inquiry-btn:hover {
|
||||
background: var(--sage);
|
||||
border-color: var(--sage);
|
||||
}
|
||||
|
||||
.prose p:last-child {
|
||||
margin-bottom: 0;
|
||||
.inquiry-note {
|
||||
margin-top: 8px;
|
||||
color: var(--muted);
|
||||
font-size: 12px;
|
||||
line-height: 1.6;
|
||||
}
|
||||
|
||||
.prose h2 {
|
||||
margin: 2em 0 0.7em;
|
||||
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;
|
||||
.detail-body .inquiry-btn {
|
||||
margin-top: 18px;
|
||||
}
|
||||
|
||||
.pager {
|
||||
@@ -1077,29 +1152,20 @@ strong {
|
||||
gap: 48px;
|
||||
}
|
||||
|
||||
.product-top {
|
||||
.product-story,
|
||||
.product-detail {
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.product-info {
|
||||
position: static;
|
||||
padding-top: 0;
|
||||
}
|
||||
|
||||
.product-info .spec {
|
||||
margin-top: 36px;
|
||||
}
|
||||
|
||||
.product-story {
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
}
|
||||
|
||||
.product-story .label {
|
||||
.product-story .label,
|
||||
.product-detail > .label {
|
||||
padding-top: 0;
|
||||
}
|
||||
|
||||
.product-hero,
|
||||
.gallery {
|
||||
grid-column: 1;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.foot-meta {
|
||||
@@ -1122,10 +1188,17 @@ strong {
|
||||
}
|
||||
|
||||
.nav {
|
||||
gap: 18px;
|
||||
gap: 0;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
/* 터치 영역 44px 확보 — 음수 마진으로 글자 위치는 그대로 둔다 */
|
||||
.nav a {
|
||||
display: inline-block;
|
||||
padding: 12px 11px;
|
||||
margin-block: -12px;
|
||||
}
|
||||
|
||||
.wordmark-en {
|
||||
display: none;
|
||||
}
|
||||
@@ -1217,7 +1290,7 @@ strong {
|
||||
}
|
||||
|
||||
.nav {
|
||||
gap: 14px;
|
||||
gap: 0;
|
||||
}
|
||||
|
||||
.wordmark-ko {
|
||||
@@ -1233,3 +1306,23 @@ strong {
|
||||
gap: 12px;
|
||||
}
|
||||
}
|
||||
|
||||
/* 작업실(studio) 편집 링크 — 로컬 미리보기에서만 노출된다 */
|
||||
.studio-edit {
|
||||
display: inline-block;
|
||||
margin-top: 12px;
|
||||
padding: 5px 11px;
|
||||
font-size: 12px;
|
||||
letter-spacing: .04em;
|
||||
color: var(--clay);
|
||||
border: 1px solid var(--line);
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.studio-edit:hover {
|
||||
border-color: var(--clay);
|
||||
}
|
||||
|
||||
.studio-edit[hidden] {
|
||||
display: none;
|
||||
}
|
||||
|
After Width: | Height: | Size: 62 KiB |
|
After Width: | Height: | Size: 98 KiB |
|
After Width: | Height: | Size: 47 KiB |
|
After Width: | Height: | Size: 217 KiB |
|
After Width: | Height: | Size: 79 KiB |
|
After Width: | Height: | Size: 391 KiB |
|
After Width: | Height: | Size: 327 KiB |
|
After Width: | Height: | Size: 359 KiB |
|
After Width: | Height: | Size: 309 KiB |
|
After Width: | Height: | Size: 212 KiB |
|
After Width: | Height: | Size: 301 KiB |
|
After Width: | Height: | Size: 287 KiB |
|
After Width: | Height: | Size: 332 KiB |
|
After Width: | Height: | Size: 164 KiB |
|
After Width: | Height: | Size: 203 KiB |
|
After Width: | Height: | Size: 350 KiB |
|
After Width: | Height: | Size: 292 KiB |
|
After Width: | Height: | Size: 209 KiB |
|
After Width: | Height: | Size: 506 KiB |
|
After Width: | Height: | Size: 255 KiB |
|
After Width: | Height: | Size: 123 KiB |
|
After Width: | Height: | Size: 101 KiB |
|
After Width: | Height: | Size: 58 KiB |
|
After Width: | Height: | Size: 61 KiB |
|
After Width: | Height: | Size: 332 KiB |
|
Before Width: | Height: | Size: 450 KiB |
@@ -20,7 +20,7 @@ CONTENT = ROOT / "content"
|
||||
TEMPLATES = ROOT / "templates"
|
||||
ASSETS = ROOT / "assets"
|
||||
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*}}")
|
||||
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,
|
||||
"home": home,
|
||||
"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", "")),
|
||||
"price_text": format_price(product.get("price")),
|
||||
"sold_html": sold_html,
|
||||
"inquiry_title": esc(product["title"]),
|
||||
}
|
||||
)
|
||||
return items
|
||||
@@ -432,9 +434,12 @@ def build_index(
|
||||
hero_image = str(featured["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:
|
||||
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_width, kit_height = image_size(kit_image)
|
||||
kit_body_html = markdown_to_html(kit["body"])
|
||||
@@ -465,6 +470,7 @@ def build_index(
|
||||
"og_title": esc(title),
|
||||
"og_description": esc(intro),
|
||||
"og_image": esc(absolute_url(hero_image)),
|
||||
"canonical": SITE_BASE,
|
||||
"og_type": "website",
|
||||
"body_class": "is-home",
|
||||
"intro": esc(intro),
|
||||
@@ -475,7 +481,14 @@ def build_index(
|
||||
"hero_title": esc(featured["title"]),
|
||||
"hero_material": esc(featured.get("material", "")),
|
||||
"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_intro": esc(site.get("process_intro", "")),
|
||||
"kit_title": esc(kit["title"]),
|
||||
@@ -522,7 +535,11 @@ def build_product_page(
|
||||
width, height = image_size(image)
|
||||
|
||||
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:
|
||||
naver_url = str(product.get("naver_url", "")).strip()
|
||||
if naver_url:
|
||||
@@ -558,6 +575,10 @@ def build_product_page(
|
||||
|
||||
subtitle = str(product.get("subtitle", "")).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)
|
||||
title = f"{product['title']} — {brand['name']}"
|
||||
|
||||
@@ -569,8 +590,10 @@ def build_product_page(
|
||||
"og_title": esc(title),
|
||||
"og_description": esc(description),
|
||||
"og_image": esc(absolute_url(image)),
|
||||
"canonical": absolute_url("p/" + product["slug"] + ".html"),
|
||||
"og_type": "product",
|
||||
"body_class": "is-product",
|
||||
"slug": esc(product["slug"]),
|
||||
"image": esc(image),
|
||||
"alt": esc(product.get("image_alt") or product["title"]),
|
||||
"width": str(width),
|
||||
@@ -579,8 +602,10 @@ def build_product_page(
|
||||
"title_text": esc(product["title"]),
|
||||
"subtitle": esc(subtitle),
|
||||
"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 "",
|
||||
"buy_html": buy_html,
|
||||
"inquiry_title": esc(product["title"]),
|
||||
"material": esc(material) or "—",
|
||||
"size": esc(product.get("size", "")) or "—",
|
||||
"care": esc(product.get("care", "")) or "—",
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
step: 1
|
||||
title: 천 고르기
|
||||
image: assets/img/craft-jogakbo.jpg
|
||||
image: assets/img/process/fabric.jpg
|
||||
image_alt: 여러 색 천 조각을 이어 붙인 조각보
|
||||
---
|
||||
린넨은 물에 한 번 담갔다 말려 수축을 빼고 시작합니다. 햇빛에 비춰 올이 고른 쪽, 빛을 고르게 받는 쪽을 고릅니다. 천의 폭이 좁으면 두 폭을 이어 붙입니다.
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
step: 3
|
||||
title: 한 땀 놓기
|
||||
image: assets/img/work-green-linen.jpg
|
||||
image: assets/img/process/stitch.jpg
|
||||
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원이 더 붙습니다.
|
||||
|
||||
도안과 촬영 사진의 저작권은 라라원단에 있습니다. 상업적인 사용은 삼가 주십시오.
|
||||
@@ -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: ""
|
||||
---
|
||||
성긴 린넨의 올 사이로 빛이 지나갑니다. 그 위에 녹색 면사로 솔잎을 길게 놓았습니다. 잎마다 방향을 조금씩 달리해, 같은 잎이 반복되지 않게 했습니다.
|
||||
|
||||
가장자리는 접어 박음질하고, 귀퉁이마다 실을 두 번 돌려 마무리했습니다. 티포트를 올리면 잎의 방향을 따라 그림자가 생깁니다.
|
||||
|
||||
한 점에 보름 남짓 걸렸습니다. 실의 색은 세 가지를 나란히 놓고 골랐습니다. 쓰고 나면 미지근한 물에 단독으로 손세탁하고 그늘에 뉘어 말립니다.
|
||||
@@ -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 티매트 한 장이 됩니다.
|
||||
|
||||
처음이면 가장자리부터 시작하세요. 실을 길게 빼지 않고, 한 땀 놓고 손을 한 번 내리는 리듬이 익숙해지면 안쪽으로 들어갑니다. 도안은 단순하게 그렸습니다. 천의 결을 가리지 않도록.
|
||||
|
||||
막히면 메일로 물어보셔도 됩니다. 사진 한 장을 보내주시면 어느 자리에서 멈췄는지 함께 봅니다.
|
||||
@@ -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: ""
|
||||
---
|
||||
아이보리 린넨 위에 흰 면사로 목련 한 송이를 놓았습니다. 꽃잎의 윤곽은 실을 두 번 겹쳐 놓고, 안쪽은 올을 풀어 비웠습니다.
|
||||
|
||||
가장자리는 실 한 올씩 풀어 올을 정리했습니다. 찻잔을 올리면 천의 결이 비쳐 보이고, 물기가 닿아도 금세 마릅니다.
|
||||
|
||||
한 점에 열흘 남짓 걸렸습니다. 하루에 두어 시간씩, 손이 가는 만큼 천천히 놓았습니다. 쓰고 나면 미지근한 물에 단독으로 손세탁하고 그늘에 뉘어 말립니다.
|
||||
@@ -9,13 +9,15 @@
|
||||
"contact": {
|
||||
"email": "hello@hanttam.kr",
|
||||
"instagram": "",
|
||||
"kakao": ""
|
||||
"kakao": "https://pf.kakao.com/_VsLWX/friend"
|
||||
},
|
||||
"shop": {
|
||||
"store_url": "",
|
||||
"kit_url": "",
|
||||
"kit_slug": "2026-10-kit-first-stitch",
|
||||
"store_url": "https://smartstore.naver.com/lalashopkr",
|
||||
"kit_url": "https://smartstore.naver.com/lalashopkr/products/5758959852",
|
||||
"kit_note": "린넨 천, 면사, 도안, 바늘 — 처음 시작하는 사람에게 필요한 것들"
|
||||
},
|
||||
"works_note": "완성품은 한 점씩 미리 만들어 두고, 재고가 있을 때만 판매합니다. 판매된 작품은 같은 무늬로 다시 만들 수 있으나, 재제작 문의가 있을 때만 진행합니다. 최근에 만든 순서로 놓았습니다.",
|
||||
"process_intro": "천을 고르고, 도안을 옮기고, 한 땀씩 놓아 마감하기까지. 서두르지 않고 네 단계로 만납니다.",
|
||||
"shipping": [
|
||||
"주문 후 3~5일 이내 제작·발송",
|
||||
@@ -29,8 +31,16 @@
|
||||
"product_sort": "newest",
|
||||
"footer_note": "사업자등록번호와 통신판매업 신고 번호는 추후 기재합니다.",
|
||||
"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": "Wrapping cloth (bojagi), Korea", "author": "Hiart", "license": "CC0"}
|
||||
]
|
||||
{
|
||||
"title": "Japanese flat silk embroidery on leno-weave fabric",
|
||||
"author": "Ineffablebookkeeper",
|
||||
"license": "CC BY-SA 4.0"
|
||||
},
|
||||
{
|
||||
"title": "Wrapping cloth (bojagi), Korea",
|
||||
"author": "Hiart",
|
||||
"license": "CC0"
|
||||
}
|
||||
],
|
||||
"sold_works_note": "재고가 없는 작품입니다. 같은 무늬로 다시 만들 수 있어요 — 카톡으로 문의하시면 제작 일정과 값을 함께 알려 드립니다."
|
||||
}
|
||||
@@ -3,20 +3,21 @@ set -euo pipefail
|
||||
|
||||
cd "$(dirname "$0")/.."
|
||||
|
||||
REMOTE="admin@100.101.79.24"
|
||||
REMOTE_DIR="/share/CACHEDEV8_DATA/web/www/teamat/"
|
||||
# 2026-11-27: 공개 사이트는 이 폴더의 dist/ 를 그대로 서빙한다.
|
||||
# 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_URL2="https://teamat.lala.dedyn.io/"
|
||||
|
||||
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")"
|
||||
if [ "$status" != "200" ]; then
|
||||
echo "배포 후 확인 실패: ${SITE_URL} (HTTP ${status})" >&2
|
||||
echo "확인 실패: ${SITE_URL} (HTTP ${status})" >&2
|
||||
exit 1
|
||||
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})"
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -0,0 +1,8 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
cd "$(dirname "$0")/.."
|
||||
|
||||
# 작품을 화면에서 찾아 고치는 로컬 전용 편집 도구.
|
||||
# 사이트가 아니라 관리 도구다. 127.0.0.1 에만 붙는다.
|
||||
exec python3 studio/server.py "$@"
|
||||
@@ -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"]
|
||||
@@ -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)
|
||||
@@ -0,0 +1,817 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ko">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>한땀 작업실</title>
|
||||
<style>
|
||||
:root {
|
||||
--paper: #f7f4ee;
|
||||
--card: #fffdf9;
|
||||
--ink: #1f1c18;
|
||||
--muted: #7a726a;
|
||||
--line: #ddd5c9;
|
||||
--accent: #7c5c3e;
|
||||
--ok: #2f6b47;
|
||||
--warn: #a4471f;
|
||||
}
|
||||
* { box-sizing: border-box; }
|
||||
html, body { height: 100%; }
|
||||
body {
|
||||
margin: 0;
|
||||
background: var(--paper);
|
||||
color: var(--ink);
|
||||
font: 15px/1.55 -apple-system, "Apple SD Gothic Neo", "Noto Sans KR", sans-serif;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
header.top {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
gap: 14px;
|
||||
padding: 14px 20px;
|
||||
border-bottom: 1px solid var(--line);
|
||||
background: var(--card);
|
||||
}
|
||||
header.top h1 { font-size: 17px; margin: 0; letter-spacing: .08em; }
|
||||
header.top .meta { color: var(--muted); font-size: 12.5px; }
|
||||
header.top .spacer { flex: 1; }
|
||||
main.split { display: flex; flex: 1; min-height: 0; }
|
||||
|
||||
/* ---------- 목록 ---------- */
|
||||
aside.list {
|
||||
width: 330px;
|
||||
border-right: 1px solid var(--line);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-height: 0;
|
||||
background: var(--card);
|
||||
}
|
||||
.search-wrap { padding: 12px 12px 8px; }
|
||||
input[type=search], input[type=text], input[type=number], input[type=date], input[type=url], textarea, select {
|
||||
width: 100%;
|
||||
font: inherit;
|
||||
color: inherit;
|
||||
background: #fff;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 4px;
|
||||
padding: 7px 9px;
|
||||
}
|
||||
input[type=search] { font-size: 14px; }
|
||||
.chips { display: flex; flex-wrap: wrap; gap: 6px; padding: 0 12px 8px; }
|
||||
.chip {
|
||||
font-size: 12px;
|
||||
padding: 3px 9px;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 999px;
|
||||
background: #fff;
|
||||
color: var(--muted);
|
||||
cursor: pointer;
|
||||
}
|
||||
.chip[aria-pressed=true] { border-color: var(--accent); color: var(--accent); font-weight: 600; }
|
||||
.listbar { display: flex; gap: 8px; align-items: center; padding: 0 12px 8px; }
|
||||
.listbar select { width: auto; font-size: 12.5px; padding: 4px 6px; }
|
||||
.listbar .count { font-size: 12px; color: var(--muted); margin-left: auto; }
|
||||
ul.rows { list-style: none; margin: 0; padding: 0 6px 24px; overflow-y: auto; flex: 1; }
|
||||
ul.rows li { padding: 0; margin: 0 0 2px; }
|
||||
ul.rows button.row {
|
||||
display: flex;
|
||||
gap: 9px;
|
||||
align-items: center;
|
||||
width: 100%;
|
||||
text-align: left;
|
||||
background: none;
|
||||
border: 0;
|
||||
border-radius: 4px;
|
||||
padding: 7px 8px;
|
||||
cursor: pointer;
|
||||
font: inherit;
|
||||
color: inherit;
|
||||
}
|
||||
ul.rows button.row:hover { background: #f1ece2; }
|
||||
ul.rows button.row[aria-current=true] { background: #ece4d5; outline: 1px solid var(--accent); }
|
||||
.thumb {
|
||||
width: 40px; height: 40px; flex: 0 0 40px;
|
||||
object-fit: cover; border-radius: 3px;
|
||||
background: #eee; border: 1px solid var(--line);
|
||||
}
|
||||
.row-main { min-width: 0; flex: 1; }
|
||||
.row-title { font-size: 13.5px; font-weight: 600; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
.row-sub { font-size: 11.5px; color: var(--muted); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
.badge {
|
||||
font-size: 10.5px; padding: 1px 6px; border-radius: 3px;
|
||||
border: 1px solid var(--line); color: var(--muted); white-space: nowrap;
|
||||
}
|
||||
.badge.sold { color: #fff; background: var(--warn); border-color: var(--warn); }
|
||||
.badge.feat { color: var(--accent); border-color: var(--accent); }
|
||||
.empty { padding: 20px 14px; color: var(--muted); font-size: 13px; }
|
||||
|
||||
/* ---------- 편집기 ---------- */
|
||||
section.editor { flex: 1; min-width: 0; display: flex; flex-direction: column; }
|
||||
.editor-head {
|
||||
display: flex; align-items: center; gap: 10px;
|
||||
padding: 12px 20px; border-bottom: 1px solid var(--line);
|
||||
}
|
||||
.editor-head h2 { font-size: 15px; margin: 0; }
|
||||
.editor-head code { font-size: 12px; color: var(--muted); background: #f2ece1; padding: 2px 6px; border-radius: 3px; }
|
||||
.editor-body { overflow-y: auto; padding: 18px 20px 28px; }
|
||||
.grid { display: grid; grid-template-columns: 1fr 1fr; gap: 12px 16px; }
|
||||
.grid .wide { grid-column: 1 / -1; }
|
||||
label.field { display: block; }
|
||||
label.field > span.lbl { display: block; font-size: 12px; color: var(--muted); margin-bottom: 4px; }
|
||||
label.field input[type=checkbox] { width: 15px; height: 15px; margin-right: 6px; vertical-align: -2px; }
|
||||
.check-line { display: flex; align-items: center; gap: 4px; padding-top: 19px; }
|
||||
textarea { resize: vertical; min-height: 90px; font-family: ui-monospace, "SF Mono", Menlo, monospace; font-size: 13px; line-height: 1.6; }
|
||||
.img-line { display: flex; gap: 8px; align-items: center; }
|
||||
.img-line input { flex: 1; }
|
||||
.img-preview { width: 52px; height: 52px; object-fit: cover; border: 1px solid var(--line); border-radius: 3px; background: #eee; }
|
||||
.drop-hint { font-size: 11.5px; color: var(--muted); margin-top: 4px; }
|
||||
.drop-hint.hot { color: var(--accent); font-weight: 600; }
|
||||
.divider { height: 1px; background: var(--line); margin: 18px 0 14px; }
|
||||
.section-label { font-size: 11.5px; letter-spacing: .12em; color: var(--muted); margin-bottom: 6px; }
|
||||
footer.savebar {
|
||||
display: flex; align-items: center; gap: 10px;
|
||||
padding: 11px 20px; border-top: 1px solid var(--line); background: var(--card);
|
||||
}
|
||||
footer.savebar .state { font-size: 12.5px; color: var(--muted); }
|
||||
footer.savebar .spacer { flex: 1; }
|
||||
button {
|
||||
font: inherit; cursor: pointer; border-radius: 4px;
|
||||
border: 1px solid var(--line); background: #fff; color: inherit; padding: 7px 13px;
|
||||
}
|
||||
button:hover:not(:disabled) { border-color: var(--accent); }
|
||||
button.primary { background: var(--accent); border-color: var(--accent); color: #fff; }
|
||||
button.primary:hover:not(:disabled) { background: #6a4d33; }
|
||||
button:disabled { opacity: .45; cursor: default; }
|
||||
button.ghost { background: none; border-color: transparent; color: var(--muted); }
|
||||
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 {
|
||||
position: fixed; inset: 0; background: rgba(31, 28, 24, .28);
|
||||
display: none; justify-content: flex-end; z-index: 40;
|
||||
}
|
||||
#drawer.open { display: flex; }
|
||||
.drawer-panel {
|
||||
width: min(460px, 92vw); background: var(--card); height: 100%;
|
||||
border-left: 1px solid var(--line); display: flex; flex-direction: column;
|
||||
}
|
||||
.drawer-panel header {
|
||||
display: flex; align-items: center; gap: 10px;
|
||||
padding: 13px 16px; border-bottom: 1px solid var(--line);
|
||||
}
|
||||
.drawer-panel header h3 { font-size: 14px; margin: 0; }
|
||||
.drawer-panel header .spacer { flex: 1; }
|
||||
ul.commits { list-style: none; margin: 0; padding: 6px; overflow-y: auto; }
|
||||
ul.commits li {
|
||||
display: flex; gap: 10px; align-items: center;
|
||||
padding: 8px 10px; border-bottom: 1px solid #f0eae0; font-size: 13px;
|
||||
}
|
||||
ul.commits .sha { font-family: ui-monospace, Menlo, monospace; font-size: 11.5px; color: var(--muted); }
|
||||
ul.commits .subject { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
ul.commits .when { font-size: 11px; color: var(--muted); }
|
||||
ul.commits button { padding: 3px 9px; font-size: 12px; }
|
||||
|
||||
/* ---------- 토스트 ---------- */
|
||||
#toast {
|
||||
position: fixed; left: 50%; bottom: 22px; transform: translateX(-50%) translateY(20px);
|
||||
background: #241f19; color: #f7f4ee; padding: 10px 16px; border-radius: 5px;
|
||||
font-size: 13px; max-width: min(720px, 92vw); opacity: 0; pointer-events: none;
|
||||
transition: opacity .18s, transform .18s; z-index: 60; white-space: pre-wrap;
|
||||
}
|
||||
#toast.show { opacity: 1; transform: translateX(-50%) translateY(0); }
|
||||
#toast.err { background: #6d2410; }
|
||||
#toast.ok { background: #1f4a33; }
|
||||
.hint { font-size: 12px; color: var(--muted); }
|
||||
kbd {
|
||||
font: 11px ui-monospace, Menlo, monospace; border: 1px solid var(--line);
|
||||
border-bottom-width: 2px; border-radius: 3px; padding: 0 4px; background: #fff;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<header class="top">
|
||||
<h1>한땀 작업실</h1>
|
||||
<span class="meta" id="topmeta">불러오는 중…</span>
|
||||
<span class="spacer"></span>
|
||||
<span class="hint"><kbd>/</kbd> 검색 · <kbd>↑↓</kbd> 이동 · <kbd>⌘S</kbd> 저장</span>
|
||||
<button id="btnHistory" class="ghost">이력 / 되돌리기</button>
|
||||
</header>
|
||||
|
||||
<main class="split">
|
||||
<aside class="list">
|
||||
<div class="search-wrap">
|
||||
<input type="search" id="q" placeholder="제목 · 슬러그 · 소재 · 본문 검색" autocomplete="off">
|
||||
</div>
|
||||
<div class="chips" id="chips">
|
||||
<button class="chip" data-f="all" aria-pressed="true">전체</button>
|
||||
<button class="chip" data-f="on" aria-pressed="false">판매중</button>
|
||||
<button class="chip" data-f="sold" aria-pressed="false">품절</button>
|
||||
<button class="chip" data-f="feat" aria-pressed="false">대표작</button>
|
||||
<button class="chip" data-f="year" aria-pressed="false">올해</button>
|
||||
</div>
|
||||
<div class="listbar">
|
||||
<select id="sort">
|
||||
<option value="modified">최근 수정</option>
|
||||
<option value="date">날짜 최신</option>
|
||||
<option value="title">이름</option>
|
||||
<option value="price">가격</option>
|
||||
</select>
|
||||
<button id="btnNew" class="ghost" style="font-size:12px;padding:4px 8px;">+ 새 작품</button>
|
||||
<span class="count" id="rowcount"></span>
|
||||
</div>
|
||||
<ul class="rows" id="rows"></ul>
|
||||
</aside>
|
||||
|
||||
<section class="editor">
|
||||
<div class="editor-head">
|
||||
<h2 id="edTitle">작품을 고르세요</h2>
|
||||
<code id="edSlug"></code>
|
||||
<span class="spacer"></span>
|
||||
<span class="hint" id="edModified"></span>
|
||||
</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">
|
||||
<p class="empty">왼쪽 목록에서 작품을 고르면 여기서 바로 고칠 수 있습니다.</p>
|
||||
</div>
|
||||
<footer class="savebar">
|
||||
<button id="btnSave" class="primary" disabled>저장 (커밋)</button>
|
||||
<label class="hint" style="display:flex;align-items:center;gap:5px;">
|
||||
<input type="checkbox" id="deployToo"> 배포까지
|
||||
</label>
|
||||
<span class="state" id="state">—</span>
|
||||
<span class="spacer"></span>
|
||||
<button id="btnReload" class="ghost" disabled>되돌리기(저장 전)</button>
|
||||
</footer>
|
||||
</section>
|
||||
</main>
|
||||
|
||||
<div id="drawer">
|
||||
<div class="drawer-panel">
|
||||
<header>
|
||||
<h3>최근 이력</h3>
|
||||
<span class="spacer"></span>
|
||||
<label class="hint" style="display:flex;align-items:center;gap:5px;">
|
||||
<input type="checkbox" id="revertDeploy"> 되돌린 뒤 배포
|
||||
</label>
|
||||
<button class="ghost" id="btnCloseDrawer">닫기</button>
|
||||
</header>
|
||||
<ul class="commits" id="commits"></ul>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="toast"></div>
|
||||
|
||||
<script>
|
||||
const state = { rows: [], fields: [], current: null, dirty: false, filter: 'all', q: '', sort: 'modified' };
|
||||
const $ = (id) => document.getElementById(id);
|
||||
const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));
|
||||
let toastTimer = null;
|
||||
|
||||
function toast(msg, kind = '') {
|
||||
const el = $('toast');
|
||||
el.textContent = msg;
|
||||
el.className = 'show ' + kind;
|
||||
clearTimeout(toastTimer);
|
||||
toastTimer = setTimeout(() => { el.className = ''; }, kind === 'err' ? 7000 : 3200);
|
||||
}
|
||||
|
||||
async function api(path, opts) {
|
||||
const res = await fetch(path, opts);
|
||||
try { return await res.json(); } catch (e) { return { ok: false, error: '응답을 읽을 수 없습니다 (' + res.status + ')' }; }
|
||||
}
|
||||
|
||||
function markDirty(dirty) {
|
||||
state.dirty = dirty;
|
||||
$('state').textContent = dirty ? '저장하지 않은 변경' : '변경 없음';
|
||||
$('btnSave').disabled = !($('f_slug') || state.current) || !dirty;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------ 목록 */
|
||||
function visibleRows() {
|
||||
const q = state.q.trim().toLowerCase();
|
||||
let rows = state.rows.filter((r) => {
|
||||
if (state.filter === 'on' && r.sold_out) return false;
|
||||
if (state.filter === 'sold' && !r.sold_out) return false;
|
||||
if (state.filter === 'feat' && !r.featured) return false;
|
||||
if (state.filter === 'year' && !String(r.date || '').startsWith(String(new Date().getFullYear()))) return false;
|
||||
if (q && !(r.search || '').includes(q)) return false;
|
||||
return true;
|
||||
});
|
||||
const k = state.sort;
|
||||
rows.sort((a, b) => {
|
||||
if (k === 'modified') return (b.mtime || 0) - (a.mtime || 0);
|
||||
if (k === 'date') return String(b.date).localeCompare(String(a.date));
|
||||
if (k === 'title') return String(a.title).localeCompare(String(b.title), 'ko');
|
||||
if (k === 'price') return (b.price || 0) - (a.price || 0);
|
||||
return 0;
|
||||
});
|
||||
return rows;
|
||||
}
|
||||
|
||||
function renderList() {
|
||||
const rows = visibleRows();
|
||||
$('rowcount').textContent = rows.length + ' / ' + state.rows.length + '점';
|
||||
const ul = $('rows');
|
||||
if (!rows.length) {
|
||||
ul.innerHTML = '<li class="empty">조건에 맞는 작품이 없습니다.</li>';
|
||||
return;
|
||||
}
|
||||
ul.innerHTML = rows.map((r) => {
|
||||
const active = state.current === r.slug;
|
||||
const img = r.image ? '<img class="thumb" src="/media/' + encodeURI(r.image) + '" alt="" loading="lazy">' : '<span class="thumb"></span>';
|
||||
const badges = [
|
||||
r.sold_out ? '<span class="badge sold">품절</span>' : '',
|
||||
r.featured ? '<span class="badge feat">대표</span>' : '',
|
||||
].join('');
|
||||
return '<li><button class="row" data-slug="' + esc(r.slug) + '" aria-current="' + active + '">' +
|
||||
img +
|
||||
'<span class="row-main"><span class="row-title">' + esc(r.title) + ' ' + badges + '</span>' +
|
||||
'<span class="row-sub">' + esc(r.slug) + ' · ' + esc(r.date) + ' · ' + esc(r.modified) + '</span></span>' +
|
||||
'</button></li>';
|
||||
}).join('');
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------ 편집기 */
|
||||
function fieldHtml(f, value) {
|
||||
const id = 'f_' + f.key;
|
||||
const wide = ['image', 'image_alt', 'care', 'naver_url'].includes(f.key) ? ' wide' : '';
|
||||
if (f.type === 'bool') {
|
||||
return '<label class="field' + wide + '"><span class="check-line"><input type="checkbox" id="' + id + '" data-key="' + f.key + '"' +
|
||||
(value ? ' checked' : '') + '> ' + esc(f.label) + '</span></label>';
|
||||
}
|
||||
if (f.type === 'lines') {
|
||||
return '<label class="field wide"><span class="lbl">' + esc(f.label) + '</span>' +
|
||||
'<textarea id="' + id + '" data-key="' + f.key + '" rows="3">' + esc(value) + '</textarea></label>';
|
||||
}
|
||||
if (f.type === 'image') {
|
||||
return '<label class="field wide"><span class="lbl">' + esc(f.label) + '</span>' +
|
||||
'<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="">' +
|
||||
'<button type="button" class="ghost" id="' + id + '_pick">올리기</button></span>' +
|
||||
'<span class="drop-hint" id="' + id + '_hint">JPG를 끌어다 놓으면 assets/img/<슬러그>/ 에 저장됩니다</span></label>';
|
||||
}
|
||||
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>' +
|
||||
'<input type="' + type + '" id="' + id + '" data-key="' + f.key + '" value="' + esc(value) + '"></label>';
|
||||
}
|
||||
|
||||
function renderEditor(p) {
|
||||
const values = p.fields || {};
|
||||
const isDraft = !!p.draft;
|
||||
if (isDraft) state.current = null;
|
||||
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 =
|
||||
'<div class="grid">' + grid + '</div>' +
|
||||
'<div class="divider"></div>' +
|
||||
'<div class="section-label">본문 (마크다운)</div>' +
|
||||
'<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></code> 지원.</p>' +
|
||||
'<div style="margin-top:10px">' + extra + '</div>';
|
||||
$('edTitle').textContent = isDraft ? '새 작품 (저장 전)' : (values.title || p.slug);
|
||||
$('edSlug').textContent = isDraft ? '' : p.slug;
|
||||
$('edModified').textContent = isDraft ? 'AI 초안' : '파일 수정 ' + p.modified;
|
||||
$('btnReload').disabled = false;
|
||||
wireEditor();
|
||||
markDirty(false);
|
||||
}
|
||||
|
||||
function wireEditor() {
|
||||
document.querySelectorAll('[data-key]').forEach((el) => {
|
||||
el.addEventListener('input', () => markDirty(true));
|
||||
el.addEventListener('change', () => markDirty(true));
|
||||
});
|
||||
const img = $('f_image');
|
||||
if (img) {
|
||||
img.addEventListener('input', () => { $('f_image_prev').src = img.value ? '/media/' + encodeURI(img.value) : ''; });
|
||||
$('f_image_pick').addEventListener('click', () => pickImage(img));
|
||||
const hint = $('f_image_hint');
|
||||
['dragenter', 'dragover'].forEach((ev) => hint.addEventListener(ev, (e) => { e.preventDefault(); hint.classList.add('hot'); }));
|
||||
['dragleave', 'drop'].forEach((ev) => hint.addEventListener(ev, () => hint.classList.remove('hot')));
|
||||
hint.addEventListener('drop', (e) => {
|
||||
e.preventDefault();
|
||||
const file = e.dataTransfer.files && e.dataTransfer.files[0];
|
||||
if (file) uploadImage(file, img);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function pickImage(target) {
|
||||
const input = document.createElement('input');
|
||||
input.type = 'file';
|
||||
input.accept = 'image/jpeg';
|
||||
input.addEventListener('change', () => { if (input.files[0]) uploadImage(input.files[0], target); });
|
||||
input.click();
|
||||
}
|
||||
|
||||
async function uploadImage(file, target) {
|
||||
const slugEl = $('f_slug');
|
||||
const slug = (slugEl ? slugEl.value.trim() : '') || state.current || '';
|
||||
if (!slug) { toast('슬러그를 먼저 정해야 이미지를 넣을 수 있습니다', 'err'); return; }
|
||||
$('state').textContent = '이미지 올리는 중…';
|
||||
const res = await fetch('/api/upload?name=' + encodeURIComponent(file.name) + '&slug=' + encodeURIComponent(slug), {
|
||||
method: 'POST', headers: { 'Content-Type': 'application/octet-stream' }, body: file,
|
||||
});
|
||||
const data = await res.json().catch(() => ({ ok: false, error: '업로드 실패' }));
|
||||
if (!data.ok) { toast(data.error || '업로드 실패', 'err'); $('state').textContent = '—'; return; }
|
||||
target.value = data.path;
|
||||
target.dispatchEvent(new Event('input', { bubbles: true }));
|
||||
target.dispatchEvent(new Event('change', { bubbles: true }));
|
||||
toast('이미지 저장: ' + data.path, 'ok');
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------ 열기/저장 */
|
||||
async function openProduct(slug) {
|
||||
if (state.dirty && !confirm('저장하지 않은 변경이 있습니다. 버리고 넘어갈까요?')) return;
|
||||
const data = await api('/api/product?slug=' + encodeURIComponent(slug));
|
||||
if (!data.ok) { toast(data.error || '작품을 열 수 없습니다', 'err'); return; }
|
||||
state.current = slug;
|
||||
renderList();
|
||||
renderEditor(data.product);
|
||||
$('state').textContent = '변경 없음';
|
||||
}
|
||||
|
||||
function collect() {
|
||||
const fields = {};
|
||||
document.querySelectorAll('[data-key]').forEach((el) => {
|
||||
fields[el.dataset.key] = el.type === 'checkbox' ? el.checked : el.value;
|
||||
});
|
||||
const slugEl = $('f_slug');
|
||||
return {
|
||||
slug: slugEl ? slugEl.value.trim() : state.current,
|
||||
fields, body: $('body').value,
|
||||
deploy: $('deployToo').checked,
|
||||
create: !!slugEl,
|
||||
};
|
||||
}
|
||||
|
||||
async function save() {
|
||||
const payload = collect();
|
||||
if (!payload.slug) { toast('슬러그를 입력해 주세요', 'err'); return; }
|
||||
$('btnSave').disabled = true;
|
||||
$('state').textContent = '저장 중… (빌드 → 커밋)';
|
||||
const data = await api('/api/product', {
|
||||
method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload),
|
||||
});
|
||||
if (!data.ok) {
|
||||
$('state').textContent = '실패';
|
||||
toast((data.error || '저장 실패') + (data.log ? '\n' + data.log : ''), 'err');
|
||||
$('btnSave').disabled = false;
|
||||
return;
|
||||
}
|
||||
markDirty(false);
|
||||
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');
|
||||
if (payload.create) {
|
||||
state.current = null;
|
||||
await refresh({ keep: true });
|
||||
await openProduct(payload.slug);
|
||||
} else {
|
||||
await refresh({ keep: true });
|
||||
}
|
||||
}
|
||||
|
||||
async function refresh(opts = {}) {
|
||||
const data = await api('/api/state');
|
||||
if (!data.ok) { toast('상태를 읽지 못했습니다', 'err'); return; }
|
||||
state.rows = data.products;
|
||||
state.fields = data.fields;
|
||||
$('topmeta').textContent = data.count + '점 · HEAD ' + data.head + ' · ' + data.repo;
|
||||
renderList();
|
||||
if (!opts.keep) {
|
||||
const wanted = new URLSearchParams(location.search).get('slug');
|
||||
if (wanted) openProduct(wanted);
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------ 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() {
|
||||
const data = await api('/api/history');
|
||||
if (!data.ok) { toast('이력을 읽지 못했습니다', 'err'); return; }
|
||||
$('commits').innerHTML = data.history.map((c) =>
|
||||
'<li><span class="sha">' + esc(c.sha) + '</span>' +
|
||||
'<span class="subject" title="' + esc(c.subject) + '">' + esc(c.subject) + '</span>' +
|
||||
'<span class="when">' + esc(c.date) + '</span>' +
|
||||
'<button data-revert="' + esc(c.sha) + '">되돌리기</button></li>'
|
||||
).join('');
|
||||
$('drawer').classList.add('open');
|
||||
}
|
||||
|
||||
async function revertTo(sha, btn) {
|
||||
if (!confirm(sha + ' 커밋을 되돌립니다(새 커밋으로 취소). 계속할까요?')) return;
|
||||
if (btn) btn.disabled = true;
|
||||
const data = await api('/api/revert', {
|
||||
method: 'POST', headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ sha, deploy: $('revertDeploy').checked }),
|
||||
});
|
||||
toast(data.ok ? data.message : ((data.error || '실패') + (data.log ? '\n' + data.log : '')), data.ok ? 'ok' : 'err');
|
||||
if (data.ok) {
|
||||
await refresh({ keep: true });
|
||||
if (state.current) { const p = await api('/api/product?slug=' + encodeURIComponent(state.current)); if (p.ok) renderEditor(p.product); }
|
||||
openHistory();
|
||||
} else if (btn) btn.disabled = false;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------ 이벤트 */
|
||||
$('q').addEventListener('input', (e) => { state.q = e.target.value; renderList(); });
|
||||
$('sort').addEventListener('change', (e) => { state.sort = e.target.value; renderList(); });
|
||||
$('chips').addEventListener('click', (e) => {
|
||||
const chip = e.target.closest('.chip');
|
||||
if (!chip) return;
|
||||
state.filter = chip.dataset.f;
|
||||
document.querySelectorAll('.chip').forEach((c) => c.setAttribute('aria-pressed', String(c === chip)));
|
||||
renderList();
|
||||
});
|
||||
$('rows').addEventListener('click', (e) => {
|
||||
const btn = e.target.closest('button.row');
|
||||
if (btn) openProduct(btn.dataset.slug);
|
||||
});
|
||||
$('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); });
|
||||
$('btnHistory').addEventListener('click', openHistory);
|
||||
$('btnCloseDrawer').addEventListener('click', () => $('drawer').classList.remove('open'));
|
||||
$('drawer').addEventListener('click', (e) => { if (e.target.id === 'drawer') $('drawer').classList.remove('open'); });
|
||||
$('commits').addEventListener('click', (e) => {
|
||||
const btn = e.target.closest('button[data-revert]');
|
||||
if (btn) revertTo(btn.dataset.revert, btn);
|
||||
});
|
||||
|
||||
document.addEventListener('keydown', (e) => {
|
||||
const typing = /^(INPUT|TEXTAREA|SELECT)$/.test(document.activeElement.tagName);
|
||||
if (e.key === '/' && !typing) { e.preventDefault(); $('q').focus(); return; }
|
||||
if (e.key === 'Escape') { $('drawer').classList.remove('open'); return; }
|
||||
if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 's') { e.preventDefault(); save(); return; }
|
||||
if (!typing && (e.key === 'ArrowDown' || e.key === 'ArrowUp')) {
|
||||
const rows = visibleRows();
|
||||
if (!rows.length) return;
|
||||
e.preventDefault();
|
||||
let idx = rows.findIndex((r) => r.slug === state.current);
|
||||
idx = e.key === 'ArrowDown' ? Math.min(rows.length - 1, idx + 1) : Math.max(0, idx - 1);
|
||||
openProduct(rows[idx].slug);
|
||||
const el = document.querySelector('button.row[data-slug="' + rows[idx].slug + '"]');
|
||||
if (el) el.scrollIntoView({ block: 'nearest' });
|
||||
}
|
||||
});
|
||||
|
||||
window.addEventListener('beforeunload', (e) => { if (state.dirty) { e.preventDefault(); e.returnValue = ''; } });
|
||||
|
||||
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>
|
||||
</body>
|
||||
</html>
|
||||
@@ -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)
|
||||
@@ -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>
|
||||
@@ -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"}
|
||||
]
|
||||
}
|
||||
@@ -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"}
|
||||
@@ -0,0 +1,107 @@
|
||||
#!/usr/bin/env python3
|
||||
"""한땀 작업실 API 스모크 테스트 — 저장·커밋·되돌리기 왕복 검증."""
|
||||
import json
|
||||
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"
|
||||
SLUG = "2026-10-whitework-tea-mat"
|
||||
MD = ROOT / "content/products" / f"{SLUG}.md"
|
||||
|
||||
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=""):
|
||||
print(("OK " if cond else "FAIL ") + name + (f" {extra}" if extra and not cond else ""))
|
||||
if not cond:
|
||||
fails.append(name)
|
||||
|
||||
|
||||
def req(path, payload=None, raw=None, method=None):
|
||||
url = BASE + path
|
||||
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(url, data=data, headers=headers, method=method or ("POST" if data else "GET"))
|
||||
try:
|
||||
with urllib.request.urlopen(request, timeout=120) 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}
|
||||
|
||||
|
||||
original = MD.read_text(encoding="utf-8")
|
||||
|
||||
# 1. 목록
|
||||
code, state = req("/api/state")
|
||||
check("GET /api/state", code == 200 and state["ok"] and state["count"] >= 3, str(code))
|
||||
head0 = state["head"]
|
||||
|
||||
# 2. 작품 열기
|
||||
code, data = req(f"/api/product?slug={SLUG}")
|
||||
check("GET /api/product", code == 200 and data["product"]["fields"]["title"] == TITLE, str(code))
|
||||
fields0 = data["product"]["fields"]
|
||||
body0 = data["product"]["body"]
|
||||
check("본문 읽힘", len(body0) > 50)
|
||||
check("추가 이미지 필드(빈 목록)", fields0["gallery"] == "")
|
||||
|
||||
# 3. 변경 없이 저장 → 커밋하지 않아야 함
|
||||
code, data = req("/api/product", {"slug": SLUG, "fields": fields0, "body": body0})
|
||||
check("무변경 저장은 커밋 안 함", data["ok"] and data["changed"] is False, json.dumps(data)[:200])
|
||||
|
||||
# 4. 실제 수정 저장 (+ 추가 이미지 1장)
|
||||
fields = dict(fields0)
|
||||
fields["subtitle"] = "스모크 테스트 부제"
|
||||
fields["price"] = "59000"
|
||||
fields["gallery"] = "assets/img/2026-10-whitework-tea-mat/cover.jpg"
|
||||
code, data = req("/api/product", {"slug": SLUG, "fields": fields, "body": body0})
|
||||
check("수정 저장 성공", data["ok"] and data.get("changed") is True, json.dumps(data)[:300])
|
||||
sha = data.get("head", "")
|
||||
check("HEAD 이동", sha != head0, f"{head0} -> {sha}")
|
||||
|
||||
text = MD.read_text(encoding="utf-8")
|
||||
check("파일 반영(subtitle)", "subtitle: 스모크 테스트 부제" in text)
|
||||
check("파일 반영(price 정수)", "price: 59000" in text, text[:400])
|
||||
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])
|
||||
|
||||
code, data = req("/api/history")
|
||||
check("이력에 수정 커밋", any(TITLE in row["subject"] for row in data["history"]), str(data["history"][:2]))
|
||||
|
||||
# 5. 이미지 업로드 거부 (JPG 아님)
|
||||
code, data = req("/api/upload?name=x.png", raw=b"\x89PNG\r\n")
|
||||
check("PNG 업로드 거부", data["ok"] is False, json.dumps(data))
|
||||
|
||||
# 6. 잘못된 슬러그
|
||||
code, data = req("/api/product?slug=../../etc/passwd")
|
||||
check("경로 조작 차단", code in (400, 404), str(code))
|
||||
|
||||
# 7. 되돌리기
|
||||
code, data = req("/api/revert", {"sha": sha, "deploy": False})
|
||||
check("되돌리기 성공", data["ok"] is True, json.dumps(data)[:300])
|
||||
check("파일 원복", MD.read_text(encoding="utf-8") == original, "원본과 다름")
|
||||
|
||||
# 8. 되돌린 뒤 무변경 저장은 다시 커밋하지 않아야 함
|
||||
code, data = req(f"/api/product?slug={SLUG}")
|
||||
code, again = req("/api/product", {"slug": SLUG, "fields": data["product"]["fields"], "body": data["product"]["body"]})
|
||||
check("원복 후 무변경", again["ok"] and again["changed"] is False, json.dumps(again)[:200])
|
||||
|
||||
print()
|
||||
print(f"{'실패 ' + str(len(fails)) + '건: ' + ', '.join(fails) if fails else '전부 통과'}")
|
||||
sys.exit(1 if fails else 0)
|
||||
@@ -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")}
|
||||
@@ -9,6 +9,7 @@
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com">
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
||||
<link href="https://fonts.googleapis.com/css2?family=Noto+Sans+KR:wght@300;400;500&family=Noto+Serif+KR:wght@400;600&display=swap" rel="stylesheet">
|
||||
<link rel="canonical" href="{{canonical}}">
|
||||
<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">
|
||||
<meta property="og:title" content="{{og_title}}">
|
||||
@@ -26,10 +27,10 @@
|
||||
<span class="wordmark-en">{{brand_name_en}}</span>
|
||||
</a>
|
||||
<nav class="nav" aria-label="주요">
|
||||
<a href="{{home}}index.html#works">작품</a>
|
||||
<a href="{{home}}index.html#process">과정</a>
|
||||
<a href="{{home}}index.html#kit">키트</a>
|
||||
<a href="{{home}}index.html#contact">문의</a>
|
||||
<a href="{{home}}#works">작품</a>
|
||||
<a href="{{home}}#process">과정</a>
|
||||
<a href="{{home}}#kit">키트</a>
|
||||
<a href="{{home}}#contact">문의</a>
|
||||
</nav>
|
||||
</div>
|
||||
</header>
|
||||
@@ -61,5 +62,12 @@
|
||||
<p class="foot-copy">© {{since}} {{brand_name}}</p>
|
||||
</div>
|
||||
</footer>
|
||||
|
||||
<script>
|
||||
// 작업실(studio) 링크: 로컬에서 열었을 때만 보인다. 운영 사이트에서는 hidden 그대로.
|
||||
if (["localhost", "127.0.0.1"].indexOf(location.hostname) !== -1) {
|
||||
document.querySelectorAll(".studio-edit").forEach(function (el) { el.hidden = false; });
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -27,7 +27,7 @@
|
||||
<header class="section-head">
|
||||
<p class="label">WORKS</p>
|
||||
<h2 id="works-title">작품</h2>
|
||||
<p class="section-note">최근에 만든 순서로 놓았습니다. 한 점씩, 천과 실을 고른 뒤에 시작합니다.</p>
|
||||
<p class="section-note">{{works_note}}</p>
|
||||
</header>
|
||||
|
||||
<div class="works-grid">
|
||||
@@ -41,7 +41,6 @@
|
||||
<h3>{{title}}</h3>
|
||||
<p class="work-sub">{{subtitle}}</p>
|
||||
<p class="work-price">{{price_text}}</p>
|
||||
{{sold_html}}
|
||||
</div>
|
||||
</a>
|
||||
</article>
|
||||
@@ -50,6 +49,76 @@
|
||||
</div>
|
||||
</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">
|
||||
<div class="shell">
|
||||
<header class="section-head">
|
||||
|
||||
@@ -2,18 +2,33 @@
|
||||
<a class="back-link" href="../index.html#works">← 작품 목록</a>
|
||||
</div>
|
||||
|
||||
<article class="product shell">
|
||||
<div class="product-top">
|
||||
<figure class="product-media">
|
||||
<img src="../{{image}}" alt="{{alt}}" width="{{width}}" height="{{height}}" loading="eager" fetchpriority="high" decoding="async">
|
||||
</figure>
|
||||
<article class="product">
|
||||
<header class="product-head shell">
|
||||
<h1 class="product-title">{{title}}</h1>
|
||||
<p class="product-sub">{{subtitle}}</p>
|
||||
<p class="product-head-price">{{price_text}}</p>
|
||||
{{price_note_html}}
|
||||
</header>
|
||||
|
||||
<div class="product-info">
|
||||
<h1>{{title}}</h1>
|
||||
<p class="product-sub">{{subtitle}}</p>
|
||||
<p class="product-price">{{price_text}}</p>
|
||||
<figure class="product-hero">
|
||||
<img src="../{{image}}" alt="{{alt}}" width="{{width}}" height="{{height}}" loading="eager" fetchpriority="high" decoding="async">
|
||||
</figure>
|
||||
|
||||
{{gallery_html}}
|
||||
|
||||
<section class="product-story shell">
|
||||
<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}}
|
||||
{{buy_html}}
|
||||
<a class="studio-edit" href="http://localhost:8081/?slug={{slug}}" hidden>이 작품 고치기</a>
|
||||
|
||||
<dl class="spec">
|
||||
<div>
|
||||
@@ -30,17 +45,9 @@
|
||||
</div>
|
||||
</dl>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<div class="product-story">
|
||||
<p class="label">STORY</p>
|
||||
<div class="prose">
|
||||
{{body_html}}
|
||||
</div>
|
||||
{{gallery_html}}
|
||||
</div>
|
||||
|
||||
<nav class="pager" aria-label="다른 작품">
|
||||
<nav class="pager shell" aria-label="다른 작품">
|
||||
<div class="pager-slot pager-prev">{{prev_html}}</div>
|
||||
<div class="pager-slot pager-next">{{next_html}}</div>
|
||||
</nav>
|
||||
|
||||
@@ -29,10 +29,13 @@
|
||||
|
||||
## 4. 판매 구조
|
||||
|
||||
- **완제품(자수 티매트)**: 사이트에서 소개·상세 → 구매 버튼은 **네이버 스마트스토어**로 이동
|
||||
- **자수 키트**: 같은 방식으로 네이버 링크
|
||||
- 사이트 안에는 결제·회원·장바구니·재고 관리를 두지 않는다
|
||||
- 가격은 표시하되(정보 제공) 결제는 외부. 링크는 `content/products/*.md` 의 `naver_url`, 키트는 `content/site.json` 의 `shop.kit_url` 에서 관리
|
||||
- **완성품(자수 티매트)**: 한 점씩 미리 완성해 두고 **재고가 있을 때만** 판매한다. 작품은 유일품(1점 = 1개)이라 재고는 `sold_out` 두 상태로 관리한다.
|
||||
- **판매되면** `sold_out: true` → 구매 버튼이 사라지고 "판매 완료 — 재제작을 원하시면 문의해 주세요" 안내로 바뀐다.
|
||||
- **판매 완료된 작품**은 같은 무늬로 다시 만들 수 있으나, **별도 문의가 있을 때만** 판매한다. 목록에는 남겨 두어 지난 작업을 볼 수 있게 한다.
|
||||
- **가격**: 한 장 15,000원, 네 장 세트 50,000원 (`price` = 최소 판매 단위, `price_note` = 세트·옵션 문장).
|
||||
- **구매 동선**: 재고가 있으면 구매 버튼 → **네이버 스마트스토어 상품 페이지**(`naver_url`)로 이동. 재고가 없으면 버튼을 만들지 않는다.
|
||||
- **자수 키트**: 완성품이 아니라 손으로 놓는 작업물. **키트 페이지에서 링크만 연결**해 스마트스토어 상품으로 넘긴다(`shop.kit_url`). 사이트에 키트용 판매 로직을 두지 않는다. 가격 16,000원(10 × 10 cm 네 장 분량 원단).
|
||||
- 사이트 안에는 결제·회원·장바구니·재고 개수 관리를 두지 않는다. 판매중/판매완료 두 상태로 충분하다.
|
||||
|
||||
## 5. 사이트 구조 (1차 범위)
|
||||
|
||||
@@ -82,7 +85,7 @@
|
||||
|---|---|
|
||||
| 소스 저장소 | Gitea `https://git.lala.dedyn.io/koreafood/teamat` (QNAP) |
|
||||
| 로컬 미리보기 | 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) |
|
||||
| 향후 | 독립 도메인(`teamat.lala.dedyn.io`), Cloudflare Pages·터널 |
|
||||
|
||||
@@ -118,7 +121,7 @@
|
||||
2. `http://localhost:8080` 에서 첫 페이지·작품 상세·이미지가 모두 뜬다
|
||||
3. 링크가 전부 살아 있다(깨진 상대경로 0개)
|
||||
4. 새 작품 md 1개를 넣고 빌드하면 목록과 상세가 자동으로 생긴다
|
||||
5. Gitea 에 푸시되어 있고, `https://home.lala.dedyn.io/teamat/` 에서 동일하게 보인다
|
||||
5. Gitea 에 푸시되어 있고, `https://teamat.lala.dedyn.io/` 에서 동일하게 보인다
|
||||
6. `scripts/rollback.sh` 로 직전 상태로 되돌아간다
|
||||
|
||||
---
|
||||
|
||||