From a6835e943a3e39cc901c6dbe9e395c7d3ce11ff3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=ED=95=9C=EB=95=80=20=EC=9E=91=EC=97=85=EC=8B=A4?= Date: Sun, 1 Nov 2026 04:28:53 +0000 Subject: [PATCH] =?UTF-8?q?=EB=93=B1=EB=A1=9D=20=ED=99=94=EB=A9=B4:=20?= =?UTF-8?q?=EC=9E=91=ED=92=88=20=EC=88=98=EC=A0=95(=EC=82=AC=EC=A7=84=20?= =?UTF-8?q?=EC=9E=AC=EB=B0=B0=EC=B9=98=C2=B7=EC=82=AD=EC=A0=9C=C2=B7?= =?UTF-8?q?=EC=B6=94=EA=B0=80,=20=ED=95=AD=EB=AA=A9=20=ED=8E=B8=EC=A7=91,?= =?UTF-8?q?=20=EC=A0=80=EC=9E=A5/=EB=B0=B0=ED=8F=AC)=20+=20=EB=B0=B0?= =?UTF-8?q?=ED=8F=AC=20=EC=8B=9C=20=EC=9E=AC=EB=B9=8C=EB=93=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 4 + studio/m.html | 197 +++++++++++++++++++++++++++++++++++++++++++---- studio/server.py | 20 ++++- studio/update.py | 166 +++++++++++++++++++++++++++++++++++++++ 4 files changed, 372 insertions(+), 15 deletions(-) create mode 100644 studio/update.py diff --git a/README.md b/README.md index 2eb6bf5..4fce685 100644 --- a/README.md +++ b/README.md @@ -84,6 +84,10 @@ bash scripts/studio.sh # http://localhost:8081 - 흐름: ① 사진 찍기(여러 장, 첫 장이 대표) → ② 내용 작성(사진을 읽어 초안) → ③ 규격·소재·세탁 칩 + 가격 → ④ 확인 후 저장 - 저장하면 완료 화면에 `목록으로 돌아가기` 가 나오고, 목록의 그 작품에 `방금 등록` 배지가 붙는다. `저장만` 으로 저장한 작품은 `미발행` 배지가 붙는다. - 목록 위 `사이트에 올리기 (미발행 N점)` = 커밋된 상태를 그대로 배포한다. 커밋 안 된 초안이 있으면 먼저 물어본다. 배포 후 배지는 사라진다. +- **고치기**: 목록 카드 오른쪽 `수정` → 제목·부제·본문·규격·소재·세탁·가격·날짜·네이버 링크·대표작/품절을 그대로 불러온다. + 사진은 순서 바꾸기(첫 장이 대표)·삭제·추가(촬영/앨범)가 되고, 저장하면 `assets/img//` 를 다시 정리한다(쓰지 않는 사진은 지운다). + `저장하고 사이트에 올리기` 또는 `저장만`. 저장 = md 재작성 → build → 커밋(`작품 수정: 제목`) → push. +- `사이트에 올리기` 는 **빌드까지 다시 한 뒤** 복사한다(되돌리기·수동 편집 뒤에도 안전). - 저장 = `사진 축소(Pillow) → content/products/.md → build.py → git commit`(경로만 지정) → `git push`(Gitea). `사이트에 올리기` 를 누르면 `dist/` 를 웹 루트로 복사한다. - 사진은 `studio/_inbox/` 에 잠시 쌓였다가 발행 시 두 곳으로 나뉜다. - 사이트용: `assets/img//cover.jpg`, `detail-NN.jpg` (저장소에 커밋. 최대 1400px, 품질 82) diff --git a/studio/m.html b/studio/m.html index afb5f43..bcd3312 100644 --- a/studio/m.html +++ b/studio/m.html @@ -87,13 +87,16 @@ .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:grid;grid-template-columns:88px 1fr;gap:12px;align-items:center;text-decoration:none; - color:var(--ink);padding:10px 0;border-bottom:1px solid var(--line);position:relative} - .work-card img{width:88px;aspect-ratio:4/5;object-fit:cover;background:var(--line);display:block} + .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} .new-badge{position:absolute;right:0;top:10px;background:var(--sage);color:#fff; font-size:10px;letter-spacing:.08em;padding:3px 6px} @@ -208,6 +211,58 @@ + + +
@@ -240,6 +295,7 @@ const STEPS = { 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; @@ -247,7 +303,7 @@ function go(step){ $(STEPS[step].el).hidden = false; $('#steps').textContent = STEPS[step].n; const cfg = STEPS[step]; - $('#bar').style.display = step==='home' ? 'none' : 'grid'; + $('#bar').style.display = (step==='home' || step==='edit') ? 'none' : 'grid'; $('#back').style.visibility = cfg.prev ? 'visible' : 'hidden'; const next = $('#next'); next.textContent = step==='specs' ? '확인' : '다음'; @@ -277,16 +333,21 @@ async function loadHome(){ ? rows.length + '점 · 최근에 만든 순서입니다. 눌러서 확인하세요.' : '아직 등록한 작품이 없습니다.'; $('#home-list').innerHTML = rows.map(p => ` - - ${p.image ? `` : ''} -
- ${p.title} - ${p.subtitle || ''} - ${p.price ? Number(p.price).toLocaleString('ko-KR') + '원' : '가격 문의'}${p.sold_out ? ' · 판매 완료' : ''} -
+
+ + ${p.image ? `` : ''} +
+ ${p.title} + ${p.subtitle || ''} + ${p.price ? Number(p.price).toLocaleString('ko-KR') + '원' : '가격 문의'}${p.sold_out ? ' · 판매 완료' : ''} +
+
+ ${S.lastSlug === p.slug ? '방금 등록' : (p.live === false ? '미발행' : '')} - `).join('') || '

아직 없습니다.

'; +
`).join('') || '

아직 없습니다.

'; + + 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'); @@ -404,8 +465,9 @@ async function loadPresets(){ const d = await api('/api/presets'); S.presets = d.presets; document.querySelectorAll('.chips[data-for]').forEach(box=>{ - const key = box.dataset.for === 'f-size' ? 'size' - : box.dataset.for === 'f-material' ? 'material' : 'care'; + const target = box.dataset.for; + const key = target.endsWith('size') ? 'size' + : target.endsWith('material') ? 'material' : 'care'; box.innerHTML = (d.presets[key]||[]).map(v=>``).join(''); box.querySelectorAll('.chip').forEach(ch=>ch.onclick=()=>{ box.querySelectorAll('.chip').forEach(c=>c.setAttribute('aria-pressed','false')); @@ -500,6 +562,113 @@ $('#deploy-all').onclick = async () => { await run(false); }; +/* ---------- 고치기 ---------- */ +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 = '

사진이 없습니다. 한 장은 있어야 합니다.

'; return; } + box.innerHTML = imgs.map((p,i)=>` +
+ + ${i===0?'대표':''} +
+ ${i>0?``:''} + ${i→`:''} + +
+
`).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 사진 올리는 중 ${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 = `${e.message}`; 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 = '제목을 넣어 주세요'; return; } + if (!S.edit || !S.edit.images.length){ s.innerHTML = '사진이 최소 한 장 필요합니다'; return; } + ['#e-save','#e-save-only'].forEach(x=>$(x).disabled=true); + s.innerHTML = ' 저장 중… (사진 정리 → 빌드 → 커밋' + (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)}
` + + (d.deployed ? '사이트에 올렸습니다. ' : '저장만 했습니다. ') + + `페이지 열기`; + toast('수정 완료'); + S.lastSlug = d.slug; + }catch(e){ s.innerHTML = `${e.message}`; } + finally{ ['#e-save','#e-save-only'].forEach(x=>$(x).disabled=false); } +} +$('#e-save').onclick = () => saveEdit(true); +$('#e-save-only').onclick = () => saveEdit(false); +$('#e-cancel').onclick = () => go('home'); + /* ---------- 시작 ---------- */ go('home'); loadPresets(); diff --git a/studio/server.py b/studio/server.py index 575e44c..2e85ced 100644 --- a/studio/server.py +++ b/studio/server.py @@ -40,6 +40,7 @@ DEFAULT_MOBILE = os.environ.get("TEAMAT_DEFAULT_PAGE", "").strip().lower() in (" TOKEN_FILE = Path(os.environ.get("TEAMAT_CONFIG_DIR") or (Path.home() / ".config" / "teamat-studio")) / "token" import register as reg # 휴대폰 등록 흐름(사진 인박스·판독·발행) +import update as upd # 등록된 작품 고치기 LIST_KEYS = {"gallery"} @@ -817,6 +818,19 @@ class Handler(BaseHTTPRequestHandler): except RuntimeError as error: self.send_json({"ok": False, "error": str(error)}, 502) return + if path == "/api/update": + helpers = {"build": build, "git_commit": git_commit, "deploy": deploy, "push": push} + try: + result = upd.update_product(self.read_json(), helpers) + result["live_url"] = SITE_URL + str(result.get("url") or "") + self.send_json(result) + except FileNotFoundError as error: + self.send_json({"ok": False, "error": str(error)}, 404) + except ValueError as error: + self.send_json({"ok": False, "error": str(error)}, 400) + except RuntimeError as error: + self.send_json({"ok": False, "error": str(error)}, 500) + return if path == "/api/deploy": payload = self.read_json() drafts = reg.pending_drafts() @@ -824,8 +838,12 @@ class Handler(BaseHTTPRequestHandler): self.send_json({"ok": False, "needs_force": True, "drafts": drafts, "error": "커밋하지 않은 초안이 있어 배포를 멈췄습니다: " + ", ".join(drafts)}, 409) return + built, build_log = build() + if not built: + self.send_json({"ok": False, "log": build_log[-500:]}, 500) + return ok, log = deploy() - self.send_json({"ok": ok, "log": log[-500:], "head": head_sha()}) + self.send_json({"ok": ok, "log": (build_log.splitlines()[0] + " · " + log)[-500:], "head": head_sha()}) return if path == "/api/publish": helpers = {"build": build, "git_commit": git_commit, "deploy": deploy, "push": push} diff --git a/studio/update.py b/studio/update.py new file mode 100644 index 0000000..7106fdf --- /dev/null +++ b/studio/update.py @@ -0,0 +1,166 @@ +"""등록된 작품 수정 — 발행(publish)과 같은 규칙으로 md·이미지·커밋을 다시 쓴다.""" + +from __future__ import annotations + +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"}