Deploy AIOS web (React glide grid + FastAPI slice)
Browse files- api/routes_assets.py +132 -1
- platform/core/assets.py +70 -10
- web/dist-embed/index.html +0 -0
- web/src/customer-grid/CatalogView.tsx +105 -20
- web/src/customer-grid/catalogData.ts +68 -1
api/routes_assets.py
CHANGED
|
@@ -22,17 +22,20 @@ Codes are validated against a closed charset before they touch a filesystem or a
|
|
| 22 |
a path separator can never reach the lookup, so traversal is refused at the door (400), and an
|
| 23 |
unknown code is 404 `asset_not_found`, never an empty 200.
|
| 24 |
"""
|
|
|
|
|
|
|
| 25 |
import os
|
| 26 |
import re
|
| 27 |
import tempfile
|
| 28 |
import time
|
| 29 |
from pathlib import Path
|
| 30 |
|
| 31 |
-
from fastapi import Depends
|
| 32 |
from fastapi import APIRouter
|
| 33 |
from fastapi.responses import FileResponse
|
| 34 |
|
| 35 |
from deps import Session, err, module_gate
|
|
|
|
| 36 |
|
| 37 |
router = APIRouter(prefix="/api/v1")
|
| 38 |
|
|
@@ -163,3 +166,131 @@ def product_asset(code: str, q: str = "web",
|
|
| 163 |
media = _EXT_MEDIA.get(Path(path).suffix.lower(), "application/octet-stream")
|
| 164 |
return FileResponse(str(path), media_type=media,
|
| 165 |
headers={"Cache-Control": _IMMUTABLE})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 22 |
a path separator can never reach the lookup, so traversal is refused at the door (400), and an
|
| 23 |
unknown code is 404 `asset_not_found`, never an empty 200.
|
| 24 |
"""
|
| 25 |
+
import base64
|
| 26 |
+
import io
|
| 27 |
import os
|
| 28 |
import re
|
| 29 |
import tempfile
|
| 30 |
import time
|
| 31 |
from pathlib import Path
|
| 32 |
|
| 33 |
+
from fastapi import Body, Depends
|
| 34 |
from fastapi import APIRouter
|
| 35 |
from fastapi.responses import FileResponse
|
| 36 |
|
| 37 |
from deps import Session, err, module_gate
|
| 38 |
+
from routes_admin import admin_gate
|
| 39 |
|
| 40 |
router = APIRouter(prefix="/api/v1")
|
| 41 |
|
|
|
|
| 166 |
media = _EXT_MEDIA.get(Path(path).suffix.lower(), "application/octet-stream")
|
| 167 |
return FileResponse(str(path), media_type=media,
|
| 168 |
headers={"Cache-Control": _IMMUTABLE})
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
# ------------------------------------------------------------------ editorial (DEBT-5)
|
| 172 |
+
# Non-SKU imagery for catalog GALLERY pages — the 2027 book's full-bleed lifestyle
|
| 173 |
+
# photography, which has no product code to live under. Second prefix in the same repo:
|
| 174 |
+
# assets/editorial/orig/<slug><ext> masters, verbatim
|
| 175 |
+
# assets/editorial/web/<slug>.png ~1600px derivative (full-page display)
|
| 176 |
+
# manifest.json gains {"editorial": {"<slug>": {"ext": ...}}}
|
| 177 |
+
# The designer addresses these as `ed:<slug>` in a page's imageCode — a prefix the product
|
| 178 |
+
# charset can never produce (':' is outside _CODE_RE), so the two namespaces cannot collide.
|
| 179 |
+
#
|
| 180 |
+
# MODAL, not layered: with AIOS_ASSET_DIR set, `<dir>/editorial/` is AUTHORITATIVE (dev and
|
| 181 |
+
# the hermetic gate); otherwise the repo is. Falling through dir→repo here would let a gate
|
| 182 |
+
# with a temp dir silently read the production repo and go green on prod state.
|
| 183 |
+
|
| 184 |
+
_ED_WEB_EDGE = 1600 # full-page display derivative; print still serves the master
|
| 185 |
+
_SLUG_RE = re.compile(r"^[a-z0-9][a-z0-9-]{0,63}$")
|
| 186 |
+
_ED_MAX_BYTES = 25 * 1024 * 1024
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
def _ed_dir(create=False):
|
| 190 |
+
d = _local_dir()
|
| 191 |
+
if d is None:
|
| 192 |
+
return None
|
| 193 |
+
p = d / "editorial"
|
| 194 |
+
if create:
|
| 195 |
+
p.mkdir(parents=True, exist_ok=True)
|
| 196 |
+
return p
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
def _ed_dir_index(ed):
|
| 200 |
+
idx = {}
|
| 201 |
+
try:
|
| 202 |
+
for p in sorted(ed.iterdir()):
|
| 203 |
+
if p.is_file() and p.suffix.lower() in _EXT_MEDIA and not p.name.startswith("."):
|
| 204 |
+
idx.setdefault(p.stem.lower(), p)
|
| 205 |
+
except OSError:
|
| 206 |
+
pass
|
| 207 |
+
return idx
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
@router.get("/assets/editorial")
|
| 211 |
+
def editorial_manifest(session: Session = Depends(module_gate(MODULE))):
|
| 212 |
+
"""The slugs that HAVE an editorial image — the designer's picker reads this."""
|
| 213 |
+
if _local_dir() is not None:
|
| 214 |
+
ed = _ed_dir()
|
| 215 |
+
return {"slugs": sorted(_ed_dir_index(ed).keys()) if ed else [], "source": "dir"}
|
| 216 |
+
slugs = _assets().editorial()
|
| 217 |
+
return {"slugs": sorted(slugs.keys()), "source": "repo" if slugs else "none"}
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
@router.get("/assets/editorial/{slug}")
|
| 221 |
+
def editorial_asset(slug: str, q: str = "web",
|
| 222 |
+
session: Session = Depends(module_gate(MODULE))):
|
| 223 |
+
if q not in _QUALITIES:
|
| 224 |
+
raise err(400, "bad_quality", f"q must be one of {', '.join(_QUALITIES)}")
|
| 225 |
+
slug = str(slug or "").strip().lower()
|
| 226 |
+
if not _SLUG_RE.match(slug):
|
| 227 |
+
raise err(400, "bad_slug", "that is not an editorial slug")
|
| 228 |
+
|
| 229 |
+
path = None
|
| 230 |
+
if _local_dir() is not None:
|
| 231 |
+
ed = _ed_dir()
|
| 232 |
+
src = _ed_dir_index(ed).get(slug) if ed else None
|
| 233 |
+
if src is not None:
|
| 234 |
+
path = _web_derivative(src, f"ed_{slug}") if q == "web" else src
|
| 235 |
+
else:
|
| 236 |
+
path = _assets().fetch_editorial(slug, q)
|
| 237 |
+
if path is None or not Path(path).is_file():
|
| 238 |
+
raise err(404, "asset_not_found", f"no editorial image named {slug}")
|
| 239 |
+
media = _EXT_MEDIA.get(Path(path).suffix.lower(), "application/octet-stream")
|
| 240 |
+
return FileResponse(str(path), media_type=media,
|
| 241 |
+
headers={"Cache-Control": _IMMUTABLE})
|
| 242 |
+
|
| 243 |
+
|
| 244 |
+
@router.post("/assets/editorial", status_code=201)
|
| 245 |
+
def editorial_upload(body: dict = Body(default=None),
|
| 246 |
+
session: Session = Depends(admin_gate)):
|
| 247 |
+
"""Store one editorial image: `{slug, data}` with `data` base64 (JSON keeps the API free
|
| 248 |
+
of a multipart dependency; an admin upload is rare enough to wear the +33%). The bytes
|
| 249 |
+
must OPEN as an image — a corrupt file is refused here, not discovered on a printed page."""
|
| 250 |
+
body = body or {}
|
| 251 |
+
slug = str(body.get("slug") or "").strip().lower()
|
| 252 |
+
if not _SLUG_RE.match(slug):
|
| 253 |
+
raise err(400, "bad_slug",
|
| 254 |
+
"slugs are lowercase letters, digits and hyphens (max 64)")
|
| 255 |
+
raw = str(body.get("data") or "")
|
| 256 |
+
raw = raw.split(",", 1)[1] if raw.startswith("data:") and "," in raw else raw
|
| 257 |
+
try:
|
| 258 |
+
blob = base64.b64decode(raw, validate=True)
|
| 259 |
+
except Exception:
|
| 260 |
+
raise err(400, "bad_image", "data must be base64 image bytes")
|
| 261 |
+
if not blob:
|
| 262 |
+
raise err(400, "bad_image", "the upload is empty")
|
| 263 |
+
if len(blob) > _ED_MAX_BYTES:
|
| 264 |
+
raise err(400, "image_too_large",
|
| 265 |
+
f"editorial masters cap at {_ED_MAX_BYTES // (1024 * 1024)} MB")
|
| 266 |
+
try:
|
| 267 |
+
from PIL import Image
|
| 268 |
+
except ImportError:
|
| 269 |
+
raise err(503, "pillow_missing",
|
| 270 |
+
"image validation needs Pillow — `pip install pillow` on this host")
|
| 271 |
+
try:
|
| 272 |
+
with Image.open(io.BytesIO(blob)) as im:
|
| 273 |
+
im.load()
|
| 274 |
+
fmt = (im.format or "").upper()
|
| 275 |
+
if fmt not in ("PNG", "JPEG"):
|
| 276 |
+
raise err(400, "bad_image", "PNG or JPEG only")
|
| 277 |
+
ext = ".png" if fmt == "PNG" else ".jpg"
|
| 278 |
+
web = im.convert("RGB") if im.mode not in ("RGB", "RGBA", "L", "LA") else im.copy()
|
| 279 |
+
web.thumbnail((_ED_WEB_EDGE, _ED_WEB_EDGE))
|
| 280 |
+
buf = io.BytesIO()
|
| 281 |
+
web.save(buf, format="PNG", optimize=True)
|
| 282 |
+
except Exception as e:
|
| 283 |
+
if getattr(e, "status_code", None):
|
| 284 |
+
raise
|
| 285 |
+
raise err(400, "bad_image", "that file does not open as an image")
|
| 286 |
+
|
| 287 |
+
if _local_dir() is not None:
|
| 288 |
+
ed = _ed_dir(create=True)
|
| 289 |
+
(ed / f"{slug}{ext}").write_bytes(blob)
|
| 290 |
+
return {"slug": slug, "source": "dir"}
|
| 291 |
+
try:
|
| 292 |
+
_assets().put_editorial(slug, blob, ext, buf.getvalue())
|
| 293 |
+
except Exception:
|
| 294 |
+
raise err(503, "asset_repo_unavailable",
|
| 295 |
+
"the asset repo did not accept the upload — try again")
|
| 296 |
+
return {"slug": slug, "source": "repo"}
|
platform/core/assets.py
CHANGED
|
@@ -24,8 +24,10 @@ from pathlib import Path
|
|
| 24 |
|
| 25 |
DEFAULT_REPO = 'royal-imports/product-assets'
|
| 26 |
_MANIFEST_TTL = 300
|
| 27 |
-
#: (fetched_at, {"CODE": {"
|
| 28 |
-
|
|
|
|
|
|
|
| 29 |
|
| 30 |
|
| 31 |
def repo_id():
|
|
@@ -36,21 +38,33 @@ def _token():
|
|
| 36 |
return os.environ.get('HF_TOKEN') or None
|
| 37 |
|
| 38 |
|
| 39 |
-
def
|
| 40 |
-
"""{CODE: {'ext': '.png'}} for the configured asset repo, or {} when unreachable."""
|
| 41 |
now = time.time()
|
| 42 |
if _MANIFEST['codes'] is not None and now - _MANIFEST['at'] < _MANIFEST_TTL:
|
| 43 |
-
return
|
| 44 |
try:
|
| 45 |
import json
|
| 46 |
|
| 47 |
from huggingface_hub import hf_hub_download
|
| 48 |
p = hf_hub_download(repo_id(), 'manifest.json', repo_type='dataset', token=_token())
|
| 49 |
-
|
|
|
|
|
|
|
| 50 |
except Exception:
|
| 51 |
-
codes = {}
|
| 52 |
-
_MANIFEST.update(at=now, codes=codes)
|
| 53 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 54 |
|
| 55 |
|
| 56 |
def fetch(code, quality='web'):
|
|
@@ -68,6 +82,52 @@ def fetch(code, quality='web'):
|
|
| 68 |
return None
|
| 69 |
|
| 70 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 71 |
def reset_cache():
|
| 72 |
"""Drop the memoized manifest — for gates and for a post-ingest refresh."""
|
| 73 |
-
_MANIFEST.update(at=0.0, codes=None)
|
|
|
|
| 24 |
|
| 25 |
DEFAULT_REPO = 'royal-imports/product-assets'
|
| 26 |
_MANIFEST_TTL = 300
|
| 27 |
+
#: (fetched_at, {"CODE": {...}}, {"slug": {...}}) — one manifest read per process per TTL.
|
| 28 |
+
#: DEBT-5 (2026-08-04): the same manifest.json now carries a second, NON-SKU half under
|
| 29 |
+
#: "editorial" — full-bleed lifestyle imagery for catalog gallery pages, keyed by slug.
|
| 30 |
+
_MANIFEST = {'at': 0.0, 'codes': None, 'editorial': None}
|
| 31 |
|
| 32 |
|
| 33 |
def repo_id():
|
|
|
|
| 38 |
return os.environ.get('HF_TOKEN') or None
|
| 39 |
|
| 40 |
|
| 41 |
+
def _load():
|
|
|
|
| 42 |
now = time.time()
|
| 43 |
if _MANIFEST['codes'] is not None and now - _MANIFEST['at'] < _MANIFEST_TTL:
|
| 44 |
+
return
|
| 45 |
try:
|
| 46 |
import json
|
| 47 |
|
| 48 |
from huggingface_hub import hf_hub_download
|
| 49 |
p = hf_hub_download(repo_id(), 'manifest.json', repo_type='dataset', token=_token())
|
| 50 |
+
man = json.loads(Path(p).read_text(encoding='utf-8')) or {}
|
| 51 |
+
codes = man.get('codes') or {}
|
| 52 |
+
editorial_ = man.get('editorial') or {}
|
| 53 |
except Exception:
|
| 54 |
+
codes, editorial_ = {}, {}
|
| 55 |
+
_MANIFEST.update(at=now, codes=codes, editorial=editorial_)
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def manifest():
|
| 59 |
+
"""{CODE: {'ext': '.png'}} for the configured asset repo, or {} when unreachable."""
|
| 60 |
+
_load()
|
| 61 |
+
return _MANIFEST['codes']
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def editorial():
|
| 65 |
+
"""{slug: {'ext': ...}} — the editorial (non-SKU) half of the manifest; {} when unreachable."""
|
| 66 |
+
_load()
|
| 67 |
+
return _MANIFEST['editorial'] or {}
|
| 68 |
|
| 69 |
|
| 70 |
def fetch(code, quality='web'):
|
|
|
|
| 82 |
return None
|
| 83 |
|
| 84 |
|
| 85 |
+
def fetch_editorial(slug, quality='web'):
|
| 86 |
+
"""A local Path to one EDITORIAL asset, or None — same shape as fetch()."""
|
| 87 |
+
meta = editorial().get(slug)
|
| 88 |
+
if not meta:
|
| 89 |
+
return None
|
| 90 |
+
rel = (f'assets/editorial/web/{slug}.png' if quality == 'web'
|
| 91 |
+
else f"assets/editorial/orig/{slug}{meta.get('ext', '.png')}")
|
| 92 |
+
try:
|
| 93 |
+
from huggingface_hub import hf_hub_download
|
| 94 |
+
return Path(hf_hub_download(repo_id(), rel, repo_type='dataset', token=_token()))
|
| 95 |
+
except Exception:
|
| 96 |
+
return None
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def put_editorial(slug, orig_bytes, ext, web_png):
|
| 100 |
+
"""Store one editorial image: the original, its web derivative and the updated manifest in
|
| 101 |
+
ONE commit (a partial upload can never leave a listed-but-unfetchable slug). Raises on
|
| 102 |
+
failure — the route turns that into an honest 503, never a silent success.
|
| 103 |
+
|
| 104 |
+
⚠ manifest.json is read-modify-write with no lock; two admins uploading in the same
|
| 105 |
+
second could drop one entry. Accepted for an admin-rare action; the fix (a server-side
|
| 106 |
+
merge) rides the day uploads become routine."""
|
| 107 |
+
import json
|
| 108 |
+
|
| 109 |
+
from huggingface_hub import CommitOperationAdd, HfApi, hf_hub_download
|
| 110 |
+
api = HfApi(token=_token())
|
| 111 |
+
try:
|
| 112 |
+
p = hf_hub_download(repo_id(), 'manifest.json', repo_type='dataset', token=_token(),
|
| 113 |
+
force_download=True)
|
| 114 |
+
man = json.loads(Path(p).read_text(encoding='utf-8')) or {}
|
| 115 |
+
except Exception:
|
| 116 |
+
man = {}
|
| 117 |
+
man.setdefault('editorial', {})[slug] = {'ext': ext}
|
| 118 |
+
api.create_commit(
|
| 119 |
+
repo_id(), repo_type='dataset',
|
| 120 |
+
operations=[
|
| 121 |
+
CommitOperationAdd(f'assets/editorial/orig/{slug}{ext}', orig_bytes),
|
| 122 |
+
CommitOperationAdd(f'assets/editorial/web/{slug}.png', web_png),
|
| 123 |
+
CommitOperationAdd('manifest.json',
|
| 124 |
+
json.dumps(man, indent=1, sort_keys=True).encode('utf-8')),
|
| 125 |
+
],
|
| 126 |
+
commit_message=f'editorial asset: {slug}')
|
| 127 |
+
reset_cache()
|
| 128 |
+
return True
|
| 129 |
+
|
| 130 |
+
|
| 131 |
def reset_cache():
|
| 132 |
"""Drop the memoized manifest — for gates and for a post-ingest refresh."""
|
| 133 |
+
_MANIFEST.update(at=0.0, codes=None, editorial=None)
|
web/dist-embed/index.html
CHANGED
|
The diff for this file is too large to render.
See raw diff
|
|
|
web/src/customer-grid/CatalogView.tsx
CHANGED
|
@@ -54,19 +54,24 @@ import type {
|
|
| 54 |
import {
|
| 55 |
CATALOG_CODE_FIELD,
|
| 56 |
DEFAULT_BRAND,
|
|
|
|
| 57 |
PAGE_KIND_LABELS,
|
| 58 |
PAPER_LABELS,
|
| 59 |
addCodes,
|
| 60 |
assetUrl,
|
| 61 |
autoBind,
|
| 62 |
codesUsed,
|
|
|
|
| 63 |
fetchAssetCodes,
|
|
|
|
| 64 |
indexByCode,
|
| 65 |
newCatalog,
|
| 66 |
newPage,
|
| 67 |
pageBox,
|
| 68 |
resolveItems,
|
| 69 |
sectionLayout,
|
|
|
|
|
|
|
| 70 |
} from "./catalogData";
|
| 71 |
import type { CatalogItem } from "./catalogData";
|
| 72 |
import { applyPrintCss, awaitImages, printOnce } from "./catalogPrint";
|
|
@@ -169,7 +174,11 @@ function Shot({
|
|
| 169 |
if (missing)
|
| 170 |
return (
|
| 171 |
<div className="cg-cat-shot cg-cat-shot-empty">
|
| 172 |
-
<span>
|
|
|
|
|
|
|
|
|
|
|
|
|
| 173 |
</div>
|
| 174 |
);
|
| 175 |
return (
|
|
@@ -447,6 +456,8 @@ export const CatalogView = memo(function CatalogView({
|
|
| 447 |
const [search, setSearch] = useState("");
|
| 448 |
const [picked, setPicked] = useState<Set<string>>(() => new Set());
|
| 449 |
const [assetCodes, setAssetCodes] = useState<Set<string> | null>(null);
|
|
|
|
|
|
|
| 450 |
const [printing, setPrinting] = useState<{ cat: CatalogSpec; quality: CatalogQuality } | null>(
|
| 451 |
null
|
| 452 |
);
|
|
@@ -465,14 +476,24 @@ export const CatalogView = memo(function CatalogView({
|
|
| 465 |
void fetchAssetCodes().then((codes) => {
|
| 466 |
if (live) setAssetCodes(codes);
|
| 467 |
});
|
|
|
|
|
|
|
|
|
|
| 468 |
return () => {
|
| 469 |
live = false;
|
| 470 |
};
|
| 471 |
}, []);
|
| 472 |
|
| 473 |
const hasAsset = useCallback(
|
| 474 |
-
(code: string): boolean | null =>
|
| 475 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 476 |
);
|
| 477 |
|
| 478 |
useLayoutEffect(() => {
|
|
@@ -584,6 +605,25 @@ export const CatalogView = memo(function CatalogView({
|
|
| 584 |
};
|
| 585 |
const [note, setNote] = useState("");
|
| 586 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 587 |
// ------------------------------------------------------------- printing
|
| 588 |
useEffect(() => {
|
| 589 |
if (!printing) return;
|
|
@@ -830,25 +870,70 @@ export const CatalogView = memo(function CatalogView({
|
|
| 830 |
) : null}
|
| 831 |
|
| 832 |
{page.kind !== "intro" ? (
|
| 833 |
-
<
|
| 834 |
-
<
|
| 835 |
-
|
| 836 |
-
|
| 837 |
-
|
| 838 |
-
|
| 839 |
-
|
| 840 |
-
|
| 841 |
-
|
| 842 |
-
|
| 843 |
-
|
| 844 |
-
|
| 845 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 846 |
<em className="cg-cat-hint">
|
| 847 |
-
|
| 848 |
-
|
| 849 |
</em>
|
| 850 |
-
|
| 851 |
-
</
|
| 852 |
) : null}
|
| 853 |
|
| 854 |
{page.kind === "section" ? (
|
|
|
|
| 54 |
import {
|
| 55 |
CATALOG_CODE_FIELD,
|
| 56 |
DEFAULT_BRAND,
|
| 57 |
+
EDITORIAL_PREFIX,
|
| 58 |
PAGE_KIND_LABELS,
|
| 59 |
PAPER_LABELS,
|
| 60 |
addCodes,
|
| 61 |
assetUrl,
|
| 62 |
autoBind,
|
| 63 |
codesUsed,
|
| 64 |
+
editorialSlug,
|
| 65 |
fetchAssetCodes,
|
| 66 |
+
fetchEditorialSlugs,
|
| 67 |
indexByCode,
|
| 68 |
newCatalog,
|
| 69 |
newPage,
|
| 70 |
pageBox,
|
| 71 |
resolveItems,
|
| 72 |
sectionLayout,
|
| 73 |
+
slugFromFilename,
|
| 74 |
+
uploadEditorial,
|
| 75 |
} from "./catalogData";
|
| 76 |
import type { CatalogItem } from "./catalogData";
|
| 77 |
import { applyPrintCss, awaitImages, printOnce } from "./catalogPrint";
|
|
|
|
| 174 |
if (missing)
|
| 175 |
return (
|
| 176 |
<div className="cg-cat-shot cg-cat-shot-empty">
|
| 177 |
+
<span>
|
| 178 |
+
{editorialSlug(code) !== null
|
| 179 |
+
? `No editorial image named ${editorialSlug(code)}`
|
| 180 |
+
: `No master for ${code}`}
|
| 181 |
+
</span>
|
| 182 |
</div>
|
| 183 |
);
|
| 184 |
return (
|
|
|
|
| 456 |
const [search, setSearch] = useState("");
|
| 457 |
const [picked, setPicked] = useState<Set<string>>(() => new Set());
|
| 458 |
const [assetCodes, setAssetCodes] = useState<Set<string> | null>(null);
|
| 459 |
+
const [editorialSlugs, setEditorialSlugs] = useState<Set<string> | null>(null);
|
| 460 |
+
const edFileRef = useRef<HTMLInputElement | null>(null);
|
| 461 |
const [printing, setPrinting] = useState<{ cat: CatalogSpec; quality: CatalogQuality } | null>(
|
| 462 |
null
|
| 463 |
);
|
|
|
|
| 476 |
void fetchAssetCodes().then((codes) => {
|
| 477 |
if (live) setAssetCodes(codes);
|
| 478 |
});
|
| 479 |
+
void fetchEditorialSlugs().then((slugs) => {
|
| 480 |
+
if (live) setEditorialSlugs(slugs);
|
| 481 |
+
});
|
| 482 |
return () => {
|
| 483 |
live = false;
|
| 484 |
};
|
| 485 |
}, []);
|
| 486 |
|
| 487 |
const hasAsset = useCallback(
|
| 488 |
+
(code: string): boolean | null => {
|
| 489 |
+
// `ed:` codes resolve against the EDITORIAL library (DEBT-5); everything
|
| 490 |
+
// else stays a product code. Unknown-library (null) keeps the designer
|
| 491 |
+
// quiet, same as the product manifest's own rule.
|
| 492 |
+
const slug = editorialSlug(code);
|
| 493 |
+
if (slug !== null) return editorialSlugs ? editorialSlugs.has(slug) : null;
|
| 494 |
+
return assetCodes ? assetCodes.has(code) : null;
|
| 495 |
+
},
|
| 496 |
+
[assetCodes, editorialSlugs]
|
| 497 |
);
|
| 498 |
|
| 499 |
useLayoutEffect(() => {
|
|
|
|
| 605 |
};
|
| 606 |
const [note, setNote] = useState("");
|
| 607 |
|
| 608 |
+
// DEBT-5: one editorial master in, `ed:<slug>` bound to the open page. The server
|
| 609 |
+
// owns validation (admin wall, charset, opens-as-an-image); this just reports honestly.
|
| 610 |
+
const uploadEditorialFile = async (f: File) => {
|
| 611 |
+
const slug = slugFromFilename(f.name);
|
| 612 |
+
if (!slug) {
|
| 613 |
+
setNote("That filename does not reduce to a usable name — rename the file first.");
|
| 614 |
+
return;
|
| 615 |
+
}
|
| 616 |
+
setNote(`Uploading ${slug}…`);
|
| 617 |
+
try {
|
| 618 |
+
const stored = await uploadEditorial(slug, f);
|
| 619 |
+
setEditorialSlugs(await fetchEditorialSlugs());
|
| 620 |
+
if (cat && page) patchPage(cat.id, page.id, { imageCode: `${EDITORIAL_PREFIX}${stored}` });
|
| 621 |
+
setNote(`Editorial image "${stored}" stored and bound to this page.`);
|
| 622 |
+
} catch (e) {
|
| 623 |
+
setNote(e instanceof Error ? e.message : "The upload failed.");
|
| 624 |
+
}
|
| 625 |
+
};
|
| 626 |
+
|
| 627 |
// ------------------------------------------------------------- printing
|
| 628 |
useEffect(() => {
|
| 629 |
if (!printing) return;
|
|
|
|
| 870 |
) : null}
|
| 871 |
|
| 872 |
{page.kind !== "intro" ? (
|
| 873 |
+
<>
|
| 874 |
+
<label className="cg-cat-fld">
|
| 875 |
+
<span>{page.kind === "section" ? "Footer image (code)" : "Image (code)"}</span>
|
| 876 |
+
<input
|
| 877 |
+
className="cg-input"
|
| 878 |
+
value={page.imageCode ?? ""}
|
| 879 |
+
placeholder="e.g. CRY-2003 or ed:showroom"
|
| 880 |
+
onChange={(e) => patchPage(cat.id, page.id, { imageCode: e.target.value })}
|
| 881 |
+
/>
|
| 882 |
+
{page.imageCode && hasAsset(page.imageCode) === false ? (
|
| 883 |
+
<em className="cg-cat-warn">
|
| 884 |
+
{editorialSlug(page.imageCode) !== null
|
| 885 |
+
? "No editorial image is stored under this name — the page will print an empty frame."
|
| 886 |
+
: "No image is archived under this code — the page will print an empty frame."}
|
| 887 |
+
</em>
|
| 888 |
+
) : (
|
| 889 |
+
<em className="cg-cat-hint">
|
| 890 |
+
Fills the width edge to edge, so a wide photograph reads best here. A cut-out
|
| 891 |
+
product render will be cropped and enlarged to fill it.
|
| 892 |
+
</em>
|
| 893 |
+
)}
|
| 894 |
+
</label>
|
| 895 |
+
<label className="cg-cat-fld">
|
| 896 |
+
<span>Editorial library</span>
|
| 897 |
+
<select
|
| 898 |
+
className="cg-select"
|
| 899 |
+
value={editorialSlug(page.imageCode ?? "") ?? ""}
|
| 900 |
+
onChange={(e) =>
|
| 901 |
+
patchPage(cat.id, page.id, {
|
| 902 |
+
imageCode: e.target.value ? `${EDITORIAL_PREFIX}${e.target.value}` : "",
|
| 903 |
+
})
|
| 904 |
+
}
|
| 905 |
+
>
|
| 906 |
+
<option value="">(use a product code above)</option>
|
| 907 |
+
{[...(editorialSlugs ?? [])].sort().map((s) => (
|
| 908 |
+
<option key={s} value={s}>
|
| 909 |
+
{s}
|
| 910 |
+
</option>
|
| 911 |
+
))}
|
| 912 |
+
</select>
|
| 913 |
+
<button
|
| 914 |
+
type="button"
|
| 915 |
+
className="cg-btn"
|
| 916 |
+
onClick={() => edFileRef.current?.click()}
|
| 917 |
+
>
|
| 918 |
+
Upload a photograph…
|
| 919 |
+
</button>
|
| 920 |
+
<input
|
| 921 |
+
ref={edFileRef}
|
| 922 |
+
type="file"
|
| 923 |
+
accept="image/png,image/jpeg"
|
| 924 |
+
style={{ display: "none" }}
|
| 925 |
+
onChange={(e) => {
|
| 926 |
+
const f = e.target.files?.[0];
|
| 927 |
+
if (f) void uploadEditorialFile(f);
|
| 928 |
+
e.target.value = "";
|
| 929 |
+
}}
|
| 930 |
+
/>
|
| 931 |
<em className="cg-cat-hint">
|
| 932 |
+
Lifestyle photography without a SKU lives here. Storing a new one needs an
|
| 933 |
+
admin login; everyone can pick from the library.
|
| 934 |
</em>
|
| 935 |
+
</label>
|
| 936 |
+
</>
|
| 937 |
) : null}
|
| 938 |
|
| 939 |
{page.kind === "section" ? (
|
web/src/customer-grid/catalogData.ts
CHANGED
|
@@ -144,13 +144,31 @@ export function autoBind(fields: Field[]): NonNullable<CatalogSpec["fields"]> {
|
|
| 144 |
* master bytes. The response is `immutable`-cached, so swapping quality for an
|
| 145 |
* export costs one fetch per image and nothing after that.
|
| 146 |
*/
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 147 |
export function assetUrl(code: string, quality: CatalogQuality): string {
|
| 148 |
-
|
|
|
|
|
|
|
|
|
|
| 149 |
}
|
| 150 |
|
| 151 |
/** C2-ASSET's manifest — which codes HAVE an image, so the designer can mark
|
| 152 |
* the ones that will print an empty frame instead of discovering it at print. */
|
| 153 |
export const ASSET_MANIFEST_URL = `${API_V1}/assets/products`;
|
|
|
|
| 154 |
|
| 155 |
export async function fetchAssetCodes(): Promise<Set<string> | null> {
|
| 156 |
try {
|
|
@@ -168,6 +186,55 @@ export async function fetchAssetCodes(): Promise<Set<string> | null> {
|
|
| 168 |
}
|
| 169 |
}
|
| 170 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 171 |
// -------------------------------------------------------------- the paper
|
| 172 |
|
| 173 |
/**
|
|
|
|
| 144 |
* master bytes. The response is `immutable`-cached, so swapping quality for an
|
| 145 |
* export costs one fetch per image and nothing after that.
|
| 146 |
*/
|
| 147 |
+
/**
|
| 148 |
+
* DEBT-5 (2026-08-04): EDITORIAL imagery — non-SKU, full-bleed lifestyle photos
|
| 149 |
+
* for gallery pages. Addressed as `ed:<slug>` wherever a page stores an image
|
| 150 |
+
* code: the colon is outside the product-code charset, so the two namespaces
|
| 151 |
+
* cannot collide, and every existing catalog keeps meaning what it meant.
|
| 152 |
+
*/
|
| 153 |
+
export const EDITORIAL_PREFIX = "ed:";
|
| 154 |
+
|
| 155 |
+
export function editorialSlug(code: string): string | null {
|
| 156 |
+
return code.startsWith(EDITORIAL_PREFIX)
|
| 157 |
+
? code.slice(EDITORIAL_PREFIX.length).trim().toLowerCase()
|
| 158 |
+
: null;
|
| 159 |
+
}
|
| 160 |
+
|
| 161 |
export function assetUrl(code: string, quality: CatalogQuality): string {
|
| 162 |
+
const slug = editorialSlug(code);
|
| 163 |
+
return slug !== null
|
| 164 |
+
? `${API_V1}/assets/editorial/${encodeURIComponent(slug)}?q=${quality}`
|
| 165 |
+
: `${API_V1}/assets/products/${encodeURIComponent(code)}?q=${quality}`;
|
| 166 |
}
|
| 167 |
|
| 168 |
/** C2-ASSET's manifest — which codes HAVE an image, so the designer can mark
|
| 169 |
* the ones that will print an empty frame instead of discovering it at print. */
|
| 170 |
export const ASSET_MANIFEST_URL = `${API_V1}/assets/products`;
|
| 171 |
+
export const EDITORIAL_MANIFEST_URL = `${API_V1}/assets/editorial`;
|
| 172 |
|
| 173 |
export async function fetchAssetCodes(): Promise<Set<string> | null> {
|
| 174 |
try {
|
|
|
|
| 186 |
}
|
| 187 |
}
|
| 188 |
|
| 189 |
+
/** The editorial library, same null-means-unknown semantics as fetchAssetCodes. */
|
| 190 |
+
export async function fetchEditorialSlugs(): Promise<Set<string> | null> {
|
| 191 |
+
try {
|
| 192 |
+
const res = await fetch(EDITORIAL_MANIFEST_URL, { credentials: "same-origin" });
|
| 193 |
+
if (!res.ok) return null;
|
| 194 |
+
const body = (await res.json()) as { slugs?: unknown };
|
| 195 |
+
if (!Array.isArray(body.slugs)) return null;
|
| 196 |
+
return new Set(
|
| 197 |
+
body.slugs.filter((s): s is string => typeof s === "string").map((s) => s.toLowerCase())
|
| 198 |
+
);
|
| 199 |
+
} catch {
|
| 200 |
+
return null;
|
| 201 |
+
}
|
| 202 |
+
}
|
| 203 |
+
|
| 204 |
+
/** Upload one editorial master (admin route). Resolves to the stored slug, or
|
| 205 |
+
* throws with the server's honest error message. */
|
| 206 |
+
export async function uploadEditorial(slug: string, file: Blob): Promise<string> {
|
| 207 |
+
const data = await new Promise<string>((resolve, reject) => {
|
| 208 |
+
const r = new FileReader();
|
| 209 |
+
r.onload = () => resolve(String(r.result ?? ""));
|
| 210 |
+
r.onerror = () => reject(new Error("could not read the file"));
|
| 211 |
+
r.readAsDataURL(file);
|
| 212 |
+
});
|
| 213 |
+
const res = await fetch(EDITORIAL_MANIFEST_URL, {
|
| 214 |
+
method: "POST",
|
| 215 |
+
credentials: "same-origin",
|
| 216 |
+
headers: { "Content-Type": "application/json" },
|
| 217 |
+
body: JSON.stringify({ slug, data }),
|
| 218 |
+
});
|
| 219 |
+
const body = (await res.json().catch(() => ({}))) as {
|
| 220 |
+
slug?: string;
|
| 221 |
+
error?: { message?: string };
|
| 222 |
+
};
|
| 223 |
+
if (!res.ok) throw new Error(body.error?.message ?? `upload failed (${res.status})`);
|
| 224 |
+
return body.slug ?? slug;
|
| 225 |
+
}
|
| 226 |
+
|
| 227 |
+
/** A slug guessed from a filename: lowercased, non-alphanumerics folded to
|
| 228 |
+
* hyphens, trimmed — mirrors the server's charset so the guess is accepted. */
|
| 229 |
+
export function slugFromFilename(name: string): string {
|
| 230 |
+
return name
|
| 231 |
+
.replace(/\.[A-Za-z0-9]+$/, "")
|
| 232 |
+
.toLowerCase()
|
| 233 |
+
.replace(/[^a-z0-9]+/g, "-")
|
| 234 |
+
.replace(/^-+|-+$/g, "")
|
| 235 |
+
.slice(0, 64);
|
| 236 |
+
}
|
| 237 |
+
|
| 238 |
// -------------------------------------------------------------- the paper
|
| 239 |
|
| 240 |
/**
|