feat(cafe24): 예약관리 — 지정 시각에 상세페이지·진열/판매 자동 적용 (Phase 5)
되돌리기(자동 복원)는 요청대로 만들지 않았다. 예약은 "그 시각에 이 내용을 적용" 하나뿐이며, 한 예약에서 상세페이지 HTML·진열·판매를 각각 고를 수 있다. 셋 다 "변경 없음"인 예약은 DB CHECK 로 막는다. 등록은 편집기 아래 「예약 적용」에서 한다. HTML 을 적용하는 예약이면 그 시점의 편집기 내용을 DRAFT revision 으로 저장해 고정한다 — 이후 편집기를 더 고쳐도 예약된 내용이 바뀌지 않아야 한다. 단건 적용과 같은 다듬기(URL 인코딩 → 소스 정리)를 거치므로 화면에서 본 값이 그대로 저장된다. 예약 폼은 적용 폼과 형제로 두고(폼 중첩 불가) 편집기 내용을 JS 가 hidden 에 복사한다. 실행은 web 이 아니라 worker 다(app/modules/cafe24/worker.py, compose 서비스 dbx-cafe24-worker, --loop 60). 웹 요청 안에서 기다리면 프록시 타임아웃·재기동에 무너지고, 브라우저를 닫으면 실행되지 않는다. worker 는 claim_due_schedule 로 한 건씩 FOR UPDATE SKIP LOCKED 로 잠그고 PROCESSING 으로 바꾼 뒤 잠금을 푼다. worker 가 둘 떠도 같은 예약을 두 번 적용하지 않고, 긴 API 호출 동안 DB 잠금을 쥐지 않는다. 적용 순서는 화면 편집과 같다(현재값 재조회 → BACKUP → PUT → 감사로그). HTML 없이 진열/판매만 바꾸는 예약은 상세설명을 읽지도 백업하지도 않는다. 실패는 1분→5분→15분 재시도 후 FAILED 확정이며, 한 건의 오류로 worker 가 죽지 않는다. 진열/판매를 한 번의 PUT 으로 함께 보내려고 products.update_product 를 추가했다 (update_descriptions 는 이 함수로 위임). None 인 필드는 payload 에서 빼므로 "건드리지 않음"이 그대로 표현된다. DB: scripts/sql/cafe24_db_002_schedule_flags.sql (멱등) — set_display/set_selling BOOLEAN NULL 추가 + 아무것도 하지 않는 예약 금지 제약. 되돌리기용 end_* 컬럼은 쓰지 않지만 삭제하지 않는다(파괴적). 시각은 KST 로 해석한다(datetime-local 은 타임존이 없다). 과거는 거부하되 폼을 채우는 동안 시간이 흐른 경우를 위해 1분 여유를 뒀다. 검증: 유닛테스트 66개 통과(신규 15개 — 3-상태 파싱, KST 해석·과거 거부·1분 여유, 요약 문구, payload 의 T/F 와 None 생략, 바꿀 것 없으면 미호출, worker 의 성공 경로 (백업+PC/모바일 동시+진열만 전송)·상태만 변경 시 백업 생략·재시도 후 최종 실패· 버전 누락 시 크래시 대신 실패·처리할 것 없을 때 종료). 예약 목록/편집기 예약 폼 렌더 확인. 라우트 16개. 실제 예약 실행은 서버 배포 후 확인 필요. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
@@ -319,6 +319,149 @@ class Cafe24Store:
|
||||
).fetchone()
|
||||
return self._serialize(row)
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# 예약 (지정 시각에 상세페이지·진열/판매 적용)
|
||||
# 되돌리기는 쓰지 않으므로 end_* 컬럼은 건드리지 않는다.
|
||||
# ════════════════════════════════════════════════════════════
|
||||
def create_schedule(
|
||||
self,
|
||||
*,
|
||||
product_no: int,
|
||||
scheduled_at: datetime,
|
||||
revision_id: int | None,
|
||||
set_display: bool | None,
|
||||
set_selling: bool | None,
|
||||
memo: str = "",
|
||||
created_by: str = "",
|
||||
) -> int:
|
||||
with self._pool.connection() as conn:
|
||||
row = conn.execute(
|
||||
"""
|
||||
INSERT INTO cafe24_product_schedules
|
||||
(product_no, scheduled_at, revision_id, set_display, set_selling,
|
||||
memo, created_by)
|
||||
VALUES (%s,%s,%s,%s,%s,%s,%s)
|
||||
RETURNING id
|
||||
""",
|
||||
(
|
||||
int(product_no),
|
||||
scheduled_at,
|
||||
revision_id,
|
||||
set_display,
|
||||
set_selling,
|
||||
(memo or "")[:500],
|
||||
created_by or "",
|
||||
),
|
||||
).fetchone()
|
||||
return int(row["id"]) if row else 0
|
||||
|
||||
def list_schedules(self, *, limit: int = 200) -> list[dict[str, Any]]:
|
||||
"""예약 목록. 대기 중인 것을 먼저, 그다음 최근 처리 순."""
|
||||
with self._pool.connection() as conn:
|
||||
rows = conn.execute(
|
||||
"""
|
||||
SELECT s.*, p.product_name,
|
||||
(s.revision_id IS NOT NULL) AS has_html
|
||||
FROM cafe24_product_schedules s
|
||||
LEFT JOIN cafe24_products p ON p.product_no = s.product_no
|
||||
ORDER BY (s.status = 'PENDING') DESC,
|
||||
CASE WHEN s.status = 'PENDING' THEN s.scheduled_at END ASC,
|
||||
s.scheduled_at DESC, s.id DESC
|
||||
LIMIT %s
|
||||
""",
|
||||
(max(1, min(int(limit), 500)),),
|
||||
).fetchall()
|
||||
return [self._serialize(r) for r in rows]
|
||||
|
||||
def cancel_schedule(self, schedule_id: int, *, actor: str = "") -> bool:
|
||||
"""대기 중인 예약만 취소한다. 실행 중/완료된 것은 건드리지 않는다."""
|
||||
with self._pool.connection() as conn:
|
||||
with conn.transaction():
|
||||
row = conn.execute(
|
||||
"""
|
||||
UPDATE cafe24_product_schedules
|
||||
SET status = 'CANCELLED', completed_at = now()
|
||||
WHERE id = %s AND status = 'PENDING'
|
||||
RETURNING id, product_no
|
||||
""",
|
||||
(int(schedule_id),),
|
||||
).fetchone()
|
||||
if row is None:
|
||||
return False
|
||||
self._insert_audit(
|
||||
conn,
|
||||
actor=actor,
|
||||
action="schedule_cancel",
|
||||
product_no=row["product_no"],
|
||||
schedule_id=row["id"],
|
||||
result="SUCCESS",
|
||||
)
|
||||
return True
|
||||
|
||||
@contextmanager
|
||||
def claim_due_schedule(self, *, now: datetime) -> Iterator[dict[str, Any] | None]:
|
||||
"""실행할 예약 1건을 잡아 PROCESSING 으로 바꾼다(worker 전용).
|
||||
|
||||
`FOR UPDATE SKIP LOCKED` 로 잠그므로 worker 가 여러 개 떠 있어도 같은 예약을
|
||||
두 번 실행하지 않는다. 재시도 대기(next_retry_at)가 남아 있으면 건너뛴다.
|
||||
"""
|
||||
with self._pool.connection() as conn:
|
||||
with conn.transaction():
|
||||
row = conn.execute(
|
||||
"""
|
||||
SELECT * FROM cafe24_product_schedules
|
||||
WHERE status = 'PENDING'
|
||||
AND scheduled_at <= %s
|
||||
AND (next_retry_at IS NULL OR next_retry_at <= %s)
|
||||
ORDER BY scheduled_at ASC, id ASC
|
||||
LIMIT 1
|
||||
FOR UPDATE SKIP LOCKED
|
||||
""",
|
||||
(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"],),
|
||||
)
|
||||
yield dict(row) if row is not None else None
|
||||
|
||||
def finish_schedule(
|
||||
self,
|
||||
schedule_id: int,
|
||||
*,
|
||||
status: str,
|
||||
error: str = "",
|
||||
next_retry_at: datetime | None = None,
|
||||
retry_count: int | None = None,
|
||||
) -> None:
|
||||
"""예약 종료 처리. 재시도로 되돌릴 때는 status='PENDING' + next_retry_at."""
|
||||
with self._pool.connection() as conn:
|
||||
conn.execute(
|
||||
"""
|
||||
UPDATE cafe24_product_schedules
|
||||
SET status = %s,
|
||||
last_error = %s,
|
||||
next_retry_at = %s,
|
||||
retry_count = COALESCE(%s, retry_count),
|
||||
completed_at = CASE WHEN %s IN ('SUCCESS','FAILED','CANCELLED')
|
||||
THEN now() ELSE completed_at END
|
||||
WHERE id = %s
|
||||
""",
|
||||
(
|
||||
store.normalize_schedule_status(status),
|
||||
(error or "")[:1000],
|
||||
next_retry_at,
|
||||
retry_count,
|
||||
store.normalize_schedule_status(status),
|
||||
int(schedule_id),
|
||||
),
|
||||
)
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# 직렬화 — datetime → KST ISO, date → ISO (다른 모듈과 동일)
|
||||
# ════════════════════════════════════════════════════════════
|
||||
|
||||
Reference in New Issue
Block a user