chore(cafe24): 정리 전 완료된 작업 보존
Cafe24 수정, 테스트 및 DB 마이그레이션 파일을 함께 기록한다.
This commit is contained in:
@@ -45,6 +45,7 @@ from .errors import (
|
||||
Cafe24AuthError,
|
||||
Cafe24ConfigError,
|
||||
Cafe24Error,
|
||||
Cafe24FtpConflict,
|
||||
Cafe24FtpError,
|
||||
Cafe24RateLimitError,
|
||||
)
|
||||
@@ -80,6 +81,7 @@ __all__ = [
|
||||
"Cafe24RateLimitError",
|
||||
"Cafe24ApiError",
|
||||
"Cafe24FtpError",
|
||||
"Cafe24FtpConflict",
|
||||
]
|
||||
|
||||
|
||||
|
||||
@@ -164,6 +164,10 @@ class Cafe24Client:
|
||||
method = method.upper()
|
||||
forced_refresh = False
|
||||
last_error: Exception | None = None
|
||||
# 쓰기 요청이 카페24에 도달했을 수도 있는 시도가 있었나(5xx 응답·응답 전 끊김).
|
||||
# 최종 오류에 실어 호출부가 "반영 여부 모름"을 구분하게 한다(errors.Cafe24ApiError).
|
||||
writes = method in ("PUT", "POST", "DELETE", "PATCH")
|
||||
maybe_applied = False
|
||||
|
||||
for attempt in range(self._max_retries + 1):
|
||||
self._pace()
|
||||
@@ -224,7 +228,9 @@ class Cafe24Client:
|
||||
time.sleep(wait)
|
||||
continue
|
||||
|
||||
error = Cafe24ApiError(message, status=status, endpoint=endpoint)
|
||||
if writes and status >= 500:
|
||||
maybe_applied = True
|
||||
error = Cafe24ApiError(message, status=status, endpoint=endpoint, maybe_applied=maybe_applied)
|
||||
if error.retryable and attempt < self._max_retries:
|
||||
last_error = error
|
||||
time.sleep(min(8.0, 0.5 * (2**attempt)))
|
||||
@@ -241,7 +247,11 @@ class Cafe24Client:
|
||||
http_status=status, result="ERROR", error_message=message,
|
||||
duration_ms=elapsed,
|
||||
)
|
||||
last_error = Cafe24ApiError(message, status=0, endpoint=endpoint)
|
||||
# 연결조차 안 된 경우만 "도달하지 않음"이 확실하다. 그 밖(읽기 타임아웃,
|
||||
# 응답 도중 끊김)은 카페24가 요청을 처리했을 수 있다.
|
||||
if writes and not isinstance(exc, (httpx.ConnectError, httpx.ConnectTimeout)):
|
||||
maybe_applied = True
|
||||
last_error = Cafe24ApiError(message, status=0, endpoint=endpoint, maybe_applied=maybe_applied)
|
||||
if attempt < self._max_retries:
|
||||
time.sleep(min(8.0, 0.5 * (2**attempt)))
|
||||
continue
|
||||
|
||||
@@ -7,15 +7,28 @@ Admin API(OAuth)로는 스킨 파일을 다루지 못한다(`config.py` 상단
|
||||
|
||||
실물 확인(스크린샷): 호스트 `{mall_id}.ftp.cafe24.com`, 포트 21, SSL/TLS 미사용
|
||||
(평문 FTP). 파일은 텍스트(UTF-8)로 다룬다.
|
||||
|
||||
쓰기는 원본에 직접 STOR 하지 않는다 (write_text_file)
|
||||
직접 STOR 는 전송 도중 끊기면 원본이 **앞부분만 남은 채** 잘린다(스킨 템플릿이면
|
||||
모든 상품 페이지가 깨진다). 그래서
|
||||
1) 같은 폴더의 임시 파일에 올리고 (원본은 아직 그대로)
|
||||
2) 다시 받아 바이트 단위로 검증하고
|
||||
3) 교체 직전 원본을 다시 읽어 편집 시작 값과 같은지 확인하고(충돌 방지)
|
||||
4) RNFR/RNTO 로 이름을 바꿔 교체한다
|
||||
서버가 "이미 있는 이름으로 바꾸기"를 거부하면 원본을 옆 이름으로 비킨 뒤 교체하고,
|
||||
실패하면 원본을 제자리로 되돌린다. 이름 바꾸기 자체를 지원하지 않으면 **중단**한다
|
||||
(직접 STOR 로 물러서지 않는다).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import ftplib
|
||||
import io
|
||||
import posixpath
|
||||
import uuid
|
||||
|
||||
from .config import Cafe24FtpConfig
|
||||
from .errors import Cafe24FtpError
|
||||
from .errors import Cafe24FtpConflict, Cafe24FtpError
|
||||
|
||||
# 응답이 없을 때 무한 대기하지 않도록 — 관리 화면 요청 안에서 동기 호출되므로
|
||||
# 너무 길면 안 되지만, 파일 하나(수십 KB) 전송에는 충분히 넉넉해야 한다.
|
||||
@@ -35,37 +48,135 @@ def _connect(config: Cafe24FtpConfig) -> ftplib.FTP:
|
||||
raise Cafe24FtpError(f"FTP 연결/로그인에 실패했습니다: {exc}") from exc
|
||||
|
||||
|
||||
def _close(ftp: ftplib.FTP) -> None:
|
||||
try:
|
||||
ftp.quit()
|
||||
except Exception: # noqa: BLE001 — 정리 실패는 무시
|
||||
ftp.close()
|
||||
|
||||
|
||||
def _retr(ftp: ftplib.FTP, path: str) -> bytes:
|
||||
buf = io.BytesIO()
|
||||
ftp.retrbinary(f"RETR {path}", buf.write)
|
||||
return buf.getvalue()
|
||||
|
||||
|
||||
def _delete_quiet(ftp: ftplib.FTP, path: str) -> None:
|
||||
try:
|
||||
ftp.delete(path)
|
||||
except ftplib.all_errors:
|
||||
pass # 임시 파일 정리 실패는 무시(이름에 cf24tmp 가 붙어 있어 구분된다)
|
||||
|
||||
|
||||
def read_text_file(config: Cafe24FtpConfig, path: str) -> str:
|
||||
"""디자인 보관함의 파일 1개를 읽어 텍스트로 돌려준다."""
|
||||
ftp = _connect(config)
|
||||
try:
|
||||
buf = io.BytesIO()
|
||||
try:
|
||||
ftp.retrbinary(f"RETR {path}", buf.write)
|
||||
raw = _retr(ftp, path)
|
||||
except ftplib.all_errors as exc:
|
||||
raise Cafe24FtpError(f"파일을 읽지 못했습니다({path}): {exc}") from exc
|
||||
try:
|
||||
return buf.getvalue().decode("utf-8")
|
||||
return raw.decode("utf-8")
|
||||
except UnicodeDecodeError as exc:
|
||||
raise Cafe24FtpError(f"파일 인코딩을 UTF-8로 해석하지 못했습니다({path}): {exc}") from exc
|
||||
finally:
|
||||
try:
|
||||
ftp.quit()
|
||||
except Exception: # noqa: BLE001 — 정리 실패는 무시
|
||||
ftp.close()
|
||||
_close(ftp)
|
||||
|
||||
|
||||
def write_text_file(config: Cafe24FtpConfig, path: str, content: str) -> None:
|
||||
"""디자인 보관함의 파일 1개를 통째로 덮어쓴다."""
|
||||
def temp_names(path: str, tag: str) -> tuple[str, str]:
|
||||
"""(임시 업로드 이름, 원본을 잠시 비킬 이름) — 같은 폴더, 원본 이름 + 표식."""
|
||||
folder, name = posixpath.split(path)
|
||||
return (posixpath.join(folder, f"{name}.cf24tmp-{tag}"),
|
||||
posixpath.join(folder, f"{name}.cf24old-{tag}"))
|
||||
|
||||
|
||||
def write_text_file(
|
||||
config: Cafe24FtpConfig, path: str, content: str, *, expected_current: str | None = None
|
||||
) -> None:
|
||||
"""디자인 보관함의 파일 1개를 안전하게 교체한다(모듈 설명 참고).
|
||||
|
||||
expected_current: 편집 시작(또는 백업) 때 읽은 원본. 주면 교체 직전 원본을 다시
|
||||
읽어 다르면 Cafe24FtpConflict 로 멈춘다(원본 그대로).
|
||||
실패 시 Cafe24FtpError — maybe_applied=True 면 원본이 이미 바뀌었을 수 있다.
|
||||
"""
|
||||
data = content.encode("utf-8")
|
||||
tmp, aside = temp_names(path, uuid.uuid4().hex[:10])
|
||||
ftp = _connect(config)
|
||||
try:
|
||||
buf = io.BytesIO(content.encode("utf-8"))
|
||||
# 1) 임시 파일에 올린다 — 원본은 아직 그대로다.
|
||||
try:
|
||||
ftp.storbinary(f"STOR {path}", buf)
|
||||
ftp.storbinary(f"STOR {tmp}", io.BytesIO(data))
|
||||
except ftplib.all_errors as exc:
|
||||
raise Cafe24FtpError(f"파일을 쓰지 못했습니다({path}): {exc}") from exc
|
||||
finally:
|
||||
_delete_quiet(ftp, tmp)
|
||||
raise Cafe24FtpError(f"임시 파일을 올리지 못했습니다 — 원본은 그대로입니다({path}): {exc}") from exc
|
||||
|
||||
# 2) 검증 — 다시 받아 바이트 단위로 비교한다(전송이 잘렸으면 여기서 잡힌다).
|
||||
try:
|
||||
ftp.quit()
|
||||
except Exception: # noqa: BLE001 — 정리 실패는 무시
|
||||
ftp.close()
|
||||
uploaded = _retr(ftp, tmp)
|
||||
except ftplib.all_errors as exc:
|
||||
_delete_quiet(ftp, tmp)
|
||||
raise Cafe24FtpError(f"올린 임시 파일을 확인하지 못했습니다 — 원본은 그대로입니다: {exc}") from exc
|
||||
if uploaded != data:
|
||||
_delete_quiet(ftp, tmp)
|
||||
raise Cafe24FtpError(
|
||||
f"올린 임시 파일이 보낸 내용과 다릅니다({len(uploaded)}/{len(data)}바이트) — 원본은 그대로입니다."
|
||||
)
|
||||
|
||||
# 3) 충돌 확인 — 교체 직전의 원본이 편집 시작 값 그대로인가.
|
||||
if expected_current is not None:
|
||||
try:
|
||||
now = _retr(ftp, path)
|
||||
except ftplib.all_errors as exc:
|
||||
_delete_quiet(ftp, tmp)
|
||||
raise Cafe24FtpError(f"교체 직전 원본을 다시 읽지 못했습니다 — 원본은 그대로입니다: {exc}") from exc
|
||||
if now != expected_current.encode("utf-8"):
|
||||
_delete_quiet(ftp, tmp)
|
||||
raise Cafe24FtpConflict(
|
||||
"적용하는 사이 FTP 파일이 바뀌었습니다 — 원본은 그대로입니다. 새로고침해 확인한 뒤 다시 적용하세요."
|
||||
)
|
||||
|
||||
# 4) 교체 — 이름 바꾸기. 덮어쓰기를 거부하는 서버면 원본을 비킨 뒤 교체한다.
|
||||
moved_aside = False
|
||||
try:
|
||||
ftp.rename(tmp, path)
|
||||
except ftplib.all_errors as first:
|
||||
try:
|
||||
ftp.rename(path, aside)
|
||||
except ftplib.all_errors as exc:
|
||||
_delete_quiet(ftp, tmp)
|
||||
raise Cafe24FtpError(
|
||||
"이 FTP 서버가 파일 이름 바꾸기(rename)를 지원하지 않아 중단했습니다 — 원본은 그대로입니다. "
|
||||
f"({first} / {exc})"
|
||||
) from exc
|
||||
try:
|
||||
ftp.rename(tmp, path)
|
||||
except ftplib.all_errors as exc:
|
||||
try:
|
||||
ftp.rename(aside, path)
|
||||
except ftplib.all_errors as exc2:
|
||||
raise Cafe24FtpError(
|
||||
f"교체에 실패했고 원본 되돌리기도 실패했습니다. FTP 에서 {aside} 를 {path} 로 "
|
||||
f"직접 되돌리세요: {exc} / {exc2}",
|
||||
maybe_applied=True,
|
||||
) from exc2
|
||||
_delete_quiet(ftp, tmp)
|
||||
raise Cafe24FtpError(f"교체에 실패해 원본을 되돌렸습니다: {exc}") from exc
|
||||
moved_aside = True
|
||||
|
||||
# 5) 확인 — 교체 뒤 원본 경로가 새 내용인가.
|
||||
try:
|
||||
final = _retr(ftp, path)
|
||||
except ftplib.all_errors as exc:
|
||||
raise Cafe24FtpError(
|
||||
f"교체 뒤 확인 조회에 실패했습니다 — 적용됐을 수 있으니 파일을 다시 열어 확인하세요: {exc}",
|
||||
maybe_applied=True,
|
||||
) from exc
|
||||
if final != data:
|
||||
raise Cafe24FtpError(
|
||||
"교체 뒤 파일 내용이 보낸 것과 다릅니다 — 파일을 다시 열어 확인하세요.", maybe_applied=True
|
||||
)
|
||||
if moved_aside:
|
||||
_delete_quiet(ftp, aside)
|
||||
finally:
|
||||
_close(ftp)
|
||||
|
||||
@@ -32,16 +32,35 @@ class Cafe24RateLimitError(Cafe24Error):
|
||||
|
||||
|
||||
class Cafe24FtpError(Cafe24Error):
|
||||
"""디자인 보관함 FTP 연결/전송 실패 (product-swiper.js 편집 등)."""
|
||||
"""디자인 보관함 FTP 연결/전송 실패 (product-swiper.js 편집 등).
|
||||
|
||||
maybe_applied: 원본 경로가 이미 새 내용으로 바뀌었을 수 있다(교체 뒤 확인 단계 실패).
|
||||
False 면 원본은 그대로다(임시 파일 단계에서 멈춤).
|
||||
"""
|
||||
|
||||
def __init__(self, message: str, *, maybe_applied: bool = False):
|
||||
super().__init__(message)
|
||||
self.maybe_applied = maybe_applied
|
||||
|
||||
|
||||
class Cafe24FtpConflict(Cafe24FtpError):
|
||||
"""교체 직전 다시 읽은 원본이 편집 시작 때와 다르다 — 남의 수정을 덮지 않고 멈춘다."""
|
||||
|
||||
|
||||
class Cafe24ApiError(Cafe24Error):
|
||||
"""그 외 API 오류(4xx/5xx). status 로 재시도 가능 여부를 판단한다."""
|
||||
"""그 외 API 오류(4xx/5xx). status 로 재시도 가능 여부를 판단한다.
|
||||
|
||||
def __init__(self, message: str, *, status: int = 0, endpoint: str = ""):
|
||||
maybe_applied: 쓰기 요청(PUT/POST/DELETE)이 카페24에 **도달했을 수도** 있는가.
|
||||
응답을 받기 전에 끊겼거나(읽기 타임아웃 등) 5xx 를 받은 시도가 한 번이라도
|
||||
있으면 True — 반영됐는지 모르므로 호출부는 재적용하지 말고 "확인 필요"로 둔다.
|
||||
연결 자체가 안 된 경우(ConnectError)와 4xx 는 반영되지 않은 것이 확실하다.
|
||||
"""
|
||||
|
||||
def __init__(self, message: str, *, status: int = 0, endpoint: str = "", maybe_applied: bool = False):
|
||||
super().__init__(message)
|
||||
self.status = status
|
||||
self.endpoint = endpoint
|
||||
self.maybe_applied = maybe_applied
|
||||
|
||||
@property
|
||||
def retryable(self) -> bool:
|
||||
|
||||
@@ -22,6 +22,7 @@ from dataclasses import dataclass
|
||||
from typing import Any
|
||||
|
||||
from .client import Cafe24Client
|
||||
from .errors import Cafe24Error
|
||||
|
||||
# 카페24 상품 목록 API 의 1회 최대 조회 수
|
||||
PAGE_LIMIT = 100
|
||||
@@ -476,26 +477,55 @@ def wait_for_variants(
|
||||
return latest
|
||||
|
||||
|
||||
VARIANT_CHUNK = 100 # 카페24 문서상 PUT variants 1회 최대 건수
|
||||
|
||||
# update_variants 행별 결과 상태
|
||||
VARIANT_OK = "ok" # 카페24가 받아들임
|
||||
VARIANT_FAILED = "failed" # 거절 — 반영되지 않음이 확실
|
||||
VARIANT_UNKNOWN = "unknown" # 요청이 도달했을 수 있으나 응답을 못 받음 — 반영 여부 모름
|
||||
|
||||
|
||||
def update_variants(
|
||||
client: Cafe24Client, product_no: int, requests: list[dict[str, Any]]
|
||||
) -> list[dict[str, Any]]:
|
||||
"""여러 품목 부분 수정. 100건씩 나눠 보낸다(문서상 1회 100건 제한)."""
|
||||
"""여러 품목 부분 수정 — **행별 결과**를 돌려준다(요청 순서 그대로).
|
||||
|
||||
[{"variant_code": "...", "status": "ok"|"failed"|"unknown",
|
||||
"error": "", "variant": {카페24 응답의 그 품목 — 없으면 {}}}]
|
||||
|
||||
100건씩 나눠 보낸다(문서상 1회 100건 제한). 한 묶음이 실패해도 멈추지 않고 다음
|
||||
묶음을 보낸다 — 앞 묶음이 이미 반영됐는데 전체를 실패로 알리면 화면과 카페24가
|
||||
어긋나고, 사용자가 반영된 행까지 다시 보내게 된다. 호출부는 ok 인 행만 반영됨으로
|
||||
기록한다.
|
||||
"""
|
||||
no = int(product_no)
|
||||
out: list[dict[str, Any]] = []
|
||||
for start in range(0, len(requests), 100):
|
||||
chunk = requests[start : start + 100]
|
||||
for start in range(0, len(requests), VARIANT_CHUNK):
|
||||
chunk = requests[start : start + VARIANT_CHUNK]
|
||||
if not chunk:
|
||||
continue
|
||||
payload = client.put(
|
||||
f"/admin/products/{no}/variants", json={"shop_no": 1, "requests": chunk}, product_no=no
|
||||
)
|
||||
try:
|
||||
payload = client.put(
|
||||
f"/admin/products/{no}/variants", json={"shop_no": 1, "requests": chunk}, product_no=no
|
||||
)
|
||||
except Cafe24Error as exc:
|
||||
status = VARIANT_UNKNOWN if getattr(exc, "maybe_applied", False) else VARIANT_FAILED
|
||||
for row in chunk:
|
||||
out.append({"variant_code": str(row.get("variant_code") or ""), "status": status,
|
||||
"error": str(exc), "variant": {}})
|
||||
continue
|
||||
result = payload.get("variants") if isinstance(payload, dict) else None
|
||||
returned: list[dict[str, Any]] = []
|
||||
if isinstance(result, list):
|
||||
out.extend(result)
|
||||
returned = [r for r in result if isinstance(r, dict)]
|
||||
elif isinstance(result, dict):
|
||||
out.append(result)
|
||||
elif isinstance(payload.get("variant"), dict):
|
||||
out.append(payload["variant"])
|
||||
returned = [result]
|
||||
elif isinstance(payload, dict) and isinstance(payload.get("variant"), dict):
|
||||
returned = [payload["variant"]]
|
||||
by_code = {str(r.get("variant_code") or ""): r for r in returned}
|
||||
for row in chunk:
|
||||
code = str(row.get("variant_code") or "")
|
||||
out.append({"variant_code": code, "status": VARIANT_OK, "error": "", "variant": by_code.get(code, {})})
|
||||
return out
|
||||
|
||||
|
||||
|
||||
+503
-96
@@ -14,10 +14,12 @@ API 로그에는 토큰/시크릿을 넣지 않는다.
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import uuid
|
||||
from contextlib import contextmanager
|
||||
from datetime import date, datetime
|
||||
from typing import Any, Iterator
|
||||
|
||||
from psycopg import errors as pg_errors
|
||||
from psycopg.rows import dict_row
|
||||
from psycopg_pool import ConnectionPool
|
||||
|
||||
@@ -97,6 +99,315 @@ class Cafe24Store:
|
||||
def close(self) -> None:
|
||||
self._pool.close()
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# 마이그레이션 005(쓰기 안전장치) 적용 여부
|
||||
# 쓰기 경로는 잠금·시도 기록 없이 카페24에 쓰지 않는다 — 적용 전이면 거부한다.
|
||||
# 읽기 경로는 005 가 없어도 동작하게 둔다(배포 순서가 어긋나도 화면은 열린다).
|
||||
# ════════════════════════════════════════════════════════════
|
||||
_schema_ok = False
|
||||
|
||||
def write_schema_ready(self) -> bool:
|
||||
if self._schema_ok:
|
||||
return True
|
||||
with self._pool.connection() as conn:
|
||||
row = conn.execute(
|
||||
"""
|
||||
SELECT to_regclass('public.cafe24_write_locks') IS NOT NULL
|
||||
AND to_regclass('public.cafe24_write_attempts') IS NOT NULL
|
||||
AND EXISTS (SELECT 1 FROM information_schema.columns
|
||||
WHERE table_name = 'cafe24_product_schedules'
|
||||
AND column_name = 'lease_token')
|
||||
AND EXISTS (SELECT 1 FROM information_schema.columns
|
||||
WHERE table_name = 'cafe24_product_revisions'
|
||||
AND column_name = 'source') AS ok
|
||||
"""
|
||||
).fetchone()
|
||||
self._schema_ok = bool(row and row.get("ok"))
|
||||
return self._schema_ok
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# 쓰기 잠금 (lease) — 웹 여러 프로세스 + 예약 worker 가 공유한다.
|
||||
# 같은 lock_key 는 한 번에 하나만 잡는다. 만료(expires_at)가 지나면 다른 쪽이
|
||||
# 가져갈 수 있다(잡은 프로세스가 죽어도 영구히 막히지 않는다). 원격 쓰기 직전
|
||||
# renew_lock 으로 "아직 내 잠금인가"를 확인한다(펜싱) — 아니면 쓰지 않는다.
|
||||
# ════════════════════════════════════════════════════════════
|
||||
def acquire_lock(self, key: str, *, owner: str, purpose: str, ttl_seconds: int) -> str | None:
|
||||
"""잠금을 잡으면 token, 남이 잡고 있으면 None."""
|
||||
token = uuid.uuid4().hex
|
||||
with self._pool.connection() as conn:
|
||||
row = conn.execute(
|
||||
"""
|
||||
INSERT INTO cafe24_write_locks (lock_key, owner, token, purpose, acquired_at, expires_at)
|
||||
VALUES (%s, %s, %s, %s, now(), now() + %s * interval '1 second')
|
||||
ON CONFLICT (lock_key) DO UPDATE SET
|
||||
owner = EXCLUDED.owner, token = EXCLUDED.token, purpose = EXCLUDED.purpose,
|
||||
acquired_at = now(), expires_at = EXCLUDED.expires_at
|
||||
WHERE cafe24_write_locks.expires_at < now()
|
||||
RETURNING token
|
||||
""",
|
||||
(key, (owner or "")[:200], token, (purpose or "")[:200], max(1, int(ttl_seconds))),
|
||||
).fetchone()
|
||||
return str(row["token"]) if row else None
|
||||
|
||||
def renew_lock(self, key: str, token: str, *, ttl_seconds: int) -> bool:
|
||||
"""아직 내 잠금이고 만료 전이면 연장하고 True. 이미 넘어갔으면 False."""
|
||||
with self._pool.connection() as conn:
|
||||
row = conn.execute(
|
||||
"""
|
||||
UPDATE cafe24_write_locks
|
||||
SET expires_at = now() + %s * interval '1 second'
|
||||
WHERE lock_key = %s AND token = %s AND expires_at > now()
|
||||
RETURNING lock_key
|
||||
""",
|
||||
(max(1, int(ttl_seconds)), key, token),
|
||||
).fetchone()
|
||||
return row is not None
|
||||
|
||||
def release_lock(self, key: str, token: str) -> None:
|
||||
with self._pool.connection() as conn:
|
||||
conn.execute(
|
||||
"DELETE FROM cafe24_write_locks WHERE lock_key = %s AND token = %s",
|
||||
(key, token),
|
||||
)
|
||||
|
||||
def lock_holder(self, key: str) -> dict[str, Any]:
|
||||
"""지금 잠금을 잡고 있는 쪽(안내 문구용). 없거나 만료됐으면 {}."""
|
||||
with self._pool.connection() as conn:
|
||||
row = conn.execute(
|
||||
"""
|
||||
SELECT owner, purpose, acquired_at, expires_at FROM cafe24_write_locks
|
||||
WHERE lock_key = %s AND expires_at > now()
|
||||
""",
|
||||
(key,),
|
||||
).fetchone()
|
||||
return self._serialize(row)
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# 쓰기 시도 기록 (cafe24_write_attempts) — 운영용 가변 표.
|
||||
# 원격 PUT 직전에 STARTED 로 남기고, 결과에 따라 상태를 바꾼다.
|
||||
# ════════════════════════════════════════════════════════════
|
||||
_ATTEMPT_FIELDS: tuple[str, ...] = (
|
||||
"product_no", "mall_id", "shop_no", "origin", "schedule_id", "actor",
|
||||
"backup_revision_id", "observed_digest", "base_digest", "target_digest",
|
||||
"target_html", "target_revision_id", "set_display", "set_selling", "memo",
|
||||
)
|
||||
|
||||
def start_attempt(self, **fields: Any) -> int:
|
||||
cols = [k for k in self._ATTEMPT_FIELDS if k in fields]
|
||||
values = [fields[k] for k in cols]
|
||||
with self._pool.connection() as conn:
|
||||
row = conn.execute(
|
||||
f"""
|
||||
INSERT INTO cafe24_write_attempts ({", ".join(cols)}, status)
|
||||
VALUES ({", ".join(["%s"] * len(cols))}, %s)
|
||||
RETURNING id
|
||||
""",
|
||||
(*values, store.ATTEMPT_STARTED),
|
||||
).fetchone()
|
||||
return int(row["id"]) if row else 0
|
||||
|
||||
def update_attempt(
|
||||
self,
|
||||
attempt_id: int,
|
||||
*,
|
||||
status: str | None = None,
|
||||
error: str | None = None,
|
||||
remote_updated_at: str | None = None,
|
||||
remote_ok: bool = False,
|
||||
resolved_by: str | None = None,
|
||||
only_from: tuple[str, ...] | None = None,
|
||||
) -> bool:
|
||||
"""상태 전이. only_from 을 주면 그 상태에서만 바꾼다(늦게 도착한 갱신 무시)."""
|
||||
sets: list[str] = []
|
||||
args: list[Any] = []
|
||||
if status is not None:
|
||||
sets.append("status = %s")
|
||||
args.append(status)
|
||||
if error is not None:
|
||||
sets.append("error = %s")
|
||||
args.append((error or "")[:1000])
|
||||
if remote_updated_at is not None:
|
||||
sets.append("remote_updated_at = %s")
|
||||
args.append(str(remote_updated_at or ""))
|
||||
if remote_ok:
|
||||
sets.append("remote_at = COALESCE(remote_at, now())")
|
||||
if resolved_by is not None:
|
||||
sets.append("resolved_by = %s")
|
||||
args.append(resolved_by[:200])
|
||||
if not sets:
|
||||
return False
|
||||
where = "id = %s"
|
||||
args.append(int(attempt_id))
|
||||
if only_from:
|
||||
where += " AND status = ANY(%s)"
|
||||
args.append(list(only_from))
|
||||
with self._pool.connection() as conn:
|
||||
row = conn.execute(
|
||||
f"UPDATE cafe24_write_attempts SET {', '.join(sets)} WHERE {where} RETURNING id",
|
||||
args,
|
||||
).fetchone()
|
||||
return row is not None
|
||||
|
||||
def record_attempt_revision(
|
||||
self,
|
||||
attempt_id: int,
|
||||
*,
|
||||
revision_type: str,
|
||||
memo: str,
|
||||
created_by: str,
|
||||
source: str = "",
|
||||
source_revision_id: int | None = None,
|
||||
) -> int:
|
||||
"""원격 반영된 시도의 버전(MANUAL/SCHEDULED/ROLLBACK)을 남기고 RECORDED 로 바꾼다.
|
||||
|
||||
한 트랜잭션에서 한다 — 시도 행을 잠그고, 이미 기록돼 있으면 그 버전 id 를 돌려준다
|
||||
(기록 복구가 두 번 돌아도 버전이 둘 생기지 않는다). 내용은 시도에 보관한
|
||||
target_html(없으면 target_revision_id 의 내용)이다. 기록 뒤 target_html 은 비운다.
|
||||
"""
|
||||
with self._pool.connection() as conn:
|
||||
with conn.transaction():
|
||||
att = conn.execute(
|
||||
"""
|
||||
SELECT a.*, COALESCE(NULLIF(a.target_html, ''), t.html_content, '') AS body
|
||||
FROM cafe24_write_attempts a
|
||||
LEFT JOIN cafe24_product_revisions t ON t.id = a.target_revision_id
|
||||
WHERE a.id = %s
|
||||
FOR UPDATE OF a
|
||||
""",
|
||||
(int(attempt_id),),
|
||||
).fetchone()
|
||||
if att is None:
|
||||
return 0
|
||||
if att.get("applied_revision_id"):
|
||||
return int(att["applied_revision_id"])
|
||||
row = conn.execute(
|
||||
"""
|
||||
INSERT INTO cafe24_product_revisions
|
||||
(product_no, html_content, revision_type, memo, created_by,
|
||||
mall_id, shop_no, source, source_revision_id)
|
||||
VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s)
|
||||
RETURNING id
|
||||
""",
|
||||
(
|
||||
int(att["product_no"]), att["body"] or "",
|
||||
store.normalize_revision_type(revision_type), (memo or "")[:500],
|
||||
created_by or "", att.get("mall_id") or "", int(att.get("shop_no") or 1),
|
||||
source or "", source_revision_id,
|
||||
),
|
||||
).fetchone()
|
||||
revision_id = int(row["id"])
|
||||
conn.execute(
|
||||
"""
|
||||
UPDATE cafe24_write_attempts
|
||||
SET status = %s, applied_revision_id = %s, target_html = '',
|
||||
remote_at = COALESCE(remote_at, now())
|
||||
WHERE id = %s
|
||||
""",
|
||||
(store.ATTEMPT_RECORDED, revision_id, int(attempt_id)),
|
||||
)
|
||||
return revision_id
|
||||
|
||||
def get_attempt(self, attempt_id: int) -> dict[str, Any]:
|
||||
with self._pool.connection() as conn:
|
||||
row = conn.execute(
|
||||
"SELECT * FROM cafe24_write_attempts WHERE id = %s", (int(attempt_id),)
|
||||
).fetchone()
|
||||
return self._serialize(row)
|
||||
|
||||
def latest_attempt_for_schedule(self, schedule_id: int) -> dict[str, Any]:
|
||||
with self._pool.connection() as conn:
|
||||
row = conn.execute(
|
||||
"""
|
||||
SELECT * FROM cafe24_write_attempts WHERE schedule_id = %s
|
||||
ORDER BY created_at DESC, id DESC LIMIT 1
|
||||
""",
|
||||
(int(schedule_id),),
|
||||
).fetchone()
|
||||
return self._serialize(row)
|
||||
|
||||
def open_attempts(self, product_no: int, *, since: datetime) -> list[dict[str, Any]]:
|
||||
"""결과 확정이 필요한 시도(STARTED/REMOTE_OK/UNKNOWN), 유예시간 안, 오래된 순.
|
||||
|
||||
005 적용 전이면 빈 목록(읽기 경로는 막지 않는다)."""
|
||||
try:
|
||||
with self._pool.connection() as conn:
|
||||
rows = conn.execute(
|
||||
"""
|
||||
SELECT id, product_no, origin, schedule_id, actor, status, target_digest,
|
||||
target_revision_id, backup_revision_id, set_display, set_selling,
|
||||
error, created_at, remote_at, memo
|
||||
FROM cafe24_write_attempts
|
||||
WHERE product_no = %s AND status = ANY(%s) AND created_at >= %s
|
||||
ORDER BY created_at ASC, id ASC
|
||||
""",
|
||||
(int(product_no), list(store.ATTEMPT_OPEN), since),
|
||||
).fetchall()
|
||||
except (pg_errors.UndefinedTable, pg_errors.UndefinedColumn):
|
||||
return []
|
||||
return [self._serialize(r) for r in rows]
|
||||
|
||||
def attempts_needing_record(self, *, since: datetime, limit: int = 20) -> list[dict[str, Any]]:
|
||||
"""원격 반영됐는데 버전 기록이 안 된 시도(REMOTE_OK) — worker 가 기록을 채운다."""
|
||||
with self._pool.connection() as conn:
|
||||
rows = conn.execute(
|
||||
"""
|
||||
SELECT id, product_no, origin, schedule_id, actor, memo, target_revision_id, target_digest
|
||||
FROM cafe24_write_attempts
|
||||
WHERE status = %s AND created_at >= %s
|
||||
ORDER BY created_at ASC, id ASC LIMIT %s
|
||||
""",
|
||||
(store.ATTEMPT_REMOTE_OK, since, max(1, int(limit))),
|
||||
).fetchall()
|
||||
return [self._serialize(r) for r in rows]
|
||||
|
||||
def write_lineage(self, product_no: int, *, since: datetime, limit: int = 30) -> list[dict[str, Any]]:
|
||||
"""원격 반영이 **확인된** 상세설명 쓰기(REMOTE_OK/RECORDED), 최신 순.
|
||||
|
||||
읽기 지연 판정의 유일한 근거다. 충돌로 거절된 적용의 백업, 예약 초안, 실패·결과
|
||||
모름 시도는 들어오지 않는다. 첫 행에만 html_content(마지막으로 쓴 HTML)를 채운다.
|
||||
created_at 은 원격 반영 시각(remote_at)이다. 005 적용 전이면 빈 목록.
|
||||
"""
|
||||
try:
|
||||
with self._pool.connection() as conn:
|
||||
rows = conn.execute(
|
||||
"""
|
||||
SELECT id, origin, actor, status, schedule_id, observed_digest, base_digest,
|
||||
target_digest, remote_updated_at, remote_at, applied_revision_id,
|
||||
target_revision_id
|
||||
FROM cafe24_write_attempts
|
||||
WHERE product_no = %s AND status = ANY(%s) AND target_digest <> ''
|
||||
AND remote_at >= %s
|
||||
ORDER BY remote_at DESC, id DESC
|
||||
LIMIT %s
|
||||
""",
|
||||
(int(product_no), list(store.ATTEMPT_CONFIRMED), since, max(1, int(limit))),
|
||||
).fetchall()
|
||||
if not rows:
|
||||
return []
|
||||
top = conn.execute(
|
||||
"""
|
||||
SELECT COALESCE(NULLIF(a.target_html, ''), r.html_content, t.html_content, '') AS body
|
||||
FROM cafe24_write_attempts a
|
||||
LEFT JOIN cafe24_product_revisions r ON r.id = a.applied_revision_id
|
||||
LEFT JOIN cafe24_product_revisions t ON t.id = a.target_revision_id
|
||||
WHERE a.id = %s
|
||||
""",
|
||||
(rows[0]["id"],),
|
||||
).fetchone()
|
||||
except (pg_errors.UndefinedTable, pg_errors.UndefinedColumn):
|
||||
return []
|
||||
out: list[dict[str, Any]] = []
|
||||
for index, row in enumerate(rows):
|
||||
item = dict(row)
|
||||
at = item.get("remote_at")
|
||||
if isinstance(at, datetime) and at.tzinfo is None:
|
||||
at = at.replace(tzinfo=KST)
|
||||
item["created_at"] = at
|
||||
item["created_by"] = item.get("actor") or ""
|
||||
item["html_content"] = (top or {}).get("body", "") if index == 0 else ""
|
||||
out.append(item)
|
||||
return out
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# OAuth 토큰 — app/integrations/cafe24/tokens.py 가 요구하는 3개 메서드
|
||||
# ════════════════════════════════════════════════════════════
|
||||
@@ -281,31 +592,38 @@ class Cafe24Store:
|
||||
# 마이그레이션 004 의 두 컬럼(last_write_snapshot, last_written_at)을 쓴다.
|
||||
# 스냅샷 JSON 모양:
|
||||
# {"product": {"data": {...store.SNAPSHOT_FIELDS...}, "written_at": ISO},
|
||||
# "options": {"data": {...GET/PUT options 응답...}, "written_at": ISO},
|
||||
# "variants": {"data": {variant_code: {...}}, "written_at": ISO}}
|
||||
# "options": {"data": {...GET/PUT options 응답..., "_before_signature", "_recent_values"},
|
||||
# "written_at": ISO},
|
||||
# "variants": {"data": {variant_code: {필드..., "_at", "_deleted"?}}, "written_at": ISO}}
|
||||
# 섹션별로 따로 갱신한다(가격만 바꿨는데 옵션 스냅샷이 사라지면 안 된다).
|
||||
def save_write_snapshot(self, product_no: int, section: str, data: Any) -> None:
|
||||
# 품목은 코드별·필드별로 병합한다(store.merge_variant_snapshot). 품목 전체 초기화
|
||||
# (옵션 삭제·재생성)는 replace=True 로 명시한다 — {} 를 넘기는 것은 "변경 없음"이다.
|
||||
def save_write_snapshot(self, product_no: int, section: str, data: Any, *, replace: bool = False) -> None:
|
||||
from psycopg.types.json import Jsonb # noqa: WPS433
|
||||
|
||||
no = int(product_no)
|
||||
if no <= 0 or section not in ("product", "options", "variants"):
|
||||
return
|
||||
now_iso = datetime.now(KST).isoformat(timespec="seconds")
|
||||
with self._pool.connection() as conn:
|
||||
with conn.transaction():
|
||||
# 행이 없으면 먼저 만든다 — FOR UPDATE 가 잠글 행이 있어야 동시 저장이
|
||||
# 서로의 병합 결과를 덮지 않는다.
|
||||
conn.execute(
|
||||
"INSERT INTO cafe24_products (product_no) VALUES (%s) ON CONFLICT (product_no) DO NOTHING",
|
||||
(no,),
|
||||
)
|
||||
row = conn.execute(
|
||||
"SELECT last_write_snapshot FROM cafe24_products WHERE product_no = %s FOR UPDATE",
|
||||
(no,),
|
||||
).fetchone()
|
||||
current = dict(row["last_write_snapshot"]) if row and row.get("last_write_snapshot") else {}
|
||||
if section == "variants" and isinstance(data, dict):
|
||||
# 품목은 코드별로 누적 병합 — 일부만 바꿔도 이전에 바꾼 것을 잃지 않게.
|
||||
merged = dict((current.get("variants") or {}).get("data") or {})
|
||||
merged.update(data)
|
||||
data = merged
|
||||
current[section] = {
|
||||
"data": data,
|
||||
"written_at": datetime.now(KST).isoformat(timespec="seconds"),
|
||||
}
|
||||
if section == "variants":
|
||||
previous = (current.get("variants") or {}).get("data") or {}
|
||||
data = store.merge_variant_snapshot(
|
||||
previous, data if isinstance(data, dict) else {}, at=now_iso, replace=replace
|
||||
)
|
||||
current[section] = {"data": data, "written_at": now_iso}
|
||||
product = data if section == "product" and isinstance(data, dict) else {}
|
||||
conn.execute(
|
||||
"""
|
||||
@@ -345,51 +663,14 @@ class Cafe24Store:
|
||||
return {}
|
||||
return dict(row["last_write_snapshot"])
|
||||
|
||||
# ── 읽기 지연 판정용 revision 조회 ──
|
||||
def latest_write_revision(self, product_no: int, *, since: datetime) -> dict[str, Any] | None:
|
||||
"""유예시간 안의 가장 최근 '쓰기' revision(MANUAL/SCHEDULED/ROLLBACK) — HTML 포함."""
|
||||
with self._pool.connection() as conn:
|
||||
row = conn.execute(
|
||||
"""
|
||||
SELECT id, product_no, revision_type, html_content, memo, created_by, created_at
|
||||
FROM cafe24_product_revisions
|
||||
WHERE product_no = %s
|
||||
AND revision_type = ANY(%s)
|
||||
AND created_at >= %s
|
||||
ORDER BY created_at DESC, id DESC
|
||||
LIMIT 1
|
||||
""",
|
||||
(int(product_no), list(store.WRITE_REVISION_TYPES), since),
|
||||
).fetchone()
|
||||
if not row:
|
||||
return None
|
||||
out = dict(row)
|
||||
at = out.get("created_at")
|
||||
if isinstance(at, datetime) and at.tzinfo is None:
|
||||
out["created_at"] = at.replace(tzinfo=KST)
|
||||
return out
|
||||
|
||||
def revision_digests(self, product_no: int, *, since: datetime) -> set[str]:
|
||||
"""유예시간 안의 revision 들의 내용 해시(store.content_digest 와 같은 md5 hex).
|
||||
|
||||
내용을 통째로 옮기지 않고 DB 에서 해시만 계산한다(상세페이지는 수 MB 일 수 있다).
|
||||
md5 를 쓰는 이유: 모든 PostgreSQL 버전에 있고, 여기서는 충돌 저항이 아니라
|
||||
"같은 내용인가"만 필요하다.
|
||||
"""
|
||||
with self._pool.connection() as conn:
|
||||
rows = conn.execute(
|
||||
"""
|
||||
SELECT md5(html_content) AS digest
|
||||
FROM cafe24_product_revisions
|
||||
WHERE product_no = %s AND created_at >= %s
|
||||
""",
|
||||
(int(product_no), since),
|
||||
).fetchall()
|
||||
return {str(r["digest"]) for r in rows if r.get("digest")}
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# 상세페이지 HTML 버전 (append-only — UPDATE/DELETE 하지 않는다)
|
||||
# 쓰기 직전 BACKUP 을 남기는 것이 유일한 복구 수단이다.
|
||||
# 읽기 지연 판정은 이 표가 아니라 cafe24_write_attempts(확인된 쓰기)를 본다 —
|
||||
# 여기에는 충돌로 거절된 적용의 백업·예약 초안처럼 카페24에 올라간 적 없는 값도
|
||||
# 들어 있기 때문이다(write_lineage 참고).
|
||||
# 메타데이터(마이그레이션 005): mall_id·shop_no(복원 시 일치 검사), source
|
||||
# (BACKUP 이 카페24 관측값인지, 지연 중이라 마지막 확인된 쓰기인지), source_revision_id.
|
||||
# ════════════════════════════════════════════════════════════
|
||||
def add_revision(
|
||||
self,
|
||||
@@ -399,13 +680,18 @@ class Cafe24Store:
|
||||
revision_type: str,
|
||||
memo: str = "",
|
||||
created_by: str = "",
|
||||
mall_id: str = "",
|
||||
shop_no: int = 1,
|
||||
source: str = "",
|
||||
source_revision_id: int | None = None,
|
||||
) -> int:
|
||||
with self._pool.connection() as conn:
|
||||
row = conn.execute(
|
||||
"""
|
||||
INSERT INTO cafe24_product_revisions
|
||||
(product_no, html_content, revision_type, memo, created_by)
|
||||
VALUES (%s,%s,%s,%s,%s)
|
||||
(product_no, html_content, revision_type, memo, created_by,
|
||||
mall_id, shop_no, source, source_revision_id)
|
||||
VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s)
|
||||
RETURNING id
|
||||
""",
|
||||
(
|
||||
@@ -414,24 +700,33 @@ class Cafe24Store:
|
||||
store.normalize_revision_type(revision_type),
|
||||
(memo or "")[:500],
|
||||
created_by or "",
|
||||
mall_id or "",
|
||||
int(shop_no or 1),
|
||||
source or "",
|
||||
source_revision_id,
|
||||
),
|
||||
).fetchone()
|
||||
return int(row["id"]) if row else 0
|
||||
|
||||
def list_revisions(self, product_no: int, *, limit: int = 20) -> list[dict[str, Any]]:
|
||||
"""버전 목록. html_content 는 수 MB 일 수 있어 길이만 계산해서 준다."""
|
||||
with self._pool.connection() as conn:
|
||||
rows = conn.execute(
|
||||
"""
|
||||
SELECT id, product_no, revision_type, memo, created_by, created_at,
|
||||
length(html_content) AS html_length
|
||||
FROM cafe24_product_revisions
|
||||
WHERE product_no = %s
|
||||
ORDER BY created_at DESC, id DESC
|
||||
LIMIT %s
|
||||
""",
|
||||
(int(product_no), max(1, min(int(limit), 200))),
|
||||
).fetchall()
|
||||
"""버전 목록. html_content 는 수 MB 일 수 있어 길이만 계산해서 준다.
|
||||
|
||||
005 적용 전이면 출처(source) 없이 돌려준다(읽기 경로는 막지 않는다)."""
|
||||
sql = """
|
||||
SELECT id, product_no, revision_type, memo, created_by, created_at,
|
||||
length(html_content) AS html_length{extra}
|
||||
FROM cafe24_product_revisions
|
||||
WHERE product_no = %s
|
||||
ORDER BY created_at DESC, id DESC
|
||||
LIMIT %s
|
||||
"""
|
||||
args = (int(product_no), max(1, min(int(limit), 200)))
|
||||
try:
|
||||
with self._pool.connection() as conn:
|
||||
rows = conn.execute(sql.format(extra=", source, source_revision_id, mall_id"), args).fetchall()
|
||||
except pg_errors.UndefinedColumn:
|
||||
with self._pool.connection() as conn:
|
||||
rows = conn.execute(sql.format(extra=""), args).fetchall()
|
||||
return [self._serialize(r) for r in rows]
|
||||
|
||||
def get_revision(self, revision_id: int) -> dict[str, Any]:
|
||||
@@ -568,18 +863,24 @@ class Cafe24Store:
|
||||
)
|
||||
return True
|
||||
|
||||
@contextmanager
|
||||
def claim_due_schedule(self, *, now: datetime) -> Iterator[dict[str, Any] | None]:
|
||||
"""실행할 예약 1건을 잡아 PROCESSING 으로 바꾼다(worker 전용).
|
||||
# ── 예약 실행 lease (마이그레이션 005) ──
|
||||
# PROCESSING 은 lease_expires_at 까지만 유효하다. worker 가 죽으면 만료 후
|
||||
# claim_expired_schedules 로 다른(또는 재기동한) worker 가 가져가 시도 기록을 보고
|
||||
# 성공/재시도/확인 필요로 나눈다(worker.recover_expired). 모든 상태 변경은
|
||||
# lease_token 이 맞을 때만 한다 — 만료 뒤 늦게 끝난 worker 가 결과를 덮지 않게.
|
||||
def claim_due_schedule(self, *, now: datetime, owner: str, ttl_seconds: int) -> dict[str, Any] | None:
|
||||
"""실행할 예약 1건을 잡아 PROCESSING + lease 로 바꾼다(worker 전용).
|
||||
|
||||
`FOR UPDATE SKIP LOCKED` 로 잠그므로 worker 가 여러 개 떠 있어도 같은 예약을
|
||||
두 번 실행하지 않는다. 재시도 대기(next_retry_at)가 남아 있으면 건너뛴다.
|
||||
두 번 잡지 않는다. 재시도 대기(next_retry_at)가 남아 있으면 건너뛴다.
|
||||
반환 행의 lease_token 으로 renew/finish 한다.
|
||||
"""
|
||||
token = uuid.uuid4().hex
|
||||
with self._pool.connection() as conn:
|
||||
with conn.transaction():
|
||||
row = conn.execute(
|
||||
"""
|
||||
SELECT * FROM cafe24_product_schedules
|
||||
SELECT id FROM cafe24_product_schedules
|
||||
WHERE status = 'PENDING'
|
||||
AND scheduled_at <= %s
|
||||
AND (next_retry_at IS NULL OR next_retry_at <= %s)
|
||||
@@ -589,48 +890,154 @@ class Cafe24Store:
|
||||
""",
|
||||
(now, now),
|
||||
).fetchone()
|
||||
if row is not None:
|
||||
conn.execute(
|
||||
"""
|
||||
UPDATE cafe24_product_schedules
|
||||
SET status = 'PROCESSING', started_at = now(), last_error = ''
|
||||
WHERE id = %s
|
||||
""",
|
||||
(row["id"],),
|
||||
if row is None:
|
||||
return None
|
||||
claimed = conn.execute(
|
||||
"""
|
||||
UPDATE cafe24_product_schedules
|
||||
SET status = 'PROCESSING', started_at = now(), last_error = '',
|
||||
lease_owner = %s, lease_token = %s,
|
||||
lease_expires_at = now() + %s * interval '1 second'
|
||||
WHERE id = %s
|
||||
RETURNING *
|
||||
""",
|
||||
((owner or "")[:200], token, max(1, int(ttl_seconds)), row["id"]),
|
||||
).fetchone()
|
||||
return dict(claimed) if claimed else None
|
||||
|
||||
def claim_expired_schedules(
|
||||
self, *, owner: str, ttl_seconds: int, legacy_minutes: int, limit: int = 20
|
||||
) -> list[dict[str, Any]]:
|
||||
"""lease 가 만료된 PROCESSING 예약을 이 worker 에게 다시 lease 한다(복구 전용).
|
||||
|
||||
lease 컬럼이 비어 있는 옛 행(005 이전에 PROCESSING 이 된 것)은 started_at 이
|
||||
legacy_minutes 보다 오래됐으면 만료로 본다.
|
||||
"""
|
||||
with self._pool.connection() as conn:
|
||||
with conn.transaction():
|
||||
rows = conn.execute(
|
||||
"""
|
||||
WITH picked AS (
|
||||
SELECT id FROM cafe24_product_schedules
|
||||
WHERE status = 'PROCESSING'
|
||||
AND (lease_expires_at < now()
|
||||
OR (lease_expires_at IS NULL
|
||||
AND COALESCE(started_at, updated_at)
|
||||
< now() - %s * interval '1 minute'))
|
||||
ORDER BY id
|
||||
LIMIT %s
|
||||
FOR UPDATE SKIP LOCKED
|
||||
)
|
||||
yield dict(row) if row is not None else None
|
||||
UPDATE cafe24_product_schedules s
|
||||
SET lease_owner = %s,
|
||||
lease_token = md5(random()::text || clock_timestamp()::text || s.id::text),
|
||||
lease_expires_at = now() + %s * interval '1 second'
|
||||
FROM picked
|
||||
WHERE s.id = picked.id
|
||||
RETURNING s.*
|
||||
""",
|
||||
(max(1, int(legacy_minutes)), max(1, int(limit)), (owner or "")[:200],
|
||||
max(1, int(ttl_seconds))),
|
||||
).fetchall()
|
||||
return [dict(r) for r in rows]
|
||||
|
||||
def renew_schedule_lease(self, schedule_id: int, token: str, *, ttl_seconds: int) -> bool:
|
||||
"""아직 내 lease 면 연장하고 True. 만료돼 넘어갔으면 False — 카페24에 쓰지 않는다."""
|
||||
with self._pool.connection() as conn:
|
||||
row = conn.execute(
|
||||
"""
|
||||
UPDATE cafe24_product_schedules
|
||||
SET lease_expires_at = now() + %s * interval '1 second'
|
||||
WHERE id = %s AND status = 'PROCESSING' AND lease_token = %s
|
||||
AND lease_expires_at > now()
|
||||
RETURNING id
|
||||
""",
|
||||
(max(1, int(ttl_seconds)), int(schedule_id), token),
|
||||
).fetchone()
|
||||
return row is not None
|
||||
|
||||
def finish_schedule(
|
||||
self,
|
||||
schedule_id: int,
|
||||
*,
|
||||
token: str,
|
||||
status: str,
|
||||
error: str = "",
|
||||
next_retry_at: datetime | None = None,
|
||||
retry_count: int | None = None,
|
||||
) -> None:
|
||||
"""예약 종료 처리. 재시도로 되돌릴 때는 status='PENDING' + next_retry_at."""
|
||||
) -> bool:
|
||||
"""예약 종료 처리(lease 가 내 것일 때만). 재시도로 되돌릴 때는 status='PENDING' + next_retry_at.
|
||||
|
||||
반환: 반영했으면 True. lease 를 잃었으면 False(다른 worker 가 복구 중 — 덮지 않는다).
|
||||
"""
|
||||
normalized = store.normalize_schedule_status(status)
|
||||
with self._pool.connection() as conn:
|
||||
conn.execute(
|
||||
row = conn.execute(
|
||||
"""
|
||||
UPDATE cafe24_product_schedules
|
||||
SET status = %s,
|
||||
last_error = %s,
|
||||
next_retry_at = %s,
|
||||
retry_count = COALESCE(%s, retry_count),
|
||||
lease_owner = '', lease_token = '', lease_expires_at = NULL,
|
||||
completed_at = CASE WHEN %s IN ('SUCCESS','FAILED','CANCELLED')
|
||||
THEN now() ELSE completed_at END
|
||||
WHERE id = %s
|
||||
WHERE id = %s AND status = 'PROCESSING' AND lease_token = %s
|
||||
RETURNING id
|
||||
""",
|
||||
(
|
||||
store.normalize_schedule_status(status),
|
||||
(error or "")[:1000],
|
||||
next_retry_at,
|
||||
retry_count,
|
||||
store.normalize_schedule_status(status),
|
||||
int(schedule_id),
|
||||
),
|
||||
)
|
||||
(normalized, (error or "")[:1000], next_retry_at, retry_count, normalized,
|
||||
int(schedule_id), token),
|
||||
).fetchone()
|
||||
return row is not None
|
||||
|
||||
def get_schedule(self, schedule_id: int) -> dict[str, Any]:
|
||||
with self._pool.connection() as conn:
|
||||
row = conn.execute(
|
||||
"SELECT * FROM cafe24_product_schedules WHERE id = %s", (int(schedule_id),)
|
||||
).fetchone()
|
||||
return self._serialize(row)
|
||||
|
||||
def review_schedule(
|
||||
self, schedule_id: int, *, status: str, note: str, actor: str, action: str
|
||||
) -> dict[str, Any]:
|
||||
"""확인 필요(NEEDS_REVIEW) 예약을 사람이 확정한다 — SUCCESS / FAILED / PENDING(다시 실행).
|
||||
|
||||
SUCCESS 가 아니면 그 예약의 열린 쓰기 시도(STARTED/UNKNOWN)를 ABANDONED 로 닫는다
|
||||
(반영 안 됨으로 확정 / 재실행으로 대체). SUCCESS 면 호출부가 버전 기록을 채운다.
|
||||
반환: 바뀐 예약 행. NEEDS_REVIEW 가 아니었으면 {}.
|
||||
"""
|
||||
normalized = store.normalize_schedule_status(status)
|
||||
with self._pool.connection() as conn:
|
||||
with conn.transaction():
|
||||
row = conn.execute(
|
||||
"""
|
||||
UPDATE cafe24_product_schedules
|
||||
SET status = %s, last_error = %s,
|
||||
next_retry_at = CASE WHEN %s = 'PENDING' THEN now() ELSE NULL END,
|
||||
completed_at = CASE WHEN %s IN ('SUCCESS','FAILED') THEN now() ELSE NULL END
|
||||
WHERE id = %s AND status = 'NEEDS_REVIEW'
|
||||
RETURNING *
|
||||
""",
|
||||
(normalized, (note or "")[:1000], normalized, normalized, int(schedule_id)),
|
||||
).fetchone()
|
||||
if row is None:
|
||||
return {}
|
||||
if normalized != store.STATUS_SUCCESS:
|
||||
conn.execute(
|
||||
"""
|
||||
UPDATE cafe24_write_attempts
|
||||
SET status = %s, resolved_by = %s
|
||||
WHERE schedule_id = %s AND status = ANY(%s)
|
||||
""",
|
||||
(store.ATTEMPT_ABANDONED, (actor or "")[:200], int(schedule_id),
|
||||
[store.ATTEMPT_STARTED, store.ATTEMPT_UNKNOWN]),
|
||||
)
|
||||
self._insert_audit(
|
||||
conn, actor=actor, action=f"schedule_review:{action}",
|
||||
product_no=row["product_no"], schedule_id=row["id"], result="SUCCESS",
|
||||
detail=note,
|
||||
)
|
||||
return self._serialize(row)
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# 직렬화 — datetime → KST ISO, date → ISO (다른 모듈과 동일)
|
||||
|
||||
@@ -13,8 +13,11 @@
|
||||
다른 데이터를 다루지만, 여기는 파일마다 경로만 다르고 나머지는 동일하다).
|
||||
|
||||
쓰기 순서는 상세페이지 적용과 동일한 원칙을 따른다:
|
||||
FTP 에서 현재 내용을 다시 읽는다(로컬 값을 현재값으로 가정하지 않는다)
|
||||
→ BACKUP 버전 저장 → 지문 대조(충돌 시 거부) → FTP 에 쓴다
|
||||
파일별 DB 잠금(writes.write_lock, 'design:{file_key}')
|
||||
→ FTP 에서 현재 내용을 다시 읽는다(로컬 값을 현재값으로 가정하지 않는다)
|
||||
→ BACKUP 버전 저장 → 지문 대조(충돌 시 거부)
|
||||
→ 임시 파일 업로드·검증 → 교체 직전 원본 재확인 → 이름 바꾸기로 교체
|
||||
(design_ftp.write_text_file — 원본에 직접 STOR 하지 않는다)
|
||||
→ MANUAL 버전 + 감사로그
|
||||
|
||||
핸들러는 `async def` 가 아니라 `def`(동기)다 — FTP 호출이 블로킹이므로
|
||||
@@ -24,12 +27,14 @@ FastAPI 스레드풀에서 돌게 둔다(다른 cafe24 라우트와 동일한
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from urllib.parse import quote
|
||||
|
||||
from fastapi import APIRouter, Form, HTTPException, Request
|
||||
from fastapi.responses import HTMLResponse, RedirectResponse
|
||||
|
||||
from app.integrations.cafe24 import (
|
||||
DESIGN_FILE_SPECS,
|
||||
Cafe24FtpConflict,
|
||||
Cafe24FtpError,
|
||||
design_file_label,
|
||||
design_file_path,
|
||||
@@ -38,7 +43,7 @@ from app.integrations.cafe24 import (
|
||||
load_ftp_config,
|
||||
)
|
||||
|
||||
from . import store
|
||||
from . import store, writes
|
||||
from .common import base_ctx, guard
|
||||
from .routes_products import _no_store
|
||||
|
||||
@@ -128,74 +133,76 @@ def design_file_apply(
|
||||
st, user = checked
|
||||
actor = str(user.get("email") or "")
|
||||
back = f"/cafe24/design/{file_key}"
|
||||
action = f"apply_design:{file_key}"
|
||||
|
||||
def go(*, msg: str = "", err: str = "") -> RedirectResponse:
|
||||
key, text = ("err", err) if err else ("msg", msg)
|
||||
return RedirectResponse(url=f"{back}?{key}={quote(text, safe='')}", status_code=303)
|
||||
|
||||
path = design_file_path(file_key)
|
||||
ftp_config = _ftp_config()
|
||||
if not ftp_config.configured:
|
||||
return RedirectResponse(
|
||||
url=f"{back}?err=" + "FTP 설정이 필요합니다: " + ", ".join(ftp_config.missing),
|
||||
status_code=303,
|
||||
)
|
||||
return go(err="FTP 설정이 필요합니다: " + ", ".join(ftp_config.missing))
|
||||
|
||||
# 브라우저 textarea 는 줄바꿈을 CRLF 로 보낸다 — 그대로 저장하면 실제 수정이
|
||||
# 없어도 매번 파일 전체의 줄바꿈이 바뀌어(지문 비교·"변경 없음" 판정이 어긋난다).
|
||||
submitted = content.replace("\r\n", "\n")
|
||||
if not submitted.strip():
|
||||
return RedirectResponse(
|
||||
url=f"{back}?err=" + "내용이 비어 있습니다. 파일을 비우려면 FTP 로 직접 하세요.",
|
||||
status_code=303,
|
||||
)
|
||||
return go(err="내용이 비어 있습니다. 파일을 비우려면 FTP 로 직접 하세요.")
|
||||
|
||||
# 같은 파일을 두 사람이 동시에 적용하지 못하게 파일별 DB 잠금 안에서 한다.
|
||||
try:
|
||||
current = design_ftp.read_text_file(ftp_config, path)
|
||||
except Cafe24FtpError as exc:
|
||||
st.log_audit(
|
||||
actor=actor, action=f"apply_design:{file_key}", result="FAIL",
|
||||
detail=f"현재값 조회 실패: {exc}",
|
||||
)
|
||||
return RedirectResponse(url=f"{back}?err=현재 파일을 읽지 못해 중단했습니다: {exc}", status_code=303)
|
||||
with writes.write_lock(st, writes.design_lock_key(file_key), actor=actor, purpose=f"{file_key} 적용"):
|
||||
try:
|
||||
current = design_ftp.read_text_file(ftp_config, path)
|
||||
except Cafe24FtpError as exc:
|
||||
writes.audit_safe(st, actor=actor, action=action, result="FAIL", detail=f"현재값 조회 실패: {exc}")
|
||||
return go(err=f"현재 파일을 읽지 못해 중단했습니다: {exc}")
|
||||
|
||||
backup_id = st.add_design_revision(
|
||||
file_key=file_key, content=current, revision_type=store.REVISION_BACKUP,
|
||||
memo="적용 직전 자동 백업", created_by=actor,
|
||||
)
|
||||
backup_id = st.add_design_revision(
|
||||
file_key=file_key, content=current, revision_type=store.REVISION_BACKUP,
|
||||
memo="적용 직전 자동 백업", created_by=actor,
|
||||
)
|
||||
|
||||
if base_fingerprint and base_fingerprint != store.fingerprint(current):
|
||||
st.log_audit(
|
||||
actor=actor, action=f"apply_design:{file_key}", revision_id=backup_id,
|
||||
result="FAIL", detail="충돌 — 편집 중 파일이 변경됨",
|
||||
)
|
||||
return RedirectResponse(
|
||||
url=f"{back}?err=편집하는 동안 파일이 변경되었습니다. 새로고침해 현재 내용을 확인한 뒤 다시 적용하세요.",
|
||||
status_code=303,
|
||||
)
|
||||
if base_fingerprint and base_fingerprint != store.fingerprint(current):
|
||||
writes.audit_safe(st, actor=actor, action=action, revision_id=backup_id,
|
||||
result="FAIL", detail="충돌 — 편집 중 파일이 변경됨")
|
||||
return go(err="편집하는 동안 파일이 변경되었습니다. 새로고침해 현재 내용을 확인한 뒤 다시 적용하세요.")
|
||||
|
||||
if submitted == current:
|
||||
return RedirectResponse(url=f"{back}?msg=변경된 내용이 없어 적용하지 않았습니다.", status_code=303)
|
||||
if submitted == current:
|
||||
return go(msg="변경된 내용이 없어 적용하지 않았습니다.")
|
||||
|
||||
try:
|
||||
design_ftp.write_text_file(ftp_config, path, submitted)
|
||||
except Cafe24FtpError as exc:
|
||||
st.log_audit(
|
||||
actor=actor, action=f"apply_design:{file_key}", revision_id=backup_id,
|
||||
result="FAIL", detail=str(exc),
|
||||
)
|
||||
logger.warning("디자인 파일 적용 실패(%s): %s", file_key, exc)
|
||||
return RedirectResponse(
|
||||
url=f"{back}?err=적용에 실패했습니다: {exc} (직전 내용은 버전 {backup_id} 로 보관됨)",
|
||||
status_code=303,
|
||||
)
|
||||
try:
|
||||
# 임시 파일 업로드 → 검증 → 교체 직전 원본 재확인(current 와 같아야) → 이름 바꾸기.
|
||||
design_ftp.write_text_file(ftp_config, path, submitted, expected_current=current)
|
||||
except Cafe24FtpConflict as exc:
|
||||
writes.audit_safe(st, actor=actor, action=action, revision_id=backup_id,
|
||||
result="FAIL", detail=f"충돌 — 교체 직전 파일이 변경됨: {exc}")
|
||||
return go(err=f"{exc} (직전 내용은 버전 {backup_id} 로 보관됨)")
|
||||
except Cafe24FtpError as exc:
|
||||
maybe = bool(getattr(exc, "maybe_applied", False))
|
||||
writes.audit_safe(st, actor=actor, action=action, revision_id=backup_id,
|
||||
result="UNKNOWN" if maybe else "FAIL", detail=str(exc))
|
||||
logger.warning("디자인 파일 적용 실패(%s): %s", file_key, exc)
|
||||
return go(err=f"적용에 실패했습니다: {exc} (직전 내용은 버전 {backup_id} 로 보관됨)")
|
||||
|
||||
revision_id = st.add_design_revision(
|
||||
file_key=file_key, content=submitted, revision_type=store.REVISION_MANUAL,
|
||||
memo=memo, created_by=actor,
|
||||
)
|
||||
st.log_audit(
|
||||
actor=actor, action=f"apply_design:{file_key}", revision_id=revision_id, result="SUCCESS",
|
||||
detail=f"{len(submitted)}자 적용 (백업 {backup_id})",
|
||||
# 파일은 이미 바뀌었다 — 여기서의 기록 실패는 "적용 실패"가 아니다.
|
||||
record_note = ""
|
||||
try:
|
||||
revision_id = st.add_design_revision(
|
||||
file_key=file_key, content=submitted, revision_type=store.REVISION_MANUAL,
|
||||
memo=memo, created_by=actor,
|
||||
)
|
||||
except Exception: # noqa: BLE001
|
||||
logger.exception("디자인 파일(%s) 적용 후 버전 기록 실패", file_key)
|
||||
revision_id = None
|
||||
record_note = " ※ 파일은 적용됐지만 버전 기록 저장에 실패했습니다 — 다시 적용하지 마세요."
|
||||
except (writes.WriteBusy, writes.WriteSetupError) as exc:
|
||||
return go(err=str(exc))
|
||||
|
||||
writes.audit_safe(
|
||||
st, actor=actor, action=action, revision_id=revision_id, result="SUCCESS",
|
||||
detail=f"{len(submitted)}자 적용 (백업 {backup_id}, 임시 파일 교체 방식)" + (" / 버전 기록 실패" if record_note else ""),
|
||||
)
|
||||
logger.info("디자인 파일 적용(%s) (%s)", file_key, actor)
|
||||
return RedirectResponse(
|
||||
url=f"{back}?msg=적용했습니다. 직전 내용은 버전 {backup_id} 로 보관됩니다.",
|
||||
status_code=303,
|
||||
)
|
||||
return go(msg=f"적용했습니다. 직전 내용은 버전 {backup_id} 로 보관됩니다.{record_note}")
|
||||
|
||||
@@ -9,15 +9,20 @@
|
||||
PUT /products/{no}/options 옵션명 · 옵션값 이름/이미지/표시방식 수정
|
||||
DELETE /products/{no}/options 옵션 삭제 (품목도 함께 삭제 — 확인 후)
|
||||
POST /products/{no}/options/image 옵션값 썸네일 업로드만 (경로 반환)
|
||||
PUT /products/{no}/variants 품목 자체코드 · 추가금액 · 진열 · 판매
|
||||
PUT /products/{no}/variants 품목 자체코드 · 추가금액 · 진열 · 판매 (행별 결과)
|
||||
|
||||
공통 규칙
|
||||
- 카페24 호출은 `app.integrations.cafe24` 만 통한다(httpx 직접 호출 금지).
|
||||
- 쓰기는 상품별 DB 잠금(writes.write_lock) 안에서 한다 — 같은 상품을 웹 여러
|
||||
프로세스·예약 worker 가 동시에 쓰지 않게. 못 잡으면 409.
|
||||
- 쓰기 전에 현재값을 읽되, **읽기 지연을 보정한 유효 현재값**과 비교해 바뀐
|
||||
것만 보낸다(routes_products.load_product). 이걸 안 하면 "A→B 로 바꾼 직후
|
||||
다시 B→A" 가 카페24의 예전 값(A)과 같다고 판단돼 무시된다.
|
||||
- PUT 응답이 곧 현재값이다. 응답을 스냅샷(`save_write_snapshot`)에 남기고 화면도
|
||||
응답으로 그린다 — 다시 GET 하지 않는다(GET 은 한동안 예전 값을 돌려준다).
|
||||
PUT 이 성공한 뒤의 기록 실패는 쓰기 실패로 알리지 않는다(재전송을 부르지 않게).
|
||||
- 품목은 **품목코드**(안정 식별자)로 짝짓는다. 옵션값 이름을 바꾼 직후 GET 품목이
|
||||
예전 이름을 돌려줘도 스냅샷의 품목코드별 표기로 바로잡는다(store.apply_variant_patch).
|
||||
- 모든 쓰기는 감사로그(`cafe24_audit_logs`)에 남긴다.
|
||||
"""
|
||||
|
||||
@@ -31,9 +36,9 @@ from fastapi import APIRouter, Body, File, HTTPException, Request, UploadFile
|
||||
from app.integrations.cafe24 import Cafe24Error, build_cafe24_api, products
|
||||
from app.timezone import now_kst
|
||||
|
||||
from . import store
|
||||
from . import store, writes
|
||||
from .common import read_lag_grace_minutes, require_store
|
||||
from .routes_products import load_product, remember_write
|
||||
from .routes_products import load_product, locked_json, remember_write
|
||||
|
||||
logger = logging.getLogger("cafe24.product_info")
|
||||
|
||||
@@ -110,39 +115,40 @@ def product_basic(
|
||||
raise HTTPException(status_code=400, detail="바꿀 항목이 없습니다.")
|
||||
|
||||
api = build_cafe24_api(st)
|
||||
try:
|
||||
current, _ = load_product(st, api, product_no)
|
||||
except Cafe24Error as exc:
|
||||
st.log_audit(actor=actor, action="update_basic", product_no=product_no,
|
||||
result="FAIL", detail=f"현재값 조회 실패: {exc}")
|
||||
raise _http_from_cafe24(exc) from exc
|
||||
if not current:
|
||||
raise HTTPException(status_code=404, detail="카페24에서 상품을 찾지 못했습니다.")
|
||||
with locked_json(st, product_no, actor=actor, purpose="상품명·가격 변경"):
|
||||
try:
|
||||
current, _ = load_product(st, api, product_no)
|
||||
except Cafe24Error as exc:
|
||||
writes.audit_safe(st, actor=actor, action="update_basic", product_no=product_no,
|
||||
result="FAIL", detail=f"현재값 조회 실패: {exc}")
|
||||
raise _http_from_cafe24(exc) from exc
|
||||
if not current:
|
||||
raise HTTPException(status_code=404, detail="카페24에서 상품을 찾지 못했습니다.")
|
||||
|
||||
changes: dict[str, str] = {}
|
||||
before: dict[str, str] = {}
|
||||
for key, value in want.items():
|
||||
old = str(current.get(key) or "")
|
||||
same = old == value if key == "product_name" else store.price_equal(old, value)
|
||||
if not same:
|
||||
changes[key] = value
|
||||
before[key] = old
|
||||
if not changes:
|
||||
return {"ok": True, "changed": [], "product": _scalar_view(current)}
|
||||
changes: dict[str, str] = {}
|
||||
before: dict[str, str] = {}
|
||||
for key, value in want.items():
|
||||
old = str(current.get(key) or "")
|
||||
same = old == value if key == "product_name" else store.price_equal(old, value)
|
||||
if not same:
|
||||
changes[key] = value
|
||||
before[key] = old
|
||||
if not changes:
|
||||
return {"ok": True, "changed": [], "product": _scalar_view(current)}
|
||||
|
||||
try:
|
||||
updated = products.update_product(api.client, product_no, **changes)
|
||||
except Cafe24Error as exc:
|
||||
st.log_audit(actor=actor, action="update_basic", product_no=product_no,
|
||||
result="FAIL", detail=f"{changes} 실패: {exc}")
|
||||
logger.warning("카페24 상품 %s 기본정보 변경 실패: %s", product_no, exc)
|
||||
raise _http_from_cafe24(exc) from exc
|
||||
try:
|
||||
updated = products.update_product(api.client, product_no, **changes)
|
||||
except Cafe24Error as exc:
|
||||
writes.audit_safe(st, actor=actor, action="update_basic", product_no=product_no,
|
||||
result="FAIL", detail=f"{changes} 실패: {exc}")
|
||||
logger.warning("카페24 상품 %s 기본정보 변경 실패: %s", product_no, exc)
|
||||
raise _http_from_cafe24(exc) from exc
|
||||
|
||||
remember_write(st, product_no, updated if isinstance(updated, dict) else {})
|
||||
remember_write(st, product_no, updated if isinstance(updated, dict) else {})
|
||||
merged = {**current, **(updated if isinstance(updated, dict) else {}), **changes}
|
||||
detail = ", ".join(f"{k}: '{before[k]}' → '{v}'" for k, v in changes.items())
|
||||
st.log_audit(actor=actor, action="update_basic", product_no=product_no,
|
||||
result="SUCCESS", detail=detail)
|
||||
writes.audit_safe(st, actor=actor, action="update_basic", product_no=product_no,
|
||||
result="SUCCESS", detail=detail)
|
||||
logger.info("카페24 상품 %s 기본정보 변경 (%s): %s", product_no, actor, detail)
|
||||
return {"ok": True, "changed": list(changes.keys()), "product": _scalar_view(merged)}
|
||||
|
||||
@@ -169,30 +175,31 @@ def product_image(
|
||||
data = _read_image(file)
|
||||
|
||||
api = build_cafe24_api(st)
|
||||
try:
|
||||
current, _ = load_product(st, api, product_no)
|
||||
except Cafe24Error as exc:
|
||||
raise _http_from_cafe24(exc) from exc
|
||||
if not current:
|
||||
raise HTTPException(status_code=404, detail="카페24에서 상품을 찾지 못했습니다.")
|
||||
before = str(current.get("detail_image") or "")
|
||||
with locked_json(st, product_no, actor=actor, purpose="대표 이미지 교체"):
|
||||
try:
|
||||
current, _ = load_product(st, api, product_no)
|
||||
except Cafe24Error as exc:
|
||||
raise _http_from_cafe24(exc) from exc
|
||||
if not current:
|
||||
raise HTTPException(status_code=404, detail="카페24에서 상품을 찾지 못했습니다.")
|
||||
before = str(current.get("detail_image") or "")
|
||||
|
||||
try:
|
||||
images = products.set_main_image(
|
||||
api.client, product_no, data, content_type=(file.content_type or "").lower()
|
||||
)
|
||||
if not images.get("detail_image"):
|
||||
raise Cafe24Error("카페24가 등록된 이미지 경로를 돌려주지 않았습니다.")
|
||||
except Cafe24Error as exc:
|
||||
st.log_audit(actor=actor, action="set_main_image", product_no=product_no,
|
||||
result="FAIL", detail=f"등록 실패: {exc}")
|
||||
logger.warning("카페24 상품 %s 대표이미지 변경 실패: %s", product_no, exc)
|
||||
raise _http_from_cafe24(exc) from exc
|
||||
try:
|
||||
images = products.set_main_image(
|
||||
api.client, product_no, data, content_type=(file.content_type or "").lower()
|
||||
)
|
||||
if not images.get("detail_image"):
|
||||
raise Cafe24Error("카페24가 등록된 이미지 경로를 돌려주지 않았습니다.")
|
||||
except Cafe24Error as exc:
|
||||
writes.audit_safe(st, actor=actor, action="set_main_image", product_no=product_no,
|
||||
result="FAIL", detail=f"등록 실패: {exc}")
|
||||
logger.warning("카페24 상품 %s 대표이미지 변경 실패: %s", product_no, exc)
|
||||
raise _http_from_cafe24(exc) from exc
|
||||
|
||||
merged = {**current, **images, "updated_date": now_kst().isoformat(timespec="seconds")}
|
||||
remember_write(st, product_no, merged)
|
||||
st.log_audit(actor=actor, action="set_main_image", product_no=product_no,
|
||||
result="SUCCESS", detail=f"'{before}' → '{images['detail_image']}'")
|
||||
merged = {**current, **images, "updated_date": now_kst().isoformat(timespec="seconds")}
|
||||
remember_write(st, product_no, merged)
|
||||
writes.audit_safe(st, actor=actor, action="set_main_image", product_no=product_no,
|
||||
result="SUCCESS", detail=f"'{before}' → '{images['detail_image']}'")
|
||||
logger.info("카페24 상품 %s 대표이미지 변경 (%s)", product_no, actor)
|
||||
return {"ok": True, "product": _scalar_view(merged)}
|
||||
|
||||
@@ -208,6 +215,8 @@ def _variant_view(v: dict[str, Any]) -> dict[str, Any]:
|
||||
{"name": str(o.get("name") or ""), "value": str(o.get("value") or "")}
|
||||
for o in opts if isinstance(o, dict)
|
||||
],
|
||||
# 첫 옵션의 옵션값 번호(value_no) — 화면이 이름보다 먼저 이것으로 옵션값과 짝짓는다.
|
||||
"value_no": v.get("value_no"),
|
||||
"custom_variant_code": str(v.get("custom_variant_code") or ""),
|
||||
"additional_amount": str(v.get("additional_amount") or "0.00"),
|
||||
"display": products._flag(v.get("display")), # noqa: SLF001
|
||||
@@ -238,6 +247,7 @@ def _options_view(option: dict[str, Any]) -> dict[str, Any]:
|
||||
"option_link_image": str(v.get("option_link_image") or ""),
|
||||
"option_color": str(v.get("option_color") or ""),
|
||||
"value_no": v.get("value_no"),
|
||||
"pending": bool(v.get("pending")),
|
||||
}
|
||||
for v in values if isinstance(v, dict)
|
||||
],
|
||||
@@ -252,43 +262,125 @@ def _options_view(option: dict[str, Any]) -> dict[str, Any]:
|
||||
}
|
||||
|
||||
|
||||
def _apply_variant_snapshot(st: Any, product_no: int, variants: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
"""GET 품목 목록에 유예시간 안의 우리 쓰기(스냅샷)를 덮어씌운다.
|
||||
def _snapshot_sections(st: Any, product_no: int) -> tuple[dict[str, Any], dict[str, Any]]:
|
||||
"""(옵션 섹션, 품목 섹션) — 각각 {"data":…, "written_at":…} 또는 {}."""
|
||||
snap = st.get_write_snapshot(product_no) or {}
|
||||
return snap.get("options") or {}, snap.get("variants") or {}
|
||||
|
||||
삭제한 품목(`{"_deleted": true}`)은 카페24 GET 이 한동안 계속 돌려주므로 걸러낸다.
|
||||
"""
|
||||
section = (st.get_write_snapshot(product_no) or {}).get("variants") or {}
|
||||
|
||||
def _within(written_at: object) -> bool:
|
||||
return store.within_grace(written_at, grace_minutes=read_lag_grace_minutes())
|
||||
|
||||
|
||||
def _patch_variants(section: dict[str, Any], variants: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
"""GET 품목 목록에 품목코드별 쓰기 기록을 덮어씌운다(삭제한 품목은 뺀다)."""
|
||||
data = section.get("data") or {}
|
||||
if not data or not store.within_grace(section.get("written_at"), grace_minutes=read_lag_grace_minutes()):
|
||||
return variants
|
||||
if not isinstance(data, dict) or not data:
|
||||
return list(variants)
|
||||
out = []
|
||||
for v in variants:
|
||||
code = str(v.get("variant_code") or "")
|
||||
patch = data.get(code)
|
||||
if isinstance(patch, dict) and patch.get("_deleted"):
|
||||
continue
|
||||
out.append({**v, **patch} if isinstance(patch, dict) else v)
|
||||
patched = store.apply_variant_patch(
|
||||
v, data.get(str(v.get("variant_code") or "")),
|
||||
section_written_at=section.get("written_at"), grace_minutes=read_lag_grace_minutes(),
|
||||
)
|
||||
if patched is not None:
|
||||
out.append(patched)
|
||||
return out
|
||||
|
||||
|
||||
def _apply_options_snapshot(st: Any, product_no: int, option: dict[str, Any]) -> dict[str, Any]:
|
||||
"""GET 옵션이 우리 마지막 쓰기와 다르고 유예시간 안이면 스냅샷(우리 쓰기)을 쓴다."""
|
||||
section = (st.get_write_snapshot(product_no) or {}).get("options") or {}
|
||||
data = section.get("data")
|
||||
if not isinstance(data, dict) or not store.within_grace(
|
||||
section.get("written_at"), grace_minutes=read_lag_grace_minutes()
|
||||
):
|
||||
return option
|
||||
return data
|
||||
def _annotate(option: dict[str, Any], variants: list[dict[str, Any]], recent: list[str]) -> tuple[dict, list]:
|
||||
"""옵션 1개 상품: 품목에 첫 옵션값 번호(value_no)를, 품목이 아직 안 보이는 최근 추가
|
||||
옵션값에 pending 표시를 붙인다(화면이 "품목 없는 옵션값"으로 오해하지 않게)."""
|
||||
groups = option.get("options") if isinstance(option.get("options"), list) else []
|
||||
if len(groups) != 1 or not isinstance(groups[0], dict):
|
||||
return option, variants
|
||||
values = [v for v in (groups[0].get("option_value") or []) if isinstance(v, dict)]
|
||||
by_text = {str(v.get("option_text") or ""): v.get("value_no") for v in values}
|
||||
used: set[str] = set()
|
||||
out_variants = []
|
||||
for v in variants:
|
||||
opts = v.get("options") if isinstance(v.get("options"), list) else []
|
||||
first = str(opts[0].get("value") or "") if opts and isinstance(opts[0], dict) else ""
|
||||
used.add(first)
|
||||
out_variants.append({**v, "value_no": by_text.get(first)} if first in by_text else v)
|
||||
recent_set = set(recent or [])
|
||||
new_values = [
|
||||
{**v, "pending": True} if str(v.get("option_text") or "") in recent_set
|
||||
and str(v.get("option_text") or "") not in used else v
|
||||
for v in values
|
||||
]
|
||||
return {**option, "options": [{**groups[0], "option_value": new_values}]}, out_variants
|
||||
|
||||
|
||||
def _load_options_and_variants(st: Any, api: Any, product_no: int) -> dict[str, Any]:
|
||||
option = _apply_options_snapshot(st, product_no, products.get_options(api.client, product_no))
|
||||
view = _options_view(option)
|
||||
raw_option = products.get_options(api.client, product_no)
|
||||
osec, vsec = _snapshot_sections(st, product_no)
|
||||
option, _stale = store.overlay_options(
|
||||
raw_option, snapshot=osec.get("data"), written_at=osec.get("written_at"),
|
||||
grace_minutes=read_lag_grace_minutes(),
|
||||
)
|
||||
raw_variants: list[dict[str, Any]] = []
|
||||
variants: list[dict[str, Any]] = []
|
||||
if view["has_option"]:
|
||||
variants = _apply_variant_snapshot(st, product_no, products.list_variants(api.client, product_no))
|
||||
return {"option": view, "variants": [_variant_view(v) for v in variants], "raw_options": option}
|
||||
if products._flag(option.get("has_option"), default=False): # noqa: SLF001
|
||||
raw_variants = products.list_variants(api.client, product_no)
|
||||
variants = _patch_variants(vsec, raw_variants)
|
||||
recent = _recent_values(osec)
|
||||
shown_option, shown_variants = _annotate(option, variants, recent)
|
||||
return {
|
||||
"option": _options_view(shown_option),
|
||||
"variants": [_variant_view(v) for v in shown_variants],
|
||||
"raw_option": raw_option,
|
||||
"effective_option": option,
|
||||
"raw_variants": raw_variants,
|
||||
"effective_variants": variants,
|
||||
"options_section": osec,
|
||||
"variants_section": vsec,
|
||||
}
|
||||
|
||||
|
||||
def _recent_values(osec: dict[str, Any]) -> list[str]:
|
||||
data = osec.get("data") if isinstance(osec.get("data"), dict) else {}
|
||||
if not data or not _within(osec.get("written_at")):
|
||||
return []
|
||||
return [str(v) for v in (data.get("_recent_values") or [])]
|
||||
|
||||
|
||||
def _prior_signatures(osec: dict[str, Any]) -> list[str]:
|
||||
data = osec.get("data") if isinstance(osec.get("data"), dict) else {}
|
||||
if not data or not _within(osec.get("written_at")):
|
||||
return []
|
||||
return [str(s) for s in (data.get("_before_signatures") or []) if isinstance(s, str)]
|
||||
|
||||
|
||||
def _unique(items: list[Any]) -> list[Any]:
|
||||
out: list[Any] = []
|
||||
for item in items:
|
||||
if item not in out:
|
||||
out.append(item)
|
||||
return out
|
||||
|
||||
|
||||
def _options_snapshot(
|
||||
written: dict[str, Any], *, befores: list[dict[str, Any]], osec: dict[str, Any], recent: list[str]
|
||||
) -> dict[str, Any]:
|
||||
"""옵션 스냅샷 = 카페24 응답 + 쓰기 직전 모양들의 서명 + 최근 추가한 옵션값."""
|
||||
signatures = _unique(_prior_signatures(osec) + [store.options_signature(b) for b in befores if b])
|
||||
texts = {
|
||||
str(v.get("option_text") or "")
|
||||
for o in (written.get("options") or []) if isinstance(o, dict)
|
||||
for v in (o.get("option_value") or []) if isinstance(v, dict)
|
||||
}
|
||||
keep = [t for t in _unique(_recent_values(osec) + list(recent)) if t in texts]
|
||||
return {**written, "_before_signatures": signatures, "_recent_values": keep}
|
||||
|
||||
|
||||
def _save_snapshot_safe(st: Any, product_no: int, section: str, data: Any, **kw: Any) -> str:
|
||||
try:
|
||||
st.save_write_snapshot(product_no, section, data, **kw)
|
||||
except Exception as exc: # noqa: BLE001 — 카페24에는 이미 반영됐다
|
||||
logger.exception("상품 %s %s 스냅샷 저장 실패", product_no, section)
|
||||
return f"{type(exc).__name__}: {exc}"
|
||||
return ""
|
||||
|
||||
|
||||
@product_info_router.get("/products/{product_no}/options")
|
||||
@@ -322,29 +414,40 @@ def options_create(
|
||||
)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
values = [v["option_text"] for v in body["options"][0]["option_value"]]
|
||||
|
||||
api = build_cafe24_api(st)
|
||||
try:
|
||||
existing = products.get_options(api.client, product_no)
|
||||
if products._flag(existing.get("has_option"), default=False): # noqa: SLF001
|
||||
raise HTTPException(status_code=409, detail="이미 옵션이 있는 상품입니다. 수정하거나 삭제한 뒤 다시 만드세요.")
|
||||
created = products.create_options(api.client, product_no, body)
|
||||
except Cafe24Error as exc:
|
||||
st.log_audit(actor=actor, action="create_options", product_no=product_no,
|
||||
result="FAIL", detail=f"{body['options'][0]['option_name']} 실패: {exc}")
|
||||
raise _http_from_cafe24(exc) from exc
|
||||
with locked_json(st, product_no, actor=actor, purpose="옵션 생성"):
|
||||
try:
|
||||
existing = products.get_options(api.client, product_no)
|
||||
if products._flag(existing.get("has_option"), default=False): # noqa: SLF001
|
||||
raise HTTPException(status_code=409, detail="이미 옵션이 있는 상품입니다. 수정하거나 삭제한 뒤 다시 만드세요.")
|
||||
created = products.create_options(api.client, product_no, body)
|
||||
except Cafe24Error as exc:
|
||||
writes.audit_safe(st, actor=actor, action="create_options", product_no=product_no,
|
||||
result="FAIL", detail=f"{body['options'][0]['option_name']} 실패: {exc}")
|
||||
raise _http_from_cafe24(exc) from exc
|
||||
|
||||
st.save_write_snapshot(product_no, "options", created)
|
||||
values = [v["option_text"] for v in body["options"][0]["option_value"]]
|
||||
st.log_audit(actor=actor, action="create_options", product_no=product_no, result="SUCCESS",
|
||||
detail=f"옵션 '{body['options'][0]['option_name']}' 생성: {', '.join(values)}")
|
||||
osec, _vsec = _snapshot_sections(st, product_no)
|
||||
record_error = _save_snapshot_safe(
|
||||
st, product_no, "options",
|
||||
_options_snapshot(created, befores=[existing], osec=osec, recent=values),
|
||||
)
|
||||
# 새 옵션의 품목은 새 품목코드다 — 이전 품목 기록은 모두 버린다(전체 초기화).
|
||||
record_error = record_error or _save_snapshot_safe(st, product_no, "variants", {}, replace=True)
|
||||
# 카페24가 자동 생성한 품목(코드 부여)을 바로 돌려준다 — 읽기 지연이 있어 짧게 재시도.
|
||||
# 화면은 이 코드로 자체코드·추가금액을 이어서 PUT 한다. 다 안 보이면 pending 으로 표시.
|
||||
variants = products.wait_for_variants(api.client, product_no, len(values))
|
||||
writes.audit_safe(st, actor=actor, action="create_options", product_no=product_no, result="SUCCESS",
|
||||
detail=f"옵션 '{body['options'][0]['option_name']}' 생성: {', '.join(values)}")
|
||||
logger.info("카페24 상품 %s 옵션 생성 (%s)", product_no, actor)
|
||||
# 카페24가 자동 생성한 품목(코드 부여)을 바로 돌려준다 — 읽기 지연이 있어 짧게 재시도.
|
||||
# 화면은 이 코드로 자체코드·추가금액을 이어서 PUT 한다.
|
||||
variants = products.wait_for_variants(api.client, product_no, len(values))
|
||||
if len(variants) < len(values):
|
||||
logger.warning("카페24 상품 %s 옵션 생성 후 품목 %s/%s 건만 조회됨", product_no, len(variants), len(values))
|
||||
return {"ok": True, "option": _options_view(created), "variants": [_variant_view(v) for v in variants]}
|
||||
shown_option, shown_variants = _annotate(created, variants, values)
|
||||
return {"ok": True, "option": _options_view(shown_option),
|
||||
"variants": [_variant_view(v) for v in shown_variants],
|
||||
"missing_variants": max(0, len(values) - len(variants)),
|
||||
"record_warning": record_error}
|
||||
|
||||
|
||||
@product_info_router.put("/products/{product_no}/options")
|
||||
@@ -358,6 +461,8 @@ def options_update(
|
||||
카페24 PUT 은 `original_options`(수정 전)와 `options`(수정 후)를 짝지어 받는다.
|
||||
수정 전 값은 화면이 들고 있던 것이 아니라 **지금 카페24에서 다시 읽은 값**(읽기
|
||||
지연 보정 후)을 쓴다 — 그래야 다른 곳에서 바뀐 이름과 어긋나지 않는다.
|
||||
이름을 바꾸면 품목코드별로 새 표기를 스냅샷에 남긴다(GET 품목이 예전 이름을
|
||||
돌려주는 동안에도 품목이 옵션값과 제대로 짝지어 보이게).
|
||||
"""
|
||||
st, user = require_store(request)
|
||||
actor = str(user.get("email") or "")
|
||||
@@ -366,64 +471,99 @@ def options_update(
|
||||
raise HTTPException(status_code=400, detail="옵션 목록이 비어 있습니다.")
|
||||
|
||||
api = build_cafe24_api(st)
|
||||
try:
|
||||
loaded = _load_options_and_variants(st, api, product_no)
|
||||
except Cafe24Error as exc:
|
||||
raise _http_from_cafe24(exc) from exc
|
||||
if not loaded["option"]["has_option"]:
|
||||
raise HTTPException(status_code=409, detail="옵션이 없는 상품입니다. 먼저 옵션을 만드세요.")
|
||||
original = loaded["option"]["options"]
|
||||
try:
|
||||
body = store.build_update_options_request(
|
||||
original, edited, option_list_type=str(payload.get("option_list_type") or ""),
|
||||
allow_append=True,
|
||||
with locked_json(st, product_no, actor=actor, purpose="옵션 수정"):
|
||||
try:
|
||||
loaded = _load_options_and_variants(st, api, product_no)
|
||||
except Cafe24Error as exc:
|
||||
raise _http_from_cafe24(exc) from exc
|
||||
if not loaded["option"]["has_option"]:
|
||||
raise HTTPException(status_code=409, detail="옵션이 없는 상품입니다. 먼저 옵션을 만드세요.")
|
||||
original = loaded["option"]["options"]
|
||||
try:
|
||||
body = store.build_update_options_request(
|
||||
original, edited, option_list_type=str(payload.get("option_list_type") or ""),
|
||||
allow_append=True,
|
||||
)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
if loaded["option"]["option_preset_code"]:
|
||||
body["option_preset_code"] = loaded["option"]["option_preset_code"]
|
||||
# 뒤에 덧붙인 옵션값 — 카페24가 받아들이면 품목을 자동 생성한다(재시도 조회).
|
||||
added_texts = [
|
||||
v["option_text"]
|
||||
for o, n in zip(body["original_options"], body["options"])
|
||||
for v in n["option_value"][len(o["option_value"]):]
|
||||
]
|
||||
added = len(added_texts)
|
||||
|
||||
try:
|
||||
updated = products.update_options(api.client, product_no, body)
|
||||
except Cafe24Error as exc:
|
||||
writes.audit_safe(st, actor=actor, action="update_options", product_no=product_no,
|
||||
result="FAIL", detail=str(exc))
|
||||
logger.warning("카페24 상품 %s 옵션 수정 실패: %s", product_no, exc)
|
||||
raise _http_from_cafe24(exc) from exc
|
||||
|
||||
# ── 여기부터는 카페24에 반영된 뒤 — 기록 실패는 경고로만 알린다 ──
|
||||
record_error = _save_snapshot_safe(
|
||||
st, product_no, "options",
|
||||
_options_snapshot(updated, befores=[loaded["raw_option"], loaded["effective_option"]],
|
||||
osec=loaded["options_section"], recent=added_texts),
|
||||
)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
if loaded["option"]["option_preset_code"]:
|
||||
body["option_preset_code"] = loaded["option"]["option_preset_code"]
|
||||
# 뒤에 덧붙인 옵션값 수 — 카페24가 받아들이면 품목을 자동 생성한다(재시도 조회).
|
||||
added = sum(
|
||||
max(0, len(n["option_value"]) - len(o["option_value"]))
|
||||
for o, n in zip(body["original_options"], body["options"])
|
||||
)
|
||||
# 이름 바꾸기 표(수정 전 → 수정 후) — 위치로 짝지어진다(build_update_options_request).
|
||||
rename: dict[tuple[str, str], tuple[str, str]] = {}
|
||||
for o, n in zip(original, body["options"]):
|
||||
for ov, nv in zip(o["option_value"], n["option_value"]):
|
||||
rename[(o["option_name"], ov["option_text"])] = (n["option_name"], nv["option_text"])
|
||||
raw_labels = {str(v.get("variant_code") or ""): v.get("options") for v in loaded["raw_variants"]}
|
||||
previous = (loaded["variants_section"].get("data") or {}) if _within(
|
||||
loaded["variants_section"].get("written_at")) else {}
|
||||
label_patch: dict[str, Any] = {}
|
||||
renamed_variants: list[dict[str, Any]] = []
|
||||
for v in loaded["effective_variants"]:
|
||||
code = str(v.get("variant_code") or "")
|
||||
current = store.labels_as_json(v.get("options"))
|
||||
new = [
|
||||
dict(zip(("name", "value"), rename.get((o["name"], o["value"]), (o["name"], o["value"]))))
|
||||
for o in current
|
||||
]
|
||||
renamed_variants.append({**v, "options": new})
|
||||
if new != current and code:
|
||||
prior = previous.get(code) if isinstance(previous.get(code), dict) else {}
|
||||
history = [
|
||||
[{"name": a, "value": b} for a, b in labels]
|
||||
for labels in store.label_history(prior.get("_options_before"))
|
||||
]
|
||||
befores = _unique(history + [current, store.labels_as_json(raw_labels.get(code))])
|
||||
label_patch[code] = {"options": new, "_options_before": [b for b in befores if b != new]}
|
||||
if label_patch:
|
||||
record_error = record_error or _save_snapshot_safe(st, product_no, "variants", label_patch)
|
||||
summary = "; ".join(
|
||||
f"{o['option_name']}: " + ", ".join(v["option_text"] for v in o["option_value"])
|
||||
for o in body["options"]
|
||||
) + (f" (+{added} 추가)" if added else "")
|
||||
|
||||
try:
|
||||
updated = products.update_options(api.client, product_no, body)
|
||||
except Cafe24Error as exc:
|
||||
st.log_audit(actor=actor, action="update_options", product_no=product_no,
|
||||
result="FAIL", detail=str(exc))
|
||||
logger.warning("카페24 상품 %s 옵션 수정 실패: %s", product_no, exc)
|
||||
raise _http_from_cafe24(exc) from exc
|
||||
|
||||
st.save_write_snapshot(product_no, "options", updated)
|
||||
summary = "; ".join(
|
||||
f"{o['option_name']}: " + ", ".join(v["option_text"] for v in o["option_value"])
|
||||
for o in body["options"]
|
||||
) + (f" (+{added} 추가)" if added else "")
|
||||
st.log_audit(actor=actor, action="update_options", product_no=product_no,
|
||||
result="SUCCESS", detail=summary[:900])
|
||||
fresh: list[dict[str, Any]] | None = None
|
||||
if added:
|
||||
# 새 옵션값의 품목코드를 받아 돌려준다 — 화면이 자체코드/추가금액을 이어서 PUT 한다.
|
||||
# 늦게 나타나는 품목은 pending 으로 표시된다(_annotate).
|
||||
_osec, vsec = _snapshot_sections(st, product_no)
|
||||
fresh = _patch_variants(
|
||||
vsec, products.wait_for_variants(api.client, product_no, len(loaded["raw_variants"]) + added)
|
||||
)
|
||||
writes.audit_safe(st, actor=actor, action="update_options", product_no=product_no,
|
||||
result="SUCCESS", detail=summary[:900])
|
||||
logger.info("카페24 상품 %s 옵션 수정 (%s)", product_no, actor)
|
||||
|
||||
shown_option, shown_variants = _annotate(
|
||||
updated, fresh if fresh is not None else renamed_variants, added_texts
|
||||
)
|
||||
out: dict[str, Any] = {"ok": True, "option": _options_view(shown_option),
|
||||
"variants": [_variant_view(v) for v in shown_variants],
|
||||
"record_warning": record_error}
|
||||
if added:
|
||||
# 새 옵션값의 품목코드를 받아 돌려준다 — 화면이 자체코드/추가금액을 이어서 PUT 한다.
|
||||
fresh = products.wait_for_variants(api.client, product_no, len(loaded["variants"]) + added)
|
||||
fresh = _apply_variant_snapshot(st, product_no, fresh)
|
||||
return {"ok": True, "option": _options_view(updated), "variants": [_variant_view(v) for v in fresh],
|
||||
"added": added}
|
||||
|
||||
# 품목의 옵션값 표기는 이름을 바꾼 만큼 달라진다 — 응답값으로 다시 맞춘다.
|
||||
variants = loaded["variants"]
|
||||
rename: dict[tuple[str, str], tuple[str, str]] = {}
|
||||
for o, n in zip(original, body["options"]):
|
||||
for ov, nv in zip(o["option_value"], n["option_value"]):
|
||||
rename[(o["option_name"], ov["option_text"])] = (n["option_name"], nv["option_text"])
|
||||
for v in variants:
|
||||
v["options"] = [
|
||||
dict(zip(("name", "value"), rename.get((opt["name"], opt["value"]), (opt["name"], opt["value"]))))
|
||||
for opt in v["options"]
|
||||
]
|
||||
return {"ok": True, "option": _options_view(updated), "variants": variants}
|
||||
out["added"] = added
|
||||
return out
|
||||
|
||||
|
||||
@product_info_router.delete("/products/{product_no}/options")
|
||||
@@ -432,22 +572,29 @@ def options_delete(request: Request, product_no: int) -> dict[str, Any]:
|
||||
st, user = require_store(request)
|
||||
actor = str(user.get("email") or "")
|
||||
api = build_cafe24_api(st)
|
||||
try:
|
||||
before = products.get_options(api.client, product_no)
|
||||
products.delete_options(api.client, product_no)
|
||||
except Cafe24Error as exc:
|
||||
st.log_audit(actor=actor, action="delete_options", product_no=product_no,
|
||||
result="FAIL", detail=str(exc))
|
||||
raise _http_from_cafe24(exc) from exc
|
||||
names = ", ".join(
|
||||
str(o.get("option_name") or "") for o in (before.get("options") or []) if isinstance(o, dict)
|
||||
)
|
||||
st.save_write_snapshot(product_no, "options", {"has_option": "F", "options": []})
|
||||
st.save_write_snapshot(product_no, "variants", {})
|
||||
st.log_audit(actor=actor, action="delete_options", product_no=product_no,
|
||||
result="SUCCESS", detail=f"삭제된 옵션: {names or '(없음)'}")
|
||||
with locked_json(st, product_no, actor=actor, purpose="옵션 삭제"):
|
||||
try:
|
||||
before = products.get_options(api.client, product_no)
|
||||
products.delete_options(api.client, product_no)
|
||||
except Cafe24Error as exc:
|
||||
writes.audit_safe(st, actor=actor, action="delete_options", product_no=product_no,
|
||||
result="FAIL", detail=str(exc))
|
||||
raise _http_from_cafe24(exc) from exc
|
||||
names = ", ".join(
|
||||
str(o.get("option_name") or "") for o in (before.get("options") or []) if isinstance(o, dict)
|
||||
)
|
||||
osec, _vsec = _snapshot_sections(st, product_no)
|
||||
record_error = _save_snapshot_safe(
|
||||
st, product_no, "options",
|
||||
_options_snapshot({"has_option": "F", "options": []}, befores=[before], osec=osec, recent=[]),
|
||||
)
|
||||
# 품목 전체 초기화 — 빈 dict 병합(=변경 없음)이 아니라 명시적 replace.
|
||||
record_error = record_error or _save_snapshot_safe(st, product_no, "variants", {}, replace=True)
|
||||
writes.audit_safe(st, actor=actor, action="delete_options", product_no=product_no,
|
||||
result="SUCCESS", detail=f"삭제된 옵션: {names or '(없음)'}")
|
||||
logger.info("카페24 상품 %s 옵션 삭제 (%s)", product_no, actor)
|
||||
return {"ok": True, "option": _options_view({"has_option": "F"}), "variants": []}
|
||||
return {"ok": True, "option": _options_view({"has_option": "F"}), "variants": [],
|
||||
"record_warning": record_error}
|
||||
|
||||
|
||||
@product_info_router.post("/products/{product_no}/options/image")
|
||||
@@ -464,13 +611,13 @@ def option_image_upload(
|
||||
try:
|
||||
path = products.upload_image_bytes(api.client, data)
|
||||
except Cafe24Error as exc:
|
||||
st.log_audit(actor=actor, action="upload_option_image", product_no=product_no,
|
||||
result="FAIL", detail=str(exc))
|
||||
writes.audit_safe(st, actor=actor, action="upload_option_image", product_no=product_no,
|
||||
result="FAIL", detail=str(exc))
|
||||
raise _http_from_cafe24(exc) from exc
|
||||
if not path:
|
||||
raise HTTPException(status_code=502, detail="카페24가 업로드 경로를 돌려주지 않았습니다.")
|
||||
st.log_audit(actor=actor, action="upload_option_image", product_no=product_no,
|
||||
result="SUCCESS", detail=path)
|
||||
writes.audit_safe(st, actor=actor, action="upload_option_image", product_no=product_no,
|
||||
result="SUCCESS", detail=path)
|
||||
return {"ok": True, "path": path}
|
||||
|
||||
|
||||
@@ -483,18 +630,20 @@ def variant_delete(request: Request, product_no: int, variant_code: str) -> dict
|
||||
if not store.VARIANT_CODE_RE.match(code):
|
||||
raise HTTPException(status_code=400, detail=f"품목코드 형식이 올바르지 않습니다: {code}")
|
||||
api = build_cafe24_api(st)
|
||||
try:
|
||||
products.delete_variant(api.client, product_no, code)
|
||||
except Cafe24Error as exc:
|
||||
st.log_audit(actor=actor, action="delete_variant", product_no=product_no,
|
||||
result="FAIL", detail=f"{code}: {exc}")
|
||||
raise _http_from_cafe24(exc) from exc
|
||||
# 카페24 GET 은 한동안 삭제된 품목을 계속 돌려준다 — 스냅샷에 삭제 표식을 남겨 걸러낸다.
|
||||
st.save_write_snapshot(product_no, "variants", {code: {"_deleted": True}})
|
||||
st.log_audit(actor=actor, action="delete_variant", product_no=product_no,
|
||||
result="SUCCESS", detail=code)
|
||||
with locked_json(st, product_no, actor=actor, purpose="품목 삭제"):
|
||||
try:
|
||||
products.delete_variant(api.client, product_no, code)
|
||||
except Cafe24Error as exc:
|
||||
writes.audit_safe(st, actor=actor, action="delete_variant", product_no=product_no,
|
||||
result="FAIL", detail=f"{code}: {exc}")
|
||||
raise _http_from_cafe24(exc) from exc
|
||||
# 카페24 GET 은 한동안 삭제된 품목을 계속 돌려준다 — 삭제 표식을 남겨 걸러낸다.
|
||||
# 표식은 이후 늦게 도착한 수정이 있어도 유지된다(store.merge_variant_snapshot).
|
||||
record_error = _save_snapshot_safe(st, product_no, "variants", {code: {"_deleted": True}})
|
||||
writes.audit_safe(st, actor=actor, action="delete_variant", product_no=product_no,
|
||||
result="SUCCESS", detail=code)
|
||||
logger.info("카페24 상품 %s 품목 %s 삭제 (%s)", product_no, code, actor)
|
||||
return {"ok": True, "variant_code": code}
|
||||
return {"ok": True, "variant_code": code, "record_warning": record_error}
|
||||
|
||||
|
||||
@product_info_router.put("/products/{product_no}/variants")
|
||||
@@ -503,7 +652,13 @@ def variants_update(
|
||||
product_no: int,
|
||||
payload: dict[str, Any] = Body(default_factory=dict),
|
||||
) -> dict[str, Any]:
|
||||
"""품목 여러 건의 자체코드 · 추가금액 · 진열 · 판매를 한 번에 바꾼다."""
|
||||
"""품목 여러 건의 자체코드 · 추가금액 · 진열 · 판매를 한 번에 바꾼다 — **행별 결과**.
|
||||
|
||||
응답 {"ok": 전부 성공?, "partial": 일부만?, "updated": {code: 반영된 값},
|
||||
"failed": {code: 사유}, "unknown": {code: 사유}}
|
||||
100건 묶음 중 일부가 실패해도 성공한 행은 성공으로 기록·표시한다(화면이 그 행을
|
||||
다시 보내지 않게). 하나도 반영되지 않았으면 502.
|
||||
"""
|
||||
st, user = require_store(request)
|
||||
actor = str(user.get("email") or "")
|
||||
rows = payload.get("rows")
|
||||
@@ -517,31 +672,51 @@ def variants_update(
|
||||
raise HTTPException(status_code=400, detail="바뀐 값이 없습니다.")
|
||||
|
||||
api = build_cafe24_api(st)
|
||||
try:
|
||||
with locked_json(st, product_no, actor=actor, purpose="품목 수정"):
|
||||
results = products.update_variants(api.client, product_no, requests)
|
||||
except Cafe24Error as exc:
|
||||
st.log_audit(actor=actor, action="update_variants", product_no=product_no,
|
||||
result="FAIL", detail=f"{len(requests)}건 실패: {exc}")
|
||||
logger.warning("카페24 상품 %s 품목 수정 실패: %s", product_no, exc)
|
||||
raise _http_from_cafe24(exc) from exc
|
||||
|
||||
# 우리가 보낸 값이 곧 현재값이다(카페24가 받아들였으므로). 응답에 담긴 값이 있으면
|
||||
# 그것을 우선한다.
|
||||
by_code: dict[str, dict[str, Any]] = {}
|
||||
for r in requests:
|
||||
by_code[r["variant_code"]] = {k: v for k, v in r.items() if k != "variant_code"}
|
||||
for r in results:
|
||||
code = str(r.get("variant_code") or "")
|
||||
if code in by_code:
|
||||
for key in ("custom_variant_code", "additional_amount", "display", "selling", "display_order"):
|
||||
if key in r and r[key] is not None:
|
||||
by_code[code][key] = r[key]
|
||||
st.save_write_snapshot(product_no, "variants", by_code)
|
||||
# 카페24가 받아들인 행만 현재값으로 기록한다. 응답에 담긴 값이 있으면 그것을 우선한다.
|
||||
sent = {r["variant_code"]: {k: v for k, v in r.items() if k != "variant_code"} for r in requests}
|
||||
by_code: dict[str, dict[str, Any]] = {}
|
||||
failed: dict[str, str] = {}
|
||||
unknown: dict[str, str] = {}
|
||||
for result in results:
|
||||
code = result["variant_code"]
|
||||
if result["status"] == products.VARIANT_OK:
|
||||
patch = dict(sent.get(code) or {})
|
||||
for key in ("custom_variant_code", "additional_amount", "display", "selling", "display_order"):
|
||||
value = (result.get("variant") or {}).get(key)
|
||||
if value is not None:
|
||||
patch[key] = value
|
||||
by_code[code] = patch
|
||||
elif result["status"] == products.VARIANT_UNKNOWN:
|
||||
unknown[code] = result["error"]
|
||||
else:
|
||||
failed[code] = result["error"]
|
||||
record_error = _save_snapshot_safe(st, product_no, "variants", by_code) if by_code else ""
|
||||
|
||||
detail = "; ".join(
|
||||
f"{code}: " + ", ".join(f"{k}={v}" for k, v in patch.items()) for code, patch in by_code.items()
|
||||
)
|
||||
st.log_audit(actor=actor, action="update_variants", product_no=product_no,
|
||||
result="SUCCESS", detail=detail[:900])
|
||||
logger.info("카페24 상품 %s 품목 %s건 수정 (%s)", product_no, len(by_code), actor)
|
||||
return {"ok": True, "updated": {code: _variant_view({"variant_code": code, **patch})
|
||||
for code, patch in by_code.items()}}
|
||||
if failed or unknown:
|
||||
detail = (f"성공 {len(by_code)} / 실패 {len(failed)} / 결과 모름 {len(unknown)} — " + detail)
|
||||
first = next(iter({**failed, **unknown}.values()), "")
|
||||
detail += f" / 오류: {first}"
|
||||
result_label = "SUCCESS" if not (failed or unknown) else ("PARTIAL" if by_code else "FAIL")
|
||||
writes.audit_safe(st, actor=actor, action="update_variants", product_no=product_no,
|
||||
result=result_label, detail=detail[:900])
|
||||
if not by_code:
|
||||
first = next(iter({**failed, **unknown}.values()), "알 수 없는 오류")
|
||||
note = " (일부는 반영됐을 수 있습니다 — 다시 불러와 확인하세요)" if unknown else ""
|
||||
logger.warning("카페24 상품 %s 품목 수정 실패: %s", product_no, first)
|
||||
raise HTTPException(status_code=502, detail=f"{first}{note}")
|
||||
logger.info("카페24 상품 %s 품목 %s건 수정 (%s, 실패 %s, 모름 %s)",
|
||||
product_no, len(by_code), actor, len(failed), len(unknown))
|
||||
return {
|
||||
"ok": not (failed or unknown),
|
||||
"partial": bool(failed or unknown),
|
||||
"updated": {code: _variant_view({"variant_code": code, **patch}) for code, patch in by_code.items()},
|
||||
"failed": failed,
|
||||
"unknown": unknown,
|
||||
"record_warning": record_error,
|
||||
}
|
||||
|
||||
@@ -50,10 +50,11 @@ PC/모바일은 구분하지 않는다 — 적용 시 `description` 만 쓰고
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from contextlib import contextmanager
|
||||
from datetime import timedelta
|
||||
from decimal import Decimal
|
||||
from typing import Any
|
||||
from urllib.parse import urlencode
|
||||
from typing import Any, Iterator
|
||||
from urllib.parse import quote, urlencode
|
||||
|
||||
from fastapi import APIRouter, Body, Form, HTTPException, Request
|
||||
from fastapi.responses import HTMLResponse, RedirectResponse
|
||||
@@ -61,7 +62,7 @@ from fastapi.responses import HTMLResponse, RedirectResponse
|
||||
from app.integrations.cafe24 import Cafe24Error, build_cafe24_api, products
|
||||
from app.timezone import now_kst
|
||||
|
||||
from . import store
|
||||
from . import store, writes
|
||||
from .common import base_ctx, guard, read_lag_grace_minutes, require_store
|
||||
|
||||
logger = logging.getLogger("cafe24.products")
|
||||
@@ -121,6 +122,16 @@ def _short_dt(value: Any) -> str:
|
||||
return text.replace("T", " ")[:16]
|
||||
|
||||
|
||||
def _iso(value: Any) -> str:
|
||||
"""datetime 이면 KST ISO, 아니면 문자열 그대로."""
|
||||
if hasattr(value, "astimezone"):
|
||||
from app.timezone import KST # noqa: WPS433
|
||||
|
||||
aware = value if value.tzinfo else value.replace(tzinfo=KST)
|
||||
return aware.astimezone(KST).isoformat(timespec="seconds")
|
||||
return str(value or "")
|
||||
|
||||
|
||||
def _row_for_list(raw: dict[str, Any]) -> dict[str, Any]:
|
||||
"""왼쪽 목록에 쓸 필드만 — 상품번호·상품명·진열·판매·최근수정."""
|
||||
normalized = products.normalize_product(raw)
|
||||
@@ -187,30 +198,34 @@ def load_product(st: Any, api: Any, product_no: int) -> tuple[dict[str, Any], bo
|
||||
|
||||
|
||||
def resolve_description(
|
||||
st: Any, product_no: int, cafe24_html: str
|
||||
st: Any, product_no: int, cafe24_html: str, *, fetched_updated: object = None
|
||||
) -> tuple[str, str, dict[str, Any] | None]:
|
||||
"""(유효 HTML, 상태, 마지막 쓰기 revision). 상태는 store.SYNC_*."""
|
||||
grace = read_lag_grace_minutes()
|
||||
since = now_kst() - timedelta(minutes=grace)
|
||||
last_write = st.latest_write_revision(product_no, since=since)
|
||||
if not last_write:
|
||||
return cafe24_html, store.SYNC_NONE, None
|
||||
digests = st.revision_digests(product_no, since=since)
|
||||
effective, state = store.resolve_description(
|
||||
cafe24_html, last_write=last_write, known_digests=digests, grace_minutes=grace
|
||||
)
|
||||
return effective, state, last_write
|
||||
"""(유효 HTML, 상태, 마지막 확인된 쓰기). 상태는 store.SYNC_*.
|
||||
|
||||
근거는 원격 반영이 확인된 쓰기(cafe24_write_attempts)뿐이다 — writes.resolve_effective.
|
||||
"""
|
||||
return writes.resolve_effective(st, product_no, cafe24_html, fetched_updated=fetched_updated)
|
||||
|
||||
|
||||
def remember_write(st: Any, product_no: int, updated: dict[str, Any]) -> dict[str, Any]:
|
||||
"""PUT 응답(상품 dict)을 캐시·스냅샷에 남긴다. 정규화된 캐시 행을 돌려준다."""
|
||||
info = products.normalize_product(updated) if updated else {}
|
||||
if info.get("product_no"):
|
||||
st.upsert_products([info])
|
||||
st.save_write_snapshot(product_no, "product", store.product_snapshot(updated))
|
||||
"""PUT 응답(상품 dict)을 캐시·스냅샷에 남긴다. 정규화된 캐시 행을 돌려준다.
|
||||
|
||||
카페24에는 이미 반영된 뒤라 기록 실패로 예외를 내지 않는다(로그만 — writes 참고).
|
||||
"""
|
||||
info, _error = writes.remember_product_write(st, product_no, updated)
|
||||
return info
|
||||
|
||||
|
||||
@contextmanager
|
||||
def locked_json(st: Any, product_no: int, *, actor: str, purpose: str) -> Iterator[Any]:
|
||||
"""JSON API 용 상품 쓰기 잠금 — 못 잡으면 409, 스키마가 없으면 503."""
|
||||
try:
|
||||
with writes.write_lock(st, writes.product_lock_key(product_no), actor=actor, purpose=purpose) as lock:
|
||||
yield lock
|
||||
except (writes.WriteBusy, writes.WriteSetupError) as exc:
|
||||
raise HTTPException(status_code=exc.http_status, detail=str(exc)) from exc
|
||||
|
||||
|
||||
def _info(product: dict[str, Any]) -> dict[str, Any]:
|
||||
"""편집기·정보 패널 공용 상품 요약."""
|
||||
info = products.normalize_product(product) if product else {}
|
||||
@@ -245,11 +260,27 @@ def _editor_ctx(st: Any, product_no: int) -> dict[str, Any]:
|
||||
product, scalar_stale = load_product(st, api, product_no)
|
||||
desc = products.descriptions_from_product(product)
|
||||
st.upsert_products([products.normalize_product(product)])
|
||||
html_effective, sync_state, last_write = resolve_description(st, product_no, desc.description)
|
||||
html_effective, sync_state, last_write = resolve_description(
|
||||
st, product_no, desc.description, fetched_updated=product.get("updated_date")
|
||||
)
|
||||
except Cafe24Error as exc:
|
||||
error = str(exc)
|
||||
logger.warning("카페24 상품 %s 조회 실패: %s", product_no, exc)
|
||||
|
||||
# 반영 여부를 모르는 이전 시도 — 편집기 위에 확정 버튼과 함께 보여준다.
|
||||
# (REMOTE_OK 는 반영이 확인된 것이라 여기 올리지 않는다 — 기록은 자동 복구된다.)
|
||||
since = now_kst() - timedelta(minutes=read_lag_grace_minutes())
|
||||
open_attempts = [
|
||||
{**a, "label": writes.describe_attempt(a),
|
||||
"status_label": "결과 모름" if a.get("status") == store.ATTEMPT_UNKNOWN else "중단됨"}
|
||||
for a in st.open_attempts(product_no, since=since)
|
||||
if a.get("status") in (store.ATTEMPT_STARTED, store.ATTEMPT_UNKNOWN)
|
||||
]
|
||||
revisions = [
|
||||
{**r, "type_label": store.REVISION_LABELS.get(str(r.get("revision_type") or ""), "")}
|
||||
for r in st.list_revisions(product_no, limit=20)
|
||||
]
|
||||
|
||||
return {
|
||||
"product_no": product_no,
|
||||
# 고객이 보는 상세페이지 주소 (CAFE24_SHOP_URL, 없으면 카페24 기본 도메인)
|
||||
@@ -268,9 +299,10 @@ def _editor_ctx(st: Any, product_no: int) -> dict[str, Any]:
|
||||
"sync_pending": sync_state == store.SYNC_PENDING,
|
||||
"sync_external": sync_state == store.SYNC_EXTERNAL,
|
||||
"scalar_stale": scalar_stale,
|
||||
"last_write_at": _short_dt(last_write.get("created_at").isoformat() if last_write and last_write.get("created_at") else ""),
|
||||
"last_write_at": _short_dt(_iso(last_write.get("created_at")) if last_write else ""),
|
||||
"last_write_by": (last_write or {}).get("created_by") or "",
|
||||
"revisions": st.list_revisions(product_no, limit=20),
|
||||
"revisions": revisions,
|
||||
"open_attempts": open_attempts,
|
||||
"editor_error": error,
|
||||
"option_display_types": store.OPTION_DISPLAY_LABELS,
|
||||
}
|
||||
@@ -384,33 +416,34 @@ def product_rename(
|
||||
raise HTTPException(status_code=400, detail=f"상품명은 {NAME_MAX}자를 넘을 수 없습니다.")
|
||||
|
||||
api = build_cafe24_api(st)
|
||||
try:
|
||||
current, _ = load_product(st, api, product_no)
|
||||
except Cafe24Error as exc:
|
||||
st.log_audit(
|
||||
actor=actor, action="rename_product", product_no=product_no,
|
||||
result="FAIL", detail=f"현재값 조회 실패: {exc}",
|
||||
)
|
||||
raise HTTPException(status_code=502, detail=f"카페24 현재값을 읽지 못했습니다: {exc}") from exc
|
||||
with locked_json(st, product_no, actor=actor, purpose="상품명 변경"):
|
||||
try:
|
||||
current, _ = load_product(st, api, product_no)
|
||||
except Cafe24Error as exc:
|
||||
writes.audit_safe(
|
||||
st, actor=actor, action="rename_product", product_no=product_no,
|
||||
result="FAIL", detail=f"현재값 조회 실패: {exc}",
|
||||
)
|
||||
raise HTTPException(status_code=502, detail=f"카페24 현재값을 읽지 못했습니다: {exc}") from exc
|
||||
|
||||
before = str(current.get("product_name") or "")
|
||||
if before == name:
|
||||
return {"ok": True, "product_name": before, "changed": False}
|
||||
before = str(current.get("product_name") or "")
|
||||
if before == name:
|
||||
return {"ok": True, "product_name": before, "changed": False}
|
||||
|
||||
try:
|
||||
updated = products.update_product(api.client, product_no, product_name=name)
|
||||
except Cafe24Error as exc:
|
||||
st.log_audit(
|
||||
actor=actor, action="rename_product", product_no=product_no,
|
||||
result="FAIL", detail=f"'{before}' → '{name}' 실패: {exc}",
|
||||
)
|
||||
logger.warning("카페24 상품 %s 이름 변경 실패: %s", product_no, exc)
|
||||
raise HTTPException(status_code=502, detail=str(exc)) from exc
|
||||
try:
|
||||
updated = products.update_product(api.client, product_no, product_name=name)
|
||||
except Cafe24Error as exc:
|
||||
writes.audit_safe(
|
||||
st, actor=actor, action="rename_product", product_no=product_no,
|
||||
result="FAIL", detail=f"'{before}' → '{name}' 실패: {exc}",
|
||||
)
|
||||
logger.warning("카페24 상품 %s 이름 변경 실패: %s", product_no, exc)
|
||||
raise HTTPException(status_code=502, detail=str(exc)) from exc
|
||||
|
||||
info = remember_write(st, product_no, updated)
|
||||
info = remember_write(st, product_no, updated)
|
||||
after = str(info.get("product_name") or name)
|
||||
st.log_audit(
|
||||
actor=actor, action="rename_product", product_no=product_no,
|
||||
writes.audit_safe(
|
||||
st, actor=actor, action="rename_product", product_no=product_no,
|
||||
result="SUCCESS", detail=f"'{before}' → '{after}'",
|
||||
)
|
||||
logger.info("카페24 상품 %s 이름 변경 (%s)", product_no, actor)
|
||||
@@ -442,31 +475,32 @@ def product_status(
|
||||
want = bool(payload.get("value"))
|
||||
|
||||
api = build_cafe24_api(st)
|
||||
try:
|
||||
updated = products.update_product(api.client, product_no, **{field: want})
|
||||
except Cafe24Error as exc:
|
||||
st.log_audit(
|
||||
actor=actor, action=f"set_{field}", product_no=product_no,
|
||||
result="FAIL", detail=f"{want} 설정 실패: {exc}",
|
||||
)
|
||||
logger.warning("카페24 상품 %s %s 변경 실패: %s", product_no, field, exc)
|
||||
raise HTTPException(status_code=502, detail=str(exc)) from exc
|
||||
|
||||
# 응답이 상품 dict 면 그것이 곧 현재 상태다. 모양이 다르면(방어) 다시 조회한다.
|
||||
if "display" not in updated or "selling" not in updated:
|
||||
with locked_json(st, product_no, actor=actor, purpose="진열/판매 변경"):
|
||||
try:
|
||||
updated, _ = load_product(st, api, product_no)
|
||||
except Cafe24Error as exc: # 쓰기는 됐다 — 화면만 요청값으로 맞춘다.
|
||||
logger.warning("카페24 상품 %s 상태 재조회 실패: %s", product_no, exc)
|
||||
updated = {}
|
||||
updated = products.update_product(api.client, product_no, **{field: want})
|
||||
except Cafe24Error as exc:
|
||||
writes.audit_safe(
|
||||
st, actor=actor, action=f"set_{field}", product_no=product_no,
|
||||
result="FAIL", detail=f"{want} 설정 실패: {exc}",
|
||||
)
|
||||
logger.warning("카페24 상품 %s %s 변경 실패: %s", product_no, field, exc)
|
||||
raise HTTPException(status_code=502, detail=str(exc)) from exc
|
||||
|
||||
info = remember_write(st, product_no, updated)
|
||||
# 응답이 상품 dict 면 그것이 곧 현재 상태다. 모양이 다르면(방어) 다시 조회한다.
|
||||
if "display" not in updated or "selling" not in updated:
|
||||
try:
|
||||
updated, _ = load_product(st, api, product_no)
|
||||
except Cafe24Error as exc: # 쓰기는 됐다 — 화면만 요청값으로 맞춘다.
|
||||
logger.warning("카페24 상품 %s 상태 재조회 실패: %s", product_no, exc)
|
||||
updated = {}
|
||||
|
||||
info = remember_write(st, product_no, updated)
|
||||
state = {
|
||||
"display": bool(info.get("display", want if field == "display" else True)),
|
||||
"selling": bool(info.get("selling", want if field == "selling" else True)),
|
||||
}
|
||||
st.log_audit(
|
||||
actor=actor, action=f"set_{field}", product_no=product_no,
|
||||
writes.audit_safe(
|
||||
st, actor=actor, action=f"set_{field}", product_no=product_no,
|
||||
result="SUCCESS", detail=f"{field}={'T' if want else 'F'}",
|
||||
)
|
||||
logger.info("카페24 상품 %s %s=%s (%s)", product_no, field, want, actor)
|
||||
@@ -479,6 +513,95 @@ def product_redirect(request: Request, product_no: int):
|
||||
return RedirectResponse(url=f"/cafe24/?selected={product_no}", status_code=303)
|
||||
|
||||
|
||||
def _back_url(product_no: int, list_query: str) -> str:
|
||||
"""적용 후 돌아갈 주소 — 검색·필터를 유지한 채 같은 상품이 선택된 화면."""
|
||||
base = f"/cafe24/?{list_query}" if list_query else f"/cafe24/?selected={product_no}"
|
||||
return base if f"selected={product_no}" in base else f"{base}&selected={product_no}"
|
||||
|
||||
|
||||
def _with_msg(back: str, *, msg: str = "", err: str = "") -> str:
|
||||
"""안내 문구를 쿼리에 붙인다. 문구 안의 &·#·% 가 주소를 깨지 않게 인코딩한다."""
|
||||
key, text = ("err", err) if err else ("msg", msg)
|
||||
return f"{back}&{key}={quote(text, safe='')}"
|
||||
|
||||
|
||||
def _run_description_write(
|
||||
st: Any,
|
||||
user: dict[str, Any],
|
||||
product_no: int,
|
||||
*,
|
||||
html: str,
|
||||
base_fingerprint: str,
|
||||
memo: str,
|
||||
list_query: str,
|
||||
origin: str,
|
||||
action: str,
|
||||
target_revision_id: int | None = None,
|
||||
) -> RedirectResponse:
|
||||
"""즉시 적용·버전 복원 공용 — writes.write_product 를 잠금 안에서 부르고 결과를 안내한다."""
|
||||
actor = str(user.get("email") or "")
|
||||
back = _back_url(product_no, list_query)
|
||||
verb = "복원" if origin == store.ORIGIN_ROLLBACK else "적용"
|
||||
api = build_cafe24_api(st)
|
||||
try:
|
||||
with writes.write_lock(
|
||||
st, writes.product_lock_key(product_no), actor=actor, purpose=f"상세설명 {verb}"
|
||||
) as lock:
|
||||
outcome = writes.write_product(
|
||||
st, api, product_no,
|
||||
lock=lock, origin=origin, actor=actor, html=html,
|
||||
base_fingerprint=base_fingerprint, target_revision_id=target_revision_id,
|
||||
memo=memo, skip_if_same=True,
|
||||
)
|
||||
except (writes.WriteSetupError, writes.WriteBusy, writes.WriteBlocked, writes.WriteConflict) as exc:
|
||||
detail = "충돌 — 편집 중 카페24 값이 변경됨" if isinstance(exc, writes.WriteConflict) else str(exc)
|
||||
writes.audit_safe(st, actor=actor, action=action, product_no=product_no,
|
||||
revision_id=exc.backup_id or None, result="FAIL", detail=detail)
|
||||
return RedirectResponse(url=_with_msg(back, err=str(exc)), status_code=303)
|
||||
except writes.RemoteWriteUnknown as exc:
|
||||
writes.audit_safe(st, actor=actor, action=action, product_no=product_no,
|
||||
revision_id=exc.backup_id or None, result="UNKNOWN",
|
||||
detail=f"시도 #{exc.attempt_id} 반영 여부 모름: {exc}")
|
||||
logger.warning("카페24 상품 %s %s 결과 모름(시도 #%s): %s", product_no, verb, exc.attempt_id, exc)
|
||||
return RedirectResponse(url=_with_msg(back, err=(
|
||||
f"카페24 응답을 받지 못해 {verb} 여부를 알 수 없습니다({exc}). 다시 {verb}하지 말고 "
|
||||
f"쇼핑몰에서 확인한 뒤 편집기 위 안내에서 결과를 확정하세요. "
|
||||
f"(직전 내용은 버전 {exc.backup_id} 로 보관됨)")), status_code=303)
|
||||
except writes.RemoteWriteFailed as exc:
|
||||
writes.audit_safe(st, actor=actor, action=action, product_no=product_no,
|
||||
revision_id=exc.backup_id or None, result="FAIL", detail=str(exc))
|
||||
logger.warning("카페24 상품 %s %s 실패: %s", product_no, verb, exc)
|
||||
return RedirectResponse(url=_with_msg(back, err=(
|
||||
f"{verb}에 실패했습니다: {exc} (직전 내용은 버전 {exc.backup_id} 로 보관됨)")), status_code=303)
|
||||
except Cafe24Error as exc:
|
||||
writes.audit_safe(st, actor=actor, action=action, product_no=product_no,
|
||||
result="FAIL", detail=f"현재값 조회 실패: {exc}")
|
||||
return RedirectResponse(url=_with_msg(back, err=f"카페24 현재값을 읽지 못해 중단했습니다: {exc}"),
|
||||
status_code=303)
|
||||
|
||||
if not outcome.changed:
|
||||
return RedirectResponse(url=_with_msg(back, msg=f"변경된 내용이 없어 {verb}하지 않았습니다."), status_code=303)
|
||||
|
||||
detail = (
|
||||
f"{len(html)}자 {verb} (백업 {outcome.backup_id}, 시도 #{outcome.attempt_id}, 모바일 PC와 동일 유지, "
|
||||
f"카페24 재조회 {'확인' if outcome.confirmed else '지연 — 마지막 적용값 표시'})"
|
||||
)
|
||||
if target_revision_id:
|
||||
detail += f" / 원본 버전 {target_revision_id}"
|
||||
if outcome.record_error:
|
||||
detail += f" / 기록 실패(자동 복구 예정): {outcome.record_error}"
|
||||
writes.audit_safe(st, actor=actor, action=action, product_no=product_no,
|
||||
revision_id=outcome.revision_id or None, result="SUCCESS", detail=detail)
|
||||
logger.info("카페24 상품 %s 상세설명 %s (%s, 재조회 확인=%s)", product_no, verb, actor, outcome.confirmed)
|
||||
note = "" if outcome.confirmed else " 카페24 관리자 API 반영은 잠시 늦을 수 있어 방금 적용한 내용을 표시합니다."
|
||||
if outcome.record_error:
|
||||
note += " ※ 카페24에는 반영됐지만 버전 기록 저장에 실패했습니다 — 자동으로 복구하니 다시 적용하지 마세요."
|
||||
return RedirectResponse(
|
||||
url=_with_msg(back, msg=f"카페24에 {verb}했습니다. 직전 내용은 버전 {outcome.backup_id} 로 보관됩니다.{note}"),
|
||||
status_code=303,
|
||||
)
|
||||
|
||||
|
||||
@products_router.post("/products/{product_no}/apply")
|
||||
def product_apply(
|
||||
request: Request,
|
||||
@@ -490,125 +613,165 @@ def product_apply(
|
||||
):
|
||||
"""편집한 HTML 을 카페24에 즉시 적용한다.
|
||||
|
||||
순서를 지키는 것이 이 함수의 핵심이다.
|
||||
1) 카페24에서 **현재** HTML 을 다시 읽는다(로컬 값을 현재값으로 믿지 않는다)
|
||||
2) 읽기 지연을 판정해 **유효 현재값**을 정한다(예전 값을 돌려주는 중이면
|
||||
우리 마지막 쓰기가 현재값이다)
|
||||
3) 그 값으로 BACKUP 버전을 남긴다 ← 유일한 복구 수단
|
||||
4) 편집 시작 시점의 지문과 비교해 충돌이면 거부한다
|
||||
5) 쓰고, 스냅샷·MANUAL 버전·감사로그를 남긴다
|
||||
순서(writes.write_product): 상품 잠금 → 카페24 현재값 재조회(로컬 값을 현재값으로
|
||||
믿지 않는다) → 결과 모르는 이전 시도 확인 → 유효 현재값(읽기 지연 보정) → BACKUP
|
||||
← 유일한 복구 수단 → 지문 대조(충돌 거부) → 시도 기록 → PUT → 버전·스냅샷 기록.
|
||||
|
||||
PC/모바일을 구분하지 않는다 — 두 필드에 같은 HTML 을 쓴다. 분리 사용 상품의
|
||||
모바일 내용이 PC 와 달랐다면 덮어쓰기 전에 그 내용도 BACKUP 으로 남긴다.
|
||||
PC/모바일을 구분하지 않는다 — description 만 쓰고 separated_mobile_description="F".
|
||||
분리 사용 상품의 모바일 내용이 PC 와 달랐다면 덮어쓰기 전에 그 내용도 BACKUP 으로 남긴다.
|
||||
"""
|
||||
checked = guard(request)
|
||||
if not isinstance(checked, tuple):
|
||||
return checked
|
||||
st, user = checked
|
||||
|
||||
actor = str(user.get("email") or "")
|
||||
# 적용 후에는 검색·필터를 유지한 채 같은 상품이 선택된 화면으로 돌아온다.
|
||||
base = f"/cafe24/?{list_query}" if list_query else f"/cafe24/?selected={product_no}"
|
||||
back = base if f"selected={product_no}" in base else f"{base}&selected={product_no}"
|
||||
|
||||
# 화면에서 보던 그대로(정리된 소스)를 카페24에 반영한다. 한글 이미지 경로는
|
||||
# 원래의 퍼센트 인코딩으로 되돌린다.
|
||||
submitted = store.format_html(store.encode_html_urls(html or ""))
|
||||
if not submitted.strip():
|
||||
return RedirectResponse(
|
||||
url=f"{back}&err=내용이 비어 있습니다. 상세페이지를 비우려면 카페24 관리자에서 하세요.",
|
||||
url=_with_msg(_back_url(product_no, list_query),
|
||||
err="내용이 비어 있습니다. 상세페이지를 비우려면 카페24 관리자에서 하세요."),
|
||||
status_code=303,
|
||||
)
|
||||
return _run_description_write(
|
||||
st, user, product_no,
|
||||
html=submitted, base_fingerprint=base_fingerprint, memo=memo, list_query=list_query,
|
||||
origin=store.ORIGIN_MANUAL, action="apply_description",
|
||||
)
|
||||
|
||||
api = build_cafe24_api(st)
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# 버전 이력 — 원문 확인 · 선택 복원
|
||||
# 자동 복원(예약 종료 후 되돌리기)은 쓰지 않는다. 사람이 버전을 골라 누를 때만
|
||||
# 정상 쓰기 경로(잠금·백업·지문 대조·시도 기록)로 한 번 적용하고 ROLLBACK 을 남긴다.
|
||||
# ════════════════════════════════════════════════════════════
|
||||
def _revision_for(st: Any, product_no: int, revision_id: int) -> dict[str, Any]:
|
||||
"""이 쇼핑몰·이 상품의 버전만 돌려준다. 아니면 404(다른 상품 버전을 주소로 못 끌어온다)."""
|
||||
from app.integrations.cafe24 import load_config # noqa: WPS433
|
||||
|
||||
revision = st.get_revision(revision_id)
|
||||
if not revision or int(revision.get("product_no") or 0) != int(product_no):
|
||||
raise HTTPException(status_code=404, detail="이 상품의 버전을 찾을 수 없습니다.")
|
||||
mall = load_config().mall_id
|
||||
rev_mall = str(revision.get("mall_id") or "")
|
||||
# mall_id 가 빈 행은 005 이전 기록이다 — cafe24_db 는 쇼핑몰 1개 전용이라 같은 쇼핑몰로 본다.
|
||||
if rev_mall and mall and rev_mall != mall:
|
||||
raise HTTPException(status_code=404, detail="다른 쇼핑몰의 버전입니다.")
|
||||
if int(revision.get("shop_no") or 1) != 1:
|
||||
raise HTTPException(status_code=404, detail="다른 멀티쇼핑몰(shop_no)의 버전입니다.")
|
||||
return revision
|
||||
|
||||
|
||||
@products_router.get("/products/{product_no}/revisions/{revision_id}")
|
||||
def revision_detail(request: Request, product_no: int, revision_id: int) -> dict[str, Any]:
|
||||
"""버전 원문(JSON). 화면은 textContent 로만 넣는다(HTML 로 해석하지 않는다)."""
|
||||
st, _user = require_store(request)
|
||||
revision = _revision_for(st, product_no, revision_id)
|
||||
body = str(revision.get("html_content") or "")
|
||||
rtype = str(revision.get("revision_type") or "")
|
||||
return {
|
||||
"ok": True,
|
||||
"revision": {
|
||||
"id": revision.get("id"),
|
||||
"product_no": revision.get("product_no"),
|
||||
"revision_type": rtype,
|
||||
"type_label": store.REVISION_LABELS.get(rtype, rtype),
|
||||
"source": revision.get("source") or "",
|
||||
"created_at": revision.get("created_at") or "",
|
||||
"created_by": revision.get("created_by") or "",
|
||||
"memo": revision.get("memo") or "",
|
||||
"length": len(body),
|
||||
# 편집기와 같은 표시(이미지 경로의 %EC… 를 한글로). 복원은 저장된 원문 그대로 쓴다.
|
||||
"html": store.decode_html_urls(body),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@products_router.post("/products/{product_no}/revisions/{revision_id}/restore")
|
||||
def revision_restore(
|
||||
request: Request,
|
||||
product_no: int,
|
||||
revision_id: int,
|
||||
base_fingerprint: str = Form(""),
|
||||
memo: str = Form(""),
|
||||
list_query: str = Form(""),
|
||||
):
|
||||
"""고른 버전을 카페24에 다시 적용한다(ROLLBACK). 즉시 적용과 같은 경로·같은 보호."""
|
||||
checked = guard(request)
|
||||
if not isinstance(checked, tuple):
|
||||
return checked
|
||||
st, user = checked
|
||||
back = _back_url(product_no, list_query)
|
||||
try:
|
||||
current = products.fetch_descriptions(api.client, product_no)
|
||||
except Cafe24Error as exc:
|
||||
st.log_audit(
|
||||
actor=actor, action="apply_description", product_no=product_no,
|
||||
result="FAIL", detail=f"현재값 조회 실패: {exc}",
|
||||
)
|
||||
return RedirectResponse(url=f"{back}&err=카페24 현재값을 읽지 못해 중단했습니다: {exc}", status_code=303)
|
||||
|
||||
# 읽기 지연 판정 — 카페24가 아직 예전 값을 돌려주면 우리 마지막 쓰기가 현재값이다.
|
||||
effective, sync_state, _ = resolve_description(st, product_no, current.description)
|
||||
pending = sync_state == store.SYNC_PENDING
|
||||
|
||||
backup_id = st.add_revision(
|
||||
product_no=product_no,
|
||||
html_content=effective,
|
||||
revision_type=store.REVISION_BACKUP,
|
||||
memo="적용 직전 자동 백업" + (" (카페24 읽기 지연 — 마지막 적용값 기준)" if pending else ""),
|
||||
created_by=actor,
|
||||
)
|
||||
# 모바일 내용이 PC 와 달랐다면 그것도 따로 남긴다. 아래에서 모바일을 PC 와 같게
|
||||
# 덮어쓰므로, 백업하지 않으면 그 내용을 되찾을 방법이 없다.
|
||||
if current.mobile_description and current.mobile_description != current.description:
|
||||
st.add_revision(
|
||||
product_no=product_no,
|
||||
html_content=current.mobile_description,
|
||||
revision_type=store.REVISION_BACKUP,
|
||||
memo="적용 직전 자동 백업 (모바일 — PC와 달랐던 내용)",
|
||||
created_by=actor,
|
||||
)
|
||||
|
||||
if base_fingerprint and base_fingerprint != store.fingerprint(effective):
|
||||
st.log_audit(
|
||||
actor=actor, action="apply_description", product_no=product_no,
|
||||
revision_id=backup_id, result="FAIL", detail="충돌 — 편집 중 카페24 값이 변경됨",
|
||||
)
|
||||
revision = _revision_for(st, product_no, revision_id)
|
||||
except HTTPException as exc:
|
||||
return RedirectResponse(url=_with_msg(back, err=str(exc.detail)), status_code=303)
|
||||
body = str(revision.get("html_content") or "")
|
||||
if not body.strip():
|
||||
return RedirectResponse(url=_with_msg(back, err="내용이 빈 버전은 복원할 수 없습니다."), status_code=303)
|
||||
if not base_fingerprint:
|
||||
# 편집기가 본 현재값 없이 복원하면 그 사이 바뀐 내용을 모르고 덮는다.
|
||||
return RedirectResponse(
|
||||
url=f"{back}&err=편집하는 동안 카페24 값이 변경되었습니다. 새로고침해 현재 내용을 확인한 뒤 다시 적용하세요.",
|
||||
status_code=303,
|
||||
url=_with_msg(back, err="편집기를 새로고침한 뒤 버전 이력에서 다시 복원하세요."), status_code=303
|
||||
)
|
||||
note = f"버전 {revision_id} 복원" + (f" — {memo.strip()}" if memo.strip() else "")
|
||||
return _run_description_write(
|
||||
st, user, product_no,
|
||||
html=body, base_fingerprint=base_fingerprint, memo=note, list_query=list_query,
|
||||
origin=store.ORIGIN_ROLLBACK, action="restore_revision", target_revision_id=int(revision_id),
|
||||
)
|
||||
|
||||
if submitted == effective:
|
||||
return RedirectResponse(url=f"{back}&msg=변경된 내용이 없어 적용하지 않았습니다.", status_code=303)
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# 반영 여부를 모르는 시도 — 사람이 쇼핑몰을 확인하고 확정한다
|
||||
# ════════════════════════════════════════════════════════════
|
||||
@products_router.post("/products/{product_no}/attempts/{attempt_id}/resolve")
|
||||
def attempt_resolve(
|
||||
request: Request,
|
||||
product_no: int,
|
||||
attempt_id: int,
|
||||
result: str = Form(""),
|
||||
list_query: str = Form(""),
|
||||
):
|
||||
"""applied = 반영됨(그 내용을 마지막 쓰기로 기록) / not_applied = 반영 안 됨(닫기).
|
||||
|
||||
예약에서 난 시도면 그 예약도 함께 완료/실패로 바꾼다. 다시 적용하는 것은 사람이
|
||||
편집기에서 한다(자동 재적용 없음).
|
||||
"""
|
||||
checked = guard(request)
|
||||
if not isinstance(checked, tuple):
|
||||
return checked
|
||||
st, user = checked
|
||||
actor = str(user.get("email") or "")
|
||||
back = _back_url(product_no, list_query)
|
||||
if result not in ("applied", "not_applied"):
|
||||
return RedirectResponse(url=_with_msg(back, err="확정할 결과를 고르세요."), status_code=303)
|
||||
open_states = (store.ATTEMPT_STARTED, store.ATTEMPT_UNKNOWN)
|
||||
try:
|
||||
# mobile_description 은 보내지 않는다 — update_descriptions 가
|
||||
# separated_mobile_description="F" 로 "PC 상세설명과 동일"을 강제하고
|
||||
# 카페24가 모바일 값을 자동으로 맞춰준다(모바일도 항상 PC와 같다).
|
||||
updated = products.update_descriptions(api.client, product_no, description=submitted)
|
||||
except Cafe24Error as exc:
|
||||
st.log_audit(
|
||||
actor=actor, action="apply_description", product_no=product_no,
|
||||
revision_id=backup_id, result="FAIL", detail=str(exc),
|
||||
)
|
||||
logger.warning("카페24 상품 %s 적용 실패: %s", product_no, exc)
|
||||
return RedirectResponse(
|
||||
url=f"{back}&err=적용에 실패했습니다: {exc} (직전 내용은 버전 {backup_id} 로 보관됨)",
|
||||
status_code=303,
|
||||
)
|
||||
|
||||
# PUT 응답은 쓰기 직후의 실제 값 — 스냅샷으로 남긴다(상품명·가격·updated_date 등).
|
||||
remember_write(st, product_no, updated if isinstance(updated, dict) else {})
|
||||
|
||||
# MANUAL revision 을 **먼저** 남긴다. 이것이 "마지막 쓰기" 기준이 되어, 카페24 GET 이
|
||||
# 한동안 예전 값을 돌려줘도 편집기는 방금 적용한 내용을 보여준다.
|
||||
revision_id = st.add_revision(
|
||||
product_no=product_no,
|
||||
html_content=submitted,
|
||||
revision_type=store.REVISION_MANUAL,
|
||||
memo=memo,
|
||||
created_by=actor,
|
||||
)
|
||||
|
||||
# 카페24 관리자 API 는 쓰기 직후 몇 초간 이전 값을 돌려줄 때가 있다(쇼핑몰
|
||||
# 화면에는 바로 반영됨). 여기서 짧게 확인만 한다 — 확인이 안 돼도 화면은 위
|
||||
# MANUAL revision 을 기준으로 그리므로 문제없다.
|
||||
confirmed = products.wait_for_description(api.client, product_no, submitted)
|
||||
|
||||
st.log_audit(
|
||||
actor=actor, action="apply_description", product_no=product_no,
|
||||
revision_id=revision_id, result="SUCCESS",
|
||||
detail=(
|
||||
f"{len(submitted)}자 적용 (백업 {backup_id}, 모바일 PC와 동일 유지, "
|
||||
f"카페24 재조회 {'확인' if confirmed else '지연 — 마지막 적용값 표시'})"
|
||||
),
|
||||
)
|
||||
logger.info("카페24 상품 %s 상세설명 적용 (%s, 재조회 확인=%s)", product_no, actor, confirmed)
|
||||
note = "" if confirmed else " 카페24 관리자 API 반영은 잠시 늦을 수 있어 방금 적용한 내용을 표시합니다."
|
||||
return RedirectResponse(
|
||||
url=f"{back}&msg=카페24에 적용했습니다. 직전 내용은 버전 {backup_id} 로 보관됩니다.{note}",
|
||||
status_code=303,
|
||||
)
|
||||
with writes.write_lock(st, writes.product_lock_key(product_no), actor=actor, purpose="적용 결과 확정"):
|
||||
attempt = st.get_attempt(attempt_id)
|
||||
if (not attempt or int(attempt.get("product_no") or 0) != int(product_no)
|
||||
or attempt.get("status") not in open_states):
|
||||
return RedirectResponse(url=_with_msg(back, err="이미 확정됐거나 없는 시도입니다."), status_code=303)
|
||||
schedule_id = attempt.get("schedule_id")
|
||||
if result == "applied":
|
||||
st.update_attempt(attempt_id, status=store.ATTEMPT_REMOTE_OK, remote_ok=True,
|
||||
resolved_by=actor, only_from=open_states)
|
||||
revision_id = writes.record_attempt(st, attempt)
|
||||
if schedule_id:
|
||||
st.review_schedule(int(schedule_id), status=store.STATUS_SUCCESS,
|
||||
note=f"{actor} 가 반영됨으로 확정", actor=actor, action="applied")
|
||||
text = f"시도 #{attempt_id} 를 반영됨으로 확정했습니다(버전 {revision_id})."
|
||||
else:
|
||||
st.update_attempt(attempt_id, status=store.ATTEMPT_ABANDONED, resolved_by=actor,
|
||||
only_from=open_states)
|
||||
if schedule_id:
|
||||
st.review_schedule(int(schedule_id), status=store.STATUS_FAILED,
|
||||
note=f"{actor} 가 반영 안 됨으로 확정", actor=actor, action="not_applied")
|
||||
text = f"시도 #{attempt_id} 를 반영 안 됨으로 확정했습니다. 필요하면 다시 적용하세요."
|
||||
except (writes.WriteBusy, writes.WriteSetupError) as exc:
|
||||
return RedirectResponse(url=_with_msg(back, err=str(exc)), status_code=303)
|
||||
writes.audit_safe(st, actor=actor, action=f"resolve_attempt:{result}", product_no=product_no,
|
||||
result="SUCCESS", detail=f"시도 #{attempt_id}")
|
||||
return RedirectResponse(url=_with_msg(back, msg=text), status_code=303)
|
||||
|
||||
@@ -22,9 +22,9 @@ import logging
|
||||
from fastapi import APIRouter, Form, Request
|
||||
from fastapi.responses import HTMLResponse, RedirectResponse
|
||||
|
||||
from app.integrations.cafe24 import Cafe24Error, build_cafe24_api, products
|
||||
from app.integrations.cafe24 import Cafe24Error, build_cafe24_api, load_config, products
|
||||
|
||||
from . import store
|
||||
from . import store, writes
|
||||
from .common import base_ctx, guard
|
||||
from .routes_products import _no_store
|
||||
|
||||
@@ -55,6 +55,7 @@ def schedules_page(request: Request) -> HTMLResponse:
|
||||
set_selling=row.get("set_selling"),
|
||||
),
|
||||
"editable": store.is_editable(row.get("status") or ""),
|
||||
"needs_review": row.get("status") == store.STATUS_NEEDS_REVIEW,
|
||||
}
|
||||
)
|
||||
|
||||
@@ -65,6 +66,7 @@ def schedules_page(request: Request) -> HTMLResponse:
|
||||
"page_subtitle": "지정 시각에 상세페이지·진열/판매 자동 적용",
|
||||
"rows": rows,
|
||||
"pending": sum(1 for r in rows if r["status"] == store.STATUS_PENDING),
|
||||
"review": sum(1 for r in rows if r["needs_review"]),
|
||||
"flash": request.query_params.get("msg", ""),
|
||||
"flash_error": request.query_params.get("err", ""),
|
||||
}
|
||||
@@ -114,6 +116,12 @@ def schedule_create(
|
||||
except ValueError as exc:
|
||||
return RedirectResponse(url=f"{back}&err={exc}", status_code=303)
|
||||
|
||||
# 예약은 worker 가 잠금·시도 기록(마이그레이션 005)으로 실행한다 — 없으면 등록도 받지 않는다.
|
||||
try:
|
||||
writes.require_schema(st)
|
||||
except writes.WriteSetupError as exc:
|
||||
return RedirectResponse(url=f"{back}&err={exc}", status_code=303)
|
||||
|
||||
revision_id: int | None = None
|
||||
if want_html:
|
||||
body = store.format_html(store.encode_html_urls(html or ""))
|
||||
@@ -127,6 +135,7 @@ def schedule_create(
|
||||
revision_type=store.REVISION_DRAFT,
|
||||
memo=f"예약 등록 ({run_at.strftime('%Y-%m-%d %H:%M')} 적용 예정)",
|
||||
created_by=actor,
|
||||
mall_id=load_config().mall_id,
|
||||
)
|
||||
|
||||
schedule_id = st.create_schedule(
|
||||
@@ -187,3 +196,51 @@ def schedule_current_flags(request: Request, product_no: int) -> dict:
|
||||
"display": normalized["display"],
|
||||
"selling": normalized["selling"],
|
||||
}
|
||||
|
||||
|
||||
# 확인 필요(NEEDS_REVIEW) 예약의 사람 확정 — 반영 여부를 모르는 채로 worker 가 멈춘 것.
|
||||
# applied = 쇼핑몰에 반영돼 있음(완료 + 버전 기록) / rerun = 다시 실행 / close = 실패로 종료.
|
||||
_REVIEW_ACTIONS = {
|
||||
"applied": (store.STATUS_SUCCESS, "반영됨으로 확정"),
|
||||
"rerun": (store.STATUS_PENDING, "다시 실행"),
|
||||
"close": (store.STATUS_FAILED, "실패로 종료"),
|
||||
}
|
||||
|
||||
|
||||
@schedules_router.post("/schedules/{schedule_id}/review")
|
||||
def schedule_review(request: Request, schedule_id: int, action: str = Form("")):
|
||||
"""확인 필요 예약을 확정한다. 자동으로 다시 실행하지 않는다 — 사람이 쇼핑몰을 보고 고른다."""
|
||||
checked = guard(request)
|
||||
if not isinstance(checked, tuple):
|
||||
return checked
|
||||
st, user = checked
|
||||
actor = str(user.get("email") or "")
|
||||
if action not in _REVIEW_ACTIONS:
|
||||
return RedirectResponse(url="/cafe24/schedules?err=확정할 동작을 고르세요.", status_code=303)
|
||||
status, label = _REVIEW_ACTIONS[action]
|
||||
row = st.get_schedule(schedule_id)
|
||||
if not row or row.get("status") != store.STATUS_NEEDS_REVIEW:
|
||||
return RedirectResponse(
|
||||
url=f"/cafe24/schedules?err=예약 #{schedule_id} 은 확인 필요 상태가 아닙니다.", status_code=303
|
||||
)
|
||||
product_no = int(row.get("product_no") or 0)
|
||||
try:
|
||||
with writes.write_lock(st, writes.product_lock_key(product_no), actor=actor, purpose="예약 결과 확정"):
|
||||
attempt = st.latest_attempt_for_schedule(schedule_id)
|
||||
open_attempt = attempt if attempt.get("status") in (store.ATTEMPT_STARTED, store.ATTEMPT_UNKNOWN) else {}
|
||||
if action == "applied":
|
||||
if not open_attempt:
|
||||
return RedirectResponse(
|
||||
url=f"/cafe24/schedules?err=예약 #{schedule_id} 에는 확정할 적용 시도가 없습니다 — "
|
||||
"다시 실행하거나 실패로 종료하세요.",
|
||||
status_code=303,
|
||||
)
|
||||
st.update_attempt(int(open_attempt["id"]), status=store.ATTEMPT_REMOTE_OK, remote_ok=True,
|
||||
resolved_by=actor,
|
||||
only_from=(store.ATTEMPT_STARTED, store.ATTEMPT_UNKNOWN))
|
||||
writes.record_attempt(st, open_attempt)
|
||||
st.review_schedule(schedule_id, status=status, note=f"{actor} — {label}", actor=actor, action=action)
|
||||
except (writes.WriteBusy, writes.WriteSetupError) as exc:
|
||||
return RedirectResponse(url=f"/cafe24/schedules?err={exc}", status_code=303)
|
||||
logger.info("카페24 예약 #%s 확인 필요 → %s (%s)", schedule_id, label, actor)
|
||||
return RedirectResponse(url=f"/cafe24/schedules?msg=예약 #{schedule_id} — {label}", status_code=303)
|
||||
|
||||
+228
-2
@@ -6,6 +6,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
from datetime import datetime, timedelta
|
||||
from urllib.parse import quote
|
||||
@@ -44,6 +45,9 @@ STATUS_PROCESSING = "PROCESSING"
|
||||
STATUS_SUCCESS = "SUCCESS"
|
||||
STATUS_FAILED = "FAILED"
|
||||
STATUS_CANCELLED = "CANCELLED"
|
||||
# 원격 반영 여부를 모른다(네트워크 끊김·worker 중단) — 사람이 카페24를 보고 확정한다.
|
||||
# 자동으로 PENDING 에 돌려 재적용하지 않는다(마이그레이션 005).
|
||||
STATUS_NEEDS_REVIEW = "NEEDS_REVIEW"
|
||||
|
||||
SCHEDULE_STATUSES: tuple[str, ...] = (
|
||||
STATUS_PENDING,
|
||||
@@ -51,6 +55,7 @@ SCHEDULE_STATUSES: tuple[str, ...] = (
|
||||
STATUS_SUCCESS,
|
||||
STATUS_FAILED,
|
||||
STATUS_CANCELLED,
|
||||
STATUS_NEEDS_REVIEW,
|
||||
)
|
||||
|
||||
SCHEDULE_STATUS_LABELS: dict[str, str] = {
|
||||
@@ -59,8 +64,36 @@ SCHEDULE_STATUS_LABELS: dict[str, str] = {
|
||||
STATUS_SUCCESS: "완료",
|
||||
STATUS_FAILED: "실패",
|
||||
STATUS_CANCELLED: "취소",
|
||||
STATUS_NEEDS_REVIEW: "확인 필요",
|
||||
}
|
||||
|
||||
# ── 쓰기 시도 상태 (cafe24_write_attempts.status, 마이그레이션 005) ──
|
||||
ATTEMPT_STARTED = "STARTED" # PUT 직전 기록. 이대로 남으면 결과를 모른다.
|
||||
ATTEMPT_REMOTE_OK = "REMOTE_OK" # 카페24 반영 성공, 로컬 버전 기록 전(기록 복구 필요)
|
||||
ATTEMPT_RECORDED = "RECORDED" # 반영 성공 + 버전 기록 완료
|
||||
ATTEMPT_REMOTE_FAILED = "REMOTE_FAILED" # 카페24가 거절 — 반영되지 않은 것이 확실
|
||||
ATTEMPT_UNKNOWN = "UNKNOWN" # 반영 여부 모름 → 사람 확인
|
||||
ATTEMPT_ABANDONED = "ABANDONED" # 사람이 "반영 안 됨"으로 확정 / 재실행으로 대체
|
||||
# 원격 반영이 확인된 시도 — 읽기 지연 판정의 근거는 이것뿐이다.
|
||||
ATTEMPT_CONFIRMED: tuple[str, ...] = (ATTEMPT_REMOTE_OK, ATTEMPT_RECORDED)
|
||||
# 결과 확정이 필요한 시도 — 이것이 남아 있으면 같은 상품 상세설명을 다시 쓰지 않는다.
|
||||
ATTEMPT_OPEN: tuple[str, ...] = (ATTEMPT_STARTED, ATTEMPT_REMOTE_OK, ATTEMPT_UNKNOWN)
|
||||
|
||||
ORIGIN_MANUAL = "MANUAL"
|
||||
ORIGIN_SCHEDULED = "SCHEDULED"
|
||||
ORIGIN_ROLLBACK = "ROLLBACK"
|
||||
# 시도 출처 → 성공 시 남길 버전 종류
|
||||
ORIGIN_REVISION_TYPE: dict[str, str] = {
|
||||
ORIGIN_MANUAL: "MANUAL",
|
||||
ORIGIN_SCHEDULED: "SCHEDULED",
|
||||
ORIGIN_ROLLBACK: "ROLLBACK",
|
||||
}
|
||||
|
||||
# ── BACKUP 출처 (cafe24_product_revisions.source) ──
|
||||
SOURCE_OBSERVED = "OBSERVED" # 카페24 GET 으로 읽은 값 그대로
|
||||
SOURCE_LAST_WRITE = "LAST_WRITE" # 카페24가 읽기 지연 중 — 우리 마지막(확인된) 쓰기를 현재값으로 봄
|
||||
SOURCE_REVISION = "REVISION" # ROLLBACK — 과거 버전을 그대로 다시 올림
|
||||
|
||||
# 사용자가 손댈 수 있는 상태 — PROCESSING/SUCCESS 는 임의 변경 금지
|
||||
EDITABLE_STATUSES: tuple[str, ...] = (STATUS_PENDING,)
|
||||
|
||||
@@ -509,11 +542,20 @@ def resolve_description(
|
||||
known_digests: set[str] | frozenset[str],
|
||||
grace_minutes: int,
|
||||
now: datetime | None = None,
|
||||
fetched_updated: object = None,
|
||||
) -> tuple[str, str]:
|
||||
"""(화면·적용에 쓸 유효 HTML, 상태) 를 돌려준다.
|
||||
|
||||
last_write: 최근 쓰기 revision — {"html_content", "created_at"}.
|
||||
known_digests: 유예시간 안의 revision 들의 내용 해시(`content_digest()` 결과) 집합.
|
||||
last_write: **원격 반영이 확인된** 마지막 쓰기 — {"html_content", "created_at",
|
||||
"remote_updated_at"(선택: 그 PUT 응답의 updated_date)}.
|
||||
known_digests: 확인된 쓰기들이 **덮어쓴 값**(쓰기 직전 관측값·기준값)과 쓴 값의
|
||||
내용 해시(`content_digest()`) 집합. 충돌로 거절된 적용의 백업, 예약 초안처럼
|
||||
카페24에 올라간 적 없는 값은 넣지 않는다 — 넣으면 관리자에서 직접 고친 값이
|
||||
우연히 그와 같을 때 "읽기 지연"으로 오판해 그 수정을 덮어쓴다.
|
||||
fetched_updated: 이번 GET 의 updated_date. 마지막 쓰기의 PUT 응답 updated_date 보다
|
||||
**뒤**라면 GET 은 우리 쓰기 이후의 레코드다 — 지연이 아니므로 카페24 값을 믿는다
|
||||
(관리자가 우리 적용 뒤 예전 값으로 되돌린 경우를 구분한다). 같거나 판단할 수
|
||||
없으면 내용 해시로 판정한다.
|
||||
"""
|
||||
if not last_write:
|
||||
return cafe24_html, SYNC_NONE
|
||||
@@ -523,11 +565,29 @@ def resolve_description(
|
||||
last_html = str(last_write.get("html_content") or "")
|
||||
if cafe24_html == last_html:
|
||||
return cafe24_html, SYNC_SYNCED
|
||||
fetched_at = _as_aware(fetched_updated)
|
||||
written_at = _as_aware(last_write.get("remote_updated_at"))
|
||||
if fetched_at is not None and written_at is not None and fetched_at > written_at:
|
||||
return cafe24_html, SYNC_EXTERNAL
|
||||
if content_digest(cafe24_html) in known_digests:
|
||||
return last_html, SYNC_PENDING
|
||||
return cafe24_html, SYNC_EXTERNAL
|
||||
|
||||
|
||||
def lineage_digests(lineage: list[dict]) -> set[str]:
|
||||
"""확인된 쓰기 목록 → 읽기 지연 판정에 쓸 내용 해시 집합.
|
||||
|
||||
각 쓰기의 직전 관측값(observed)·기준값(base)·쓴 값(target). 빈 해시는 뺀다.
|
||||
"""
|
||||
out: set[str] = set()
|
||||
for item in lineage or []:
|
||||
for key in ("observed_digest", "base_digest", "target_digest"):
|
||||
value = str(item.get(key) or "")
|
||||
if value:
|
||||
out.add(value)
|
||||
return out
|
||||
|
||||
|
||||
def content_digest(html: str) -> str:
|
||||
"""revision 내용 대조용 md5 hex — DB 의 `md5(html_content)` 와 같은 값.
|
||||
|
||||
@@ -598,6 +658,172 @@ def overlay_recent_write(
|
||||
return merged, True
|
||||
|
||||
|
||||
# ── 품목 스냅샷: 코드별 · 필드별 병합 ──
|
||||
# 스냅샷 모양: {variant_code: {필드: 값, ..., "_at": ISO, "_deleted": bool,
|
||||
# "options": [{name,value}...], "_options_before": [...]}}
|
||||
def merge_variant_snapshot(current: dict | None, patch: dict | None, *, at: str, replace: bool = False) -> dict:
|
||||
"""품목 스냅샷 병합.
|
||||
|
||||
- 같은 품목의 이전 필드는 유지하고 새로 쓴 필드만 덮는다. (예전에는 품목 단위로
|
||||
통째로 바꿔서, 자체코드를 고친 뒤 진열만 바꾸면 자체코드 기록이 사라졌다.)
|
||||
- replace=True 는 전체 초기화(옵션 삭제·재생성) — 이전 품목 기록을 모두 버린다.
|
||||
빈 patch({}) 를 "초기화" 로 해석하지 않는다(병합에서 {} 는 아무것도 안 바꾼다).
|
||||
- 삭제 표식(_deleted)은 한 번 붙으면 유지한다. 삭제 뒤에 늦게 도착한 수정이
|
||||
그 품목을 되살리지 않게 한다.
|
||||
- 품목마다 기록 시각(_at)을 남겨 유예시간을 품목별로 판정한다.
|
||||
"""
|
||||
base: dict = {} if replace else {
|
||||
str(code): dict(fields) for code, fields in (current or {}).items() if isinstance(fields, dict)
|
||||
}
|
||||
for code, fields in (patch or {}).items():
|
||||
if not isinstance(fields, dict):
|
||||
continue
|
||||
code = str(code)
|
||||
entry = base.get(code, {})
|
||||
if entry.get("_deleted") and not fields.get("_deleted"):
|
||||
continue # 삭제된 품목에 대한 늦은 수정 — 되살리지 않는다
|
||||
if fields.get("_deleted"):
|
||||
base[code] = {"_deleted": True, "_at": at}
|
||||
continue
|
||||
entry.update(fields)
|
||||
entry["_at"] = at
|
||||
base[code] = entry
|
||||
return base
|
||||
|
||||
|
||||
def _labels(options: object) -> list[tuple[str, str]]:
|
||||
if not isinstance(options, list):
|
||||
return []
|
||||
return [
|
||||
(str(o.get("name") or ""), str(o.get("value") or ""))
|
||||
for o in options if isinstance(o, dict)
|
||||
]
|
||||
|
||||
|
||||
def apply_variant_patch(
|
||||
variant: dict,
|
||||
patch: dict | None,
|
||||
*,
|
||||
section_written_at: object,
|
||||
grace_minutes: int,
|
||||
now: datetime | None = None,
|
||||
) -> dict | None:
|
||||
"""GET 품목 1건에 우리 쓰기 기록을 덮어씌운다. 삭제한 품목이면 None.
|
||||
|
||||
옵션 표기(options)는 **품목코드**(안정 식별자)로 짝지은 기록이다. 옵션값 이름을
|
||||
바꾼 직후 GET 품목이 아직 예전 이름을 돌려주면(읽기 지연) 이름으로는 짝이 안 맞아
|
||||
정상 품목이 "품목 없는 옵션값"으로 보였다. 그래서
|
||||
- GET 표기가 쓰기 직전 표기들(_options_before) 중 하나 → 지연 → 우리가 쓴 표기로
|
||||
- GET 표기 == 우리가 쓴 표기 → 이미 따라잡음
|
||||
- 둘 다 아님 → 관리자에서 다시 고침 → GET 을 믿는다
|
||||
_options_before 는 유예시간 안에 연달아 바꾼 이전 표기를 모두 담은 목록이다
|
||||
(A→B→C 직후 GET 이 A 를 돌려줘도 지연으로 본다).
|
||||
"""
|
||||
if not isinstance(patch, dict) or not patch:
|
||||
return variant
|
||||
at = patch.get("_at") or section_written_at
|
||||
if not within_grace(at, grace_minutes=grace_minutes, now=now):
|
||||
return variant
|
||||
if patch.get("_deleted"):
|
||||
return None
|
||||
out = dict(variant)
|
||||
for key, value in patch.items():
|
||||
if key.startswith("_") or key == "options":
|
||||
continue
|
||||
out[key] = value
|
||||
if "options" in patch:
|
||||
current = _labels(variant.get("options"))
|
||||
wanted = _labels(patch.get("options"))
|
||||
befores = label_history(patch.get("_options_before"))
|
||||
if current != wanted and (patch.get("_options_before") is None or current in befores):
|
||||
out["options"] = [{"name": n, "value": v} for n, v in wanted]
|
||||
return out
|
||||
|
||||
|
||||
def label_history(raw: object) -> list[list[tuple[str, str]]]:
|
||||
"""_options_before → 표기 목록의 목록. 옛 모양(표기 하나 = dict 목록)도 받는다."""
|
||||
if not isinstance(raw, list) or not raw:
|
||||
return []
|
||||
if all(isinstance(item, dict) for item in raw):
|
||||
return [_labels(raw)]
|
||||
return [_labels(item) for item in raw if isinstance(item, list)]
|
||||
|
||||
|
||||
def labels_as_json(options: object) -> list[dict]:
|
||||
"""표기(options) → 스냅샷 저장 모양 [{name, value}]."""
|
||||
return [{"name": n, "value": v} for n, v in _labels(options)]
|
||||
|
||||
|
||||
# ── 옵션 스냅샷: 쓰기 직전 모양과 비교해 지연/외부 변경을 가린다 ──
|
||||
def options_signature(option: object) -> str:
|
||||
"""옵션 dict 의 비교용 서명 — 옵션 사용 여부, 옵션명·표시방식, 옵션값 이름·이미지."""
|
||||
if not isinstance(option, dict):
|
||||
return ""
|
||||
raw = option.get("has_option")
|
||||
has = raw is True or str(raw or "").strip().upper() in ("T", "TRUE", "1", "Y")
|
||||
groups = []
|
||||
if has:
|
||||
for o in option.get("options") or []:
|
||||
if not isinstance(o, dict):
|
||||
continue
|
||||
values = [
|
||||
[str(v.get("option_text") or ""), str(v.get("option_image_file") or ""),
|
||||
str(v.get("option_link_image") or "")]
|
||||
for v in (o.get("option_value") or []) if isinstance(v, dict)
|
||||
]
|
||||
groups.append([str(o.get("option_name") or ""), str(o.get("option_display_type") or ""), values])
|
||||
return json.dumps([has, groups], ensure_ascii=False, sort_keys=True)
|
||||
|
||||
|
||||
def overlay_options(
|
||||
fetched: dict,
|
||||
*,
|
||||
snapshot: dict | None,
|
||||
written_at: object,
|
||||
grace_minutes: int,
|
||||
now: datetime | None = None,
|
||||
) -> tuple[dict, bool]:
|
||||
"""(보여줄 옵션 dict, 지연 여부). 스냅샷에 `_before_signatures`(쓰기 직전 모양들의
|
||||
서명 — 유예시간 안에 연달아 바꾼 이전 모양 포함)가 있으면 GET 이 그중 하나일 때만
|
||||
지연으로 본다 — 관리자에서 다시 고친 옵션을 유예시간 동안 덮지 않게.
|
||||
서명 목록이 없는 옛 스냅샷은 예전처럼 유예시간 안이면 스냅샷을 쓴다."""
|
||||
if not isinstance(snapshot, dict) or not snapshot:
|
||||
return fetched, False
|
||||
if not within_grace(written_at, grace_minutes=grace_minutes, now=now):
|
||||
return fetched, False
|
||||
got = options_signature(fetched)
|
||||
if got == options_signature(snapshot):
|
||||
return fetched, False
|
||||
befores = snapshot.get("_before_signatures")
|
||||
if isinstance(befores, list) and got not in befores:
|
||||
return fetched, False
|
||||
return snapshot, True
|
||||
|
||||
|
||||
# ── 예약 worker 가 lease 만료된 PROCESSING 을 복구할 때의 판정 ──
|
||||
RECOVER_SUCCESS = "SUCCESS" # 이미 반영·기록됨
|
||||
RECOVER_RECORD = "RECORD" # 반영됨 — 버전 기록만 채우고 SUCCESS
|
||||
RECOVER_RETRY = "RETRY" # 반영 안 됨이 확실 — 재시도 예산 안에서 다시 대기
|
||||
RECOVER_FAIL = "FAIL" # 반영 안 됨 + 재시도 예산 소진
|
||||
RECOVER_REVIEW = "REVIEW" # 반영 여부 모름 — NEEDS_REVIEW (자동 재적용 금지)
|
||||
|
||||
|
||||
def recovery_decision(attempt: dict | None, retry_count: object) -> tuple[str, str]:
|
||||
"""(판정, 사람이 읽을 사유). attempt 는 그 예약의 가장 최근 쓰기 시도(없으면 None)."""
|
||||
if not attempt:
|
||||
note = "worker 가 카페24에 쓰기 전에 중단되었습니다"
|
||||
return (RECOVER_RETRY if can_retry(retry_count) else RECOVER_FAIL), note
|
||||
status = str(attempt.get("status") or "")
|
||||
if status == ATTEMPT_RECORDED:
|
||||
return RECOVER_SUCCESS, "카페24 반영·기록이 끝난 뒤 중단되었습니다"
|
||||
if status == ATTEMPT_REMOTE_OK:
|
||||
return RECOVER_RECORD, "카페24에는 반영됐고 로컬 기록 전에 중단되었습니다"
|
||||
if status in (ATTEMPT_REMOTE_FAILED, ATTEMPT_ABANDONED):
|
||||
note = "카페24가 요청을 반영하지 않았습니다"
|
||||
return (RECOVER_RETRY if can_retry(retry_count) else RECOVER_FAIL), note
|
||||
return RECOVER_REVIEW, "카페24에 쓰는 도중 중단되어 반영 여부를 알 수 없습니다 — 쇼핑몰에서 확인하세요"
|
||||
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# 기본 정보(상품명·가격) 입력 검증 — 오른쪽 정보 패널
|
||||
# ════════════════════════════════════════════════════════════
|
||||
|
||||
@@ -14,6 +14,33 @@
|
||||
{# 읽기 지연 배너 — 카페24 관리자 API 가 아직 이전 값을 돌려주는 동안에는 마지막으로
|
||||
적용한 내용(MANUAL/SCHEDULED revision)을 편집기에 보여준다. 쇼핑몰 화면에는 이미
|
||||
반영돼 있다(실물 관찰). 지문도 이 값으로 만들어 다음 적용이 충돌로 오판되지 않는다. #}
|
||||
{# 반영 여부를 모르는 이전 적용 — 네트워크가 끊겼거나 처리 도중 멈춘 것. 확정 전에는 이 상품
|
||||
상세설명을 다시 쓰지 않는다(재적용 금지). 쇼핑몰을 보고 사람이 결과를 고른다.
|
||||
카페24 값이 그 적용 내용과 같아지면 다음 적용 때 자동으로 "반영됨"이 된다. #}
|
||||
{% for att in open_attempts or [] %}
|
||||
<div class="cf24-flash cf24-flash-err cf24-attempt" data-attempt-id="{{ att.id }}">
|
||||
<strong>적용 결과 확인 필요</strong> — {{ att.label }} · {{ att.status_label }}{% if att.error %} ({{ att.error }}){% endif %}.
|
||||
쇼핑몰 상세페이지를 열어 이 적용이 반영됐는지 확인한 뒤 고르세요. 확정하기 전에는 이 상품 상세설명을 다시 적용할 수 없습니다.
|
||||
<span class="cf24-attempt-actions">
|
||||
<form method="post" action="/cafe24/products/{{ product_no }}/attempts/{{ att.id }}/resolve" style="display:inline;"
|
||||
data-erp-confirm="쇼핑몰에서 이 적용 내용이 보이는 것을 확인했나요? 반영됨으로 기록합니다.">
|
||||
<input type="hidden" name="result" value="applied" />
|
||||
<input type="hidden" name="list_query" value="{{ list_query }}" />
|
||||
<button type="submit" class="erp-btn erp-btn-outline cf24-btn-inline">반영됨</button>
|
||||
</form>
|
||||
<form method="post" action="/cafe24/products/{{ product_no }}/attempts/{{ att.id }}/resolve" style="display:inline;"
|
||||
data-erp-confirm="이 적용이 쇼핑몰에 반영되지 않은 것을 확인했나요? 반영 안 됨으로 닫습니다(다시 적용은 직접 하세요).">
|
||||
<input type="hidden" name="result" value="not_applied" />
|
||||
<input type="hidden" name="list_query" value="{{ list_query }}" />
|
||||
<button type="submit" class="erp-btn erp-btn-outline cf24-btn-inline">반영 안 됨</button>
|
||||
</form>
|
||||
</span>
|
||||
</div>
|
||||
{% endfor %}
|
||||
|
||||
{# 적용·예약이 오류로 돌아왔을 때 브라우저에 남겨 둔 편집본을 여기서 되살린다(products.html JS). #}
|
||||
<div id="cf24-draft-slot"></div>
|
||||
|
||||
{% if sync_pending %}
|
||||
<div class="cf24-flash cf24-flash-warn" id="cf24-sync-banner">
|
||||
<strong>카페24 반영 대기 중</strong> — 카페24 관리자 API 가 아직 이전 소스를 돌려주고 있어
|
||||
@@ -199,28 +226,40 @@
|
||||
</form>
|
||||
</details>
|
||||
|
||||
<details class="cf24-details">
|
||||
<details class="cf24-details" id="cf24-history">
|
||||
<summary>버전 이력 {% if revisions %}({{ revisions | length }}건){% endif %}</summary>
|
||||
{% if revisions %}
|
||||
<div class="cf24-scroll">
|
||||
<table class="erp-table cf24-compact">
|
||||
<thead>
|
||||
<tr><th>시각</th><th>유형</th><th>길이</th><th>작업자</th><th>메모</th></tr>
|
||||
<tr><th>시각</th><th>유형</th><th>길이</th><th>작업자</th><th>메모</th><th></th></tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{% for rev in revisions %}
|
||||
<tr>
|
||||
<td class="cf24-nowrap">{{ rev.created_at }}</td>
|
||||
<td class="cf24-nowrap"><code>{{ rev.revision_type }}</code></td>
|
||||
<td class="cf24-nowrap" title="{{ rev.type_label }}">
|
||||
<code>{{ rev.revision_type }}</code>
|
||||
{% if rev.source == 'LAST_WRITE' %}<span class="cf24-muted" title="카페24가 읽기 지연 중이라 마지막으로 확인된 적용값을 백업했습니다">지연</span>{% endif %}
|
||||
</td>
|
||||
<td class="cf24-nowrap">{{ rev.html_length }}자</td>
|
||||
<td class="cf24-nowrap">{{ rev.created_by or '—' }}</td>
|
||||
<td>{{ rev.memo or '' }}</td>
|
||||
<td class="cf24-nowrap">
|
||||
{% if rev.html_length %}
|
||||
<button type="button" class="erp-btn erp-btn-outline cf24-btn-inline" data-rev-view="{{ rev.id }}">원문</button>
|
||||
{% endif %}
|
||||
</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<p class="cf24-muted">버전 선택 복원은 Phase 6 에서 붙습니다. 내용은 모두 보관됩니다.</p>
|
||||
<p class="cf24-muted">
|
||||
「원문」에서 그 버전의 소스를 확인·복사하고, 필요하면 「이 버전으로 복원」으로 카페24에 다시 적용합니다.
|
||||
복원도 적용과 같은 순서(현재값 재조회 → 직전 내용 자동 백업 → 편집 중 변경 확인)를 거치며 이력에
|
||||
<code>ROLLBACK</code> 으로 남습니다. 자동 복원(예약 종료 후 되돌리기)은 쓰지 않습니다.
|
||||
</p>
|
||||
{% else %}
|
||||
<p class="cf24-muted">아직 이 상품의 변경 이력이 없습니다.</p>
|
||||
{% endif %}
|
||||
|
||||
@@ -13,7 +13,7 @@
|
||||
<div class="erp-card cf24-card">
|
||||
<div class="cf24-card-head">
|
||||
<h3>예약 목록</h3>
|
||||
<span class="cf24-muted">대기 {{ pending }}건 · 최근 200건</span>
|
||||
<span class="cf24-muted">대기 {{ pending }}건{% if review %} · <strong class="cf24-err">확인 필요 {{ review }}건</strong>{% endif %} · 최근 200건</span>
|
||||
</div>
|
||||
|
||||
<p class="cf24-note">
|
||||
@@ -22,6 +22,11 @@
|
||||
적용 직전 내용은 상품별 <code>BACKUP</code> 버전으로 보관됩니다.
|
||||
<strong>대기</strong> 상태인 예약만 취소할 수 있습니다.
|
||||
</p>
|
||||
<p class="cf24-note">
|
||||
<strong>확인 필요</strong> — 카페24에 쓰는 도중 응답이 끊겼거나 worker 가 멈춰 반영 여부를 알 수 없는 예약입니다.
|
||||
자동으로 다시 실행하지 않습니다. 쇼핑몰에서 상세페이지·진열/판매를 확인한 뒤
|
||||
「반영됨」(완료로 기록) · 「다시 실행」 · 「실패로 종료」 중 하나를 고르세요.
|
||||
</p>
|
||||
|
||||
{% if rows %}
|
||||
<div class="cf24-scroll">
|
||||
@@ -53,12 +58,13 @@
|
||||
{% if r.status == 'SUCCESS' %}<span class="erp-badge cf24-badge-ok">{{ r.status_label }}</span>
|
||||
{% elif r.status == 'FAILED' %}<span class="cf24-err">{{ r.status_label }}</span>
|
||||
{% elif r.status == 'PENDING' %}<span class="cf24-warn">{{ r.status_label }}</span>
|
||||
{% elif r.status == 'NEEDS_REVIEW' %}<span class="erp-badge cf24-badge-off">{{ r.status_label }}</span>
|
||||
{% else %}<span class="cf24-muted">{{ r.status_label }}</span>{% endif %}
|
||||
{% if r.retry_count %}<span class="cf24-muted">({{ r.retry_count }}회)</span>{% endif %}
|
||||
</td>
|
||||
<td>
|
||||
{{ r.memo or '' }}
|
||||
{% if r.last_error %}<div class="cf24-err">{{ r.last_error }}</div>{% endif %}
|
||||
{% if r.last_error %}<div class="{{ 'cf24-muted' if r.status == 'SUCCESS' else 'cf24-err' }}">{{ r.last_error }}</div>{% endif %}
|
||||
</td>
|
||||
<td class="cf24-nowrap">{{ r.created_by or '—' }}</td>
|
||||
<td class="cf24-nowrap">
|
||||
@@ -67,6 +73,22 @@
|
||||
data-erp-confirm="예약 #{{ r.id }} 을 취소할까요?">
|
||||
<button type="submit" class="erp-btn erp-btn-outline">취소</button>
|
||||
</form>
|
||||
{% elif r.needs_review %}
|
||||
<form method="post" action="/cafe24/schedules/{{ r.id }}/review" class="cf24-review-form"
|
||||
data-erp-confirm="쇼핑몰에서 반영된 것을 확인했나요? 예약 #{{ r.id }} 을 완료로 기록합니다.">
|
||||
<input type="hidden" name="action" value="applied" />
|
||||
<button type="submit" class="erp-btn erp-btn-outline">반영됨</button>
|
||||
</form>
|
||||
<form method="post" action="/cafe24/schedules/{{ r.id }}/review" class="cf24-review-form"
|
||||
data-erp-confirm="예약 #{{ r.id }} 을 다시 실행합니다. 이미 반영돼 있었다면 같은 내용을 한 번 더 적용합니다. 계속할까요?">
|
||||
<input type="hidden" name="action" value="rerun" />
|
||||
<button type="submit" class="erp-btn erp-btn-outline">다시 실행</button>
|
||||
</form>
|
||||
<form method="post" action="/cafe24/schedules/{{ r.id }}/review" class="cf24-review-form"
|
||||
data-erp-confirm="예약 #{{ r.id }} 을 실패로 종료할까요?">
|
||||
<input type="hidden" name="action" value="close" />
|
||||
<button type="submit" class="erp-btn erp-btn-outline">실패로 종료</button>
|
||||
</form>
|
||||
{% endif %}
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
@@ -0,0 +1,523 @@
|
||||
"""카페24 모듈 단위 테스트용 대역 — 메모리 저장소 · 가짜 카페24 · 가짜 FTP.
|
||||
|
||||
실제 DB 의 동작(잠금 만료, SKIP LOCKED, JSONB 병합 등)은 이 대역으로 증명되지 않는다.
|
||||
그 부분은 test_cafe24_db.py(격리된 로컬 PostgreSQL)가 검증한다. 여기서는 쓰기 순서와
|
||||
분기(백업·충돌·결과 분류·복구 판정)를 빠르게 확인한다.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import copy
|
||||
import ftplib
|
||||
import itertools
|
||||
import uuid
|
||||
from contextlib import contextmanager
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Any
|
||||
|
||||
from app.integrations.cafe24.errors import Cafe24ApiError
|
||||
from app.modules.cafe24 import store
|
||||
from app.timezone import KST, now_kst
|
||||
|
||||
|
||||
class MemoryStore:
|
||||
"""Cafe24Store 가 writes/worker/라우터에 주는 메서드를 메모리로 흉내낸다."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self._ids = itertools.count(1)
|
||||
self.revisions: dict[int, dict[str, Any]] = {}
|
||||
self.attempts: dict[int, dict[str, Any]] = {}
|
||||
self.locks: dict[str, dict[str, Any]] = {}
|
||||
self.schedules: dict[int, dict[str, Any]] = {}
|
||||
self.snapshots: dict[int, dict[str, Any]] = {}
|
||||
self.audits: list[dict[str, Any]] = []
|
||||
self.products: dict[int, dict[str, Any]] = {}
|
||||
self.fail_on: set[str] = set() # 이 메서드 이름이 들어 있으면 예외(기록 실패 재현)
|
||||
self.schema_ok = True
|
||||
|
||||
def _maybe_fail(self, name: str) -> None:
|
||||
if name in self.fail_on:
|
||||
raise RuntimeError(f"DB 장애({name})")
|
||||
|
||||
# ── 스키마 ──
|
||||
def write_schema_ready(self) -> bool:
|
||||
return self.schema_ok
|
||||
|
||||
# ── 잠금 ──
|
||||
def acquire_lock(self, key, *, owner, purpose, ttl_seconds):
|
||||
now = now_kst()
|
||||
held = self.locks.get(key)
|
||||
if held and held["expires_at"] > now:
|
||||
return None
|
||||
token = uuid.uuid4().hex
|
||||
self.locks[key] = {"owner": owner, "purpose": purpose, "token": token,
|
||||
"expires_at": now + timedelta(seconds=ttl_seconds)}
|
||||
return token
|
||||
|
||||
def renew_lock(self, key, token, *, ttl_seconds):
|
||||
held = self.locks.get(key)
|
||||
if not held or held["token"] != token or held["expires_at"] <= now_kst():
|
||||
return False
|
||||
held["expires_at"] = now_kst() + timedelta(seconds=ttl_seconds)
|
||||
return True
|
||||
|
||||
def release_lock(self, key, token):
|
||||
if self.locks.get(key, {}).get("token") == token:
|
||||
del self.locks[key]
|
||||
|
||||
def lock_holder(self, key):
|
||||
held = self.locks.get(key)
|
||||
return dict(held) if held and held["expires_at"] > now_kst() else {}
|
||||
|
||||
def expire_lock(self, key):
|
||||
if key in self.locks:
|
||||
self.locks[key]["expires_at"] = now_kst() - timedelta(seconds=1)
|
||||
|
||||
# ── 버전 ──
|
||||
def add_revision(self, *, product_no, html_content, revision_type, memo="", created_by="",
|
||||
mall_id="", shop_no=1, source="", source_revision_id=None):
|
||||
self._maybe_fail("add_revision")
|
||||
rid = next(self._ids)
|
||||
self.revisions[rid] = {
|
||||
"id": rid, "product_no": int(product_no), "html_content": html_content or "",
|
||||
"revision_type": store.normalize_revision_type(revision_type), "memo": memo,
|
||||
"created_by": created_by, "mall_id": mall_id, "shop_no": shop_no, "source": source,
|
||||
"source_revision_id": source_revision_id, "created_at": now_kst().isoformat(),
|
||||
}
|
||||
return rid
|
||||
|
||||
def get_revision(self, revision_id):
|
||||
return dict(self.revisions.get(int(revision_id), {}))
|
||||
|
||||
def list_revisions(self, product_no, *, limit=20):
|
||||
rows = [dict(r, html_length=len(r["html_content"])) for r in self.revisions.values()
|
||||
if r["product_no"] == int(product_no)]
|
||||
return sorted(rows, key=lambda r: -r["id"])[:limit]
|
||||
|
||||
def of_type(self, revision_type):
|
||||
return [r for r in self.revisions.values() if r["revision_type"] == revision_type]
|
||||
|
||||
# ── 쓰기 시도 ──
|
||||
def start_attempt(self, **fields):
|
||||
self._maybe_fail("start_attempt")
|
||||
aid = next(self._ids)
|
||||
row = {"id": aid, "status": store.ATTEMPT_STARTED, "error": "", "remote_updated_at": "",
|
||||
"remote_at": None, "resolved_by": "", "applied_revision_id": None,
|
||||
"created_at": now_kst(), "target_html": "", "target_revision_id": None,
|
||||
"observed_digest": "", "base_digest": "", "target_digest": "", "schedule_id": None,
|
||||
"set_display": None, "set_selling": None, "memo": "", "actor": "", "origin": "MANUAL"}
|
||||
row.update(fields)
|
||||
self.attempts[aid] = row
|
||||
return aid
|
||||
|
||||
def update_attempt(self, attempt_id, *, status=None, error=None, remote_updated_at=None,
|
||||
remote_ok=False, resolved_by=None, only_from=None):
|
||||
self._maybe_fail("update_attempt")
|
||||
row = self.attempts.get(int(attempt_id))
|
||||
if not row or (only_from and row["status"] not in only_from):
|
||||
return False
|
||||
if status is not None:
|
||||
row["status"] = status
|
||||
if error is not None:
|
||||
row["error"] = error
|
||||
if remote_updated_at is not None:
|
||||
row["remote_updated_at"] = remote_updated_at
|
||||
if remote_ok and row["remote_at"] is None:
|
||||
row["remote_at"] = now_kst()
|
||||
if resolved_by is not None:
|
||||
row["resolved_by"] = resolved_by
|
||||
return True
|
||||
|
||||
def record_attempt_revision(self, attempt_id, *, revision_type, memo, created_by, source="",
|
||||
source_revision_id=None):
|
||||
self._maybe_fail("record_attempt_revision")
|
||||
row = self.attempts[int(attempt_id)]
|
||||
if row.get("applied_revision_id"):
|
||||
return row["applied_revision_id"]
|
||||
body = row.get("target_html") or self.revisions.get(row.get("target_revision_id") or 0, {}).get("html_content", "")
|
||||
rid = self.add_revision(product_no=row["product_no"], html_content=body, revision_type=revision_type,
|
||||
memo=memo, created_by=created_by, mall_id=row.get("mall_id", ""),
|
||||
source=source, source_revision_id=source_revision_id)
|
||||
row.update(status=store.ATTEMPT_RECORDED, applied_revision_id=rid, target_html="")
|
||||
if row["remote_at"] is None:
|
||||
row["remote_at"] = now_kst()
|
||||
return rid
|
||||
|
||||
def get_attempt(self, attempt_id):
|
||||
return dict(self.attempts.get(int(attempt_id), {}))
|
||||
|
||||
def latest_attempt_for_schedule(self, schedule_id):
|
||||
rows = [a for a in self.attempts.values() if a.get("schedule_id") == int(schedule_id)]
|
||||
return dict(max(rows, key=lambda a: a["id"])) if rows else {}
|
||||
|
||||
def open_attempts(self, product_no, *, since):
|
||||
return [dict(a) for a in sorted(self.attempts.values(), key=lambda a: a["id"])
|
||||
if a["product_no"] == int(product_no) and a["status"] in store.ATTEMPT_OPEN
|
||||
and a["created_at"] >= since]
|
||||
|
||||
def attempts_needing_record(self, *, since, limit=20):
|
||||
return [dict(a) for a in self.attempts.values()
|
||||
if a["status"] == store.ATTEMPT_REMOTE_OK and a["created_at"] >= since][:limit]
|
||||
|
||||
def write_lineage(self, product_no, *, since, limit=30):
|
||||
rows = [a for a in self.attempts.values()
|
||||
if a["product_no"] == int(product_no) and a["status"] in store.ATTEMPT_CONFIRMED
|
||||
and a["target_digest"] and a["remote_at"] and a["remote_at"] >= since]
|
||||
rows.sort(key=lambda a: (a["remote_at"], a["id"]), reverse=True)
|
||||
out = []
|
||||
for i, a in enumerate(rows[:limit]):
|
||||
body = ""
|
||||
if i == 0:
|
||||
body = (a.get("target_html")
|
||||
or self.revisions.get(a.get("applied_revision_id") or 0, {}).get("html_content")
|
||||
or self.revisions.get(a.get("target_revision_id") or 0, {}).get("html_content") or "")
|
||||
out.append({**a, "created_at": a["remote_at"], "created_by": a.get("actor", ""), "html_content": body})
|
||||
return out
|
||||
|
||||
# ── 상품 캐시 · 스냅샷 ──
|
||||
def upsert_products(self, rows):
|
||||
self._maybe_fail("upsert_products")
|
||||
for r in rows:
|
||||
self.products[int(r["product_no"])] = dict(r)
|
||||
return len(rows)
|
||||
|
||||
def save_write_snapshot(self, product_no, section, data, *, replace=False):
|
||||
self._maybe_fail("save_write_snapshot")
|
||||
at = now_kst().isoformat(timespec="seconds")
|
||||
current = self.snapshots.setdefault(int(product_no), {})
|
||||
if section == "variants":
|
||||
previous = (current.get("variants") or {}).get("data") or {}
|
||||
data = store.merge_variant_snapshot(previous, data, at=at, replace=replace)
|
||||
current[section] = {"data": data, "written_at": at}
|
||||
|
||||
def get_write_snapshot(self, product_no):
|
||||
return dict(self.snapshots.get(int(product_no), {}))
|
||||
|
||||
# ── 예약 ──
|
||||
def add_schedule(self, **fields):
|
||||
sid = next(self._ids)
|
||||
row = {"id": sid, "product_no": 131, "revision_id": None, "set_display": None, "set_selling": None,
|
||||
"status": store.STATUS_PENDING, "retry_count": 0, "next_retry_at": None, "last_error": "",
|
||||
"scheduled_at": now_kst() - timedelta(minutes=1), "lease_token": "", "lease_owner": "",
|
||||
"lease_expires_at": None, "started_at": None}
|
||||
row.update(fields)
|
||||
self.schedules[sid] = row
|
||||
return sid
|
||||
|
||||
def claim_due_schedule(self, *, now, owner, ttl_seconds):
|
||||
due = [s for s in sorted(self.schedules.values(), key=lambda s: (s["scheduled_at"], s["id"]))
|
||||
if s["status"] == store.STATUS_PENDING and s["scheduled_at"] <= now
|
||||
and (s["next_retry_at"] is None or s["next_retry_at"] <= now)]
|
||||
if not due:
|
||||
return None
|
||||
row = due[0]
|
||||
row.update(status=store.STATUS_PROCESSING, lease_owner=owner, lease_token=uuid.uuid4().hex,
|
||||
lease_expires_at=now_kst() + timedelta(seconds=ttl_seconds), started_at=now_kst(),
|
||||
last_error="")
|
||||
return dict(row)
|
||||
|
||||
def claim_expired_schedules(self, *, owner, ttl_seconds, legacy_minutes, limit=20):
|
||||
out = []
|
||||
for row in self.schedules.values():
|
||||
if row["status"] != store.STATUS_PROCESSING:
|
||||
continue
|
||||
expired = row["lease_expires_at"] is not None and row["lease_expires_at"] < now_kst()
|
||||
legacy = row["lease_expires_at"] is None and (row["started_at"] or now_kst()) < now_kst() - timedelta(minutes=legacy_minutes)
|
||||
if expired or legacy:
|
||||
row.update(lease_owner=owner, lease_token=uuid.uuid4().hex,
|
||||
lease_expires_at=now_kst() + timedelta(seconds=ttl_seconds))
|
||||
out.append(dict(row))
|
||||
return out[:limit]
|
||||
|
||||
def renew_schedule_lease(self, schedule_id, token, *, ttl_seconds):
|
||||
row = self.schedules.get(int(schedule_id))
|
||||
if (not row or row["status"] != store.STATUS_PROCESSING or row["lease_token"] != token
|
||||
or row["lease_expires_at"] <= now_kst()):
|
||||
return False
|
||||
row["lease_expires_at"] = now_kst() + timedelta(seconds=ttl_seconds)
|
||||
return True
|
||||
|
||||
def finish_schedule(self, schedule_id, *, token, status, error="", next_retry_at=None, retry_count=None):
|
||||
self._maybe_fail("finish_schedule")
|
||||
row = self.schedules.get(int(schedule_id))
|
||||
if not row or row["status"] != store.STATUS_PROCESSING or row["lease_token"] != token:
|
||||
return False
|
||||
row.update(status=store.normalize_schedule_status(status), last_error=error, next_retry_at=next_retry_at,
|
||||
lease_token="", lease_owner="", lease_expires_at=None)
|
||||
if retry_count is not None:
|
||||
row["retry_count"] = retry_count
|
||||
return True
|
||||
|
||||
def expire_schedule_lease(self, schedule_id):
|
||||
self.schedules[int(schedule_id)]["lease_expires_at"] = now_kst() - timedelta(seconds=1)
|
||||
|
||||
def get_schedule(self, schedule_id):
|
||||
return dict(self.schedules.get(int(schedule_id), {}))
|
||||
|
||||
def review_schedule(self, schedule_id, *, status, note, actor, action):
|
||||
row = self.schedules.get(int(schedule_id))
|
||||
if not row or row["status"] != store.STATUS_NEEDS_REVIEW:
|
||||
return {}
|
||||
row.update(status=status, last_error=note,
|
||||
next_retry_at=now_kst() if status == store.STATUS_PENDING else None)
|
||||
if status != store.STATUS_SUCCESS:
|
||||
for a in self.attempts.values():
|
||||
if a.get("schedule_id") == int(schedule_id) and a["status"] in (store.ATTEMPT_STARTED, store.ATTEMPT_UNKNOWN):
|
||||
a.update(status=store.ATTEMPT_ABANDONED, resolved_by=actor)
|
||||
return dict(row)
|
||||
|
||||
# ── 감사 ──
|
||||
def log_audit(self, **fields):
|
||||
self._maybe_fail("log_audit")
|
||||
self.audits.append(fields)
|
||||
|
||||
def log_api_call(self, **_fields):
|
||||
pass
|
||||
|
||||
|
||||
class FakeConfig:
|
||||
mall_id = "testmall"
|
||||
shop_base = "https://testmall.cafe24.com"
|
||||
|
||||
def product_url(self, no):
|
||||
return f"https://testmall.cafe24.com/product/detail.html?product_no={no}"
|
||||
|
||||
|
||||
class FakeCafe24:
|
||||
"""카페24 상품 API 대역 — 상세설명·진열/판매·updated_date 를 들고 있고,
|
||||
읽기 지연(lag)·PUT 실패·응답 유실을 흉내낸다."""
|
||||
|
||||
def __init__(self, description: str = "<p>A</p>", *, product_no: int = 131):
|
||||
self.product_no = product_no
|
||||
self.state = {"product_no": product_no, "product_name": "상품", "product_code": "P000000B",
|
||||
"description": description, "mobile_description": description,
|
||||
"separated_mobile_description": "F", "display": "T", "selling": "T",
|
||||
"updated_date": "2026-09-30T10:00:00+09:00"}
|
||||
self.stale: dict | None = None # 설정하면 GET 이 이 값을 돌려준다(읽기 지연)
|
||||
self.put_error: Exception | None = None
|
||||
self.put_error_after_apply = False # True 면 반영한 뒤 오류(응답 유실)
|
||||
self.calls: list[tuple] = []
|
||||
self._clock = 0
|
||||
self.option: dict = {"has_option": "F", "options": []}
|
||||
self.variants: list = []
|
||||
self.stale_option: dict | None = None # 설정하면 GET options 가 이 값을 돌려준다
|
||||
self.stale_variants: list | None = None # 설정하면 GET variants 가 이 값을 돌려준다
|
||||
self.hidden_variants = 0 # 새로 생긴 품목이 GET 에 늦게 나타나는 횟수
|
||||
self.fail_variant_chunk = 0 # n번째 PUT variants 묶음을 실패시킨다
|
||||
self.variant_error: Exception | None = None
|
||||
self._variant_puts = 0
|
||||
self._code_seq = 0
|
||||
|
||||
def external_edit(self, description: str) -> None:
|
||||
"""카페24 관리자에서 사람이 직접 고친 것."""
|
||||
self._tick()
|
||||
self.state.update(description=description, mobile_description=description)
|
||||
|
||||
def _tick(self) -> None:
|
||||
self._clock += 1
|
||||
self.state["updated_date"] = (datetime(2026, 9, 30, 10, 0, tzinfo=KST)
|
||||
+ timedelta(minutes=self._clock)).isoformat()
|
||||
|
||||
# Cafe24Client 흉내 — products.* 래퍼가 부르는 get/put
|
||||
def get(self, path, **kw):
|
||||
self.calls.append(("GET", path))
|
||||
if path == f"/admin/products/{self.product_no}":
|
||||
return {"product": dict(self.stale if self.stale is not None else self.state)}
|
||||
out = self._options_call("GET", path, None)
|
||||
return copy.deepcopy(out) if out is not None else {}
|
||||
|
||||
# ── 옵션 / 품목 ── (상태는 __init__ 에서 만든다)
|
||||
|
||||
def _new_code(self) -> str:
|
||||
self._code_seq += 1
|
||||
return f"P000000B{self._code_seq:04X}"
|
||||
|
||||
def _options_call(self, method, path, json):
|
||||
no = self.product_no
|
||||
req = (json or {}).get("request") or {}
|
||||
if path == f"/admin/products/{no}/options":
|
||||
if method == "GET":
|
||||
return {"option": self.stale_option if self.stale_option is not None else self.option}
|
||||
if method == "POST":
|
||||
opt = req["options"][0]
|
||||
values = [{"option_text": v["option_text"], "value_no": i + 1} for i, v in enumerate(opt["option_value"])]
|
||||
self.option = {"has_option": "T", "option_type": "T", "option_list_type": "S",
|
||||
"options": [{"option_name": opt["option_name"], "option_code": "O1",
|
||||
"option_display_type": opt.get("option_display_type", "S"),
|
||||
"option_value": values}]}
|
||||
self.variants = [{"variant_code": self._new_code(), "options": [{"name": opt["option_name"], "value": v["option_text"]}],
|
||||
"custom_variant_code": "", "additional_amount": "0.00", "display": "T", "selling": "T"}
|
||||
for v in values]
|
||||
return {"option": self.option}
|
||||
if method == "PUT":
|
||||
new = req["options"]
|
||||
for gi, group in enumerate(new):
|
||||
cur = self.option["options"][gi]
|
||||
old_name = cur["option_name"]
|
||||
old_values = [v["option_text"] for v in cur["option_value"]]
|
||||
cur["option_name"] = group["option_name"]
|
||||
vals = []
|
||||
for vi, v in enumerate(group["option_value"]):
|
||||
vals.append({"option_text": v["option_text"], "value_no": vi + 1,
|
||||
"option_image_file": v.get("option_image_file", "")})
|
||||
if vi < len(old_values):
|
||||
for var in self.variants:
|
||||
for o in var["options"]:
|
||||
if o["name"] == old_name and o["value"] == old_values[vi]:
|
||||
o["value"] = v["option_text"]
|
||||
else:
|
||||
self.variants.append({"variant_code": self._new_code(),
|
||||
"options": [{"name": group["option_name"], "value": v["option_text"]}],
|
||||
"custom_variant_code": "", "additional_amount": "0.00",
|
||||
"display": "T", "selling": "T", "_new": True})
|
||||
for var in self.variants:
|
||||
for o in var["options"]:
|
||||
if o["name"] == old_name:
|
||||
o["name"] = group["option_name"]
|
||||
cur["option_value"] = vals
|
||||
return {"option": self.option}
|
||||
if method == "DELETE":
|
||||
self.option = {"has_option": "F", "options": []}
|
||||
self.variants = []
|
||||
return {"option": {"product_no": no}}
|
||||
if path == f"/admin/products/{no}/variants":
|
||||
if method == "GET":
|
||||
if self.stale_variants is not None:
|
||||
return {"variants": [dict(v) for v in self.stale_variants]}
|
||||
shown = [dict(v) for v in self.variants]
|
||||
if self.hidden_variants > 0:
|
||||
self.hidden_variants -= 1
|
||||
shown = [v for v in shown if not v.get("_new")]
|
||||
return {"variants": shown}
|
||||
if method == "PUT":
|
||||
self._variant_puts += 1
|
||||
if self.fail_variant_chunk and self._variant_puts == self.fail_variant_chunk:
|
||||
raise self.variant_error or Cafe24ApiError("품목 수정 거절", status=422)
|
||||
out = []
|
||||
for r in (json or {}).get("requests") or []:
|
||||
for var in self.variants:
|
||||
if var["variant_code"] == r["variant_code"]:
|
||||
var.update({k: v for k, v in r.items() if k != "variant_code"})
|
||||
out.append(dict(var))
|
||||
return {"variants": out}
|
||||
if path.startswith(f"/admin/products/{no}/variants/") and method == "DELETE":
|
||||
code = path.rsplit("/", 1)[1]
|
||||
self.variants = [v for v in self.variants if v["variant_code"] != code]
|
||||
return {"variant": {"variant_code": code}}
|
||||
return None
|
||||
|
||||
def post(self, path, *, json=None, **kw):
|
||||
self.calls.append(("POST", path, json))
|
||||
out = self._options_call("POST", path, json)
|
||||
return copy.deepcopy(out) if out is not None else {}
|
||||
|
||||
def delete(self, path, **kw):
|
||||
self.calls.append(("DELETE", path))
|
||||
out = self._options_call("DELETE", path, None)
|
||||
return out if out is not None else {}
|
||||
|
||||
def put(self, path, *, json=None, **kw):
|
||||
self.calls.append(("PUT", path, json))
|
||||
if path != f"/admin/products/{self.product_no}":
|
||||
out = self._options_call("PUT", path, json)
|
||||
return copy.deepcopy(out) if out is not None else {}
|
||||
if self.put_error is not None and not self.put_error_after_apply:
|
||||
raise self.put_error
|
||||
req = (json or {}).get("request", {})
|
||||
self._tick()
|
||||
for key in ("description", "display", "selling", "product_name", "separated_mobile_description"):
|
||||
if key in req:
|
||||
self.state[key] = req[key]
|
||||
if "description" in req:
|
||||
self.state["mobile_description"] = req["description"]
|
||||
if self.put_error is not None:
|
||||
raise self.put_error
|
||||
return {"product": dict(self.state)}
|
||||
|
||||
def puts(self):
|
||||
return [c for c in self.calls if c[0] == "PUT"]
|
||||
|
||||
|
||||
class FakeApi:
|
||||
def __init__(self, client):
|
||||
self.client = client
|
||||
self.config = FakeConfig()
|
||||
|
||||
|
||||
def network_error(maybe_applied: bool = True) -> Cafe24ApiError:
|
||||
return Cafe24ApiError("네트워크 오류 (ReadTimeout)", status=0, maybe_applied=maybe_applied)
|
||||
|
||||
|
||||
class FakeFTP:
|
||||
"""ftplib.FTP 대역 — RETR/STOR/RNFR·RNTO/DELE 를 메모리 파일로. 실패를 주입할 수 있다."""
|
||||
|
||||
files: dict[str, bytes] = {}
|
||||
rename_mode = "overwrite" # overwrite | no_overwrite | unsupported
|
||||
truncate_store = False # STOR 가 앞부분만 쓰고 끝난 것처럼
|
||||
on_before_rename = None # 교체 직전 끼어들기(남이 원본을 바꿈 등)
|
||||
log: list[tuple] = []
|
||||
|
||||
def __init__(self):
|
||||
pass
|
||||
|
||||
def connect(self, host, port, timeout=None):
|
||||
FakeFTP.log.append(("connect",))
|
||||
|
||||
def login(self, user, password):
|
||||
pass
|
||||
|
||||
def set_pasv(self, value):
|
||||
pass
|
||||
|
||||
def retrbinary(self, cmd, callback):
|
||||
path = cmd.split(" ", 1)[1]
|
||||
if path not in self.files:
|
||||
raise ftplib.error_perm("550 No such file")
|
||||
callback(self.files[path])
|
||||
|
||||
def storbinary(self, cmd, fp):
|
||||
path = cmd.split(" ", 1)[1]
|
||||
data = fp.read()
|
||||
FakeFTP.log.append(("STOR", path))
|
||||
self.files[path] = data[: len(data) // 2] if FakeFTP.truncate_store else data
|
||||
|
||||
def rename(self, src, dst):
|
||||
FakeFTP.log.append(("RENAME", src, dst))
|
||||
if FakeFTP.on_before_rename is not None:
|
||||
hook, FakeFTP.on_before_rename = FakeFTP.on_before_rename, None
|
||||
hook(self.files)
|
||||
if FakeFTP.rename_mode == "unsupported":
|
||||
raise ftplib.error_perm("502 RNFR not implemented")
|
||||
if src not in self.files:
|
||||
raise ftplib.error_perm("550 No such file")
|
||||
if dst in self.files and FakeFTP.rename_mode == "no_overwrite":
|
||||
raise ftplib.error_perm("553 File exists")
|
||||
self.files[dst] = self.files.pop(src)
|
||||
|
||||
def delete(self, path):
|
||||
FakeFTP.log.append(("DELE", path))
|
||||
self.files.pop(path, None)
|
||||
|
||||
def quit(self):
|
||||
pass
|
||||
|
||||
def close(self):
|
||||
pass
|
||||
|
||||
@classmethod
|
||||
def reset(cls, files):
|
||||
cls.files = dict(files)
|
||||
cls.rename_mode = "overwrite"
|
||||
cls.truncate_store = False
|
||||
cls.on_before_rename = None
|
||||
cls.log = []
|
||||
|
||||
|
||||
@contextmanager
|
||||
def patched_ftp():
|
||||
saved = ftplib.FTP
|
||||
ftplib.FTP = FakeFTP
|
||||
try:
|
||||
yield FakeFTP
|
||||
finally:
|
||||
ftplib.FTP = saved
|
||||
@@ -8,6 +8,7 @@ DB/네트워크 없이 검증한다(가짜 저장소 + refresh 함수 주입).
|
||||
from __future__ import annotations
|
||||
|
||||
import ftplib
|
||||
import logging
|
||||
import os
|
||||
from contextlib import contextmanager
|
||||
from datetime import timedelta
|
||||
@@ -15,7 +16,8 @@ from datetime import timedelta
|
||||
from app.integrations.cafe24 import config as cfgmod
|
||||
from app.integrations.cafe24 import crypto, oauth, products, tokens
|
||||
from app.integrations.cafe24.errors import Cafe24ApiError, Cafe24AuthError, Cafe24ConfigError
|
||||
from app.modules.cafe24 import store, worker
|
||||
from app.modules.cafe24 import store, worker, writes
|
||||
from app.modules.cafe24.tests import fakes
|
||||
from app.timezone import now_kst
|
||||
|
||||
SECRET = "unit-test-secret"
|
||||
@@ -25,6 +27,8 @@ SECRET = "unit-test-secret"
|
||||
# 값을 돌려줌) 재시도 예산을 다 채우게 되는데, 테스트에서까지 그 시간을 그대로
|
||||
# 기다릴 필요는 없다.
|
||||
products.time.sleep = lambda *_a, **_k: None
|
||||
# 장애 주입 테스트가 남기는 logger.exception 출력은 결과와 무관하다 — 조용히.
|
||||
logging.getLogger("cafe24").setLevel(logging.CRITICAL)
|
||||
|
||||
_TEST_ENV = {
|
||||
"CAFE24_MALL_ID": "testmall",
|
||||
@@ -711,203 +715,303 @@ def test_design_file_path_env_override():
|
||||
os.environ["CAFE24_PC_DETAIL_FTP_PATH"] = saved
|
||||
|
||||
|
||||
class _FakeFTP:
|
||||
"""ftplib.FTP 대역 — 실제 소켓 없이 RETR/STOR 명령만 흉내낸다."""
|
||||
|
||||
files: dict[str, bytes] = {}
|
||||
|
||||
def __init__(self):
|
||||
self.calls = []
|
||||
|
||||
def connect(self, host, port, timeout=None):
|
||||
self.calls.append(("connect", host, port))
|
||||
|
||||
def login(self, user, password):
|
||||
self.calls.append(("login", user, password))
|
||||
|
||||
def set_pasv(self, value):
|
||||
pass
|
||||
|
||||
def retrbinary(self, cmd, callback):
|
||||
path = cmd.split(" ", 1)[1]
|
||||
if path not in self.files:
|
||||
raise ftplib.error_perm("550 No such file")
|
||||
callback(self.files[path])
|
||||
|
||||
def storbinary(self, cmd, fp):
|
||||
path = cmd.split(" ", 1)[1]
|
||||
self.files[path] = fp.read()
|
||||
|
||||
def quit(self):
|
||||
self.calls.append(("quit",))
|
||||
_FTP_CFG = cfgmod.Cafe24FtpConfig(host="h", port=21, user="u", password="p")
|
||||
_SWIPER = "/sde_design/mobile11/product-swiper/product-swiper.js"
|
||||
|
||||
|
||||
def test_design_ftp_read_and_write_roundtrip():
|
||||
from app.integrations.cafe24 import design_ftp
|
||||
|
||||
path = "/sde_design/mobile11/product-swiper/product-swiper.js"
|
||||
_FakeFTP.files = {path: "old".encode("utf-8")}
|
||||
saved = ftplib.FTP
|
||||
ftplib.FTP = _FakeFTP
|
||||
try:
|
||||
cfg = cfgmod.Cafe24FtpConfig(host="h", port=21, user="u", password="p")
|
||||
content = design_ftp.read_text_file(cfg, path)
|
||||
assert content == "old"
|
||||
|
||||
design_ftp.write_text_file(cfg, path, "new content")
|
||||
assert design_ftp.read_text_file(cfg, path) == "new content"
|
||||
finally:
|
||||
ftplib.FTP = saved
|
||||
with fakes.patched_ftp() as ftp:
|
||||
ftp.reset({_SWIPER: "old".encode("utf-8")})
|
||||
assert design_ftp.read_text_file(_FTP_CFG, _SWIPER) == "old"
|
||||
design_ftp.write_text_file(_FTP_CFG, _SWIPER, "new content", expected_current="old")
|
||||
assert design_ftp.read_text_file(_FTP_CFG, _SWIPER) == "new content"
|
||||
# 원본에 직접 STOR 하지 않는다 — 임시 파일에 올린 뒤 이름 바꾸기로 교체
|
||||
stors = [e for e in ftp.log if e[0] == "STOR"]
|
||||
assert stors and all(".cf24tmp-" in e[1] for e in stors), ftp.log
|
||||
assert any(e[0] == "RENAME" and e[2] == _SWIPER for e in ftp.log)
|
||||
# 임시 파일이 남지 않는다
|
||||
assert set(ftp.files) == {_SWIPER}
|
||||
|
||||
|
||||
def test_design_ftp_missing_file_raises_cafe24_error():
|
||||
from app.integrations.cafe24 import design_ftp
|
||||
from app.integrations.cafe24.errors import Cafe24FtpError
|
||||
|
||||
_FakeFTP.files = {}
|
||||
saved = ftplib.FTP
|
||||
ftplib.FTP = _FakeFTP
|
||||
try:
|
||||
cfg = cfgmod.Cafe24FtpConfig(host="h", port=21, user="u", password="p")
|
||||
with fakes.patched_ftp() as ftp:
|
||||
ftp.reset({})
|
||||
try:
|
||||
design_ftp.read_text_file(cfg, "/missing.js")
|
||||
design_ftp.read_text_file(_FTP_CFG, "/missing.js")
|
||||
raise AssertionError("Cafe24FtpError 가 났어야 한다")
|
||||
except Cafe24FtpError:
|
||||
pass
|
||||
finally:
|
||||
ftplib.FTP = saved
|
||||
|
||||
|
||||
def test_design_ftp_truncated_upload_keeps_original():
|
||||
"""[04] 전송이 잘려도 원본은 그대로 — 임시 파일 검증에서 멈춘다."""
|
||||
from app.integrations.cafe24 import design_ftp
|
||||
from app.integrations.cafe24.errors import Cafe24FtpError
|
||||
|
||||
with fakes.patched_ftp() as ftp:
|
||||
ftp.reset({_SWIPER: b"ORIGINAL"})
|
||||
ftp.truncate_store = True
|
||||
try:
|
||||
design_ftp.write_text_file(_FTP_CFG, _SWIPER, "NEW CONTENT 1234", expected_current="ORIGINAL")
|
||||
raise AssertionError("잘린 업로드를 성공으로 처리했다")
|
||||
except Cafe24FtpError as exc:
|
||||
assert exc.maybe_applied is False
|
||||
assert ftp.files == {_SWIPER: b"ORIGINAL"} # 원본 그대로 + 임시 파일 정리
|
||||
|
||||
|
||||
def test_design_ftp_rename_unsupported_aborts_without_direct_stor():
|
||||
"""[04] 이름 바꾸기를 지원하지 않으면 중단 — 원본에 직접 쓰지 않는다."""
|
||||
from app.integrations.cafe24 import design_ftp
|
||||
from app.integrations.cafe24.errors import Cafe24FtpError
|
||||
|
||||
with fakes.patched_ftp() as ftp:
|
||||
ftp.reset({_SWIPER: b"ORIGINAL"})
|
||||
ftp.rename_mode = "unsupported"
|
||||
try:
|
||||
design_ftp.write_text_file(_FTP_CFG, _SWIPER, "NEW", expected_current="ORIGINAL")
|
||||
raise AssertionError("rename 미지원인데 진행했다")
|
||||
except Cafe24FtpError as exc:
|
||||
assert "rename" in str(exc)
|
||||
assert ftp.files == {_SWIPER: b"ORIGINAL"}
|
||||
assert not any(e == ("STOR", _SWIPER) for e in ftp.log)
|
||||
|
||||
|
||||
def test_design_ftp_no_overwrite_rename_swaps_safely():
|
||||
"""덮어쓰기 rename 을 거부하는 서버 — 원본을 비킨 뒤 교체하고 비킨 파일은 지운다."""
|
||||
from app.integrations.cafe24 import design_ftp
|
||||
|
||||
with fakes.patched_ftp() as ftp:
|
||||
ftp.reset({_SWIPER: b"ORIGINAL"})
|
||||
ftp.rename_mode = "no_overwrite"
|
||||
design_ftp.write_text_file(_FTP_CFG, _SWIPER, "NEW", expected_current="ORIGINAL")
|
||||
assert ftp.files == {_SWIPER: b"NEW"}
|
||||
|
||||
|
||||
def test_design_ftp_conflict_right_before_replace():
|
||||
"""[04] 교체 직전 원본이 바뀌어 있으면(남이 수정) 덮지 않고 멈춘다."""
|
||||
from app.integrations.cafe24 import design_ftp
|
||||
from app.integrations.cafe24.errors import Cafe24FtpConflict
|
||||
|
||||
with fakes.patched_ftp() as ftp:
|
||||
ftp.reset({_SWIPER: b"SOMEONE ELSE"})
|
||||
try:
|
||||
design_ftp.write_text_file(_FTP_CFG, _SWIPER, "MINE", expected_current="ORIGINAL")
|
||||
raise AssertionError("충돌을 못 잡았다")
|
||||
except Cafe24FtpConflict:
|
||||
pass
|
||||
assert ftp.files == {_SWIPER: b"SOMEONE ELSE"}
|
||||
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# 예약 worker — 성공/재시도/최종실패
|
||||
# 예약 worker — 성공/재시도/최종실패/확인 필요/중단 복구 (메모리 저장소 대역)
|
||||
# 실제 DB 의 lease·SKIP LOCKED 는 test_cafe24_db.py 에서 검증한다.
|
||||
# ════════════════════════════════════════════════════════════
|
||||
class _FakeStore:
|
||||
"""worker 가 쓰는 저장소 메서드만 흉내낸다."""
|
||||
|
||||
def __init__(self, rows):
|
||||
self.rows = list(rows)
|
||||
self.revisions = {}
|
||||
self.added = []
|
||||
self.finished = []
|
||||
self.audits = []
|
||||
|
||||
@contextmanager
|
||||
def claim_due_schedule(self, *, now):
|
||||
yield self.rows.pop(0) if self.rows else None
|
||||
|
||||
def get_revision(self, revision_id):
|
||||
return self.revisions.get(int(revision_id), {})
|
||||
|
||||
def add_revision(self, **fields):
|
||||
self.added.append(fields)
|
||||
return 900 + len(self.added)
|
||||
|
||||
def save_write_snapshot(self, product_no, section, data):
|
||||
self.snapshots = getattr(self, "snapshots", [])
|
||||
self.snapshots.append((product_no, section, data))
|
||||
|
||||
def finish_schedule(self, schedule_id, *, status, error="", next_retry_at=None, retry_count=None):
|
||||
self.finished.append(
|
||||
{"id": schedule_id, "status": status, "error": error,
|
||||
"next_retry_at": next_retry_at, "retry_count": retry_count}
|
||||
)
|
||||
|
||||
def log_audit(self, **fields):
|
||||
self.audits.append(fields)
|
||||
|
||||
|
||||
class _FakeApi:
|
||||
def __init__(self, client):
|
||||
self.client = client
|
||||
|
||||
|
||||
class _WorkerClient(_FakeClient):
|
||||
"""PUT 을 실패시킬 수 있는 클라이언트."""
|
||||
|
||||
def __init__(self, payload=None, fail_put=None):
|
||||
super().__init__(payload)
|
||||
self.fail_put = fail_put
|
||||
|
||||
def put(self, path, *, params=None, json=None, product_no=None):
|
||||
if self.fail_put:
|
||||
raise self.fail_put
|
||||
return super().put(path, params=params, json=json, product_no=product_no)
|
||||
|
||||
|
||||
def _schedule_row(**overrides):
|
||||
row = {
|
||||
"id": 7, "product_no": 131, "revision_id": 55,
|
||||
"set_display": True, "set_selling": None, "retry_count": 0,
|
||||
}
|
||||
row.update(overrides)
|
||||
return row
|
||||
def _worker_env(description="<p>A</p>", **schedule):
|
||||
st = fakes.MemoryStore()
|
||||
cafe = fakes.FakeCafe24(description)
|
||||
api = fakes.FakeApi(cafe)
|
||||
rid = st.add_revision(product_no=131, html_content="<p>예약 내용</p>", revision_type="DRAFT")
|
||||
fields = {"revision_id": rid, "set_display": True}
|
||||
fields.update(schedule)
|
||||
sid = st.add_schedule(**fields)
|
||||
return st, cafe, api, sid, rid
|
||||
|
||||
|
||||
def test_worker_applies_html_and_flags():
|
||||
st = _FakeStore([_schedule_row()])
|
||||
st.revisions[55] = {"html_content": "<p>예약 내용</p>"}
|
||||
client = _WorkerClient({"product": _PRODUCT})
|
||||
assert worker.process_once(st, _FakeApi(client)) == 1
|
||||
st, cafe, api, sid, _rid = _worker_env()
|
||||
assert worker.process_once(st, api) == 1
|
||||
|
||||
# 쓰기 직전 현재값을 읽어 BACKUP 을 남겼는가
|
||||
assert any(r["revision_type"] == store.REVISION_BACKUP for r in st.added)
|
||||
backups = st.of_type(store.REVISION_BACKUP)
|
||||
assert backups and backups[0]["html_content"] == "<p>A</p>"
|
||||
assert backups[0]["source"] == store.SOURCE_OBSERVED
|
||||
# HTML 과 진열 상태를 한 번의 PUT 으로 보냈는가
|
||||
put = [c for c in client.calls if c["method"] == "PUT"][0]
|
||||
assert put["json"]["request"]["description"] == "<p>예약 내용</p>"
|
||||
put = cafe.puts()[0]
|
||||
assert put[2]["request"]["description"] == "<p>예약 내용</p>"
|
||||
# mobile_description 은 보내지 않는다 — separated_mobile_description="F" 로
|
||||
# "PC 상세설명과 동일"을 강제한다(직접 보내면 "직접 등록"으로 바뀌어버린다).
|
||||
assert "mobile_description" not in put["json"]["request"]
|
||||
assert put["json"]["request"]["separated_mobile_description"] == "F"
|
||||
assert put["json"]["request"]["display"] == "T"
|
||||
assert "selling" not in put["json"]["request"] # 변경 없음이면 보내지 않는다
|
||||
assert st.finished == [
|
||||
{"id": 7, "status": store.STATUS_SUCCESS, "error": "",
|
||||
"next_retry_at": None, "retry_count": None}
|
||||
]
|
||||
assert "mobile_description" not in put[2]["request"]
|
||||
assert put[2]["request"]["separated_mobile_description"] == "F"
|
||||
assert put[2]["request"]["display"] == "T"
|
||||
assert "selling" not in put[2]["request"] # 변경 없음이면 보내지 않는다
|
||||
row = st.schedules[sid]
|
||||
assert row["status"] == store.STATUS_SUCCESS and row["last_error"] == ""
|
||||
assert row["lease_token"] == "" # 끝나면 lease 를 비운다
|
||||
assert len(st.of_type(store.REVISION_SCHEDULED)) == 1
|
||||
assert list(st.attempts.values())[0]["status"] == store.ATTEMPT_RECORDED
|
||||
assert st.locks == {} # 상품 잠금 해제
|
||||
|
||||
|
||||
def test_worker_flags_only_skips_backup():
|
||||
"""HTML 없이 진열/판매만 바꾸는 예약은 상세설명을 읽거나 백업하지 않는다."""
|
||||
st = _FakeStore([_schedule_row(revision_id=None, set_selling=False)])
|
||||
client = _WorkerClient({"product": _PRODUCT})
|
||||
assert worker.process_once(st, _FakeApi(client)) == 1
|
||||
assert st.added == [] # 백업 없음
|
||||
put = [c for c in client.calls if c["method"] == "PUT"][0]
|
||||
assert "description" not in put["json"]["request"]
|
||||
assert put["json"]["request"] == {"display": "T", "selling": "F"}
|
||||
st, cafe, api, sid, _ = _worker_env(revision_id=None, set_selling=False)
|
||||
before = len(st.revisions)
|
||||
assert worker.process_once(st, api) == 1
|
||||
assert len(st.revisions) == before # 백업·SCHEDULED 버전 없음
|
||||
put = cafe.puts()[0]
|
||||
assert put[2]["request"] == {"display": "T", "selling": "F"}
|
||||
assert st.schedules[sid]["status"] == store.STATUS_SUCCESS
|
||||
|
||||
|
||||
def test_worker_retries_then_fails():
|
||||
"""실패는 재시도 예산 안에서 다시 시도하고, 소진되면 FAILED 로 확정한다."""
|
||||
boom = Cafe24ApiError("서버 오류", status=500)
|
||||
|
||||
st = _FakeStore([_schedule_row(retry_count=0)])
|
||||
st.revisions[55] = {"html_content": "<p>x</p>"}
|
||||
worker.process_once(st, _FakeApi(_WorkerClient({"product": _PRODUCT}, fail_put=boom)))
|
||||
first = st.finished[0]
|
||||
"""거절(반영 안 됨이 확실)은 재시도 예산 안에서 다시 시도하고, 소진되면 FAILED."""
|
||||
st, cafe, api, sid, _ = _worker_env()
|
||||
cafe.put_error = Cafe24ApiError("잘못된 요청", status=422)
|
||||
worker.process_once(st, api)
|
||||
first = st.schedules[sid]
|
||||
assert first["status"] == store.STATUS_PENDING # 다시 대기로
|
||||
assert first["retry_count"] == 1
|
||||
assert first["next_retry_at"] is not None
|
||||
assert list(st.attempts.values())[-1]["status"] == store.ATTEMPT_REMOTE_FAILED
|
||||
|
||||
st2 = _FakeStore([_schedule_row(retry_count=store.MAX_RETRY)])
|
||||
st2.revisions[55] = {"html_content": "<p>x</p>"}
|
||||
worker.process_once(st2, _FakeApi(_WorkerClient({"product": _PRODUCT}, fail_put=boom)))
|
||||
assert st2.finished[0]["status"] == store.STATUS_FAILED
|
||||
st2, cafe2, api2, sid2, _ = _worker_env(retry_count=store.MAX_RETRY)
|
||||
cafe2.put_error = Cafe24ApiError("서버 오류", status=400)
|
||||
worker.process_once(st2, api2)
|
||||
assert st2.schedules[sid2]["status"] == store.STATUS_FAILED
|
||||
assert any(a["result"] == "FAIL" for a in st2.audits)
|
||||
|
||||
|
||||
def test_worker_missing_revision_is_failure_not_crash():
|
||||
st = _FakeStore([_schedule_row(revision_id=999, retry_count=store.MAX_RETRY)])
|
||||
worker.process_once(st, _FakeApi(_WorkerClient({"product": _PRODUCT})))
|
||||
assert st.finished[0]["status"] == store.STATUS_FAILED
|
||||
assert "999" in st.finished[0]["error"]
|
||||
st, _cafe, api, sid, _ = _worker_env(revision_id=999, retry_count=store.MAX_RETRY)
|
||||
worker.process_once(st, api)
|
||||
assert st.schedules[sid]["status"] == store.STATUS_FAILED
|
||||
assert "999" in st.schedules[sid]["last_error"]
|
||||
|
||||
|
||||
def test_worker_stops_when_nothing_due():
|
||||
st = _FakeStore([])
|
||||
assert worker.process_once(st, _FakeApi(_WorkerClient())) == 0
|
||||
st = fakes.MemoryStore()
|
||||
assert worker.process_once(st, fakes.FakeApi(fakes.FakeCafe24())) == 0
|
||||
|
||||
|
||||
def test_worker_unknown_result_needs_review_not_retry():
|
||||
"""[05][07] 응답 유실(반영 여부 모름) — 재시도로 한 번 더 쓰지 않고 확인 필요로 둔다."""
|
||||
st, cafe, api, sid, _ = _worker_env()
|
||||
cafe.put_error = fakes.network_error(maybe_applied=True)
|
||||
cafe.put_error_after_apply = True
|
||||
worker.process_once(st, api)
|
||||
assert st.schedules[sid]["status"] == store.STATUS_NEEDS_REVIEW
|
||||
assert list(st.attempts.values())[-1]["status"] == store.ATTEMPT_UNKNOWN
|
||||
worker.process_once(st, api)
|
||||
assert len(cafe.puts()) == 1 # 다시 쓰지 않았다
|
||||
|
||||
|
||||
def test_worker_remote_ok_but_record_failure_is_success_not_failed():
|
||||
"""[07] PUT 성공 뒤 로컬 버전 기록 실패 → FAILED 가 아니라 SUCCESS + 기록 복구 메모, 재적용 없음."""
|
||||
st, cafe, api, sid, _ = _worker_env()
|
||||
st.fail_on.add("record_attempt_revision")
|
||||
worker.process_once(st, api)
|
||||
row = st.schedules[sid]
|
||||
assert row["status"] == store.STATUS_SUCCESS, row
|
||||
assert "기록" in row["last_error"]
|
||||
attempt = list(st.attempts.values())[-1]
|
||||
assert attempt["status"] == store.ATTEMPT_REMOTE_OK # 반영됨, 기록 복구 대기
|
||||
# 다음 주기: 기록 복구만 하고 다시 PUT 하지 않는다
|
||||
st.fail_on.clear()
|
||||
worker.process_once(st, api)
|
||||
assert len(cafe.puts()) == 1
|
||||
assert attempt["status"] == store.ATTEMPT_RECORDED
|
||||
assert len(st.of_type(store.REVISION_SCHEDULED)) == 1
|
||||
|
||||
|
||||
def test_worker_busy_product_defers_without_burning_retry():
|
||||
"""[02] 같은 상품을 다른 작업이 쓰는 중이면 쓰지 않고 잠시 뒤로 미룬다(재시도 횟수 그대로)."""
|
||||
st, cafe, api, sid, _ = _worker_env()
|
||||
st.acquire_lock("product:131", owner="king|web:1", purpose="상세설명 적용", ttl_seconds=60)
|
||||
worker.process_once(st, api)
|
||||
row = st.schedules[sid]
|
||||
assert row["status"] == store.STATUS_PENDING and row["retry_count"] == 0
|
||||
assert row["next_retry_at"] is not None
|
||||
assert cafe.puts() == []
|
||||
|
||||
|
||||
def test_worker_backup_uses_confirmed_last_write_during_lag():
|
||||
"""[06] 예약 직전 카페24가 읽기 지연으로 옛 HTML 을 돌려줘도, 백업은 마지막 확인된 적용값."""
|
||||
st, cafe, api, sid, _ = _worker_env(description="<p>OLD</p>")
|
||||
# 방금 웹에서 NEW 를 적용(확인된 쓰기) — 카페24 GET 은 아직 OLD
|
||||
with writes.write_lock(st, "product:131", actor="king", purpose="t") as lock:
|
||||
writes.write_product(st, api, 131, lock=lock, origin=store.ORIGIN_MANUAL, actor="king",
|
||||
html="<p>NEW</p>", wait_confirm=False)
|
||||
cafe.stale = {**cafe.state, "description": "<p>OLD</p>", "mobile_description": "<p>OLD</p>",
|
||||
"updated_date": "2026-09-30T09:00:00+09:00"}
|
||||
worker.process_once(st, api)
|
||||
backups = [r for r in st.of_type(store.REVISION_BACKUP) if "예약" in r["memo"]]
|
||||
assert backups and backups[-1]["html_content"] == "<p>NEW</p>", backups
|
||||
assert backups[-1]["source"] == store.SOURCE_LAST_WRITE
|
||||
|
||||
|
||||
def test_worker_recovers_expired_processing_by_attempt_state():
|
||||
"""[05] lease 만료 PROCESSING — 시도 기록으로 판정(무조건 PENDING 금지)."""
|
||||
st = fakes.MemoryStore()
|
||||
cafe = fakes.FakeCafe24("<p>A</p>")
|
||||
api = fakes.FakeApi(cafe)
|
||||
rid = st.add_revision(product_no=131, html_content="<p>예약</p>", revision_type="DRAFT")
|
||||
|
||||
def processing(**fields):
|
||||
sid = st.add_schedule(revision_id=rid, status=store.STATUS_PROCESSING,
|
||||
lease_token="dead", started_at=now_kst(), **fields)
|
||||
st.expire_schedule_lease(sid)
|
||||
return sid
|
||||
|
||||
# (1) 원격 쓰기 전에 죽음 → 재시도 대기
|
||||
s1 = processing()
|
||||
# (2) 반영·기록까지 끝난 뒤 죽음 → 완료
|
||||
s2 = processing()
|
||||
st.start_attempt(product_no=131, schedule_id=s2, origin="SCHEDULED", target_digest="x",
|
||||
target_revision_id=rid)
|
||||
st.attempts[max(st.attempts)]["status"] = store.ATTEMPT_RECORDED
|
||||
# (3) 반영됐고 기록 전에 죽음 → 기록 채우고 완료(재적용 없음)
|
||||
s3 = processing()
|
||||
a3 = st.start_attempt(product_no=131, schedule_id=s3, origin="SCHEDULED",
|
||||
target_digest=store.content_digest("<p>예약</p>"), target_revision_id=rid)
|
||||
st.attempts[a3]["status"] = store.ATTEMPT_REMOTE_OK
|
||||
# (4) PUT 도중 죽음, 카페24 값은 예약 결과와 다름 → 확인 필요
|
||||
s4 = processing()
|
||||
st.start_attempt(product_no=131, schedule_id=s4, origin="SCHEDULED",
|
||||
target_digest=store.content_digest("<p>예약</p>"), target_revision_id=rid)
|
||||
# (5) 레거시(lease 없음) PROCESSING, 40분 전 → 만료로 보고 재시도 대기
|
||||
s5 = st.add_schedule(revision_id=rid, status=store.STATUS_PROCESSING, lease_token="",
|
||||
started_at=now_kst() - timedelta(minutes=40))
|
||||
|
||||
worker.recover(st, api)
|
||||
assert st.schedules[s1]["status"] == store.STATUS_PENDING and st.schedules[s1]["retry_count"] == 1
|
||||
assert st.schedules[s2]["status"] == store.STATUS_SUCCESS
|
||||
assert st.schedules[s3]["status"] == store.STATUS_SUCCESS
|
||||
assert st.attempts[a3]["status"] == store.ATTEMPT_RECORDED
|
||||
assert st.schedules[s4]["status"] == store.STATUS_NEEDS_REVIEW
|
||||
assert st.schedules[s5]["status"] == store.STATUS_PENDING
|
||||
assert cafe.puts() == [] # 복구는 쓰지 않는다
|
||||
|
||||
|
||||
def test_worker_recover_verifies_remote_value():
|
||||
"""[05] 결과 모름 시도라도 카페24 현재값이 예약 결과와 같으면 반영됨으로 확정."""
|
||||
st = fakes.MemoryStore()
|
||||
cafe = fakes.FakeCafe24("<p>예약</p>") # 이미 반영돼 있다
|
||||
api = fakes.FakeApi(cafe)
|
||||
rid = st.add_revision(product_no=131, html_content="<p>예약</p>", revision_type="DRAFT")
|
||||
sid = st.add_schedule(revision_id=rid, status=store.STATUS_PROCESSING, lease_token="dead",
|
||||
started_at=now_kst())
|
||||
st.expire_schedule_lease(sid)
|
||||
aid = st.start_attempt(product_no=131, schedule_id=sid, origin="SCHEDULED",
|
||||
target_digest=store.content_digest("<p>예약</p>"), target_revision_id=rid)
|
||||
worker.recover(st, api)
|
||||
assert st.schedules[sid]["status"] == store.STATUS_SUCCESS
|
||||
assert st.attempts[aid]["status"] == store.ATTEMPT_RECORDED
|
||||
|
||||
|
||||
def test_worker_late_finish_after_lease_loss_does_not_overwrite():
|
||||
"""[05] lease 를 잃은 worker 의 늦은 결과는 반영되지 않는다(token 불일치)."""
|
||||
st, _cafe, _api, sid, _ = _worker_env()
|
||||
row = st.claim_due_schedule(now=now_kst(), owner="w1", ttl_seconds=60)
|
||||
st.expire_schedule_lease(sid)
|
||||
st.claim_expired_schedules(owner="w2", ttl_seconds=60, legacy_minutes=30)
|
||||
assert st.finish_schedule(sid, token=row["lease_token"], status=store.STATUS_FAILED) is False
|
||||
assert st.schedules[sid]["status"] == store.STATUS_PROCESSING
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# 카페24 읽기 지연 보정 — 마지막 쓰기가 권위
|
||||
# ════════════════════════════════════════════════════════════
|
||||
@@ -1185,7 +1289,8 @@ def test_upload_images_and_variants_wrappers():
|
||||
assert products.list_variants(client, 7) == [{"variant_code": "P000000R000A"}]
|
||||
assert products.get_options(client, 7)["has_option"] == "T"
|
||||
assert products.update_variants(client, 7, [{"variant_code": "P000000R000A", "display": "F"}]) == [
|
||||
{"variant_code": "P000000R000A", "display": "F"}
|
||||
{"variant_code": "P000000R000A", "status": "ok", "error": "",
|
||||
"variant": {"variant_code": "P000000R000A", "display": "F"}}
|
||||
]
|
||||
sent = [c for c in client.calls if c[0] == "PUT"][-1]
|
||||
assert sent[2]["requests"][0]["variant_code"] == "P000000R000A"
|
||||
@@ -1221,6 +1326,404 @@ def test_set_main_image_uses_product_images_endpoint():
|
||||
assert products.set_main_image(client, 13, b"") == {}
|
||||
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# 쓰기 공통 처리(writes.write_product) — [01][02][06][07] 회귀
|
||||
# ════════════════════════════════════════════════════════════
|
||||
def _apply(st, api, html, *, fp=None, origin=store.ORIGIN_MANUAL, actor="king", **kw):
|
||||
with writes.write_lock(st, "product:131", actor=actor, purpose="t", wait_seconds=0) as lock:
|
||||
return writes.write_product(st, api, 131, lock=lock, origin=origin, actor=actor, html=html,
|
||||
base_fingerprint=fp, wait_confirm=False, **kw)
|
||||
|
||||
|
||||
def _editor_view(st, cafe):
|
||||
"""편집기가 보여줄 유효 현재값과 지문(routes_products._editor_ctx 와 같은 판정)."""
|
||||
product = cafe.get(f"/admin/products/{cafe.product_no}")["product"]
|
||||
effective, state, _ = writes.resolve_effective(st, 131, product["description"],
|
||||
fetched_updated=product.get("updated_date"))
|
||||
return effective, state, store.fingerprint(effective)
|
||||
|
||||
|
||||
def test_01_rejected_conflict_backup_does_not_mask_external_edit():
|
||||
"""[01] 충돌로 거절된 적용의 BACKUP(=외부 값 X)이 읽기 지연 근거가 되면 X 를 덮어쓴다."""
|
||||
st = fakes.MemoryStore()
|
||||
cafe = fakes.FakeCafe24("<p>A</p>")
|
||||
api = fakes.FakeApi(cafe)
|
||||
_apply(st, api, "<p>W1</p>") # 우리 쓰기(확인됨)
|
||||
_eff, _state, stale_fp = _editor_view(st, cafe) # 사용자 1: W1 을 보고 편집 시작
|
||||
cafe.external_edit("<p>X</p>") # 관리자에서 직접 X 로 고침
|
||||
|
||||
try:
|
||||
_apply(st, api, "<p>Y</p>", fp=stale_fp) # 사용자 1 적용 → 충돌로 거절(BACKUP X 가 남는다)
|
||||
raise AssertionError("충돌을 못 잡았다")
|
||||
except writes.WriteConflict:
|
||||
pass
|
||||
assert any(r["html_content"] == "<p>X</p>" for r in st.of_type(store.REVISION_BACKUP))
|
||||
|
||||
effective, state, fp = _editor_view(st, cafe)
|
||||
assert (effective, state) == ("<p>X</p>", store.SYNC_EXTERNAL), (effective, state)
|
||||
try:
|
||||
_apply(st, api, "<p>Y</p>", fp=stale_fp) # 같은 옛 지문으로 다시 → 여전히 충돌
|
||||
raise AssertionError("외부 수정 X 를 덮어썼다")
|
||||
except writes.WriteConflict:
|
||||
pass
|
||||
assert cafe.state["description"] == "<p>X</p>"
|
||||
_apply(st, api, "<p>Y</p>", fp=fp) # 새로 본 X 기준이면 적용된다
|
||||
assert cafe.state["description"] == "<p>Y</p>"
|
||||
|
||||
|
||||
def test_01_draft_value_is_not_treated_as_known():
|
||||
"""[01] 예약 초안(DRAFT)은 카페24에 올라간 적이 없다 — 관리자가 그 값으로 고쳐도 외부 변경."""
|
||||
st = fakes.MemoryStore()
|
||||
cafe = fakes.FakeCafe24("<p>A</p>")
|
||||
api = fakes.FakeApi(cafe)
|
||||
_apply(st, api, "<p>W1</p>")
|
||||
st.add_revision(product_no=131, html_content="<p>D</p>", revision_type="DRAFT")
|
||||
cafe.external_edit("<p>D</p>")
|
||||
assert _editor_view(st, cafe)[:2] == ("<p>D</p>", store.SYNC_EXTERNAL)
|
||||
|
||||
|
||||
def test_01_read_lag_still_shows_last_confirmed_write():
|
||||
"""읽기 지연 보정은 유지 — GET 이 쓰기 직전 값(A)을 돌려주면 마지막 확인된 쓰기를 보여준다."""
|
||||
st = fakes.MemoryStore()
|
||||
cafe = fakes.FakeCafe24("<p>A</p>")
|
||||
api = fakes.FakeApi(cafe)
|
||||
_apply(st, api, "<p>B</p>")
|
||||
cafe.stale = {**cafe.state, "description": "<p>A</p>", "updated_date": "2026-09-30T09:00:00+09:00"}
|
||||
assert _editor_view(st, cafe)[:2] == ("<p>B</p>", store.SYNC_PENDING)
|
||||
_apply(st, api, "<p>C</p>") # A→B→C 직후 GET 이 A 여도 지연
|
||||
assert _editor_view(st, cafe)[:2] == ("<p>C</p>", store.SYNC_PENDING)
|
||||
|
||||
|
||||
def test_01_revert_after_our_write_detected_by_updated_date():
|
||||
"""[01] 관리자가 우리 적용 뒤 예전 값(A)으로 되돌림 — updated_date 가 더 뒤라 외부 변경."""
|
||||
st = fakes.MemoryStore()
|
||||
cafe = fakes.FakeCafe24("<p>A</p>")
|
||||
api = fakes.FakeApi(cafe)
|
||||
_apply(st, api, "<p>B</p>")
|
||||
cafe.external_edit("<p>A</p>")
|
||||
assert _editor_view(st, cafe)[:2] == ("<p>A</p>", store.SYNC_EXTERNAL)
|
||||
|
||||
|
||||
def test_01_failed_write_is_not_lineage():
|
||||
"""[01] 카페24가 거절한 쓰기는 "마지막 쓰기"가 아니다."""
|
||||
st = fakes.MemoryStore()
|
||||
cafe = fakes.FakeCafe24("<p>A</p>")
|
||||
api = fakes.FakeApi(cafe)
|
||||
cafe.put_error = Cafe24ApiError("거절", status=422)
|
||||
try:
|
||||
_apply(st, api, "<p>B</p>")
|
||||
raise AssertionError("실패를 삼켰다")
|
||||
except writes.RemoteWriteFailed:
|
||||
pass
|
||||
assert list(st.attempts.values())[-1]["status"] == store.ATTEMPT_REMOTE_FAILED
|
||||
assert _editor_view(st, cafe)[:2] == ("<p>A</p>", store.SYNC_NONE)
|
||||
assert st.of_type(store.REVISION_MANUAL) == []
|
||||
|
||||
|
||||
def test_02_second_writer_is_serialized_and_detects_conflict():
|
||||
"""[02] 같은 편집 기준(A)으로 두 사람이 동시에 적용 — 잠금으로 순서가 생기고 뒤 사람은 충돌."""
|
||||
st = fakes.MemoryStore()
|
||||
cafe = fakes.FakeCafe24("<p>A</p>")
|
||||
api = fakes.FakeApi(cafe)
|
||||
fp_a = store.fingerprint("<p>A</p>")
|
||||
with writes.write_lock(st, "product:131", actor="alice", purpose="t", wait_seconds=0):
|
||||
try: # 앞 사람이 쓰는 동안 뒤 사람은 잠금을 못 잡는다
|
||||
with writes.write_lock(st, "product:131", actor="bob", purpose="t", wait_seconds=0):
|
||||
raise AssertionError("잠금이 겹쳤다")
|
||||
except writes.WriteBusy as exc:
|
||||
assert "alice" in str(exc)
|
||||
_apply(st, api, "<p>ALICE</p>", fp=fp_a, actor="alice")
|
||||
cafe.stale = {**cafe.state, "description": "<p>A</p>", "updated_date": "2026-09-30T09:00:00+09:00"}
|
||||
try: # GET 이 지연으로 A 를 돌려줘도, 마지막 확인된 쓰기(ALICE)가 기준이라 충돌
|
||||
_apply(st, api, "<p>BOB</p>", fp=fp_a, actor="bob")
|
||||
raise AssertionError("둘 다 성공했다")
|
||||
except writes.WriteConflict:
|
||||
pass
|
||||
assert cafe.state["description"] == "<p>ALICE</p>"
|
||||
|
||||
|
||||
def test_02_expired_lock_cannot_write_fencing():
|
||||
"""[02] 잠금이 만료돼 남에게 넘어간 뒤에는 PUT 하지 않는다(펜싱)."""
|
||||
st = fakes.MemoryStore()
|
||||
cafe = fakes.FakeCafe24("<p>A</p>")
|
||||
api = fakes.FakeApi(cafe)
|
||||
with writes.write_lock(st, "product:131", actor="slow", purpose="t", wait_seconds=0) as lock:
|
||||
st.expire_lock("product:131")
|
||||
with writes.write_lock(st, "product:131", actor="other", purpose="t", wait_seconds=0):
|
||||
pass # 만료 뒤 다른 요청이 가져갔다가 풀었다
|
||||
try:
|
||||
writes.write_product(st, api, 131, lock=lock, origin="MANUAL", actor="slow",
|
||||
html="<p>S</p>", wait_confirm=False)
|
||||
raise AssertionError("만료된 잠금으로 썼다")
|
||||
except writes.WriteBusy:
|
||||
pass
|
||||
assert cafe.puts() == []
|
||||
|
||||
|
||||
def test_02_schema_missing_refuses_to_write():
|
||||
st = fakes.MemoryStore()
|
||||
st.schema_ok = False
|
||||
try:
|
||||
with writes.write_lock(st, "product:131", actor="k", purpose="t"):
|
||||
raise AssertionError("스키마 없이 잠금을 줬다")
|
||||
except writes.WriteSetupError as exc:
|
||||
assert "005" in str(exc)
|
||||
|
||||
|
||||
def test_06_manual_backup_marks_source():
|
||||
"""[06] BACKUP 메타데이터 — 관측값(OBSERVED) / 지연 중 마지막 확인된 쓰기(LAST_WRITE)."""
|
||||
st = fakes.MemoryStore()
|
||||
cafe = fakes.FakeCafe24("<p>A</p>")
|
||||
api = fakes.FakeApi(cafe)
|
||||
first = _apply(st, api, "<p>B</p>")
|
||||
b1 = st.revisions[first.backup_id]
|
||||
assert (b1["html_content"], b1["source"]) == ("<p>A</p>", store.SOURCE_OBSERVED)
|
||||
cafe.stale = {**cafe.state, "description": "<p>A</p>", "updated_date": "2026-09-30T09:00:00+09:00"}
|
||||
second = _apply(st, api, "<p>C</p>")
|
||||
b2 = st.revisions[second.backup_id]
|
||||
assert (b2["html_content"], b2["source"]) == ("<p>B</p>", store.SOURCE_LAST_WRITE)
|
||||
assert b2["source_revision_id"] == first.revision_id
|
||||
|
||||
|
||||
def test_07_manual_record_failure_is_not_apply_failure():
|
||||
"""[07] PUT 성공 뒤 버전 기록 실패 — 예외 없이 record_error, 시도는 REMOTE_OK(기록 복구 대기)."""
|
||||
st = fakes.MemoryStore()
|
||||
cafe = fakes.FakeCafe24("<p>A</p>")
|
||||
api = fakes.FakeApi(cafe)
|
||||
st.fail_on.add("record_attempt_revision")
|
||||
out = _apply(st, api, "<p>B</p>")
|
||||
assert out.record_error and not out.revision_id
|
||||
attempt = st.attempts[out.attempt_id]
|
||||
assert attempt["status"] == store.ATTEMPT_REMOTE_OK and attempt["target_html"] == "<p>B</p>"
|
||||
# 기록이 없어도 확인된 쓰기로 본다 — 지연 중에도 B 를 보여준다
|
||||
cafe.stale = {**cafe.state, "description": "<p>A</p>", "updated_date": "2026-09-30T09:00:00+09:00"}
|
||||
assert _editor_view(st, cafe)[:2] == ("<p>B</p>", store.SYNC_PENDING)
|
||||
# 다음 쓰기 때 기록을 채운다(다시 PUT 하지 않음)
|
||||
st.fail_on.clear()
|
||||
puts = len(cafe.puts())
|
||||
cafe.stale = None
|
||||
_apply(st, api, "<p>C</p>")
|
||||
assert attempt["status"] == store.ATTEMPT_RECORDED and attempt["target_html"] == ""
|
||||
assert len(cafe.puts()) == puts + 1 # C 쓰기 한 번뿐
|
||||
|
||||
|
||||
def test_07_unknown_result_blocks_rewrite_until_verified():
|
||||
"""[07] 응답 유실 — UNKNOWN. 확정 전에는 같은 상품 상세설명을 다시 쓰지 않는다.
|
||||
카페24 값이 그 시도의 결과와 같아지면(=반영됨) 자동으로 확정한다."""
|
||||
st = fakes.MemoryStore()
|
||||
cafe = fakes.FakeCafe24("<p>A</p>")
|
||||
api = fakes.FakeApi(cafe)
|
||||
cafe.put_error = fakes.network_error(maybe_applied=True)
|
||||
try:
|
||||
_apply(st, api, "<p>B</p>")
|
||||
raise AssertionError("결과 모름을 성공/실패로 판정했다")
|
||||
except writes.RemoteWriteUnknown as exc:
|
||||
aid = exc.attempt_id
|
||||
assert st.attempts[aid]["status"] == store.ATTEMPT_UNKNOWN
|
||||
cafe.put_error = None
|
||||
try:
|
||||
_apply(st, api, "<p>C</p>")
|
||||
raise AssertionError("결과 모름 시도가 있는데 또 썼다")
|
||||
except writes.WriteBlocked:
|
||||
pass
|
||||
cafe.state.update(description="<p>B</p>") # 확인해 보니 반영돼 있었다
|
||||
_apply(st, api, "<p>C</p>")
|
||||
assert st.attempts[aid]["status"] == store.ATTEMPT_RECORDED
|
||||
assert [r["html_content"] for r in st.of_type(store.REVISION_MANUAL)] == ["<p>B</p>", "<p>C</p>"]
|
||||
|
||||
|
||||
def test_07_connect_error_is_definite_failure():
|
||||
"""연결조차 안 된 오류는 반영 안 됨이 확실 — UNKNOWN 이 아니라 REMOTE_FAILED."""
|
||||
st = fakes.MemoryStore()
|
||||
cafe = fakes.FakeCafe24("<p>A</p>")
|
||||
cafe.put_error = fakes.network_error(maybe_applied=False)
|
||||
try:
|
||||
_apply(st, fakes.FakeApi(cafe), "<p>B</p>")
|
||||
except writes.RemoteWriteFailed:
|
||||
pass
|
||||
assert list(st.attempts.values())[-1]["status"] == store.ATTEMPT_REMOTE_FAILED
|
||||
|
||||
|
||||
def test_rollback_records_rollback_revision():
|
||||
"""[13] 선택 복원은 정상 경로로 한 번 적용하고 ROLLBACK(원본 버전 표시)을 남긴다."""
|
||||
st = fakes.MemoryStore()
|
||||
cafe = fakes.FakeCafe24("<p>A</p>")
|
||||
api = fakes.FakeApi(cafe)
|
||||
first = _apply(st, api, "<p>B</p>")
|
||||
backup = first.backup_id # A
|
||||
out = _apply(st, api, st.revisions[backup]["html_content"], fp=store.fingerprint("<p>B</p>"),
|
||||
origin=store.ORIGIN_ROLLBACK, target_revision_id=backup, memo=f"버전 {backup} 복원")
|
||||
assert cafe.state["description"] == "<p>A</p>"
|
||||
rb = st.revisions[out.revision_id]
|
||||
assert rb["revision_type"] == "ROLLBACK" and rb["source_revision_id"] == backup
|
||||
assert rb["html_content"] == "<p>A</p>"
|
||||
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# 스냅샷 병합 · 품목 표기 · 옵션 모양 — [10][11]
|
||||
# ════════════════════════════════════════════════════════════
|
||||
def test_11_variant_snapshot_field_merge():
|
||||
at = now_kst().isoformat()
|
||||
a = store.merge_variant_snapshot({}, {"V1": {"custom_variant_code": "C1"}}, at=at)
|
||||
b = store.merge_variant_snapshot(a, {"V1": {"display": "F"}}, at=at)
|
||||
assert b["V1"]["custom_variant_code"] == "C1" and b["V1"]["display"] == "F"
|
||||
|
||||
|
||||
def test_11_empty_patch_is_not_reset_but_replace_is():
|
||||
at = now_kst().isoformat()
|
||||
a = store.merge_variant_snapshot({}, {"V1": {"display": "F"}}, at=at)
|
||||
assert store.merge_variant_snapshot(a, {}, at=at) == a
|
||||
assert store.merge_variant_snapshot(a, {}, at=at, replace=True) == {}
|
||||
|
||||
|
||||
def test_11_deleted_variant_is_not_resurrected():
|
||||
at = now_kst().isoformat()
|
||||
a = store.merge_variant_snapshot({}, {"V1": {"_deleted": True}}, at=at)
|
||||
b = store.merge_variant_snapshot(a, {"V1": {"display": "T", "custom_variant_code": "X"}}, at=at)
|
||||
assert b["V1"].get("_deleted") is True and "custom_variant_code" not in b["V1"]
|
||||
v = store.apply_variant_patch({"variant_code": "V1"}, b["V1"], section_written_at=at, grace_minutes=60)
|
||||
assert v is None
|
||||
|
||||
|
||||
def test_11_per_code_grace():
|
||||
old = (now_kst() - timedelta(hours=10)).isoformat()
|
||||
patch = {"display": "F", "_at": old}
|
||||
v = store.apply_variant_patch({"variant_code": "V1", "display": "T"}, patch,
|
||||
section_written_at=now_kst().isoformat(), grace_minutes=60)
|
||||
assert v["display"] == "T" # 그 품목 기록은 유예시간이 지났다
|
||||
|
||||
|
||||
def test_10_lagging_variant_labels_matched_by_code():
|
||||
"""[10] 옵션값 이름 변경 직후 GET 품목이 옛 이름 — 품목코드 기록으로 새 이름을 보여준다."""
|
||||
at = now_kst().isoformat()
|
||||
patch = {"options": [{"name": "색상", "value": "Jet"}], "_options_before": [[{"name": "색상", "value": "Black"}]],
|
||||
"_at": at}
|
||||
lag = store.apply_variant_patch({"variant_code": "V1", "options": [{"name": "색상", "value": "Black"}]},
|
||||
patch, section_written_at=at, grace_minutes=60)
|
||||
assert lag["options"] == [{"name": "색상", "value": "Jet"}]
|
||||
ext = store.apply_variant_patch({"variant_code": "V1", "options": [{"name": "색상", "value": "Onyx"}]},
|
||||
patch, section_written_at=at, grace_minutes=60)
|
||||
assert ext["options"] == [{"name": "색상", "value": "Onyx"}] # 관리자에서 다시 고친 이름은 믿는다
|
||||
|
||||
|
||||
def test_10_options_overlay_respects_external_change():
|
||||
at = now_kst().isoformat()
|
||||
before = {"has_option": "T", "options": [{"option_name": "색상", "option_value": [{"option_text": "Black"}]}]}
|
||||
ours = {"has_option": "T", "options": [{"option_name": "색상", "option_value": [{"option_text": "Jet"}]}]}
|
||||
other = {"has_option": "T", "options": [{"option_name": "색상", "option_value": [{"option_text": "Onyx"}]}]}
|
||||
snap = {**ours, "_before_signatures": [store.options_signature(before)]}
|
||||
assert store.overlay_options(before, snapshot=snap, written_at=at, grace_minutes=60) == (snap, True)
|
||||
assert store.overlay_options(other, snapshot=snap, written_at=at, grace_minutes=60) == (other, False)
|
||||
assert store.overlay_options(ours, snapshot=snap, written_at=at, grace_minutes=60) == (ours, False)
|
||||
|
||||
|
||||
def test_05_recovery_decision_table():
|
||||
rd = store.recovery_decision
|
||||
assert rd(None, 0)[0] == store.RECOVER_RETRY
|
||||
assert rd(None, store.MAX_RETRY)[0] == store.RECOVER_FAIL
|
||||
assert rd({"status": "RECORDED"}, 0)[0] == store.RECOVER_SUCCESS
|
||||
assert rd({"status": "REMOTE_OK"}, 0)[0] == store.RECOVER_RECORD
|
||||
assert rd({"status": "REMOTE_FAILED"}, 0)[0] == store.RECOVER_RETRY
|
||||
assert rd({"status": "STARTED"}, 0)[0] == store.RECOVER_REVIEW
|
||||
assert rd({"status": "UNKNOWN"}, 99)[0] == store.RECOVER_REVIEW # 예산과 무관하게 사람 확인
|
||||
|
||||
|
||||
def test_resolve_description_updated_date_rule():
|
||||
lw = {"html_content": "B", "created_at": now_kst(), "remote_updated_at": "2026-09-30T10:05:00+09:00"}
|
||||
digests = {store.content_digest("A")}
|
||||
newer = store.resolve_description("A", last_write=lw, known_digests=digests, grace_minutes=60,
|
||||
fetched_updated="2026-09-30T10:06:00+09:00")
|
||||
same = store.resolve_description("A", last_write=lw, known_digests=digests, grace_minutes=60,
|
||||
fetched_updated="2026-09-30T10:05:00+09:00")
|
||||
older = store.resolve_description("A", last_write=lw, known_digests=digests, grace_minutes=60,
|
||||
fetched_updated="2026-09-30T10:00:00+09:00")
|
||||
assert newer == ("A", store.SYNC_EXTERNAL)
|
||||
assert same == ("B", store.SYNC_PENDING) and older == ("B", store.SYNC_PENDING)
|
||||
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# 품목 일괄 수정 행별 결과 — [09]
|
||||
# ════════════════════════════════════════════════════════════
|
||||
class _ChunkClient:
|
||||
def __init__(self, fail_chunk: int, error):
|
||||
self.fail_chunk = fail_chunk
|
||||
self.error = error
|
||||
self.n = 0
|
||||
|
||||
def put(self, path, *, json=None, **kw):
|
||||
self.n += 1
|
||||
if self.n == self.fail_chunk:
|
||||
raise self.error
|
||||
return {"variants": [{"variant_code": r["variant_code"], "display": r.get("display")} for r in json["requests"]]}
|
||||
|
||||
|
||||
def _codes(n):
|
||||
return [{"variant_code": f"P0000000{i:04d}", "display": "F"} for i in range(n)]
|
||||
|
||||
|
||||
def test_09_partial_chunk_failure_reports_per_row():
|
||||
rows = products.update_variants(_ChunkClient(2, Cafe24ApiError("거절", status=422)), 7, _codes(150))
|
||||
assert [r["status"] for r in rows[:100]] == ["ok"] * 100
|
||||
assert [r["status"] for r in rows[100:]] == ["failed"] * 50
|
||||
assert rows[0]["variant"]["display"] == "F" and rows[120]["error"] == "거절"
|
||||
|
||||
|
||||
def test_09_first_chunk_failure_still_sends_second():
|
||||
client = _ChunkClient(1, fakes.network_error(maybe_applied=True))
|
||||
rows = products.update_variants(client, 7, _codes(150))
|
||||
assert client.n == 2
|
||||
assert {r["status"] for r in rows[:100]} == {"unknown"}
|
||||
assert {r["status"] for r in rows[100:]} == {"ok"}
|
||||
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# 전송 계층 — 쓰기 요청이 카페24에 닿았을 수 있는가(maybe_applied)
|
||||
# ════════════════════════════════════════════════════════════
|
||||
def _client_with(handler):
|
||||
import httpx
|
||||
|
||||
from app.integrations.cafe24 import client as client_mod
|
||||
|
||||
class _Tokens:
|
||||
def get_access_token(self):
|
||||
return "AT"
|
||||
|
||||
def force_expire(self):
|
||||
pass
|
||||
|
||||
real = httpx.Client
|
||||
transport = httpx.MockTransport(handler)
|
||||
client_mod.httpx.Client = lambda **kw: real(transport=transport, **kw)
|
||||
client_mod.time.sleep = lambda *_a, **_k: None
|
||||
return client_mod.Cafe24Client(_config(), _Tokens(), min_interval=0), (client_mod, real)
|
||||
|
||||
|
||||
def _restore(saved):
|
||||
client_mod, real = saved
|
||||
client_mod.httpx.Client = real
|
||||
|
||||
|
||||
def test_client_maybe_applied_classification():
|
||||
import httpx
|
||||
|
||||
cases = [
|
||||
("PUT", lambda req: (_ for _ in ()).throw(httpx.ReadTimeout("t", request=req)), True),
|
||||
("PUT", lambda req: (_ for _ in ()).throw(httpx.ConnectError("c", request=req)), False),
|
||||
("PUT", lambda req: httpx.Response(500, json={"error": {"message": "서버"}}), True),
|
||||
("PUT", lambda req: httpx.Response(422, json={"error": {"message": "검증"}}), False),
|
||||
("GET", lambda req: (_ for _ in ()).throw(httpx.ReadTimeout("t", request=req)), False),
|
||||
]
|
||||
for method, handler, expected in cases:
|
||||
client, saved = _client_with(handler)
|
||||
try:
|
||||
client.request(method, "/admin/products/1", json={"request": {}} if method == "PUT" else None)
|
||||
raise AssertionError("오류가 나야 한다")
|
||||
except Cafe24ApiError as exc:
|
||||
assert exc.maybe_applied is expected, (method, expected, str(exc))
|
||||
finally:
|
||||
_restore(saved)
|
||||
|
||||
|
||||
def _run_all():
|
||||
fns = [v for k, v in sorted(globals().items()) if k.startswith("test_") and callable(v)]
|
||||
for fn in fns:
|
||||
|
||||
+223
-119
@@ -8,14 +8,28 @@
|
||||
웹 요청 안에서 기다리는 방식은 프록시 타임아웃·재기동에 그대로 무너진다.
|
||||
compose 서비스 `dbx-cafe24-worker` 가 web 과 같은 이미지로 이 모듈을 돌린다.
|
||||
|
||||
한 번에 한 건씩 처리한다
|
||||
`claim_due_schedule` 이 `FOR UPDATE SKIP LOCKED` 로 한 건을 잠그고 PROCESSING 으로
|
||||
바꾼다. worker 가 실수로 두 개 떠도 같은 예약이 두 번 적용되지 않는다.
|
||||
한 번에 한 건씩, lease 로 잡는다 (마이그레이션 005)
|
||||
`claim_due_schedule` 이 `FOR UPDATE SKIP LOCKED` 로 한 건을 잡아 PROCESSING + lease
|
||||
(만료 시각·token)로 바꾼다. worker 가 여럿이어도 같은 예약을 두 번 잡지 않는다.
|
||||
카페24에 쓰기 직전 lease 를 연장해 "아직 내 것인가"를 확인하고(펜싱), 결과는
|
||||
token 이 맞을 때만 남긴다 — 만료 뒤 늦게 끝난 worker 가 남의 결과를 덮지 않는다.
|
||||
|
||||
적용 순서는 화면 편집과 같다
|
||||
카페24 현재값 재조회 → BACKUP revision → PUT → SUCCESS + 감사로그
|
||||
실패하면 재시도 예산(store.MAX_RETRY) 안에서 간격을 두고 다시 시도하고,
|
||||
소진되면 FAILED 로 확정한다. 되돌리기는 쓰지 않는다.
|
||||
적용 순서는 화면 편집과 같다 (writes.write_product 공용)
|
||||
상품 잠금 → 카페24 현재값 재조회 → 유효 현재값(읽기 지연 보정) → BACKUP
|
||||
→ 시도 기록 → PUT → 버전(SCHEDULED)·스냅샷 기록
|
||||
예약 직전 백업도 읽기 지연을 보정한 값이다(카페24가 아직 옛 HTML 을 돌려줘도
|
||||
그것을 "직전 내용"으로 남기지 않는다). 백업의 source 로 관측값/확인된 적용값을 구분한다.
|
||||
|
||||
결과 분류
|
||||
카페24가 거절 → 재시도 예산(store.MAX_RETRY) 안에서 간격을 두고 다시, 소진되면 FAILED
|
||||
반영 여부 모름 → NEEDS_REVIEW (자동 재적용 금지 — 사람이 쇼핑몰을 보고 확정)
|
||||
반영 성공·기록 실패 → SUCCESS + "기록 복구 필요" 메모. 기록은 다음 주기에 채운다(재적용 없음)
|
||||
같은 상품을 다른 작업이 쓰는 중 → 재시도 횟수를 쓰지 않고 잠시 뒤 다시
|
||||
|
||||
중단 복구 (recover)
|
||||
lease 가 만료된 PROCESSING 은 그 예약의 마지막 쓰기 시도를 보고 판정한다
|
||||
(store.recovery_decision). 무조건 PENDING 으로 돌리지 않는다 — 카페24에 이미 반영됐을
|
||||
수 있기 때문이다. 카페24 현재값이 예약 결과와 같으면 반영된 것으로 확정한다.
|
||||
|
||||
토큰 갱신은 TokenService 가 행 잠금 안에서 하므로 web 과 동시에 떠 있어도 안전하다.
|
||||
"""
|
||||
@@ -25,6 +39,7 @@ from __future__ import annotations
|
||||
import argparse
|
||||
import logging
|
||||
import os
|
||||
import socket
|
||||
import sys
|
||||
import time
|
||||
from datetime import timedelta
|
||||
@@ -33,141 +48,230 @@ from typing import Any
|
||||
from app.integrations.cafe24 import Cafe24Error, build_cafe24_api, products
|
||||
from app.timezone import now_kst
|
||||
|
||||
from . import store
|
||||
from . import store, writes
|
||||
from .common import read_lag_grace_minutes
|
||||
|
||||
logger = logging.getLogger("cafe24.worker")
|
||||
|
||||
ACTOR = "SCHEDULER"
|
||||
DEFAULT_LEASE_SEC = 600 # 한 건 처리(현재값 조회 + PUT + 확인)에 넉넉한 시간
|
||||
LEGACY_PROCESSING_MIN = 30 # lease 컬럼이 없는 옛 PROCESSING 을 만료로 볼 시간
|
||||
BUSY_RETRY_SECONDS = 30 # 같은 상품을 다른 작업이 쓰는 중일 때 다시 볼 간격
|
||||
SETUP_RETRY_SECONDS = 300 # 마이그레이션 미적용 등 설정 문제일 때 다시 볼 간격
|
||||
|
||||
|
||||
def _apply(store_db: Any, api: Any, row: dict[str, Any]) -> str:
|
||||
"""예약 1건 적용. 성공 시 사람이 읽을 요약 문자열."""
|
||||
def lease_seconds() -> int:
|
||||
try:
|
||||
value = int(str(os.getenv("CAFE24_SCHEDULE_LEASE_SEC") or "").strip())
|
||||
except ValueError:
|
||||
return DEFAULT_LEASE_SEC
|
||||
return max(60, value)
|
||||
|
||||
|
||||
def worker_owner() -> str:
|
||||
return f"{ACTOR}|{socket.gethostname()}:{os.getpid()}"
|
||||
|
||||
|
||||
def _summary(row: dict[str, Any]) -> str:
|
||||
return store.describe_schedule_action(
|
||||
has_html=bool(row.get("revision_id")),
|
||||
set_display=row.get("set_display"),
|
||||
set_selling=row.get("set_selling"),
|
||||
)
|
||||
|
||||
|
||||
def _retry_or_fail(st: Any, row: dict[str, Any], token: str, error: str) -> str:
|
||||
"""재시도 예산 안이면 PENDING + 대기, 아니면 FAILED. 반환: 결과 상태."""
|
||||
retry_count = int(row.get("retry_count") or 0)
|
||||
schedule_id = int(row["id"])
|
||||
if store.can_retry(retry_count):
|
||||
wait = store.retry_backoff_seconds(retry_count)
|
||||
st.finish_schedule(
|
||||
schedule_id, token=token, status=store.STATUS_PENDING, error=error,
|
||||
next_retry_at=now_kst() + timedelta(seconds=wait), retry_count=retry_count + 1,
|
||||
)
|
||||
logger.warning("예약 #%s 상품 %s 실패 — %s초 후 재시도 (%s/%s): %s",
|
||||
schedule_id, row.get("product_no"), wait, retry_count + 1, store.MAX_RETRY, error)
|
||||
return store.STATUS_PENDING
|
||||
st.finish_schedule(schedule_id, token=token, status=store.STATUS_FAILED, error=error)
|
||||
writes.audit_safe(st, actor=ACTOR, action="schedule_apply", product_no=row.get("product_no"),
|
||||
schedule_id=schedule_id, result="FAIL", detail=error)
|
||||
logger.error("예약 #%s 상품 %s 최종 실패: %s", schedule_id, row.get("product_no"), error)
|
||||
return store.STATUS_FAILED
|
||||
|
||||
|
||||
def run_one(st: Any, api: Any, row: dict[str, Any]) -> str:
|
||||
"""lease 로 잡은 예약 1건 실행. 반환: 남긴 상태(또는 'LEASE_LOST')."""
|
||||
schedule_id = int(row["id"])
|
||||
product_no = int(row["product_no"])
|
||||
token = str(row.get("lease_token") or "")
|
||||
lease = lease_seconds()
|
||||
revision_id = row.get("revision_id")
|
||||
set_display = row.get("set_display")
|
||||
set_selling = row.get("set_selling")
|
||||
|
||||
html: str | None = None
|
||||
if revision_id:
|
||||
revision = store_db.get_revision(int(revision_id))
|
||||
if not revision:
|
||||
raise Cafe24Error(f"예약이 가리키는 버전 {revision_id} 을 찾을 수 없습니다.")
|
||||
html = revision.get("html_content") or ""
|
||||
if not html.strip():
|
||||
raise Cafe24Error(f"버전 {revision_id} 의 내용이 비어 있습니다.")
|
||||
def fence() -> bool:
|
||||
return bool(st.renew_schedule_lease(schedule_id, token, ttl_seconds=lease))
|
||||
|
||||
# 상세설명을 바꿀 때는 쓰기 직전 현재값을 읽어 백업한다(로컬 값을 믿지 않는다).
|
||||
backup_id = 0
|
||||
if html is not None:
|
||||
current = products.fetch_descriptions(api.client, product_no)
|
||||
backup_id = store_db.add_revision(
|
||||
product_no=product_no,
|
||||
html_content=current.description,
|
||||
revision_type=store.REVISION_BACKUP,
|
||||
memo=f"예약 #{schedule_id} 적용 직전 자동 백업",
|
||||
created_by=ACTOR,
|
||||
)
|
||||
if current.mobile_description and current.mobile_description != current.description:
|
||||
store_db.add_revision(
|
||||
product_no=product_no,
|
||||
html_content=current.mobile_description,
|
||||
revision_type=store.REVISION_BACKUP,
|
||||
memo=f"예약 #{schedule_id} 적용 직전 자동 백업 (모바일)",
|
||||
created_by=ACTOR,
|
||||
try:
|
||||
html: str | None = None
|
||||
if revision_id:
|
||||
revision = st.get_revision(int(revision_id))
|
||||
if not revision:
|
||||
raise Cafe24Error(f"예약이 가리키는 버전 {revision_id} 을 찾을 수 없습니다.")
|
||||
html = str(revision.get("html_content") or "")
|
||||
if not html.strip():
|
||||
raise Cafe24Error(f"버전 {revision_id} 의 내용이 비어 있습니다.")
|
||||
with writes.write_lock(
|
||||
st, writes.product_lock_key(product_no), actor=ACTOR,
|
||||
purpose=f"예약 #{schedule_id} 실행", wait_seconds=0,
|
||||
) as lock:
|
||||
outcome = writes.write_product(
|
||||
st, api, product_no,
|
||||
lock=lock, origin=store.ORIGIN_SCHEDULED, actor=ACTOR, html=html,
|
||||
set_display=set_display, set_selling=set_selling,
|
||||
schedule_id=schedule_id, target_revision_id=int(revision_id) if revision_id else None,
|
||||
memo=f"예약 #{schedule_id} 적용", extra_fence=fence,
|
||||
)
|
||||
except writes.WriteSetupError as exc:
|
||||
st.finish_schedule(schedule_id, token=token, status=store.STATUS_PENDING, error=str(exc),
|
||||
next_retry_at=now_kst() + timedelta(seconds=SETUP_RETRY_SECONDS))
|
||||
logger.error("예약 #%s 실행 보류 — %s", schedule_id, exc)
|
||||
return store.STATUS_PENDING
|
||||
except writes.WriteBusy as exc:
|
||||
# 다른 작업이 같은 상품을 쓰는 중이거나 lease 를 잃었다. 재시도 횟수를 쓰지 않는다.
|
||||
# (lease 를 잃었으면 finish 는 token 이 안 맞아 아무것도 바꾸지 않는다.)
|
||||
done = st.finish_schedule(schedule_id, token=token, status=store.STATUS_PENDING, error=str(exc),
|
||||
next_retry_at=now_kst() + timedelta(seconds=BUSY_RETRY_SECONDS))
|
||||
logger.info("예약 #%s 상품 %s 보류(%s): %s", schedule_id, product_no, "재대기" if done else "lease 잃음", exc)
|
||||
return store.STATUS_PENDING if done else "LEASE_LOST"
|
||||
except (writes.WriteBlocked, writes.RemoteWriteUnknown) as exc:
|
||||
st.finish_schedule(schedule_id, token=token, status=store.STATUS_NEEDS_REVIEW, error=str(exc))
|
||||
writes.audit_safe(st, actor=ACTOR, action="schedule_apply", product_no=product_no,
|
||||
schedule_id=schedule_id, result="UNKNOWN", detail=str(exc))
|
||||
logger.error("예약 #%s 상품 %s 확인 필요: %s", schedule_id, product_no, exc)
|
||||
return store.STATUS_NEEDS_REVIEW
|
||||
except (writes.RemoteWriteFailed, Cafe24Error) as exc:
|
||||
return _retry_or_fail(st, row, token, str(exc))
|
||||
except Exception as exc: # noqa: BLE001 — 카페24에 쓰기 전의 사고(원격 이후는 write_product 가 삼킨다)
|
||||
logger.exception("예약 #%s 처리 중 예상치 못한 오류(카페24 쓰기 전)", schedule_id)
|
||||
return _retry_or_fail(st, row, token, f"{type(exc).__name__}: {exc}")
|
||||
|
||||
# PC/모바일은 구분하지 않는다 — mobile_description 은 보내지 않고
|
||||
# separated_mobile_description="F" 로 "PC 상세설명과 동일"을 강제한다.
|
||||
# (mobile_description 을 직접 보내면 카페24가 그 설정을 "직접 등록"으로 바꿔버린다.)
|
||||
updated = products.update_product(
|
||||
api.client,
|
||||
product_no,
|
||||
description=html,
|
||||
separated_mobile_description="F" if html is not None else None,
|
||||
display=set_display,
|
||||
selling=set_selling,
|
||||
note = ""
|
||||
if outcome.record_error:
|
||||
note = f"카페24 반영 성공 · 로컬 기록 실패(자동 복구 예정, 재적용 안 함): {outcome.record_error}"
|
||||
done = st.finish_schedule(schedule_id, token=token, status=store.STATUS_SUCCESS, error=note)
|
||||
if not done:
|
||||
# 반영은 됐다. 결과를 못 남겼어도 lease 만료 후 recover 가 시도 기록(REMOTE_OK/RECORDED)을
|
||||
# 보고 SUCCESS 로 확정한다 — 다시 적용하지 않는다.
|
||||
logger.warning("예약 #%s 적용됨 — 결과 기록 실패(lease 잃음). 복구 단계가 확정합니다.", schedule_id)
|
||||
summary = _summary(row)
|
||||
writes.audit_safe(
|
||||
st, actor=ACTOR, action="schedule_apply", product_no=product_no,
|
||||
revision_id=outcome.revision_id or (int(revision_id) if revision_id else None),
|
||||
schedule_id=schedule_id, result="SUCCESS",
|
||||
detail=summary + (f" (백업 {outcome.backup_id})" if outcome.backup_id else "")
|
||||
+ (f" / {note}" if note else ""),
|
||||
)
|
||||
# PUT 응답은 쓰기 직후의 실제 값이다 — 스냅샷으로 남겨 화면이 GET 의 읽기 지연에
|
||||
# 흔들리지 않게 한다(routes_products._load_product 가 덮어씌운다).
|
||||
if isinstance(updated, dict) and updated.get("product_no"):
|
||||
logger.info("예약 #%s 상품 %s 적용 완료 — %s", schedule_id, product_no, summary)
|
||||
return store.STATUS_SUCCESS
|
||||
|
||||
|
||||
def _verify_attempt(st: Any, api: Any, attempt: dict[str, Any]) -> bool:
|
||||
"""카페24 현재값이 그 시도의 결과와 같은가(같으면 반영된 것으로 확정해도 된다)."""
|
||||
try:
|
||||
product = products.get_product(api.client, int(attempt["product_no"]))
|
||||
except Cafe24Error as exc:
|
||||
logger.warning("시도 #%s 확인용 조회 실패: %s", attempt.get("id"), exc)
|
||||
return False
|
||||
return writes.attempt_matches_remote(attempt, product)
|
||||
|
||||
|
||||
def recover_one(st: Any, api: Any, row: dict[str, Any]) -> str:
|
||||
"""lease 만료 PROCESSING 1건 복구 판정 — 반환: 남긴 상태."""
|
||||
schedule_id = int(row["id"])
|
||||
token = str(row.get("lease_token") or "")
|
||||
attempt = st.latest_attempt_for_schedule(schedule_id) or None
|
||||
decision, note = store.recovery_decision(attempt, row.get("retry_count"))
|
||||
note = f"중단 복구: {note}"
|
||||
|
||||
if decision == store.RECOVER_REVIEW and attempt:
|
||||
try:
|
||||
store_db.save_write_snapshot(product_no, "product", store.product_snapshot(updated))
|
||||
except Exception: # noqa: BLE001 — 스냅샷 실패가 예약 결과를 바꾸면 안 된다.
|
||||
logger.exception("예약 #%s 상품 %s 스냅샷 저장 실패", schedule_id, product_no)
|
||||
if html is not None:
|
||||
# 화면 편집(apply)과 동일 — 카페24 관리자 API 의 쓰기 직후 읽기 지연을
|
||||
# 여기서 짧게 흡수한다(쇼핑몰에는 바로 반영되지만 관리자 조회만 뒤쳐질 때가 있다).
|
||||
# 확인이 안 돼도 실패가 아니다 — 화면은 마지막 쓰기(SCHEDULED revision)를 기준으로
|
||||
# 그린다. 여기서 SCHEDULED revision 을 남겨야 그 기준이 생긴다.
|
||||
products.wait_for_description(api.client, product_no, html)
|
||||
store_db.add_revision(
|
||||
product_no=product_no,
|
||||
html_content=html,
|
||||
revision_type=store.REVISION_SCHEDULED,
|
||||
memo=f"예약 #{schedule_id} 적용",
|
||||
created_by=ACTOR,
|
||||
)
|
||||
with writes.write_lock(st, writes.product_lock_key(int(row["product_no"])), actor=ACTOR,
|
||||
purpose=f"예약 #{schedule_id} 복구 확인", wait_seconds=0):
|
||||
if _verify_attempt(st, api, attempt):
|
||||
st.update_attempt(int(attempt["id"]), status=store.ATTEMPT_REMOTE_OK, remote_ok=True,
|
||||
resolved_by="auto:카페24 값이 예약 결과와 같음",
|
||||
only_from=(store.ATTEMPT_STARTED, store.ATTEMPT_UNKNOWN))
|
||||
decision, note = store.RECOVER_RECORD, "중단 복구: 카페24 현재값이 예약 결과와 같아 반영됨으로 확정"
|
||||
except writes.WriteBusy:
|
||||
pass # 다음 주기에 다시 — 판정은 REVIEW 로 남긴다
|
||||
if decision == store.RECOVER_RECORD and attempt:
|
||||
try:
|
||||
writes.record_attempt(st, attempt)
|
||||
except Exception as exc: # noqa: BLE001 — 반영은 됐다. 기록은 다음 주기에.
|
||||
logger.exception("예약 #%s 복구 중 버전 기록 실패", schedule_id)
|
||||
note += f" (버전 기록 실패 — 자동 재시도: {type(exc).__name__})"
|
||||
decision = store.RECOVER_SUCCESS
|
||||
|
||||
summary = store.describe_schedule_action(
|
||||
has_html=html is not None, set_display=set_display, set_selling=set_selling
|
||||
if decision == store.RECOVER_SUCCESS:
|
||||
st.finish_schedule(schedule_id, token=token, status=store.STATUS_SUCCESS, error=note)
|
||||
status = store.STATUS_SUCCESS
|
||||
elif decision == store.RECOVER_REVIEW:
|
||||
st.finish_schedule(schedule_id, token=token, status=store.STATUS_NEEDS_REVIEW, error=note)
|
||||
status = store.STATUS_NEEDS_REVIEW
|
||||
else:
|
||||
status = _retry_or_fail(st, row, token, note)
|
||||
writes.audit_safe(st, actor=ACTOR, action="schedule_recover", product_no=row.get("product_no"),
|
||||
schedule_id=schedule_id, result=status, detail=note)
|
||||
logger.warning("예약 #%s 중단 복구 → %s (%s)", schedule_id, status, note)
|
||||
return status
|
||||
|
||||
|
||||
def record_pending_attempts(st: Any) -> int:
|
||||
"""카페24에 반영됐는데 버전 기록이 빠진 시도(REMOTE_OK)의 기록을 채운다."""
|
||||
since = now_kst() - timedelta(minutes=read_lag_grace_minutes())
|
||||
done = 0
|
||||
for attempt in st.attempts_needing_record(since=since):
|
||||
try:
|
||||
with writes.write_lock(st, writes.product_lock_key(int(attempt["product_no"])), actor=ACTOR,
|
||||
purpose="기록 복구", wait_seconds=0):
|
||||
writes.record_attempt(st, attempt)
|
||||
done += 1
|
||||
except writes.WriteBusy:
|
||||
continue
|
||||
except Exception: # noqa: BLE001
|
||||
logger.exception("시도 #%s 기록 복구 실패", attempt.get("id"))
|
||||
return done
|
||||
|
||||
|
||||
def recover(st: Any, api: Any) -> int:
|
||||
"""중단 복구 — 기록 복구 + lease 만료 PROCESSING 판정. 처리 건수."""
|
||||
count = record_pending_attempts(st)
|
||||
rows = st.claim_expired_schedules(
|
||||
owner=worker_owner(), ttl_seconds=lease_seconds(), legacy_minutes=LEGACY_PROCESSING_MIN
|
||||
)
|
||||
store_db.log_audit(
|
||||
actor=ACTOR,
|
||||
action="schedule_apply",
|
||||
product_no=product_no,
|
||||
revision_id=int(revision_id) if revision_id else None,
|
||||
schedule_id=schedule_id,
|
||||
result="SUCCESS",
|
||||
detail=summary + (f" (백업 {backup_id})" if backup_id else ""),
|
||||
)
|
||||
return summary
|
||||
for row in rows:
|
||||
try:
|
||||
recover_one(st, api, row)
|
||||
except Exception: # noqa: BLE001 — 한 건 때문에 나머지를 멈추지 않는다(lease 만료 후 다시)
|
||||
logger.exception("예약 #%s 복구 중 오류", row.get("id"))
|
||||
count += 1
|
||||
return count
|
||||
|
||||
|
||||
def process_once(store_db: Any, api: Any) -> int:
|
||||
"""실행할 예약을 모두 처리한다. 처리한 건수를 돌려준다."""
|
||||
def process_once(st: Any, api: Any) -> int:
|
||||
"""중단 복구 후, 실행할 예약을 모두 처리한다. 처리한(잡은) 예약 건수를 돌려준다."""
|
||||
try:
|
||||
recover(st, api)
|
||||
except Exception: # noqa: BLE001 — 복구 실패가 새 예약 실행을 막지 않게
|
||||
logger.exception("중단 복구 단계 오류 — 다음 주기에 다시 시도")
|
||||
handled = 0
|
||||
while True:
|
||||
with store_db.claim_due_schedule(now=now_kst()) as row:
|
||||
if row is None:
|
||||
return handled
|
||||
# 잠금은 여기서 이미 풀렸다. 상태가 PROCESSING 이라 다른 worker 가 집지 않는다.
|
||||
schedule_id = int(row["id"])
|
||||
product_no = int(row["product_no"])
|
||||
try:
|
||||
summary = _apply(store_db, api, row)
|
||||
except Cafe24Error as exc:
|
||||
retry_count = int(row.get("retry_count") or 0)
|
||||
if store.can_retry(retry_count):
|
||||
wait = store.retry_backoff_seconds(retry_count)
|
||||
store_db.finish_schedule(
|
||||
schedule_id,
|
||||
status=store.STATUS_PENDING,
|
||||
error=str(exc),
|
||||
next_retry_at=now_kst() + timedelta(seconds=wait),
|
||||
retry_count=retry_count + 1,
|
||||
)
|
||||
logger.warning(
|
||||
"예약 #%s 상품 %s 실패 — %s초 후 재시도 (%s/%s): %s",
|
||||
schedule_id, product_no, wait, retry_count + 1, store.MAX_RETRY, exc,
|
||||
)
|
||||
else:
|
||||
store_db.finish_schedule(
|
||||
schedule_id, status=store.STATUS_FAILED, error=str(exc)
|
||||
)
|
||||
store_db.log_audit(
|
||||
actor=ACTOR, action="schedule_apply", product_no=product_no,
|
||||
schedule_id=schedule_id, result="FAIL", detail=str(exc),
|
||||
)
|
||||
logger.error("예약 #%s 상품 %s 최종 실패: %s", schedule_id, product_no, exc)
|
||||
except Exception as exc: # noqa: BLE001 — 한 건의 사고가 worker 를 죽이면 안 된다.
|
||||
store_db.finish_schedule(
|
||||
schedule_id, status=store.STATUS_FAILED, error=f"{type(exc).__name__}: {exc}"
|
||||
)
|
||||
logger.exception("예약 #%s 처리 중 예상치 못한 오류", schedule_id)
|
||||
else:
|
||||
store_db.finish_schedule(schedule_id, status=store.STATUS_SUCCESS)
|
||||
logger.info("예약 #%s 상품 %s 적용 완료 — %s", schedule_id, product_no, summary)
|
||||
row = st.claim_due_schedule(now=now_kst(), owner=worker_owner(), ttl_seconds=lease_seconds())
|
||||
if row is None:
|
||||
return handled
|
||||
run_one(st, api, row)
|
||||
handled += 1
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,531 @@
|
||||
"""카페24 쓰기 공통 처리 — 잠금 · 유효 현재값 판정 · 백업 · 시도 기록 · 결과 분류.
|
||||
|
||||
상세설명(과 예약의 진열/판매)을 카페24에 쓰는 모든 경로 — 즉시 적용, 버전 복원,
|
||||
예약 worker — 가 `write_product` 한 곳을 지난다. 경로마다 판정이 달라 생기던 문제
|
||||
(예약 직전 백업이 지연된 옛 HTML 을 담는 등)를 막기 위해서다.
|
||||
|
||||
순서 (docs/CAFE24_MODULE.md 3-2, 3-5)
|
||||
상품 잠금(DB lease) → 카페24 현재값 GET → 결과 모르는 이전 시도 확인
|
||||
→ 유효 현재값(읽기 지연 보정) → BACKUP → 지문 대조(충돌 거부)
|
||||
→ 잠금 펜싱 → 시도 기록(STARTED) → PUT
|
||||
→ 원격 결과 분류(REMOTE_OK / REMOTE_FAILED / UNKNOWN)
|
||||
→ 스냅샷 · 버전(MANUAL/SCHEDULED/ROLLBACK) 기록(RECORDED)
|
||||
|
||||
원칙
|
||||
- 읽기 지연 판정의 근거는 **원격 반영이 확인된 쓰기**(cafe24_write_attempts 의
|
||||
REMOTE_OK/RECORDED)뿐이다. 충돌로 거절된 적용의 백업·예약 초안은 넣지 않는다.
|
||||
- PUT 이 성공한 뒤의 실패(스냅샷·버전 기록)는 "적용 실패"가 아니다. 결과에
|
||||
record_error 로 알리고, 시도 기록(REMOTE_OK)에 남은 내용으로 나중에 복구한다.
|
||||
재적용하지 않는다.
|
||||
- 반영 여부를 모르는 시도(STARTED/UNKNOWN)가 남아 있으면 같은 상품 상세설명을
|
||||
다시 쓰지 않는다(WriteBlocked). 카페24 값이 그 시도의 내용과 같으면 자동 확정.
|
||||
- 잠금은 웹 여러 프로세스 + worker 가 공유하는 DB 표(cafe24_write_locks)다.
|
||||
카페24 관리자 화면에서 사람이 동시에 고치는 것은 막을 수 없다 — 그것은 지문
|
||||
대조(편집 시작 시점 값과 비교)로만 잡는다.
|
||||
|
||||
카페24 호출은 `app.integrations.cafe24` 만 쓴다(httpx 직접 호출 금지).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
import socket
|
||||
import time
|
||||
from contextlib import contextmanager
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import timedelta
|
||||
from typing import Any, Callable, Iterator
|
||||
|
||||
from app.integrations.cafe24 import Cafe24Error, products
|
||||
from app.timezone import now_kst
|
||||
|
||||
from . import store
|
||||
from .common import read_lag_grace_minutes
|
||||
|
||||
logger = logging.getLogger("cafe24.writes")
|
||||
|
||||
DEFAULT_LOCK_TTL_SEC = 300 # 이미지 업로드(최대 120초 × 재시도)도 담을 만큼
|
||||
DEFAULT_LOCK_WAIT_SEC = 3.0 # 웹 요청은 짧게만 기다린다 — 오래 걸리면 "수정 중" 안내
|
||||
|
||||
|
||||
def _env_number(name: str, default: float) -> float:
|
||||
try:
|
||||
value = float(str(os.getenv(name) or "").strip())
|
||||
except ValueError:
|
||||
return default
|
||||
return value if value >= 0 else default
|
||||
|
||||
|
||||
def lock_ttl_seconds() -> int:
|
||||
return max(30, int(_env_number("CAFE24_WRITE_LOCK_TTL_SEC", DEFAULT_LOCK_TTL_SEC)))
|
||||
|
||||
|
||||
def lock_wait_seconds() -> float:
|
||||
return min(30.0, _env_number("CAFE24_WRITE_LOCK_WAIT_SEC", DEFAULT_LOCK_WAIT_SEC))
|
||||
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# 예외 — http_status 는 JSON API 가 그대로 쓴다
|
||||
# ════════════════════════════════════════════════════════════
|
||||
class WriteError(Exception):
|
||||
http_status = 500
|
||||
|
||||
def __init__(self, message: str, *, backup_id: int = 0, attempt_id: int = 0):
|
||||
super().__init__(message)
|
||||
self.backup_id = backup_id
|
||||
self.attempt_id = attempt_id
|
||||
|
||||
|
||||
class WriteSetupError(WriteError):
|
||||
"""마이그레이션 005 미적용 등 — 안전장치 없이 쓰지 않는다."""
|
||||
|
||||
http_status = 503
|
||||
|
||||
|
||||
class WriteBusy(WriteError):
|
||||
"""다른 요청(또는 예약 실행)이 같은 대상을 쓰는 중이거나, 잠금을 잃었다."""
|
||||
|
||||
http_status = 409
|
||||
|
||||
|
||||
class WriteConflict(WriteError):
|
||||
"""편집 시작 뒤 카페24 값이 바뀌었다(지문 불일치)."""
|
||||
|
||||
http_status = 409
|
||||
|
||||
|
||||
class WriteBlocked(WriteError):
|
||||
"""반영 여부를 모르는 이전 시도가 남아 있다 — 사람이 확정하기 전에는 쓰지 않는다."""
|
||||
|
||||
http_status = 409
|
||||
|
||||
def __init__(self, message: str, *, attempts: list[dict[str, Any]] | None = None, **kw: Any):
|
||||
super().__init__(message, **kw)
|
||||
self.attempts = attempts or []
|
||||
|
||||
|
||||
class RemoteWriteFailed(WriteError):
|
||||
"""카페24가 거절 — 반영되지 않은 것이 확실하다."""
|
||||
|
||||
http_status = 502
|
||||
|
||||
|
||||
class RemoteWriteUnknown(WriteError):
|
||||
"""요청이 도달했을 수 있으나 응답을 못 받았다 — 반영 여부를 모른다. 재적용 금지."""
|
||||
|
||||
http_status = 502
|
||||
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# 잠금
|
||||
# ════════════════════════════════════════════════════════════
|
||||
def product_lock_key(product_no: int) -> str:
|
||||
return f"product:{int(product_no)}"
|
||||
|
||||
|
||||
def design_lock_key(file_key: str) -> str:
|
||||
return f"design:{file_key}"
|
||||
|
||||
|
||||
def lock_owner(actor: str) -> str:
|
||||
"""잠금 소유자 표기 — '사람|호스트:pid'. 안내 문구에는 '|' 앞(사람)만 쓴다."""
|
||||
return f"{actor or '-'}|{socket.gethostname()}:{os.getpid()}"
|
||||
|
||||
|
||||
def require_schema(st: Any) -> None:
|
||||
try:
|
||||
ok = st.write_schema_ready()
|
||||
except Exception as exc: # noqa: BLE001 — DB 접속 실패도 "쓰지 않음"으로
|
||||
raise WriteSetupError(f"cafe24_db 상태를 확인하지 못해 카페24에 쓰지 않았습니다: {type(exc).__name__}") from exc
|
||||
if not ok:
|
||||
raise WriteSetupError(
|
||||
"cafe24_db 마이그레이션 005(쓰기 안전장치)가 적용되지 않아 카페24에 쓰지 않았습니다. "
|
||||
"관리자에게 scripts/sql/cafe24_db_005_write_safety.sql 적용을 요청하세요."
|
||||
)
|
||||
|
||||
|
||||
@dataclass
|
||||
class WriteLock:
|
||||
st: Any
|
||||
key: str
|
||||
token: str
|
||||
ttl: int
|
||||
|
||||
def still_mine(self) -> bool:
|
||||
"""아직 내 잠금이면 연장하고 True(펜싱). 만료돼 넘어갔으면 False."""
|
||||
try:
|
||||
return bool(self.st.renew_lock(self.key, self.token, ttl_seconds=self.ttl))
|
||||
except Exception: # noqa: BLE001 — 확인할 수 없으면 쓰지 않는다
|
||||
logger.exception("잠금 연장 실패 %s", self.key)
|
||||
return False
|
||||
|
||||
|
||||
@contextmanager
|
||||
def write_lock(
|
||||
st: Any,
|
||||
key: str,
|
||||
*,
|
||||
actor: str,
|
||||
purpose: str,
|
||||
wait_seconds: float | None = None,
|
||||
ttl_seconds: int | None = None,
|
||||
) -> Iterator[WriteLock]:
|
||||
"""DB 잠금을 잡은 채 작업한다. 못 잡으면 WriteBusy, 스키마가 없으면 WriteSetupError."""
|
||||
require_schema(st)
|
||||
ttl = int(ttl_seconds or lock_ttl_seconds())
|
||||
wait = lock_wait_seconds() if wait_seconds is None else max(0.0, float(wait_seconds))
|
||||
deadline = time.monotonic() + wait
|
||||
while True:
|
||||
token = st.acquire_lock(key, owner=lock_owner(actor), purpose=purpose, ttl_seconds=ttl)
|
||||
if token:
|
||||
break
|
||||
if time.monotonic() >= deadline:
|
||||
raise WriteBusy(_busy_message(st, key))
|
||||
time.sleep(0.25)
|
||||
lock = WriteLock(st=st, key=key, token=token, ttl=ttl)
|
||||
try:
|
||||
yield lock
|
||||
finally:
|
||||
try:
|
||||
st.release_lock(key, token)
|
||||
except Exception: # noqa: BLE001 — 못 풀어도 만료되면 풀린다
|
||||
logger.exception("잠금 해제 실패 %s (만료 후 자동 해제)", key)
|
||||
|
||||
|
||||
def _busy_message(st: Any, key: str) -> str:
|
||||
try:
|
||||
holder = st.lock_holder(key) or {}
|
||||
except Exception: # noqa: BLE001
|
||||
holder = {}
|
||||
who = str(holder.get("owner") or "").split("|", 1)[0]
|
||||
what = str(holder.get("purpose") or "")
|
||||
detail = " · ".join(p for p in (what, who) if p and p != "-")
|
||||
return "다른 작업이 같은 대상을 수정하고 있습니다" + (f"({detail})" if detail else "") + ". 잠시 후 다시 시도하세요."
|
||||
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# 유효 현재값 — 읽기 지연 보정 (확인된 쓰기만 근거)
|
||||
# ════════════════════════════════════════════════════════════
|
||||
def resolve_effective(
|
||||
st: Any, product_no: int, cafe24_html: str, *, fetched_updated: object = None
|
||||
) -> tuple[str, str, dict[str, Any] | None]:
|
||||
"""(유효 HTML, 상태 store.SYNC_*, 마지막 확인된 쓰기)."""
|
||||
grace = read_lag_grace_minutes()
|
||||
since = now_kst() - timedelta(minutes=grace)
|
||||
lineage = st.write_lineage(product_no, since=since)
|
||||
if not lineage:
|
||||
return cafe24_html, store.SYNC_NONE, None
|
||||
last = lineage[0]
|
||||
effective, state = store.resolve_description(
|
||||
cafe24_html,
|
||||
last_write=last,
|
||||
known_digests=store.lineage_digests(lineage),
|
||||
grace_minutes=grace,
|
||||
fetched_updated=fetched_updated,
|
||||
)
|
||||
return effective, state, last
|
||||
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# 기록 — PUT 성공 뒤의 로컬 저장(실패해도 "적용 실패"가 아니다)
|
||||
# ════════════════════════════════════════════════════════════
|
||||
def remember_product_write(st: Any, product_no: int, updated: dict[str, Any]) -> tuple[dict[str, Any], str]:
|
||||
"""PUT 응답(상품 dict)을 캐시·스냅샷에 남긴다. (정규화된 상품 행, 기록 오류 문자열)."""
|
||||
info = products.normalize_product(updated) if updated else {}
|
||||
if not info.get("product_no"):
|
||||
return info, ""
|
||||
try:
|
||||
st.upsert_products([info])
|
||||
st.save_write_snapshot(product_no, "product", store.product_snapshot(updated))
|
||||
except Exception as exc: # noqa: BLE001 — 카페24에는 이미 반영됐다
|
||||
logger.exception("상품 %s 쓰기 스냅샷 저장 실패", product_no)
|
||||
return info, f"{type(exc).__name__}: {exc}"
|
||||
return info, ""
|
||||
|
||||
|
||||
def audit_safe(st: Any, **fields: Any) -> None:
|
||||
"""감사로그 — 실패해도 호출부 결과를 바꾸지 않는다(이미 카페24에 반영된 뒤일 수 있다)."""
|
||||
try:
|
||||
st.log_audit(**fields)
|
||||
except Exception: # noqa: BLE001
|
||||
logger.exception("감사로그 기록 실패: %s", fields.get("action"))
|
||||
|
||||
|
||||
def record_attempt(st: Any, attempt: dict[str, Any]) -> int:
|
||||
"""원격 반영된 시도의 버전을 남기고 RECORDED 로 바꾼다(이미 있으면 그 id). 멱등.
|
||||
|
||||
진열/판매만 바꾼 시도(상세설명 없음)는 버전을 만들지 않고 상태만 RECORDED 로 둔다.
|
||||
"""
|
||||
if not attempt.get("target_digest") and not attempt.get("target_revision_id"):
|
||||
st.update_attempt(int(attempt["id"]), status=store.ATTEMPT_RECORDED, remote_ok=True)
|
||||
return 0
|
||||
origin = str(attempt.get("origin") or store.ORIGIN_MANUAL)
|
||||
revision_type = store.ORIGIN_REVISION_TYPE.get(origin, "MANUAL")
|
||||
source = store.SOURCE_REVISION if origin == store.ORIGIN_ROLLBACK else ""
|
||||
source_revision = attempt.get("target_revision_id") if origin != store.ORIGIN_MANUAL else None
|
||||
return int(st.record_attempt_revision(
|
||||
int(attempt["id"]),
|
||||
revision_type=revision_type,
|
||||
memo=str(attempt.get("memo") or ""),
|
||||
created_by=str(attempt.get("actor") or ""),
|
||||
source=source,
|
||||
source_revision_id=int(source_revision) if source_revision else None,
|
||||
))
|
||||
|
||||
|
||||
def _flags_match(product: dict[str, Any], attempt: dict[str, Any]) -> bool:
|
||||
for key in ("set_display", "set_selling"):
|
||||
want = attempt.get(key)
|
||||
if want is None:
|
||||
continue
|
||||
field_name = key.replace("set_", "")
|
||||
if products._flag(product.get(field_name)) != bool(want): # noqa: SLF001 — 같은 규칙
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def attempt_matches_remote(attempt: dict[str, Any], product: dict[str, Any]) -> bool:
|
||||
"""카페24 현재값이 그 시도가 쓰려던 결과와 같은가(같으면 결과를 "반영됨"으로 확정해도 된다)."""
|
||||
if not product:
|
||||
return False
|
||||
digest = str(attempt.get("target_digest") or "")
|
||||
if digest and store.content_digest(str(product.get("description") or "")) != digest:
|
||||
return False
|
||||
if not digest and attempt.get("set_display") is None and attempt.get("set_selling") is None:
|
||||
return False
|
||||
return _flags_match(product, attempt)
|
||||
|
||||
|
||||
def settle_open_attempts(
|
||||
st: Any, product_no: int, *, product: dict[str, Any], actor: str = "SYSTEM"
|
||||
) -> list[dict[str, Any]]:
|
||||
"""열린 시도를 정리하고 **아직 결과를 모르는 것**만 돌려준다. 잠금 안에서 부른다.
|
||||
|
||||
REMOTE_OK → 버전 기록을 채운다(기록 복구)
|
||||
STARTED / UNKNOWN → 카페24 현재값이 그 시도의 결과와 같으면 반영됨으로 확정
|
||||
(예약이 "확인 필요"였다면 완료로 바꾼다). 다르면 남긴다.
|
||||
"""
|
||||
since = now_kst() - timedelta(minutes=read_lag_grace_minutes())
|
||||
unresolved: list[dict[str, Any]] = []
|
||||
for attempt in st.open_attempts(product_no, since=since):
|
||||
status = attempt.get("status")
|
||||
if status == store.ATTEMPT_REMOTE_OK:
|
||||
try:
|
||||
record_attempt(st, attempt)
|
||||
except Exception: # noqa: BLE001 — 원격은 반영됨. 다음 기회에 다시.
|
||||
logger.exception("시도 #%s 기록 복구 실패", attempt.get("id"))
|
||||
continue
|
||||
if attempt_matches_remote(attempt, product):
|
||||
st.update_attempt(
|
||||
int(attempt["id"]), status=store.ATTEMPT_REMOTE_OK, remote_ok=True,
|
||||
resolved_by="auto:카페24 값이 요청 결과와 같음",
|
||||
only_from=(store.ATTEMPT_STARTED, store.ATTEMPT_UNKNOWN),
|
||||
)
|
||||
try:
|
||||
record_attempt(st, attempt)
|
||||
except Exception: # noqa: BLE001
|
||||
logger.exception("시도 #%s 기록 실패(자동 확정 후)", attempt.get("id"))
|
||||
if attempt.get("schedule_id"):
|
||||
st.review_schedule(
|
||||
int(attempt["schedule_id"]), status=store.STATUS_SUCCESS,
|
||||
note="자동 확인: 카페24 현재값이 예약 내용과 같습니다", actor=actor, action="auto_verify",
|
||||
)
|
||||
continue
|
||||
unresolved.append(attempt)
|
||||
return unresolved
|
||||
|
||||
|
||||
def describe_attempt(attempt: dict[str, Any]) -> str:
|
||||
origin = {store.ORIGIN_MANUAL: "즉시 적용", store.ORIGIN_SCHEDULED: "예약", store.ORIGIN_ROLLBACK: "복원"}.get(
|
||||
str(attempt.get("origin") or ""), "적용")
|
||||
when = str(attempt.get("created_at") or "").replace("T", " ")[:16]
|
||||
who = str(attempt.get("actor") or "")
|
||||
sched = f" · 예약 #{attempt['schedule_id']}" if attempt.get("schedule_id") else ""
|
||||
return f"시도 #{attempt.get('id')} ({origin}{sched}, {when}{', ' + who if who else ''})"
|
||||
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# 본 처리
|
||||
# ════════════════════════════════════════════════════════════
|
||||
@dataclass
|
||||
class WriteOutcome:
|
||||
attempt_id: int = 0
|
||||
backup_id: int = 0
|
||||
revision_id: int = 0
|
||||
changed: bool = True # False = 바뀐 것이 없어 PUT 하지 않음
|
||||
pending: bool = False # 백업이 "마지막 확인된 쓰기" 기준이었나(카페24 읽기 지연)
|
||||
recorded: bool = False # 버전 기록까지 끝났나
|
||||
record_error: str = "" # PUT 성공 뒤 로컬 기록 실패 사유(재적용 금지 — 자동 복구)
|
||||
confirmed: bool = False # PUT 뒤 GET 이 새 값을 돌려줬나
|
||||
updated: dict[str, Any] = field(default_factory=dict)
|
||||
|
||||
|
||||
def write_product(
|
||||
st: Any,
|
||||
api: Any,
|
||||
product_no: int,
|
||||
*,
|
||||
lock: WriteLock,
|
||||
origin: str,
|
||||
actor: str,
|
||||
html: str | None,
|
||||
base_fingerprint: str | None = None,
|
||||
set_display: bool | None = None,
|
||||
set_selling: bool | None = None,
|
||||
schedule_id: int | None = None,
|
||||
target_revision_id: int | None = None,
|
||||
memo: str = "",
|
||||
skip_if_same: bool = False,
|
||||
extra_fence: Callable[[], bool] | None = None,
|
||||
wait_confirm: bool = True,
|
||||
) -> WriteOutcome:
|
||||
"""상세설명(html)·진열/판매를 카페24에 쓴다. 잠금(lock)을 잡은 채 부른다.
|
||||
|
||||
예외(아무것도 쓰지 않음): Cafe24Error(현재값 조회 실패), WriteBlocked, WriteConflict,
|
||||
WriteBusy(펜싱 실패) / RemoteWriteFailed(거절) / RemoteWriteUnknown(반영 여부 모름).
|
||||
PUT 성공 뒤의 로컬 기록 실패는 예외가 아니라 WriteOutcome.record_error 로 알린다.
|
||||
"""
|
||||
mall_id = str(getattr(api.config, "mall_id", "") or "")
|
||||
shop_no = 1
|
||||
out = WriteOutcome()
|
||||
current_html: str | None = None
|
||||
effective: str | None = None
|
||||
|
||||
if html is not None:
|
||||
product = products.get_product(api.client, product_no)
|
||||
if not product:
|
||||
raise Cafe24Error("카페24에서 상품을 찾지 못했습니다.")
|
||||
desc = products.descriptions_from_product(product)
|
||||
current_html = desc.description
|
||||
|
||||
unresolved = [a for a in settle_open_attempts(st, product_no, product=product, actor=actor)
|
||||
if a.get("target_digest")]
|
||||
if unresolved:
|
||||
names = ", ".join(describe_attempt(a) for a in unresolved[:3])
|
||||
raise WriteBlocked(
|
||||
f"이전 적용의 반영 여부를 아직 확인하지 못했습니다: {names}. "
|
||||
"쇼핑몰에서 확인한 뒤 편집기 위 안내에서 결과를 확정하고 다시 시도하세요.",
|
||||
attempts=unresolved,
|
||||
)
|
||||
|
||||
effective, state, last = resolve_effective(
|
||||
st, product_no, current_html, fetched_updated=product.get("updated_date")
|
||||
)
|
||||
out.pending = state == store.SYNC_PENDING
|
||||
label = {store.ORIGIN_SCHEDULED: f"예약 #{schedule_id} 적용 직전 자동 백업",
|
||||
store.ORIGIN_ROLLBACK: "복원 직전 자동 백업"}.get(origin, "적용 직전 자동 백업")
|
||||
out.backup_id = st.add_revision(
|
||||
product_no=product_no,
|
||||
html_content=effective,
|
||||
revision_type=store.REVISION_BACKUP,
|
||||
memo=label + (" (카페24 읽기 지연 — 마지막으로 확인된 적용값 기준)" if out.pending else ""),
|
||||
created_by=actor,
|
||||
mall_id=mall_id,
|
||||
shop_no=shop_no,
|
||||
source=store.SOURCE_LAST_WRITE if out.pending else store.SOURCE_OBSERVED,
|
||||
source_revision_id=(last or {}).get("applied_revision_id") if out.pending else None,
|
||||
)
|
||||
# 모바일이 PC 와 달랐다면 그것도 남긴다 — 아래 쓰기로 모바일이 PC 와 같아진다.
|
||||
if desc.mobile_description and desc.mobile_description != desc.description:
|
||||
st.add_revision(
|
||||
product_no=product_no,
|
||||
html_content=desc.mobile_description,
|
||||
revision_type=store.REVISION_BACKUP,
|
||||
memo=label + " (모바일 — PC와 달랐던 내용)",
|
||||
created_by=actor,
|
||||
mall_id=mall_id,
|
||||
shop_no=shop_no,
|
||||
source=store.SOURCE_OBSERVED,
|
||||
)
|
||||
if base_fingerprint and base_fingerprint != store.fingerprint(effective):
|
||||
raise WriteConflict(
|
||||
"편집하는 동안 카페24 값이 변경되었습니다. 새로고침해 현재 내용을 확인한 뒤 다시 적용하세요.",
|
||||
backup_id=out.backup_id,
|
||||
)
|
||||
if skip_if_same and html == effective and set_display is None and set_selling is None:
|
||||
out.changed = False
|
||||
return out
|
||||
|
||||
# 펜싱 — 잠금이 만료돼 남에게 넘어갔으면 쓰지 않는다.
|
||||
if not lock.still_mine() or (extra_fence is not None and not extra_fence()):
|
||||
raise WriteBusy("작업 시간이 길어져 잠금이 만료되었습니다. 카페24에 쓰지 않았습니다 — 다시 시도하세요.",
|
||||
backup_id=out.backup_id)
|
||||
|
||||
out.attempt_id = st.start_attempt(
|
||||
product_no=int(product_no),
|
||||
mall_id=mall_id,
|
||||
shop_no=shop_no,
|
||||
origin=origin,
|
||||
schedule_id=schedule_id,
|
||||
actor=actor,
|
||||
backup_revision_id=out.backup_id or None,
|
||||
observed_digest=store.content_digest(current_html) if current_html is not None else "",
|
||||
base_digest=store.content_digest(effective) if effective is not None else "",
|
||||
target_digest=store.content_digest(html) if html is not None else "",
|
||||
# 예약·복원은 내용이 버전(target_revision_id)에 있다 — 즉시 적용만 시도에 보관한다.
|
||||
target_html=html if (html is not None and not target_revision_id) else "",
|
||||
target_revision_id=target_revision_id,
|
||||
set_display=set_display,
|
||||
set_selling=set_selling,
|
||||
memo=(memo or "")[:500],
|
||||
)
|
||||
|
||||
try:
|
||||
updated = products.update_product(
|
||||
api.client,
|
||||
product_no,
|
||||
description=html,
|
||||
# PC/모바일 구분 안 함 — mobile_description 은 보내지 않고 "PC 와 동일"을 강제.
|
||||
separated_mobile_description="F" if html is not None else None,
|
||||
display=set_display,
|
||||
selling=set_selling,
|
||||
)
|
||||
except Exception as exc: # noqa: BLE001 — 분류해서 다시 던진다
|
||||
known = isinstance(exc, Cafe24Error)
|
||||
unknown = (not known) or bool(getattr(exc, "maybe_applied", False))
|
||||
message = str(exc) if known else f"{type(exc).__name__}: {exc}"
|
||||
try:
|
||||
st.update_attempt(
|
||||
out.attempt_id,
|
||||
status=store.ATTEMPT_UNKNOWN if unknown else store.ATTEMPT_REMOTE_FAILED,
|
||||
error=message,
|
||||
only_from=(store.ATTEMPT_STARTED,),
|
||||
)
|
||||
except Exception: # noqa: BLE001 — 기록 실패 시 STARTED 로 남는다(= 결과 모름, 안전 쪽)
|
||||
logger.exception("시도 #%s 결과 기록 실패", out.attempt_id)
|
||||
kind = RemoteWriteUnknown if unknown else RemoteWriteFailed
|
||||
raise kind(message, backup_id=out.backup_id, attempt_id=out.attempt_id) from exc
|
||||
|
||||
# ── 여기부터는 카페24에 반영된 뒤다. 무엇이 실패해도 "적용 실패"가 아니다. ──
|
||||
out.updated = updated if isinstance(updated, dict) else {}
|
||||
errors: list[str] = []
|
||||
try:
|
||||
st.update_attempt(
|
||||
out.attempt_id, status=store.ATTEMPT_REMOTE_OK, remote_ok=True,
|
||||
remote_updated_at=str(out.updated.get("updated_date") or ""),
|
||||
only_from=(store.ATTEMPT_STARTED,),
|
||||
)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
logger.exception("시도 #%s REMOTE_OK 기록 실패", out.attempt_id)
|
||||
errors.append(f"시도 상태: {type(exc).__name__}")
|
||||
if out.updated.get("product_no"):
|
||||
_, snap_error = remember_product_write(st, product_no, out.updated)
|
||||
if snap_error:
|
||||
errors.append(f"스냅샷: {snap_error}")
|
||||
try:
|
||||
out.revision_id = record_attempt(st, {
|
||||
"id": out.attempt_id, "origin": origin, "actor": actor, "memo": memo,
|
||||
"target_revision_id": target_revision_id,
|
||||
"target_digest": store.content_digest(html) if html is not None else "",
|
||||
})
|
||||
out.recorded = True
|
||||
except Exception as exc: # noqa: BLE001
|
||||
logger.exception("시도 #%s 버전 기록 실패", out.attempt_id)
|
||||
errors.append(f"버전 기록: {type(exc).__name__}: {exc}")
|
||||
out.record_error = "; ".join(errors)
|
||||
|
||||
if html is not None and wait_confirm:
|
||||
# 카페24 관리자 API 의 쓰기 직후 읽기 지연을 짧게 흡수(확인 실패는 실패가 아니다).
|
||||
out.confirmed = products.wait_for_description(api.client, product_no, html)
|
||||
return out
|
||||
@@ -59,29 +59,86 @@
|
||||
|
||||
var state = { option: null, variants: [], displayTypes: {}, orphans: [], imageBase: "" };
|
||||
|
||||
// 모달은 페이지에 하나라 여러 상품이 같은 body 를 쓴다. 이 상품으로 연 "회차"(modal.gen)가
|
||||
// 바뀌었거나(닫힘·다른 상품) 더 나중에 보낸 조회가 있으면, 늦게 도착한 응답은 버린다.
|
||||
// (A 상품 응답이 B 상품 창에 그려지거나, 먼저 보낸 조회가 나중 조회를 덮는 것을 막는다.)
|
||||
var myGen = -1;
|
||||
var loadSeq = 0;
|
||||
function alive() { return modal.isOpen() && modal.gen === myGen; }
|
||||
|
||||
openBtn.addEventListener("click", function () {
|
||||
var nameEl = document.getElementById("cf24-name-text");
|
||||
modal.open((nameEl ? nameEl.textContent : "") + " (상품번호 " + no + ")");
|
||||
myGen = modal.gen;
|
||||
load();
|
||||
});
|
||||
|
||||
function load() {
|
||||
var seq = ++loadSeq;
|
||||
var gen = myGen;
|
||||
body.innerHTML = '<p class="cf24-muted">카페24에서 불러오는 중…</p>';
|
||||
return apiJson("GET", "/cafe24/products/" + no + "/options")
|
||||
.then(function (data) {
|
||||
if (seq !== loadSeq || gen !== modal.gen || !modal.isOpen()) return false;
|
||||
state.option = data.option;
|
||||
state.variants = data.variants || [];
|
||||
state.displayTypes = data.display_types || {};
|
||||
state.imageBase = data.image_base || "";
|
||||
render();
|
||||
return true;
|
||||
})
|
||||
.catch(function (err) {
|
||||
if (seq !== loadSeq || gen !== modal.gen || !modal.isOpen()) return false;
|
||||
body.innerHTML = '<p class="cf24-err">옵션을 불러오지 못했습니다: ' + esc(err.message) +
|
||||
'</p><button type="button" class="erp-btn erp-btn-outline" id="cf24-opt-retry">다시 시도</button>';
|
||||
body.querySelector("#cf24-opt-retry").addEventListener("click", load);
|
||||
return false;
|
||||
});
|
||||
}
|
||||
|
||||
// 다시 불러오되, 아직 카페24에 저장되지 못한 품목 입력(자체코드·추가금액·진열/판매)은 옵션값
|
||||
// 이름으로 짝지어 되살린다. 품목코드가 늦게 나타나거나 일부 행 저장이 실패했을 때 입력을
|
||||
// 잃지 않게 한다(실패 뒤 자동으로 새로 읽어 입력을 지우던 문제).
|
||||
function reloadKeeping(keep, errors) {
|
||||
return load().then(function (ok) {
|
||||
if (!ok) return 0;
|
||||
var tbody = body.querySelector("#cf24-u-body");
|
||||
if (!tbody) return 0;
|
||||
var restored = 0;
|
||||
Array.prototype.forEach.call(tbody.children, function (tr) {
|
||||
var nameEl = tr.querySelector('[name="option_text"]');
|
||||
var k = nameEl && keep[norm(nameEl.value)];
|
||||
if (!k) return;
|
||||
var changed = false;
|
||||
[["custom_variant_code", k.custom], ["additional_amount", k.amount]].forEach(function (pair) {
|
||||
var el = tr.querySelector('[name="' + pair[0] + '"]');
|
||||
if (el && pair[1] != null && el.value !== pair[1]) {
|
||||
el.value = pair[1];
|
||||
el.dispatchEvent(new Event("input"));
|
||||
changed = true;
|
||||
}
|
||||
});
|
||||
["display", "selling"].forEach(function (flag) {
|
||||
var btn = tr.querySelector('.cf24-v-toggle[data-flag="' + flag + '"]');
|
||||
if (btn && k[flag] != null && btn.dataset.on !== k[flag]) { paintToggle(btn, k[flag] === "1", false); changed = true; }
|
||||
});
|
||||
var why = errors && errors[norm(nameEl.value)];
|
||||
if (why) { tr.classList.add("is-error"); tr.title = "저장 실패: " + why; }
|
||||
if (changed || why) restored++;
|
||||
});
|
||||
return restored;
|
||||
});
|
||||
}
|
||||
|
||||
function rowValues(tr) {
|
||||
return {
|
||||
custom: tr.querySelector('[name="custom_variant_code"]').value,
|
||||
amount: tr.querySelector('[name="additional_amount"]').value,
|
||||
display: tr.querySelector('.cf24-v-toggle[data-flag="display"]').dataset.on,
|
||||
selling: tr.querySelector('.cf24-v-toggle[data-flag="selling"]').dataset.on
|
||||
};
|
||||
}
|
||||
|
||||
/* ── 공통 조각 ── */
|
||||
function typeSelect(current, name) {
|
||||
var out = '<select name="' + name + '">';
|
||||
@@ -236,25 +293,34 @@
|
||||
통합 목록 — 옵션값 1 : 품목 1
|
||||
═══════════════════════════════════════════════════════════ */
|
||||
// 행 = 품목 목록 순서. index 는 options 응답 안 위치(옵션 PUT 짝맞춤용).
|
||||
// 품목이 없는 옵션값은 state.orphans 로 따로 모은다(행으로 그리지 않는다).
|
||||
// 품목과 옵션값은 **옵션값 번호(value_no)** 로 먼저 짝짓고, 없을 때만 이름으로 짝짓는다.
|
||||
// (옵션값 이름을 바꾼 직후 카페24 품목 조회가 예전 이름을 돌려줘도 정상 품목이 숨지 않게.
|
||||
// 서버가 품목코드별 쓰기 기록으로 표기를 바로잡고 value_no 를 붙여 준다.)
|
||||
// 방금 추가해 품목이 아직 안 보이는 옵션값(pending)은 "품목 생성 대기" 행으로 그린다.
|
||||
// 그 밖에 품목이 없는 옵션값은 state.orphans 로 따로 모은다(행으로 그리지 않는다).
|
||||
function unifiedRows() {
|
||||
var opt = state.option;
|
||||
state.orphans = [];
|
||||
if (!opt || !opt.has_option) return [];
|
||||
var group = opt.options[0];
|
||||
var byText = {};
|
||||
group.option_value.forEach(function (v, vi) { byText[v.option_text] = { index: vi, value: v, variant: null }; });
|
||||
var entries = group.option_value.map(function (v, vi) { return { index: vi, value: v, variant: null }; });
|
||||
var byNo = {}, byText = {};
|
||||
entries.forEach(function (r) {
|
||||
if (r.value.value_no != null && r.value.value_no !== "") byNo[String(r.value.value_no)] = r;
|
||||
if (!byText[r.value.option_text]) byText[r.value.option_text] = r;
|
||||
});
|
||||
var rows = [];
|
||||
state.variants.forEach(function (variant) {
|
||||
if (!variant.options.length) return;
|
||||
var r = byText[variant.options[0].value];
|
||||
var r = (variant.value_no != null && byNo[String(variant.value_no)]) || byText[variant.options[0].value];
|
||||
if (!r || r.variant) return;
|
||||
r.variant = variant;
|
||||
rows.push(r);
|
||||
});
|
||||
group.option_value.forEach(function (v) {
|
||||
var r = byText[v.option_text];
|
||||
if (rows.indexOf(r) < 0) state.orphans.push(r);
|
||||
entries.forEach(function (r) {
|
||||
if (r.variant) return;
|
||||
if (r.value.pending) { r.await = true; rows.push(r); }
|
||||
else state.orphans.push(r);
|
||||
});
|
||||
return rows;
|
||||
}
|
||||
@@ -266,8 +332,10 @@
|
||||
var thumbSrc = [v.option_image_file, v.option_link_image,
|
||||
state.option && state.option.has_option ? variantImageFor(state.option.options[0].option_name, v.option_text) : ""];
|
||||
var code = variant ? variant.variant_code : "";
|
||||
var awaiting = !!r.await && !code;
|
||||
// data-index: options 응답 안 위치(옵션 PUT 짝맞춤용, 새 행은 빈 값) / data-pos: 처음 그린 순서(순서 변경 판정용)
|
||||
return '<tr class="cf24-u-row' + (isNewRow ? " is-new" : "") + '" data-index="' + (isNewRow ? "" : r.index) + '" data-pos="' + (position == null ? "" : position) + '" data-code="' + esc(code) + '">' +
|
||||
// data-await: 옵션값은 카페24에 있으나 품목코드가 아직 조회되지 않음 — 입력은 받고, 저장 때 코드를 다시 찾는다.
|
||||
return '<tr class="cf24-u-row' + (isNewRow ? " is-new" : "") + (awaiting ? " is-await" : "") + '" data-index="' + (isNewRow ? "" : r.index) + '" data-pos="' + (position == null ? "" : position) + '" data-code="' + esc(code) + '"' + (awaiting ? ' data-await="1"' : "") + '>' +
|
||||
'<td class="cf24-u-drag">' + (canDrag ? '<span class="cf24-drag-handle" draggable="true" title="드래그하여 순서 변경">⋮⋮</span>' : "") + "</td>" +
|
||||
'<td class="cf24-u-thumb"><span class="cf24-opt-thumb-slot">' + thumbHtml(thumbSrc, v.option_image_file ? "옵션 버튼 이미지" : v.option_link_image ? "옵션 연결 이미지" : "품목 이미지") + "</span>" +
|
||||
'<input type="hidden" name="option_image_file" value="' + esc(v.option_image_file || "") + '" />' +
|
||||
@@ -276,12 +344,14 @@
|
||||
'<td class="cf24-u-name"><input type="text" name="option_text" value="' + esc(v.option_text) + '" placeholder="옵션값 이름" /></td>' +
|
||||
'<td class="cf24-v-syscode">' + (code
|
||||
? '<button type="button" class="cf24-v-copy" data-copy-text="' + esc(code) + '" title="클릭하면 품목코드를 복사합니다">' + esc(code) + "</button>"
|
||||
: '<span class="cf24-muted">저장 시 부여</span>') + "</td>" +
|
||||
: awaiting
|
||||
? '<span class="cf24-muted" title="카페24가 품목을 만드는 중이거나 조회가 늦습니다. 입력해 두면 저장할 때 코드를 다시 찾아 반영합니다.">품목 생성 대기</span>'
|
||||
: '<span class="cf24-muted">저장 시 부여</span>') + "</td>" +
|
||||
'<td class="cf24-v-code"><input type="text" name="custom_variant_code" maxlength="40" value="' + esc(variant ? variant.custom_variant_code : "") + '" /></td>' +
|
||||
'<td class="cf24-v-amount"><input type="text" name="additional_amount" inputmode="numeric" value="' + esc(amountPlain(variant ? variant.additional_amount : "0")) + '" /></td>' +
|
||||
'<td class="cf24-v-flag">' + toggleBtn("display", variant ? !!variant.display : true) + "</td>" +
|
||||
'<td class="cf24-v-flag">' + toggleBtn("selling", variant ? !!variant.selling : true) + "</td>" +
|
||||
'<td class="cf24-u-del"><button type="button" class="cf24-u-remove" title="' + (isNewRow ? "행 삭제" : "품목 삭제 (카페24에 바로 반영)") + '">✕</button></td>' +
|
||||
'<td class="cf24-u-del">' + (awaiting ? "" : '<button type="button" class="cf24-u-remove" title="' + (isNewRow ? "행 삭제" : "품목 삭제 (카페24에 바로 반영)") + '">✕</button>') + "</td>" +
|
||||
"</tr>";
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,155 @@
|
||||
-- =====================================================================
|
||||
-- cafe24_db 005 — 쓰기 안전장치
|
||||
-- 1) 상품·디자인 파일별 쓰기 잠금(lease) cafe24_write_locks
|
||||
-- 2) 카페24 쓰기 시도 기록(원격 결과·기록 단계) cafe24_write_attempts
|
||||
-- 3) 버전(revision)의 쇼핑몰·출처 메타데이터 cafe24_product_revisions
|
||||
-- 4) 예약 실행 lease + "확인 필요" 상태 cafe24_product_schedules
|
||||
-- =====================================================================
|
||||
-- 멱등(idempotent): 여러 번 실행해도 안전. 데이터 DROP/TRUNCATE/DELETE 없음.
|
||||
-- (예약 상태 CHECK 제약만 새 값 목록으로 교체한다 — 데이터는 그대로다.)
|
||||
--
|
||||
-- ⚠️ 운영 적용은 사용자 승인 + 백업 확인 후. 코드 배포 **전에** 적용한다
|
||||
-- (새 코드는 이 표가 없으면 카페24 쓰기를 거부한다 — 잠금 없이 쓰지 않기 위해).
|
||||
--
|
||||
-- 실행:
|
||||
-- docker exec -i postgres-db psql -U postgres -d cafe24_db \
|
||||
-- < scripts/sql/cafe24_db_005_write_safety.sql
|
||||
--
|
||||
-- 배경 (docs/CAFE24_MODULE.md 3-5):
|
||||
-- - 같은 상품을 두 사람(또는 웹 + 예약 worker)이 동시에 적용하면 둘 다 성공하고
|
||||
-- 나중 것이 앞의 것을 조용히 덮었다 → 상품별 DB 잠금(만료시각이 있는 lease).
|
||||
-- 프로세스가 죽어도 만료되면 다른 요청이 가져간다.
|
||||
-- - 읽기 지연 판정이 "우리가 아는 값" 목록에 충돌로 거절된 적용의 백업·초안까지
|
||||
-- 넣어, 관리자에서 직접 고친 값을 지연으로 오판했다 → 원격 쓰기가 **성공한**
|
||||
-- 시도만 판정 근거로 쓴다(이 표의 status).
|
||||
-- - 원격 쓰기는 성공했는데 로컬 기록이 실패하면 FAILED 로 보이고 재적용됐다
|
||||
-- → 원격 결과와 기록 단계를 나눠 남긴다.
|
||||
-- - worker 가 PROCESSING 중에 죽으면 영구히 남았다 → lease 만료 후 시도 기록을
|
||||
-- 보고 성공/재시도/확인 필요로 나눈다(무조건 PENDING 으로 돌리지 않는다).
|
||||
-- =====================================================================
|
||||
|
||||
\set ON_ERROR_STOP on
|
||||
|
||||
-- ── updated_at 트리거 함수 (init 에 있지만 단독 실행 대비) ──
|
||||
CREATE OR REPLACE FUNCTION cafe24_set_updated_at() RETURNS trigger AS $$
|
||||
BEGIN
|
||||
NEW.updated_at := now();
|
||||
RETURN NEW;
|
||||
END;
|
||||
$$ LANGUAGE plpgsql;
|
||||
|
||||
-- ════════════════════════════════════════════════════════════
|
||||
-- 1) 쓰기 잠금 — lock_key 예: 'product:131', 'design:pc_detail'
|
||||
-- 잡기: INSERT … ON CONFLICT DO UPDATE … WHERE expires_at < now()
|
||||
-- 풀기: DELETE … WHERE lock_key = ? AND token = ?
|
||||
-- 원격 쓰기 직전 token 으로 연장(펜싱) — 만료돼 남에게 넘어갔으면 쓰지 않는다.
|
||||
-- ════════════════════════════════════════════════════════════
|
||||
CREATE TABLE IF NOT EXISTS cafe24_write_locks (
|
||||
lock_key TEXT PRIMARY KEY,
|
||||
owner TEXT NOT NULL DEFAULT '',
|
||||
token TEXT NOT NULL,
|
||||
purpose TEXT NOT NULL DEFAULT '',
|
||||
acquired_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
expires_at TIMESTAMPTZ NOT NULL
|
||||
);
|
||||
|
||||
-- ════════════════════════════════════════════════════════════
|
||||
-- 2) 쓰기 시도 기록 (상세설명·진열/판매를 카페24에 PUT 하는 작업)
|
||||
-- status
|
||||
-- STARTED PUT 직전에 남김. 이 상태로 남아 있으면 결과를 모른다.
|
||||
-- REMOTE_OK 카페24 PUT 성공. 로컬 버전 기록은 아직(기록 복구 필요).
|
||||
-- RECORDED PUT 성공 + 버전(MANUAL/SCHEDULED/ROLLBACK) 기록 완료.
|
||||
-- REMOTE_FAILED 카페24가 거절(요청이 반영되지 않음이 확실).
|
||||
-- UNKNOWN 네트워크 끊김·5xx 등으로 반영 여부를 모름 → 사람 확인.
|
||||
-- ABANDONED 사람이 "반영 안 됨"으로 확정했거나 재실행으로 대체됨.
|
||||
-- target_html 은 기록(RECORDED) 전까지만 보관한다(기록 복구용). 기록 후 비운다.
|
||||
-- ════════════════════════════════════════════════════════════
|
||||
CREATE TABLE IF NOT EXISTS cafe24_write_attempts (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
product_no BIGINT NOT NULL,
|
||||
mall_id TEXT NOT NULL DEFAULT '',
|
||||
shop_no INTEGER NOT NULL DEFAULT 1,
|
||||
origin TEXT NOT NULL DEFAULT 'MANUAL',
|
||||
schedule_id BIGINT,
|
||||
actor TEXT NOT NULL DEFAULT '',
|
||||
status TEXT NOT NULL DEFAULT 'STARTED',
|
||||
backup_revision_id BIGINT,
|
||||
observed_digest TEXT NOT NULL DEFAULT '',
|
||||
base_digest TEXT NOT NULL DEFAULT '',
|
||||
target_digest TEXT NOT NULL DEFAULT '',
|
||||
target_html TEXT NOT NULL DEFAULT '',
|
||||
target_revision_id BIGINT,
|
||||
applied_revision_id BIGINT,
|
||||
set_display BOOLEAN,
|
||||
set_selling BOOLEAN,
|
||||
memo TEXT NOT NULL DEFAULT '',
|
||||
remote_updated_at TEXT NOT NULL DEFAULT '',
|
||||
error TEXT NOT NULL DEFAULT '',
|
||||
resolved_by TEXT NOT NULL DEFAULT '',
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
remote_at TIMESTAMPTZ,
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
CONSTRAINT chk_cafe24_attempt_status CHECK (
|
||||
status IN ('STARTED','REMOTE_OK','RECORDED','REMOTE_FAILED','UNKNOWN','ABANDONED')
|
||||
),
|
||||
CONSTRAINT chk_cafe24_attempt_origin CHECK (
|
||||
origin IN ('MANUAL','SCHEDULED','ROLLBACK')
|
||||
)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_cafe24_attempts_product
|
||||
ON cafe24_write_attempts (product_no, created_at DESC, id DESC);
|
||||
CREATE INDEX IF NOT EXISTS idx_cafe24_attempts_schedule
|
||||
ON cafe24_write_attempts (schedule_id) WHERE schedule_id IS NOT NULL;
|
||||
CREATE INDEX IF NOT EXISTS idx_cafe24_attempts_open
|
||||
ON cafe24_write_attempts (product_no, created_at DESC)
|
||||
WHERE status IN ('STARTED','REMOTE_OK','UNKNOWN');
|
||||
|
||||
DROP TRIGGER IF EXISTS trg_cafe24_write_attempts_updated ON cafe24_write_attempts;
|
||||
CREATE TRIGGER trg_cafe24_write_attempts_updated
|
||||
BEFORE UPDATE ON cafe24_write_attempts
|
||||
FOR EACH ROW EXECUTE FUNCTION cafe24_set_updated_at();
|
||||
|
||||
-- ════════════════════════════════════════════════════════════
|
||||
-- 3) 버전 메타데이터 (append-only 는 그대로 — INSERT 시점에만 채운다)
|
||||
-- mall_id / shop_no 어느 쇼핑몰의 버전인가(복원 시 일치 검사). 기존 행은 ''/1
|
||||
-- source BACKUP 의 출처
|
||||
-- OBSERVED 카페24 GET 으로 읽은 값
|
||||
-- LAST_WRITE 카페24가 읽기 지연 중이라 우리 마지막 쓰기(확인된
|
||||
-- 적용값)를 현재값으로 본 것
|
||||
-- ROLLBACK 은 'REVISION'(source_revision_id = 복원한 버전)
|
||||
-- source_revision_id LAST_WRITE 백업이 근거로 삼은 버전 / ROLLBACK 원본 버전
|
||||
-- ════════════════════════════════════════════════════════════
|
||||
ALTER TABLE cafe24_product_revisions
|
||||
ADD COLUMN IF NOT EXISTS mall_id TEXT NOT NULL DEFAULT '',
|
||||
ADD COLUMN IF NOT EXISTS shop_no INTEGER NOT NULL DEFAULT 1,
|
||||
ADD COLUMN IF NOT EXISTS source TEXT NOT NULL DEFAULT '',
|
||||
ADD COLUMN IF NOT EXISTS source_revision_id BIGINT;
|
||||
|
||||
-- ════════════════════════════════════════════════════════════
|
||||
-- 4) 예약 lease + 상태 NEEDS_REVIEW(확인 필요)
|
||||
-- PROCESSING 은 lease_expires_at 까지만 유효하다. 만료되면 worker 가 시도 기록을 보고
|
||||
-- 기록 완료/원격 성공 → SUCCESS, 원격 거절 → 재시도 규칙, 원격 전 중단 → 재시도 규칙,
|
||||
-- 결과 모름 → NEEDS_REVIEW (사람이 카페24를 보고 확정)
|
||||
-- lease 컬럼이 비어 있는 옛 PROCESSING 행은 started_at 기준으로 만료를 판정한다.
|
||||
-- ════════════════════════════════════════════════════════════
|
||||
ALTER TABLE cafe24_product_schedules
|
||||
ADD COLUMN IF NOT EXISTS lease_owner TEXT NOT NULL DEFAULT '',
|
||||
ADD COLUMN IF NOT EXISTS lease_token TEXT NOT NULL DEFAULT '',
|
||||
ADD COLUMN IF NOT EXISTS lease_expires_at TIMESTAMPTZ;
|
||||
|
||||
ALTER TABLE cafe24_product_schedules
|
||||
DROP CONSTRAINT IF EXISTS chk_cafe24_schedule_status;
|
||||
ALTER TABLE cafe24_product_schedules
|
||||
ADD CONSTRAINT chk_cafe24_schedule_status CHECK (
|
||||
status IN ('PENDING','PROCESSING','SUCCESS','FAILED','CANCELLED','NEEDS_REVIEW')
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_cafe24_schedules_processing
|
||||
ON cafe24_product_schedules (lease_expires_at)
|
||||
WHERE status = 'PROCESSING';
|
||||
|
||||
-- ── 권한 (cafe24_app: CRUD only) ──
|
||||
GRANT SELECT, INSERT, UPDATE, DELETE ON cafe24_write_locks, cafe24_write_attempts TO cafe24_app;
|
||||
GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA public TO cafe24_app;
|
||||
|
||||
SELECT 'cafe24_db 005 applied' AS status;
|
||||
@@ -0,0 +1,633 @@
|
||||
"""카페24 모듈 — 실제 PostgreSQL 잠금·lease·JSONB 병합 + FastAPI 라우트 통합 테스트.
|
||||
|
||||
운영 DB 와 분리된 **로컬 테스트용 PostgreSQL** 에서만 돈다. 카페24 API·FTP 는 가짜
|
||||
(app/modules/cafe24/tests/fakes.py)이며 실제 쇼핑몰·디자인 파일은 건드리지 않는다.
|
||||
|
||||
# 1) 로컬 테스트 DB 에 스키마 적용(최초 1회)
|
||||
# psql -v app_password=... -f scripts/sql/cafe24_db_init.sql
|
||||
# psql -d cafe24_db -f scripts/sql/cafe24_db_002_… 003 … 004 … 005_write_safety.sql
|
||||
# 2) 실행
|
||||
CAFE24_TEST_DB_URL=postgresql://postgres@localhost:55432/cafe24_db python tests/test_cafe24_db.py
|
||||
|
||||
CAFE24_TEST_DB_URL 이 없거나 localhost/127.0.0.1 이 아니면 전부 건너뛴다(운영 DB 보호).
|
||||
테스트마다 새 상품번호를 쓰고 기존 행을 지우지 않는다.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import random
|
||||
import sys
|
||||
import threading
|
||||
import types
|
||||
from datetime import timedelta
|
||||
from urllib.parse import parse_qs, urlparse
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
|
||||
DSN = os.getenv("CAFE24_TEST_DB_URL", "")
|
||||
_host = urlparse(DSN).hostname if DSN else None
|
||||
ENABLED = bool(DSN) and _host in ("localhost", "127.0.0.1")
|
||||
|
||||
logging.getLogger("cafe24").setLevel(logging.CRITICAL)
|
||||
|
||||
if ENABLED:
|
||||
from fastapi.responses import HTMLResponse
|
||||
|
||||
USERS = {
|
||||
"king@test.local": {"email": "king@test.local", "role": "admin", "modules": {"cafe24": True}},
|
||||
"amy@test.local": {"email": "amy@test.local", "role": "user", "modules": {"cafe24": True}},
|
||||
"nope@test.local": {"email": "nope@test.local", "role": "user", "modules": {}},
|
||||
}
|
||||
fake_main = types.ModuleType("app.main")
|
||||
fake_main.get_current_user_record = lambda request: USERS.get(request.headers.get("x-test-user", ""))
|
||||
fake_main.build_erp_nav = lambda user, active="": []
|
||||
|
||||
def _render(request, name, ctx, status_code=200):
|
||||
keep = {k: ctx.get(k) for k in ("sync_state", "fingerprint", "html_pc", "editor_error", "open_attempts",
|
||||
"revisions", "reason", "flash", "flash_error", "rows")}
|
||||
return HTMLResponse(name + "\n" + json.dumps(keep, ensure_ascii=False, default=str), status_code=status_code)
|
||||
|
||||
fake_main.render_template = _render
|
||||
sys.modules["app.main"] = fake_main
|
||||
os.environ.update({
|
||||
"CAFE24_MALL_ID": "testmall", "CAFE24_CLIENT_ID": "cid", "CAFE24_CLIENT_SECRET": "cs",
|
||||
"CAFE24_REDIRECT_URI": "http://localhost/cb", "CAFE24_TOKEN_SECRET": "unit-test-secret",
|
||||
"CAFE24_WRITE_LOCK_WAIT_SEC": "3",
|
||||
})
|
||||
os.environ.pop("CAFE24_READ_LAG_GRACE_MIN", None)
|
||||
|
||||
from fastapi import FastAPI # noqa: E402
|
||||
from fastapi.testclient import TestClient # noqa: E402
|
||||
|
||||
from app.integrations.cafe24 import products # noqa: E402
|
||||
from app.modules.cafe24 import ( # noqa: E402
|
||||
routes_design_files, routes_product_info, routes_products, routes_schedules, store, worker, writes,
|
||||
)
|
||||
from app.modules.cafe24.db import Cafe24Store # noqa: E402
|
||||
from app.modules.cafe24.router import router as cafe24_router # noqa: E402
|
||||
from app.modules.cafe24.tests import fakes # noqa: E402
|
||||
from app.timezone import now_kst # noqa: E402
|
||||
|
||||
products.time.sleep = lambda *_a, **_k: None
|
||||
ST = Cafe24Store(DSN)
|
||||
ST2 = Cafe24Store(DSN) # 두 번째 "프로세스"(별도 연결 풀)
|
||||
|
||||
class _Multi:
|
||||
"""상품번호별 FakeCafe24 로 요청을 나눠 준다(모르는 상품은 빈 응답)."""
|
||||
|
||||
def __init__(self):
|
||||
self.by_no: dict[int, fakes.FakeCafe24] = {}
|
||||
|
||||
def _pick(self, path):
|
||||
parts = path.split("/")
|
||||
try:
|
||||
return self.by_no.get(int(parts[3]))
|
||||
except (IndexError, ValueError):
|
||||
return None
|
||||
|
||||
def __getattr__(self, method):
|
||||
if method not in ("get", "put", "post", "delete"):
|
||||
raise AttributeError(method)
|
||||
|
||||
def call(path, **kw):
|
||||
target = self._pick(path)
|
||||
return getattr(target, method)(path, **kw) if target else {}
|
||||
|
||||
return call
|
||||
|
||||
MULTI = _Multi()
|
||||
for _mod in (routes_products, routes_product_info, routes_schedules):
|
||||
_mod.build_cafe24_api = lambda st, **kw: fakes.FakeApi(MULTI)
|
||||
|
||||
APP = FastAPI()
|
||||
APP.include_router(cafe24_router)
|
||||
APP.state.cafe24_store = ST
|
||||
CLIENT = TestClient(APP)
|
||||
|
||||
_BASE = random.randint(100_000, 900_000) * 10
|
||||
|
||||
|
||||
def _new_product(description="<p>A</p>") -> tuple[int, "fakes.FakeCafe24"]:
|
||||
global _BASE
|
||||
_BASE += 1
|
||||
cafe = fakes.FakeCafe24(description, product_no=_BASE)
|
||||
MULTI.by_no[_BASE] = cafe
|
||||
return _BASE, cafe
|
||||
|
||||
|
||||
def req(method, url, who="king@test.local", **kw):
|
||||
return CLIENT.request(method, url, headers={"x-test-user": who}, follow_redirects=False, **kw)
|
||||
|
||||
|
||||
def q(sql, *args):
|
||||
with ST._pool.connection() as conn: # noqa: SLF001 — 테스트 확인용
|
||||
cur = conn.execute(sql, args)
|
||||
return cur.fetchall() if cur.description else []
|
||||
|
||||
|
||||
def _location(resp) -> dict:
|
||||
loc = resp.headers.get("location", "")
|
||||
return {k: v[0] for k, v in parse_qs(urlparse(loc).query).items()}
|
||||
|
||||
|
||||
def _pane(no):
|
||||
resp = req("GET", f"/cafe24/products/{no}/pane")
|
||||
assert resp.status_code == 200, resp.text
|
||||
return json.loads(resp.text.split("\n", 1)[1])
|
||||
|
||||
|
||||
def _apply(no, html, fp, who="king@test.local", memo=""):
|
||||
return req("POST", f"/cafe24/products/{no}/apply",
|
||||
data={"html": html, "base_fingerprint": fp, "memo": memo}, who=who)
|
||||
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# DB — 잠금(lease)
|
||||
# ════════════════════════════════════════════════════════════
|
||||
def test_lock_exclusive_across_pools_and_expiry_fencing():
|
||||
key = f"test:lock:{_BASE}:{random.random()}"
|
||||
t1 = ST.acquire_lock(key, owner="a|h:1", purpose="p", ttl_seconds=60)
|
||||
assert t1
|
||||
assert ST2.acquire_lock(key, owner="b|h:2", purpose="p", ttl_seconds=60) is None
|
||||
assert ST2.lock_holder(key)["owner"].startswith("a|")
|
||||
assert ST.renew_lock(key, t1, ttl_seconds=60)
|
||||
q("UPDATE cafe24_write_locks SET expires_at = now() - interval '1 second' WHERE lock_key = %s", key)
|
||||
t2 = ST2.acquire_lock(key, owner="b|h:2", purpose="p", ttl_seconds=60)
|
||||
assert t2 and t2 != t1
|
||||
assert ST.renew_lock(key, t1, ttl_seconds=60) is False # 펜싱: 넘어간 잠금은 연장 불가
|
||||
ST.release_lock(key, t1) # 남의 잠금은 못 푼다
|
||||
assert ST2.lock_holder(key)["owner"].startswith("b|")
|
||||
ST2.release_lock(key, t2)
|
||||
assert ST.lock_holder(key) == {}
|
||||
|
||||
|
||||
def test_lock_race_only_one_winner():
|
||||
key = f"test:race:{_BASE}:{random.random()}"
|
||||
tokens, barrier = [], threading.Barrier(8)
|
||||
|
||||
def grab(s):
|
||||
barrier.wait()
|
||||
tokens.append(s.acquire_lock(key, owner="x", purpose="p", ttl_seconds=30))
|
||||
|
||||
threads = [threading.Thread(target=grab, args=(ST if i % 2 else ST2,)) for i in range(8)]
|
||||
[t.start() for t in threads]
|
||||
[t.join() for t in threads]
|
||||
assert sum(1 for t in tokens if t) == 1, tokens
|
||||
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# DB — 예약 lease
|
||||
# ════════════════════════════════════════════════════════════
|
||||
def _schedule(no, **kw):
|
||||
fields = dict(product_no=no, scheduled_at=now_kst() - timedelta(minutes=1), revision_id=None,
|
||||
set_display=True, set_selling=None)
|
||||
fields.update(kw)
|
||||
return ST.create_schedule(**fields)
|
||||
|
||||
|
||||
def test_schedule_claim_is_exclusive_between_workers():
|
||||
no, _ = _new_product()
|
||||
ids = {_schedule(no) for _ in range(6)}
|
||||
got, barrier = [], threading.Barrier(2)
|
||||
|
||||
def run(s, name):
|
||||
barrier.wait()
|
||||
while True:
|
||||
row = s.claim_due_schedule(now=now_kst(), owner=name, ttl_seconds=60)
|
||||
if row is None:
|
||||
return
|
||||
got.append(row["id"])
|
||||
|
||||
threads = [threading.Thread(target=run, args=(ST, "w1")), threading.Thread(target=run, args=(ST2, "w2"))]
|
||||
[t.start() for t in threads]
|
||||
[t.join() for t in threads]
|
||||
mine = [i for i in got if i in ids]
|
||||
assert sorted(mine) == sorted(ids) and len(mine) == len(set(mine)), got
|
||||
|
||||
|
||||
def test_schedule_lease_expiry_and_stale_finish():
|
||||
no, _ = _new_product()
|
||||
sid = _schedule(no, scheduled_at=now_kst() - timedelta(days=3650)) # 가장 먼저 잡히게
|
||||
row = ST.claim_due_schedule(now=now_kst(), owner="w1", ttl_seconds=60)
|
||||
assert row["id"] == sid and row["lease_token"]
|
||||
assert ST.renew_schedule_lease(sid, row["lease_token"], ttl_seconds=60)
|
||||
q("UPDATE cafe24_product_schedules SET lease_expires_at = now() - interval '1 second' WHERE id = %s", sid)
|
||||
taken = [r for r in ST2.claim_expired_schedules(owner="w2", ttl_seconds=60, legacy_minutes=30) if r["id"] == sid]
|
||||
assert taken and taken[0]["lease_token"] != row["lease_token"]
|
||||
assert ST.renew_schedule_lease(sid, row["lease_token"], ttl_seconds=60) is False
|
||||
assert ST.finish_schedule(sid, token=row["lease_token"], status="FAILED") is False # 늦은 결과 무시
|
||||
assert ST2.finish_schedule(sid, token=taken[0]["lease_token"], status="SUCCESS") is True
|
||||
assert q("SELECT status, lease_token FROM cafe24_product_schedules WHERE id = %s", sid)[0] == \
|
||||
{"status": "SUCCESS", "lease_token": ""}
|
||||
|
||||
|
||||
def test_legacy_processing_row_is_recovered():
|
||||
"""005 이전에 PROCESSING 이 된 행(lease 없음)도 오래됐으면 복구 대상."""
|
||||
no, _ = _new_product()
|
||||
sid = _schedule(no)
|
||||
q("UPDATE cafe24_product_schedules SET status='PROCESSING', started_at = now() - interval '40 minutes' "
|
||||
"WHERE id = %s RETURNING id", sid)
|
||||
rows = [r for r in ST.claim_expired_schedules(owner="w", ttl_seconds=60, legacy_minutes=30) if r["id"] == sid]
|
||||
assert rows and rows[0]["lease_token"]
|
||||
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# DB — 시도 기록 · 확인된 쓰기 · 스냅샷
|
||||
# ════════════════════════════════════════════════════════════
|
||||
def test_record_attempt_revision_is_idempotent_under_race():
|
||||
no, _ = _new_product()
|
||||
aid = ST.start_attempt(product_no=no, origin="MANUAL", actor="k", target_html="<p>X</p>",
|
||||
target_digest=store.content_digest("<p>X</p>"))
|
||||
ST.update_attempt(aid, status="REMOTE_OK", remote_ok=True)
|
||||
out, barrier = [], threading.Barrier(2)
|
||||
|
||||
def rec(s):
|
||||
barrier.wait()
|
||||
out.append(s.record_attempt_revision(aid, revision_type="MANUAL", memo="", created_by="k"))
|
||||
|
||||
threads = [threading.Thread(target=rec, args=(s,)) for s in (ST, ST2)]
|
||||
[t.start() for t in threads]
|
||||
[t.join() for t in threads]
|
||||
assert len(set(out)) == 1
|
||||
assert q("SELECT count(*) AS n FROM cafe24_product_revisions WHERE product_no = %s AND revision_type='MANUAL'",
|
||||
no)[0]["n"] == 1
|
||||
assert q("SELECT status, target_html FROM cafe24_write_attempts WHERE id = %s", aid)[0] == \
|
||||
{"status": "RECORDED", "target_html": ""}
|
||||
|
||||
|
||||
def test_write_lineage_only_confirmed():
|
||||
no, _ = _new_product()
|
||||
since = now_kst() - timedelta(hours=1)
|
||||
for status, html in (("REMOTE_FAILED", "F"), ("UNKNOWN", "U"), ("STARTED", "S"), ("RECORDED", "OK1"), ("REMOTE_OK", "OK2")):
|
||||
aid = ST.start_attempt(product_no=no, origin="MANUAL", target_html=html,
|
||||
target_digest=store.content_digest(html), observed_digest=store.content_digest("OBS-" + html))
|
||||
if status != "STARTED":
|
||||
ST.update_attempt(aid, status=status, remote_ok=status in ("RECORDED", "REMOTE_OK"))
|
||||
ST.add_revision(product_no=no, html_content="CONFLICT-BACKUP", revision_type="BACKUP")
|
||||
lineage = ST.write_lineage(no, since=since)
|
||||
assert [store.content_digest(x) for x in ("OK2", "OK1")] == [a["target_digest"] for a in lineage]
|
||||
assert lineage[0]["html_content"] == "OK2"
|
||||
digests = store.lineage_digests(lineage)
|
||||
assert store.content_digest("CONFLICT-BACKUP") not in digests
|
||||
assert store.content_digest("F") not in digests and store.content_digest("U") not in digests
|
||||
|
||||
|
||||
def test_snapshot_jsonb_field_merge_replace_and_deleted():
|
||||
no, _ = _new_product()
|
||||
ST.save_write_snapshot(no, "variants", {"V1": {"custom_variant_code": "C1"}, "V2": {"display": "F"}})
|
||||
ST.save_write_snapshot(no, "variants", {"V1": {"display": "F"}})
|
||||
data = ST.get_write_snapshot(no)["variants"]["data"]
|
||||
assert data["V1"]["custom_variant_code"] == "C1" and data["V1"]["display"] == "F" and "V2" in data
|
||||
ST.save_write_snapshot(no, "variants", {"V2": {"_deleted": True}})
|
||||
ST.save_write_snapshot(no, "variants", {"V2": {"display": "T"}})
|
||||
assert ST.get_write_snapshot(no)["variants"]["data"]["V2"].get("_deleted") is True
|
||||
ST.save_write_snapshot(no, "variants", {})
|
||||
assert "V1" in ST.get_write_snapshot(no)["variants"]["data"]
|
||||
ST.save_write_snapshot(no, "variants", {}, replace=True)
|
||||
assert ST.get_write_snapshot(no)["variants"]["data"] == {}
|
||||
|
||||
|
||||
def test_snapshot_concurrent_saves_both_persist():
|
||||
no, _ = _new_product()
|
||||
barrier = threading.Barrier(2)
|
||||
|
||||
def save(s, code):
|
||||
barrier.wait()
|
||||
s.save_write_snapshot(no, "variants", {code: {"display": "F"}})
|
||||
|
||||
threads = [threading.Thread(target=save, args=(ST, "VA")), threading.Thread(target=save, args=(ST2, "VB"))]
|
||||
[t.start() for t in threads]
|
||||
[t.join() for t in threads]
|
||||
assert set(ST.get_write_snapshot(no)["variants"]["data"]) == {"VA", "VB"}
|
||||
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# 라우트 — [01] 충돌 백업이 외부 수정을 가리지 않는다 / 권한
|
||||
# ════════════════════════════════════════════════════════════
|
||||
def test_route_permission_required():
|
||||
no, _ = _new_product()
|
||||
assert req("POST", f"/cafe24/products/{no}/apply", who="nope@test.local",
|
||||
data={"html": "x"}).status_code == 403
|
||||
assert req("GET", f"/cafe24/products/{no}/revisions/1", who="nope@test.local").status_code == 403
|
||||
|
||||
|
||||
def test_route_01_conflict_then_external_edit_not_overwritten():
|
||||
no, cafe = _new_product("<p>A</p>")
|
||||
p0 = _pane(no)
|
||||
assert _location(_apply(no, "<p>W1</p>", p0["fingerprint"])).get("msg")
|
||||
stale_fp = _pane(no)["fingerprint"]
|
||||
cafe.external_edit("<p>X</p>")
|
||||
assert "변경" in _location(_apply(no, "<p>Y</p>", stale_fp)).get("err", "")
|
||||
pane = _pane(no)
|
||||
assert pane["sync_state"] == store.SYNC_EXTERNAL and "<p>X</p>" in pane["html_pc"]
|
||||
assert "변경" in _location(_apply(no, "<p>Y</p>", stale_fp)).get("err", "")
|
||||
assert cafe.state["description"] == "<p>X</p>"
|
||||
|
||||
|
||||
def test_route_02_concurrent_applies_one_wins():
|
||||
no, cafe = _new_product("<p>A</p>")
|
||||
fp = _pane(no)["fingerprint"]
|
||||
import time as _time
|
||||
|
||||
real_put = cafe.put
|
||||
|
||||
def slow_put(path, **kw):
|
||||
_time.sleep(0.4)
|
||||
return real_put(path, **kw)
|
||||
|
||||
cafe.put = slow_put
|
||||
results, barrier = [], threading.Barrier(2)
|
||||
|
||||
def go(text, who):
|
||||
barrier.wait()
|
||||
results.append(_location(_apply(no, text, fp, who=who)))
|
||||
|
||||
threads = [threading.Thread(target=go, args=("<p>AMY</p>", "amy@test.local")),
|
||||
threading.Thread(target=go, args=("<p>KING</p>", "king@test.local"))]
|
||||
[t.start() for t in threads]
|
||||
[t.join() for t in threads]
|
||||
ok = [r for r in results if r.get("msg")]
|
||||
err = [r for r in results if r.get("err")]
|
||||
assert len(ok) == 1 and len(err) == 1, results
|
||||
desc_puts = [c for c in cafe.calls if c[0] == "PUT" and "description" in (c[2] or {}).get("request", {})]
|
||||
assert len(desc_puts) == 1
|
||||
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# 라우트 — [13] 버전 원문 · 선택 복원 · [07] 결과 확정
|
||||
# ════════════════════════════════════════════════════════════
|
||||
def test_route_13_revision_detail_scoped_and_restore():
|
||||
no, cafe = _new_product("<p>A</p>")
|
||||
other, _ = _new_product("<p>O</p>")
|
||||
_apply(no, "<p>B<script>x</script></p>", _pane(no)["fingerprint"])
|
||||
backup = next(r for r in _pane(no)["revisions"] if r["revision_type"] == "BACKUP")
|
||||
detail = req("GET", f"/cafe24/products/{no}/revisions/{backup['id']}").json()["revision"]
|
||||
assert detail["html"] == "<p>A</p>" and detail["type_label"]
|
||||
assert req("GET", f"/cafe24/products/{other}/revisions/{backup['id']}").status_code == 404
|
||||
foreign = ST.add_revision(product_no=no, html_content="<p>F</p>", revision_type="MANUAL", mall_id="othermall")
|
||||
assert req("GET", f"/cafe24/products/{no}/revisions/{foreign}").status_code == 404
|
||||
shop2 = ST.add_revision(product_no=no, html_content="<p>S</p>", revision_type="MANUAL", shop_no=2)
|
||||
assert req("GET", f"/cafe24/products/{no}/revisions/{shop2}").status_code == 404
|
||||
# 복원 — 지문 없이는 거부, 옛 지문이면 충돌, 현재 지문이면 ROLLBACK
|
||||
assert _location(req("POST", f"/cafe24/products/{no}/revisions/{backup['id']}/restore", data={})).get("err")
|
||||
assert "변경" in _location(req("POST", f"/cafe24/products/{no}/revisions/{backup['id']}/restore",
|
||||
data={"base_fingerprint": store.fingerprint("<p>A</p>")})).get("err", "")
|
||||
fp = _pane(no)["fingerprint"]
|
||||
loc = _location(req("POST", f"/cafe24/products/{no}/revisions/{backup['id']}/restore",
|
||||
data={"base_fingerprint": fp, "memo": "되돌림"}))
|
||||
assert "복원" in loc.get("msg", ""), loc
|
||||
assert cafe.state["description"] == "<p>A</p>"
|
||||
rb = q("SELECT revision_type, source, source_revision_id, memo FROM cafe24_product_revisions "
|
||||
"WHERE product_no = %s ORDER BY id DESC LIMIT 1", no)[0]
|
||||
assert rb["revision_type"] == "ROLLBACK" and rb["source_revision_id"] == backup["id"] and "되돌림" in rb["memo"]
|
||||
# 다른 상품 버전을 이 상품 주소로 복원 시도 → 거부
|
||||
assert _location(req("POST", f"/cafe24/products/{other}/revisions/{backup['id']}/restore",
|
||||
data={"base_fingerprint": fp})).get("err")
|
||||
|
||||
|
||||
def test_route_07_unknown_attempt_blocks_until_resolved():
|
||||
no, cafe = _new_product("<p>A</p>")
|
||||
fp = _pane(no)["fingerprint"]
|
||||
cafe.put_error = fakes.network_error(maybe_applied=True)
|
||||
assert "알 수 없습니다" in _location(_apply(no, "<p>B</p>", fp)).get("err", "")
|
||||
cafe.put_error = None
|
||||
pane = _pane(no)
|
||||
assert len(pane["open_attempts"]) == 1
|
||||
assert "확인하지 못했습니다" in _location(_apply(no, "<p>C</p>", pane["fingerprint"])).get("err", "")
|
||||
aid = pane["open_attempts"][0]["id"]
|
||||
loc = _location(req("POST", f"/cafe24/products/{no}/attempts/{aid}/resolve", data={"result": "not_applied"}))
|
||||
assert loc.get("msg"), loc
|
||||
assert _pane(no)["open_attempts"] == []
|
||||
assert _location(_apply(no, "<p>C</p>", _pane(no)["fingerprint"])).get("msg")
|
||||
assert cafe.state["description"] == "<p>C</p>"
|
||||
|
||||
|
||||
def test_route_07_record_failure_reported_as_success():
|
||||
no, cafe = _new_product("<p>A</p>")
|
||||
fp = _pane(no)["fingerprint"]
|
||||
real = ST.record_attempt_revision
|
||||
|
||||
def boom(*a, **kw):
|
||||
raise RuntimeError("DB 장애")
|
||||
|
||||
ST.record_attempt_revision = boom
|
||||
try:
|
||||
loc = _location(_apply(no, "<p>B</p>", fp))
|
||||
finally:
|
||||
ST.record_attempt_revision = real
|
||||
assert "다시 적용하지 마세요" in loc.get("msg", ""), loc
|
||||
status = q("SELECT status FROM cafe24_write_attempts WHERE product_no = %s ORDER BY id DESC LIMIT 1", no)
|
||||
assert status[0]["status"] == "REMOTE_OK"
|
||||
# worker 의 기록 복구가 채운다(다시 PUT 하지 않음)
|
||||
worker.record_pending_attempts(ST)
|
||||
assert q("SELECT status FROM cafe24_write_attempts WHERE product_no = %s ORDER BY id DESC LIMIT 1",
|
||||
no)[0]["status"] == "RECORDED"
|
||||
assert len([c for c in cafe.calls if c[0] == "PUT"]) == 1
|
||||
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# 라우트 — [09] 행별 결과 · [10] 품목 표기 · [11] 삭제 품목
|
||||
# ════════════════════════════════════════════════════════════
|
||||
def _create_options(no, values):
|
||||
resp = req("POST", f"/cafe24/products/{no}/options", json={"option_name": "구성", "values": values})
|
||||
assert resp.status_code == 200, resp.text
|
||||
return resp.json()
|
||||
|
||||
|
||||
def test_route_09_variants_partial_success():
|
||||
no, cafe = _new_product()
|
||||
created = _create_options(no, [f"v{i}" for i in range(150)])
|
||||
rows = [{"variant_code": v["variant_code"], "custom_variant_code": f"C{i}"}
|
||||
for i, v in enumerate(created["variants"])]
|
||||
cafe.fail_variant_chunk = 2
|
||||
resp = req("PUT", f"/cafe24/products/{no}/variants", json={"rows": rows})
|
||||
assert resp.status_code == 200, resp.text
|
||||
body = resp.json()
|
||||
assert body["partial"] and len(body["updated"]) == 100 and len(body["failed"]) == 50
|
||||
snap = ST.get_write_snapshot(no)["variants"]["data"]
|
||||
assert len([c for c in snap if c in body["updated"]]) == 100
|
||||
assert not any(c in snap for c in body["failed"])
|
||||
audit = q("SELECT result FROM cafe24_audit_logs WHERE product_no = %s AND action='update_variants' "
|
||||
"ORDER BY id DESC LIMIT 1", no)[0]
|
||||
assert audit["result"] == "PARTIAL"
|
||||
cafe.fail_variant_chunk = 0
|
||||
cafe._variant_puts = 0
|
||||
cafe.fail_variant_chunk = 1
|
||||
resp = req("PUT", f"/cafe24/products/{no}/variants", json={"rows": rows[:5]})
|
||||
assert resp.status_code == 502
|
||||
|
||||
|
||||
def test_route_10_rename_with_lagging_variants_keeps_rows():
|
||||
no, cafe = _new_product()
|
||||
created = _create_options(no, ["Black", "Red"])
|
||||
before_variants = [dict(v, options=[dict(o) for o in v["options"]]) for v in cafe.variants]
|
||||
before_option = json.loads(json.dumps(cafe.option))
|
||||
resp = req("PUT", f"/cafe24/products/{no}/options", json={"options": [{
|
||||
"option_name": "구성", "option_value": [{"option_text": "Jet"}, {"option_text": "Crimson"}]}]})
|
||||
assert resp.status_code == 200, resp.text
|
||||
# 카페24 GET 이 아직 옛 옵션·옛 품목 표기를 돌려준다(읽기 지연)
|
||||
cafe.stale_option = before_option
|
||||
cafe.stale_variants = before_variants
|
||||
got = req("GET", f"/cafe24/products/{no}/options").json()
|
||||
texts = [v["option_text"] for v in got["option"]["options"][0]["option_value"]]
|
||||
labels = sorted(v["options"][0]["value"] for v in got["variants"])
|
||||
assert texts == ["Jet", "Crimson"] and labels == ["Crimson", "Jet"], (texts, labels)
|
||||
assert all(v["value_no"] for v in got["variants"]) # 옵션값 번호로 짝지을 수 있다
|
||||
# 관리자에서 다시 Onyx 로 고침 — 그 값은 믿는다
|
||||
cafe.stale_option = None
|
||||
cafe.stale_variants = None
|
||||
cafe.option["options"][0]["option_value"][0]["option_text"] = "Onyx"
|
||||
cafe.variants[0]["options"][0]["value"] = "Onyx"
|
||||
got = req("GET", f"/cafe24/products/{no}/options").json()
|
||||
assert got["option"]["options"][0]["option_value"][0]["option_text"] == "Onyx"
|
||||
assert "Onyx" in [v["options"][0]["value"] for v in got["variants"]]
|
||||
assert created["variants"]
|
||||
|
||||
|
||||
def test_route_08_appended_value_pending_until_variant_appears():
|
||||
no, cafe = _new_product()
|
||||
_create_options(no, ["A"])
|
||||
cafe.hidden_variants = 99 # 새 품목이 한동안 안 보인다
|
||||
resp = req("PUT", f"/cafe24/products/{no}/options", json={"options": [{
|
||||
"option_name": "구성", "option_value": [{"option_text": "A"}, {"option_text": "B"}]}]}).json()
|
||||
values = resp["option"]["options"][0]["option_value"]
|
||||
assert values[1]["option_text"] == "B" and values[1]["pending"] is True
|
||||
got = req("GET", f"/cafe24/products/{no}/options").json()
|
||||
assert got["option"]["options"][0]["option_value"][1]["pending"] is True
|
||||
cafe.hidden_variants = 0
|
||||
got = req("GET", f"/cafe24/products/{no}/options").json()
|
||||
assert got["option"]["options"][0]["option_value"][1]["pending"] is False
|
||||
assert len(got["variants"]) == 2
|
||||
|
||||
|
||||
def test_route_11_deleted_variant_stays_hidden():
|
||||
no, cafe = _new_product()
|
||||
created = _create_options(no, ["A", "B"])
|
||||
code = created["variants"][0]["variant_code"]
|
||||
stale = [dict(v) for v in cafe.variants]
|
||||
assert req("DELETE", f"/cafe24/products/{no}/variants/{code}").status_code == 200
|
||||
ST.save_write_snapshot(no, "variants", {code: {"display": "T"}}) # 늦게 도착한 수정
|
||||
cafe.stale_variants = stale
|
||||
got = req("GET", f"/cafe24/products/{no}/options").json()
|
||||
assert code not in [v["variant_code"] for v in got["variants"]]
|
||||
|
||||
|
||||
def test_route_lock_busy_returns_409():
|
||||
no, _ = _new_product()
|
||||
token = ST2.acquire_lock(f"product:{no}", owner="amy|h:1", purpose="상세설명 적용", ttl_seconds=60)
|
||||
os.environ["CAFE24_WRITE_LOCK_WAIT_SEC"] = "0"
|
||||
try:
|
||||
resp = req("POST", f"/cafe24/products/{no}/basic", json={"price": "1000"})
|
||||
assert resp.status_code == 409 and "amy" in resp.json()["detail"], resp.text
|
||||
finally:
|
||||
os.environ["CAFE24_WRITE_LOCK_WAIT_SEC"] = "3"
|
||||
ST2.release_lock(f"product:{no}", token)
|
||||
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# worker — 실제 DB
|
||||
# ════════════════════════════════════════════════════════════
|
||||
def _draft(no, html):
|
||||
return ST.add_revision(product_no=no, html_content=html, revision_type="DRAFT", mall_id="testmall")
|
||||
|
||||
|
||||
def test_worker_real_db_success_and_needs_review():
|
||||
no, cafe = _new_product("<p>A</p>")
|
||||
sid = _schedule(no, revision_id=_draft(no, "<p>S</p>"), scheduled_at=now_kst() - timedelta(days=3000))
|
||||
worker.process_once(ST, fakes.FakeApi(MULTI))
|
||||
row = ST.get_schedule(sid)
|
||||
assert row["status"] == "SUCCESS" and cafe.state["description"] == "<p>S</p>", row
|
||||
assert q("SELECT count(*) AS n FROM cafe24_product_revisions WHERE product_no=%s AND revision_type='SCHEDULED'",
|
||||
no)[0]["n"] == 1
|
||||
|
||||
no2, cafe2 = _new_product("<p>A</p>")
|
||||
cafe2.put_error = fakes.network_error(maybe_applied=True)
|
||||
cafe2.put_error_after_apply = True
|
||||
sid2 = _schedule(no2, revision_id=_draft(no2, "<p>S2</p>"), scheduled_at=now_kst() - timedelta(days=3000))
|
||||
worker.process_once(ST, fakes.FakeApi(MULTI))
|
||||
assert ST.get_schedule(sid2)["status"] == "NEEDS_REVIEW"
|
||||
# 사람이 쇼핑몰을 보고 "반영됨" 확정
|
||||
resp = req("POST", f"/cafe24/schedules/{sid2}/review", data={"action": "applied"})
|
||||
assert _location(resp).get("msg"), resp.headers
|
||||
assert ST.get_schedule(sid2)["status"] == "SUCCESS"
|
||||
assert q("SELECT status FROM cafe24_write_attempts WHERE schedule_id=%s", sid2)[0]["status"] == "RECORDED"
|
||||
|
||||
|
||||
def test_worker_real_db_recovers_crash_after_remote_ok():
|
||||
no, cafe = _new_product("<p>A</p>")
|
||||
rid = _draft(no, "<p>R</p>")
|
||||
sid = _schedule(no, revision_id=rid, scheduled_at=now_kst() - timedelta(days=3000))
|
||||
row = ST.claim_due_schedule(now=now_kst(), owner="dead", ttl_seconds=60)
|
||||
assert row["id"] == sid
|
||||
aid = ST.start_attempt(product_no=no, schedule_id=sid, origin="SCHEDULED", target_revision_id=rid,
|
||||
target_digest=store.content_digest("<p>R</p>"))
|
||||
ST.update_attempt(aid, status="REMOTE_OK", remote_ok=True) # 반영 직후 죽음
|
||||
q("UPDATE cafe24_product_schedules SET lease_expires_at = now() - interval '1 second' WHERE id=%s RETURNING id", sid)
|
||||
worker.process_once(ST, fakes.FakeApi(MULTI))
|
||||
assert ST.get_schedule(sid)["status"] == "SUCCESS"
|
||||
assert q("SELECT status FROM cafe24_write_attempts WHERE id=%s", aid)[0]["status"] == "RECORDED"
|
||||
assert [c for c in cafe.calls if c[0] == "PUT"] == [] # 재적용 없음
|
||||
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# 디자인 파일 — [04] 잠금 + 임시 파일 교체
|
||||
# ════════════════════════════════════════════════════════════
|
||||
def test_design_apply_route_temp_replace_and_conflict():
|
||||
os.environ.update({"CAFE24_FTP_USER": "u", "CAFE24_FTP_PASSWORD": "p", "CAFE24_FTP_HOST": "h"})
|
||||
path = routes_design_files.design_file_path("swiper")
|
||||
with fakes.patched_ftp() as ftp:
|
||||
ftp.reset({path: b"OLD"})
|
||||
fp = store.fingerprint("OLD")
|
||||
loc = _location(req("POST", "/cafe24/design/swiper/apply", data={"content": "NEW", "base_fingerprint": fp}))
|
||||
assert loc.get("msg"), loc
|
||||
assert ftp.files == {path: b"NEW"}
|
||||
# 교체 직전 남이 바꿈 → 충돌, 원본(남의 값) 그대로
|
||||
ftp.on_before_rename = None
|
||||
fp = store.fingerprint("NEW")
|
||||
|
||||
real_retr = fakes.FakeFTP.retrbinary
|
||||
calls = {"n": 0}
|
||||
|
||||
def sneaky(self, cmd, cb):
|
||||
calls["n"] += 1
|
||||
if calls["n"] == 3: # 1: 현재값 조회, 2: 임시 파일 검증, 3: 교체 직전 재확인
|
||||
self.files[path] = b"THEIRS"
|
||||
return real_retr(self, cmd, cb)
|
||||
|
||||
fakes.FakeFTP.retrbinary = sneaky
|
||||
try:
|
||||
loc = _location(req("POST", "/cafe24/design/swiper/apply", data={"content": "MINE", "base_fingerprint": fp}))
|
||||
finally:
|
||||
fakes.FakeFTP.retrbinary = real_retr
|
||||
assert "바뀌었습니다" in loc.get("err", ""), loc
|
||||
assert ftp.files == {path: b"THEIRS"}
|
||||
|
||||
|
||||
def _run_all() -> None:
|
||||
if not ENABLED:
|
||||
print("SKIP — CAFE24_TEST_DB_URL(localhost) 이 없어 건너뜁니다.")
|
||||
return
|
||||
fns = [v for k, v in sorted(globals().items()) if k.startswith("test_") and callable(v)]
|
||||
failed = 0
|
||||
for fn in fns:
|
||||
try:
|
||||
fn()
|
||||
print("PASS", fn.__name__)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
failed += 1
|
||||
import traceback
|
||||
|
||||
print("FAIL", fn.__name__, "→", repr(exc))
|
||||
traceback.print_exc()
|
||||
print(f"\n{len(fns) - failed}/{len(fns)} passed.")
|
||||
ST.close()
|
||||
ST2.close()
|
||||
if failed:
|
||||
raise SystemExit(1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
_run_all()
|
||||
Reference in New Issue
Block a user