Compare commits
3
Commits
481831e00d
...
a6835e943a
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a6835e943a | ||
|
|
f2ae889795 | ||
|
|
51f3cdbe1c |
No files matched your search
@@ -84,6 +84,10 @@ bash scripts/studio.sh # http://localhost:8081
|
||||
- 흐름: ① 사진 찍기(여러 장, 첫 장이 대표) → ② 내용 작성(사진을 읽어 초안) → ③ 규격·소재·세탁 칩 + 가격 → ④ 확인 후 저장
|
||||
- 저장하면 완료 화면에 `목록으로 돌아가기` 가 나오고, 목록의 그 작품에 `방금 등록` 배지가 붙는다. `저장만` 으로 저장한 작품은 `미발행` 배지가 붙는다.
|
||||
- 목록 위 `사이트에 올리기 (미발행 N점)` = 커밋된 상태를 그대로 배포한다. 커밋 안 된 초안이 있으면 먼저 물어본다. 배포 후 배지는 사라진다.
|
||||
- **고치기**: 목록 카드 오른쪽 `수정` → 제목·부제·본문·규격·소재·세탁·가격·날짜·네이버 링크·대표작/품절을 그대로 불러온다.
|
||||
사진은 순서 바꾸기(첫 장이 대표)·삭제·추가(촬영/앨범)가 되고, 저장하면 `assets/img/<slug>/` 를 다시 정리한다(쓰지 않는 사진은 지운다).
|
||||
`저장하고 사이트에 올리기` 또는 `저장만`. 저장 = md 재작성 → build → 커밋(`작품 수정: 제목`) → push.
|
||||
- `사이트에 올리기` 는 **빌드까지 다시 한 뒤** 복사한다(되돌리기·수동 편집 뒤에도 안전).
|
||||
- 저장 = `사진 축소(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)
|
||||
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 70 KiB |
@@ -1,18 +0,0 @@
|
||||
---
|
||||
slug: 2026-11-edit-test
|
||||
title: 수정한 작품 제목
|
||||
subtitle: 고친 부제
|
||||
date: 2026-11-01
|
||||
price: 23000
|
||||
price_note: ""
|
||||
sold_out: false
|
||||
featured: false
|
||||
image: assets/img/2026-11-edit-test/cover.jpg
|
||||
image_alt: 천 위에 흰 실로 무늬를 놓은 모습
|
||||
gallery:
|
||||
material: 린넨 100%
|
||||
size: 12 × 12 cm
|
||||
care: 손세탁
|
||||
naver_url: ""
|
||||
---
|
||||
고친 본문입니다. 문장이 이렇게 바뀌었는지 확인합니다.
|
||||
+177
-8
@@ -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}
|
||||
</style>
|
||||
@@ -208,6 +211,58 @@
|
||||
<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>
|
||||
|
||||
<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>
|
||||
</section>
|
||||
</main>
|
||||
|
||||
<div class="bar" id="bar">
|
||||
@@ -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 => `
|
||||
<a class="work-card" href="/p/${p.slug}.html" target="_blank" rel="noopener">
|
||||
<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>' : '')}
|
||||
</a>`).join('') || '<p class="note">아직 없습니다.</p>';
|
||||
</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');
|
||||
@@ -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=>`<button class="chip">${v}</button>`).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 = '<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-save').onclick = () => saveEdit(true);
|
||||
$('#e-save-only').onclick = () => saveEdit(false);
|
||||
$('#e-cancel').onclick = () => go('home');
|
||||
|
||||
/* ---------- 시작 ---------- */
|
||||
go('home'); loadPresets();
|
||||
</script>
|
||||
|
||||
+19
-1
@@ -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}
|
||||
|
||||
@@ -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"}
|
||||
Reference in new issue
Block a user